aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorTobias Thierer <tobiast@google.com>2018-10-24 10:50:56 +0000
committerGerrit Code Review <noreply-gerritcodereview@google.com>2018-10-24 10:50:56 +0000
commit3592ed4b0c303841a07c74320333923a37988252 (patch)
tree7869361c499873f77e5ad6774b927b1b213ddc9c
parent362de896c6b33d18b36fc0fc161f39d0eba632e8 (diff)
parent00f143fad06fedaea1159ec9926ab4a7a3136ae3 (diff)
downloadrobolectric-3592ed4b0c303841a07c74320333923a37988252.tar.gz
Merge "external/robolectric: delete dead code"
-rw-r--r--.gitignore25
-rw-r--r--.idea/ant.xml7
-rw-r--r--.idea/codeStyleSettings.xml13
-rw-r--r--.idea/compiler.xml27
-rw-r--r--.idea/copyright/profiles_settings.xml5
-rw-r--r--.idea/dictionaries/pivotal.xml9
-rw-r--r--.idea/encodings.xml5
-rw-r--r--.idea/misc.xml56
-rw-r--r--.idea/modules.xml10
-rw-r--r--.idea/projectCodeStyle.xml40
-rw-r--r--.idea/runConfigurations/AllTests.xml36
-rw-r--r--.idea/scopes/scope_settings.xml5
-rw-r--r--.idea/uiDesigner.xml125
-rw-r--r--.idea/vcs.xml10
-rw-r--r--.pairs33
-rw-r--r--.travis.yml2
-rw-r--r--v1/Android.mk63
-rw-r--r--v1/LICENSE.txt21
-rw-r--r--v1/README.md14
-rw-r--r--v1/build.gradle26
-rw-r--r--v1/build.properties26
-rw-r--r--v1/build.xml254
-rw-r--r--v1/find-android.bat6
-rwxr-xr-xv1/find-android.sh10
-rw-r--r--v1/lib/main/android-support-v4.jarbin402010 -> 0 bytes
-rw-r--r--v1/lib/main/android.jarbin19357924 -> 0 bytes
-rw-r--r--v1/lib/main/commons-codec-1.6.jarbin232771 -> 0 bytes
-rw-r--r--v1/lib/main/commons-logging-1.1.1.jarbin60686 -> 0 bytes
-rw-r--r--v1/lib/main/h2-1.2.147.jarbin1217057 -> 0 bytes
-rw-r--r--v1/lib/main/httpclient-4.0.3.jarbin292893 -> 0 bytes
-rw-r--r--v1/lib/main/httpcore-4.0.1.jarbin172888 -> 0 bytes
-rw-r--r--v1/lib/main/javassist-3.14.0-GA.jarbin647917 -> 0 bytes
-rw-r--r--v1/lib/main/json-20080701.jarbin37875 -> 0 bytes
-rw-r--r--v1/lib/main/maps_v16.jarbin26685 -> 0 bytes
-rw-r--r--v1/lib/main/opengl-api-gl1.1-android-2.1_r1.jarbin18492 -> 0 bytes
-rw-r--r--v1/lib/main/sqlite-jdbc-3.7.2.jarbin3201133 -> 0 bytes
-rw-r--r--v1/lib/main/xpp3-1.1.4c.jarbin120069 -> 0 bytes
-rw-r--r--v1/lib/test/mockito-core-1.8.5.jarbin1338813 -> 0 bytes
-rw-r--r--v1/pom.xml322
-rw-r--r--v1/src/main/java/NOTICE283
-rw-r--r--v1/src/main/java/android/content/TestIntentSender.java6
-rw-r--r--v1/src/main/java/android/hardware/TestSensorManager.java10
-rw-r--r--v1/src/main/java/android/net/Uri__FromAndroid.java2250
-rw-r--r--v1/src/main/java/android/os/ShadowAsyncTaskBridge.java32
-rw-r--r--v1/src/main/java/android/os/ShadowBinderBridge.java16
-rw-r--r--v1/src/main/java/android/os/TestVibrator.java26
-rw-r--r--v1/src/main/java/android/view/animation/ShadowAnimationBridge.java20
-rw-r--r--v1/src/main/java/android/webkit/TestWebSettings.java188
-rw-r--r--v1/src/main/java/com/foo/Receiver.java13
-rw-r--r--v1/src/main/java/com/google/android/maps/ShadowItemizedOverlayBridge.java16
-rw-r--r--v1/src/main/java/com/xtremelabs/ConfigTestReceiver.java13
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/ApplicationResolver.java79
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/Robolectric.java1316
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/RobolectricConfig.java350
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/RobolectricConfigs.java14
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/RobolectricForMaps.java28
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/RobolectricShadowOfLevel9.java24
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/RobolectricTestRunner.java643
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/ShadowScrollView.java14
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/annotation/DisableStrictI18n.java13
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/annotation/EnableStrictI18n.java12
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/annotation/Values.java12
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/bytecode/AndroidTranslator.java499
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/bytecode/ClassCache.java131
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/bytecode/ClassHandler.java17
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/bytecode/IgnorableClassNotFoundException.java9
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/bytecode/RobolectricClassLoader.java85
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/bytecode/RobolectricInternals.java161
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/bytecode/ShadowWrangler.java456
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/bytecode/Type.java85
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/internal/AppSingletonizer.java35
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/internal/ClassNameResolver.java41
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/internal/DoNotInstrument.java10
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/internal/EmptyRunnable.java7
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/internal/Implementation.java14
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/internal/Implements.java17
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/internal/Instrument.java10
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/internal/RealObject.java12
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/internal/RobolectricTestRunnerInterface.java18
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/matchers/CompoundButtonCheckedMatcher.java28
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/matchers/HasCompoundDrawablesMatcher.java45
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/matchers/HasResourceMatcher.java46
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/matchers/ImageViewHasDrawableMatcher.java49
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/matchers/StartedMatcher.java89
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/matchers/StartedServiceMatcher.java115
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/matchers/TextViewHasTextMatcher.java42
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/matchers/ViewHasTextMatcher.java62
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/res/AttrResourceLoader.java73
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/res/ColorResourceLoader.java56
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/res/DimenResourceLoader.java41
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/res/DocumentLoader.java67
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/res/DrawableResourceLoader.java188
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/res/IntegerResourceLoader.java52
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/res/MenuLoader.java184
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/res/PluralResourceLoader.java96
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/res/PreferenceLoader.java162
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/res/RawResourceLoader.java46
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/res/ResourceExtractor.java89
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/res/ResourceLoader.java557
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/res/ResourceReferenceResolver.java82
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/res/ResourceValueConverter.java5
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/res/RobolectricPackageManager.java221
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/res/StringArrayResourceLoader.java46
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/res/StringResourceLoader.java27
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/res/ViewLoader.java308
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/res/XTagXmlResourceLoader.java71
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/res/XmlLoader.java20
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/res/XpathResourceXmlLoader.java32
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/HttpResponseGenerator.java8
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/SerializedFragmentState.java19
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowAbsListView.java65
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowAbsSeekBar.java12
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowAbsSpinner.java46
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowAbsoluteLayout.java10
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowAbstractCursor.java177
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowAccount.java86
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowAccountManager.java206
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowActivity.java549
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowActivityGroup.java25
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowActivityInfo.java20
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowActivityManager.java83
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowAdapterView.java343
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowAddress.java105
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowAlarmManager.java111
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowAlertDialog.java470
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowAlphaAnimation.java24
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowAndroidHttpClient.java89
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowAnimation.java156
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowAnimationDrawable.java39
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowAnimationSet.java30
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowAnimationUtils.java22
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowAppWidgetManager.java225
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowApplication.java543
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowArrayAdapter.java182
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowAssetManager.java41
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowAsyncTask.java123
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowAudioManager.java93
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowAutoCompleteTextView.java60
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowBase64.java22
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowBaseAdapter.java82
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowBinder.java53
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowBitmap.java189
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowBitmapDrawable.java142
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowBitmapFactory.java116
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowBluetoothAdapter.java53
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowBluetoothDevice.java20
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowBundle.java457
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowButton.java17
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowCamera.java157
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowCameraParameters.java167
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowCameraSize.java18
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowCanvas.java181
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowCheckedTextView.java28
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowClipboardManager.java25
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowColor.java19
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowColorDrawable.java39
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowColorMatrix.java70
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowColorMatrixColorFilter.java27
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowColorStateList.java14
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowComponentName.java107
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowCompoundButton.java58
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowConfiguration.java30
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowConnectivityManager.java64
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowContentProvider.java18
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowContentProviderOperation.java99
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowContentProviderOperationBuilder.java91
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowContentProviderResult.java26
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowContentResolver.java415
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowContentUris.java27
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowContentValues.java316
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowContext.java177
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowContextThemeWrapper.java13
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowContextWrapper.java264
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowCookieManager.java53
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowCookieSyncManager.java48
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowCountDownTimer.java61
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowCriteria.java54
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowCursorAdapter.java444
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowCursorLoader.java81
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowCursorWrapper.java218
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowDatabaseUtils.java44
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowDateFormat.java16
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowDefaultRequestDirector.java206
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowDialog.java266
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowDialogFragment.java95
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowDialogPreference.java18
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowDisplay.java133
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowDrawable.java204
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowEditText.java60
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowEnvironment.java37
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowExpandableListView.java29
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowFilter.java10
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowFloatMath.java50
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowFragment.java168
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowFragmentActivity.java121
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowFragmentPagerAdapter.java32
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowFrameLayout.java31
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowGallery.java27
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowGeoPoint.java69
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowGeocoder.java156
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowGridView.java18
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowHandler.java231
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowHandlerThread.java80
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowHtml.java87
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowImageView.java178
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowInputMethodManager.java41
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowIntent.java683
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowIntentFilter.java69
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowIntentFilterAuthorityEntry.java30
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowItemizedOverlay.java92
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowJsPromptResult.java13
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowJsResult.java20
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowKeyEvent.java27
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowKeyGuardLock.java24
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowKeyguardManager.java33
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowLayerDrawable.java51
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowLayoutInflater.java82
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowLayoutParams.java16
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowLinearLayout.java13
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowLinkMovementMethod.java15
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowListActivity.java81
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowListFragment.java32
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowListPreference.java55
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowListView.java209
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowLocalBroadcastManager.java14
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowLocation.java437
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowLocationManager.java391
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowLog.java133
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowLooper.java193
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowMapActivity.java40
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowMapController.java86
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowMapView.java271
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowMarginLayoutParams.java26
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowMatrix.java74
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowMatrixCursor.java88
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowMediaPlayer.java181
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowMediaRecorder.java256
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowMediaStore.java39
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowMenuInflater.java29
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowMessage.java121
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowMessenger.java27
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowMimeTypeMap.java77
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowMotionEvent.java155
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowNdefMessage.java24
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowNdefRecord.java23
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowNetworkInfo.java117
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowNfcAdapter.java73
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowNotification.java63
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowNotificationManager.java73
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowOverlayItem.java63
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowPagerAdapter.java23
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowPaint.java219
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowPair.java58
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowParcel.java1009
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowPasswordTransformationMethod.java37
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowPath.java121
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowPatterns.java135
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowPendingIntent.java198
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowPeriodicSync.java30
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowPhoneNumberUtils.java19
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowPoint.java80
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowPointF.java82
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowPopupWindow.java173
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowPowerManager.java70
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowPreference.java205
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowPreferenceActivity.java30
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowPreferenceCategory.java10
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowPreferenceGroup.java103
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowPreferenceManager.java25
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowPreferenceScreen.java22
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowProcess.java26
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowProgressBar.java78
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowProgressDialog.java54
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowRadioButton.java28
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowRadioGroup.java51
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowRatingBar.java118
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowRect.java115
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowRemoteCallbackList.java137
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowRemoteViews.java127
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowResolveInfo.java52
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowResourceCursorAdapter.java111
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowResources.java246
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowResultReceiver.java32
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSQLiteCloseable.java20
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSQLiteCursor.java262
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSQLiteDatabase.java381
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSQLiteOpenHelper.java58
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSQLiteProgram.java150
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSQLiteQueryBuilder.java50
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSQLiteStatement.java84
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSSLCertificateSocketFactory.java21
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowScanResult.java39
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSeekBar.java34
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSensorManager.java48
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowService.java94
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSettings.java160
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowShapeDrawable.java17
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSignature.java72
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSimpleCursorAdapter.java407
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSmsManager.java89
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSpannableString.java86
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSpannableStringBuilder.java72
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSparseArray.java395
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSparseBooleanArray.java99
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSparseIntArray.java62
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSpinner.java22
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSslErrorHandler.java31
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowStatFs.java71
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowStateListDrawable.java60
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSurfaceView.java62
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSyncResult.java91
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowTabActivity.java28
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowTabHost.java122
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowTabSpec.java117
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowTelephonyManager.java110
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowTextPaint.java13
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowTextUtils.java75
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowTextView.java603
-rwxr-xr-xv1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowTime.java502
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowToast.java148
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowTranslateAnimation.java74
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowTypedArray.java61
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowTypedValue.java218
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowURLSpan.java20
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowUriMatcher.java116
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowVibrator.java54
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowVideoView.java160
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowView.java1011
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowViewAnimator.java42
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowViewConfiguration.java230
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowViewFlipper.java29
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowViewGroup.java251
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowViewMeasureSpec.java54
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowViewPager.java50
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowViewStub.java104
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowViewTreeObserver.java35
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowWebView.java245
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowWifiConfiguration.java51
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowWifiInfo.java20
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowWifiManager.java181
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowWindow.java15
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowZoomButtonsController.java32
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/StatusLineStub.java18
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/shadows/package.html29
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/test/ConfigTestReceiver.java13
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/tester/android/content/TestSharedPreferences.java185
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/tester/android/content/pm/StubPackageManager.java305
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/tester/android/database/SimpleTestCursor.java65
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/tester/android/database/TestCursor.java214
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/tester/android/text/TestClipboardManager.java22
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/tester/android/util/TestAttributeSet.java216
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/tester/android/util/TestFragmentManager.java238
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/tester/android/util/TestFragmentTransaction.java241
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/tester/android/view/TestMenu.java182
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/tester/android/view/TestMenuItem.java255
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/tester/android/view/TestSubMenu.java53
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/tester/android/view/TestWindow.java197
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/tester/android/view/TestWindowManager.java44
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/tester/org/apache/http/FakeHttpLayer.java404
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/tester/org/apache/http/HttpEntityStub.java55
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/tester/org/apache/http/HttpRequestInfo.java36
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/tester/org/apache/http/HttpResponseStub.java122
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/tester/org/apache/http/ParamsParser.java80
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/tester/org/apache/http/RequestMatcher.java7
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/tester/org/apache/http/TestHttpResponse.java249
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/tester/org/apache/http/impl/client/DefaultRequestDirector.java1163
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/tester/org/apache/http/impl/client/HttpRedirect.java64
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/util/DatabaseConfig.java133
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/util/H2Map.java75
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/util/H2Map_TypeForwardOnly.java13
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/util/I18nException.java22
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/util/Join.java31
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/util/PropertiesHelper.java50
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/util/RobolectricBackgroundExecutorService.java92
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/util/SQLite.java206
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/util/SQLiteMap.java26
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/util/Scheduler.java161
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/util/Strings.java25
-rw-r--r--v1/src/main/java/com/xtremelabs/robolectric/util/Transcript.java32
-rw-r--r--v1/src/main/java/overview.html42
-rw-r--r--v1/src/test/java/android/webkit/TestWebSettingsTest.java181
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/ApplicationResolverTest.java54
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/DotConfigTestReceiver.java13
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/IncludedDependenciesTest.java29
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/InstrumentDetectorTest.java174
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/R.java169
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/RobolectricConfigTest.java96
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/RobolectricTest.java196
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/RobolectricTestRunnerClassLoaderSetup.java18
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/RobolectricTestRunnerTest.java112
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/TemporaryBindingsTest.java39
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/TestApplication.java6
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/WithCustomClassListTestRunner.java16
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/WithTestDefaultsRunner.java20
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/WithoutTestDefaultsRunner.java15
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/bytecode/AndroidTranslatorClassIntrumentedTest.java156
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/bytecode/AndroidTranslatorTest.java234
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/bytecode/AndroidTranslatorUnitTest.java151
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/bytecode/ClassCacheTest.java124
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/bytecode/CustomRobolectricTestRunnerTest.java77
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/bytecode/Foo.java18
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/bytecode/RobolectricWiringTest.java117
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/bytecode/ShadowFoo.java31
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/bytecode/ShadowWranglerTest.java239
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/internal/ClassNameResolverTest.java34
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/matchers/StartedMatcherTest.java93
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/matchers/StartedServiceMatcherTest.java95
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/res/AttrResourceLoaderTest.java56
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/res/ColorResourceLoaderTest.java75
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/res/DimenResourceLoaderTest.java37
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/res/DrawableResourceLoaderTest.java120
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/res/IntegerResourceLoaderTest.java35
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/res/MenuLoaderTest.java194
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/res/MenuResourceLoaderTest.java39
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/res/PluralResourceLoaderTest.java33
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/res/PreferenceLoaderTest.java80
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/res/RawResourceLoaderTest.java57
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/res/ResourceExtractorTest.java36
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/res/ResourceLoaderTest.java106
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/res/RobolectricPackageManagerTest.java174
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/res/StringArrayResourceLoaderTest.java50
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/res/StringResourceLoaderTest.java36
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/res/TestAttributeSetTest.java148
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/res/ViewLoaderTest.java392
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/AbsSeekBarTest.java30
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/AbsSpinnerTest.java129
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/AbstractCursorTest.java278
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/AccountManagerTest.java157
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/AccountTest.java72
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/ActivityGroupTest.java24
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/ActivityManagerTest.java35
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/ActivityTest.java598
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/AdapterViewBehavior.java201
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/AlarmManagerTest.java162
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/AlertDialogTest.java384
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/AlphaAnimationTest.java24
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/AndroidHttpClientTest.java42
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/AnimationSetTest.java45
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/AnimationTest.java140
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/AnimationUtilsTest.java30
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/AppWidgetManagerTest.java108
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/ApplicationTest.java311
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/ArrayAdapterTest.java161
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/AssetManagerTest.java87
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/AsyncTaskTest.java145
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/AudioManagerTest.java81
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/Base64Test.java32
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/BaseAdapterTest.java52
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/BinderTest.java30
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/BitmapDrawableTest.java103
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/BitmapFactoryTest.java127
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/BitmapTest.java140
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/BundleTest.java406
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/CameraParametersTest.java135
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/CameraSizeTest.java45
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/CameraTest.java291
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/CanvasTest.java109
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/CheckBoxTest.java27
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/CheckedTextViewTest.java41
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/ClipboardManagerTest.java54
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/ColorTest.java26
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/ConfigurationTest.java44
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/ConnectivityManagerTest.java105
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/ContentProviderOperationBuilderTest.java70
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/ContentProviderOperationTest.java76
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/ContentProviderResultTest.java29
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/ContentProviderTest.java71
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/ContentResolverTest.java371
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/ContentUrisTest.java47
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/ContextTest.java240
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/ContextWrapperTest.java199
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/CookieManagerTest.java55
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/CookieSyncManagerTest.java43
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/CountDownTimerTest.java82
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/CountingAdapter.java41
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/CriteriaTest.java50
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/CursorAdapterTest.java116
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/CursorLoaderTest.java56
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/CursorWrapperTest.java105
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/DatabaseTestBase.java606
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/DatabaseUtilsTest.java19
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/DefaultRequestDirectorTest.java365
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/DialogFragmentTest.java227
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/DialogPreferenceTest.java73
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/DialogTest.java189
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/DisplayTest.java41
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/DrawableTest.java175
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/EditTextTest.java91
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/EnvironmentTest.java56
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/ExpandableListViewTest.java57
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/FragmentActivityTest.java185
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/FragmentManagerTest.java249
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/FragmentTest.java41
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/FragmentTransactionTest.java298
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/FrameLayoutTest.java33
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/GalleryTest.java59
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/GeocoderTest.java63
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/H2DatabaseTest.java20
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/HandlerTest.java398
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/HandlerThreadTest.java81
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/HtmlTest.java44
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/ImageViewTest.java107
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/InputMethodManagerTest.java38
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/IntentFilterAuthorityEntryTest.java23
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/IntentFilterTest.java34
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/IntentTest.java488
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/ItemizedOverlayTest.java78
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/JsPromptResultTest.java18
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/JsResultTest.java27
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/KeyguardManagerTest.java42
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/LayerDrawableTest.java103
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/LayoutInflaterTest.java29
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/LayoutParamsTest.java19
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/LinearLayoutTest.java31
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/LinkMovementMethodTest.java19
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/ListActivityTest.java54
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/ListFragmentTest.java30
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/ListPreferenceTest.java74
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/ListViewTest.java576
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/LocalBroadcastManagerTest.java75
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/LocationManagerTest.java423
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/LocationTest.java121
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/LogTest.java173
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/LooperTest.java106
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/MapActivityTest.java49
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/MapViewTest.java179
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/MarginLayoutParamsTest.java28
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/MatrixCursorTest.java157
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/MediaPlayerTest.java34
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/MediaRecorderTest.java234
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/MediaStoreTest.java21
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/MenuInflaterTest.java34
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/MessageTest.java164
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/MessengerTest.java33
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/MimeTypeMapTest.java97
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/MotionEventTest.java83
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/NdefMessageTest.java21
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/NdefRecordTest.java20
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/NetworkInfoTest.java22
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/NfcAdapterTest.java17
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/NotificationManagerTest.java96
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/NotificationTest.java23
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/PagerAdapterTest.java44
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/PaintTest.java44
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/PairTest.java38
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/ParcelTest.java513
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/PasswordTransformationMethodTest.java56
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/PathTest.java51
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/PendingIntentTest.java138
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/PeriodicSyncTest.java29
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/PhoneNumberUtilTest.java23
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/PopupWindowTest.java178
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/PowerManagerTest.java77
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/PreferenceActivityTest.java64
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/PreferenceCategoryTest.java32
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/PreferenceGroupTest.java179
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/PreferenceManagerTest.java35
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/PreferenceScreenTest.java42
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/PreferenceTest.java266
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/ProcessTest.java28
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/ProgressBarTest.java107
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/ProgressDialogTest.java153
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/RadioButtonTest.java69
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/RadioGroupTest.java63
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/RatingBarTest.java71
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/RectTest.java192
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/RemoteCallbackListTest.java35
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/ResolveInfoTest.java39
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/ResourcesTest.java144
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/ResultReceiverTest.java38
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/SQLiteCursorTest.java365
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/SQLiteDatabaseTest.java46
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/SQLiteOpenHelperTest.java132
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/SQLiteQueryBuilderTest.java152
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/SQLiteStatementTest.java104
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/ScanResultTest.java26
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/ScrollViewTest.java20
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/SeekBarTest.java63
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/SensorManagerTest.java82
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/ServiceTest.java77
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/SettingsTest.java104
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/ShadowAutoCompleteTextViewTest.java94
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/ShadowBinderTest.java44
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/ShadowEditTextTest.java26
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/ShapeDrawableTest.java22
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/SignatureTest.java52
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/SmsManagerTest.java71
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/SpannableStringBuilderTest.java47
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/SpannableStringTest.java136
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/SparseArrayTest.java177
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/SpinnerTest.java29
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/SslErrorHandlerTest.java47
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/StatFsTest.java63
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/StateListDrawableTest.java45
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/SyncResultTest.java59
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/TabActivityTest.java33
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/TabHostTest.java206
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/TabSpecTest.java119
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/TelephonyManagerTest.java94
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/TestFragment.java99
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/TestParcelable.java34
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/TestService.java29
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/TextPaintTest.java19
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/TextUtilsTest.java65
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/TextViewTest.java478
-rwxr-xr-xv1/src/test/java/com/xtremelabs/robolectric/shadows/TimeTest.java238
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/ToastTest.java31
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/TranslateAnimationTest.java52
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/TypedArrayTest.java71
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/TypedValueTest.java80
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/UriMatcherTest.java87
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/UriTest.java25
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/VibratorTest.java57
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/VideoViewTest.java157
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/ViewAnimatorTest.java45
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/ViewConfigurationTest.java70
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/ViewFlipperTest.java32
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/ViewGroupTest.java336
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/ViewInnerTextTest.java76
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/ViewMeasureSpecTest.java46
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/ViewPagerTest.java69
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/ViewStubTest.java61
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/ViewTest.java516
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/ViewTreeObserverTest.java79
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/WebViewTest.java184
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/WifiConfigurationTest.java63
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/WifiInfoTest.java28
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/shadows/WifiManagerTest.java207
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/tester/android/content/TestSharedPreferencesTest.java144
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/tester/android/database/SimpleTestCursorTest.java69
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/tester/android/view/TestMenuTest.java65
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/tester/android/view/TestWindowTest.java16
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/tester/org/apache/http/FakeHttpLayerTest.java96
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/tester/org/apache/http/ParamsParserTest.java35
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/tester/org/apache/http/TestHttpResponseTest.java129
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/util/CustomView.java16
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/util/CustomView2.java17
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/util/DatabaseConfigTest.java90
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/util/H2MapTest.java78
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/util/H2Map_TypeForwardOnlyTest.java30
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/util/H2Test.java39
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/util/NullDatabaseMap.java34
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/util/NullDatabaseMapTest.java62
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/util/PropertiesHelperTest.java27
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/util/RobolectricBackgroundExecutorServiceTest.java77
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/util/SQLiteTestHelper.java17
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/util/SQLite_Test.java70
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/util/SchedulerTest.java164
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/util/StringsTest.java16
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/util/TestAnimationListener.java26
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/util/TestBroadcastReceiver.java16
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/util/TestOnClickListener.java11
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/util/TestOnLongClickListener.java13
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/util/TestR.java22
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/util/TestRunnable.java9
-rw-r--r--v1/src/test/java/com/xtremelabs/robolectric/util/TestUtil.java95
-rw-r--r--v1/src/test/resources/TestAndroidManifest.xml5
-rw-r--r--v1/src/test/resources/TestAndroidManifestWithAppName.xml6
-rw-r--r--v1/src/test/resources/TestAndroidManifestWithBadAppName.xml6
-rw-r--r--v1/src/test/resources/TestAndroidManifestWithFlags.xml20
-rw-r--r--v1/src/test/resources/TestAndroidManifestWithMinSdkVersionOnly.xml4
-rw-r--r--v1/src/test/resources/TestAndroidManifestWithNoProcess.xml5
-rw-r--r--v1/src/test/resources/TestAndroidManifestWithPackageName.xml4
-rw-r--r--v1/src/test/resources/TestAndroidManifestWithProcess.xml6
-rw-r--r--v1/src/test/resources/TestAndroidManifestWithReceivers.xml45
-rw-r--r--v1/src/test/resources/TestAndroidManifestWithSdkVersion.xml5
-rw-r--r--v1/src/test/resources/assets/assetsHome.txt1
-rw-r--r--v1/src/test/resources/assets/docs/extra/testing/hello.txt1
-rw-r--r--v1/src/test/resources/res/drawable/animation_list.xml6
-rw-r--r--v1/src/test/resources/res/drawable/l0_red.pngbin1935 -> 0 bytes
-rw-r--r--v1/src/test/resources/res/drawable/l1_orange.pngbin2613 -> 0 bytes
-rw-r--r--v1/src/test/resources/res/drawable/l2_yellow.pngbin2735 -> 0 bytes
-rw-r--r--v1/src/test/resources/res/drawable/l3_green.pngbin2614 -> 0 bytes
-rw-r--r--v1/src/test/resources/res/drawable/l4_blue.pngbin2346 -> 0 bytes
-rw-r--r--v1/src/test/resources/res/drawable/l5_indigo.pngbin2259 -> 0 bytes
-rw-r--r--v1/src/test/resources/res/drawable/l6_violet.pngbin1528 -> 0 bytes
-rw-r--r--v1/src/test/resources/res/drawable/l7_white.pngbin331 -> 0 bytes
-rw-r--r--v1/src/test/resources/res/drawable/nine_patch_drawable.9.pngbin240 -> 0 bytes
-rw-r--r--v1/src/test/resources/res/drawable/rainbow.xml11
-rw-r--r--v1/src/test/resources/res/drawable/state_drawable.xml15
-rw-r--r--v1/src/test/resources/res/layout-land/different_screen_sizes.xml12
-rw-r--r--v1/src/test/resources/res/layout-large-v16/different_screen_sizes.xml12
-rw-r--r--v1/src/test/resources/res/layout-v11/different_screen_sizes.xml12
-rw-r--r--v1/src/test/resources/res/layout-xlarge-v11/different_screen_sizes.xml12
-rw-r--r--v1/src/test/resources/res/layout-xlarge/different_screen_sizes.xml12
-rw-r--r--v1/src/test/resources/res/layout/.bogus_hidden_dir_for_tests/bad.xml1
-rw-r--r--v1/src/test/resources/res/layout/activity_list_item.xml18
-rw-r--r--v1/src/test/resources/res/layout/custom_layout.xml5
-rw-r--r--v1/src/test/resources/res/layout/custom_layout2.xml9
-rw-r--r--v1/src/test/resources/res/layout/different_screen_sizes.xml12
-rw-r--r--v1/src/test/resources/res/layout/fragment_activity.xml23
-rw-r--r--v1/src/test/resources/res/layout/included_layout_parent.xml13
-rw-r--r--v1/src/test/resources/res/layout/included_linear_layout.xml9
-rw-r--r--v1/src/test/resources/res/layout/inner_merge.xml11
-rw-r--r--v1/src/test/resources/res/layout/main.xml71
-rw-r--r--v1/src/test/resources/res/layout/mapview.xml17
-rw-r--r--v1/src/test/resources/res/layout/media.xml50
-rw-r--r--v1/src/test/resources/res/layout/outer.xml14
-rw-r--r--v1/src/test/resources/res/layout/override_include.xml17
-rw-r--r--v1/src/test/resources/res/layout/request_focus.xml18
-rw-r--r--v1/src/test/resources/res/layout/request_focus_with_two_edit_texts.xml19
-rw-r--r--v1/src/test/resources/res/layout/snippet.xml9
-rw-r--r--v1/src/test/resources/res/layout/tab_activity.xml26
-rw-r--r--v1/src/test/resources/res/layout/text_views.xml32
-rw-r--r--v1/src/test/resources/res/layout/text_views_hints.xml31
-rw-r--r--v1/src/test/resources/res/layout/toplevel_merge.xml20
-rw-r--r--v1/src/test/resources/res/layout/views.xml47
-rw-r--r--v1/src/test/resources/res/layout/webview_holder.xml16
-rw-r--r--v1/src/test/resources/res/layout/with_invalid_onclick.xml6
-rw-r--r--v1/src/test/resources/res/menu/test.xml6
-rw-r--r--v1/src/test/resources/res/menu/test_withchilds.xml14
-rw-r--r--v1/src/test/resources/res/raw/raw_no_ext1
-rw-r--r--v1/src/test/resources/res/raw/raw_resource.txt1
-rw-r--r--v1/src/test/resources/res/values-fr/strings.xml4
-rw-r--r--v1/src/test/resources/res/values/attrs.xml9
-rw-r--r--v1/src/test/resources/res/values/colors.xml16
-rw-r--r--v1/src/test/resources/res/values/dimens.xml7
-rw-r--r--v1/src/test/resources/res/values/integer.xml8
-rw-r--r--v1/src/test/resources/res/values/plurals.xml9
-rw-r--r--v1/src/test/resources/res/values/string_arrays.xml22
-rw-r--r--v1/src/test/resources/res/values/strings.xml12
-rw-r--r--v1/src/test/resources/res/xml/preferences.xml46
-rwxr-xr-xv1/update-downloads.rb40
-rw-r--r--v3/LICENSE.txt23
-rw-r--r--v3/README.txt44
-rw-r--r--v3/build.gradle40
-rw-r--r--v3/libs/README.txt11
-rw-r--r--v3/libs/sqlite4java-0.282.jarbin129381 -> 0 bytes
-rw-r--r--v3/libs/vtd-xml-2.11.jarbin637560 -> 0 bytes
-rw-r--r--v3/robolectric-3.1-SNAPSHOT.jarbin174071 -> 0 bytes
-rw-r--r--v3/robolectric-annotations-3.1-SNAPSHOT.jarbin10647 -> 0 bytes
-rw-r--r--v3/robolectric-processor-3.1-SNAPSHOT.jarbin41844 -> 0 bytes
-rw-r--r--v3/robolectric-resources-3.1-SNAPSHOT.jarbin152064 -> 0 bytes
-rw-r--r--v3/robolectric-utils-3.1-SNAPSHOT.jarbin40476 -> 0 bytes
-rw-r--r--v3/runtime/android-all-4.1.2_r1-robolectric-0.jarbin31438553 -> 0 bytes
-rw-r--r--v3/runtime/android-all-4.2.2_r1.2-robolectric-0.jarbin32062933 -> 0 bytes
-rw-r--r--v3/runtime/android-all-4.3_r2-robolectric-0.jarbin33644619 -> 0 bytes
-rw-r--r--v3/runtime/android-all-4.4_r1-robolectric-1.jarbin41609020 -> 0 bytes
-rw-r--r--v3/runtime/android-all-5.0.0_r2-robolectric-1.jarbin42868636 -> 0 bytes
-rw-r--r--v3/runtime/android-all-5.1.1_r9-robolectric-1.jarbin43608647 -> 0 bytes
-rw-r--r--v3/runtime/json-20080701.jarbin37875 -> 0 bytes
-rw-r--r--v3/runtime/shadows-core-3.1-SNAPSHOT-16.jarbin2659281 -> 0 bytes
-rw-r--r--v3/runtime/shadows-core-3.1-SNAPSHOT-17.jarbin2661915 -> 0 bytes
-rw-r--r--v3/runtime/shadows-core-3.1-SNAPSHOT-18.jarbin2667505 -> 0 bytes
-rw-r--r--v3/runtime/shadows-core-3.1-SNAPSHOT-19.jarbin2670228 -> 0 bytes
-rw-r--r--v3/runtime/shadows-core-3.1-SNAPSHOT-21.jarbin2671103 -> 0 bytes
-rw-r--r--v3/runtime/shadows-core-3.1-SNAPSHOT-22.jarbin2672254 -> 0 bytes
-rw-r--r--v3/runtime/tagsoup-1.2.jarbin90023 -> 0 bytes
-rw-r--r--v3/shadows-httpclient-3.1-SNAPSHOT.jarbin46286 -> 0 bytes
-rw-r--r--v3/shadows-multidex-3.1-SNAPSHOT.jarbin4157 -> 0 bytes
-rw-r--r--v3/shadows-play-services-3.1-SNAPSHOT.jarbin4399 -> 0 bytes
-rw-r--r--v3/shadows-support-v4-3.1-SNAPSHOT.jarbin26442 -> 0 bytes
-rwxr-xr-xv3/update_robolectric.sh31
753 files changed, 0 insertions, 72924 deletions
diff --git a/.gitignore b/.gitignore
deleted file mode 100644
index 58585665c..000000000
--- a/.gitignore
+++ /dev/null
@@ -1,25 +0,0 @@
-bin/
-out/
-.idea/workspace.xml
-.idea/libraries/
-.idea/modules.xml
-.idea/vcs.xml
-.idea/compiler.xml
-.idea/misc.xml
-.idea/.name
-robolectric.iml
-tmp/
-target/
-pages
-.DS_Store
-local.properties
-.project
-.classpath
-.settings
-*.iws
-*.iml
-*.ipr
-*.orig
-*.swp
-*~
-\#*\#
diff --git a/.idea/ant.xml b/.idea/ant.xml
deleted file mode 100644
index 2581ca3fe..000000000
--- a/.idea/ant.xml
+++ /dev/null
@@ -1,7 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<project version="4">
- <component name="AntConfiguration">
- <defaultAnt bundledAnt="true" />
- </component>
-</project>
-
diff --git a/.idea/codeStyleSettings.xml b/.idea/codeStyleSettings.xml
deleted file mode 100644
index 9178b389f..000000000
--- a/.idea/codeStyleSettings.xml
+++ /dev/null
@@ -1,13 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<project version="4">
- <component name="ProjectCodeStyleSettingsManager">
- <option name="PER_PROJECT_SETTINGS">
- <value>
- <XML>
- <option name="XML_LEGACY_SETTINGS_IMPORTED" value="true" />
- </XML>
- </value>
- </option>
- </component>
-</project>
-
diff --git a/.idea/compiler.xml b/.idea/compiler.xml
deleted file mode 100644
index a0e1a887f..000000000
--- a/.idea/compiler.xml
+++ /dev/null
@@ -1,27 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<project version="4">
- <component name="CompilerConfiguration">
- <option name="DEFAULT_COMPILER" value="Javac" />
- <resourceExtensions>
- <entry name=".+\.(properties|xml|html|dtd|tld)" />
- <entry name=".+\.(gif|png|jpeg|jpg)" />
- </resourceExtensions>
- <wildcardResourcePatterns>
- <entry name="?*.properties" />
- <entry name="?*.xml" />
- <entry name="?*.gif" />
- <entry name="?*.png" />
- <entry name="?*.jpeg" />
- <entry name="?*.jpg" />
- <entry name="?*.html" />
- <entry name="?*.dtd" />
- <entry name="?*.tld" />
- <entry name="?*.ftl" />
- </wildcardResourcePatterns>
- <annotationProcessing enabled="false" useClasspath="true" />
- </component>
- <component name="JavacSettings">
- <option name="ADDITIONAL_OPTIONS_STRING" value="-target 1.6" />
- </component>
-</project>
-
diff --git a/.idea/copyright/profiles_settings.xml b/.idea/copyright/profiles_settings.xml
deleted file mode 100644
index 3572571ad..000000000
--- a/.idea/copyright/profiles_settings.xml
+++ /dev/null
@@ -1,5 +0,0 @@
-<component name="CopyrightManager">
- <settings default="">
- <module2copyright />
- </settings>
-</component> \ No newline at end of file
diff --git a/.idea/dictionaries/pivotal.xml b/.idea/dictionaries/pivotal.xml
deleted file mode 100644
index 195119fc6..000000000
--- a/.idea/dictionaries/pivotal.xml
+++ /dev/null
@@ -1,9 +0,0 @@
-<component name="ProjectDictionaryState">
- <dictionary name="pivotal">
- <words>
- <w>accessor</w>
- <w>accessors</w>
- <w>xtremelabs</w>
- </words>
- </dictionary>
-</component> \ No newline at end of file
diff --git a/.idea/encodings.xml b/.idea/encodings.xml
deleted file mode 100644
index e206d70d8..000000000
--- a/.idea/encodings.xml
+++ /dev/null
@@ -1,5 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<project version="4">
- <component name="Encoding" useUTFGuessing="true" native2AsciiForPropertiesFiles="false" />
-</project>
-
diff --git a/.idea/misc.xml b/.idea/misc.xml
deleted file mode 100644
index a35fce1a5..000000000
--- a/.idea/misc.xml
+++ /dev/null
@@ -1,56 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<project version="4">
- <component name="EntryPointsManager">
- <entry_points version="2.0" />
- </component>
- <component name="FacetAutodetectingManager">
- <autodetection-disabled>
- <facet-type id="android">
- <modules>
- <module name="robolectric" />
- </modules>
- </facet-type>
- </autodetection-disabled>
- </component>
- <component name="IdProvider" IDEtalkID="E3CEF9CB8037AEFF57D7356A0309656F" />
- <component name="JavadocGenerationManager">
- <option name="OUTPUT_DIRECTORY" />
- <option name="OPTION_SCOPE" value="protected" />
- <option name="OPTION_HIERARCHY" value="true" />
- <option name="OPTION_NAVIGATOR" value="true" />
- <option name="OPTION_INDEX" value="true" />
- <option name="OPTION_SEPARATE_INDEX" value="true" />
- <option name="OPTION_DOCUMENT_TAG_USE" value="false" />
- <option name="OPTION_DOCUMENT_TAG_AUTHOR" value="false" />
- <option name="OPTION_DOCUMENT_TAG_VERSION" value="false" />
- <option name="OPTION_DOCUMENT_TAG_DEPRECATED" value="true" />
- <option name="OPTION_DEPRECATED_LIST" value="true" />
- <option name="OTHER_OPTIONS" value="" />
- <option name="HEAP_SIZE" />
- <option name="LOCALE" />
- <option name="OPEN_IN_BROWSER" value="true" />
- </component>
- <component name="MavenProjectsManager">
- <option name="originalFiles">
- <list>
- <option value="$PROJECT_DIR$/pom.xml" />
- </list>
- </option>
- <option name="activeProfiles">
- <list>
- <option value="ant-deps" />
- </list>
- </option>
- </component>
- <component name="ProjectResources">
- <default-html-doctype>http://www.w3.org/1999/xhtml</default-html-doctype>
- </component>
- <component name="ProjectRootManager" version="2" languageLevel="JDK_1_6" assert-keyword="true" jdk-15="true" project-jdk-name="1.6" project-jdk-type="JavaSDK">
- <output url="file://$PROJECT_DIR$/out" />
- </component>
- <component name="SvnBranchConfigurationManager">
- <option name="mySupportsUserInfoFilter" value="true" />
- </component>
- <component name="WebServicesPlugin" addRequiredLibraries="true" />
-</project>
-
diff --git a/.idea/modules.xml b/.idea/modules.xml
deleted file mode 100644
index 09f6f8141..000000000
--- a/.idea/modules.xml
+++ /dev/null
@@ -1,10 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<project version="4">
- <component name="ProjectModuleManager">
- <modules>
- <module fileurl="file://$PROJECT_DIR$/robolectric.iml" filepath="$PROJECT_DIR$/robolectric.iml" />
- <module fileurl="file://$PROJECT_DIR$/robolectric-gh-pages.iml" filepath="$PROJECT_DIR$/robolectric-gh-pages.iml" />
- </modules>
- </component>
-</project>
-
diff --git a/.idea/projectCodeStyle.xml b/.idea/projectCodeStyle.xml
deleted file mode 100644
index 64590113f..000000000
--- a/.idea/projectCodeStyle.xml
+++ /dev/null
@@ -1,40 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<project version="4">
- <component name="CodeStyleSettingsManager">
- <option name="PER_PROJECT_SETTINGS">
- <value>
- <ADDITIONAL_INDENT_OPTIONS fileType="java">
- <option name="INDENT_SIZE" value="4" />
- <option name="CONTINUATION_INDENT_SIZE" value="8" />
- <option name="TAB_SIZE" value="4" />
- <option name="USE_TAB_CHARACTER" value="false" />
- <option name="SMART_TABS" value="false" />
- <option name="LABEL_INDENT_SIZE" value="0" />
- <option name="LABEL_INDENT_ABSOLUTE" value="false" />
- <option name="USE_RELATIVE_INDENTS" value="false" />
- </ADDITIONAL_INDENT_OPTIONS>
- <ADDITIONAL_INDENT_OPTIONS fileType="jsp">
- <option name="INDENT_SIZE" value="4" />
- <option name="CONTINUATION_INDENT_SIZE" value="8" />
- <option name="TAB_SIZE" value="4" />
- <option name="USE_TAB_CHARACTER" value="false" />
- <option name="SMART_TABS" value="false" />
- <option name="LABEL_INDENT_SIZE" value="0" />
- <option name="LABEL_INDENT_ABSOLUTE" value="false" />
- <option name="USE_RELATIVE_INDENTS" value="false" />
- </ADDITIONAL_INDENT_OPTIONS>
- <ADDITIONAL_INDENT_OPTIONS fileType="xml">
- <option name="INDENT_SIZE" value="4" />
- <option name="CONTINUATION_INDENT_SIZE" value="8" />
- <option name="TAB_SIZE" value="4" />
- <option name="USE_TAB_CHARACTER" value="false" />
- <option name="SMART_TABS" value="false" />
- <option name="LABEL_INDENT_SIZE" value="0" />
- <option name="LABEL_INDENT_ABSOLUTE" value="false" />
- <option name="USE_RELATIVE_INDENTS" value="false" />
- </ADDITIONAL_INDENT_OPTIONS>
- </value>
- </option>
- </component>
-</project>
-
diff --git a/.idea/runConfigurations/AllTests.xml b/.idea/runConfigurations/AllTests.xml
deleted file mode 100644
index 40f4120d1..000000000
--- a/.idea/runConfigurations/AllTests.xml
+++ /dev/null
@@ -1,36 +0,0 @@
-<component name="ProjectRunConfigurationManager">
- <configuration default="false" name="AllTests" type="JUnit" factoryName="JUnit">
- <extension name="coverage" enabled="false" merge="false" sample_coverage="true" runner="idea">
- <pattern>
- <option name="PATTERN" value="com.xtremelabs.robolectric.shadows.*" />
- <option name="ENABLED" value="true" />
- </pattern>
- </extension>
- <module name="droid-sugar" />
- <option name="ALTERNATIVE_JRE_PATH_ENABLED" value="false" />
- <option name="ALTERNATIVE_JRE_PATH" value="" />
- <option name="PACKAGE_NAME" value="com.xtremelabs.robolectric" />
- <option name="MAIN_CLASS_NAME" value="" />
- <option name="METHOD_NAME" value="" />
- <option name="TEST_OBJECT" value="package" />
- <option name="VM_PARAMETERS" value="" />
- <option name="PARAMETERS" value="" />
- <option name="WORKING_DIRECTORY" value="file://$PROJECT_DIR$" />
- <option name="ENV_VARIABLES" />
- <option name="PASS_PARENT_ENVS" value="true" />
- <option name="TEST_SEARCH_SCOPE">
- <value defaultName="wholeProject" />
- </option>
- <envs />
- <patterns />
- <RunnerSettings RunnerId="Debug">
- <option name="DEBUG_PORT" value="52365" />
- <option name="TRANSPORT" value="0" />
- <option name="LOCAL" value="true" />
- </RunnerSettings>
- <RunnerSettings RunnerId="Run" />
- <ConfigurationWrapper RunnerId="Debug" />
- <ConfigurationWrapper RunnerId="Run" />
- <method />
- </configuration>
-</component> \ No newline at end of file
diff --git a/.idea/scopes/scope_settings.xml b/.idea/scopes/scope_settings.xml
deleted file mode 100644
index 922003b84..000000000
--- a/.idea/scopes/scope_settings.xml
+++ /dev/null
@@ -1,5 +0,0 @@
-<component name="DependencyValidationManager">
- <state>
- <option name="SKIP_IMPORT_STATEMENTS" value="false" />
- </state>
-</component> \ No newline at end of file
diff --git a/.idea/uiDesigner.xml b/.idea/uiDesigner.xml
deleted file mode 100644
index 3b0002030..000000000
--- a/.idea/uiDesigner.xml
+++ /dev/null
@@ -1,125 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<project version="4">
- <component name="Palette2">
- <group name="Swing">
- <item class="com.intellij.uiDesigner.HSpacer" tooltip-text="Horizontal Spacer" icon="/com/intellij/uiDesigner/icons/hspacer.png" removable="false" auto-create-binding="false" can-attach-label="false">
- <default-constraints vsize-policy="1" hsize-policy="6" anchor="0" fill="1" />
- </item>
- <item class="com.intellij.uiDesigner.VSpacer" tooltip-text="Vertical Spacer" icon="/com/intellij/uiDesigner/icons/vspacer.png" removable="false" auto-create-binding="false" can-attach-label="false">
- <default-constraints vsize-policy="6" hsize-policy="1" anchor="0" fill="2" />
- </item>
- <item class="javax.swing.JPanel" icon="/com/intellij/uiDesigner/icons/panel.png" removable="false" auto-create-binding="false" can-attach-label="false">
- <default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3" />
- </item>
- <item class="javax.swing.JScrollPane" icon="/com/intellij/uiDesigner/icons/scrollPane.png" removable="false" auto-create-binding="false" can-attach-label="true">
- <default-constraints vsize-policy="7" hsize-policy="7" anchor="0" fill="3" />
- </item>
- <item class="javax.swing.JButton" icon="/com/intellij/uiDesigner/icons/button.png" removable="false" auto-create-binding="true" can-attach-label="false">
- <default-constraints vsize-policy="0" hsize-policy="3" anchor="0" fill="1" />
- <initial-values>
- <property name="text" value="Button" />
- </initial-values>
- </item>
- <item class="javax.swing.JRadioButton" icon="/com/intellij/uiDesigner/icons/radioButton.png" removable="false" auto-create-binding="true" can-attach-label="false">
- <default-constraints vsize-policy="0" hsize-policy="3" anchor="8" fill="0" />
- <initial-values>
- <property name="text" value="RadioButton" />
- </initial-values>
- </item>
- <item class="javax.swing.JCheckBox" icon="/com/intellij/uiDesigner/icons/checkBox.png" removable="false" auto-create-binding="true" can-attach-label="false">
- <default-constraints vsize-policy="0" hsize-policy="3" anchor="8" fill="0" />
- <initial-values>
- <property name="text" value="CheckBox" />
- </initial-values>
- </item>
- <item class="javax.swing.JLabel" icon="/com/intellij/uiDesigner/icons/label.png" removable="false" auto-create-binding="false" can-attach-label="false">
- <default-constraints vsize-policy="0" hsize-policy="0" anchor="8" fill="0" />
- <initial-values>
- <property name="text" value="Label" />
- </initial-values>
- </item>
- <item class="javax.swing.JTextField" icon="/com/intellij/uiDesigner/icons/textField.png" removable="false" auto-create-binding="true" can-attach-label="true">
- <default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
- <preferred-size width="150" height="-1" />
- </default-constraints>
- </item>
- <item class="javax.swing.JPasswordField" icon="/com/intellij/uiDesigner/icons/passwordField.png" removable="false" auto-create-binding="true" can-attach-label="true">
- <default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
- <preferred-size width="150" height="-1" />
- </default-constraints>
- </item>
- <item class="javax.swing.JFormattedTextField" icon="/com/intellij/uiDesigner/icons/formattedTextField.png" removable="false" auto-create-binding="true" can-attach-label="true">
- <default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
- <preferred-size width="150" height="-1" />
- </default-constraints>
- </item>
- <item class="javax.swing.JTextArea" icon="/com/intellij/uiDesigner/icons/textArea.png" removable="false" auto-create-binding="true" can-attach-label="true">
- <default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
- <preferred-size width="150" height="50" />
- </default-constraints>
- </item>
- <item class="javax.swing.JTextPane" icon="/com/intellij/uiDesigner/icons/textPane.png" removable="false" auto-create-binding="true" can-attach-label="true">
- <default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
- <preferred-size width="150" height="50" />
- </default-constraints>
- </item>
- <item class="javax.swing.JEditorPane" icon="/com/intellij/uiDesigner/icons/editorPane.png" removable="false" auto-create-binding="true" can-attach-label="true">
- <default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
- <preferred-size width="150" height="50" />
- </default-constraints>
- </item>
- <item class="javax.swing.JComboBox" icon="/com/intellij/uiDesigner/icons/comboBox.png" removable="false" auto-create-binding="true" can-attach-label="true">
- <default-constraints vsize-policy="0" hsize-policy="2" anchor="8" fill="1" />
- </item>
- <item class="javax.swing.JTable" icon="/com/intellij/uiDesigner/icons/table.png" removable="false" auto-create-binding="true" can-attach-label="false">
- <default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
- <preferred-size width="150" height="50" />
- </default-constraints>
- </item>
- <item class="javax.swing.JList" icon="/com/intellij/uiDesigner/icons/list.png" removable="false" auto-create-binding="true" can-attach-label="false">
- <default-constraints vsize-policy="6" hsize-policy="2" anchor="0" fill="3">
- <preferred-size width="150" height="50" />
- </default-constraints>
- </item>
- <item class="javax.swing.JTree" icon="/com/intellij/uiDesigner/icons/tree.png" removable="false" auto-create-binding="true" can-attach-label="false">
- <default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
- <preferred-size width="150" height="50" />
- </default-constraints>
- </item>
- <item class="javax.swing.JTabbedPane" icon="/com/intellij/uiDesigner/icons/tabbedPane.png" removable="false" auto-create-binding="true" can-attach-label="false">
- <default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3">
- <preferred-size width="200" height="200" />
- </default-constraints>
- </item>
- <item class="javax.swing.JSplitPane" icon="/com/intellij/uiDesigner/icons/splitPane.png" removable="false" auto-create-binding="false" can-attach-label="false">
- <default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3">
- <preferred-size width="200" height="200" />
- </default-constraints>
- </item>
- <item class="javax.swing.JSpinner" icon="/com/intellij/uiDesigner/icons/spinner.png" removable="false" auto-create-binding="true" can-attach-label="true">
- <default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1" />
- </item>
- <item class="javax.swing.JSlider" icon="/com/intellij/uiDesigner/icons/slider.png" removable="false" auto-create-binding="true" can-attach-label="false">
- <default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1" />
- </item>
- <item class="javax.swing.JSeparator" icon="/com/intellij/uiDesigner/icons/separator.png" removable="false" auto-create-binding="false" can-attach-label="false">
- <default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3" />
- </item>
- <item class="javax.swing.JProgressBar" icon="/com/intellij/uiDesigner/icons/progressbar.png" removable="false" auto-create-binding="true" can-attach-label="false">
- <default-constraints vsize-policy="0" hsize-policy="6" anchor="0" fill="1" />
- </item>
- <item class="javax.swing.JToolBar" icon="/com/intellij/uiDesigner/icons/toolbar.png" removable="false" auto-create-binding="false" can-attach-label="false">
- <default-constraints vsize-policy="0" hsize-policy="6" anchor="0" fill="1">
- <preferred-size width="-1" height="20" />
- </default-constraints>
- </item>
- <item class="javax.swing.JToolBar$Separator" icon="/com/intellij/uiDesigner/icons/toolbarSeparator.png" removable="false" auto-create-binding="false" can-attach-label="false">
- <default-constraints vsize-policy="0" hsize-policy="0" anchor="0" fill="1" />
- </item>
- <item class="javax.swing.JScrollBar" icon="/com/intellij/uiDesigner/icons/scrollbar.png" removable="false" auto-create-binding="true" can-attach-label="false">
- <default-constraints vsize-policy="6" hsize-policy="0" anchor="0" fill="2" />
- </item>
- </group>
- </component>
-</project>
-
diff --git a/.idea/vcs.xml b/.idea/vcs.xml
deleted file mode 100644
index cbc984988..000000000
--- a/.idea/vcs.xml
+++ /dev/null
@@ -1,10 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<project version="4">
- <component name="ClearCaseSharedConfig">
- <option name="myUseUcmModel" value="true" />
- </component>
- <component name="VcsDirectoryMappings">
- <mapping directory="" vcs="Git" />
- </component>
-</project>
-
diff --git a/.pairs b/.pairs
deleted file mode 100644
index 917a24cc0..000000000
--- a/.pairs
+++ /dev/null
@@ -1,33 +0,0 @@
-# .pairs - configuration for 'git pair'
-# place in project or home directory
-pairs:
- hu: Harry Ugol
- ts: Tyler Schultz
- md: Matt DuVall
- xw: Christian Williams; xian
- jm: Joe Moore
- if: Ian Fisher; ifisher
- pg: Phil Goodwin; phil
- pp: Phil Plante
- rr: Ryan Richard; rrichard
- gv: Gregg Van Hove; gvanhove
- rk: Rick Kawala
- df: David Farber; dfarber
- gj: Glenn Jahnke; glennj
- am: Alexander Murmann
- jt: Jesse Toth
- lt: Lenny Turetsky
- mg: Mike Grafton
- gc: Greg Choi
- tl: Tim Labeeuw
- mh: Michael Haddad; mhaddad
- mm: Mike Mazur; mmazur
- wei: Wei Wu; wwu@apptera.com
- ad: Andrew Dai
- bc: Brian Colvin
- av: Aaron VonderHaar; avonderhaar
- at: Amrit Thakur
-email:
- prefix: pair
- domain: pivotallabs.com
-
diff --git a/.travis.yml b/.travis.yml
deleted file mode 100644
index 674d0214b..000000000
--- a/.travis.yml
+++ /dev/null
@@ -1,2 +0,0 @@
-language: java
-install: ant prepare-travis-ci
diff --git a/v1/Android.mk b/v1/Android.mk
deleted file mode 100644
index c8405e004..000000000
--- a/v1/Android.mk
+++ /dev/null
@@ -1,63 +0,0 @@
-# Copyright (C) 2010 The Android Open Source Project
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-LOCAL_PATH := $(call my-dir)
-include $(CLEAR_VARS)
-
-LOCAL_MODULE := robolectric
-LOCAL_SRC_FILES := $(call all-java-files-under, src/main/java)
-
-LOCAL_STATIC_JAVA_LIBRARIES := \
- robolectric-android \
- robolectric-android-support-v4 \
- robolectric-commons-codec \
- robolectric-commons-logging \
- robolectric-h2 \
- hamcrest \
- robolectric-httpclient \
- robolectric-httpcore \
- robolectric-javassist \
- robolectric-json \
- junit \
- robolectric-maps \
- objenesis-host \
- robolectric-sqlite-jdbc \
- robolectric-xpp3
-
-include $(BUILD_HOST_JAVA_LIBRARY)
-
-#############################################################
-# Pre-built dependency jars
-#############################################################
-
-include $(CLEAR_VARS)
-
-# TODO: Figure out how to not use a prebuilt android API 18 jar and grab from
-# prebuilts
-
-LOCAL_PREBUILT_STATIC_JAVA_LIBRARIES := \
- robolectric-android:lib/main/android.jar \
- robolectric-android-support-v4:lib/main/android-support-v4.jar \
- robolectric-commons-codec:lib/main/commons-codec-1.6.jar \
- robolectric-commons-logging:lib/main/commons-logging-1.1.1.jar \
- robolectric-h2:lib/main/commons-logging-1.1.1.jar \
- robolectric-httpclient:lib/main/httpclient-4.0.3.jar \
- robolectric-httpcore:lib/main/httpcore-4.0.1.jar \
- robolectric-javassist:lib/main/javassist-3.14.0-GA.jar \
- robolectric-json:lib/main/json-20080701.jar \
- robolectric-maps:lib/main/maps_v16.jar \
- robolectric-sqlite-jdbc:lib/main/sqlite-jdbc-3.7.2.jar \
- robolectric-xpp3:lib/main/xpp3-1.1.4c.jar
-
-include $(BUILD_HOST_PREBUILT)
diff --git a/v1/LICENSE.txt b/v1/LICENSE.txt
deleted file mode 100644
index c9dccb8d8..000000000
--- a/v1/LICENSE.txt
+++ /dev/null
@@ -1,21 +0,0 @@
-The MIT License
-
-Copyright (c) 2010 Xtreme Labs and Pivotal Labs
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-THE SOFTWARE.
diff --git a/v1/README.md b/v1/README.md
deleted file mode 100644
index 665c6aa0c..000000000
--- a/v1/README.md
+++ /dev/null
@@ -1,14 +0,0 @@
-<a name="README">[Robolectric](http://pivotal.github.com/robolectric/index.html)</a>
-=======
-
-**An Android Testing Framework**
-
-Robolectric can be built using either Maven or Ant. Both Eclipse (with the M2Eclipse plug-in) and
-IntelliJ can import the pom.xml file and will automatically generate their project files from it.
-
-For more information about how to use Robolectric on your project, extend its functionality, and join the community of
-contributors, please see: [http://pivotal.github.com/robolectric/index.html](http://pivotal.github.com/robolectric/index.html)
-
-[![Build Status](https://secure.travis-ci.org/pivotal/robolectric.png?branch=master)](http://travis-ci.org/pivotal/robolectric)
-
-http://ci.robolectric.org \ No newline at end of file
diff --git a/v1/build.gradle b/v1/build.gradle
deleted file mode 100644
index 0ad4ac66c..000000000
--- a/v1/build.gradle
+++ /dev/null
@@ -1,26 +0,0 @@
-apply plugin: 'java'
-
-sourceSets {
- main {
- java {
- srcDirs = ['src/main/java']
- }
- }
-}
-
-dependencies {
- compile getAndroidPrebuilt('18')
- compile files('lib/main/android-support-v4.jar')
- compile files('lib/main/commons-codec-1.6.jar')
- compile files('lib/main/commons-logging-1.1.1.jar')
- compile files('lib/main/httpclient-4.0.3.jar')
- compile files('lib/main/httpcore-4.0.1.jar')
- compile files('lib/main/javassist-3.14.0-GA.jar')
- compile files('lib/main/json-20080701.jar')
- compile files('lib/main/maps_v16.jar')
- compile files('lib/main/sqlite-jdbc-3.7.2.jar')
- compile files('lib/main/xpp3-1.1.4c.jar')
- compile project(':hamcrest')
- compile project(path: ':junit', configuration: 'host')
- compile project(':objenesis')
-}
diff --git a/v1/build.properties b/v1/build.properties
deleted file mode 100644
index f13aaf4d3..000000000
--- a/v1/build.properties
+++ /dev/null
@@ -1,26 +0,0 @@
-# This file is used to override default values used by the Ant build system.
-#
-# This file must be checked in Version Control Systems, as it is
-# integral to the build system of your project.
-
-# This file is only used by the Ant script.
-
-# You can use this to override default values such as
-# 'source.dir' for the location of your java source folder and
-# 'out.dir' for the location of your output folder.
-
-main.dir=src/main/java
-test.dir=src/test/java
-tmp.dir=tmp
-target.dir=target
-
-external.libs.dir=lib/main
-
-out.absolute.dir=bin
-
-# You can also use it define how the release builds are signed by declaring
-# the following properties:
-# 'key.store' for the location of your keystore and
-# 'key.alias' for the name of the key to use.
-# The password will be asked during the build when you use the 'release' target.
-
diff --git a/v1/build.xml b/v1/build.xml
deleted file mode 100644
index e183a482b..000000000
--- a/v1/build.xml
+++ /dev/null
@@ -1,254 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<project name="robolectric" default="test">
-
- <!-- The build.properties file can be created by you and is never touched
- by the 'android' tool. This is the place to change some of the default property values
- used by the Ant rules.
- Here are some properties you may want to change/update:
-
- application.package
- the name of your application package as defined in the manifest. Used by the
- 'uninstall' rule.
- source.dir
- the name of the source directory. Default is 'src'.
- out.dir
- the name of the output directory. Default is 'bin'.
-
- Properties related to the SDK location or the project target should be updated
- using the 'android' tool with the 'update' action.
-
- This file is an integral part of the build system for your application and
- should be checked in in Version Control Systems.
-
- -->
- <property file="build.properties"/>
-
- <!-- The default.properties file is created and updated by the 'android' tool, as well
- as ADT.
- This file is an integral part of the build system for your application and
- should be checked in in Version Control Systems. -->
- <property file="default.properties"/>
-
- <condition property="isWindows"> <os family="windows" /> </condition>
-
- <target name="findAndroidWindows" if="isWindows">
- <echo message="Finding the Android version in windows"/>
- <exec executable="./find-android.bat"/>
- </target>
- <target name="findAndroidUnix" unless="isWindows">
- <echo message="Finding the Android version in *nix"/>
- <exec executable="./find-android.sh"/>
- </target>
- <property file="local.properties"/>
-
- <!-- Custom Android task to deal with the project target, and import the proper rules.
- This requires ant 1.6.0 or above. -->
- <path id="android.antlibs">
- <pathelement path="${sdk.dir}/tools/lib/anttasks.jar"/>
- <pathelement path="${sdk.dir}/tools/lib/sdklib.jar"/>
- <pathelement path="${sdk.dir}/tools/lib/androidprefs.jar"/>
- <pathelement path="${sdk.dir}/tools/lib/apkbuilder.jar"/>
- <pathelement path="${sdk.dir}/tools/lib/jarutils.jar"/>
- </path>
-
- <path id="android.target.classpath">
- <pathelement path="${sdk.dir}/platforms/android-16/android.jar"/>
- <pathelement path="${sdk.dir}/add-ons/addon_google_apis_google_inc_16/libs/maps.jar"/>
- <pathelement path="${sdk.dir}/add-ons/addon-google_apis-google_inc_-16/libs/maps.jar"/>
- <pathelement path="${sdk.dir}/add-ons/addon-google_apis-google-16/libs/maps.jar"/>
- <pathelement path="${sdk.dir}/extras/android/support/v4/android-support-v4.jar"/>
- <pathelement path="${sdk.dir}/android-compatibility/v4/android-support-v4.jar"/>
- </path>
-
- <property name="main.absolute.dir" location="${main.dir}"/>
- <property name="out.main.dir" value="${out.absolute.dir}/mainClasses"/>
- <property name="out.main.absolute.dir" value="${out.main.dir}"/>
- <property name="main.external.libs.dir" value="lib/main"/>
- <property name="main.external.libs.absolute.dir" location="${main.external.libs.dir}"/>
-
- <property name="test.absolute.dir" location="${test.dir}"/>
- <property name="out.test.dir" value="${out.absolute.dir}/testClasses"/>
- <property name="out.test.absolute.dir" value="${out.test.dir}"/>
- <property name="test.external.libs.dir" value="lib/test"/>
- <property name="test.external.libs.absolute.dir" location="${test.external.libs.dir}"/>
-
- <property name="publish.dir" location="${out.absolute.dir}/publish"/>
-
- <property name="pages.dir" value="pages"/>
- <property name="downloads.dir" value="${pages.dir}/downloads"/>
- <property name="javadoc.out.dir" value="${pages.dir}/javadoc"/>
-
- <property name="base.package" value="com.xtremelabs.robolectric"/>
-
- <property environment="env"/>
- <condition property="build.number" value="${env.BUILD_NUMBER}" else="unknown">
- <isset property="env.BUILD_NUMBER"/>
- </condition>
-
- <target name="compile"
- description="compile module source"
- depends="findAndroidUnix, findAndroidWindows">
- <mkdir dir="${out.main.absolute.dir}"/>
-
- <javac encoding="ascii" source="1.6" target="1.6" debug="true" extdirs=""
- destdir="${out.main.absolute.dir}"
- verbose="${verbose}"
- classpath="${extensible.classpath}"
- includeantruntime="false">
- <src path="${main.absolute.dir}"/>
- <classpath>
- <pathelement path="${out.main.absolute.dir}"/>
- <path refid="android.target.classpath"/>
- <fileset dir="${main.external.libs.absolute.dir}" includes="*.jar"/>
- </classpath>
- </javac>
- </target>
-
- <target name="jar" description="create the robolectric jar" depends="compile">
- <mkdir dir="${target.dir}"/>
- <jar destfile="${target.dir}/robolectric.jar">
- <fileset dir="${out.main.absolute.dir}" includes="**/*.class"/>
- </jar>
- </target>
-
- <target name="jar-all" description="create the robolectric jar including all dependencies" depends="jar">
- <mkdir dir="${target.dir}/staging"/>
- <unjar dest="${target.dir}/staging" >
- <fileset dir="${main.external.libs.absolute.dir}" >
- <exclude name="*src.jar" />
- <exclude name="junit*.jar" />
- <exclude name="hamcrest*.jar" />
- </fileset>
- </unjar>
- <unjar dest="${target.dir}/staging" src="${target.dir}/robolectric.jar"/>
- <jar destfile="${target.dir}/robolectric-all.jar" basedir="${target.dir}/staging"/>
- <delete dir="${target.dir}/staging"/>
- </target>
-
- <target name="source-jar" description="create a jar file that includes all of the source code">
- <mkdir dir="${target.dir}"/>
- <jar destfile="${target.dir}/robolectric-src.jar" basedir="${main.absolute.dir}"/>
- </target>
-
- <target name="compile.tests" depends="compile"
- description="compile module source; test classes" unless="skip.tests">
- <mkdir dir="${out.test.absolute.dir}"/>
-
- <javac encoding="ascii" source="1.6" target="1.6" debug="true" extdirs=""
- destdir="${out.test.absolute.dir}"
- verbose="${verbose}"
- classpath="${extensible.classpath}"
- includeantruntime="false">
- <src path="${test.absolute.dir}"/>
- <classpath>
- <pathelement path="${out.main.absolute.dir}"/>
- <pathelement path="${out.test.absolute.dir}"/>
- <path refid="android.target.classpath"/>
- <fileset dir="${main.external.libs.absolute.dir}" includes="*.jar"/>
- <fileset dir="${test.external.libs.absolute.dir}" includes="*.jar"/>
- </classpath>
- </javac>
- </target>
-
- <target name="clean" description="cleanup module">
- <delete dir="${out.absolute.dir}"/>
- <delete dir="${out.test.absolute.dir}"/>
- <delete dir="${tmp.dir}"/>
- <delete dir="${target.dir}"/>
- </target>
-
- <target name="test" depends="compile.tests" description="test all">
- <mkdir dir="${basedir}/out/reports/tests"/>
- <junit showoutput="true" failureproperty="junit.failure">
- <formatter type="plain" usefile="false" if="junit.console.out"/>
- <formatter type="plain"/>
- <formatter type="xml"/>
- <batchtest todir="${basedir}/out/reports/tests">
- <fileset dir="${test.absolute.dir}">
- <include name="**/*Test.java"/>
- </fileset>
- </batchtest>
- <classpath>
- <pathelement path="${out.main.absolute.dir}"/>
- <pathelement path="${out.test.absolute.dir}"/>
- <fileset dir="${main.external.libs.dir}" includes="*.jar"/>
- <fileset dir="${test.external.libs.dir}" includes="*.jar"/>
- <path refid="android.target.classpath"/>
- </classpath>
- </junit>
- <fail if="junit.failure" message="Unit test(s) failed. See reports!"/>
- </target>
-
- <target name="check-for-pages-dir-setup">
- <condition property="pages.dir.exists">
- <available file="${pages.dir}" type="dir"/>
- </condition>
- </target>
-
- <target name="check-for-pages-dir" depends="check-for-pages-dir-setup" unless="pages.dir.exists">
- <echo message="do you need a 'pages' symlink?"/>
- </target>
-
- <target name="snapshot" description="update most recent version of robolectric as jars" depends="clean, test, jar-all, source-jar, check-for-pages-dir" if="pages.dir.exists">
- <copy todir="${downloads.dir}">
- <fileset dir="${target.dir}" includes="robolectric*.jar"/>
- </copy>
- <exec executable="./update-downloads.rb"/>
- </target>
-
- <target name="gen-javadoc" description="generate javadoc for the public API" depends="check-for-pages-dir" if="pages.dir.exists">
- <mkdir dir="${javadoc.out.dir}" />
- <javadoc
- packagenames="${base.package}.*"
- access="protected"
- defaultexcludes="yes"
- windowtitle="Robolectric API"
- sourcepath="${main.absolute.dir}"
- overview="${main.absolute.dir}/overview.html"
- destdir="${javadoc.out.dir}">
- <classpath>
- <pathelement path="${out.main.absolute.dir}"/>
- <path refid="android.target.classpath"/>
- <fileset dir="${main.external.libs.absolute.dir}" includes="*.jar"/>
- </classpath>
- <doctitle><![CDATA[<h1>Robolectric<br/>API Documentation</h1>]]></doctitle>
- </javadoc>
- </target>
-
- <target name="maven-install-jars" description="Install the jar files that Maven can't find for itself">
- <exec executable="mvn">
- <arg line="install:install-file -DgroupId=com.google.android.maps -DartifactId=maps -Dversion=10_r2 -Dpackaging=jar -Dfile=${sdk.dir}/add-ons/addon_google_apis_google_inc_10/libs/maps.jar" />
- </exec>
- <exec executable="mvn">
- <arg line="install:install-file -DgroupId=com.google.android.maps -DartifactId=maps -Dversion=10_r2 -Dpackaging=jar -Dfile=${sdk.dir}/add-ons/addon-google_apis-google_inc_-10/libs/maps.jar" />
- </exec>
- <exec executable="mvn">
- <arg line="install:install-file -DgroupId=com.google.android.maps -DartifactId=maps -Dversion=10_r2 -Dpackaging=jar -Dfile=${sdk.dir}/add-ons/addon-google_apis-google-10/libs/maps.jar" />
- </exec>
- </target>
-
- <!-- used by travis-ci -->
- <target name="prepare-travis-ci" description="Prepare for travis ci build">
- <mkdir dir="tmp"/>
- <get src="http://dl.google.com/android/android-sdk_r20.0.3-linux.tgz" dest="tmp" skipexisting="true"/>
- <untar src="tmp/android-sdk_r20.0.3-linux.tgz" compression="gzip" dest="tmp/sdk"/>
- <echo file="tmp/install-sdk">#!/bin/sh -e
- ANDROID="tmp/sdk/android-sdk-linux/tools/android"
- chmod +x $ANDROID
- SDKS=$($ANDROID list sdk --all | awk \
- '/SDK Platform.* API 10/ || /Google APIs, Android API 10, revision 2/ \
- { s=s "," int($1) } \
- END { print substr(s, 2, length(s)) }' \
- )
- $ANDROID update sdk --no-ui --all --filter $SDKS
- </echo>
- <chmod file="tmp/install-sdk" perm="u+x"/>
- <exec executable="tmp/install-sdk"/>
- <propertyfile file="local.properties">
- <entry key="sdk.dir" value="${basedir}/tmp/sdk/android-sdk-linux/"/>
- </propertyfile>
- <exec executable="mvn">
- <arg line="install:install-file -DgroupId=com.google.android.maps -DartifactId=maps -Dversion=10_r2 -Dpackaging=jar -Dfile=tmp/sdk/android-sdk-linux/add-ons/addon-google_apis-google-10/libs/maps.jar"/>
- </exec>
- </target>
-</project>
diff --git a/v1/find-android.bat b/v1/find-android.bat
deleted file mode 100644
index 470f346ca..000000000
--- a/v1/find-android.bat
+++ /dev/null
@@ -1,6 +0,0 @@
-@echo off
-for %%i in (android.bat) do set x=%%~dp$PATH:i
-set x=%x:\tools=%
-
-# not yet tested!
-@echo "sdk.dir=%x%" >> local.properties
diff --git a/v1/find-android.sh b/v1/find-android.sh
deleted file mode 100755
index 55f852606..000000000
--- a/v1/find-android.sh
+++ /dev/null
@@ -1,10 +0,0 @@
-#!/bin/sh
-
-# TODO: make this script work with android installed via homebrew. Until then, you must manually make sure
-# ANDROID_HOME has been set before running ant (e.g. ANDROID_HOME=/usr/local/Cellar/android-sdk/r10 ant)
-
-if [ -z $ANDROID_HOME ]; then
- ANDROID_HOME=`which android | sed 's/\/tools\/android$//'`
-fi
-
-echo "sdk.dir=$ANDROID_HOME" > local.properties
diff --git a/v1/lib/main/android-support-v4.jar b/v1/lib/main/android-support-v4.jar
deleted file mode 100644
index ab81fba80..000000000
--- a/v1/lib/main/android-support-v4.jar
+++ /dev/null
Binary files differ
diff --git a/v1/lib/main/android.jar b/v1/lib/main/android.jar
deleted file mode 100644
index 1402ae48c..000000000
--- a/v1/lib/main/android.jar
+++ /dev/null
Binary files differ
diff --git a/v1/lib/main/commons-codec-1.6.jar b/v1/lib/main/commons-codec-1.6.jar
deleted file mode 100644
index ee1bc49ac..000000000
--- a/v1/lib/main/commons-codec-1.6.jar
+++ /dev/null
Binary files differ
diff --git a/v1/lib/main/commons-logging-1.1.1.jar b/v1/lib/main/commons-logging-1.1.1.jar
deleted file mode 100644
index 1deef144c..000000000
--- a/v1/lib/main/commons-logging-1.1.1.jar
+++ /dev/null
Binary files differ
diff --git a/v1/lib/main/h2-1.2.147.jar b/v1/lib/main/h2-1.2.147.jar
deleted file mode 100644
index f93c4a22d..000000000
--- a/v1/lib/main/h2-1.2.147.jar
+++ /dev/null
Binary files differ
diff --git a/v1/lib/main/httpclient-4.0.3.jar b/v1/lib/main/httpclient-4.0.3.jar
deleted file mode 100644
index 16e349a48..000000000
--- a/v1/lib/main/httpclient-4.0.3.jar
+++ /dev/null
Binary files differ
diff --git a/v1/lib/main/httpcore-4.0.1.jar b/v1/lib/main/httpcore-4.0.1.jar
deleted file mode 100644
index 4aef35e2f..000000000
--- a/v1/lib/main/httpcore-4.0.1.jar
+++ /dev/null
Binary files differ
diff --git a/v1/lib/main/javassist-3.14.0-GA.jar b/v1/lib/main/javassist-3.14.0-GA.jar
deleted file mode 100644
index 0fbfc3ced..000000000
--- a/v1/lib/main/javassist-3.14.0-GA.jar
+++ /dev/null
Binary files differ
diff --git a/v1/lib/main/json-20080701.jar b/v1/lib/main/json-20080701.jar
deleted file mode 100644
index c9a093edb..000000000
--- a/v1/lib/main/json-20080701.jar
+++ /dev/null
Binary files differ
diff --git a/v1/lib/main/maps_v16.jar b/v1/lib/main/maps_v16.jar
deleted file mode 100644
index fa96514ce..000000000
--- a/v1/lib/main/maps_v16.jar
+++ /dev/null
Binary files differ
diff --git a/v1/lib/main/opengl-api-gl1.1-android-2.1_r1.jar b/v1/lib/main/opengl-api-gl1.1-android-2.1_r1.jar
deleted file mode 100644
index f635aeae8..000000000
--- a/v1/lib/main/opengl-api-gl1.1-android-2.1_r1.jar
+++ /dev/null
Binary files differ
diff --git a/v1/lib/main/sqlite-jdbc-3.7.2.jar b/v1/lib/main/sqlite-jdbc-3.7.2.jar
deleted file mode 100644
index 2030ea0f1..000000000
--- a/v1/lib/main/sqlite-jdbc-3.7.2.jar
+++ /dev/null
Binary files differ
diff --git a/v1/lib/main/xpp3-1.1.4c.jar b/v1/lib/main/xpp3-1.1.4c.jar
deleted file mode 100644
index 451ac82af..000000000
--- a/v1/lib/main/xpp3-1.1.4c.jar
+++ /dev/null
Binary files differ
diff --git a/v1/lib/test/mockito-core-1.8.5.jar b/v1/lib/test/mockito-core-1.8.5.jar
deleted file mode 100644
index e1f33b406..000000000
--- a/v1/lib/test/mockito-core-1.8.5.jar
+++ /dev/null
Binary files differ
diff --git a/v1/pom.xml b/v1/pom.xml
deleted file mode 100644
index eac20bcb7..000000000
--- a/v1/pom.xml
+++ /dev/null
@@ -1,322 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
- <modelVersion>4.0.0</modelVersion>
-
- <parent>
- <groupId>org.sonatype.oss</groupId>
- <artifactId>oss-parent</artifactId>
- <version>5</version>
- </parent>
-
- <groupId>com.pivotallabs</groupId>
- <artifactId>robolectric</artifactId>
- <version>1.2-SNAPSHOT</version>
- <packaging>jar</packaging>
- <name>Robolectric</name>
- <description>An alternative Android testing framework.</description>
- <url>http://pivotal.github.com/robolectric/</url>
-
- <dependencies>
- <dependency>
- <groupId>org.hamcrest</groupId>
- <artifactId>hamcrest-core</artifactId>
- <version>1.2</version>
- <scope>provided</scope>
- </dependency>
-
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit-dep</artifactId>
- <version>4.8.2</version>
- <scope>provided</scope>
- </dependency>
-
- <dependency>
- <groupId>org.objenesis</groupId>
- <artifactId>objenesis</artifactId>
- <version>1.0</version>
- </dependency>
-
- <dependency>
- <groupId>org.xerial</groupId>
- <artifactId>sqlite-jdbc</artifactId>
- <version>3.7.2</version>
- </dependency>
-
- <dependency>
- <groupId>com.h2database</groupId>
- <artifactId>h2</artifactId>
- <version>1.2.147</version>
- <scope>test</scope>
- </dependency>
-
- <dependency>
- <groupId>org.javassist</groupId>
- <artifactId>javassist</artifactId>
- <version>3.14.0-GA</version>
- </dependency>
-
- <dependency>
- <groupId>commons-logging</groupId>
- <artifactId>commons-logging</artifactId>
- <version>1.1.1</version>
- </dependency>
-
- <dependency>
- <groupId>commons-codec</groupId>
- <artifactId>commons-codec</artifactId>
- <version>1.6</version>
- </dependency>
-
- <dependency>
- <groupId>org.apache.httpcomponents</groupId>
- <artifactId>httpclient</artifactId>
- <version>4.0.3</version>
- </dependency>
-
- <dependency>
- <groupId>android</groupId>
- <artifactId>android</artifactId>
- <version>4.3_r2</version>
- <scope>provided</scope>
- </dependency>
-
- <dependency>
- <groupId>com.google.android.maps</groupId>
- <artifactId>maps</artifactId>
- <version>18_r3</version>
- <scope>provided</scope>
- </dependency>
-
- <dependency>
- <groupId>com.google.android</groupId>
- <artifactId>support-v4</artifactId>
- <version>r6</version>
- </dependency>
-
- <dependency>
- <groupId>org.mockito</groupId>
- <artifactId>mockito-core</artifactId>
- <version>1.8.5</version>
- <scope>test</scope>
- </dependency>
- </dependencies>
-
- <build>
- <plugins>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-source-plugin</artifactId>
- <version>2.1.2</version>
- <configuration />
- <executions>
- <execution>
- <id>attach-sources</id>
- <goals>
- <goal>jar</goal>
- </goals>
- </execution>
- </executions>
- </plugin>
- <plugin>
- <artifactId>maven-compiler-plugin</artifactId>
- <version>2.3.2</version>
- <configuration>
- <source>1.6</source>
- <target>1.6</target>
- </configuration>
- </plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-surefire-plugin</artifactId>
- <version>2.6</version>
- <configuration>
- <excludes>
- <exclude>**/Test*.java</exclude>
- </excludes>
- </configuration>
- </plugin>
-
- <plugin>
- <artifactId>maven-assembly-plugin</artifactId>
- <version>2.2</version>
- <configuration>
- <descriptorRefs>
- <descriptorRef>jar-with-dependencies</descriptorRef>
- </descriptorRefs>
- </configuration>
- <executions>
- <execution>
- <id>make-assembly</id>
- <phase>package</phase>
- <goals>
- <goal>single</goal>
- </goals>
- </execution>
- </executions>
- </plugin>
- <!-- required for testing robolectric-sqlite -->
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-jar-plugin</artifactId>
- <version>2.3.1</version>
- <executions>
- <execution>
- <goals>
- <goal>test-jar</goal>
- </goals>
- </execution>
- </executions>
- </plugin>
-
- <plugin>
- <artifactId>maven-clean-plugin</artifactId>
- <version>2.4.1</version>
- <configuration>
- <filesets>
- <fileset>
- <directory>tmp</directory>
- <includes>
- <include>*</include>
- </includes>
- </fileset>
- </filesets>
- </configuration>
- </plugin>
-
- </plugins>
- </build>
-
- <profiles>
- <profile>
- <id>ant-deps</id>
- <build>
- <plugins>
- <plugin>
- <artifactId>maven-antrun-plugin</artifactId>
- <version>1.6</version>
- <executions>
- <execution>
- <id>clean-dependencies</id>
- <phase>package</phase>
- <goals>
- <goal>run</goal>
- </goals>
- <configuration>
- <target>
- <delete dir="${project.basedir}/lib/main" />
- <mkdir dir="${project.basedir}/lib/main" />
- </target>
- </configuration>
- </execution>
- </executions>
- </plugin>
- <plugin>
- <artifactId>maven-dependency-plugin</artifactId>
- <executions>
- <execution>
- <id>copy-dependencies</id>
- <phase>package</phase>
- <goals>
- <goal>copy-dependencies</goal>
- </goals>
- <configuration>
- <outputDirectory>${project.basedir}/lib/main</outputDirectory>
- <overWriteReleases>false</overWriteReleases>
- <overWriteSnapshots>false</overWriteSnapshots>
- <overWriteIfNewer>true</overWriteIfNewer>
- <excludeArtifactIds>android,maps,mockito-core</excludeArtifactIds>
- </configuration>
- </execution>
- </executions>
- </plugin>
- </plugins>
- </build>
- </profile>
- </profiles>
-
- <scm>
- <url>git@github.com:pivotal/robolectric.git</url>
- <connection>scm:git:git://github.com/pivotal/robolectric.git</connection>
- <developerConnection>scm:git:git@github.com:pivotal/robolectric.git</developerConnection>
- </scm>
-
- <ciManagement>
- <system>Hudson</system>
- <url>http://ci.robolectric.org/job/robolectric</url>
- </ciManagement>
-
- <developers>
- <developer>
- <id>xian</id>
- <name>Christian Williams</name>
- <email>xian@pivotallabs.com</email>
- <organization>Pivotal Labs</organization>
- <organizationUrl>http://pivotallabs.com/</organizationUrl>
- <roles>
- <role>Developer</role>
- </roles>
- <timezone>PST/PDT</timezone>
- </developer>
- <developer>
- <id>tyler</id>
- <name>Tyler Schultz</name>
- <email>tyler@pivotallabs.com</email>
- <organization>Pivotal Labs</organization>
- <organizationUrl>http://pivotallabs.com/</organizationUrl>
- <roles>
- <role>Project Owner</role>
- <role>Developer</role>
- </roles>
- <timezone>PST/PDT</timezone>
- </developer>
- <developer>
- <id>phil</id>
- <name>Phil Goodwin</name>
- <email>phil@pivotallabs.com</email>
- <organization>Pivotal Labs</organization>
- <organizationUrl>http://pivotallabs.com/</organizationUrl>
- <roles>
- <role>Developer</role>
- </roles>
- <timezone>PST/PDT</timezone>
- </developer>
- </developers>
-
- <mailingLists>
- <mailingList>
- <name>User List</name>
- <post>robolectric@googlegroups.com</post>
- <archive>http://groups.google.com/group/robolectric</archive>
- </mailingList>
- </mailingLists>
-
- <licenses>
- <license>
- <name>MIT license</name>
- <comments>
- The MIT License
-
- Copyright (c) 2010 Xtreme Labs and Pivotal Labs
-
- Permission is hereby granted, free of charge, to any person obtaining a copy
- of this software and associated documentation files (the "Software"), to deal
- in the Software without restriction, including without limitation the rights
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- copies of the Software, and to permit persons to whom the Software is
- furnished to do so, subject to the following conditions:
-
- The above copyright notice and this permission notice shall be included in
- all copies or substantial portions of the Software.
-
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- THE SOFTWARE.
- </comments>
- </license>
- </licenses>
-</project>
diff --git a/v1/src/main/java/NOTICE b/v1/src/main/java/NOTICE
deleted file mode 100644
index 20062013e..000000000
--- a/v1/src/main/java/NOTICE
+++ /dev/null
@@ -1,283 +0,0 @@
- =========================================================================
- == NOTICE file corresponding to the section 4 d of ==
- == the Apache License, Version 2.0, ==
- == in this case for the Android-specific code. ==
- =========================================================================
-
-Android Code
-Copyright 2005-2008 The Android Open Source Project
-
-This product includes software developed as part of
-The Android Open Source Project (http://source.android.com).
-
- =========================================================================
- == NOTICE file corresponding to the section 4 d of ==
- == the Apache License, Version 2.0, ==
- == in this case for Apache Commons code. ==
- =========================================================================
-
-Apache Commons
-Copyright 1999-2004 The Apache Software Foundation
-
-This product includes software developed at
-The Apache Software Foundation (http://www.apache.org/).
-
- =========================================================================
- == NOTICE file corresponding to the section 4 d of ==
- == the Apache License, Version 2.0, ==
- == in this case for Jakarta Commons Logging. ==
- =========================================================================
-
-Jakarta Commons Logging (JCL)
-Copyright 2005,2006 The Apache Software Foundation.
-
-This product includes software developed at
-The Apache Software Foundation (http://www.apache.org/).
-
- =========================================================================
- == NOTICE file corresponding to the section 4 d of ==
- == the Apache License, Version 2.0, ==
- == in this case for the Nuance code. ==
- =========================================================================
-
-These files are Copyright 2007 Nuance Communications, but released under
-the Apache2 License.
-
- =========================================================================
- == NOTICE file corresponding to the section 4 d of ==
- == the Apache License, Version 2.0, ==
- == in this case for the Media Codecs code. ==
- =========================================================================
-
-Media Codecs
-These files are Copyright 1998 - 2009 PacketVideo, but released under
-the Apache2 License.
-
- Apache License
- Version 2.0, January 2004
- http://www.apache.org/licenses/
-
- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
-
- 1. Definitions.
-
- "License" shall mean the terms and conditions for use, reproduction,
- and distribution as defined by Sections 1 through 9 of this document.
-
- "Licensor" shall mean the copyright owner or entity authorized by
- the copyright owner that is granting the License.
-
- "Legal Entity" shall mean the union of the acting entity and all
- other entities that control, are controlled by, or are under common
- control with that entity. For the purposes of this definition,
- "control" means (i) the power, direct or indirect, to cause the
- direction or management of such entity, whether by contract or
- otherwise, or (ii) ownership of fifty percent (50%) or more of the
- outstanding shares, or (iii) beneficial ownership of such entity.
-
- "You" (or "Your") shall mean an individual or Legal Entity
- exercising permissions granted by this License.
-
- "Source" form shall mean the preferred form for making modifications,
- including but not limited to software source code, documentation
- source, and configuration files.
-
- "Object" form shall mean any form resulting from mechanical
- transformation or translation of a Source form, including but
- not limited to compiled object code, generated documentation,
- and conversions to other media types.
-
- "Work" shall mean the work of authorship, whether in Source or
- Object form, made available under the License, as indicated by a
- copyright notice that is included in or attached to the work
- (an example is provided in the Appendix below).
-
- "Derivative Works" shall mean any work, whether in Source or Object
- form, that is based on (or derived from) the Work and for which the
- editorial revisions, annotations, elaborations, or other modifications
- represent, as a whole, an original work of authorship. For the purposes
- of this License, Derivative Works shall not include works that remain
- separable from, or merely link (or bind by name) to the interfaces of,
- the Work and Derivative Works thereof.
-
- "Contribution" shall mean any work of authorship, including
- the original version of the Work and any modifications or additions
- to that Work or Derivative Works thereof, that is intentionally
- submitted to Licensor for inclusion in the Work by the copyright owner
- or by an individual or Legal Entity authorized to submit on behalf of
- the copyright owner. For the purposes of this definition, "submitted"
- means any form of electronic, verbal, or written communication sent
- to the Licensor or its representatives, including but not limited to
- communication on electronic mailing lists, source code control systems,
- and issue tracking systems that are managed by, or on behalf of, the
- Licensor for the purpose of discussing and improving the Work, but
- excluding communication that is conspicuously marked or otherwise
- designated in writing by the copyright owner as "Not a Contribution."
-
- "Contributor" shall mean Licensor and any individual or Legal Entity
- on behalf of whom a Contribution has been received by Licensor and
- subsequently incorporated within the Work.
-
- 2. Grant of Copyright License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- copyright license to reproduce, prepare Derivative Works of,
- publicly display, publicly perform, sublicense, and distribute the
- Work and such Derivative Works in Source or Object form.
-
- 3. Grant of Patent License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- (except as stated in this section) patent license to make, have made,
- use, offer to sell, sell, import, and otherwise transfer the Work,
- where such license applies only to those patent claims licensable
- by such Contributor that are necessarily infringed by their
- Contribution(s) alone or by combination of their Contribution(s)
- with the Work to which such Contribution(s) was submitted. If You
- institute patent litigation against any entity (including a
- cross-claim or counterclaim in a lawsuit) alleging that the Work
- or a Contribution incorporated within the Work constitutes direct
- or contributory patent infringement, then any patent licenses
- granted to You under this License for that Work shall terminate
- as of the date such litigation is filed.
-
- 4. Redistribution. You may reproduce and distribute copies of the
- Work or Derivative Works thereof in any medium, with or without
- modifications, and in Source or Object form, provided that You
- meet the following conditions:
-
- (a) You must give any other recipients of the Work or
- Derivative Works a copy of this License; and
-
- (b) You must cause any modified files to carry prominent notices
- stating that You changed the files; and
-
- (c) You must retain, in the Source form of any Derivative Works
- that You distribute, all copyright, patent, trademark, and
- attribution notices from the Source form of the Work,
- excluding those notices that do not pertain to any part of
- the Derivative Works; and
-
- (d) If the Work includes a "NOTICE" text file as part of its
- distribution, then any Derivative Works that You distribute must
- include a readable copy of the attribution notices contained
- within such NOTICE file, excluding those notices that do not
- pertain to any part of the Derivative Works, in at least one
- of the following places: within a NOTICE text file distributed
- as part of the Derivative Works; within the Source form or
- documentation, if provided along with the Derivative Works; or,
- within a display generated by the Derivative Works, if and
- wherever such third-party notices normally appear. The contents
- of the NOTICE file are for informational purposes only and
- do not modify the License. You may add Your own attribution
- notices within Derivative Works that You distribute, alongside
- or as an addendum to the NOTICE text from the Work, provided
- that such additional attribution notices cannot be construed
- as modifying the License.
-
- You may add Your own copyright statement to Your modifications and
- may provide additional or different license terms and conditions
- for use, reproduction, or distribution of Your modifications, or
- for any such Derivative Works as a whole, provided Your use,
- reproduction, and distribution of the Work otherwise complies with
- the conditions stated in this License.
-
- 5. Submission of Contributions. Unless You explicitly state otherwise,
- any Contribution intentionally submitted for inclusion in the Work
- by You to the Licensor shall be under the terms and conditions of
- this License, without any additional terms or conditions.
- Notwithstanding the above, nothing herein shall supersede or modify
- the terms of any separate license agreement you may have executed
- with Licensor regarding such Contributions.
-
- 6. Trademarks. This License does not grant permission to use the trade
- names, trademarks, service marks, or product names of the Licensor,
- except as required for reasonable and customary use in describing the
- origin of the Work and reproducing the content of the NOTICE file.
-
- 7. Disclaimer of Warranty. Unless required by applicable law or
- agreed to in writing, Licensor provides the Work (and each
- Contributor provides its Contributions) on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- implied, including, without limitation, any warranties or conditions
- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
- PARTICULAR PURPOSE. You are solely responsible for determining the
- appropriateness of using or redistributing the Work and assume any
- risks associated with Your exercise of permissions under this License.
-
- 8. Limitation of Liability. In no event and under no legal theory,
- whether in tort (including negligence), contract, or otherwise,
- unless required by applicable law (such as deliberate and grossly
- negligent acts) or agreed to in writing, shall any Contributor be
- liable to You for damages, including any direct, indirect, special,
- incidental, or consequential damages of any character arising as a
- result of this License or out of the use or inability to use the
- Work (including but not limited to damages for loss of goodwill,
- work stoppage, computer failure or malfunction, or any and all
- other commercial damages or losses), even if such Contributor
- has been advised of the possibility of such damages.
-
- 9. Accepting Warranty or Additional Liability. While redistributing
- the Work or Derivative Works thereof, You may choose to offer,
- and charge a fee for, acceptance of support, warranty, indemnity,
- or other liability obligations and/or rights consistent with this
- License. However, in accepting such obligations, You may act only
- on Your own behalf and on Your sole responsibility, not on behalf
- of any other Contributor, and only if You agree to indemnify,
- defend, and hold each Contributor harmless for any liability
- incurred by, or claims asserted against, such Contributor by reason
- of your accepting any such warranty or additional liability.
-
- END OF TERMS AND CONDITIONS
-
-
-
-UNICODE, INC. LICENSE AGREEMENT - DATA FILES AND SOFTWARE
-
-Unicode Data Files include all data files under the directories
-http://www.unicode.org/Public/, http://www.unicode.org/reports/,
-and http://www.unicode.org/cldr/data/ . Unicode Software includes any
-source code published in the Unicode Standard or under the directories
-http://www.unicode.org/Public/, http://www.unicode.org/reports/, and
-http://www.unicode.org/cldr/data/.
-
-NOTICE TO USER: Carefully read the following legal agreement. BY
-DOWNLOADING, INSTALLING, COPYING OR OTHERWISE USING UNICODE INC.'S DATA
-FILES ("DATA FILES"), AND/OR SOFTWARE ("SOFTWARE"), YOU UNEQUIVOCALLY
-ACCEPT, AND AGREE TO BE BOUND BY, ALL OF THE TERMS AND CONDITIONS OF
-THIS AGREEMENT. IF YOU DO NOT AGREE, DO NOT DOWNLOAD, INSTALL, COPY,
-DISTRIBUTE OR USE THE DATA FILES OR SOFTWARE.
-
-COPYRIGHT AND PERMISSION NOTICE
-
-Copyright © 1991-2008 Unicode, Inc. All rights reserved. Distributed
-under the Terms of Use in http://www.unicode.org/copyright.html.
-
-Permission is hereby granted, free of charge, to any person obtaining
-a copy of the Unicode data files and any associated documentation (the
-"Data Files") or Unicode software and any associated documentation (the
-"Software") to deal in the Data Files or Software without restriction,
-including without limitation the rights to use, copy, modify, merge,
-publish, distribute, and/or sell copies of the Data Files or Software,
-and to permit persons to whom the Data Files or Software are furnished to
-do so, provided that (a) the above copyright notice(s) and this permission
-notice appear with all copies of the Data Files or Software, (b) both the
-above copyright notice(s) and this permission notice appear in associated
-documentation, and (c) there is clear notice in each modified Data File
-or in the Software as well as in the documentation associated with the
-Data File(s) or Software that the data or software has been modified.
-
-THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF
-ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
-OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
-OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS
-INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT
-OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
-OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
-OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE
-OR PERFORMANCE OF THE DATA FILES OR SOFTWARE.
-
-Except as contained in this notice, the name of a copyright holder
-shall not be used in advertising or otherwise to promote the sale, use
-or other dealings in these Data Files or Software without prior written
-authorization of the copyright holder.
diff --git a/v1/src/main/java/android/content/TestIntentSender.java b/v1/src/main/java/android/content/TestIntentSender.java
deleted file mode 100644
index 40d37dd98..000000000
--- a/v1/src/main/java/android/content/TestIntentSender.java
+++ /dev/null
@@ -1,6 +0,0 @@
-package android.content;
-
-public class TestIntentSender extends IntentSender{
- public Intent intent;
-
-}
diff --git a/v1/src/main/java/android/hardware/TestSensorManager.java b/v1/src/main/java/android/hardware/TestSensorManager.java
deleted file mode 100644
index c64f52074..000000000
--- a/v1/src/main/java/android/hardware/TestSensorManager.java
+++ /dev/null
@@ -1,10 +0,0 @@
-package android.hardware;
-
-
-public class TestSensorManager extends SensorManager {
-
- public TestSensorManager() {
-
- }
-
-}
diff --git a/v1/src/main/java/android/net/Uri__FromAndroid.java b/v1/src/main/java/android/net/Uri__FromAndroid.java
deleted file mode 100644
index 2c77864a4..000000000
--- a/v1/src/main/java/android/net/Uri__FromAndroid.java
+++ /dev/null
@@ -1,2250 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.net;
-
-import android.os.Parcel;
-import android.os.Parcelable;
-import android.util.Log;
-
-import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.IOException;
-import java.io.UnsupportedEncodingException;
-import java.net.URLEncoder;
-import java.util.*;
-
-/**
- * Immutable URI reference. A URI reference includes a URI and a fragment, the
- * component of the URI following a '#'. Builds and parses URI references
- * which conform to
- * <a href="http://www.faqs.org/rfcs/rfc2396.html">RFC 2396</a>.
- *
- * <p>In the interest of performance, this class performs little to no
- * validation. Behavior is undefined for invalid input. This class is very
- * forgiving--in the face of invalid input, it will return garbage
- * rather than throw an exception unless otherwise specified.
- */
-public abstract class Uri__FromAndroid implements Parcelable, Comparable<Uri__FromAndroid> {
-
- /*
-
- This class aims to do as little up front work as possible. To accomplish
- that, we vary the implementation dependending on what the user passes in.
- For example, we have one implementation if the user passes in a
- URI string (StringUri) and another if the user passes in the
- individual components (OpaqueUri).
-
- *Concurrency notes*: Like any truly immutable object, this class is safe
- for concurrent use. This class uses a caching pattern in some places where
- it doesn't use volatile or synchronized. This is safe to do with ints
- because getting or setting an int is atomic. It's safe to do with a String
- because the internal fields are final and the memory model guarantees other
- threads won't see a partially initialized instance. We are not guaranteed
- that some threads will immediately see changes from other threads on
- certain platforms, but we don't mind if those threads reconstruct the
- cached result. As a result, we get thread safe caching with no concurrency
- overhead, which means the most common case, access from a single thread,
- is as fast as possible.
-
- From the Java Language spec.:
-
- "17.5 Final Field Semantics
-
- ... when the object is seen by another thread, that thread will always
- see the correctly constructed version of that object's final fields.
- It will also see versions of any object or array referenced by
- those final fields that are at least as up-to-date as the final fields
- are."
-
- In that same vein, all non-transient fields within Uri
- implementations should be final and immutable so as to ensure true
- immutability for clients even when they don't use proper concurrency
- control.
-
- For reference, from RFC 2396:
-
- "4.3. Parsing a URI Reference
-
- A URI reference is typically parsed according to the four main
- components and fragment identifier in order to determine what
- components are present and whether the reference is relative or
- absolute. The individual components are then parsed for their
- subparts and, if not opaque, to verify their validity.
-
- Although the BNF defines what is allowed in each component, it is
- ambiguous in terms of differentiating between an authority component
- and a path component that begins with two slash characters. The
- greedy algorithm is used for disambiguation: the left-most matching
- rule soaks up as much of the URI reference string as it is capable of
- matching. In other words, the authority component wins."
-
- The "four main components" of a hierarchical URI consist of
- <scheme>://<authority><path>?<query>
-
- */
-
- /** Log tag. */
- private static final String LOG = Uri__FromAndroid.class.getSimpleName();
-
- /**
- * NOTE: EMPTY accesses this field during its own initialization, so this
- * field *must* be initialized first, or else EMPTY will see a null value!
- *
- * Placeholder for strings which haven't been cached. This enables us
- * to cache null. We intentionally create a new String instance so we can
- * compare its identity and there is no chance we will confuse it with
- * user data.
- */
- @SuppressWarnings("RedundantStringConstructorCall")
- private static final String NOT_CACHED = new String("NOT CACHED");
-
- /**
- * The empty URI, equivalent to "".
- */
- public static final Uri__FromAndroid EMPTY = new HierarchicalUri(null, Part.NULL,
- PathPart.EMPTY, Part.NULL, Part.NULL);
-
- /**
- * Prevents external subclassing.
- */
- private Uri__FromAndroid() {}
-
- /**
- * Returns true if this URI is hierarchical like "http://google.com".
- * Absolute URIs are hierarchical if the scheme-specific part starts with
- * a '/'. Relative URIs are always hierarchical.
- */
- public abstract boolean isHierarchical();
-
- /**
- * Returns true if this URI is opaque like "mailto:nobody@google.com". The
- * scheme-specific part of an opaque URI cannot start with a '/'.
- */
- public boolean isOpaque() {
- return !isHierarchical();
- }
-
- /**
- * Returns true if this URI is relative, i.e. if it doesn't contain an
- * explicit scheme.
- *
- * @return true if this URI is relative, false if it's absolute
- */
- public abstract boolean isRelative();
-
- /**
- * Returns true if this URI is absolute, i.e. if it contains an
- * explicit scheme.
- *
- * @return true if this URI is absolute, false if it's relative
- */
- public boolean isAbsolute() {
- return !isRelative();
- }
-
- /**
- * Gets the scheme of this URI. Example: "http"
- *
- * @return the scheme or null if this is a relative URI
- */
- public abstract String getScheme();
-
- /**
- * Gets the scheme-specific part of this URI, i.e. everything between the
- * scheme separator ':' and the fragment separator '#'. If this is a
- * relative URI, this method returns the entire URI. Decodes escaped octets.
- *
- * <p>Example: "//www.google.com/search?q=android"
- *
- * @return the decoded scheme-specific-part
- */
- public abstract String getSchemeSpecificPart();
-
- /**
- * Gets the scheme-specific part of this URI, i.e. everything between the
- * scheme separator ':' and the fragment separator '#'. If this is a
- * relative URI, this method returns the entire URI. Leaves escaped octets
- * intact.
- *
- * <p>Example: "//www.google.com/search?q=android"
- *
- * @return the decoded scheme-specific-part
- */
- public abstract String getEncodedSchemeSpecificPart();
-
- /**
- * Gets the decoded authority part of this URI. For
- * server addresses, the authority is structured as follows:
- * {@code [ userinfo '@' ] host [ ':' port ]}
- *
- * <p>Examples: "google.com", "bob@google.com:80"
- *
- * @return the authority for this URI or null if not present
- */
- public abstract String getAuthority();
-
- /**
- * Gets the encoded authority part of this URI. For
- * server addresses, the authority is structured as follows:
- * {@code [ userinfo '@' ] host [ ':' port ]}
- *
- * <p>Examples: "google.com", "bob@google.com:80"
- *
- * @return the authority for this URI or null if not present
- */
- public abstract String getEncodedAuthority();
-
- /**
- * Gets the decoded user information from the authority.
- * For example, if the authority is "nobody@google.com", this method will
- * return "nobody".
- *
- * @return the user info for this URI or null if not present
- */
- public abstract String getUserInfo();
-
- /**
- * Gets the encoded user information from the authority.
- * For example, if the authority is "nobody@google.com", this method will
- * return "nobody".
- *
- * @return the user info for this URI or null if not present
- */
- public abstract String getEncodedUserInfo();
-
- /**
- * Gets the encoded host from the authority for this URI. For example,
- * if the authority is "bob@google.com", this method will return
- * "google.com".
- *
- * @return the host for this URI or null if not present
- */
- public abstract String getHost();
-
- /**
- * Gets the port from the authority for this URI. For example,
- * if the authority is "google.com:80", this method will return 80.
- *
- * @return the port for this URI or -1 if invalid or not present
- */
- public abstract int getPort();
-
- /**
- * Gets the decoded path.
- *
- * @return the decoded path, or null if this is not a hierarchical URI
- * (like "mailto:nobody@google.com") or the URI is invalid
- */
- public abstract String getPath();
-
- /**
- * Gets the encoded path.
- *
- * @return the encoded path, or null if this is not a hierarchical URI
- * (like "mailto:nobody@google.com") or the URI is invalid
- */
- public abstract String getEncodedPath();
-
- /**
- * Gets the decoded query component from this URI. The query comes after
- * the query separator ('?') and before the fragment separator ('#'). This
- * method would return "q=android" for
- * "http://www.google.com/search?q=android".
- *
- * @return the decoded query or null if there isn't one
- */
- public abstract String getQuery();
-
- /**
- * Gets the encoded query component from this URI. The query comes after
- * the query separator ('?') and before the fragment separator ('#'). This
- * method would return "q=android" for
- * "http://www.google.com/search?q=android".
- *
- * @return the encoded query or null if there isn't one
- */
- public abstract String getEncodedQuery();
-
- /**
- * Gets the decoded fragment part of this URI, everything after the '#'.
- *
- * @return the decoded fragment or null if there isn't one
- */
- public abstract String getFragment();
-
- /**
- * Gets the encoded fragment part of this URI, everything after the '#'.
- *
- * @return the encoded fragment or null if there isn't one
- */
- public abstract String getEncodedFragment();
-
- /**
- * Gets the decoded path segments.
- *
- * @return decoded path segments, each without a leading or trailing '/'
- */
- public abstract List<String> getPathSegments();
-
- /**
- * Gets the decoded last segment in the path.
- *
- * @return the decoded last segment or null if the path is empty
- */
- public abstract String getLastPathSegment();
-
- /**
- * Compares this Uri to another object for equality. Returns true if the
- * encoded string representations of this Uri and the given Uri are
- * equal. Case counts. Paths are not normalized. If one Uri specifies a
- * default port explicitly and the other leaves it implicit, they will not
- * be considered equal.
- */
- public boolean equals(Object o) {
- if (!(o instanceof Uri__FromAndroid)) {
- return false;
- }
-
- Uri__FromAndroid other = (Uri__FromAndroid) o;
-
- return toString().equals(other.toString());
- }
-
- /**
- * Hashes the encoded string represention of this Uri consistently with
- * {@link #equals(Object)}.
- */
- public int hashCode() {
- return toString().hashCode();
- }
-
- /**
- * Compares the string representation of this Uri with that of
- * another.
- */
- public int compareTo(Uri__FromAndroid other) {
- return toString().compareTo(other.toString());
- }
-
- /**
- * Returns the encoded string representation of this URI.
- * Example: "http://google.com/"
- */
- public abstract String toString();
-
- /**
- * Constructs a new builder, copying the attributes from this Uri.
- */
- public abstract Builder buildUpon();
-
- /** Index of a component which was not found. */
- private final static int NOT_FOUND = -1;
-
- /** Placeholder value for an index which hasn't been calculated yet. */
- private final static int NOT_CALCULATED = -2;
-
- /**
- * Error message presented when a user tries to treat an opaque URI as
- * hierarchical.
- */
- private static final String NOT_HIERARCHICAL
- = "This isn't a hierarchical URI.";
-
- /** Default encoding. */
- private static final String DEFAULT_ENCODING = "UTF-8";
-
- /**
- * Creates a Uri which parses the given encoded URI string.
- *
- * @param uriString an RFC 2396-compliant, encoded URI
- * @throws NullPointerException if uriString is null
- * @return Uri for this given uri string
- */
- public static Uri__FromAndroid parse(String uriString) {
- return new StringUri(uriString);
- }
-
- /**
- * Creates a Uri from a file. The URI has the form
- * "file://<absolute path>". Encodes path characters with the exception of
- * '/'.
- *
- * <p>Example: "file:///tmp/android.txt"
- *
- * @throws NullPointerException if file is null
- * @return a Uri for the given file
- */
- public static Uri__FromAndroid fromFile(File file) {
- if (file == null) {
- throw new NullPointerException("file");
- }
-
- PathPart path = PathPart.fromDecoded(file.getAbsolutePath());
- return new HierarchicalUri(
- "file", Part.EMPTY, path, Part.NULL, Part.NULL);
- }
-
- /**
- * An implementation which wraps a String URI. This URI can be opaque or
- * hierarchical, but we extend AbstractHierarchicalUri in case we need
- * the hierarchical functionality.
- */
- private static class StringUri extends AbstractHierarchicalUri {
-
- /** Used in parcelling. */
- static final int TYPE_ID = 1;
-
- /** URI string representation. */
- private final String uriString;
-
- private StringUri(String uriString) {
- if (uriString == null) {
- throw new NullPointerException("uriString");
- }
-
- this.uriString = uriString;
- }
-
- static Uri__FromAndroid readFrom(Parcel parcel) {
- return new StringUri(parcel.readString());
- }
-
- public int describeContents() {
- return 0;
- }
-
- public void writeToParcel(Parcel parcel, int flags) {
- parcel.writeInt(TYPE_ID);
- parcel.writeString(uriString);
- }
-
- /** Cached scheme separator index. */
- private volatile int cachedSsi = NOT_CALCULATED;
-
- /** Finds the first ':'. Returns -1 if none found. */
- private int findSchemeSeparator() {
- return cachedSsi == NOT_CALCULATED
- ? cachedSsi = uriString.indexOf(':')
- : cachedSsi;
- }
-
- /** Cached fragment separator index. */
- private volatile int cachedFsi = NOT_CALCULATED;
-
- /** Finds the first '#'. Returns -1 if none found. */
- private int findFragmentSeparator() {
- return cachedFsi == NOT_CALCULATED
- ? cachedFsi = uriString.indexOf('#', findSchemeSeparator())
- : cachedFsi;
- }
-
- public boolean isHierarchical() {
- int ssi = findSchemeSeparator();
-
- if (ssi == NOT_FOUND) {
- // All relative URIs are hierarchical.
- return true;
- }
-
- if (uriString.length() == ssi + 1) {
- // No ssp.
- return false;
- }
-
- // If the ssp starts with a '/', this is hierarchical.
- return uriString.charAt(ssi + 1) == '/';
- }
-
- public boolean isRelative() {
- // Note: We return true if the index is 0
- return findSchemeSeparator() == NOT_FOUND;
- }
-
- private volatile String scheme = NOT_CACHED;
-
- public String getScheme() {
- @SuppressWarnings("StringEquality")
- boolean cached = (scheme != NOT_CACHED);
- return cached ? scheme : (scheme = parseScheme());
- }
-
- private String parseScheme() {
- int ssi = findSchemeSeparator();
- return ssi == NOT_FOUND ? null : uriString.substring(0, ssi);
- }
-
- private Part ssp;
-
- private Part getSsp() {
- return ssp == null ? ssp = Part.fromEncoded(parseSsp()) : ssp;
- }
-
- public String getEncodedSchemeSpecificPart() {
- return getSsp().getEncoded();
- }
-
- public String getSchemeSpecificPart() {
- return getSsp().getDecoded();
- }
-
- private String parseSsp() {
- int ssi = findSchemeSeparator();
- int fsi = findFragmentSeparator();
-
- // Return everything between ssi and fsi.
- return fsi == NOT_FOUND
- ? uriString.substring(ssi + 1)
- : uriString.substring(ssi + 1, fsi);
- }
-
- private Part authority;
-
- private Part getAuthorityPart() {
- if (authority == null) {
- String encodedAuthority
- = parseAuthority(this.uriString, findSchemeSeparator());
- return authority = Part.fromEncoded(encodedAuthority);
- }
-
- return authority;
- }
-
- public String getEncodedAuthority() {
- return getAuthorityPart().getEncoded();
- }
-
- public String getAuthority() {
- return getAuthorityPart().getDecoded();
- }
-
- private PathPart path;
-
- private PathPart getPathPart() {
- return path == null
- ? path = PathPart.fromEncoded(parsePath())
- : path;
- }
-
- public String getPath() {
- return getPathPart().getDecoded();
- }
-
- public String getEncodedPath() {
- return getPathPart().getEncoded();
- }
-
- public List<String> getPathSegments() {
- return getPathPart().getPathSegments();
- }
-
- private String parsePath() {
- String uriString = this.uriString;
- int ssi = findSchemeSeparator();
-
- // If the URI is absolute.
- if (ssi > -1) {
- // Is there anything after the ':'?
- boolean schemeOnly = ssi + 1 == uriString.length();
- if (schemeOnly) {
- // Opaque URI.
- return null;
- }
-
- // A '/' after the ':' means this is hierarchical.
- if (uriString.charAt(ssi + 1) != '/') {
- // Opaque URI.
- return null;
- }
- } else {
- // All relative URIs are hierarchical.
- }
-
- return parsePath(uriString, ssi);
- }
-
- private Part query;
-
- private Part getQueryPart() {
- return query == null
- ? query = Part.fromEncoded(parseQuery()) : query;
- }
-
- public String getEncodedQuery() {
- return getQueryPart().getEncoded();
- }
-
- private String parseQuery() {
- // It doesn't make sense to cache this index. We only ever
- // calculate it once.
- int qsi = uriString.indexOf('?', findSchemeSeparator());
- if (qsi == NOT_FOUND) {
- return null;
- }
-
- int fsi = findFragmentSeparator();
-
- if (fsi == NOT_FOUND) {
- return uriString.substring(qsi + 1);
- }
-
- if (fsi < qsi) {
- // Invalid.
- return null;
- }
-
- return uriString.substring(qsi + 1, fsi);
- }
-
- public String getQuery() {
- return getQueryPart().getDecoded();
- }
-
- private Part fragment;
-
- private Part getFragmentPart() {
- return fragment == null
- ? fragment = Part.fromEncoded(parseFragment()) : fragment;
- }
-
- public String getEncodedFragment() {
- return getFragmentPart().getEncoded();
- }
-
- private String parseFragment() {
- int fsi = findFragmentSeparator();
- return fsi == NOT_FOUND ? null : uriString.substring(fsi + 1);
- }
-
- public String getFragment() {
- return getFragmentPart().getDecoded();
- }
-
- public String toString() {
- return uriString;
- }
-
- /**
- * Parses an authority out of the given URI string.
- *
- * @param uriString URI string
- * @param ssi scheme separator index, -1 for a relative URI
- *
- * @return the authority or null if none is found
- */
- static String parseAuthority(String uriString, int ssi) {
- int length = uriString.length();
-
- // If "//" follows the scheme separator, we have an authority.
- if (length > ssi + 2
- && uriString.charAt(ssi + 1) == '/'
- && uriString.charAt(ssi + 2) == '/') {
- // We have an authority.
-
- // Look for the start of the path, query, or fragment, or the
- // end of the string.
- int end = ssi + 3;
- LOOP: while (end < length) {
- switch (uriString.charAt(end)) {
- case '/': // Start of path
- case '?': // Start of query
- case '#': // Start of fragment
- break LOOP;
- }
- end++;
- }
-
- return uriString.substring(ssi + 3, end);
- } else {
- return null;
- }
-
- }
-
- /**
- * Parses a path out of this given URI string.
- *
- * @param uriString URI string
- * @param ssi scheme separator index, -1 for a relative URI
- *
- * @return the path
- */
- static String parsePath(String uriString, int ssi) {
- int length = uriString.length();
-
- // Find start of path.
- int pathStart;
- if (length > ssi + 2
- && uriString.charAt(ssi + 1) == '/'
- && uriString.charAt(ssi + 2) == '/') {
- // Skip over authority to path.
- pathStart = ssi + 3;
- LOOP: while (pathStart < length) {
- switch (uriString.charAt(pathStart)) {
- case '?': // Start of query
- case '#': // Start of fragment
- return ""; // Empty path.
- case '/': // Start of path!
- break LOOP;
- }
- pathStart++;
- }
- } else {
- // Path starts immediately after scheme separator.
- pathStart = ssi + 1;
- }
-
- // Find end of path.
- int pathEnd = pathStart;
- LOOP: while (pathEnd < length) {
- switch (uriString.charAt(pathEnd)) {
- case '?': // Start of query
- case '#': // Start of fragment
- break LOOP;
- }
- pathEnd++;
- }
-
- return uriString.substring(pathStart, pathEnd);
- }
-
- public Builder buildUpon() {
- if (isHierarchical()) {
- return new Builder()
- .scheme(getScheme())
- .authority(getAuthorityPart())
- .path(getPathPart())
- .query(getQueryPart())
- .fragment(getFragmentPart());
- } else {
- return new Builder()
- .scheme(getScheme())
- .opaquePart(getSsp())
- .fragment(getFragmentPart());
- }
- }
- }
-
- /**
- * Creates an opaque Uri from the given components. Encodes the ssp
- * which means this method cannot be used to create hierarchical URIs.
- *
- * @param scheme of the URI
- * @param ssp scheme-specific-part, everything between the
- * scheme separator (':') and the fragment separator ('#'), which will
- * get encoded
- * @param fragment fragment, everything after the '#', null if undefined,
- * will get encoded
- *
- * @throws NullPointerException if scheme or ssp is null
- * @return Uri composed of the given scheme, ssp, and fragment
- *
- * @see Builder if you don't want the ssp and fragment to be encoded
- */
- public static Uri__FromAndroid fromParts(String scheme, String ssp,
- String fragment) {
- if (scheme == null) {
- throw new NullPointerException("scheme");
- }
- if (ssp == null) {
- throw new NullPointerException("ssp");
- }
-
- return new OpaqueUri(scheme, Part.fromDecoded(ssp),
- Part.fromDecoded(fragment));
- }
-
- /**
- * Opaque URI.
- */
- private static class OpaqueUri extends Uri__FromAndroid {
-
- /** Used in parcelling. */
- static final int TYPE_ID = 2;
-
- private final String scheme;
- private final Part ssp;
- private final Part fragment;
-
- private OpaqueUri(String scheme, Part ssp, Part fragment) {
- this.scheme = scheme;
- this.ssp = ssp;
- this.fragment = fragment == null ? Part.NULL : fragment;
- }
-
- static Uri__FromAndroid readFrom(Parcel parcel) {
- return new OpaqueUri(
- parcel.readString(),
- Part.readFrom(parcel),
- Part.readFrom(parcel)
- );
- }
-
- public int describeContents() {
- return 0;
- }
-
- public void writeToParcel(Parcel parcel, int flags) {
- parcel.writeInt(TYPE_ID);
- parcel.writeString(scheme);
- ssp.writeTo(parcel);
- fragment.writeTo(parcel);
- }
-
- public boolean isHierarchical() {
- return false;
- }
-
- public boolean isRelative() {
- return scheme == null;
- }
-
- public String getScheme() {
- return this.scheme;
- }
-
- public String getEncodedSchemeSpecificPart() {
- return ssp.getEncoded();
- }
-
- public String getSchemeSpecificPart() {
- return ssp.getDecoded();
- }
-
- public String getAuthority() {
- return null;
- }
-
- public String getEncodedAuthority() {
- return null;
- }
-
- public String getPath() {
- return null;
- }
-
- public String getEncodedPath() {
- return null;
- }
-
- public String getQuery() {
- return null;
- }
-
- public String getEncodedQuery() {
- return null;
- }
-
- public String getFragment() {
- return fragment.getDecoded();
- }
-
- public String getEncodedFragment() {
- return fragment.getEncoded();
- }
-
- public List<String> getPathSegments() {
- return Collections.emptyList();
- }
-
- public String getLastPathSegment() {
- return null;
- }
-
- public String getUserInfo() {
- return null;
- }
-
- public String getEncodedUserInfo() {
- return null;
- }
-
- public String getHost() {
- return null;
- }
-
- public int getPort() {
- return -1;
- }
-
- private volatile String cachedString = NOT_CACHED;
-
- public String toString() {
- @SuppressWarnings("StringEquality")
- boolean cached = cachedString != NOT_CACHED;
- if (cached) {
- return cachedString;
- }
-
- StringBuilder sb = new StringBuilder();
-
- sb.append(scheme).append(':');
- sb.append(getEncodedSchemeSpecificPart());
-
- if (!fragment.isEmpty()) {
- sb.append('#').append(fragment.getEncoded());
- }
-
- return cachedString = sb.toString();
- }
-
- public Builder buildUpon() {
- return new Builder()
- .scheme(this.scheme)
- .opaquePart(this.ssp)
- .fragment(this.fragment);
- }
- }
-
- /**
- * Wrapper for path segment array.
- */
- static class PathSegments extends AbstractList<String>
- implements RandomAccess {
-
- static final PathSegments EMPTY = new PathSegments(null, 0);
-
- final String[] segments;
- final int size;
-
- PathSegments(String[] segments, int size) {
- this.segments = segments;
- this.size = size;
- }
-
- public String get(int index) {
- if (index >= size) {
- throw new IndexOutOfBoundsException();
- }
-
- return segments[index];
- }
-
- public int size() {
- return this.size;
- }
- }
-
- /**
- * Builds PathSegments.
- */
- static class PathSegmentsBuilder {
-
- String[] segments;
- int size = 0;
-
- void add(String segment) {
- if (segments == null) {
- segments = new String[4];
- } else if (size + 1 == segments.length) {
- String[] expanded = new String[segments.length * 2];
- System.arraycopy(segments, 0, expanded, 0, segments.length);
- segments = expanded;
- }
-
- segments[size++] = segment;
- }
-
- PathSegments build() {
- if (segments == null) {
- return PathSegments.EMPTY;
- }
-
- try {
- return new PathSegments(segments, size);
- } finally {
- // Makes sure this doesn't get reused.
- segments = null;
- }
- }
- }
-
- /**
- * Support for hierarchical URIs.
- */
- private abstract static class AbstractHierarchicalUri extends Uri__FromAndroid {
-
- public String getLastPathSegment() {
- // TODO: If we haven't parsed all of the segments already, just
- // grab the last one directly so we only allocate one string.
-
- List<String> segments = getPathSegments();
- int size = segments.size();
- if (size == 0) {
- return null;
- }
- return segments.get(size - 1);
- }
-
- private Part userInfo;
-
- private Part getUserInfoPart() {
- return userInfo == null
- ? userInfo = Part.fromEncoded(parseUserInfo()) : userInfo;
- }
-
- public final String getEncodedUserInfo() {
- return getUserInfoPart().getEncoded();
- }
-
- private String parseUserInfo() {
- String authority = getEncodedAuthority();
- if (authority == null) {
- return null;
- }
-
- int end = authority.indexOf('@');
- return end == NOT_FOUND ? null : authority.substring(0, end);
- }
-
- public String getUserInfo() {
- return getUserInfoPart().getDecoded();
- }
-
- private volatile String host = NOT_CACHED;
-
- public String getHost() {
- @SuppressWarnings("StringEquality")
- boolean cached = (host != NOT_CACHED);
- return cached ? host
- : (host = parseHost());
- }
-
- private String parseHost() {
- String authority = getEncodedAuthority();
- if (authority == null) {
- return null;
- }
-
- // Parse out user info and then port.
- int userInfoSeparator = authority.indexOf('@');
- int portSeparator = authority.indexOf(':', userInfoSeparator);
-
- String encodedHost = portSeparator == NOT_FOUND
- ? authority.substring(userInfoSeparator + 1)
- : authority.substring(userInfoSeparator + 1, portSeparator);
-
- return decode(encodedHost);
- }
-
- private volatile int port = NOT_CALCULATED;
-
- public int getPort() {
- return port == NOT_CALCULATED
- ? port = parsePort()
- : port;
- }
-
- private int parsePort() {
- String authority = getEncodedAuthority();
- if (authority == null) {
- return -1;
- }
-
- // Make sure we look for the port separtor *after* the user info
- // separator. We have URLs with a ':' in the user info.
- int userInfoSeparator = authority.indexOf('@');
- int portSeparator = authority.indexOf(':', userInfoSeparator);
-
- if (portSeparator == NOT_FOUND) {
- return -1;
- }
-
- String portString = decode(authority.substring(portSeparator + 1));
- try {
- return Integer.parseInt(portString);
- } catch (NumberFormatException e) {
- Log.w(LOG, "Error parsing port string.", e);
- return -1;
- }
- }
- }
-
- /**
- * Hierarchical Uri.
- */
- private static class HierarchicalUri extends AbstractHierarchicalUri {
-
- /** Used in parcelling. */
- static final int TYPE_ID = 3;
-
- private final String scheme; // can be null
- private final Part authority;
- private final PathPart path;
- private final Part query;
- private final Part fragment;
-
- private HierarchicalUri(String scheme, Part authority, PathPart path,
- Part query, Part fragment) {
- this.scheme = scheme;
- this.authority = Part.nonNull(authority);
- this.path = path == null ? PathPart.NULL : path;
- this.query = Part.nonNull(query);
- this.fragment = Part.nonNull(fragment);
- }
-
- static Uri__FromAndroid readFrom(Parcel parcel) {
- return new HierarchicalUri(
- parcel.readString(),
- Part.readFrom(parcel),
- PathPart.readFrom(parcel),
- Part.readFrom(parcel),
- Part.readFrom(parcel)
- );
- }
-
- public int describeContents() {
- return 0;
- }
-
- public void writeToParcel(Parcel parcel, int flags) {
- parcel.writeInt(TYPE_ID);
- parcel.writeString(scheme);
- authority.writeTo(parcel);
- path.writeTo(parcel);
- query.writeTo(parcel);
- fragment.writeTo(parcel);
- }
-
- public boolean isHierarchical() {
- return true;
- }
-
- public boolean isRelative() {
- return scheme == null;
- }
-
- public String getScheme() {
- return scheme;
- }
-
- private Part ssp;
-
- private Part getSsp() {
- return ssp == null
- ? ssp = Part.fromEncoded(makeSchemeSpecificPart()) : ssp;
- }
-
- public String getEncodedSchemeSpecificPart() {
- return getSsp().getEncoded();
- }
-
- public String getSchemeSpecificPart() {
- return getSsp().getDecoded();
- }
-
- /**
- * Creates the encoded scheme-specific part from its sub parts.
- */
- private String makeSchemeSpecificPart() {
- StringBuilder builder = new StringBuilder();
- appendSspTo(builder);
- return builder.toString();
- }
-
- private void appendSspTo(StringBuilder builder) {
- String encodedAuthority = authority.getEncoded();
- if (encodedAuthority != null) {
- // Even if the authority is "", we still want to append "//".
- builder.append("//").append(encodedAuthority);
- }
-
- String encodedPath = path.getEncoded();
- if (encodedPath != null) {
- builder.append(encodedPath);
- }
-
- if (!query.isEmpty()) {
- builder.append('?').append(query.getEncoded());
- }
- }
-
- public String getAuthority() {
- return this.authority.getDecoded();
- }
-
- public String getEncodedAuthority() {
- return this.authority.getEncoded();
- }
-
- public String getEncodedPath() {
- return this.path.getEncoded();
- }
-
- public String getPath() {
- return this.path.getDecoded();
- }
-
- public String getQuery() {
- return this.query.getDecoded();
- }
-
- public String getEncodedQuery() {
- return this.query.getEncoded();
- }
-
- public String getFragment() {
- return this.fragment.getDecoded();
- }
-
- public String getEncodedFragment() {
- return this.fragment.getEncoded();
- }
-
- public List<String> getPathSegments() {
- return this.path.getPathSegments();
- }
-
- private volatile String uriString = NOT_CACHED;
-
- @Override
- public String toString() {
- @SuppressWarnings("StringEquality")
- boolean cached = (uriString != NOT_CACHED);
- return cached ? uriString
- : (uriString = makeUriString());
- }
-
- private String makeUriString() {
- StringBuilder builder = new StringBuilder();
-
- if (scheme != null) {
- builder.append(scheme).append(':');
- }
-
- appendSspTo(builder);
-
- if (!fragment.isEmpty()) {
- builder.append('#').append(fragment.getEncoded());
- }
-
- return builder.toString();
- }
-
- public Builder buildUpon() {
- return new Builder()
- .scheme(scheme)
- .authority(authority)
- .path(path)
- .query(query)
- .fragment(fragment);
- }
- }
-
- /**
- * Helper class for building or manipulating URI references. Not safe for
- * concurrent use.
- *
- * <p>An absolute hierarchical URI reference follows the pattern:
- * {@code &lt;scheme&gt;://&lt;authority&gt;&lt;absolute path&gt;?&lt;query&gt;#&lt;fragment&gt;}
- *
- * <p>Relative URI references (which are always hierarchical) follow one
- * of two patterns: {@code &lt;relative or absolute path&gt;?&lt;query&gt;#&lt;fragment&gt;}
- * or {@code //&lt;authority&gt;&lt;absolute path&gt;?&lt;query&gt;#&lt;fragment&gt;}
- *
- * <p>An opaque URI follows this pattern:
- * {@code &lt;scheme&gt;:&lt;opaque part&gt;#&lt;fragment&gt;}
- */
- public static final class Builder {
-
- private String scheme;
- private Part opaquePart;
- private Part authority;
- private PathPart path;
- private Part query;
- private Part fragment;
-
- /**
- * Constructs a new Builder.
- */
- public Builder() {}
-
- /**
- * Sets the scheme.
- *
- * @param scheme name or {@code null} if this is a relative Uri
- */
- public Builder scheme(String scheme) {
- this.scheme = scheme;
- return this;
- }
-
- Builder opaquePart(Part opaquePart) {
- this.opaquePart = opaquePart;
- return this;
- }
-
- /**
- * Encodes and sets the given opaque scheme-specific-part.
- *
- * @param opaquePart decoded opaque part
- */
- public Builder opaquePart(String opaquePart) {
- return opaquePart(Part.fromDecoded(opaquePart));
- }
-
- /**
- * Sets the previously encoded opaque scheme-specific-part.
- *
- * @param opaquePart encoded opaque part
- */
- public Builder encodedOpaquePart(String opaquePart) {
- return opaquePart(Part.fromEncoded(opaquePart));
- }
-
- Builder authority(Part authority) {
- // This URI will be hierarchical.
- this.opaquePart = null;
-
- this.authority = authority;
- return this;
- }
-
- /**
- * Encodes and sets the authority.
- */
- public Builder authority(String authority) {
- return authority(Part.fromDecoded(authority));
- }
-
- /**
- * Sets the previously encoded authority.
- */
- public Builder encodedAuthority(String authority) {
- return authority(Part.fromEncoded(authority));
- }
-
- Builder path(PathPart path) {
- // This URI will be hierarchical.
- this.opaquePart = null;
-
- this.path = path;
- return this;
- }
-
- /**
- * Sets the path. Leaves '/' characters intact but encodes others as
- * necessary.
- *
- * <p>If the path is not null and doesn't start with a '/', and if
- * you specify a scheme and/or authority, the builder will prepend the
- * given path with a '/'.
- */
- public Builder path(String path) {
- return path(PathPart.fromDecoded(path));
- }
-
- /**
- * Sets the previously encoded path.
- *
- * <p>If the path is not null and doesn't start with a '/', and if
- * you specify a scheme and/or authority, the builder will prepend the
- * given path with a '/'.
- */
- public Builder encodedPath(String path) {
- return path(PathPart.fromEncoded(path));
- }
-
- /**
- * Encodes the given segment and appends it to the path.
- */
- public Builder appendPath(String newSegment) {
- return path(PathPart.appendDecodedSegment(path, newSegment));
- }
-
- /**
- * Appends the given segment to the path.
- */
- public Builder appendEncodedPath(String newSegment) {
- return path(PathPart.appendEncodedSegment(path, newSegment));
- }
-
- Builder query(Part query) {
- // This URI will be hierarchical.
- this.opaquePart = null;
-
- this.query = query;
- return this;
- }
-
- /**
- * Encodes and sets the query.
- */
- public Builder query(String query) {
- return query(Part.fromDecoded(query));
- }
-
- /**
- * Sets the previously encoded query.
- */
- public Builder encodedQuery(String query) {
- return query(Part.fromEncoded(query));
- }
-
- Builder fragment(Part fragment) {
- this.fragment = fragment;
- return this;
- }
-
- /**
- * Encodes and sets the fragment.
- */
- public Builder fragment(String fragment) {
- return fragment(Part.fromDecoded(fragment));
- }
-
- /**
- * Sets the previously encoded fragment.
- */
- public Builder encodedFragment(String fragment) {
- return fragment(Part.fromEncoded(fragment));
- }
-
- /**
- * Encodes the key and value and then appends the parameter to the
- * query string.
- *
- * @param key which will be encoded
- * @param value which will be encoded
- */
- public Builder appendQueryParameter(String key, String value) {
- // This URI will be hierarchical.
- this.opaquePart = null;
-
- String encodedParameter = encode(key, null) + "="
- + encode(value, null);
-
- if (query == null) {
- query = Part.fromEncoded(encodedParameter);
- return this;
- }
-
- String oldQuery = query.getEncoded();
- if (oldQuery == null || oldQuery.length() == 0) {
- query = Part.fromEncoded(encodedParameter);
- } else {
- query = Part.fromEncoded(oldQuery + "&" + encodedParameter);
- }
-
- return this;
- }
-
- /**
- * Constructs a Uri with the current attributes.
- *
- * @throws UnsupportedOperationException if the URI is opaque and the
- * scheme is null
- */
- public Uri__FromAndroid build() {
- if (opaquePart != null) {
- if (this.scheme == null) {
- throw new UnsupportedOperationException(
- "An opaque URI must have a scheme.");
- }
-
- return new OpaqueUri(scheme, opaquePart, fragment);
- } else {
- // Hierarchical URIs should not return null for getPath().
- PathPart path = this.path;
- if (path == null || path == PathPart.NULL) {
- path = PathPart.EMPTY;
- } else {
- // If we have a scheme and/or authority, the path must
- // be absolute. Prepend it with a '/' if necessary.
- if (hasSchemeOrAuthority()) {
- path = PathPart.makeAbsolute(path);
- }
- }
-
- return new HierarchicalUri(
- scheme, authority, path, query, fragment);
- }
- }
-
- private boolean hasSchemeOrAuthority() {
- return scheme != null
- || (authority != null && authority != Part.NULL);
-
- }
-
- @Override
- public String toString() {
- return build().toString();
- }
- }
-
- /**
- * Searches the query string for parameter values with the given key.
- *
- * @param key which will be encoded
- *
- * @throws UnsupportedOperationException if this isn't a hierarchical URI
- * @throws NullPointerException if key is null
- *
- * @return a list of decoded values
- */
- public List<String> getQueryParameters(String key) {
- if (isOpaque()) {
- throw new UnsupportedOperationException(NOT_HIERARCHICAL);
- }
-
- String query = getEncodedQuery();
- if (query == null) {
- return Collections.emptyList();
- }
-
- String encodedKey;
- try {
- encodedKey = URLEncoder.encode(key, DEFAULT_ENCODING);
- } catch (UnsupportedEncodingException e) {
- throw new AssertionError(e);
- }
-
- // Prepend query with "&" making the first parameter the same as the
- // rest.
- query = "&" + query;
-
- // Parameter prefix.
- String prefix = "&" + encodedKey + "=";
-
- ArrayList<String> values = new ArrayList<String>();
-
- int start = 0;
- int length = query.length();
- while (start < length) {
- start = query.indexOf(prefix, start);
-
- if (start == -1) {
- // No more values.
- break;
- }
-
- // Move start to start of value.
- start += prefix.length();
-
- // Find end of value.
- int end = query.indexOf('&', start);
- if (end == -1) {
- end = query.length();
- }
-
- String value = query.substring(start, end);
- values.add(decode(value));
-
- start = end;
- }
-
- return Collections.unmodifiableList(values);
- }
-
- /**
- * Searches the query string for the first value with the given key.
- *
- * @param key which will be encoded
- * @throws UnsupportedOperationException if this isn't a hierarchical URI
- * @throws NullPointerException if key is null
- *
- * @return the decoded value or null if no parameter is found
- */
- public String getQueryParameter(String key) {
- if (isOpaque()) {
- throw new UnsupportedOperationException(NOT_HIERARCHICAL);
- }
-
- String query = getEncodedQuery();
-
- if (query == null) {
- return null;
- }
-
- String encodedKey;
- try {
- encodedKey = URLEncoder.encode(key, DEFAULT_ENCODING);
- } catch (UnsupportedEncodingException e) {
- throw new AssertionError(e);
- }
-
- String prefix = encodedKey + "=";
-
- if (query.length() < prefix.length()) {
- return null;
- }
-
- int start;
- if (query.startsWith(prefix)) {
- // It's the first parameter.
- start = prefix.length();
- } else {
- // It must be later in the query string.
- prefix = "&" + prefix;
- start = query.indexOf(prefix);
-
- if (start == -1) {
- // Not found.
- return null;
- }
-
- start += prefix.length();
- }
-
- // Find end of value.
- int end = query.indexOf('&', start);
- if (end == -1) {
- end = query.length();
- }
-
- String value = query.substring(start, end);
- return decode(value);
- }
-
- /** Identifies a null parcelled Uri. */
- private static final int NULL_TYPE_ID = 0;
-
- /**
- * Reads Uris from Parcels.
- */
- public static final Parcelable.Creator<Uri__FromAndroid> CREATOR
- = new Parcelable.Creator<Uri__FromAndroid>() {
- public Uri__FromAndroid createFromParcel(Parcel in) {
- int type = in.readInt();
- switch (type) {
- case NULL_TYPE_ID: return null;
- case StringUri.TYPE_ID: return StringUri.readFrom(in);
- case OpaqueUri.TYPE_ID: return OpaqueUri.readFrom(in);
- case HierarchicalUri.TYPE_ID:
- return HierarchicalUri.readFrom(in);
- }
-
- throw new AssertionError("Unknown URI type: " + type);
- }
-
- public Uri__FromAndroid[] newArray(int size) {
- return new Uri__FromAndroid[size];
- }
- };
-
- /**
- * Writes a Uri to a Parcel.
- *
- * @param out parcel to write to
- * @param uri to write, can be null
- */
- public static void writeToParcel(Parcel out, Uri__FromAndroid uri) {
- if (uri == null) {
- out.writeInt(NULL_TYPE_ID);
- } else {
- uri.writeToParcel(out, 0);
- }
- }
-
- private static final char[] HEX_DIGITS = "0123456789ABCDEF".toCharArray();
-
- /**
- * Encodes characters in the given string as '%'-escaped octets
- * using the UTF-8 scheme. Leaves letters ("A-Z", "a-z"), numbers
- * ("0-9"), and unreserved characters ("_-!.~'()*") intact. Encodes
- * all other characters.
- *
- * @param s string to encode
- * @return an encoded version of s suitable for use as a URI component,
- * or null if s is null
- */
- public static String encode(String s) {
- return encode(s, null);
- }
-
- /**
- * Encodes characters in the given string as '%'-escaped octets
- * using the UTF-8 scheme. Leaves letters ("A-Z", "a-z"), numbers
- * ("0-9"), and unreserved characters ("_-!.~'()*") intact. Encodes
- * all other characters with the exception of those specified in the
- * allow argument.
- *
- * @param s string to encode
- * @param allow set of additional characters to allow in the encoded form,
- * null if no characters should be skipped
- * @return an encoded version of s suitable for use as a URI component,
- * or null if s is null
- */
- public static String encode(String s, String allow) {
- if (s == null) {
- return null;
- }
-
- // Lazily-initialized buffers.
- StringBuilder encoded = null;
-
- int oldLength = s.length();
-
- // This loop alternates between copying over allowed characters and
- // encoding in chunks. This results in fewer method calls and
- // allocations than encoding one character at a time.
- int current = 0;
- while (current < oldLength) {
- // Start in "copying" mode where we copy over allowed chars.
-
- // Find the next character which needs to be encoded.
- int nextToEncode = current;
- while (nextToEncode < oldLength
- && isAllowed(s.charAt(nextToEncode), allow)) {
- nextToEncode++;
- }
-
- // If there's nothing more to encode...
- if (nextToEncode == oldLength) {
- if (current == 0) {
- // We didn't need to encode anything!
- return s;
- } else {
- // Presumably, we've already done some encoding.
- encoded.append(s, current, oldLength);
- return encoded.toString();
- }
- }
-
- if (encoded == null) {
- encoded = new StringBuilder();
- }
-
- if (nextToEncode > current) {
- // Append allowed characters leading up to this point.
- encoded.append(s, current, nextToEncode);
- } else {
- // assert nextToEncode == current
- }
-
- // Switch to "encoding" mode.
-
- // Find the next allowed character.
- current = nextToEncode;
- int nextAllowed = current + 1;
- while (nextAllowed < oldLength
- && !isAllowed(s.charAt(nextAllowed), allow)) {
- nextAllowed++;
- }
-
- // Convert the substring to bytes and encode the bytes as
- // '%'-escaped octets.
- String toEncode = s.substring(current, nextAllowed);
- try {
- byte[] bytes = toEncode.getBytes(DEFAULT_ENCODING);
- int bytesLength = bytes.length;
- for (int i = 0; i < bytesLength; i++) {
- encoded.append('%');
- encoded.append(HEX_DIGITS[(bytes[i] & 0xf0) >> 4]);
- encoded.append(HEX_DIGITS[bytes[i] & 0xf]);
- }
- } catch (UnsupportedEncodingException e) {
- throw new AssertionError(e);
- }
-
- current = nextAllowed;
- }
-
- // Encoded could still be null at this point if s is empty.
- return encoded == null ? s : encoded.toString();
- }
-
- /**
- * Returns true if the given character is allowed.
- *
- * @param c character to check
- * @param allow characters to allow
- * @return true if the character is allowed or false if it should be
- * encoded
- */
- private static boolean isAllowed(char c, String allow) {
- return (c >= 'A' && c <= 'Z')
- || (c >= 'a' && c <= 'z')
- || (c >= '0' && c <= '9')
- || "_-!.~'()*".indexOf(c) != NOT_FOUND
- || (allow != null && allow.indexOf(c) != NOT_FOUND);
- }
-
- /** Unicode replacement character: \\uFFFD. */
- private static final byte[] REPLACEMENT = { (byte) 0xFF, (byte) 0xFD };
-
- /**
- * Decodes '%'-escaped octets in the given string using the UTF-8 scheme.
- * Replaces invalid octets with the unicode replacement character
- * ("\\uFFFD").
- *
- * @param s encoded string to decode
- * @return the given string with escaped octets decoded, or null if
- * s is null
- */
- public static String decode(String s) {
- /*
- Compared to java.net.URLEncoderDecoder.decode(), this method decodes a
- chunk at a time instead of one character at a time, and it doesn't
- throw exceptions. It also only allocates memory when necessary--if
- there's nothing to decode, this method won't do much.
- */
-
- if (s == null) {
- return null;
- }
-
- // Lazily-initialized buffers.
- StringBuilder decoded = null;
- ByteArrayOutputStream out = null;
-
- int oldLength = s.length();
-
- // This loop alternates between copying over normal characters and
- // escaping in chunks. This results in fewer method calls and
- // allocations than decoding one character at a time.
- int current = 0;
- while (current < oldLength) {
- // Start in "copying" mode where we copy over normal characters.
-
- // Find the next escape sequence.
- int nextEscape = s.indexOf('%', current);
-
- if (nextEscape == NOT_FOUND) {
- if (decoded == null) {
- // We didn't actually decode anything.
- return s;
- } else {
- // Append the remainder and return the decoded string.
- decoded.append(s, current, oldLength);
- return decoded.toString();
- }
- }
-
- // Prepare buffers.
- if (decoded == null) {
- // Looks like we're going to need the buffers...
- // We know the new string will be shorter. Using the old length
- // may overshoot a bit, but it will save us from resizing the
- // buffer.
- decoded = new StringBuilder(oldLength);
- out = new ByteArrayOutputStream(4);
- } else {
- // Clear decoding buffer.
- out.reset();
- }
-
- // Append characters leading up to the escape.
- if (nextEscape > current) {
- decoded.append(s, current, nextEscape);
-
- current = nextEscape;
- } else {
- // assert current == nextEscape
- }
-
- // Switch to "decoding" mode where we decode a string of escape
- // sequences.
-
- // Decode and append escape sequences. Escape sequences look like
- // "%ab" where % is literal and a and b are hex digits.
- try {
- do {
- if (current + 2 >= oldLength) {
- // Truncated escape sequence.
- out.write(REPLACEMENT);
- } else {
- int a = Character.digit(s.charAt(current + 1), 16);
- int b = Character.digit(s.charAt(current + 2), 16);
-
- if (a == -1 || b == -1) {
- // Non hex digits.
- out.write(REPLACEMENT);
- } else {
- // Combine the hex digits into one byte and write.
- out.write((a << 4) + b);
- }
- }
-
- // Move passed the escape sequence.
- current += 3;
- } while (current < oldLength && s.charAt(current) == '%');
-
- // Decode UTF-8 bytes into a string and append it.
- decoded.append(out.toString(DEFAULT_ENCODING));
- } catch (UnsupportedEncodingException e) {
- throw new AssertionError(e);
- } catch (IOException e) {
- throw new AssertionError(e);
- }
- }
-
- // If we don't have a buffer, we didn't have to decode anything.
- return decoded == null ? s : decoded.toString();
- }
-
- /**
- * Support for part implementations.
- */
- static abstract class AbstractPart {
-
- /**
- * Enum which indicates which representation of a given part we have.
- */
- static class Representation {
- static final int BOTH = 0;
- static final int ENCODED = 1;
- static final int DECODED = 2;
- }
-
- volatile String encoded;
- volatile String decoded;
-
- AbstractPart(String encoded, String decoded) {
- this.encoded = encoded;
- this.decoded = decoded;
- }
-
- abstract String getEncoded();
-
- final String getDecoded() {
- @SuppressWarnings("StringEquality")
- boolean hasDecoded = decoded != NOT_CACHED;
- return hasDecoded ? decoded : (decoded = decode(encoded));
- }
-
- final void writeTo(Parcel parcel) {
- @SuppressWarnings("StringEquality")
- boolean hasEncoded = encoded != NOT_CACHED;
-
- @SuppressWarnings("StringEquality")
- boolean hasDecoded = decoded != NOT_CACHED;
-
- if (hasEncoded && hasDecoded) {
- parcel.writeInt(Representation.BOTH);
- parcel.writeString(encoded);
- parcel.writeString(decoded);
- } else if (hasEncoded) {
- parcel.writeInt(Representation.ENCODED);
- parcel.writeString(encoded);
- } else if (hasDecoded) {
- parcel.writeInt(Representation.DECODED);
- parcel.writeString(decoded);
- } else {
- throw new AssertionError();
- }
- }
- }
-
- /**
- * Immutable wrapper of encoded and decoded versions of a URI part. Lazily
- * creates the encoded or decoded version from the other.
- */
- static class Part extends AbstractPart {
-
- /** A part with null values. */
- static final Part NULL = new EmptyPart(null);
-
- /** A part with empty strings for values. */
- static final Part EMPTY = new EmptyPart("");
-
- private Part(String encoded, String decoded) {
- super(encoded, decoded);
- }
-
- boolean isEmpty() {
- return false;
- }
-
- String getEncoded() {
- @SuppressWarnings("StringEquality")
- boolean hasEncoded = encoded != NOT_CACHED;
- return hasEncoded ? encoded : (encoded = encode(decoded));
- }
-
- static Part readFrom(Parcel parcel) {
- int representation = parcel.readInt();
- switch (representation) {
- case Representation.BOTH:
- return from(parcel.readString(), parcel.readString());
- case Representation.ENCODED:
- return fromEncoded(parcel.readString());
- case Representation.DECODED:
- return fromDecoded(parcel.readString());
- default:
- throw new AssertionError();
- }
- }
-
- /**
- * Returns given part or {@link #NULL} if the given part is null.
- */
- static Part nonNull(Part part) {
- return part == null ? NULL : part;
- }
-
- /**
- * Creates a part from the encoded string.
- *
- * @param encoded part string
- */
- static Part fromEncoded(String encoded) {
- return from(encoded, NOT_CACHED);
- }
-
- /**
- * Creates a part from the decoded string.
- *
- * @param decoded part string
- */
- static Part fromDecoded(String decoded) {
- return from(NOT_CACHED, decoded);
- }
-
- /**
- * Creates a part from the encoded and decoded strings.
- *
- * @param encoded part string
- * @param decoded part string
- */
- static Part from(String encoded, String decoded) {
- // We have to check both encoded and decoded in case one is
- // NOT_CACHED.
-
- if (encoded == null) {
- return NULL;
- }
- if (encoded.length() == 0) {
- return EMPTY;
- }
-
- if (decoded == null) {
- return NULL;
- }
- if (decoded .length() == 0) {
- return EMPTY;
- }
-
- return new Part(encoded, decoded);
- }
-
- private static class EmptyPart extends Part {
- public EmptyPart(String value) {
- super(value, value);
- }
-
- @Override
- boolean isEmpty() {
- return true;
- }
- }
- }
-
- /**
- * Immutable wrapper of encoded and decoded versions of a path part. Lazily
- * creates the encoded or decoded version from the other.
- */
- static class PathPart extends AbstractPart {
-
- /** A part with null values. */
- static final PathPart NULL = new PathPart(null, null);
-
- /** A part with empty strings for values. */
- static final PathPart EMPTY = new PathPart("", "");
-
- private PathPart(String encoded, String decoded) {
- super(encoded, decoded);
- }
-
- String getEncoded() {
- @SuppressWarnings("StringEquality")
- boolean hasEncoded = encoded != NOT_CACHED;
-
- // Don't encode '/'.
- return hasEncoded ? encoded : (encoded = encode(decoded, "/"));
- }
-
- /**
- * Cached path segments. This doesn't need to be volatile--we don't
- * care if other threads see the result.
- */
- private PathSegments pathSegments;
-
- /**
- * Gets the individual path segments. Parses them if necessary.
- *
- * @return parsed path segments or null if this isn't a hierarchical
- * URI
- */
- PathSegments getPathSegments() {
- if (pathSegments != null) {
- return pathSegments;
- }
-
- String path = getEncoded();
- if (path == null) {
- return pathSegments = PathSegments.EMPTY;
- }
-
- PathSegmentsBuilder segmentBuilder = new PathSegmentsBuilder();
-
- int previous = 0;
- int current;
- while ((current = path.indexOf('/', previous)) > -1) {
- // This check keeps us from adding a segment if the path starts
- // '/' and an empty segment for "//".
- if (previous < current) {
- String decodedSegment
- = decode(path.substring(previous, current));
- segmentBuilder.add(decodedSegment);
- }
- previous = current + 1;
- }
-
- // Add in the final path segment.
- if (previous < path.length()) {
- segmentBuilder.add(decode(path.substring(previous)));
- }
-
- return pathSegments = segmentBuilder.build();
- }
-
- static PathPart appendEncodedSegment(PathPart oldPart,
- String newSegment) {
- // If there is no old path, should we make the new path relative
- // or absolute? I pick absolute.
-
- if (oldPart == null) {
- // No old path.
- return fromEncoded("/" + newSegment);
- }
-
- String oldPath = oldPart.getEncoded();
-
- if (oldPath == null) {
- oldPath = "";
- }
-
- int oldPathLength = oldPath.length();
- String newPath;
- if (oldPathLength == 0) {
- // No old path.
- newPath = "/" + newSegment;
- } else if (oldPath.charAt(oldPathLength - 1) == '/') {
- newPath = oldPath + newSegment;
- } else {
- newPath = oldPath + "/" + newSegment;
- }
-
- return fromEncoded(newPath);
- }
-
- static PathPart appendDecodedSegment(PathPart oldPart, String decoded) {
- String encoded = encode(decoded);
-
- // TODO: Should we reuse old PathSegments? Probably not.
- return appendEncodedSegment(oldPart, encoded);
- }
-
- static PathPart readFrom(Parcel parcel) {
- int representation = parcel.readInt();
- switch (representation) {
- case Representation.BOTH:
- return from(parcel.readString(), parcel.readString());
- case Representation.ENCODED:
- return fromEncoded(parcel.readString());
- case Representation.DECODED:
- return fromDecoded(parcel.readString());
- default:
- throw new AssertionError();
- }
- }
-
- /**
- * Creates a path from the encoded string.
- *
- * @param encoded part string
- */
- static PathPart fromEncoded(String encoded) {
- return from(encoded, NOT_CACHED);
- }
-
- /**
- * Creates a path from the decoded string.
- *
- * @param decoded part string
- */
- static PathPart fromDecoded(String decoded) {
- return from(NOT_CACHED, decoded);
- }
-
- /**
- * Creates a path from the encoded and decoded strings.
- *
- * @param encoded part string
- * @param decoded part string
- */
- static PathPart from(String encoded, String decoded) {
- if (encoded == null) {
- return NULL;
- }
-
- if (encoded.length() == 0) {
- return EMPTY;
- }
-
- return new PathPart(encoded, decoded);
- }
-
- /**
- * Prepends path values with "/" if they're present, not empty, and
- * they don't already start with "/".
- */
- static PathPart makeAbsolute(PathPart oldPart) {
- @SuppressWarnings("StringEquality")
- boolean encodedCached = oldPart.encoded != NOT_CACHED;
-
- // We don't care which version we use, and we don't want to force
- // unneccessary encoding/decoding.
- String oldPath = encodedCached ? oldPart.encoded : oldPart.decoded;
-
- if (oldPath == null || oldPath.length() == 0
- || oldPath.startsWith("/")) {
- return oldPart;
- }
-
- // Prepend encoded string if present.
- String newEncoded = encodedCached
- ? "/" + oldPart.encoded : NOT_CACHED;
-
- // Prepend decoded string if present.
- @SuppressWarnings("StringEquality")
- boolean decodedCached = oldPart.decoded != NOT_CACHED;
- String newDecoded = decodedCached
- ? "/" + oldPart.decoded
- : NOT_CACHED;
-
- return new PathPart(newEncoded, newDecoded);
- }
- }
-
- /**
- * Creates a new Uri by appending an already-encoded path segment to a
- * base Uri.
- *
- * @param baseUri Uri to append path segment to
- * @param pathSegment encoded path segment to append
- * @return a new Uri based on baseUri with the given segment appended to
- * the path
- * @throws NullPointerException if baseUri is null
- */
- public static Uri__FromAndroid withAppendedPath(Uri__FromAndroid baseUri, String pathSegment) {
- Builder builder = baseUri.buildUpon();
- builder = builder.appendEncodedPath(pathSegment);
- return builder.build();
- }
-}
diff --git a/v1/src/main/java/android/os/ShadowAsyncTaskBridge.java b/v1/src/main/java/android/os/ShadowAsyncTaskBridge.java
deleted file mode 100644
index 7b553d756..000000000
--- a/v1/src/main/java/android/os/ShadowAsyncTaskBridge.java
+++ /dev/null
@@ -1,32 +0,0 @@
-package android.os;
-
-import com.xtremelabs.robolectric.internal.DoNotInstrument;
-
-@DoNotInstrument
-public class ShadowAsyncTaskBridge<Params, Progress, Result> {
- private AsyncTask<Params, Progress, Result> asyncTask;
-
- public ShadowAsyncTaskBridge(AsyncTask<Params, Progress, Result> asyncTask) {
- this.asyncTask = asyncTask;
- }
-
- public Result doInBackground(Params... params) {
- return asyncTask.doInBackground(params);
- }
-
- public void onPreExecute() {
- asyncTask.onPreExecute();
- }
-
- public void onPostExecute(Result result) {
- asyncTask.onPostExecute(result);
- }
-
- public void onProgressUpdate(Progress... values) {
- asyncTask.onProgressUpdate(values);
- }
-
- public void onCancelled() {
- asyncTask.onCancelled();
- }
-}
diff --git a/v1/src/main/java/android/os/ShadowBinderBridge.java b/v1/src/main/java/android/os/ShadowBinderBridge.java
deleted file mode 100644
index 76ba97a90..000000000
--- a/v1/src/main/java/android/os/ShadowBinderBridge.java
+++ /dev/null
@@ -1,16 +0,0 @@
-package android.os;
-
-import com.xtremelabs.robolectric.internal.DoNotInstrument;
-
-@DoNotInstrument
-public class ShadowBinderBridge {
- private Binder realBinder;
-
- public ShadowBinderBridge(Binder realBinder) {
- this.realBinder = realBinder;
- }
-
- public boolean onTransact(int code, Parcel data, Parcel reply, int flags) throws RemoteException {
- return realBinder.onTransact(code, data, reply, flags);
- }
-}
diff --git a/v1/src/main/java/android/os/TestVibrator.java b/v1/src/main/java/android/os/TestVibrator.java
deleted file mode 100644
index ad3326d2a..000000000
--- a/v1/src/main/java/android/os/TestVibrator.java
+++ /dev/null
@@ -1,26 +0,0 @@
-package android.os;
-
-public class TestVibrator extends Vibrator {
-
- @Override
- public void cancel() {
- // TODO Auto-generated method stub
- }
-
- @Override
- public boolean hasVibrator() {
- // TODO Auto-generated method stub
- return false;
- }
-
- @Override
- public void vibrate(long arg0) {
- // TODO Auto-generated method stub
- }
-
- @Override
- public void vibrate(long[] arg0, int arg1) {
- // TODO Auto-generated method stub
- }
-
-}
diff --git a/v1/src/main/java/android/view/animation/ShadowAnimationBridge.java b/v1/src/main/java/android/view/animation/ShadowAnimationBridge.java
deleted file mode 100644
index 3d1edc90b..000000000
--- a/v1/src/main/java/android/view/animation/ShadowAnimationBridge.java
+++ /dev/null
@@ -1,20 +0,0 @@
-package android.view.animation;
-
-
-import com.xtremelabs.robolectric.internal.DoNotInstrument;
-
-@DoNotInstrument
-public class ShadowAnimationBridge {
-
- private Animation realAnimation;
-
- public ShadowAnimationBridge(Animation realAnimation) {
- this.realAnimation = realAnimation;
-
- }
-
-
- public void applyTransformation(float interpolatedTime, Transformation t) {
- realAnimation.applyTransformation(interpolatedTime, t);
- }
-}
diff --git a/v1/src/main/java/android/webkit/TestWebSettings.java b/v1/src/main/java/android/webkit/TestWebSettings.java
deleted file mode 100644
index af57d795f..000000000
--- a/v1/src/main/java/android/webkit/TestWebSettings.java
+++ /dev/null
@@ -1,188 +0,0 @@
-package android.webkit;
-
-import com.xtremelabs.robolectric.internal.DoNotInstrument;
-import com.xtremelabs.robolectric.internal.Implementation;
-
-/**
- * Concrete implementation of the abstract WebSettings class.
- */
-@DoNotInstrument
-public class TestWebSettings extends WebSettings {
-
- private boolean allowFileAccess = true;
- private boolean allowFileAccessFromFile = true;
- private boolean allowUniversalAccessFromFile = true;
- private boolean blockNetworkImage = false;
- private boolean blockNetworkLoads = false;
- private boolean builtInZoomControls = true;
- private boolean databaseEnabled = false;
- private boolean domStorageEnabled = false;
- private boolean javaScriptEnabled = false;
- private boolean lightTouchEnabled = false;
- private boolean loadWithOverviewMode = false;
- private boolean needInitialFocus = false;
- private boolean pluginsEnabled = false;
- private WebSettings.PluginState pluginState = WebSettings.PluginState.OFF;
- private boolean supportMultipleWindows = false;
- private boolean supportZoom = true;
-
- public TestWebSettings() {
- }
-
- @Override
- public boolean getAllowFileAccessFromFileURLs() {
- return allowFileAccessFromFile;
- }
-
- @Override
- public boolean getAllowUniversalAccessFromFileURLs() {
- return allowUniversalAccessFromFile;
- }
-
- @Override
- public void setAllowFileAccessFromFileURLs(boolean allow) {
- allowFileAccessFromFile = allow;
- }
-
- @Override
- public void setAllowUniversalAccessFromFileURLs(boolean allow) {
- allowUniversalAccessFromFile = allow;
- }
-
- @Implementation
- public boolean getAllowFileAccess() {
- return allowFileAccess;
- }
-
- @Implementation
- public void setAllowFileAccess(boolean allow) {
- allowFileAccess = allow;
- }
-
- @Implementation
- public synchronized boolean getBlockNetworkImage() {
- return blockNetworkImage;
- }
-
- @Implementation
- public synchronized void setBlockNetworkImage(boolean flag) {
- blockNetworkImage = flag;
- }
-
- @Implementation
- public synchronized boolean getBlockNetworkLoads() {
- return blockNetworkLoads;
- }
-
- @Implementation
- public synchronized void setBlockNetworkLoads(boolean flag) {
- blockNetworkLoads = flag;
- }
-
- @Implementation
- public boolean getBuiltInZoomControls() {
- return builtInZoomControls;
- }
-
- @Implementation
- public void setBuiltInZoomControls(boolean enabled) {
- builtInZoomControls = enabled;
- }
-
- @Implementation
- public synchronized boolean getDatabaseEnabled() {
- return databaseEnabled;
- }
-
- @Implementation
- public synchronized void setDatabaseEnabled(boolean flag) {
- databaseEnabled = flag;
- }
-
- @Implementation
- public synchronized boolean getDomStorageEnabled() {
- return domStorageEnabled;
- }
-
- @Implementation
- public synchronized void setDomStorageEnabled(boolean flag) {
- domStorageEnabled = flag;
- }
-
- @Implementation
- public synchronized boolean getJavaScriptEnabled() {
- return javaScriptEnabled;
- }
-
- @Implementation
- public synchronized void setJavaScriptEnabled(boolean flag) {
- javaScriptEnabled = flag;
- }
-
- @Implementation
- public boolean getLightTouchEnabled() {
- return lightTouchEnabled;
- }
-
- @Implementation
- public void setLightTouchEnabled(boolean flag) {
- lightTouchEnabled = flag;
- }
-
- @Implementation
- public boolean getLoadWithOverviewMode() {
- return loadWithOverviewMode;
- }
-
- @Implementation
- public void setLoadWithOverviewMode(boolean flag) {
- loadWithOverviewMode = flag;
- }
-
- public boolean getNeedInitialFocus() {
- return needInitialFocus;
- }
-
- @Implementation
- public void setNeedInitialFocus(boolean flag) {
- needInitialFocus = flag;
- }
-
- @Implementation
- public synchronized boolean getPluginsEnabled() {
- return pluginsEnabled;
- }
-
- @Implementation
- public synchronized void setPluginsEnabled(boolean flag) {
- pluginsEnabled = flag;
- }
-
- @Implementation
- public synchronized WebSettings.PluginState getPluginState() {
- return pluginState;
- }
-
- @Implementation
- public synchronized void setPluginState(WebSettings.PluginState state) {
- pluginState = state;
- }
-
- public boolean getSupportMultipleWindows() {
- return supportMultipleWindows;
- }
-
- @Implementation
- public synchronized void setSupportMultipleWindows(boolean support) {
- supportMultipleWindows = support;
- }
-
- public boolean getSupportZoom() {
- return supportZoom;
- }
-
- @Implementation
- public void setSupportZoom(boolean support) {
- supportZoom = support;
- }
-}
diff --git a/v1/src/main/java/com/foo/Receiver.java b/v1/src/main/java/com/foo/Receiver.java
deleted file mode 100644
index c1ed412b3..000000000
--- a/v1/src/main/java/com/foo/Receiver.java
+++ /dev/null
@@ -1,13 +0,0 @@
-package com.foo;
-
-import android.content.BroadcastReceiver;
-import android.content.Context;
-import android.content.Intent;
-
-public class Receiver extends BroadcastReceiver {
-
- @Override
- public void onReceive(Context context, Intent intent) {
- }
-
-}
diff --git a/v1/src/main/java/com/google/android/maps/ShadowItemizedOverlayBridge.java b/v1/src/main/java/com/google/android/maps/ShadowItemizedOverlayBridge.java
deleted file mode 100644
index a7b70c257..000000000
--- a/v1/src/main/java/com/google/android/maps/ShadowItemizedOverlayBridge.java
+++ /dev/null
@@ -1,16 +0,0 @@
-package com.google.android.maps;
-
-import com.xtremelabs.robolectric.internal.DoNotInstrument;
-
-@DoNotInstrument
-public class ShadowItemizedOverlayBridge<Item extends OverlayItem> {
- private ItemizedOverlay<Item> itemizedObject;
-
- public ShadowItemizedOverlayBridge(ItemizedOverlay<Item> itemizedObject) {
- this.itemizedObject = itemizedObject;
- }
-
- public Item createItem(int i) {
- return itemizedObject.createItem(i);
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/ConfigTestReceiver.java b/v1/src/main/java/com/xtremelabs/ConfigTestReceiver.java
deleted file mode 100644
index 2319678e9..000000000
--- a/v1/src/main/java/com/xtremelabs/ConfigTestReceiver.java
+++ /dev/null
@@ -1,13 +0,0 @@
-package com.xtremelabs;
-
-import android.content.BroadcastReceiver;
-import android.content.Context;
-import android.content.Intent;
-
-public class ConfigTestReceiver extends BroadcastReceiver {
-
- @Override
- public void onReceive(Context context, Intent intent) {
- }
-
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/ApplicationResolver.java b/v1/src/main/java/com/xtremelabs/robolectric/ApplicationResolver.java
deleted file mode 100644
index c571a194d..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/ApplicationResolver.java
+++ /dev/null
@@ -1,79 +0,0 @@
-package com.xtremelabs.robolectric;
-
-import android.app.Application;
-import android.content.BroadcastReceiver;
-import android.content.IntentFilter;
-import com.xtremelabs.robolectric.internal.ClassNameResolver;
-import com.xtremelabs.robolectric.res.RobolectricPackageManager;
-import com.xtremelabs.robolectric.shadows.ShadowApplication;
-import org.w3c.dom.Document;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-
-public class ApplicationResolver {
- RobolectricConfig config;
-
- public ApplicationResolver(RobolectricConfig config) {
- this.config = config;
- }
-
- public Application resolveApplication() {
- String applicationName = config.getApplicationName();
- String packageName = config.getPackageName();
-
- Application application;
- if (applicationName != null) {
- application = newApplicationInstance(packageName, applicationName);
- } else {
- application = new Application();
- }
-
- ShadowApplication shadowApplication = shadowOf(application);
- shadowApplication.setPackageName(packageName);
- shadowApplication.setApplicationName(applicationName);
-
- shadowApplication.setPackageManager(new RobolectricPackageManager(application, config));
- registerBroadcastReceivers(shadowApplication);
-
- return application;
- }
-
- private void registerBroadcastReceivers(ShadowApplication shadowApplication) {
- for (int i = 0; i < config.getReceiverCount(); i++) {
- IntentFilter filter = new IntentFilter();
- for (String action : config.getReceiverIntentFilterActions(i)) {
- filter.addAction(action);
- }
- String receiverClassName = replaceLastDotWith$IfInnerStaticClass(config.getReceiverClassName(i));
- shadowApplication.registerReceiver((BroadcastReceiver) Robolectric.newInstanceOf(receiverClassName), filter);
- }
- }
-
- private String replaceLastDotWith$IfInnerStaticClass(String receiverClassName) {
- String[] splits = receiverClassName.split("\\.");
- String staticInnerClassRegex = "[A-Z][a-zA-Z]*";
- if (splits[splits.length - 1].matches(staticInnerClassRegex) && splits[splits.length - 2].matches(staticInnerClassRegex)) {
- int lastDotIndex = receiverClassName.lastIndexOf(".");
- StringBuffer buffer = new StringBuffer(receiverClassName);
- buffer.setCharAt(lastDotIndex,'$');
- return buffer.toString();
- }
- return receiverClassName;
- }
-
- private String getTagAttributeText(Document doc, String tag, String attribute) {
- return doc.getElementsByTagName(tag).item(0).getAttributes().getNamedItem(attribute).getTextContent();
- }
-
- private Application newApplicationInstance(String packageName, String applicationName) {
- Application application;
- try {
- Class<? extends Application> applicationClass =
- new ClassNameResolver<Application>(packageName, applicationName).resolve();
- application = applicationClass.newInstance();
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- return application;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/Robolectric.java b/v1/src/main/java/com/xtremelabs/robolectric/Robolectric.java
deleted file mode 100644
index 0d420b72d..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/Robolectric.java
+++ /dev/null
@@ -1,1316 +0,0 @@
-package com.xtremelabs.robolectric;
-
-import java.lang.reflect.Field;
-import java.lang.reflect.Modifier;
-import java.util.Arrays;
-import java.util.List;
-
-import org.apache.http.Header;
-import org.apache.http.HttpRequest;
-import org.apache.http.HttpResponse;
-import org.apache.http.impl.client.DefaultRequestDirector;
-
-import android.accounts.AccountManager;
-import android.app.*;
-import android.appwidget.AppWidgetManager;
-import android.bluetooth.BluetoothAdapter;
-import android.bluetooth.BluetoothDevice;
-import android.content.*;
-import android.content.pm.ResolveInfo;
-import android.content.pm.Signature;
-import android.content.res.AssetManager;
-import android.content.res.Configuration;
-import android.content.res.Resources;
-import android.content.res.Resources.Theme;
-import android.database.CursorWrapper;
-import android.database.sqlite.*;
-import android.graphics.*;
-import android.graphics.drawable.*;
-import android.hardware.Camera;
-import android.hardware.SensorManager;
-import android.location.Address;
-import android.location.Geocoder;
-import android.location.LocationManager;
-import android.media.AudioManager;
-import android.media.MediaPlayer;
-import android.media.MediaRecorder;
-import android.net.ConnectivityManager;
-import android.net.NetworkInfo;
-import android.net.wifi.ScanResult;
-import android.net.wifi.WifiConfiguration;
-import android.net.wifi.WifiInfo;
-import android.net.wifi.WifiManager;
-import android.os.*;
-import android.preference.*;
-import android.support.v4.app.DialogFragment;
-import android.support.v4.app.Fragment;
-import android.support.v4.app.FragmentActivity;
-import android.support.v4.app.FragmentPagerAdapter;
-import android.support.v4.app.ListFragment;
-import android.support.v4.content.CursorLoader;
-import android.support.v4.view.PagerAdapter;
-import android.support.v4.view.ViewPager;
-import android.telephony.PhoneNumberUtils;
-import android.telephony.SmsManager;
-import android.telephony.TelephonyManager;
-import android.text.ClipboardManager;
-import android.text.TextPaint;
-import android.text.format.DateFormat;
-import android.text.method.PasswordTransformationMethod;
-import android.util.SparseArray;
-import android.util.SparseBooleanArray;
-import android.util.SparseIntArray;
-import android.view.*;
-import android.view.animation.*;
-import android.view.inputmethod.InputMethodManager;
-import android.webkit.*;
-import android.widget.*;
-
-import com.xtremelabs.robolectric.bytecode.RobolectricInternals;
-import com.xtremelabs.robolectric.bytecode.ShadowWrangler;
-import com.xtremelabs.robolectric.shadows.*;
-import com.xtremelabs.robolectric.shadows.ShadowResources.ShadowTheme;
-import com.xtremelabs.robolectric.tester.org.apache.http.FakeHttpLayer;
-import com.xtremelabs.robolectric.tester.org.apache.http.HttpRequestInfo;
-import com.xtremelabs.robolectric.tester.org.apache.http.RequestMatcher;
-import com.xtremelabs.robolectric.util.Scheduler;
-
-public class Robolectric {
- public static Application application;
-
- public static <T> T newInstanceOf(Class<T> clazz) {
- return RobolectricInternals.newInstanceOf(clazz);
- }
-
- public static Object newInstanceOf(String className) {
- try {
- Class<?> clazz = Class.forName(className);
- if (clazz != null) {
- return newInstanceOf(clazz);
- }
- } catch (ClassNotFoundException e) {
- }
- return null;
- }
-
- public static void bindShadowClass(Class<?> shadowClass) {
- RobolectricInternals.bindShadowClass(shadowClass);
- }
-
- public static void bindDefaultShadowClasses() {
- bindShadowClasses(getDefaultShadowClasses());
- }
-
- public static void bindShadowClasses(List<Class<?>> shadowClasses) {
- for (Class<?> shadowClass : shadowClasses) {
- bindShadowClass(shadowClass);
- }
- }
-
- /**
- * Invoke this utility method in tests to reveal which Android api classes and methods are being invoked
- * for which there are no shadows or shadow methods. This helps expose which methods are being invoked
- * either by a third party library or application code which need new shadow methods to be written. Generates
- * output for the current test only.
- */
- public static void logMissingInvokedShadowMethods() {
- ShadowWrangler.getInstance().logMissingInvokedShadowMethods();
- }
-
- public static List<Class<?>> getDefaultShadowClasses() {
- return Arrays.asList(
- ShadowAbsListView.class,
- ShadowAbsoluteLayout.class,
- ShadowAbsSeekBar.class,
- ShadowAbsSpinner.class,
- ShadowAbstractCursor.class,
- ShadowAccount.class,
- ShadowAccountManager.class,
- ShadowActivity.class,
- ShadowActivityInfo.class,
- ShadowActivityGroup.class,
- ShadowActivityManager.class,
- ShadowAdapterView.class,
- ShadowAddress.class,
- ShadowAlarmManager.class,
- ShadowAlertDialog.class,
- ShadowAlertDialog.ShadowBuilder.class,
- ShadowAlphaAnimation.class,
- ShadowAndroidHttpClient.class,
- ShadowAnimation.class,
- ShadowAnimationDrawable.class,
- ShadowAnimationSet.class,
- ShadowAnimationUtils.class,
- ShadowApplication.class,
- ShadowAppWidgetManager.class,
- ShadowArrayAdapter.class,
- ShadowAssetManager.class,
- ShadowAsyncTask.class,
- ShadowAudioManager.class,
- ShadowAutoCompleteTextView.class,
- ShadowBase64.class,
- ShadowBaseAdapter.class,
- ShadowBinder.class,
- ShadowBitmap.class,
- ShadowBitmapDrawable.class,
- ShadowBitmapFactory.class,
- ShadowBluetoothAdapter.class,
- ShadowBluetoothDevice.class,
- ShadowBundle.class,
- ShadowButton.class,
- ShadowCamera.class,
- ShadowCameraParameters.class,
- ShadowCameraSize.class,
- ShadowCanvas.class,
- ShadowCheckedTextView.class,
- ShadowClipboardManager.class,
- ShadowColor.class,
- ShadowColorDrawable.class,
- ShadowColorMatrix.class,
- ShadowColorMatrixColorFilter.class,
- ShadowColorStateList.class,
- ShadowComponentName.class,
- ShadowCompoundButton.class,
- ShadowConfiguration.class,
- ShadowConnectivityManager.class,
- ShadowContentProvider.class,
- ShadowContentProviderOperation.class,
- ShadowContentProviderOperationBuilder.class,
- ShadowContentProviderResult.class,
- ShadowContentResolver.class,
- ShadowContentUris.class,
- ShadowContentValues.class,
- ShadowContext.class,
- ShadowContextWrapper.class,
- ShadowContextThemeWrapper.class,
- ShadowCookieManager.class,
- ShadowCookieSyncManager.class,
- ShadowCriteria.class,
- ShadowCountDownTimer.class,
- ShadowCursorAdapter.class,
- ShadowCursorLoader.class,
- ShadowCursorWrapper.class,
- ShadowDatabaseUtils.class,
- ShadowDateFormat.class,
- ShadowDefaultRequestDirector.class,
- ShadowDisplay.class,
- ShadowDrawable.class,
- ShadowDialog.class,
- ShadowDialogFragment.class,
- ShadowDialogPreference.class,
- ShadowEditText.class,
- ShadowEnvironment.class,
- ShadowExpandableListView.class,
- ShadowFilter.class,
- ShadowFloatMath.class,
- ShadowFragment.class,
- ShadowFragmentActivity.class,
- ShadowFragmentPagerAdapter.class,
- ShadowFrameLayout.class,
- ShadowGallery.class,
- ShadowGeocoder.class,
- ShadowGeoPoint.class,
- ShadowGridView.class,
- ShadowHandler.class,
- ShadowHandlerThread.class,
- ShadowHtml.class,
- ShadowImageView.class,
- ShadowInputMethodManager.class,
- ShadowIntent.class,
- ShadowIntentFilter.class,
- ShadowIntentFilterAuthorityEntry.class,
- ShadowItemizedOverlay.class,
- ShadowJsPromptResult.class,
- ShadowJsResult.class,
- ShadowKeyEvent.class,
- ShadowKeyguardManager.class,
- ShadowKeyGuardLock.class,
- ShadowLayerDrawable.class,
- ShadowLayoutInflater.class,
- ShadowLayoutParams.class,
- ShadowLinearLayout.class,
- ShadowLinkMovementMethod.class,
- ShadowListActivity.class,
- ShadowListFragment.class,
- ShadowListPreference.class,
- ShadowListView.class,
- ShadowLocation.class,
- ShadowLocationManager.class,
- ShadowLog.class,
- ShadowLooper.class,
- ShadowMapController.class,
- ShadowMapActivity.class,
- ShadowMapView.class,
- ShadowMarginLayoutParams.class,
- ShadowMatrix.class,
- ShadowMatrixCursor.class,
- ShadowMediaPlayer.class,
- ShadowMediaRecorder.class,
- ShadowMediaStore.ShadowImages.ShadowMedia.class,
- ShadowMenuInflater.class,
- ShadowMessage.class,
- ShadowMessenger.class,
- ShadowMimeTypeMap.class,
- ShadowMotionEvent.class,
- ShadowNotification.class,
- ShadowNdefMessage.class,
- ShadowNdefRecord.class,
- ShadowNfcAdapter.class,
- ShadowNotificationManager.class,
- ShadowNetworkInfo.class,
- ShadowOverlayItem.class,
- ShadowPagerAdapter.class,
- ShadowPaint.class,
- ShadowPair.class,
- ShadowParcel.class,
- ShadowPasswordTransformationMethod.class,
- ShadowPath.class,
- ShadowPatterns.class,
- ShadowPendingIntent.class,
- ShadowPeriodicSync.class,
- ShadowPhoneNumberUtils.class,
- ShadowPoint.class,
- ShadowPointF.class,
- ShadowPopupWindow.class,
- ShadowPowerManager.class,
- ShadowPowerManager.ShadowWakeLock.class,
- ShadowPreference.class,
- ShadowPreferenceActivity.class,
- ShadowPreferenceCategory.class,
- ShadowPreferenceGroup.class,
- ShadowPreferenceManager.class,
- ShadowPreferenceScreen.class,
- ShadowProcess.class,
- ShadowProgressBar.class,
- ShadowProgressDialog.class,
- ShadowRadioButton.class,
- ShadowRadioGroup.class,
- ShadowRatingBar.class,
- ShadowRect.class,
- ShadowResolveInfo.class,
- ShadowRemoteCallbackList.class,
- ShadowRemoteViews.class,
- ShadowResultReceiver.class,
- ShadowResourceCursorAdapter.class,
- ShadowResources.class,
- ShadowResources.ShadowTheme.class,
- ShadowScanResult.class,
- ShadowScrollView.class,
- ShadowSeekBar.class,
- ShadowSensorManager.class,
- ShadowService.class,
- ShadowSettings.class,
- ShadowSettings.ShadowGlobal.class,
- ShadowSettings.ShadowSecure.class,
- ShadowSettings.ShadowSystem.class,
- ShadowSignature.class,
- ShadowSimpleCursorAdapter.class,
- ShadowShapeDrawable.class,
- ShadowSmsManager.class,
- ShadowSpannableString.class,
- ShadowSpannableStringBuilder.class,
- ShadowSparseArray.class,
- ShadowSparseBooleanArray.class,
- ShadowSparseIntArray.class,
- ShadowSpinner.class,
- ShadowSSLCertificateSocketFactory.class,
- ShadowSyncResult.class,
- ShadowSyncResult.ShadowSyncStats.class,
- ShadowSQLiteProgram.class,
- ShadowSQLiteCloseable.class,
- ShadowSQLiteDatabase.class,
- ShadowSQLiteCursor.class,
- ShadowSQLiteOpenHelper.class,
- ShadowSQLiteStatement.class,
- ShadowSQLiteQueryBuilder.class,
- ShadowSslErrorHandler.class,
- ShadowStateListDrawable.class,
- ShadowStatFs.class,
- ShadowSurfaceView.class,
- ShadowTabActivity.class,
- ShadowTabHost.class,
- ShadowTabSpec.class,
- ShadowTelephonyManager.class,
- ShadowTextPaint.class,
- ShadowTextUtils.class,
- ShadowTextView.class,
- ShadowTime.class,
- ShadowToast.class,
- ShadowTranslateAnimation.class,
- ShadowTypedArray.class,
- ShadowTypedValue.class,
- ShadowUriMatcher.class,
- ShadowURLSpan.class,
- ShadowVibrator.class,
- ShadowVideoView.class,
- ShadowView.class,
- ShadowViewAnimator.class,
- ShadowViewConfiguration.class,
- ShadowViewGroup.class,
- ShadowViewFlipper.class,
- ShadowViewMeasureSpec.class,
- ShadowViewPager.class,
- ShadowViewStub.class,
- ShadowViewTreeObserver.class,
- ShadowWebView.class,
- ShadowWifiConfiguration.class,
- ShadowWifiInfo.class,
- ShadowWifiManager.class,
- ShadowWifiManager.ShadowWifiLock.class,
- ShadowWindow.class,
- ShadowZoomButtonsController.class
- );
- }
-
- public static void resetStaticState() {
- ShadowWrangler.getInstance().silence();
- Robolectric.application = new Application();
- ShadowBinder.reset();
- ShadowBitmapFactory.reset();
- ShadowDrawable.reset();
- ShadowMediaStore.reset();
- ShadowLog.reset();
- ShadowContext.clearFilesAndCache();
- ShadowLooper.resetThreadLoopers();
- ShadowDialog.reset();
- ShadowContentResolver.reset();
- ShadowLocalBroadcastManager.reset();
- ShadowMimeTypeMap.reset();
- ShadowStatFs.reset();
- ShadowProcess.reset();
- ShadowAccount.reset();
- ShadowIntent.reset();
- ShadowSignature.reset();
- ShadowBundle.reset();
- ShadowPatterns.reset();
- }
-
- public static <T> T directlyOn(T shadowedObject) {
- return RobolectricInternals.directlyOn(shadowedObject);
- }
-
- public static ShadowAbsListView shadowOf(AbsListView instance) {
- return (ShadowAbsListView) shadowOf_(instance);
- }
-
- public static ShadowAbsSeekBar shadowOf(AbsSeekBar instance) {
- return (ShadowAbsSeekBar) shadowOf_(instance);
- }
-
- public static ShadowAccountManager shadowOf(AccountManager instance) {
- return (ShadowAccountManager) shadowOf_(instance);
- }
-
- public static ShadowActivity shadowOf(Activity instance) {
- return (ShadowActivity) shadowOf_(instance);
- }
-
- public static ShadowActivityGroup shadowOf(ActivityGroup instance) {
- return (ShadowActivityGroup) shadowOf_(instance);
- }
-
- public static ShadowActivityManager shadowOf(ActivityManager instance) {
- return (ShadowActivityManager) shadowOf_(instance);
- }
-
- public static ShadowAdapterView shadowOf(AdapterView instance) {
- return (ShadowAdapterView) shadowOf_(instance);
- }
-
- public static ShadowAddress shadowOf(Address instance) {
- return (ShadowAddress) shadowOf_(instance);
- }
-
- public static ShadowAlarmManager shadowOf(AlarmManager instance) {
- return (ShadowAlarmManager) Robolectric.shadowOf_(instance);
- }
-
- public static ShadowAlertDialog shadowOf(AlertDialog instance) {
- return (ShadowAlertDialog) shadowOf_(instance);
- }
-
- public static ShadowAlphaAnimation shadowOf(AlphaAnimation instance) {
- return (ShadowAlphaAnimation) shadowOf_(instance);
- }
-
- public static ShadowAnimation shadowOf(Animation instance) {
- return (ShadowAnimation) shadowOf_(instance);
- }
-
- public static ShadowAnimationDrawable shadowOf(AnimationDrawable instance) {
- return (ShadowAnimationDrawable) shadowOf_(instance);
- }
-
- public static ShadowAnimationSet shadowOf(AnimationSet instance) {
- return (ShadowAnimationSet) shadowOf_(instance);
- }
-
- public static ShadowAnimationUtils shadowOf(AnimationUtils instance) {
- return (ShadowAnimationUtils) shadowOf_(instance);
- }
-
- public static ShadowApplication shadowOf(Application instance) {
- return (ShadowApplication) shadowOf_(instance);
- }
-
- public static ShadowAppWidgetManager shadowOf(AppWidgetManager instance) {
- return (ShadowAppWidgetManager) shadowOf_(instance);
- }
-
- public static ShadowArrayAdapter shadowOf(ArrayAdapter instance) {
- return (ShadowArrayAdapter) shadowOf_(instance);
- }
-
- public static ShadowAssetManager shadowOf(AssetManager instance) {
- return (ShadowAssetManager) Robolectric.shadowOf_(instance);
- }
-
- @SuppressWarnings("rawtypes")
- public static ShadowAsyncTask shadowOf(AsyncTask instance){
- return (ShadowAsyncTask) Robolectric.shadowOf_( instance );
- }
-
- public static ShadowAudioManager shadowOf(AudioManager instance) {
- return (ShadowAudioManager) shadowOf_(instance);
- }
-
- public static ShadowAutoCompleteTextView shadowOf(AutoCompleteTextView instance) {
- return (ShadowAutoCompleteTextView) shadowOf_(instance);
- }
-
- public static ShadowBaseAdapter shadowOf(BaseAdapter other) {
- return (ShadowBaseAdapter) Robolectric.shadowOf_(other);
- }
-
- public static ShadowBitmap shadowOf(Bitmap other) {
- return (ShadowBitmap) Robolectric.shadowOf_(other);
- }
-
- public static ShadowBitmapDrawable shadowOf(BitmapDrawable instance) {
- return (ShadowBitmapDrawable) shadowOf_(instance);
- }
-
- public static ShadowBluetoothAdapter shadowOf(BluetoothAdapter other) {
- return (ShadowBluetoothAdapter) Robolectric.shadowOf_(other);
- }
-
- public static ShadowBluetoothDevice shadowOf(BluetoothDevice other) {
- return (ShadowBluetoothDevice) Robolectric.shadowOf_(other);
- }
-
- public static ShadowBundle shadowOf(Bundle instance) {
- return (ShadowBundle) shadowOf_(instance);
- }
-
- public static ShadowCamera shadowOf(Camera instance) {
- return (ShadowCamera) shadowOf_(instance);
- }
-
- public static ShadowCameraParameters shadowOf(Camera.Parameters instance) {
- return (ShadowCameraParameters) shadowOf_(instance);
- }
-
- public static ShadowCameraSize shadowOf(Camera.Size instance) {
- return (ShadowCameraSize) shadowOf_(instance);
- }
-
- public static ShadowCanvas shadowOf(Canvas instance) {
- return (ShadowCanvas) shadowOf_(instance);
- }
-
- public static ShadowCheckedTextView shadowOf(CheckedTextView instance) {
- return (ShadowCheckedTextView) shadowOf_(instance);
- }
-
- public static ShadowClipboardManager shadowOf(ClipboardManager instance) {
- return (ShadowClipboardManager) shadowOf_(instance);
- }
-
- public static ShadowColor shadowOf(Color instance) {
- return (ShadowColor) shadowOf_(instance);
- }
-
- public static ShadowColorDrawable shadowOf(ColorDrawable instance) {
- return (ShadowColorDrawable) shadowOf_(instance);
- }
-
- public static ShadowColorMatrix shadowOf(ColorMatrix instance) {
- return (ShadowColorMatrix) shadowOf_(instance);
- }
-
- public static ShadowConfiguration shadowOf(Configuration instance) {
- return (ShadowConfiguration) Robolectric.shadowOf_(instance);
- }
-
- public static ShadowConnectivityManager shadowOf(ConnectivityManager instance) {
- return (ShadowConnectivityManager) shadowOf_(instance);
- }
-
- public static ShadowCookieManager shadowOf(CookieManager instance) {
- return (ShadowCookieManager) shadowOf_(instance);
- }
-
- public static ShadowContentResolver shadowOf(ContentResolver instance) {
- return (ShadowContentResolver) shadowOf_(instance);
- }
-
- public static ShadowContentProviderOperation shadowOf(ContentProviderOperation instance) {
- return (ShadowContentProviderOperation) shadowOf_(instance);
- }
-
- public static ShadowContentProviderOperationBuilder shadowOf(ContentProviderOperation.Builder instance) {
- return (ShadowContentProviderOperationBuilder) shadowOf_(instance);
- }
-
- public static ShadowContentProviderResult shadowOf(ContentProviderResult instance) {
- return (ShadowContentProviderResult) shadowOf_(instance);
- }
-
- public static ShadowCookieSyncManager shadowOf(CookieSyncManager instance) {
- return (ShadowCookieSyncManager) shadowOf_(instance);
- }
-
- public static ShadowContext shadowOf(Context instance) {
- return (ShadowContext) shadowOf_(instance);
- }
-
- public static ShadowContentValues shadowOf(ContentValues other) {
- return (ShadowContentValues) Robolectric.shadowOf_(other);
- }
-
- public static ShadowContextWrapper shadowOf(ContextWrapper instance) {
- return (ShadowContextWrapper) shadowOf_(instance);
- }
-
- public static ShadowCountDownTimer shadowOf(CountDownTimer instance) {
- return (ShadowCountDownTimer) Robolectric.shadowOf_(instance);
- }
-
- public static ShadowCursorAdapter shadowOf(CursorAdapter instance) {
- return (ShadowCursorAdapter) shadowOf_(instance);
- }
-
- public static ShadowCursorLoader shadowOf(CursorLoader instance) {
- return (ShadowCursorLoader) shadowOf_(instance);
- }
-
- public static ShadowCursorWrapper shadowOf(CursorWrapper instance) {
- return (ShadowCursorWrapper) shadowOf_(instance);
- }
-
- public static ShadowDateFormat shadowOf(DateFormat instance) {
- return (ShadowDateFormat) shadowOf_(instance);
- }
-
- public static ShadowDefaultRequestDirector shadowOf(DefaultRequestDirector instance) {
- return (ShadowDefaultRequestDirector) shadowOf_(instance);
- }
-
- public static ShadowDialog shadowOf(Dialog instance) {
- return (ShadowDialog) shadowOf_(instance);
- }
-
- public static ShadowDialogFragment shadowOf(DialogFragment instance) {
- return (ShadowDialogFragment) shadowOf_(instance);
- }
-
- public static ShadowDialogPreference shadowOf(DialogPreference instance) {
- return (ShadowDialogPreference) shadowOf_(instance);
- }
-
- public static ShadowDrawable shadowOf(Drawable instance) {
- return (ShadowDrawable) shadowOf_(instance);
- }
-
- public static ShadowDisplay shadowOf(Display instance) {
- return (ShadowDisplay) shadowOf_(instance);
- }
-
- public static ShadowExpandableListView shadowOf(ExpandableListView instance) {
- return (ShadowExpandableListView) shadowOf_(instance);
- }
-
- public static ShadowFilter shadowOf(Filter instance) {
- return (ShadowFilter) shadowOf_(instance);
- }
-
- public static ShadowFragment shadowOf(Fragment instance) {
- return (ShadowFragment) shadowOf_(instance);
- }
-
- public static ShadowFragmentActivity shadowOf(FragmentActivity instance) {
- return (ShadowFragmentActivity) shadowOf_(instance);
- }
-
- public static ShadowFragmentPagerAdapter shadowOf(FragmentPagerAdapter instance) {
- return (ShadowFragmentPagerAdapter) shadowOf_(instance);
- }
-
- public static ShadowFrameLayout shadowOf(FrameLayout instance) {
- return (ShadowFrameLayout) shadowOf_(instance);
- }
-
- public static ShadowGallery shadowOf(Gallery instance) {
- return (ShadowGallery) shadowOf_(instance);
- }
-
- public static ShadowGeocoder shadowOf(Geocoder instance) {
- return (ShadowGeocoder) shadowOf_(instance);
- }
-
- public static ShadowGridView shadowOf(GridView instance) {
- return (ShadowGridView) shadowOf_(instance);
- }
-
- public static ShadowHandler shadowOf(Handler instance) {
- return (ShadowHandler) shadowOf_(instance);
- }
-
- public static ShadowHandlerThread shadowOf(HandlerThread instance) {
- return (ShadowHandlerThread) shadowOf_(instance);
- }
-
- public static ShadowImageView shadowOf(ImageView instance) {
- return (ShadowImageView) shadowOf_(instance);
- }
-
- public static ShadowInputMethodManager shadowOf(InputMethodManager instance) {
- return (ShadowInputMethodManager) shadowOf_(instance);
- }
-
- public static ShadowIntent shadowOf(Intent instance) {
- return (ShadowIntent) shadowOf_(instance);
- }
-
- public static ShadowJsPromptResult shadowOf(JsPromptResult instance) {
- return (ShadowJsPromptResult) shadowOf_(instance);
- }
-
- public static ShadowJsResult shadowOf(JsResult instance) {
- return (ShadowJsResult) shadowOf_(instance);
- }
-
- public static ShadowKeyguardManager shadowOf(KeyguardManager instance) {
- return (ShadowKeyguardManager) shadowOf_(instance);
- }
-
- public static ShadowKeyGuardLock shadowOf(KeyguardManager.KeyguardLock instance) {
- return (ShadowKeyGuardLock) shadowOf_(instance);
- }
-
- public static ShadowLayerDrawable shadowOf(LayerDrawable instance) {
- return (ShadowLayerDrawable) shadowOf_(instance);
- }
-
- public static ShadowLayoutInflater shadowOf(LayoutInflater instance) {
- return (ShadowLayoutInflater) shadowOf_(instance);
- }
-
- public static ShadowListActivity shadowOf(ListActivity instance) {
- return (ShadowListActivity) shadowOf_(instance);
- }
-
- public static ShadowListFragment shadowOf(ListFragment instance) {
- return (ShadowListFragment) shadowOf_(instance);
- }
-
- public static ShadowListPreference shadowOf(ListPreference instance) {
- return (ShadowListPreference) shadowOf_(instance);
- }
-
- public static ShadowListView shadowOf(ListView instance) {
- return (ShadowListView) shadowOf_(instance);
- }
-
- public static ShadowLocationManager shadowOf(LocationManager instance) {
- return (ShadowLocationManager) shadowOf_(instance);
- }
-
- public static ShadowLooper shadowOf(Looper instance) {
- return (ShadowLooper) shadowOf_(instance);
- }
-
- public static ShadowMatrix shadowOf(Matrix other) {
- return (ShadowMatrix) Robolectric.shadowOf_(other);
- }
-
- public static ShadowMediaPlayer shadowOf(MediaPlayer instance) {
- return (ShadowMediaPlayer) shadowOf_(instance);
- }
-
- public static ShadowMediaRecorder shadowOf(MediaRecorder instance) {
- return (ShadowMediaRecorder) shadowOf_(instance);
- }
-
- public static ShadowMenuInflater shadowOf(MenuInflater instance) {
- return (ShadowMenuInflater) shadowOf_(instance);
- }
-
- public static ShadowMessage shadowOf(Message instance) {
- return (ShadowMessage) shadowOf_(instance);
- }
-
- public static ShadowMimeTypeMap shadowOf(MimeTypeMap instance) {
- return (ShadowMimeTypeMap) shadowOf_(instance);
- }
-
- public static ShadowMotionEvent shadowOf(MotionEvent other) {
- return (ShadowMotionEvent) Robolectric.shadowOf_(other);
- }
-
- public static ShadowNetworkInfo shadowOf(NetworkInfo instance) {
- return (ShadowNetworkInfo) shadowOf_(instance);
- }
-
- public static ShadowNotification shadowOf(Notification other) {
- return (ShadowNotification) Robolectric.shadowOf_(other);
- }
-
- public static ShadowNotificationManager shadowOf(NotificationManager other) {
- return (ShadowNotificationManager) Robolectric.shadowOf_(other);
- }
-
- public static ShadowPagerAdapter shadowOf(PagerAdapter instance) {
- return (ShadowPagerAdapter) shadowOf_(instance);
- }
-
- public static ShadowPaint shadowOf(Paint instance) {
- return (ShadowPaint) shadowOf_(instance);
- }
-
- public static ShadowParcel shadowOf(Parcel instance) {
- return (ShadowParcel) shadowOf_(instance);
- }
-
- public static ShadowPasswordTransformationMethod shadowOf(PasswordTransformationMethod instance) {
- return (ShadowPasswordTransformationMethod) shadowOf_(instance);
- }
-
- public static ShadowPath shadowOf(Path instance) {
- return (ShadowPath) shadowOf_(instance);
- }
-
- public static ShadowPendingIntent shadowOf(PendingIntent instance) {
- return (ShadowPendingIntent) shadowOf_(instance);
- }
-
- public static ShadowPhoneNumberUtils shadowOf(PhoneNumberUtils instance) {
- return (ShadowPhoneNumberUtils) shadowOf_(instance);
- }
-
- public static ShadowPopupWindow shadowOf(PopupWindow instance) {
- return (ShadowPopupWindow) shadowOf_(instance);
- }
-
- public static ShadowPowerManager shadowOf(PowerManager instance) {
- return (ShadowPowerManager) shadowOf_(instance);
- }
-
- public static ShadowPreference shadowOf(Preference instance) {
- return (ShadowPreference) shadowOf_(instance);
- }
-
- public static ShadowPreferenceActivity shadowOf(PreferenceActivity instance) {
- return (ShadowPreferenceActivity) shadowOf_(instance);
- }
-
- public static ShadowPreferenceCategory shadowOf(PreferenceCategory instance) {
- return (ShadowPreferenceCategory) shadowOf_(instance);
- }
-
- public static ShadowPreferenceGroup shadowOf(PreferenceGroup instance) {
- return (ShadowPreferenceGroup) shadowOf_(instance);
- }
-
- public static ShadowPreferenceScreen shadowOf(PreferenceScreen instance) {
- return (ShadowPreferenceScreen) shadowOf_(instance);
- }
-
- public static ShadowProgressBar shadowOf(ProgressBar instance) {
- return (ShadowProgressBar) shadowOf_(instance);
- }
-
- public static ShadowProgressDialog shadowOf(ProgressDialog instance) {
- return (ShadowProgressDialog) shadowOf_(instance);
- }
-
- public static ShadowRect shadowOf(Rect instance) {
- return (ShadowRect) shadowOf_(instance);
- }
-
- public static ShadowRatingBar shadowOf(RatingBar instance) {
- return (ShadowRatingBar) shadowOf_(instance);
- }
-
- public static ShadowRemoteViews shadowOf(RemoteViews instance) {
- return (ShadowRemoteViews) shadowOf_(instance);
- }
-
- public static ShadowResolveInfo shadowOf(ResolveInfo instance) {
- return (ShadowResolveInfo) shadowOf_(instance);
- }
-
- public static ShadowResourceCursorAdapter shadowOf(ResourceCursorAdapter instance) {
- return (ShadowResourceCursorAdapter) shadowOf_(instance);
- }
-
- public static ShadowResources shadowOf(Resources instance) {
- return (ShadowResources) shadowOf_(instance);
- }
-
- public static ShadowResultReceiver shadowOf(ResultReceiver instance) {
- return (ShadowResultReceiver) shadowOf_(instance);
- }
-
- public static ShadowScanResult shadowOf(ScanResult instance) {
- return (ShadowScanResult) shadowOf_(instance);
- }
-
- public static ShadowScrollView shadowOf(ScrollView instance) {
- return (ShadowScrollView) shadowOf_(instance);
- }
-
- public static ShadowSeekBar shadowOf(SeekBar instance) {
- return (ShadowSeekBar) shadowOf_(instance);
- }
-
- public static ShadowSensorManager shadowOf(SensorManager instance) {
- return (ShadowSensorManager) shadowOf_(instance);
- }
-
- public static ShadowService shadowOf(Service instance) {
- return (ShadowService) shadowOf_(instance);
- }
-
- public static ShadowShapeDrawable shadowOf(ShapeDrawable instance) {
- return (ShadowShapeDrawable) shadowOf_(instance);
- }
-
- public static ShadowSignature shadowOf(Signature instance) {
- return (ShadowSignature) shadowOf_(instance);
- }
-
- public static ShadowSimpleCursorAdapter shadowOf(SimpleCursorAdapter instance) {
- return (ShadowSimpleCursorAdapter) shadowOf_(instance);
- }
-
- public static ShadowSmsManager shadowOf(SmsManager instance) {
- return (ShadowSmsManager) shadowOf_(instance);
- }
-
- public static <E> ShadowSparseArray<E> shadowOf(SparseArray<E> other) {
- //noinspection unchecked
- return (ShadowSparseArray<E>) Robolectric.shadowOf_(other);
- }
-
- public static ShadowSparseBooleanArray shadowOf(SparseBooleanArray other) {
- return (ShadowSparseBooleanArray) Robolectric.shadowOf_(other);
- }
-
- public static ShadowSparseIntArray shadowOf(SparseIntArray other){
- return (ShadowSparseIntArray) Robolectric.shadowOf_( other );
- }
-
- public static ShadowSQLiteCursor shadowOf(SQLiteCursor other) {
- return (ShadowSQLiteCursor) Robolectric.shadowOf_(other);
- }
-
- public static ShadowSQLiteDatabase shadowOf(SQLiteDatabase other) {
- return (ShadowSQLiteDatabase) Robolectric.shadowOf_(other);
- }
-
- public static ShadowSQLiteOpenHelper shadowOf(SQLiteOpenHelper other) {
- return (ShadowSQLiteOpenHelper) Robolectric.shadowOf_(other);
- }
-
- public static ShadowSQLiteProgram shadowOf(SQLiteProgram other) {
- return (ShadowSQLiteProgram) Robolectric.shadowOf_(other);
- }
-
- public static ShadowSQLiteQueryBuilder shadowOf(SQLiteQueryBuilder other) {
- return (ShadowSQLiteQueryBuilder) Robolectric.shadowOf_(other);
- }
-
- public static ShadowSQLiteStatement shadowOf(SQLiteStatement other) {
- return (ShadowSQLiteStatement) Robolectric.shadowOf_(other);
- }
-
- public static ShadowSslErrorHandler shadowOf(SslErrorHandler instance) {
- return (ShadowSslErrorHandler) shadowOf_(instance);
- }
-
- public static ShadowStateListDrawable shadowOf(StateListDrawable instance) {
- return (ShadowStateListDrawable) shadowOf_(instance);
- }
-
- public static ShadowTabHost shadowOf(TabHost instance) {
- return (ShadowTabHost) shadowOf_(instance);
- }
-
- public static ShadowTabSpec shadowOf(TabHost.TabSpec instance) {
- return (ShadowTabSpec) shadowOf_(instance);
- }
-
- public static ShadowTelephonyManager shadowOf(TelephonyManager instance) {
- return (ShadowTelephonyManager) shadowOf_(instance);
- }
-
- public static ShadowTextPaint shadowOf(TextPaint instance) {
- return (ShadowTextPaint) shadowOf_(instance);
- }
-
- public static ShadowTextView shadowOf(TextView instance) {
- return (ShadowTextView) shadowOf_(instance);
- }
-
- public static ShadowToast shadowOf(Toast instance) {
- return (ShadowToast) shadowOf_(instance);
- }
-
- public static ShadowTranslateAnimation shadowOf(TranslateAnimation instance) {
- return (ShadowTranslateAnimation) shadowOf_(instance);
- }
-
- public static ShadowUriMatcher shadowOf(UriMatcher instance) {
- return (ShadowUriMatcher) shadowOf_(instance);
- }
-
- public static ShadowView shadowOf(View instance) {
- return (ShadowView) shadowOf_(instance);
- }
-
- public static ShadowViewAnimator shadowOf(ViewAnimator instance) {
- return (ShadowViewAnimator) shadowOf_(instance);
- }
-
- public static ShadowViewConfiguration shadowOf(ViewConfiguration instance) {
- return (ShadowViewConfiguration) shadowOf_(instance);
- }
-
- public static ShadowViewFlipper shadowOf(ViewFlipper instance) {
- return (ShadowViewFlipper) shadowOf_(instance);
- }
-
- public static ShadowViewPager shadowOf(ViewPager instance) {
- return (ShadowViewPager) shadowOf_(instance);
- }
-
- public static ShadowViewTreeObserver shadowOf(ViewTreeObserver instance) {
- return (ShadowViewTreeObserver) shadowOf_(instance);
- }
-
- public static ShadowViewGroup shadowOf(ViewGroup instance) {
- return (ShadowViewGroup) shadowOf_(instance);
- }
-
- public static ShadowVibrator shadowOf(Vibrator instance) {
- return (ShadowVibrator) shadowOf_(instance);
- }
-
- public static ShadowVideoView shadowOf(VideoView instance) {
- return (ShadowVideoView) shadowOf_(instance);
- }
-
- public static ShadowWebView shadowOf(WebView instance) {
- return (ShadowWebView) shadowOf_(instance);
- }
-
- public static ShadowWifiConfiguration shadowOf(WifiConfiguration instance) {
- return (ShadowWifiConfiguration) shadowOf_(instance);
- }
-
- public static ShadowWifiInfo shadowOf(WifiInfo instance) {
- return (ShadowWifiInfo) shadowOf_(instance);
- }
-
- public static ShadowWifiManager shadowOf(WifiManager instance) {
- return (ShadowWifiManager) shadowOf_(instance);
- }
-
- public static ShadowZoomButtonsController shadowOf(ZoomButtonsController instance) {
- return (ShadowZoomButtonsController) shadowOf_(instance);
- }
-
- public static ShadowTheme shadowOf(Theme instance) {
- return (ShadowTheme) shadowOf_(instance);
- }
-
- @SuppressWarnings({"unchecked"})
- public static <P, R> P shadowOf_(R instance) {
- return (P) ShadowWrangler.getInstance().shadowOf(instance);
- }
-
- /**
- * Runs any background tasks previously queued by {@link android.os.AsyncTask#execute(Object[])}.
- * <p/>
- * <p/>
- * Note: calling this method does not pause or un-pause the scheduler.
- */
- public static void runBackgroundTasks() {
- getBackgroundScheduler().advanceBy(0);
- }
-
- /**
- * Runs any immediately runnable tasks previously queued on the UI thread,
- * e.g. by {@link Activity#runOnUiThread(Runnable)} or {@link android.os.AsyncTask#onPostExecute(Object)}.
- * <p/>
- * <p/>
- * Note: calling this method does not pause or un-pause the scheduler.
- */
- public static void runUiThreadTasks() {
- getUiThreadScheduler().advanceBy(0);
- }
-
- public static void runUiThreadTasksIncludingDelayedTasks() {
- getUiThreadScheduler().advanceToLastPostedRunnable();
- }
-
- /**
- * Sets up an HTTP response to be returned by calls to Apache's {@code HttpClient} implementers.
- *
- * @param statusCode the status code of the response
- * @param responseBody the body of the response
- * @param headers optional headers for the request
- */
- public static void addPendingHttpResponse(int statusCode, String responseBody, Header... headers) {
- getFakeHttpLayer().addPendingHttpResponse(statusCode, responseBody, headers);
- }
-
- /**
- * Sets up an HTTP response to be returned by calls to Apache's {@code HttpClient} implementers.
- *
- * @param statusCode the status code of the response
- * @param responseBody the body of the response
- * @param contentType the contentType of the response
- * @deprecated use {@link #addPendingHttpResponse(int, String, Header...)} instead
- */
- @Deprecated
- public static void addPendingHttpResponseWithContentType(int statusCode, String responseBody, Header contentType) {
- getFakeHttpLayer().addPendingHttpResponse(statusCode, responseBody, contentType);
- }
-
- /**
- * Sets up an HTTP response to be returned by calls to Apache's {@code HttpClient} implementers.
- *
- * @param httpResponse the response
- */
- public static void addPendingHttpResponse(HttpResponse httpResponse) {
- getFakeHttpLayer().addPendingHttpResponse(httpResponse);
- }
-
- /**
- * Sets up an HTTP response to be returned by calls to Apache's {@code HttpClient} implementers.
- *
- * @param httpResponseGenerator an HttpResponseGenerator that will provide responses
- */
- public static void addPendingHttpResponse(HttpResponseGenerator httpResponseGenerator) {
- getFakeHttpLayer().addPendingHttpResponse(httpResponseGenerator);
- }
-
- /**
- * Accessor to obtain HTTP requests made during the current test in the order in which they were made.
- *
- * @param index index of the request to retrieve.
- * @return the requested request.
- */
- public static HttpRequest getSentHttpRequest(int index) {
- return ShadowDefaultRequestDirector.getSentHttpRequest(index);
- }
-
- public static HttpRequest getLatestSentHttpRequest() {
- return ShadowDefaultRequestDirector.getLatestSentHttpRequest();
- }
-
- /**
- * Accessor to find out if HTTP requests were made during the current test.
- *
- * @return whether a request was made.
- */
- public static boolean httpRequestWasMade() {
- return getShadowApplication().getFakeHttpLayer().hasRequestInfos();
- }
-
- public static boolean httpRequestWasMade(String uri) {
- return getShadowApplication().getFakeHttpLayer().hasRequestMatchingRule(new FakeHttpLayer.UriRequestMatcher(uri));
- }
-
- /**
- * Accessor to obtain metadata for an HTTP request made during the current test in the order in which they were made.
- *
- * @param index index of the request to retrieve.
- * @return the requested request metadata.
- */
- public static HttpRequestInfo getSentHttpRequestInfo(int index) {
- return ShadowDefaultRequestDirector.getSentHttpRequestInfo(index);
- }
-
- /**
- * Adds an HTTP response rule. The response will be returned when the rule is matched.
- *
- * @param method method to match.
- * @param uri uri to match.
- * @param response response to return when a match is found.
- */
- public static void addHttpResponseRule(String method, String uri, HttpResponse response) {
- getFakeHttpLayer().addHttpResponseRule(method, uri, response);
- }
-
- /**
- * Adds an HTTP response rule with a default method of GET. The response will be returned when the rule is matched.
- *
- * @param uri uri to match.
- * @param response response to return when a match is found.
- */
- public static void addHttpResponseRule(String uri, HttpResponse response) {
- getFakeHttpLayer().addHttpResponseRule(uri, response);
- }
-
- /**
- * Adds an HTTP response rule. The response will be returned when the rule is matched.
- *
- * @param uri uri to match.
- * @param response response to return when a match is found.
- */
- public static void addHttpResponseRule(String uri, String response) {
- getFakeHttpLayer().addHttpResponseRule(uri, response);
- }
-
- /**
- * Adds an HTTP response rule. The response will be returned when the rule is matched.
- *
- * @param requestMatcher custom {@code RequestMatcher}.
- * @param response response to return when a match is found.
- */
- public static void addHttpResponseRule(RequestMatcher requestMatcher, HttpResponse response) {
- getFakeHttpLayer().addHttpResponseRule(requestMatcher, response);
- }
-
- /**
- * Adds an HTTP response rule. For each time the rule is matched, responses will be shifted
- * off the list and returned. When all responses have been given and the rule is matched again,
- * an exception will be thrown.
- *
- * @param requestMatcher custom {@code RequestMatcher}.
- * @param responses responses to return in order when a match is found.
- */
- public static void addHttpResponseRule(RequestMatcher requestMatcher, List<? extends HttpResponse> responses) {
- getFakeHttpLayer().addHttpResponseRule(requestMatcher, responses);
- }
-
- public static FakeHttpLayer getFakeHttpLayer() {
- return getShadowApplication().getFakeHttpLayer();
- }
-
- public static void setDefaultHttpResponse(int statusCode, String responseBody) {
- getFakeHttpLayer().setDefaultHttpResponse(statusCode, responseBody);
- }
-
- public static void setDefaultHttpResponse(HttpResponse defaultHttpResponse) {
- getFakeHttpLayer().setDefaultHttpResponse(defaultHttpResponse);
- }
-
- public static void clearHttpResponseRules() {
- getFakeHttpLayer().clearHttpResponseRules();
- }
-
- public static void clearPendingHttpResponses() {
- getFakeHttpLayer().clearPendingHttpResponses();
- }
-
- public static void pauseLooper(Looper looper) {
- ShadowLooper.pauseLooper(looper);
- }
-
- public static void unPauseLooper(Looper looper) {
- ShadowLooper.unPauseLooper(looper);
- }
-
- public static void pauseMainLooper() {
- ShadowLooper.pauseMainLooper();
- }
-
- public static void unPauseMainLooper() {
- ShadowLooper.unPauseMainLooper();
- }
-
- public static void idleMainLooper(long interval) {
- ShadowLooper.idleMainLooper(interval);
- }
-
- public static Scheduler getUiThreadScheduler() {
- return shadowOf(Looper.getMainLooper()).getScheduler();
- }
-
- public static Scheduler getBackgroundScheduler() {
- return getShadowApplication().getBackgroundScheduler();
- }
-
- public static ShadowApplication getShadowApplication() {
- return shadowOf(Robolectric.application);
- }
-
- public static void setDisplayMetricsDensity(float densityMultiplier) {
- shadowOf(getShadowApplication().getResources()).setDensity(densityMultiplier);
- }
-
- public static void setDefaultDisplay(Display display) {
- shadowOf(getShadowApplication().getResources()).setDisplay(display);
- }
-
- /**
- * Calls {@code performClick()} on a {@code View} after ensuring that it and its ancestors are visible and that it
- * is enabled.
- *
- * @param view the view to click on
- * @return true if {@code View.OnClickListener}s were found and fired, false otherwise.
- * @throws RuntimeException if the preconditions are not met.
- */
- public static boolean clickOn(View view) {
- return shadowOf(view).checkedPerformClick();
- }
-
- public static String visualize(View view) {
- Canvas canvas = new Canvas();
- view.draw(canvas);
- return shadowOf(canvas).getDescription();
- }
-
- public static String visualize(Canvas canvas) {
- return shadowOf(canvas).getDescription();
- }
-
- public static String visualize(Bitmap bitmap) {
- return shadowOf(bitmap).getDescription();
- }
-
- /**
- * Reflection helper methods.
- */
- public static class Reflection {
- public static <T> T newInstanceOf(Class<T> clazz) {
- return Robolectric.newInstanceOf(clazz);
- }
-
- public static Object newInstanceOf(String className) {
- return Robolectric.newInstanceOf(className);
- }
-
- public static void setFinalStaticField(Class classWhichContainsField, String fieldName, Object newValue) {
- try {
- Field field = classWhichContainsField.getDeclaredField(fieldName);
- field.setAccessible(true);
-
- Field modifiersField = Field.class.getDeclaredField("modifiers");
- modifiersField.setAccessible(true);
- modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
-
- field.set(null, newValue);
- } catch (NoSuchFieldException e) {
- throw new RuntimeException(e);
- } catch (IllegalAccessException e) {
- throw new RuntimeException(e);
- }
- }
- }
-
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/RobolectricConfig.java b/v1/src/main/java/com/xtremelabs/robolectric/RobolectricConfig.java
deleted file mode 100644
index ccbf71e78..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/RobolectricConfig.java
+++ /dev/null
@@ -1,350 +0,0 @@
-package com.xtremelabs.robolectric;
-
-import android.app.Application;
-import com.xtremelabs.robolectric.internal.ClassNameResolver;
-import org.w3c.dom.Document;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-
-import javax.xml.parsers.DocumentBuilder;
-import javax.xml.parsers.DocumentBuilderFactory;
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.util.ArrayList;
-import java.util.List;
-
-import static android.content.pm.ApplicationInfo.*;
-
-public class RobolectricConfig {
- private final File androidManifestFile;
- private final File resourceDirectory;
- private final File assetsDirectory;
- private String rClassName;
- private String packageName;
- private String processName;
- private String applicationName;
- private boolean manifestIsParsed = false;
- private int sdkVersion;
- private int minSdkVersion;
- private boolean sdkVersionSpecified = true;
- private boolean minSdkVersionSpecified = true;
- private int applicationFlags;
- private final List<ReceiverAndIntentFilter> receivers = new ArrayList<ReceiverAndIntentFilter>();
- private boolean strictI18n = false;
- private String locale = "";
- private String oldLocale = "";
-
- /**
- * Creates a Robolectric configuration using default Android files relative to the specified base directory.
- * <p/>
- * The manifest will be baseDir/AndroidManifest.xml, res will be baseDir/res, and assets in baseDir/assets.
- *
- * @param baseDir the base directory of your Android project
- */
- public RobolectricConfig(final File baseDir) {
- this(new File(baseDir, "AndroidManifest.xml"), new File(baseDir, "res"), new File(baseDir, "assets"));
- }
-
- public RobolectricConfig(final File androidManifestFile, final File resourceDirectory) {
- this(androidManifestFile, resourceDirectory, new File(resourceDirectory.getParent(), "assets"));
- }
-
- /**
- * Creates a Robolectric configuration using specified locations.
- *
- * @param androidManifestFile location of the AndroidManifest.xml file
- * @param resourceDirectory location of the res directory
- * @param assetsDirectory location of the assets directory
- */
- public RobolectricConfig(final File androidManifestFile, final File resourceDirectory, final File assetsDirectory) {
- this.androidManifestFile = androidManifestFile;
- this.resourceDirectory = resourceDirectory;
- this.assetsDirectory = assetsDirectory;
- }
-
- public String getRClassName() throws Exception {
- parseAndroidManifest();
- return rClassName;
- }
-
- public void validate() throws FileNotFoundException {
- if (!androidManifestFile.exists() || !androidManifestFile.isFile()) {
- throw new FileNotFoundException(androidManifestFile.getAbsolutePath() + " not found or not a file; it should point to your project's AndroidManifest.xml");
- }
-
- if (!getResourceDirectory().exists() || !getResourceDirectory().isDirectory()) {
- throw new FileNotFoundException(getResourceDirectory().getAbsolutePath() + " not found or not a directory; it should point to your project's res directory");
- }
- }
-
- private void parseAndroidManifest() {
- if (manifestIsParsed) {
- return;
- }
- DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
- try {
- DocumentBuilder db = dbf.newDocumentBuilder();
- Document manifestDocument = db.parse(androidManifestFile);
-
- packageName = getTagAttributeText(manifestDocument, "manifest", "package");
- rClassName = packageName + ".R";
- applicationName = getTagAttributeText(manifestDocument, "application", "android:name");
- Integer minSdkVer = getTagAttributeIntValue(manifestDocument, "uses-sdk", "android:minSdkVersion");
- Integer sdkVer = getTagAttributeIntValue(manifestDocument, "uses-sdk", "android:targetSdkVersion");
- if (minSdkVer == null) {
- minSdkVersion = 10;
- minSdkVersionSpecified = false;
- } else {
- minSdkVersion = minSdkVer;
- }
- if (sdkVer == null) {
- sdkVersion = 10;
- sdkVersionSpecified = false;
- } else {
- sdkVersion = sdkVer;
- }
-
- processName = getTagAttributeText(manifestDocument, "application", "android:process");
- if (processName == null) {
- processName = packageName;
- }
-
- parseApplicationFlags(manifestDocument);
- parseReceivers(manifestDocument, packageName);
- } catch (Exception ignored) {
- }
- manifestIsParsed = true;
- }
-
- private void parseReceivers(final Document manifestDocument, String packageName) {
- Node application = manifestDocument.getElementsByTagName("application").item(0);
- if (application == null) {
- return;
- }
- for (Node receiverNode : getChildrenTags(application, "receiver")) {
- Node namedItem = receiverNode.getAttributes().getNamedItem("android:name");
- if (namedItem == null) {
- continue;
- }
- String receiverName = namedItem.getTextContent();
- if (receiverName.startsWith(".")) {
- receiverName = packageName + receiverName;
- }
- for (Node intentFilterNode : getChildrenTags(receiverNode, "intent-filter")) {
- List<String> actions = new ArrayList<String>();
- for (Node actionNode : getChildrenTags(intentFilterNode, "action")) {
- Node nameNode = actionNode.getAttributes().getNamedItem("android:name");
- if (nameNode != null) {
- actions.add(nameNode.getTextContent());
- }
- }
- receivers.add(new ReceiverAndIntentFilter(receiverName, actions));
- }
- }
- }
-
- private List<Node> getChildrenTags(final Node node, final String tagName) {
- List<Node> children = new ArrayList<Node>();
- for (int i = 0; i < node.getChildNodes().getLength(); i++) {
- Node childNode = node.getChildNodes().item(i);
- if (childNode.getNodeName().equalsIgnoreCase(tagName)) {
- children.add(childNode);
- }
- }
- return children;
- }
-
- private void parseApplicationFlags(final Document manifestDocument) {
- applicationFlags = getApplicationFlag(manifestDocument, "android:allowBackup", FLAG_ALLOW_BACKUP);
- applicationFlags += getApplicationFlag(manifestDocument, "android:allowClearUserData", FLAG_ALLOW_CLEAR_USER_DATA);
- applicationFlags += getApplicationFlag(manifestDocument, "android:allowTaskReparenting", FLAG_ALLOW_TASK_REPARENTING);
- applicationFlags += getApplicationFlag(manifestDocument, "android:debuggable", FLAG_DEBUGGABLE);
- applicationFlags += getApplicationFlag(manifestDocument, "android:hasCode", FLAG_HAS_CODE);
- applicationFlags += getApplicationFlag(manifestDocument, "android:killAfterRestore", FLAG_KILL_AFTER_RESTORE);
- applicationFlags += getApplicationFlag(manifestDocument, "android:persistent", FLAG_PERSISTENT);
- applicationFlags += getApplicationFlag(manifestDocument, "android:resizeable", FLAG_RESIZEABLE_FOR_SCREENS);
- applicationFlags += getApplicationFlag(manifestDocument, "android:restoreAnyVersion", FLAG_RESTORE_ANY_VERSION);
- applicationFlags += getApplicationFlag(manifestDocument, "android:largeScreens", FLAG_SUPPORTS_LARGE_SCREENS);
- applicationFlags += getApplicationFlag(manifestDocument, "android:normalScreens", FLAG_SUPPORTS_NORMAL_SCREENS);
- applicationFlags += getApplicationFlag(manifestDocument, "android:anyDensity", FLAG_SUPPORTS_SCREEN_DENSITIES);
- applicationFlags += getApplicationFlag(manifestDocument, "android:smallScreens", FLAG_SUPPORTS_SMALL_SCREENS);
- applicationFlags += getApplicationFlag(manifestDocument, "android:testOnly", FLAG_TEST_ONLY);
- applicationFlags += getApplicationFlag(manifestDocument, "android:vmSafeMode", FLAG_VM_SAFE_MODE);
- }
-
- private int getApplicationFlag(final Document doc, final String attribute, final int attributeValue) {
- String flagString = getTagAttributeText(doc, "application", attribute);
- return "true".equalsIgnoreCase(flagString) ? attributeValue : 0;
- }
-
- private Integer getTagAttributeIntValue(final Document doc, final String tag, final String attribute) {
- return getTagAttributeIntValue(doc, tag, attribute, null);
- }
-
- private Integer getTagAttributeIntValue(final Document doc, final String tag, final String attribute, final Integer defaultValue) {
- String valueString = getTagAttributeText(doc, tag, attribute);
- if (valueString != null) {
- return Integer.parseInt(valueString);
- }
- return defaultValue;
- }
-
- public String getApplicationName() {
- parseAndroidManifest();
- return applicationName;
- }
-
- public String getPackageName() {
- parseAndroidManifest();
- return packageName;
- }
-
- public int getMinSdkVersion() {
- parseAndroidManifest();
- return minSdkVersion;
- }
-
- public int getSdkVersion() {
- parseAndroidManifest();
- return sdkVersion;
- }
-
- public int getApplicationFlags() {
- parseAndroidManifest();
- return applicationFlags;
- }
-
- public String getProcessName() {
- parseAndroidManifest();
- return processName;
- }
-
- public File getResourceDirectory() {
- return resourceDirectory;
- }
-
- public File getAssetsDirectory() {
- return assetsDirectory;
- }
-
- public int getReceiverCount() {
- parseAndroidManifest();
- return receivers.size();
- }
-
- public String getReceiverClassName(final int receiverIndex) {
- parseAndroidManifest();
- return receivers.get(receiverIndex).getBroadcastReceiverClassName();
- }
-
- public List<String> getReceiverIntentFilterActions(final int receiverIndex) {
- parseAndroidManifest();
- return receivers.get(receiverIndex).getIntentFilterActions();
- }
-
- public boolean getStrictI18n() {
- return strictI18n;
- }
-
- public void setStrictI18n(boolean strict) {
- strictI18n = strict;
- }
-
- public void setLocale( String locale ){
- this.oldLocale = this.locale;
- this.locale = locale;
- }
-
- public String getLocale() {
- return this.locale;
- }
-
- public boolean isLocaleChanged() {
- return !locale.equals( oldLocale );
- }
-
- private static String getTagAttributeText(final Document doc, final String tag, final String attribute) {
- NodeList elementsByTagName = doc.getElementsByTagName(tag);
- for (int i = 0; i < elementsByTagName.getLength(); ++i) {
- Node item = elementsByTagName.item(i);
- Node namedItem = item.getAttributes().getNamedItem(attribute);
- if (namedItem != null) {
- return namedItem.getTextContent();
- }
- }
- return null;
- }
-
- private static Application newApplicationInstance(final String packageName, final String applicationName) {
- Application application;
- try {
- Class<? extends Application> applicationClass =
- new ClassNameResolver<Application>(packageName, applicationName).resolve();
- application = applicationClass.newInstance();
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- return application;
- }
-
- @Override
- public boolean equals(final Object o) {
- if (this == o) {
- return true;
- }
- if (o == null || getClass() != o.getClass()) {
- return false;
- }
-
- RobolectricConfig that = (RobolectricConfig) o;
-
- if (androidManifestFile != null ? !androidManifestFile.equals(that.androidManifestFile) : that.androidManifestFile != null) {
- return false;
- }
- if (getAssetsDirectory() != null ? !getAssetsDirectory().equals(that.getAssetsDirectory()) : that.getAssetsDirectory() != null) {
- return false;
- }
- if (getResourceDirectory() != null ? !getResourceDirectory().equals(that.getResourceDirectory()) : that.getResourceDirectory() != null) {
- return false;
- }
-
- return true;
- }
-
- @Override
- public int hashCode() {
- int result = androidManifestFile != null ? androidManifestFile.hashCode() : 0;
- result = 31 * result + (getResourceDirectory() != null ? getResourceDirectory().hashCode() : 0);
- result = 31 * result + (getAssetsDirectory() != null ? getAssetsDirectory().hashCode() : 0);
- return result;
- }
-
- public int getRealSdkVersion() {
- parseAndroidManifest();
- if (sdkVersionSpecified) {
- return sdkVersion;
- }
- if (minSdkVersionSpecified) {
- return minSdkVersion;
- }
- return sdkVersion;
- }
-
- private static class ReceiverAndIntentFilter {
- private final List<String> intentFilterActions;
- private final String broadcastReceiverClassName;
-
- public ReceiverAndIntentFilter(final String broadcastReceiverClassName, final List<String> intentFilterActions) {
- this.broadcastReceiverClassName = broadcastReceiverClassName;
- this.intentFilterActions = intentFilterActions;
- }
-
- public String getBroadcastReceiverClassName() {
- return broadcastReceiverClassName;
- }
-
- public List<String> getIntentFilterActions() {
- return intentFilterActions;
- }
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/RobolectricConfigs.java b/v1/src/main/java/com/xtremelabs/robolectric/RobolectricConfigs.java
deleted file mode 100644
index e027d41f2..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/RobolectricConfigs.java
+++ /dev/null
@@ -1,14 +0,0 @@
-package com.xtremelabs.robolectric;
-
-import android.content.BroadcastReceiver;
-import android.content.Context;
-import android.content.Intent;
-
-public class RobolectricConfigs {
-
- public static class ConfigTestReceiver extends BroadcastReceiver {
- @Override
- public void onReceive(Context context, Intent intent) {
- }
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/RobolectricForMaps.java b/v1/src/main/java/com/xtremelabs/robolectric/RobolectricForMaps.java
deleted file mode 100644
index 7273657a4..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/RobolectricForMaps.java
+++ /dev/null
@@ -1,28 +0,0 @@
-package com.xtremelabs.robolectric;
-
-import com.google.android.maps.GeoPoint;
-import com.google.android.maps.ItemizedOverlay;
-import com.google.android.maps.MapController;
-import com.google.android.maps.MapView;
-import com.xtremelabs.robolectric.shadows.ShadowGeoPoint;
-import com.xtremelabs.robolectric.shadows.ShadowItemizedOverlay;
-import com.xtremelabs.robolectric.shadows.ShadowMapController;
-import com.xtremelabs.robolectric.shadows.ShadowMapView;
-
-public class RobolectricForMaps {
- public static ShadowGeoPoint shadowOf(GeoPoint instance) {
- return (ShadowGeoPoint) Robolectric.shadowOf_(instance);
- }
-
- public static ShadowMapView shadowOf(MapView instance) {
- return (ShadowMapView) Robolectric.shadowOf_(instance);
- }
-
- public static ShadowMapController shadowOf(MapController instance) {
- return (ShadowMapController) Robolectric.shadowOf_(instance);
- }
-
- public static ShadowItemizedOverlay shadowOf(ItemizedOverlay instance) {
- return (ShadowItemizedOverlay) Robolectric.shadowOf_(instance);
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/RobolectricShadowOfLevel9.java b/v1/src/main/java/com/xtremelabs/robolectric/RobolectricShadowOfLevel9.java
deleted file mode 100644
index 65f75c51f..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/RobolectricShadowOfLevel9.java
+++ /dev/null
@@ -1,24 +0,0 @@
-package com.xtremelabs.robolectric;
-
-import android.nfc.NdefMessage;
-import android.nfc.NdefRecord;
-import android.nfc.NfcAdapter;
-import com.xtremelabs.robolectric.shadows.ShadowNdefMessage;
-import com.xtremelabs.robolectric.shadows.ShadowNdefRecord;
-import com.xtremelabs.robolectric.shadows.ShadowNfcAdapter;
-
-public class RobolectricShadowOfLevel9 {
- private RobolectricShadowOfLevel9() { }
-
- public static ShadowNdefMessage shadowOf(NdefMessage instance) {
- return (ShadowNdefMessage) Robolectric.shadowOf_(instance);
- }
-
- public static ShadowNdefRecord shadowOf(NdefRecord instance) {
- return (ShadowNdefRecord) Robolectric.shadowOf_(instance);
- }
-
- public static ShadowNfcAdapter shadowOf(NfcAdapter instance) {
- return (ShadowNfcAdapter) Robolectric.shadowOf_(instance);
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/RobolectricTestRunner.java b/v1/src/main/java/com/xtremelabs/robolectric/RobolectricTestRunner.java
deleted file mode 100644
index 50fc33bf5..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/RobolectricTestRunner.java
+++ /dev/null
@@ -1,643 +0,0 @@
-package com.xtremelabs.robolectric;
-
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.PrintStream;
-import java.lang.annotation.Annotation;
-import java.lang.reflect.Constructor;
-import java.lang.reflect.Method;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.logging.Logger;
-
-import javassist.Loader;
-
-import javax.xml.parsers.DocumentBuilder;
-import javax.xml.parsers.DocumentBuilderFactory;
-import javax.xml.parsers.ParserConfigurationException;
-
-import org.junit.runners.BlockJUnit4ClassRunner;
-import org.junit.runners.model.FrameworkMethod;
-import org.junit.runners.model.InitializationError;
-import org.junit.runners.model.Statement;
-import org.w3c.dom.Document;
-import org.xml.sax.SAXException;
-
-import android.app.Application;
-import android.net.Uri__FromAndroid;
-
-import com.xtremelabs.robolectric.bytecode.ClassHandler;
-import com.xtremelabs.robolectric.bytecode.RobolectricClassLoader;
-import com.xtremelabs.robolectric.bytecode.ShadowWrangler;
-import com.xtremelabs.robolectric.internal.RealObject;
-import com.xtremelabs.robolectric.internal.RobolectricTestRunnerInterface;
-import com.xtremelabs.robolectric.res.ResourceLoader;
-import com.xtremelabs.robolectric.shadows.ShadowApplication;
-import com.xtremelabs.robolectric.shadows.ShadowLog;
-import com.xtremelabs.robolectric.util.DatabaseConfig;
-import com.xtremelabs.robolectric.util.DatabaseConfig.DatabaseMap;
-import com.xtremelabs.robolectric.util.DatabaseConfig.UsingDatabaseMap;
-import com.xtremelabs.robolectric.util.SQLiteMap;
-
-/**
- * Installs a {@link RobolectricClassLoader} and {@link com.xtremelabs.robolectric.res.ResourceLoader} in order to
- * provide a simulation of the Android runtime environment.
- */
-public class RobolectricTestRunner extends BlockJUnit4ClassRunner implements RobolectricTestRunnerInterface {
-
- private static final String MANIFEST_PATH_PROPERTY = "robolectric.path.manifest";
- private static final String RES_PATH_PROPERTY = "robolectric.path.res";
- private static final String ASSETS_PATH_PROPERTY = "robolectric.path.assets";
- private static final String DEFAULT_MANIFEST_PATH = "./AndroidManifest.xml";
- private static final String DEFAULT_RES_PATH = "./res";
- private static final String DEFAULT_ASSETS_PATH = "./assets";
-
- private static final Logger logger =
- Logger.getLogger(RobolectricTestRunner.class.getSimpleName());
-
- /** Instrument detector. We use it to check whether the current instance is instrumented. */
- private static InstrumentDetector instrumentDetector = InstrumentDetector.DEFAULT;
-
- private static RobolectricClassLoader defaultLoader;
- private static Map<RobolectricConfig, ResourceLoader> resourceLoaderForRootAndDirectory = new HashMap<RobolectricConfig, ResourceLoader>();
-
- // fields in the RobolectricTestRunner in the original ClassLoader
- private RobolectricClassLoader classLoader;
- private ClassHandler classHandler;
- private RobolectricTestRunnerInterface delegate;
- private DatabaseMap databaseMap;
-
- // fields in the RobolectricTestRunner in the instrumented ClassLoader
- protected RobolectricConfig robolectricConfig;
-
- private static RobolectricClassLoader getDefaultLoader() {
- if (defaultLoader == null) {
- defaultLoader = new RobolectricClassLoader(ShadowWrangler.getInstance());
- }
- return defaultLoader;
- }
-
- public static void setInstrumentDetector(final InstrumentDetector detector) {
- instrumentDetector = detector;
- }
-
- public static void setDefaultLoader(Loader robolectricClassLoader) {
- //used by the RoboSpecs project to allow for mixed scala\java tests to be run with Maven Surefire (see the RoboSpecs project on github)
- if (defaultLoader == null) {
- defaultLoader = (RobolectricClassLoader)robolectricClassLoader;
- } else throw new RuntimeException("You may not set the default robolectricClassLoader unless it is null!");
- }
-
- /**
- * Call this if you would like Robolectric to rewrite additional classes and turn them
- * into "do nothing" classes which proxy all method calls to shadow classes, just like it does
- * with the android classes by default.
- *
- * @param classOrPackageToBeInstrumented fully-qualified class or package name
- */
- protected static void addClassOrPackageToInstrument(String classOrPackageToBeInstrumented) {
- if (!isInstrumented()) {
- defaultLoader.addCustomShadowClass(classOrPackageToBeInstrumented);
- }
- }
-
- /**
- * Creates a runner to run {@code testClass}. Looks in your working directory for your AndroidManifest.xml file
- * and res directory.
- *
- * @param testClass the test class to be run
- * @throws InitializationError if junit says so
- */
- public RobolectricTestRunner(final Class<?> testClass) throws InitializationError {
- this(testClass, new RobolectricConfig(
- new File(getSystemProperty(MANIFEST_PATH_PROPERTY, DEFAULT_MANIFEST_PATH)),
- new File(getSystemProperty(RES_PATH_PROPERTY, DEFAULT_RES_PATH)),
- new File(getSystemProperty(ASSETS_PATH_PROPERTY, DEFAULT_ASSETS_PATH))));
- }
-
- /**
- * Creates a runner to run {@code testClass}. Looks in your working directory for your AndroidManifest.xml file
- * and res directory.
- *
- * @param testClass the test class to be run
- * @param classLoader a custom RobolectricClassLoader to be used.
- * @throws InitializationError if junit says so
- */
- public RobolectricTestRunner(final Class<?> testClass, RobolectricClassLoader classLoader)
- throws InitializationError {
- this(testClass,
- isInstrumented() ? null : ShadowWrangler.getInstance(),
- isInstrumented() ? null : classLoader,
- new RobolectricConfig(
- new File(getSystemProperty(MANIFEST_PATH_PROPERTY, DEFAULT_MANIFEST_PATH)),
- new File(getSystemProperty(RES_PATH_PROPERTY, DEFAULT_RES_PATH)),
- new File(getSystemProperty(ASSETS_PATH_PROPERTY, DEFAULT_ASSETS_PATH))));
- }
-
- /**
- * Call this constructor in subclasses in order to specify non-default configuration (e.g. location of the
- * AndroidManifest.xml file and resource directory).
- *
- * @param testClass the test class to be run
- * @param robolectricConfig the configuration data
- * @throws InitializationError if junit says so
- */
- protected RobolectricTestRunner(final Class<?> testClass, final RobolectricConfig robolectricConfig)
- throws InitializationError {
- this(testClass,
- isInstrumented() ? null : ShadowWrangler.getInstance(),
- isInstrumented() ? null : getDefaultLoader(),
- robolectricConfig, new SQLiteMap());
- }
-
- /**
- * Call this constructor in subclasses in order to specify non-default configuration (e.g. location of the
- * AndroidManifest.xml file, resource directory, and DatabaseMap).
- *
- * @param testClass the test class to be run
- * @param robolectricConfig the configuration data
- * @param databaseMap the database mapping
- * @throws InitializationError if junit says so
- */
- protected RobolectricTestRunner(Class<?> testClass, RobolectricConfig robolectricConfig, DatabaseMap databaseMap)
- throws InitializationError {
- this(testClass,
- isInstrumented() ? null : ShadowWrangler.getInstance(),
- isInstrumented() ? null : getDefaultLoader(),
- robolectricConfig, databaseMap);
- }
-
- /**
- * Call this constructor in subclasses in order to specify the project root directory.
- *
- * @param testClass the test class to be run
- * @param androidProjectRoot the directory containing your AndroidManifest.xml file and res dir
- * @throws InitializationError if the test class is malformed
- */
- public RobolectricTestRunner(final Class<?> testClass, final File androidProjectRoot) throws InitializationError {
- this(testClass, new RobolectricConfig(androidProjectRoot));
- }
-
- /**
- * Call this constructor in subclasses in order to specify the project root directory.
- *
- * @param testClass the test class to be run
- * @param androidProjectRoot the directory containing your AndroidManifest.xml file and res dir
- * @throws InitializationError if junit says so
- * @deprecated Use {@link #RobolectricTestRunner(Class, File)} instead.
- */
- @Deprecated
- public RobolectricTestRunner(final Class<?> testClass, final String androidProjectRoot) throws InitializationError {
- this(testClass, new RobolectricConfig(new File(androidProjectRoot)));
- }
-
- /**
- * Call this constructor in subclasses in order to specify the location of the AndroidManifest.xml file and the
- * resource directory. The #androidManifestPath is used to locate the AndroidManifest.xml file which, in turn,
- * contains package name for the {@code R} class which contains the identifiers for all of the resources. The
- * resource directory is where the resource loader will look for resources to load.
- *
- * @param testClass the test class to be run
- * @param androidManifestPath the AndroidManifest.xml file
- * @param resourceDirectory the directory containing the project's resources
- * @throws InitializationError if junit says so
- */
- protected RobolectricTestRunner(final Class<?> testClass, final File androidManifestPath, final File resourceDirectory)
- throws InitializationError {
- this(testClass, new RobolectricConfig(androidManifestPath, resourceDirectory));
- }
-
- /**
- * Call this constructor in subclasses in order to specify the location of the AndroidManifest.xml file and the
- * resource directory. The #androidManifestPath is used to locate the AndroidManifest.xml file which, in turn,
- * contains package name for the {@code R} class which contains the identifiers for all of the resources. The
- * resource directory is where the resource loader will look for resources to load.
- *
- * @param testClass the test class to be run
- * @param androidManifestPath the relative path to the AndroidManifest.xml file
- * @param resourceDirectory the relative path to the directory containing the project's resources
- * @throws InitializationError if junit says so
- * @deprecated Use {@link #RobolectricTestRunner(Class, File, File)} instead.
- */
- @Deprecated
- protected RobolectricTestRunner(final Class<?> testClass, final String androidManifestPath, final String resourceDirectory)
- throws InitializationError {
- this(testClass, new RobolectricConfig(new File(androidManifestPath), new File(resourceDirectory)));
- }
-
- protected RobolectricTestRunner(Class<?> testClass, ClassHandler classHandler, RobolectricClassLoader classLoader, RobolectricConfig robolectricConfig) throws InitializationError {
- this(testClass, classHandler, classLoader, robolectricConfig, new SQLiteMap());
- }
-
-
- /**
- * This is not the constructor you are looking for... probably. This constructor creates a bridge between the test
- * runner called by JUnit and a second instance of the test runner that is loaded via the instrumenting class
- * loader. This instrumented instance of the test runner, along with the instrumented instance of the actual test,
- * provides access to Robolectric's features and the un-instrumented instance of the test runner delegates most of
- * the interesting test runner behavior to it. Providing your own class handler and class loader here in order to
- * get different functionality is a difficult and dangerous project. If you need to customize the project root and
- * resource directory, use {@link #RobolectricTestRunner(Class, String, String)}. For other extensions, consider
- * creating a subclass and overriding the documented methods of this class.
- *
- * @param testClass the test class to be run
- * @param classHandler the {@link ClassHandler} to use to in shadow delegation
- * @param classLoader the {@link RobolectricClassLoader}
- * @param robolectricConfig the configuration
- * @throws InitializationError if junit says so
- */
- protected RobolectricTestRunner(final Class<?> testClass, final ClassHandler classHandler, final RobolectricClassLoader classLoader, final RobolectricConfig robolectricConfig, final DatabaseMap map) throws InitializationError {
- super(isInstrumented() ? testClass
- : ensureClassLoaderNotNull(classLoader).bootstrap(testClass));
-
- if (!isInstrumented()) {
- this.classHandler = classHandler;
- this.classLoader = ensureClassLoaderNotNull(classLoader);
- this.robolectricConfig = robolectricConfig;
- this.databaseMap = setupDatabaseMap(testClass, map);
-
- Thread.currentThread().setContextClassLoader(classLoader);
-
- delegateLoadingOf(Uri__FromAndroid.class.getName());
- delegateLoadingOf(RobolectricTestRunnerInterface.class.getName());
- delegateLoadingOf(RealObject.class.getName());
- delegateLoadingOf(ShadowWrangler.class.getName());
- delegateLoadingOf(RobolectricConfig.class.getName());
- delegateLoadingOf(DatabaseMap.class.getName());
- delegateLoadingOf(android.R.class.getName());
-
- Class<?> delegateClass = classLoader.bootstrap(this.getClass());
- try {
- Constructor<?> constructorForDelegate = delegateClass.getConstructor(Class.class);
- this.delegate = (RobolectricTestRunnerInterface) constructorForDelegate.newInstance(classLoader.bootstrap(testClass));
- this.delegate.setRobolectricConfig(robolectricConfig);
- this.delegate.setDatabaseMap(databaseMap);
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
- }
-
- private static RobolectricClassLoader ensureClassLoaderNotNull(
- RobolectricClassLoader classLoader) {
- return classLoader == null ? getDefaultLoader() : classLoader;
- }
-
- protected static boolean isInstrumented() {
- return instrumentDetector.isInstrumented();
- }
-
- /**
- * Only used when creating the delegate instance within the instrumented ClassLoader.
- * <p/>
- * This is not the constructor you are looking for.
- */
- @SuppressWarnings({"UnusedDeclaration", "JavaDoc"})
- protected RobolectricTestRunner(final Class<?> testClass, final ClassHandler classHandler, final RobolectricConfig robolectricConfig) throws InitializationError {
- super(testClass);
- this.classHandler = classHandler;
- this.robolectricConfig = robolectricConfig;
- }
-
- /** @deprecated use {@link Robolectric.Reflection#setFinalStaticField(Class, String, Object)} */
- @Deprecated
- public static void setStaticValue(Class<?> clazz, String fieldName, Object value) {
- Robolectric.Reflection.setFinalStaticField(clazz, fieldName, value);
- }
-
- protected void delegateLoadingOf(final String className) {
- classLoader.delegateLoadingOf(className);
- }
-
- @Override protected Statement methodBlock(final FrameworkMethod method) {
- setupI18nStrictState(method.getMethod(), robolectricConfig);
- lookForLocaleAnnotation( method.getMethod(), robolectricConfig );
-
- if (classHandler != null) {
- classHandler.configure(robolectricConfig);
- classHandler.beforeTest();
- }
- delegate.internalBeforeTest(method.getMethod());
-
- final Statement statement = super.methodBlock(method);
- return new Statement() {
- @Override public void evaluate() throws Throwable {
- // todo: this try/finally probably isn't right -- should mimic RunAfters? [xw]
- try {
- statement.evaluate();
- } finally {
- delegate.internalAfterTest(method.getMethod());
- if (classHandler != null) {
- classHandler.afterTest();
- }
- }
- }
- };
- }
-
- /*
- * Called before each test method is run. Sets up the simulation of the Android runtime environment.
- */
- @Override public void internalBeforeTest(final Method method) {
- setupApplicationState(robolectricConfig);
-
- beforeTest(method);
- }
-
- @Override public void internalAfterTest(final Method method) {
- afterTest(method);
- }
-
- @Override public void setRobolectricConfig(final RobolectricConfig robolectricConfig) {
- this.robolectricConfig = robolectricConfig;
- }
-
- /**
- * Called before each test method is run.
- *
- * @param method the test method about to be run
- */
- public void beforeTest(final Method method) {
- }
-
- /**
- * Called after each test method is run.
- *
- * @param method the test method that just ran.
- */
- public void afterTest(final Method method) {
- }
-
- /**
- * You probably don't want to override this method. Override #prepareTest(Object) instead.
- *
- * @see BlockJUnit4ClassRunner#createTest()
- */
- @Override
- public Object createTest() throws Exception {
- if (delegate != null) {
- return delegate.createTest();
- } else {
- Object test = super.createTest();
- prepareTest(test);
- return test;
- }
- }
-
- public void prepareTest(final Object test) {
- }
-
- public void setupApplicationState(final RobolectricConfig robolectricConfig) {
- setupLogging();
-
- ResourceLoader resourceLoader = createResourceLoader(robolectricConfig );
-
- Robolectric.bindDefaultShadowClasses();
- bindShadowClasses();
-
- resourceLoader.setLayoutQualifierSearchPath();
- Robolectric.resetStaticState();
- resetStaticState();
-
- DatabaseConfig.setDatabaseMap(this.databaseMap);//Set static DatabaseMap in DBConfig
-
- Robolectric.application = ShadowApplication.bind(createApplication(), resourceLoader);
- }
-
- /**
- * Override this method to bind your own shadow classes
- */
- protected void bindShadowClasses() {
- }
-
- /**
- * Override this method to reset the state of static members before each test.
- */
- protected void resetStaticState() {
- }
-
- private static String getSystemProperty(String propertyName, String defaultValue) {
- String property = System.getProperty(propertyName);
- if (property == null) {
- property = defaultValue;
- logger.info("No system property " + propertyName + " found, default to "
- + defaultValue);
- }
- return property;
- }
-
- /**
- * Sets Robolectric config to determine if Robolectric should blacklist API calls that are not
- * I18N/L10N-safe.
- * <p/>
- * I18n-strict mode affects suitably annotated shadow methods. Robolectric will throw exceptions
- * if these methods are invoked by application code. Additionally, Robolectric's ResourceLoader
- * will throw exceptions if layout resources use bare string literals instead of string resource IDs.
- * <p/>
- * To enable or disable i18n-strict mode for specific test cases, annotate them with
- * {@link com.xtremelabs.robolectric.annotation.EnableStrictI18n} or
- * {@link com.xtremelabs.robolectric.annotation.DisableStrictI18n}.
- * <p/>
- *
- * By default, I18n-strict mode is disabled.
- *
- * @param method
- * @param robolectricConfig
- */
- private void setupI18nStrictState(Method method, RobolectricConfig robolectricConfig) {
- // Global
- boolean strictI18n = globalI18nStrictEnabled();
-
- // Test case class
- Annotation[] annos = method.getDeclaringClass().getAnnotations();
- strictI18n = lookForI18nAnnotations(strictI18n, annos);
-
- // Test case methods
- annos = method.getAnnotations();
- strictI18n = lookForI18nAnnotations(strictI18n, annos);
-
- robolectricConfig.setStrictI18n(strictI18n);
- }
-
- /**
- * Default implementation of global switch for i18n-strict mode.
- * To enable i18n-strict mode globally, set the system property
- * "robolectric.strictI18n" to true. This can be done via java
- * system properties in either Ant or Maven.
- * <p/>
- * Subclasses can override this method and establish their own policy
- * for enabling i18n-strict mode.
- *
- * @return
- */
- protected boolean globalI18nStrictEnabled() {
- return Boolean.valueOf(System.getProperty("robolectric.strictI18n"));
- }
-
- /**
- * As test methods are loaded by the delegate's class loader, the normal
- * method#isAnnotationPresent test fails. Look at string versions of the
- * annotation names to test for their presence.
- *
- * @param strictI18n
- * @param annos
- * @return
- */
- private boolean lookForI18nAnnotations(boolean strictI18n, Annotation[] annos) {
- for ( int i = 0; i < annos.length; i++ ) {
- String name = annos[i].annotationType().getName();
- if (name.equals("com.xtremelabs.robolectric.annotation.EnableStrictI18n")) {
- strictI18n = true;
- break;
- }
- if (name.equals("com.xtremelabs.robolectric.annotation.DisableStrictI18n")) {
- strictI18n = false;
- break;
- }
- }
- return strictI18n;
- }
-
- private void lookForLocaleAnnotation( Method method, RobolectricConfig robolectricConfig ){
- String locale = "";
- // TODO: there are maybe better implementation for getAnnotation
- // Have tried to use several other simple ways, but failed.
- Annotation[] annos = method.getDeclaredAnnotations();
- for( Annotation anno: annos ){
-
- if( anno.annotationType().getName().equals( "com.xtremelabs.robolectric.annotation.Values" )){
- String annotationString = anno.toString();
- int startIndex = annotationString.indexOf( '=' );
- int endIndex = annotationString.indexOf( ')' );
-
- if( startIndex < 0 || endIndex < 0 ){ return; }
-
- locale = annotationString.substring( startIndex + 1, endIndex );
- }
- }
-
- robolectricConfig.setLocale( locale );
- }
-
- private void setupLogging() {
- String logging = System.getProperty("robolectric.logging");
- if (logging != null && ShadowLog.stream == null) {
- PrintStream stream = null;
- if ("stdout".equalsIgnoreCase(logging)) {
- stream = System.out;
- } else if ("stderr".equalsIgnoreCase(logging)) {
- stream = System.err;
- } else {
- try {
- final PrintStream file = new PrintStream(new FileOutputStream(logging));
- stream = file;
- Runtime.getRuntime().addShutdownHook(new Thread() {
- @Override public void run() {
- try { file.close(); } catch (Exception ignored) { }
- }
- });
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- ShadowLog.stream = stream;
- }
- }
-
- /**
- * Override this method if you want to provide your own implementation of Application.
- * <p/>
- * This method attempts to instantiate an application instance as specified by the AndroidManifest.xml.
- *
- * @return An instance of the Application class specified by the ApplicationManifest.xml or an instance of
- * Application if not specified.
- */
- protected Application createApplication() {
- return new ApplicationResolver(robolectricConfig).resolveApplication();
- }
-
- private ResourceLoader createResourceLoader(final RobolectricConfig robolectricConfig) {
- ResourceLoader resourceLoader = resourceLoaderForRootAndDirectory.get(robolectricConfig);
- // When locale has changed, reload the resource files.
- if (resourceLoader == null || robolectricConfig.isLocaleChanged() ) {
- try {
- robolectricConfig.validate();
-
- String rClassName = robolectricConfig.getRClassName();
- Class rClass;
- try {
- rClass = Class.forName(rClassName);
- } catch (ClassNotFoundException e) {
- rClass = null;
- }
- resourceLoader = new ResourceLoader(robolectricConfig.getRealSdkVersion(), rClass, robolectricConfig.getResourceDirectory(), robolectricConfig.getAssetsDirectory(), robolectricConfig.getLocale() );
- resourceLoaderForRootAndDirectory.put(robolectricConfig, resourceLoader);
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
-
- resourceLoader.setStrictI18n(robolectricConfig.getStrictI18n());
- return resourceLoader;
- }
-
- private String findResourcePackageName(final File projectManifestFile) throws ParserConfigurationException, IOException, SAXException {
- DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
- DocumentBuilder db = dbf.newDocumentBuilder();
- Document doc = db.parse(projectManifestFile);
-
- String projectPackage = doc.getElementsByTagName("manifest").item(0).getAttributes().getNamedItem("package").getTextContent();
-
- return projectPackage + ".R";
- }
-
- /*
- * Specifies what database to use for testing (ex: H2 or Sqlite),
- * this will load H2 by default, the SQLite TestRunner version will override this.
- */
- protected DatabaseMap setupDatabaseMap(Class<?> testClass, DatabaseMap map) {
- DatabaseMap dbMap = map;
-
- if (testClass.isAnnotationPresent(UsingDatabaseMap.class)) {
- UsingDatabaseMap usingMap = testClass.getAnnotation(UsingDatabaseMap.class);
- if(usingMap.value()!=null){
- dbMap = Robolectric.newInstanceOf(usingMap.value());
- } else {
- if (dbMap==null)
- throw new RuntimeException("UsingDatabaseMap annotation value must provide a class implementing DatabaseMap");
- }
- }
- return dbMap;
- }
-
- public DatabaseMap getDatabaseMap() {
- return databaseMap;
- }
-
- @Override
- public void setDatabaseMap(DatabaseMap databaseMap) {
- this.databaseMap = databaseMap;
- }
-
- /**
- * Detects whether current instance is already instrumented.
- */
- public interface InstrumentDetector {
-
- /** Default detector. */
- InstrumentDetector DEFAULT = new InstrumentDetector() {
- @Override
- public boolean isInstrumented() {
- return RobolectricTestRunner.class.getClassLoader().getClass().getName().contains(RobolectricClassLoader.class.getName());
- }
- };
-
- /**
- * @return true if current instance is already instrumented
- */
- boolean isInstrumented();
-
- }
-
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/ShadowScrollView.java b/v1/src/main/java/com/xtremelabs/robolectric/ShadowScrollView.java
deleted file mode 100644
index 3c69d0e16..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/ShadowScrollView.java
+++ /dev/null
@@ -1,14 +0,0 @@
-package com.xtremelabs.robolectric;
-
-import android.widget.ScrollView;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.shadows.ShadowFrameLayout;
-
-@Implements(ScrollView.class)
-public class ShadowScrollView extends ShadowFrameLayout {
- @Implementation
- public void smoothScrollTo(int x, int y) {
- scrollTo(x, y);
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/annotation/DisableStrictI18n.java b/v1/src/main/java/com/xtremelabs/robolectric/annotation/DisableStrictI18n.java
deleted file mode 100644
index ca6c55739..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/annotation/DisableStrictI18n.java
+++ /dev/null
@@ -1,13 +0,0 @@
-package com.xtremelabs.robolectric.annotation;
-
-/**
- * Indicates that a JUnit test class or method should not be checked for I18N/L10N-safety
- * under any circumstances.
- *
- * @see EnableStrictI18n
- */
-@java.lang.annotation.Documented
-@java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
-@java.lang.annotation.Target({java.lang.annotation.ElementType.TYPE, java.lang.annotation.ElementType.METHOD})
-public @interface DisableStrictI18n {
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/annotation/EnableStrictI18n.java b/v1/src/main/java/com/xtremelabs/robolectric/annotation/EnableStrictI18n.java
deleted file mode 100644
index f9c21837c..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/annotation/EnableStrictI18n.java
+++ /dev/null
@@ -1,12 +0,0 @@
-package com.xtremelabs.robolectric.annotation;
-
-/**
- * Indicates that a JUnit test class or method should be checked for I18N/L10N-safety.
- *
- * @see DisableStrictI18n
- */
-@java.lang.annotation.Documented
-@java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
-@java.lang.annotation.Target({java.lang.annotation.ElementType.TYPE,java.lang.annotation.ElementType.METHOD})
-public @interface EnableStrictI18n {
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/annotation/Values.java b/v1/src/main/java/com/xtremelabs/robolectric/annotation/Values.java
deleted file mode 100644
index c5923049f..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/annotation/Values.java
+++ /dev/null
@@ -1,12 +0,0 @@
-package com.xtremelabs.robolectric.annotation;
-
-/**
- * Indicate that roboletric should look for values that is specific for the locale
- *
- */
-@java.lang.annotation.Documented
-@java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
-@java.lang.annotation.Target(java.lang.annotation.ElementType.METHOD)
-public @interface Values {
- String locale();
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/bytecode/AndroidTranslator.java b/v1/src/main/java/com/xtremelabs/robolectric/bytecode/AndroidTranslator.java
deleted file mode 100644
index e55f76fbc..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/bytecode/AndroidTranslator.java
+++ /dev/null
@@ -1,499 +0,0 @@
-package com.xtremelabs.robolectric.bytecode;
-
-import android.net.Uri;
-import com.xtremelabs.robolectric.internal.DoNotInstrument;
-import com.xtremelabs.robolectric.internal.Instrument;
-import javassist.*;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.List;
-
-@SuppressWarnings({"UnusedDeclaration"})
-public class AndroidTranslator implements Translator {
- /**
- * IMPORTANT -- increment this number when the bytecode generated for modified classes changes
- * so the cache file can be invalidated.
- */
- public static final int CACHE_VERSION = 21;
-
- private static final List<ClassHandler> CLASS_HANDLERS = new ArrayList<ClassHandler>();
-
- private ClassHandler classHandler;
- private ClassCache classCache;
- private final List<String> instrumentingList = new ArrayList<String>();
- private final List<String> instrumentingExcludeList = new ArrayList<String>();
-
- public AndroidTranslator(ClassHandler classHandler, ClassCache classCache) {
- this.classHandler = classHandler;
- this.classCache = classCache;
-
- // Initialize lists
- instrumentingList.add("android.");
- instrumentingList.add("com.google.android.maps");
- instrumentingList.add("org.apache.http.impl.client.DefaultRequestDirector");
-
- instrumentingExcludeList.add("android.support.v4.app.NotificationCompat");
- instrumentingExcludeList.add("android.support.v4.content.LocalBroadcastManager");
- instrumentingExcludeList.add("android.support.v4.util.LruCache");
- }
-
- public AndroidTranslator(ClassHandler classHandler, ClassCache classCache, List<String> customShadowClassNames) {
- this(classHandler, classCache);
- if (customShadowClassNames != null && !customShadowClassNames.isEmpty()) {
- instrumentingList.addAll(customShadowClassNames);
- }
- }
-
- public void addCustomShadowClass(String customShadowClassName) {
- if (!instrumentingList.contains(customShadowClassName)) {
- instrumentingList.add(customShadowClassName);
- }
- }
-
- public static ClassHandler getClassHandler(int index) {
- return CLASS_HANDLERS.get(index);
- }
-
- @Override
- public void start(ClassPool classPool) throws NotFoundException, CannotCompileException {
- injectClassHandlerToInstrumentedClasses(classPool);
- }
-
- private void injectClassHandlerToInstrumentedClasses(ClassPool classPool) throws NotFoundException, CannotCompileException {
- int index;
- synchronized (CLASS_HANDLERS) {
- CLASS_HANDLERS.add(classHandler);
- index = CLASS_HANDLERS.size() - 1;
- }
-
- CtClass robolectricInternalsCtClass = classPool.get(RobolectricInternals.class.getName());
- robolectricInternalsCtClass.setModifiers(Modifier.PUBLIC);
-
- robolectricInternalsCtClass.getClassInitializer().insertBefore("{\n" +
- "classHandler = " + AndroidTranslator.class.getName() + ".getClassHandler(" + index + ");\n" +
- "}");
- }
-
- @Override
- public void onLoad(ClassPool classPool, String className) throws NotFoundException, CannotCompileException {
- if (classCache.isWriting()) {
- throw new IllegalStateException("shouldn't be modifying bytecode after we've started writing cache! class=" + className);
- }
-
- if (classHasFromAndroidEquivalent(className)) {
- replaceClassWithFromAndroidEquivalent(classPool, className);
- return;
- }
-
- CtClass ctClass;
- try {
- ctClass = classPool.get(className);
- } catch (NotFoundException e) {
- throw new IgnorableClassNotFoundException(e);
- }
-
- if (shouldInstrument(ctClass)) {
- int modifiers = ctClass.getModifiers();
- if (Modifier.isFinal(modifiers)) {
- ctClass.setModifiers(modifiers & ~Modifier.FINAL);
- }
-
- classHandler.instrument(ctClass);
-
- fixConstructors(ctClass);
- fixMethods(ctClass);
-
- try {
- classCache.addClass(className, ctClass.toBytecode());
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
- }
-
- /* package */ boolean shouldInstrument(CtClass ctClass) {
- if (ctClass.hasAnnotation(Instrument.class)) {
- return true;
- } else if (ctClass.isInterface() || ctClass.hasAnnotation(DoNotInstrument.class)) {
- return false;
- } else {
- for (String klassName : instrumentingExcludeList) {
- if (ctClass.getName().startsWith(klassName)) {
- return false;
- }
- }
- for (String klassName : instrumentingList) {
- if (ctClass.getName().startsWith(klassName)) {
- return true;
- }
- }
- return false;
- }
- }
-
- private boolean classHasFromAndroidEquivalent(String className) {
- return className.startsWith(Uri.class.getName());
- }
-
- private void replaceClassWithFromAndroidEquivalent(ClassPool classPool, String className) throws NotFoundException {
- FromAndroidClassNameParts classNameParts = new FromAndroidClassNameParts(className);
- if (classNameParts.isFromAndroid()) return;
-
- String from = classNameParts.getNameWithFromAndroid();
- CtClass ctClass = classPool.getAndRename(from, className);
-
- ClassMap map = new ClassMap() {
- @Override
- public Object get(Object jvmClassName) {
- FromAndroidClassNameParts classNameParts = new FromAndroidClassNameParts(jvmClassName.toString());
- if (classNameParts.isFromAndroid()) {
- return classNameParts.getNameWithoutFromAndroid();
- } else {
- return jvmClassName;
- }
- }
- };
- ctClass.replaceClassName(map);
- }
-
- class FromAndroidClassNameParts {
- private static final String TOKEN = "__FromAndroid";
-
- private String prefix;
- private String suffix;
-
- FromAndroidClassNameParts(String name) {
- int dollarIndex = name.indexOf("$");
- prefix = name;
- suffix = "";
- if (dollarIndex > -1) {
- prefix = name.substring(0, dollarIndex);
- suffix = name.substring(dollarIndex);
- }
- }
-
- public boolean isFromAndroid() {
- return prefix.endsWith(TOKEN);
- }
-
- public String getNameWithFromAndroid() {
- return prefix + TOKEN + suffix;
- }
-
- public String getNameWithoutFromAndroid() {
- return prefix.replace(TOKEN, "") + suffix;
- }
- }
-
- private void addBypassShadowField(CtClass ctClass, String fieldName) {
- try {
- try {
- ctClass.getField(fieldName);
- } catch (NotFoundException e) {
- CtField field = new CtField(CtClass.booleanType, fieldName, ctClass);
- field.setModifiers(java.lang.reflect.Modifier.PUBLIC | java.lang.reflect.Modifier.STATIC);
- ctClass.addField(field);
- }
- } catch (CannotCompileException e) {
- throw new RuntimeException(e);
- }
- }
-
- private void fixConstructors(CtClass ctClass) throws CannotCompileException, NotFoundException {
-
- if (ctClass.isEnum()) {
- // skip enum constructors because they are not stubs in android.jar
- return;
- }
-
- boolean hasDefault = false;
-
- for (CtConstructor ctConstructor : ctClass.getDeclaredConstructors()) {
- try {
- fixConstructor(ctClass, hasDefault, ctConstructor);
-
- if (ctConstructor.getParameterTypes().length == 0) {
- hasDefault = true;
- }
- } catch (Exception e) {
- throw new RuntimeException("problem instrumenting " + ctConstructor, e);
- }
- }
-
- if (!hasDefault) {
- String methodBody = generateConstructorBody(ctClass, new CtClass[0]);
- ctClass.addConstructor(CtNewConstructor.make(new CtClass[0], new CtClass[0], "{\n" + methodBody + "}\n", ctClass));
- }
- }
-
- private boolean fixConstructor(CtClass ctClass, boolean needsDefault, CtConstructor ctConstructor) throws NotFoundException, CannotCompileException {
- String methodBody = generateConstructorBody(ctClass, ctConstructor.getParameterTypes());
- ctConstructor.setBody("{\n" + methodBody + "}\n");
- return needsDefault;
- }
-
- private String generateConstructorBody(CtClass ctClass, CtClass[] parameterTypes) throws NotFoundException {
- return generateMethodBody(ctClass,
- new CtMethod(CtClass.voidType, "<init>", parameterTypes, ctClass),
- CtClass.voidType,
- Type.VOID,
- false,
- false);
- }
-
- private void fixMethods(CtClass ctClass) throws NotFoundException, CannotCompileException {
- for (CtMethod ctMethod : ctClass.getDeclaredMethods()) {
- fixMethod(ctClass, ctMethod, true);
- }
- CtMethod equalsMethod = ctClass.getMethod("equals", "(Ljava/lang/Object;)Z");
- CtMethod hashCodeMethod = ctClass.getMethod("hashCode", "()I");
- CtMethod toStringMethod = ctClass.getMethod("toString", "()Ljava/lang/String;");
-
- fixMethod(ctClass, equalsMethod, false);
- fixMethod(ctClass, hashCodeMethod, false);
- fixMethod(ctClass, toStringMethod, false);
- }
-
- private String describe(CtMethod ctMethod) throws NotFoundException {
- return Modifier.toString(ctMethod.getModifiers()) + " " + ctMethod.getReturnType().getSimpleName() + " " + ctMethod.getLongName();
- }
-
- private void fixMethod(CtClass ctClass, CtMethod ctMethod, boolean wasFoundInClass) throws NotFoundException {
- String describeBefore = describe(ctMethod);
- try {
- CtClass declaringClass = ctMethod.getDeclaringClass();
- int originalModifiers = ctMethod.getModifiers();
-
- boolean wasNative = Modifier.isNative(originalModifiers);
- boolean wasFinal = Modifier.isFinal(originalModifiers);
- boolean wasAbstract = Modifier.isAbstract(originalModifiers);
- boolean wasDeclaredInClass = ctClass == declaringClass;
-
- if (wasFinal && ctClass.isEnum()) {
- return;
- }
-
- int newModifiers = originalModifiers;
- if (wasNative) {
- newModifiers = Modifier.clear(newModifiers, Modifier.NATIVE);
- }
- if (wasFinal) {
- newModifiers = Modifier.clear(newModifiers, Modifier.FINAL);
- }
- if (wasFoundInClass) {
- ctMethod.setModifiers(newModifiers);
- }
-
- CtClass returnCtClass = ctMethod.getReturnType();
- Type returnType = Type.find(returnCtClass);
-
- String methodName = ctMethod.getName();
- CtClass[] paramTypes = ctMethod.getParameterTypes();
-
-// if (!isAbstract) {
-// if (methodName.startsWith("set") && paramTypes.length == 1) {
-// String fieldName = "__" + methodName.substring(3);
-// if (declareField(ctClass, fieldName, paramTypes[0])) {
-// methodBody = fieldName + " = $1;\n" + methodBody;
-// }
-// } else if (methodName.startsWith("get") && paramTypes.length == 0) {
-// String fieldName = "__" + methodName.substring(3);
-// if (declareField(ctClass, fieldName, returnType)) {
-// methodBody = "return " + fieldName + ";\n";
-// }
-// }
-// }
-
- boolean isStatic = Modifier.isStatic(originalModifiers);
- String methodBody = generateMethodBody(ctClass, ctMethod, wasNative, wasAbstract, returnCtClass, returnType, isStatic, !wasFoundInClass);
-
- if (!wasFoundInClass) {
- CtMethod newMethod = makeNewMethod(ctClass, ctMethod, returnCtClass, methodName, paramTypes, "{\n" + methodBody + generateCallToSuper(methodName, paramTypes) + "\n}");
- newMethod.setModifiers(newModifiers);
- if (wasDeclaredInClass) {
- ctMethod.insertBefore("{\n" + methodBody + "}\n");
- } else {
- ctClass.addMethod(newMethod);
- }
- } else if (wasAbstract || wasNative) {
- CtMethod newMethod = makeNewMethod(ctClass, ctMethod, returnCtClass, methodName, paramTypes, "{\n" + methodBody + "\n}");
- ctMethod.setBody(newMethod, null);
- } else {
- ctMethod.insertBefore("{\n" + methodBody + "}\n");
- }
- } catch (Exception e) {
- throw new RuntimeException("problem instrumenting " + describeBefore, e);
- }
- }
-
- private CtMethod makeNewMethod(CtClass ctClass, CtMethod ctMethod, CtClass returnCtClass, String methodName, CtClass[] paramTypes, String methodBody) throws CannotCompileException, NotFoundException {
- return CtNewMethod.make(
- ctMethod.getModifiers(),
- returnCtClass,
- methodName,
- paramTypes,
- ctMethod.getExceptionTypes(),
- methodBody,
- ctClass);
- }
-
- public String generateCallToSuper(String methodName, CtClass[] paramTypes) {
- return "return super." + methodName + "(" + makeParameterReplacementList(paramTypes.length) + ");";
- }
-
- public String makeParameterReplacementList(int length) {
- if (length == 0) {
- return "";
- }
-
- String parameterReplacementList = "$1";
- for (int i = 2; i <= length; ++i) {
- parameterReplacementList += ", $" + i;
- }
- return parameterReplacementList;
- }
-
- private String generateMethodBody(CtClass ctClass, CtMethod ctMethod, boolean wasNative, boolean wasAbstract, CtClass returnCtClass, Type returnType, boolean aStatic, boolean shouldGenerateCallToSuper) throws NotFoundException {
- String methodBody;
- if (wasAbstract) {
- methodBody = returnType.isVoid() ? "" : "return " + returnType.defaultReturnString() + ";";
- } else {
- methodBody = generateMethodBody(ctClass, ctMethod, returnCtClass, returnType, aStatic, shouldGenerateCallToSuper);
- }
-
- if (wasNative) {
- methodBody += returnType.isVoid() ? "" : "return " + returnType.defaultReturnString() + ";";
- }
- return methodBody;
- }
-
- public String generateMethodBody(CtClass ctClass, CtMethod ctMethod, CtClass returnCtClass, Type returnType, boolean isStatic, boolean shouldGenerateCallToSuper) throws NotFoundException {
- boolean returnsVoid = returnType.isVoid();
- String className = ctClass.getName();
-
- String methodBody;
- StringBuilder buf = new StringBuilder();
- buf.append("if (!");
- buf.append(RobolectricInternals.class.getName());
- buf.append(".shouldCallDirectly(");
- buf.append(isStatic ? className + ".class" : "this");
- buf.append(")) {\n");
-
- if (!returnsVoid) {
- buf.append("Object x = ");
- }
- buf.append(RobolectricInternals.class.getName());
- buf.append(".methodInvoked(\n ");
- buf.append(className);
- buf.append(".class, \"");
- buf.append(ctMethod.getName());
- buf.append("\", ");
- if (!isStatic) {
- buf.append("this");
- } else {
- buf.append("null");
- }
- buf.append(", ");
-
- appendParamTypeArray(buf, ctMethod);
- buf.append(", ");
- appendParamArray(buf, ctMethod);
-
- buf.append(")");
- buf.append(";\n");
-
- if (!returnsVoid) {
- buf.append("if (x != null) return ((");
- buf.append(returnType.nonPrimitiveClassName(returnCtClass));
- buf.append(") x)");
- buf.append(returnType.unboxString());
- buf.append(";\n");
- if (shouldGenerateCallToSuper) {
- buf.append(generateCallToSuper(ctMethod.getName(), ctMethod.getParameterTypes()));
- } else {
- buf.append("return ");
- buf.append(returnType.defaultReturnString());
- buf.append(";\n");
- }
- } else {
- buf.append("return;\n");
- }
-
- buf.append("}\n");
-
- methodBody = buf.toString();
- return methodBody;
- }
-
- private void appendParamTypeArray(StringBuilder buf, CtMethod ctMethod) throws NotFoundException {
- CtClass[] parameterTypes = ctMethod.getParameterTypes();
- if (parameterTypes.length == 0) {
- buf.append("new String[0]");
- } else {
- buf.append("new String[] {");
- for (int i = 0; i < parameterTypes.length; i++) {
- if (i > 0) buf.append(", ");
- buf.append("\"");
- CtClass parameterType = parameterTypes[i];
- buf.append(parameterType.getName());
- buf.append("\"");
- }
- buf.append("}");
- }
- }
-
- private void appendParamArray(StringBuilder buf, CtMethod ctMethod) throws NotFoundException {
- int parameterCount = ctMethod.getParameterTypes().length;
- if (parameterCount == 0) {
- buf.append("new Object[0]");
- } else {
- buf.append("new Object[] {");
- for (int i = 0; i < parameterCount; i++) {
- if (i > 0) buf.append(", ");
- buf.append(RobolectricInternals.class.getName());
- buf.append(".autobox(");
- buf.append("$").append(i + 1);
- buf.append(")");
- }
- buf.append("}");
- }
- }
-
- private boolean declareField(CtClass ctClass, String fieldName, CtClass fieldType) throws CannotCompileException, NotFoundException {
- CtMethod ctMethod = getMethod(ctClass, "get" + fieldName, "");
- if (ctMethod == null) {
- return false;
- }
- CtClass getterFieldType = ctMethod.getReturnType();
-
- if (!getterFieldType.equals(fieldType)) {
- return false;
- }
-
- if (getField(ctClass, fieldName) == null) {
- CtField field = new CtField(fieldType, fieldName, ctClass);
- field.setModifiers(Modifier.PRIVATE);
- ctClass.addField(field);
- }
-
- return true;
- }
-
- private CtField getField(CtClass ctClass, String fieldName) {
- try {
- return ctClass.getField(fieldName);
- } catch (NotFoundException e) {
- return null;
- }
- }
-
- private CtMethod getMethod(CtClass ctClass, String methodName, String desc) {
- try {
- return ctClass.getMethod(methodName, desc);
- } catch (NotFoundException e) {
- return null;
- }
- }
-
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/bytecode/ClassCache.java b/v1/src/main/java/com/xtremelabs/robolectric/bytecode/ClassCache.java
deleted file mode 100644
index 323b9670c..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/bytecode/ClassCache.java
+++ /dev/null
@@ -1,131 +0,0 @@
-package com.xtremelabs.robolectric.bytecode;
-
-import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.Enumeration;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.jar.Attributes;
-import java.util.jar.JarEntry;
-import java.util.jar.JarFile;
-import java.util.jar.JarOutputStream;
-import java.util.jar.Manifest;
-
-public class ClassCache {
- private static final Attributes.Name VERSION_ATTRIBUTE = new Attributes.Name("version");
-
- private Map<String, byte[]> cachedClasses = new HashMap<String, byte[]>();
- private boolean startedWriting = false;
-
- public ClassCache(String classCachePath, final int expectedCacheVersion) {
- final File cacheJarFile = new File(classCachePath);
- JarFile cacheFile;
- try {
- cacheFile = new JarFile(cacheJarFile);
- int cacheVersion = 0;
- Manifest manifest = cacheFile.getManifest();
- if (manifest != null) {
- Attributes attributes = manifest.getEntries().get("robolectric");
- if (attributes != null) {
- String cacheVersionStr = (String) attributes.get(VERSION_ATTRIBUTE);
- if (cacheVersionStr != null) {
- cacheVersion = Integer.parseInt(cacheVersionStr);
- }
- }
- }
- if (cacheVersion != expectedCacheVersion) {
- cacheJarFile.delete();
- } else {
- readEntries(cacheFile);
- }
- } catch (IOException e) {
- // no problem
- }
-
- Runtime.getRuntime().addShutdownHook(new Thread() {
- @Override public void run() {
- Manifest manifest = new Manifest();
- Attributes attributes = new Attributes();
- attributes.put(VERSION_ATTRIBUTE, String.valueOf(expectedCacheVersion));
- manifest.getEntries().put("robolectric", attributes);
-
- saveAllClassesToCache(cacheJarFile, manifest);
- }
- });
- }
-
- public byte[] getClassBytesFor(String name) {
- return cachedClasses.get(name);
- }
-
- public boolean isWriting() {
- synchronized (this) {
- return startedWriting;
- }
- }
-
- public void addClass(String className, byte[] classBytes) {
- cachedClasses.put(className, classBytes);
- }
-
- private void readEntries(JarFile cacheFile) {
- Enumeration<JarEntry> entries = cacheFile.entries();
- try {
- while (entries.hasMoreElements()) {
- JarEntry entry = entries.nextElement();
- String className = entry.getName();
- if (className.endsWith(".class")) {
- int classSize = (int) entry.getSize();
- InputStream inputStream = cacheFile.getInputStream(entry);
- ByteArrayOutputStream baos = new ByteArrayOutputStream(classSize);
- int c;
- while ((c = inputStream.read()) != -1) {
- baos.write(c);
- }
- className = className.substring(0, className.indexOf(".class")).replace('/', '.');
- addClass(className, baos.toByteArray());
- }
-
- }
- } catch (IOException e) {
- // no problem, we didn't want those bytes that much anyway
- }
- }
-
- protected void saveAllClassesToCache(File file, Manifest manifest) {
- synchronized (this) {
- startedWriting = true;
-
- if (cachedClasses.size() > 0) {
- JarOutputStream jarOutputStream = null;
- try {
- File cacheJarDir = file.getParentFile();
- if (!cacheJarDir.exists()) {
- cacheJarDir.mkdirs();
- }
-
- jarOutputStream = new JarOutputStream(new FileOutputStream(file), manifest);
- for (Map.Entry<String, byte[]> entry : cachedClasses.entrySet()) {
- String key = entry.getKey();
- jarOutputStream.putNextEntry(new JarEntry(key.replace('.', '/') + ".class"));
- jarOutputStream.write(entry.getValue());
- jarOutputStream.closeEntry();
- }
- } catch (IOException e) {
- throw new RuntimeException(e);
- } finally {
- if (jarOutputStream != null) {
- try {
- jarOutputStream.close();
- } catch (IOException ignore) {
- }
- }
- }
- }
- startedWriting = false;
- }
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/bytecode/ClassHandler.java b/v1/src/main/java/com/xtremelabs/robolectric/bytecode/ClassHandler.java
deleted file mode 100644
index e44fc1295..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/bytecode/ClassHandler.java
+++ /dev/null
@@ -1,17 +0,0 @@
-package com.xtremelabs.robolectric.bytecode;
-
-import com.xtremelabs.robolectric.RobolectricConfig;
-
-import javassist.CtClass;
-
-public interface ClassHandler {
- void configure(RobolectricConfig robolectricConfig);
-
- void instrument(CtClass ctClass);
-
- void beforeTest();
-
- void afterTest();
-
- Object methodInvoked(Class clazz, String methodName, Object instance, String[] paramTypes, Object[] params) throws Throwable;
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/bytecode/IgnorableClassNotFoundException.java b/v1/src/main/java/com/xtremelabs/robolectric/bytecode/IgnorableClassNotFoundException.java
deleted file mode 100644
index c081717a1..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/bytecode/IgnorableClassNotFoundException.java
+++ /dev/null
@@ -1,9 +0,0 @@
-package com.xtremelabs.robolectric.bytecode;
-
-import javassist.NotFoundException;
-
-public class IgnorableClassNotFoundException extends NotFoundException {
- public IgnorableClassNotFoundException(NotFoundException e) {
- super("msg", e);
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/bytecode/RobolectricClassLoader.java b/v1/src/main/java/com/xtremelabs/robolectric/bytecode/RobolectricClassLoader.java
deleted file mode 100644
index 68d9e3c1a..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/bytecode/RobolectricClassLoader.java
+++ /dev/null
@@ -1,85 +0,0 @@
-package com.xtremelabs.robolectric.bytecode;
-
-import javassist.CannotCompileException;
-import javassist.ClassPool;
-import javassist.LoaderClassPath;
-import javassist.NotFoundException;
-
-import java.io.File;
-import java.lang.System;
-import java.util.List;
-
-public class RobolectricClassLoader extends javassist.Loader {
- private ClassCache classCache;
- private AndroidTranslator androidTranslator;
-
- public RobolectricClassLoader(ClassHandler classHandler) {
- this(classHandler, null);
- }
-
- public RobolectricClassLoader(ClassHandler classHandler, List<String> customClassNames) {
- super(RobolectricClassLoader.class.getClassLoader(), null);
-
- delegateLoadingOf(AndroidTranslator.class.getName());
- delegateLoadingOf(ClassHandler.class.getName());
-
- final String classCachePath = System.getProperty("cached.robolectric.classes.path");
- final File classCacheDirectory;
- if (null == classCachePath || "".equals(classCachePath.trim())) {
- classCacheDirectory = new File("./tmp");
- } else {
- classCacheDirectory = new File(classCachePath);
- }
-
- classCache = new ClassCache(new File(classCacheDirectory, "cached-robolectric-classes.jar").getAbsolutePath(), AndroidTranslator.CACHE_VERSION);
- try {
- ClassPool classPool = new ClassPool();
- classPool.appendClassPath(new LoaderClassPath(RobolectricClassLoader.class.getClassLoader()));
-
- androidTranslator = new AndroidTranslator(classHandler, classCache, customClassNames);
- addTranslator(classPool, androidTranslator);
- } catch (NotFoundException e) {
- throw new RuntimeException(e);
- } catch (CannotCompileException e) {
- throw new RuntimeException(e);
- }
- }
-
- public void addCustomShadowClass(String classOrPackageToBeInstrumented) {
- androidTranslator.addCustomShadowClass(classOrPackageToBeInstrumented);
- }
-
- @Override
- public Class loadClass(String name) throws ClassNotFoundException {
- boolean shouldComeFromThisClassLoader = !(name.startsWith("org.junit") || name.startsWith("org.hamcrest")
- || name.startsWith("org.specs2") || name.startsWith("scala.")); //org.specs2 and scala. allows for android projects with mixed scala\java tests to be run with Maven Surefire (see the RoboSpecs project on github)
-
- Class<?> theClass;
- if (shouldComeFromThisClassLoader) {
- theClass = super.loadClass(name);
- } else {
- theClass = getParent().loadClass(name);
- }
-
- return theClass;
- }
-
- public Class<?> bootstrap(Class testClass) {
- String testClassName = testClass.getName();
-
- try {
- return loadClass(testClassName);
- } catch (ClassNotFoundException e) {
- throw new RuntimeException(e);
- }
- }
-
- @Override
- protected Class findClass(String name) throws ClassNotFoundException {
- byte[] classBytes = classCache.getClassBytesFor(name);
- if (classBytes != null) {
- return defineClass(name, classBytes, 0, classBytes.length);
- }
- return super.findClass(name);
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/bytecode/RobolectricInternals.java b/v1/src/main/java/com/xtremelabs/robolectric/bytecode/RobolectricInternals.java
deleted file mode 100644
index ed553cada..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/bytecode/RobolectricInternals.java
+++ /dev/null
@@ -1,161 +0,0 @@
-package com.xtremelabs.robolectric.bytecode;
-
-import com.xtremelabs.robolectric.internal.Implements;
-
-import java.lang.reflect.Constructor;
-import java.lang.reflect.InvocationTargetException;
-import java.util.HashSet;
-import java.util.Set;
-
-@SuppressWarnings({"UnusedDeclaration"})
-public class RobolectricInternals {
- // initialized via magic by AndroidTranslator
- private static ClassHandler classHandler;
- private static Set<String> unloadableClassNames = new HashSet<String>();
-
- private static final ThreadLocal<Vars> ALL_VARS = new ThreadLocal<Vars>() {
- @Override protected Vars initialValue() {
- return new Vars();
- }
- };
-
- private static class Vars {
- Object callDirectly;
- }
-
- public static <T> T newInstanceOf(Class<T> clazz) {
- try {
- Constructor<T> defaultConstructor = clazz.getDeclaredConstructor();
- defaultConstructor.setAccessible(true);
- return defaultConstructor.newInstance();
- } catch (InstantiationException e) {
- throw new RuntimeException(e);
- } catch (IllegalAccessException e) {
- throw new RuntimeException(e);
- } catch (NoSuchMethodException e) {
- throw new RuntimeException(e);
- } catch (InvocationTargetException e) {
- throw new RuntimeException(e);
- }
- }
-
- public static void bindShadowClass(Class<?> shadowClass) {
- Implements realClass = shadowClass.getAnnotation(Implements.class);
- if (realClass == null) {
- throw new IllegalArgumentException(shadowClass + " is not annotated with @Implements");
- }
-
- try {
- ShadowWrangler.getInstance().bindShadowClass(realClass.value(), shadowClass);
- } catch (TypeNotPresentException typeLoadingException) {
- String unloadableClassName = shadowClass.getSimpleName();
- if (isIgnorableClassLoadingException(typeLoadingException)) {
- //this allows users of the robolectric.jar file to use the non-Google APIs version of the api
- if (unloadableClassNames.add(unloadableClassName)) {
- System.out.println("Warning: an error occurred while binding shadow class: " + unloadableClassName);
- }
- } else {
- throw typeLoadingException;
- }
- }
- }
-
- private static boolean isIgnorableClassLoadingException(Throwable typeLoadingException) {
- if (typeLoadingException != null) {
- // instanceof doesn't work here. Are we in different classloaders?
- if (typeLoadingException.getClass().getName().equals(IgnorableClassNotFoundException.class.getName())) {
- return true;
- }
-
- if (typeLoadingException instanceof NoClassDefFoundError
- || typeLoadingException instanceof ClassNotFoundException
- || typeLoadingException instanceof TypeNotPresentException) {
- return isIgnorableClassLoadingException(typeLoadingException.getCause());
- }
- }
- return false;
- }
-
- public static <T> T directlyOn(T shadowedObject) {
- Vars vars = ALL_VARS.get();
-
- if (vars.callDirectly != null) {
- Object expectedInstance = vars.callDirectly;
- vars.callDirectly = null;
- throw new RuntimeException("already expecting a direct call on <" + expectedInstance + "> but here's a new request for <" + shadowedObject + ">");
- }
-
- vars.callDirectly = shadowedObject;
- return shadowedObject;
- }
-
- public static boolean shouldCallDirectly(Object directInstance) {
- Vars vars = ALL_VARS.get();
- if (vars.callDirectly != null) {
- if (vars.callDirectly != directInstance) {
- Object expectedInstance = vars.callDirectly;
- vars.callDirectly = null;
- throw new RuntimeException("expected to perform direct call on <" + expectedInstance + "> but got <" + directInstance + ">");
- } else {
- vars.callDirectly = null;
- }
- return true;
- } else {
- return false;
- }
- }
-
- @SuppressWarnings({"UnusedDeclaration"})
- public static Object methodInvoked(Class clazz, String methodName, Object instance, String[] paramTypes, Object[] params) throws Throwable {
- try {
- return classHandler.methodInvoked(clazz, methodName, instance, paramTypes, params);
- } catch(java.lang.LinkageError e) {
- throw new Exception(e);
- }
- }
-
- @SuppressWarnings({"UnusedDeclaration"})
- public static Object autobox(Object o) {
- return o;
- }
-
- @SuppressWarnings({"UnusedDeclaration"})
- public static Object autobox(boolean o) {
- return o;
- }
-
- @SuppressWarnings({"UnusedDeclaration"})
- public static Object autobox(byte o) {
- return o;
- }
-
- @SuppressWarnings({"UnusedDeclaration"})
- public static Object autobox(char o) {
- return o;
- }
-
- @SuppressWarnings({"UnusedDeclaration"})
- public static Object autobox(short o) {
- return o;
- }
-
- @SuppressWarnings({"UnusedDeclaration"})
- public static Object autobox(int o) {
- return o;
- }
-
- @SuppressWarnings({"UnusedDeclaration"})
- public static Object autobox(long o) {
- return o;
- }
-
- @SuppressWarnings({"UnusedDeclaration"})
- public static Object autobox(float o) {
- return o;
- }
-
- @SuppressWarnings({"UnusedDeclaration"})
- public static Object autobox(double o) {
- return o;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/bytecode/ShadowWrangler.java b/v1/src/main/java/com/xtremelabs/robolectric/bytecode/ShadowWrangler.java
deleted file mode 100644
index 600edb49d..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/bytecode/ShadowWrangler.java
+++ /dev/null
@@ -1,456 +0,0 @@
-package com.xtremelabs.robolectric.bytecode;
-
-import com.xtremelabs.robolectric.RobolectricConfig;
-import com.xtremelabs.robolectric.internal.RealObject;
-import com.xtremelabs.robolectric.util.I18nException;
-import com.xtremelabs.robolectric.util.Join;
-import javassist.CannotCompileException;
-import javassist.CtClass;
-import javassist.CtField;
-import javassist.NotFoundException;
-
-import java.lang.annotation.Annotation;
-import java.lang.reflect.Array;
-import java.lang.reflect.Constructor;
-import java.lang.reflect.Field;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.lang.reflect.Modifier;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-public class ShadowWrangler implements ClassHandler {
- public static final String SHADOW_FIELD_NAME = "__shadow__";
-
- private static ShadowWrangler singleton;
-
- public boolean debug = false;
- private boolean strictI18n = false;
-
- private final Map<Class, MetaShadow> metaShadowMap = new HashMap<Class, MetaShadow>();
- private Map<String, String> shadowClassMap = new HashMap<String, String>();
- private Map<Class, Field> shadowFieldMap = new HashMap<Class, Field>();
- private boolean logMissingShadowMethods = false;
-
- // sorry! it really only makes sense to have one per ClassLoader anyway though [xw/hu]
- public static ShadowWrangler getInstance() {
- if (singleton == null) {
- singleton = new ShadowWrangler();
- }
- return singleton;
- }
-
- private ShadowWrangler() {
- }
-
- @Override
- public void configure(RobolectricConfig robolectricConfig) {
- strictI18n = robolectricConfig.getStrictI18n();
- }
-
- @Override
- public void instrument(CtClass ctClass) {
- try {
- CtClass objectClass = ctClass.getClassPool().get(Object.class.getName());
- try {
- ctClass.getField(SHADOW_FIELD_NAME);
- } catch (NotFoundException e) {
- CtField field = new CtField(objectClass, SHADOW_FIELD_NAME, ctClass);
- field.setModifiers(Modifier.PUBLIC);
- ctClass.addField(field);
- }
- } catch (CannotCompileException e) {
- throw new RuntimeException(e);
- } catch (NotFoundException e) {
- throw new RuntimeException(e);
- }
- }
-
- @Override
- public void beforeTest() {
- shadowClassMap.clear();
- }
-
- @Override
- public void afterTest() {
- }
-
- public void bindShadowClass(Class<?> realClass, Class<?> shadowClass) {
- shadowClassMap.put(realClass.getName(), shadowClass.getName());
- if (debug) System.out.println("shadow " + realClass + " with " + shadowClass);
- }
-
- @Override
- public Object methodInvoked(Class clazz, String methodName, Object instance, String[] paramTypes, Object[] params) throws Throwable {
- InvocationPlan invocationPlan = new InvocationPlan(clazz, methodName, instance, paramTypes);
- if (!invocationPlan.prepare()) {
- reportNoShadowMethodFound(clazz, methodName, paramTypes);
- return null;
- }
-
- if (strictI18n && !invocationPlan.isI18nSafe()) {
- throw new I18nException("Method " + methodName + " on class " + clazz.getName() + " is not i18n-safe.");
- }
-
- try {
- return invocationPlan.getMethod().invoke(invocationPlan.getShadow(), params);
- } catch (IllegalArgumentException e) {
- throw new RuntimeException(invocationPlan.getShadow().getClass().getName() + " is not assignable from " +
- invocationPlan.getDeclaredShadowClass().getName(), e);
- } catch (InvocationTargetException e) {
- throw stripStackTrace(e.getCause());
- }
- }
-
- private <T extends Throwable> T stripStackTrace(T throwable) {
- List<StackTraceElement> stackTrace = new ArrayList<StackTraceElement>();
- for (StackTraceElement stackTraceElement : throwable.getStackTrace()) {
- String className = stackTraceElement.getClassName();
- boolean isInternalCall = className.startsWith("sun.reflect.")
- || className.startsWith("java.lang.reflect.")
- || className.equals(ShadowWrangler.class.getName())
- || className.equals(RobolectricInternals.class.getName());
- if (!isInternalCall) {
- stackTrace.add(stackTraceElement);
- }
- }
- throwable.setStackTrace(stackTrace.toArray(new StackTraceElement[stackTrace.size()]));
- return throwable;
- }
-
- private void reportNoShadowMethodFound(Class clazz, String methodName, String[] paramTypes) {
- if (logMissingShadowMethods) {
- System.out.println("No Shadow method found for " + clazz.getSimpleName() + "." + methodName + "(" +
- Join.join(", ", (Object[]) paramTypes) + ")");
- }
- }
-
- public static Class<?> loadClass(String paramType, ClassLoader classLoader) {
- Class primitiveClass = Type.findPrimitiveClass(paramType);
- if (primitiveClass != null) return primitiveClass;
-
- int arrayLevel = 0;
- while (paramType.endsWith("[]")) {
- arrayLevel++;
- paramType = paramType.substring(0, paramType.length() - 2);
- }
-
- Class<?> clazz = Type.findPrimitiveClass(paramType);
- if (clazz == null) {
- try {
- clazz = classLoader.loadClass(paramType);
- } catch (ClassNotFoundException e) {
- throw new RuntimeException(e);
- }
- }
-
- while (arrayLevel-- > 0) {
- clazz = Array.newInstance(clazz, 0).getClass();
- }
-
- return clazz;
- }
-
- public Object shadowFor(Object instance) {
- Field field = getShadowField(instance);
- Object shadow = readField(instance, field);
-
- if (shadow != null) {
- return shadow;
- }
-
- String shadowClassName = getShadowClassName(instance.getClass());
-
- if (debug)
- System.out.println("creating new " + shadowClassName + " as shadow for " + instance.getClass().getName());
- try {
- Class<?> shadowClass = loadClass(shadowClassName, instance.getClass().getClassLoader());
- Constructor<?> constructor = findConstructor(instance, shadowClass);
- if (constructor != null) {
- shadow = constructor.newInstance(instance);
- } else {
- shadow = shadowClass.newInstance();
- }
- field.set(instance, shadow);
-
- injectRealObjectOn(shadow, shadowClass, instance);
-
- return shadow;
- } catch (InstantiationException e) {
- throw new RuntimeException(e);
- } catch (IllegalAccessException e) {
- throw new RuntimeException(e);
- } catch (InvocationTargetException e) {
- throw new RuntimeException(e);
- }
- }
-
- private void injectRealObjectOn(Object shadow, Class<?> shadowClass, Object instance) {
- MetaShadow metaShadow = getMetaShadow(shadowClass);
- for (Field realObjectField : metaShadow.realObjectFields) {
- writeField(shadow, instance, realObjectField);
- }
- }
-
- private MetaShadow getMetaShadow(Class<?> shadowClass) {
- synchronized (metaShadowMap) {
- MetaShadow metaShadow = metaShadowMap.get(shadowClass);
- if (metaShadow == null) {
- metaShadow = new MetaShadow(shadowClass);
- metaShadowMap.put(shadowClass, metaShadow);
- }
- return metaShadow;
- }
- }
-
- private String getShadowClassName(Class clazz) {
- String shadowClassName = null;
- while (shadowClassName == null && clazz != null) {
- shadowClassName = shadowClassMap.get(clazz.getName());
- clazz = clazz.getSuperclass();
- }
- return shadowClassName;
- }
-
- public Class<?> findShadowClass(Class<?> originalClass, ClassLoader classLoader) {
- String declaredShadowClassName = getShadowClassName(originalClass);
- if (declaredShadowClassName == null) {
- return null;
- }
- return loadClass(declaredShadowClassName, classLoader);
- }
-
- private Constructor<?> findConstructor(Object instance, Class<?> shadowClass) {
- Class clazz = instance.getClass();
-
- Constructor constructor;
- for (constructor = null; constructor == null && clazz != null; clazz = clazz.getSuperclass()) {
- try {
- constructor = shadowClass.getConstructor(clazz);
- } catch (NoSuchMethodException e) {
- // expected
- }
- }
- return constructor;
- }
-
- private Field getShadowField(Object instance) {
- Class clazz = instance.getClass();
- Field field = shadowFieldMap.get(clazz);
- if (field == null) {
- try {
- field = clazz.getField(SHADOW_FIELD_NAME);
- } catch (NoSuchFieldException e) {
- throw new RuntimeException(instance.getClass().getName() + " has no shadow field", e);
- }
- shadowFieldMap.put(clazz, field);
- }
- return field;
- }
-
- public Object shadowOf(Object instance) {
- if (instance == null) {
- throw new NullPointerException("can't get a shadow for null");
- }
- Field field = getShadowField(instance);
- return readField(instance, field);
- }
-
- private Object readField(Object target, Field field) {
- try {
- return field.get(target);
- } catch (IllegalAccessException e1) {
- throw new RuntimeException(e1);
- }
- }
-
- private void writeField(Object target, Object value, Field realObjectField) {
- try {
- realObjectField.set(target, value);
- } catch (IllegalAccessException e) {
- throw new RuntimeException(e);
- }
- }
-
- public void logMissingInvokedShadowMethods() {
- logMissingShadowMethods = true;
- }
-
- public void silence() {
- logMissingShadowMethods = false;
- }
-
- private class InvocationPlan {
- private Class clazz;
- private ClassLoader classLoader;
- private String methodName;
- private Object instance;
- private String[] paramTypes;
- private Class<?> declaredShadowClass;
- private Method method;
- private Object shadow;
-
- public InvocationPlan(Class clazz, String methodName, Object instance, String... paramTypes) {
- this.clazz = clazz;
- this.classLoader = clazz.getClassLoader();
- this.methodName = methodName;
- this.instance = instance;
- this.paramTypes = paramTypes;
- }
-
- public Class<?> getDeclaredShadowClass() {
- return declaredShadowClass;
- }
-
- public Method getMethod() {
- return method;
- }
-
- public Object getShadow() {
- return shadow;
- }
-
- public boolean isI18nSafe() {
- // method is loaded by another class loader. So do everything reflectively.
- Annotation[] annos = method.getAnnotations();
- for (int i = 0; i < annos.length; i++) {
- String name = annos[i].annotationType().getName();
- if (name.equals("com.xtremelabs.robolectric.internal.Implementation")) {
- try {
- Method m = (annos[i]).getClass().getMethod("i18nSafe");
- return (Boolean) m.invoke(annos[i]);
- } catch (Exception e) {
- return true; // should probably throw some other exception
- }
- }
- }
-
- return true;
- }
-
- public boolean prepare() {
- Class<?>[] paramClasses = getParamClasses();
-
- Class<?> originalClass = loadClass(clazz.getName(), classLoader);
-
- declaredShadowClass = findDeclaredShadowClassForMethod(originalClass, methodName, paramClasses);
- if (declaredShadowClass == null) {
- return false;
- }
-
- if (methodName.equals("<init>")) {
- methodName = "__constructor__";
- }
-
- if (instance != null) {
- shadow = shadowFor(instance);
- method = getMethod(shadow.getClass(), methodName, paramClasses);
- } else {
- shadow = null;
- method = getMethod(findShadowClass(clazz, classLoader), methodName, paramClasses);
- }
-
- if (method == null) {
- if (debug) {
- System.out.println("No method found for " + clazz + "." + methodName + "(" + Arrays.asList(paramClasses) + ") on " + declaredShadowClass.getName());
- }
- return false;
- }
-
- if ((instance == null) != Modifier.isStatic(method.getModifiers())) {
- throw new RuntimeException("method staticness of " + clazz.getName() + "." + methodName + " and " + declaredShadowClass.getName() + "." + method.getName() + " don't match");
- }
-
- method.setAccessible(true);
-
- return true;
- }
-
- private Class<?> findDeclaredShadowClassForMethod(Class<?> originalClass, String methodName, Class<?>[] paramClasses) {
- Class<?> declaringClass = findDeclaringClassForMethod(methodName, paramClasses, originalClass);
- return findShadowClass(declaringClass, classLoader);
- }
-
- private Class<?> findDeclaringClassForMethod(String methodName, Class<?>[] paramClasses, Class<?> originalClass) {
- Class<?> declaringClass;
- if (this.methodName.equals("<init>")) {
- declaringClass = originalClass;
- } else {
- Method originalMethod;
- try {
- originalMethod = originalClass.getDeclaredMethod(methodName, paramClasses);
- } catch (NoSuchMethodException e) {
- throw new RuntimeException(e);
- }
- declaringClass = originalMethod.getDeclaringClass();
- }
- return declaringClass;
- }
-
- private Class<?>[] getParamClasses() {
- Class<?>[] paramClasses = new Class<?>[paramTypes.length];
-
- for (int i = 0; i < paramTypes.length; i++) {
- paramClasses[i] = loadClass(paramTypes[i], classLoader);
- }
- return paramClasses;
- }
-
- private Method getMethod(Class<?> clazz, String methodName, Class<?>[] paramClasses) {
- Method method = null;
- try {
- method = clazz.getMethod(methodName, paramClasses);
- } catch (NoSuchMethodException e) {
- try {
- method = clazz.getDeclaredMethod(methodName, paramClasses);
- } catch (NoSuchMethodException e1) {
- method = null;
- }
- }
-
- if (method != null && !isOnShadowClass(method)) {
- method = null;
- }
-
- return method;
- }
-
- private boolean isOnShadowClass(Method method) {
- Class<?> declaringClass = method.getDeclaringClass();
- // why doesn't getAnnotation(com.xtremelabs.robolectric.internal.Implements) work here? It always returns null. pg 20101115
- // It doesn't work because the method and declaringClass were loaded by the delegate class loader. Different classloaders so types don't match. mp 20110823
- for (Annotation annotation : declaringClass.getAnnotations()) {
- if (annotation.annotationType().toString().equals("interface com.xtremelabs.robolectric.internal.Implements")) {
- return true;
- }
- }
- return false;
- }
-
- @Override
- public String toString() {
- return "delegating to " + declaredShadowClass.getName() + "." + method.getName()
- + "(" + Arrays.toString(method.getParameterTypes()) + ")";
- }
- }
-
- private class MetaShadow {
- List<Field> realObjectFields = new ArrayList<Field>();
-
- public MetaShadow(Class<?> shadowClass) {
- while (shadowClass != null) {
- for (Field field : shadowClass.getDeclaredFields()) {
- if (field.isAnnotationPresent(RealObject.class)) {
- field.setAccessible(true);
- realObjectFields.add(field);
- }
- }
- shadowClass = shadowClass.getSuperclass();
- }
-
- }
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/bytecode/Type.java b/v1/src/main/java/com/xtremelabs/robolectric/bytecode/Type.java
deleted file mode 100644
index a6168b099..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/bytecode/Type.java
+++ /dev/null
@@ -1,85 +0,0 @@
-package com.xtremelabs.robolectric.bytecode;
-
-import javassist.CtClass;
-
-enum Type {
- VOID(null, null, "", "", Void.TYPE),
- BOOLEAN(false, "false", ".booleanValue()", "java.lang.Boolean", Boolean.TYPE),
- BYTE(0, "0", ".byteValue()", "java.lang.Byte", Byte.TYPE),
- CHAR(0, "0", ".charValue()", "java.lang.Character", Character.TYPE),
- SHORT(0, "0", ".shortValue()", "java.lang.Short", Short.TYPE),
- INT(0, "0", ".intValue()", "java.lang.Integer", Integer.TYPE),
- LONG(0, "0l", ".longValue()", "java.lang.Long", Long.TYPE),
- FLOAT(0, "0f", ".floatValue()", "java.lang.Float", Float.TYPE),
- DOUBLE(0, "0d", ".doubleValue()", "java.lang.Double", Double.TYPE),
- OBJECT(null, "null", "", null, null);
-
- Type(Object defaultReturnValue, String defaultReturnString, String unboxString, String nonPrimitiveClassName, Class type) {
- this.defaultReturnValue = defaultReturnValue;
- this.defaultReturnString = defaultReturnString;
- this.unboxString = unboxString;
- this.nonPrimitiveClassName = nonPrimitiveClassName;
- this.type = type;
- }
-
- private Object defaultReturnValue;
- private String defaultReturnString;
- private String unboxString;
- private String nonPrimitiveClassName;
- private Class type;
-
- Object defaultReturnValue() {
- return defaultReturnValue;
- }
-
- String defaultReturnString() {
- return defaultReturnString;
- }
-
- String unboxString() {
- return unboxString;
- }
-
- String nonPrimitiveClassName(CtClass returnCtClass) {
- return nonPrimitiveClassName == null ? returnCtClass.getName() : nonPrimitiveClassName;
- }
-
- boolean isVoid() {
- return this == VOID;
- }
-
- public static Type find(CtClass ctClass) {
- if (ctClass.equals(CtClass.voidType)) {
- return VOID;
- } else if (ctClass.equals(CtClass.booleanType)) {
- return BOOLEAN;
- } else if (ctClass.equals(CtClass.byteType)) {
- return BYTE;
- } else if (ctClass.equals(CtClass.charType)) {
- return CHAR;
- } else if (ctClass.equals(CtClass.shortType)) {
- return SHORT;
- } else if (ctClass.equals(CtClass.intType)) {
- return INT;
- } else if (ctClass.equals(CtClass.longType)) {
- return LONG;
- } else if (ctClass.equals(CtClass.floatType)) {
- return FLOAT;
- } else if (ctClass.equals(CtClass.doubleType)) {
- return DOUBLE;
- } else if (!ctClass.isPrimitive()) {
- return OBJECT;
- } else {
- throw new RuntimeException("unknown return type " + ctClass);
- }
- }
-
- public static Class findPrimitiveClass(String name) {
- for (Type type : Type.values()) {
- if (type.type != null && type.type.getName().equals(name)) {
- return type.type;
- }
- }
- return null;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/internal/AppSingletonizer.java b/v1/src/main/java/com/xtremelabs/robolectric/internal/AppSingletonizer.java
deleted file mode 100644
index 203b22da0..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/internal/AppSingletonizer.java
+++ /dev/null
@@ -1,35 +0,0 @@
-package com.xtremelabs.robolectric.internal;
-
-import android.app.Application;
-import android.content.Context;
-import com.xtremelabs.robolectric.shadows.ShadowApplication;
-
-import static com.xtremelabs.robolectric.Robolectric.newInstanceOf;
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-
-public abstract class AppSingletonizer<T> {
- private Class<T> clazz;
-
- public AppSingletonizer(Class<T> clazz) {
- this.clazz = clazz;
- }
-
- synchronized public T getInstance(Context context) {
- Application applicationContext = (Application) context.getApplicationContext();
- ShadowApplication shadowApplication = (ShadowApplication) shadowOf(applicationContext);
- T instance = get(shadowApplication);
- if (instance == null) {
- instance = createInstance(applicationContext);
- set(shadowApplication, instance);
- }
- return instance;
- }
-
- protected abstract T get(ShadowApplication shadowApplication);
-
- protected abstract void set(ShadowApplication shadowApplication, T instance);
-
- protected T createInstance(Application applicationContext) {
- return newInstanceOf(clazz);
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/internal/ClassNameResolver.java b/v1/src/main/java/com/xtremelabs/robolectric/internal/ClassNameResolver.java
deleted file mode 100644
index 4f2db4ef0..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/internal/ClassNameResolver.java
+++ /dev/null
@@ -1,41 +0,0 @@
-package com.xtremelabs.robolectric.internal;
-
-public class ClassNameResolver<T> {
- private String packageName;
- private String className;
-
- public ClassNameResolver(String packageName, String className) {
- this.packageName = packageName;
- this.className = className;
- }
-
- public Class<? extends T> resolve() {
- Class<? extends T> aClass;
- if (looksFullyQualified(className)) {
- aClass = safeClassForName(className);
- } else {
- aClass = safeClassForName(packageName + "." + className);
- if (aClass == null) {
- aClass = safeClassForName(packageName + className);
- }
- }
-
- if (aClass == null) {
- throw new RuntimeException("Could not find a class for package: "
- + packageName + " and class name: " + className);
- }
- return aClass;
- }
-
- private boolean looksFullyQualified(String className) {
- return className.contains(".") && !className.startsWith(".");
- }
-
- private Class<? extends T> safeClassForName(String classNamePath) {
- try {
- return (Class<? extends T>) Class.forName(classNamePath);
- } catch (ClassNotFoundException e) {
- return null;
- }
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/internal/DoNotInstrument.java b/v1/src/main/java/com/xtremelabs/robolectric/internal/DoNotInstrument.java
deleted file mode 100644
index 38eaf991c..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/internal/DoNotInstrument.java
+++ /dev/null
@@ -1,10 +0,0 @@
-package com.xtremelabs.robolectric.internal;
-
-/**
- * Indicates that a class should not be stripped/instrumented under any circumstances.
- */
-@java.lang.annotation.Documented
-@java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
-@java.lang.annotation.Target({java.lang.annotation.ElementType.TYPE})
-public @interface DoNotInstrument {
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/internal/EmptyRunnable.java b/v1/src/main/java/com/xtremelabs/robolectric/internal/EmptyRunnable.java
deleted file mode 100644
index b58fd66f1..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/internal/EmptyRunnable.java
+++ /dev/null
@@ -1,7 +0,0 @@
-package com.xtremelabs.robolectric.internal;
-
-public class EmptyRunnable implements Runnable {
- @Override
- public void run() {
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/internal/Implementation.java b/v1/src/main/java/com/xtremelabs/robolectric/internal/Implementation.java
deleted file mode 100644
index 64d0d77b3..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/internal/Implementation.java
+++ /dev/null
@@ -1,14 +0,0 @@
-package com.xtremelabs.robolectric.internal;
-
-/**
- * Indicates that a method declaration is intended to Shadow a method with the same signature on the associated
- * Android class.
- *
- * @see Implements
- */
-@java.lang.annotation.Documented
-@java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
-@java.lang.annotation.Target({java.lang.annotation.ElementType.METHOD})
-public @interface Implementation {
- boolean i18nSafe() default true;
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/internal/Implements.java b/v1/src/main/java/com/xtremelabs/robolectric/internal/Implements.java
deleted file mode 100644
index 9fe151e3a..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/internal/Implements.java
+++ /dev/null
@@ -1,17 +0,0 @@
-package com.xtremelabs.robolectric.internal;
-
-
-/**
- * Indicates that a class declaration is intended to Shadow an Android class declaration. The Robolectric runtime
- * searches classes with this annotation for methods with the {@link Implementation} annotation and calls them in
- * place of the methods on the Android class.
- */
-@java.lang.annotation.Documented
-@java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
-@java.lang.annotation.Target({java.lang.annotation.ElementType.TYPE})
-public @interface Implements {
- /**
- * the Android class to be shadowed
- */
- Class value();
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/internal/Instrument.java b/v1/src/main/java/com/xtremelabs/robolectric/internal/Instrument.java
deleted file mode 100644
index 2a4031e84..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/internal/Instrument.java
+++ /dev/null
@@ -1,10 +0,0 @@
-package com.xtremelabs.robolectric.internal;
-
-/**
- * Indicates that a class should always be instrumented by AndroidTranslator regardless of its package.
- */
-@java.lang.annotation.Documented
-@java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
-@java.lang.annotation.Target({java.lang.annotation.ElementType.TYPE})
-public @interface Instrument {
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/internal/RealObject.java b/v1/src/main/java/com/xtremelabs/robolectric/internal/RealObject.java
deleted file mode 100644
index e22e5aa1e..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/internal/RealObject.java
+++ /dev/null
@@ -1,12 +0,0 @@
-package com.xtremelabs.robolectric.internal;
-
-/**
- * Shadow fields annotated @RealObject will have the real instance injected.
- *
- * @see Implements
- */
-@java.lang.annotation.Documented
-@java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
-@java.lang.annotation.Target({java.lang.annotation.ElementType.FIELD})
-public @interface RealObject {
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/internal/RobolectricTestRunnerInterface.java b/v1/src/main/java/com/xtremelabs/robolectric/internal/RobolectricTestRunnerInterface.java
deleted file mode 100644
index d0ea3d5d5..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/internal/RobolectricTestRunnerInterface.java
+++ /dev/null
@@ -1,18 +0,0 @@
-package com.xtremelabs.robolectric.internal;
-
-import com.xtremelabs.robolectric.RobolectricConfig;
-import com.xtremelabs.robolectric.util.DatabaseConfig.DatabaseMap;
-
-import java.lang.reflect.Method;
-
-public interface RobolectricTestRunnerInterface {
- Object createTest() throws Exception;
-
- void internalBeforeTest(Method method);
-
- void internalAfterTest(Method method);
-
- void setRobolectricConfig(RobolectricConfig config);
-
- void setDatabaseMap(DatabaseMap databaseMap);
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/matchers/CompoundButtonCheckedMatcher.java b/v1/src/main/java/com/xtremelabs/robolectric/matchers/CompoundButtonCheckedMatcher.java
deleted file mode 100644
index 9e38010bc..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/matchers/CompoundButtonCheckedMatcher.java
+++ /dev/null
@@ -1,28 +0,0 @@
-package com.xtremelabs.robolectric.matchers;
-
-import android.widget.CompoundButton;
-import org.hamcrest.Description;
-import org.hamcrest.Factory;
-import org.hamcrest.Matcher;
-import org.junit.internal.matchers.TypeSafeMatcher;
-
-public class CompoundButtonCheckedMatcher<T extends CompoundButton> extends TypeSafeMatcher<T> {
- private boolean expected;
-
- public CompoundButtonCheckedMatcher(boolean expected) {
- this.expected = expected;
- }
-
- @Override public boolean matchesSafely(T compoundButton) {
- return compoundButton != null && expected == compoundButton.isChecked();
- }
-
- @Override public void describeTo(Description description) {
- description.appendText("to be [" + (expected ? "checked" : "unchecked") + "]");
- }
-
- @Factory
- public static <T extends CompoundButton> Matcher<T> isChecked(boolean expectedChecked) {
- return new CompoundButtonCheckedMatcher<T>(expectedChecked);
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/matchers/HasCompoundDrawablesMatcher.java b/v1/src/main/java/com/xtremelabs/robolectric/matchers/HasCompoundDrawablesMatcher.java
deleted file mode 100644
index 58fb3ef37..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/matchers/HasCompoundDrawablesMatcher.java
+++ /dev/null
@@ -1,45 +0,0 @@
-package com.xtremelabs.robolectric.matchers;
-
-import android.widget.TextView;
-import com.xtremelabs.robolectric.shadows.ShadowTextView;
-import org.hamcrest.Description;
-import org.hamcrest.Factory;
-import org.hamcrest.Matcher;
-import org.junit.internal.matchers.TypeSafeMatcher;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-
-public class HasCompoundDrawablesMatcher extends TypeSafeMatcher<TextView> {
- private String message;
- private ShadowTextView.CompoundDrawables expectedCompoundDrawables;
-
- public HasCompoundDrawablesMatcher(int left, int top, int right, int bottom) {
- expectedCompoundDrawables = new ShadowTextView.CompoundDrawables(left, top, right, bottom);
- }
-
- @Override
- public boolean matchesSafely(TextView actual) {
- if (actual == null) {
- message = "actual view was null";
- return false;
- }
-
- ShadowTextView.CompoundDrawables actualCompoundDrawables = shadowOf(actual).getCompoundDrawablesImpl();
- if (!expectedCompoundDrawables.equals(actualCompoundDrawables)) {
- message = "[" + actualCompoundDrawables + "] to equal [" + expectedCompoundDrawables + "]";
- return false;
- } else {
- return true;
- }
- }
-
- @Override
- public void describeTo(Description description) {
- description.appendText(message);
- }
-
- @Factory
- public static Matcher<TextView> hasCompoundDrawables(int left, int top, int right, int bottom) {
- return new HasCompoundDrawablesMatcher(left, top, right, bottom);
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/matchers/HasResourceMatcher.java b/v1/src/main/java/com/xtremelabs/robolectric/matchers/HasResourceMatcher.java
deleted file mode 100644
index 12928e684..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/matchers/HasResourceMatcher.java
+++ /dev/null
@@ -1,46 +0,0 @@
-package com.xtremelabs.robolectric.matchers;
-
-import android.widget.ImageView;
-import org.hamcrest.Description;
-import org.hamcrest.Factory;
-import org.hamcrest.Matcher;
-import org.junit.internal.matchers.TypeSafeMatcher;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-
-public class HasResourceMatcher extends TypeSafeMatcher<ImageView> {
- private int expectedResourceId;
- private Integer actualResourceId;
-
- public HasResourceMatcher(int expectedResourceId) {
- this.expectedResourceId = expectedResourceId;
- }
-
- @Override
- public boolean matchesSafely(ImageView actual) {
- if (actual == null) {
- return false;
- }
-
- actualResourceId = shadowOf(actual).getResourceId();
-
- return actualResourceId == expectedResourceId;
- }
-
- @Override
- public void describeTo(Description description) {
- if (actualResourceId == null) {
- description.appendText("actual view was null");
- } else {
- description.appendText("[" + actualResourceId + "]");
- description.appendText(" to equal ");
- description.appendText("[" + expectedResourceId + "]");
- }
- }
-
- @Factory
- public static Matcher<ImageView> hasResource(int expectedResourceId) {
- return new HasResourceMatcher(expectedResourceId);
- }
-
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/matchers/ImageViewHasDrawableMatcher.java b/v1/src/main/java/com/xtremelabs/robolectric/matchers/ImageViewHasDrawableMatcher.java
deleted file mode 100644
index 81d17e2f3..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/matchers/ImageViewHasDrawableMatcher.java
+++ /dev/null
@@ -1,49 +0,0 @@
-package com.xtremelabs.robolectric.matchers;
-
-import android.widget.ImageView;
-import com.xtremelabs.robolectric.res.ResourceLoader;
-import org.hamcrest.Description;
-import org.hamcrest.Factory;
-import org.hamcrest.Matcher;
-import org.junit.internal.matchers.TypeSafeMatcher;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-
-public class ImageViewHasDrawableMatcher<T extends ImageView> extends TypeSafeMatcher<T> {
- private int expectedResourceId;
- private String message;
-
- public ImageViewHasDrawableMatcher(int expectedResourceId) {
- this.expectedResourceId = expectedResourceId;
- }
-
- @Override
- public boolean matchesSafely(T actualImageView) {
- if (actualImageView == null) {
- return false;
- }
-
- ResourceLoader resourceLoader = ResourceLoader.getFrom(actualImageView.getContext());
-
- int actualResourceId = shadowOf(actualImageView).getResourceId();
- String actualName = nameOrUnset(resourceLoader, actualResourceId);
- String expectedName = nameOrUnset(resourceLoader, expectedResourceId);
- message = "[" + actualResourceId + " (" + actualName + ")] to equal [" + expectedResourceId + " (" + expectedName + ")]";
- return actualResourceId == expectedResourceId;
- }
-
- private String nameOrUnset(ResourceLoader resourceLoader, int resourceId) {
- return resourceId == 0 ? "unset" : resourceLoader.getNameForId(resourceId);
- }
-
-
- @Override
- public void describeTo(Description description) {
- description.appendText(message);
- }
-
- @Factory
- public static <T extends ImageView> Matcher<T> hasDrawable(int expectedResourceId) {
- return new ImageViewHasDrawableMatcher<T>(expectedResourceId);
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/matchers/StartedMatcher.java b/v1/src/main/java/com/xtremelabs/robolectric/matchers/StartedMatcher.java
deleted file mode 100644
index 569ba9413..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/matchers/StartedMatcher.java
+++ /dev/null
@@ -1,89 +0,0 @@
-package com.xtremelabs.robolectric.matchers;
-
-import android.app.Activity;
-import android.content.Context;
-import android.content.ContextWrapper;
-import android.content.Intent;
-import com.xtremelabs.robolectric.shadows.ShadowIntent;
-import org.hamcrest.Description;
-import org.junit.internal.matchers.TypeSafeMatcher;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-
-public class StartedMatcher extends TypeSafeMatcher<Context> {
- private final Intent expectedIntent;
-
- private String message;
-
- public StartedMatcher(Intent expectedIntent) {
- this.expectedIntent = expectedIntent;
- }
-
- public StartedMatcher(String packageName, Class<? extends Activity> expectedActivityClass) {
- this(createIntent(packageName, expectedActivityClass));
- }
-
- public StartedMatcher(Class<? extends Activity> expectedActivityClass) {
- this(createIntent(expectedActivityClass));
- }
-
- public StartedMatcher(Class<? extends Activity> expectedActivityClass, String expectedAction) {
- this(createIntent(expectedActivityClass));
-
- expectedIntent.setAction(expectedAction);
- }
-
- @Override
- public boolean matchesSafely(Context actualContext) {
- if (expectedIntent == null) {
- message = "null intent (did you mean to expect null?)";
- return false;
- }
-
- String expected = expectedIntent.toString();
- message = "to start " + expected + ", but ";
-
- Intent actualStartedIntent = shadowOf((ContextWrapper) actualContext).getNextStartedActivity();
-
- if (actualStartedIntent == null) {
- message += "didn't start anything";
- return false;
- }
-
- ShadowIntent shadowIntent = shadowOf(actualStartedIntent);
-
- boolean intentsMatch = shadowOf(expectedIntent).realIntentEquals(shadowIntent);
- if (!intentsMatch) {
- message += "started " + actualStartedIntent;
- }
- return intentsMatch;
- }
-
- @Override
- public void describeTo(Description description) {
- description.appendText(message);
- }
-
- public static Intent createIntent(Class<? extends Activity> activityClass, String extraKey, String extraValue) {
- Intent intent = createIntent(activityClass);
- intent.putExtra(extraKey, extraValue);
- return intent;
- }
-
- public static Intent createIntent(Class<? extends Activity> activityClass, String action) {
- Intent intent = createIntent(activityClass);
- intent.setAction(action);
- return intent;
- }
-
- public static Intent createIntent(Class<? extends Activity> activityClass) {
- String packageName = activityClass.getPackage().getName();
- return createIntent(packageName, activityClass);
- }
-
- public static Intent createIntent(String packageName, Class<? extends Activity> activityClass) {
- Intent intent = new Intent();
- intent.setClassName(packageName, activityClass.getName());
- return intent;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/matchers/StartedServiceMatcher.java b/v1/src/main/java/com/xtremelabs/robolectric/matchers/StartedServiceMatcher.java
deleted file mode 100644
index ce1dfe1ff..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/matchers/StartedServiceMatcher.java
+++ /dev/null
@@ -1,115 +0,0 @@
-package com.xtremelabs.robolectric.matchers;
-
-import android.app.Service;
-import android.content.Context;
-import android.content.ContextWrapper;
-import android.content.Intent;
-import com.xtremelabs.robolectric.shadows.ShadowIntent;
-import org.hamcrest.Description;
-import org.junit.internal.matchers.TypeSafeMatcher;
-
-import java.util.Set;
-
-import static com.xtremelabs.robolectric.Robolectric.getShadowApplication;
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-
-public class StartedServiceMatcher extends TypeSafeMatcher<Context> {
- private final Intent expectedIntent;
-
- private String message;
-
- public StartedServiceMatcher(Intent expectedIntent) {
- this.expectedIntent = expectedIntent;
- }
-
- public StartedServiceMatcher(String packageName, Class<? extends Service> expectedServiceClass) {
- this(createIntent(packageName, expectedServiceClass));
- }
-
- public StartedServiceMatcher(Class<? extends Service> expectedServiceClass) {
- this(createIntent(expectedServiceClass));
- }
-
- public StartedServiceMatcher(Class<? extends Service> expectedServiceClass, String expectedAction) {
- this(createIntent(expectedServiceClass));
-
- expectedIntent.setAction(expectedAction);
- }
-
- /**
- * Check if the class of the intent and the keys of the intent's extras match
- *
- * @param actualContext
- * @return
- */
- @Override
- public boolean matchesSafely(Context actualContext) {
- if (expectedIntent == null) {
- message = "null intent (did you mean to expect null?)";
- return false;
- }
-
- String expected = expectedIntent.toString();
- message = "to start " + expected + ", but ";
-
- Intent actualStartedIntent = shadowOf((ContextWrapper) actualContext).getNextStartedService();
-
- if (actualStartedIntent == null) {
- message += "didn't start anything";
- return false;
- }
-
- ShadowIntent shadowIntent = shadowOf(actualStartedIntent);
-
- //boolean intentsMatch = shadowOf(expectedIntent).realIntentEquals(shadowIntent);
- // Test only that we are sending intent to the right service class
- boolean intentsMatch = shadowOf(expectedIntent).getIntentClass().equals(shadowIntent.getIntentClass());
- if (!intentsMatch) {
- message += "started " + actualStartedIntent;
- } else {
- // Test that both intent extras have the same keys
- Set<String> keys = shadowIntent.getExtras().keySet();
- Set<String> expectedKeys = shadowOf(expectedIntent).getExtras().keySet();
- intentsMatch = keys.equals(expectedKeys);
- if(!intentsMatch){
- message += "did not get the same extras keys";
- }
- }
-
- return intentsMatch;
- }
-
- @Override
- public void describeTo(Description description) {
- description.appendText(message);
- }
-
- public static Intent createIntent(Class<? extends Service> serviceClass, String extraKey, String extraValue) {
- Intent intent = createIntent(serviceClass);
- intent.putExtra(extraKey, extraValue);
- return intent;
- }
-
- public static Intent createIntent(Class<? extends Service> serviceClass, String action) {
- Intent intent = createIntent(serviceClass);
- intent.setAction(action);
- return intent;
- }
-
- public static Intent createIntent(Class<? extends Service> serviceClass) {
- Package pack = serviceClass.getPackage();
- String packageName = "android.service";
- // getPackage is returning null when run from tests
- if(pack != null) {
- pack.getName();
- }
- return createIntent(packageName, serviceClass);
- }
-
- public static Intent createIntent(String packageName, Class<? extends Service> serviceClass) {
- Intent intent = new Intent();
- intent.setClassName(packageName, serviceClass.getName());
- intent.setClass(getShadowApplication().getApplicationContext(), serviceClass);
- return intent;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/matchers/TextViewHasTextMatcher.java b/v1/src/main/java/com/xtremelabs/robolectric/matchers/TextViewHasTextMatcher.java
deleted file mode 100644
index 3fd468ad1..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/matchers/TextViewHasTextMatcher.java
+++ /dev/null
@@ -1,42 +0,0 @@
-package com.xtremelabs.robolectric.matchers;
-
-import android.widget.TextView;
-import org.hamcrest.Description;
-import org.hamcrest.Factory;
-import org.hamcrest.Matcher;
-import org.junit.internal.matchers.TypeSafeMatcher;
-
-public class TextViewHasTextMatcher<T extends TextView> extends TypeSafeMatcher<T> {
- private String expected;
- private String actualText;
-
- public TextViewHasTextMatcher(String expected) {
- this.expected = expected;
- }
-
- @Override
- public boolean matchesSafely(T actual) {
- if (actual == null) {
- return false;
- }
- final CharSequence charSequence = actual.getText();
- if (charSequence == null || charSequence.toString() == null) {
- return false;
- }
- actualText = charSequence.toString();
- return actualText.equals(expected);
- }
-
-
- @Override
- public void describeTo(Description description) {
- description.appendText("[" + actualText + "]");
- description.appendText(" to equal ");
- description.appendText("[" + expected + "]");
- }
-
- @Factory
- public static <T extends TextView> Matcher<T> hasText(String expectedTextViewText) {
- return new TextViewHasTextMatcher<T>(expectedTextViewText);
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/matchers/ViewHasTextMatcher.java b/v1/src/main/java/com/xtremelabs/robolectric/matchers/ViewHasTextMatcher.java
deleted file mode 100644
index 6cb1fcd4b..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/matchers/ViewHasTextMatcher.java
+++ /dev/null
@@ -1,62 +0,0 @@
-package com.xtremelabs.robolectric.matchers;
-
-import android.view.View;
-import org.hamcrest.Description;
-import org.hamcrest.Factory;
-import org.hamcrest.Matcher;
-import org.junit.internal.matchers.TypeSafeMatcher;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-
-public class ViewHasTextMatcher<T extends View> extends TypeSafeMatcher<T> {
- private String expected;
- private int expectedResourceId;
- private String actualText;
-
- public ViewHasTextMatcher(String expected) {
- this.expected = expected;
- expectedResourceId = -1;
- }
-
- public ViewHasTextMatcher(int expectedResourceId) {
- this.expected = null;
- this.expectedResourceId = expectedResourceId;
- }
-
- @Override
- public boolean matchesSafely(View actual) {
- if (actual == null) {
- return false;
- }
-
- if (expectedResourceId != -1) {
- expected = actual.getContext().getResources().getString(expectedResourceId);
- }
-
- final CharSequence charSequence = shadowOf(actual).innerText();
- if (charSequence == null || charSequence.toString() == null) {
- return false;
- }
- actualText = charSequence.toString();
-
- return actualText.equals(expected);
- }
-
- @Override
- public void describeTo(Description description) {
- description.appendText("[" + actualText + "]");
- description.appendText(" to equal ");
- description.appendText("[" + expected + "]");
- }
-
-
- @Factory
- public static <T extends View> Matcher<T> hasText(String expectedTextViewText) {
- return new ViewHasTextMatcher<T>(expectedTextViewText);
- }
-
- @Factory
- public static <T extends View> Matcher<T> hasText(int expectedTextViewResourceId) {
- return new ViewHasTextMatcher<T>(expectedTextViewResourceId);
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/res/AttrResourceLoader.java b/v1/src/main/java/com/xtremelabs/robolectric/res/AttrResourceLoader.java
deleted file mode 100644
index 1ec1dd436..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/res/AttrResourceLoader.java
+++ /dev/null
@@ -1,73 +0,0 @@
-package com.xtremelabs.robolectric.res;
-
-import android.view.View;
-import org.w3c.dom.Document;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-
-import javax.xml.xpath.XPathConstants;
-import javax.xml.xpath.XPathExpression;
-import javax.xml.xpath.XPathFactory;
-import java.io.File;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Map;
-import java.util.Set;
-
-public class AttrResourceLoader extends XmlLoader {
- Map<String, String> classAttrEnumToValue = new HashMap<String, String>();
- Set<String> knownClassAttrs = new HashSet<String>();
-
- public AttrResourceLoader(ResourceExtractor resourceExtractor) {
- super(resourceExtractor);
- }
-
- @Override
- protected void processResourceXml(File xmlFile, Document document, boolean isSystem) throws Exception {
- XPathExpression stringsXPath = XPathFactory.newInstance().newXPath().compile("/resources/declare-styleable/attr/enum");
- NodeList stringNodes = (NodeList) stringsXPath.evaluate(document, XPathConstants.NODESET);
- for (int i = 0; i < stringNodes.getLength(); i++) {
- Node node = stringNodes.item(i);
- String viewName = node.getParentNode().getParentNode().getAttributes().getNamedItem("name").getNodeValue();
- String enumName = node.getParentNode().getAttributes().getNamedItem("name").getNodeValue();
- String name = node.getAttributes().getNamedItem("name").getNodeValue();
- String value = node.getAttributes().getNamedItem("value").getNodeValue();
-
- classAttrEnumToValue.put(key(viewName, enumName, name, isSystem), value);
- knownClassAttrs.add(key(viewName, enumName, isSystem));
- }
- }
-
- public String convertValueToEnum(Class<? extends View> viewClass, String namespace, String attrName, String attrValue) {
- boolean isSystem = "android".equals(namespace);
- String className = findKnownAttrClass(attrName, viewClass, isSystem);
- return classAttrEnumToValue.get(key(className, attrName, attrValue, isSystem));
- }
-
- public boolean hasAttributeFor(Class<? extends View> viewClass, String namespace, String attrName) {
- boolean isSystem = "android".equals(namespace);
- return findKnownAttrClass(attrName, viewClass, isSystem) != null;
- }
-
- private String findKnownAttrClass(String attrName, Class<?> clazz, boolean isSystem) {
- while (clazz != null) {
- String className = clazz.getName();
- if (isSystem) {
- className = clazz.getSimpleName();
- }
- if (knownClassAttrs.contains(key(className, attrName, isSystem))) {
- return className;
- }
- clazz = clazz.getSuperclass();
- }
- return null;
- }
-
- private String key(String viewName, String attrName, String name, boolean isSystem) {
- return key(viewName, attrName, isSystem) + "#" + name;
- }
-
- private String key(String viewName, String attrName, boolean isSystem) {
- return (isSystem ? "android:" : "") + viewName + "#" + attrName;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/res/ColorResourceLoader.java b/v1/src/main/java/com/xtremelabs/robolectric/res/ColorResourceLoader.java
deleted file mode 100644
index f81046daa..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/res/ColorResourceLoader.java
+++ /dev/null
@@ -1,56 +0,0 @@
-package com.xtremelabs.robolectric.res;
-
-import android.graphics.Color;
-import org.w3c.dom.Node;
-
-import java.util.HashMap;
-import java.util.Map;
-
-public class ColorResourceLoader extends XpathResourceXmlLoader implements ResourceValueConverter {
- private ResourceReferenceResolver<Integer> colorResolver = new ResourceReferenceResolver<Integer>("color");
- private static Map<String, Integer> androidColors = new HashMap<String, Integer>();
-
- static {
- androidColors.put("black", Color.BLACK);
- androidColors.put("darkgray", Color.DKGRAY);
- androidColors.put("gray", Color.GRAY);
- androidColors.put("lightgray", Color.LTGRAY);
- androidColors.put("white", Color.WHITE);
- androidColors.put("red", Color.RED);
- androidColors.put("green", Color.GREEN);
- androidColors.put("blue", Color.BLUE);
- androidColors.put("yellow", Color.YELLOW);
- androidColors.put("cyan", Color.CYAN);
- androidColors.put("magenta", Color.MAGENTA);
- }
-
- public ColorResourceLoader(ResourceExtractor resourceExtractor) {
- super(resourceExtractor, "/resources/color");
- }
-
- public int getValue(int colorId) {
- String resourceName = resourceExtractor.getResourceName(colorId);
- if (resourceName == null) {
- return -1;
- }
-
- Integer colorResolverValue = colorResolver.getValue(resourceName);
- return colorResolverValue == null ? -1 : colorResolverValue;
- }
-
- @Override
- protected void processNode(Node node, String name, boolean isSystem) {
- colorResolver.processResource(name, node.getTextContent(), this, isSystem);
- }
-
- @Override
- public Integer convertRawValue(String rawValue) {
- if (rawValue.startsWith("#")) {
- long color = Long.parseLong(rawValue.substring(1), 16);
- return (int) color;
- } else if (androidColors.containsKey(rawValue)) {
- return androidColors.get(rawValue);
- }
- return null;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/res/DimenResourceLoader.java b/v1/src/main/java/com/xtremelabs/robolectric/res/DimenResourceLoader.java
deleted file mode 100644
index 46eeb7d7c..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/res/DimenResourceLoader.java
+++ /dev/null
@@ -1,41 +0,0 @@
-package com.xtremelabs.robolectric.res;
-
-import org.w3c.dom.Node;
-public class DimenResourceLoader extends XpathResourceXmlLoader implements ResourceValueConverter {
-
- private static final String[] UNITS = { "dp", "dip", "px", "sp", "mm" };
-
- private ResourceReferenceResolver<Float> dimenResolver =
- new ResourceReferenceResolver<Float>("dimen", new String[] { "dimen", "integer" });
-
- public DimenResourceLoader(ResourceExtractor resourceExtractor) {
- super(resourceExtractor, "/resources/dimen");
- }
-
- public float getValue(int resourceId) {
- return dimenResolver.getValue(resourceExtractor.getResourceName(resourceId));
- }
-
- public float getValue(String resourceName, boolean isSystem) {
- return getValue(resourceExtractor.getResourceId(resourceName, isSystem));
- }
-
- @Override
- protected void processNode(Node node, String name, boolean isSystem) {
- dimenResolver.processResource(name, node.getTextContent(), this, isSystem);
- }
-
- @Override
- public Object convertRawValue(String rawValue) {
- int end = rawValue.length();
- for ( int i = 0; i < UNITS.length; i++ ) {
- int index = rawValue.indexOf(UNITS[i]);
- if ( index >= 0 && end > index ) {
- end = index;
- }
- }
-
- return Float.parseFloat(rawValue.substring(0, end));
- }
-}
-
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/res/DocumentLoader.java b/v1/src/main/java/com/xtremelabs/robolectric/res/DocumentLoader.java
deleted file mode 100644
index b4eb1d510..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/res/DocumentLoader.java
+++ /dev/null
@@ -1,67 +0,0 @@
-package com.xtremelabs.robolectric.res;
-
-import org.w3c.dom.Document;
-
-import javax.xml.parsers.DocumentBuilder;
-import javax.xml.parsers.DocumentBuilderFactory;
-import java.io.File;
-import java.io.FileFilter;
-
-public class DocumentLoader {
- private final XmlLoader[] xmlLoaders;
- private final DocumentBuilderFactory documentBuilderFactory;
- private FileFilter xmlFileFilter = new FileFilter() {
- @Override public boolean accept(File file) {
- return file.getName().endsWith(".xml");
- }
- };
-
- public DocumentLoader(XmlLoader... xmlLoaders) {
- this.xmlLoaders = xmlLoaders;
-
- documentBuilderFactory = DocumentBuilderFactory.newInstance();
- documentBuilderFactory.setNamespaceAware(true);
- documentBuilderFactory.setIgnoringComments(true);
- documentBuilderFactory.setIgnoringElementContentWhitespace(true);
- }
-
- public void loadResourceXmlDirs(File... resourceXmlDirs) throws Exception {
- loadResourceXmlDirs(false, resourceXmlDirs);
- }
-
- public void loadResourceXmlDirs(boolean isSystem, File... resourceXmlDirs) throws Exception {
- for (File resourceXmlDir : resourceXmlDirs) {
- loadResourceXmlDir(resourceXmlDir, isSystem);
- }
- }
-
- public void loadResourceXmlDir(File resourceXmlDir) throws Exception {
- loadResourceXmlDir(resourceXmlDir, false);
- }
-
- public void loadSystemResourceXmlDir(File resourceXmlDir) throws Exception {
- loadResourceXmlDir(resourceXmlDir, true);
- }
-
- private void loadResourceXmlDir(File resourceXmlDir, boolean isSystem) throws Exception {
- if (!resourceXmlDir.exists()) {
- throw new RuntimeException("no such directory " + resourceXmlDir);
- }
-
- for (File file : resourceXmlDir.listFiles(xmlFileFilter)) {
- loadResourceXmlFile(file, isSystem);
- }
- }
-
- private void loadResourceXmlFile(File file, boolean isSystem) throws Exception {
- for (XmlLoader xmlLoader : xmlLoaders) {
- xmlLoader.processResourceXml(file, parse(file), isSystem);
- }
- }
-
- private Document parse(File xmlFile) throws Exception {
- DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
- return documentBuilder.parse(xmlFile);
- }
-
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/res/DrawableResourceLoader.java b/v1/src/main/java/com/xtremelabs/robolectric/res/DrawableResourceLoader.java
deleted file mode 100644
index bac82e164..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/res/DrawableResourceLoader.java
+++ /dev/null
@@ -1,188 +0,0 @@
-package com.xtremelabs.robolectric.res;
-
-import android.R;
-import android.graphics.drawable.AnimationDrawable;
-import android.graphics.drawable.Drawable;
-import android.graphics.drawable.LayerDrawable;
-import android.graphics.drawable.StateListDrawable;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.shadows.ShadowStateListDrawable;
-import org.w3c.dom.Document;
-import org.w3c.dom.NamedNodeMap;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-
-import java.io.File;
-import java.io.IOException;
-import java.util.HashMap;
-import java.util.Map;
-
-/**
- * DrawableResourceLoader
- */
-public class DrawableResourceLoader extends XmlLoader {
-
- // Put all the states for a StateListDrawable in the into a Map for looking up
- // http://developer.android.com/guide/topics/resources/drawable-resource.html#StateList
- private static final Map<String, Integer> stateMap = new HashMap<String, Integer>();
- static {
- stateMap.put("android:state_selected", R.attr.state_selected);
- stateMap.put("android:state_pressed", R.attr.state_pressed);
- stateMap.put("android:state_focused", R.attr.state_focused);
- stateMap.put("android:state_checkable", R.attr.state_checkable);
- stateMap.put("android:state_checked", R.attr.state_checked);
- stateMap.put("android:state_enabled", R.attr.state_enabled);
- stateMap.put("android:state_window_focused", R.attr.state_window_focused);
- }
-
- /** document */
- protected Map<String, Document> documents = new HashMap<String, Document>();
-
- /** resource directory */
- protected File resourceDirectory;
-
- /**
- * DrawableResourceLoader constructor.
- *
- * @param extractor Extractor
- * @param resourceDirectory Resource directory
- */
- public DrawableResourceLoader(ResourceExtractor extractor, File resourceDirectory) {
- super(extractor);
- this.resourceDirectory = resourceDirectory;
- }
-
- /**
- * Check if resource is xml.
- *
- * @param resourceId Resource id
- * @return Boolean
- */
- public boolean isXml(int resourceId) {
- return documents.containsKey(resourceExtractor.getResourceName(resourceId));
- }
-
- public Drawable getXmlDrawable(int resId) {
-
- if (!isXml(resId)) {
- return null;
- }
-
- Document xmlDoc = documents.get(resourceExtractor.getResourceName(resId));
- NodeList nodes = xmlDoc.getElementsByTagName("selector");
- if (nodes != null && nodes.getLength() > 0) {
- return buildStateListDrawable(xmlDoc);
- }
-
- nodes = xmlDoc.getElementsByTagName("layer-list");
- if (nodes != null && nodes.getLength() > 0) {
- return new LayerDrawable(null);
- }
-
- nodes = xmlDoc.getElementsByTagName("animation-list");
- if (nodes != null && nodes.getLength() > 0) {
- return new AnimationDrawable();
- }
-
- return null;
- }
-
- /**
- * Store document locally keyed by resource name.
- *
- * @param xmlFile Xml file
- * @param document Document
- * @param isSystem System resource
- * @throws Exception
- * @see com.xtremelabs.robolectric.res.XmlLoader#processResourceXml(java.io.File,
- * org.w3c.dom.Document, boolean)
- */
- @Override
- protected void processResourceXml(File xmlFile, Document document, boolean isSystem) throws Exception {
- String name = toResourceName(xmlFile);
- if (!documents.containsKey(name)) {
- if (isSystem) {
- name = "android:" + name;
- }
- documents.put(name, document);
- }
- }
-
- /**
- * Convert file name to resource name.
- *
- * @param xmlFile Xml File
- * @return Resource name
- */
- private String toResourceName(File xmlFile) {
- try {
- return xmlFile.getCanonicalPath().replaceAll("[/\\\\\\\\]", "/")
- .replaceAll("^.*?/res/", "").replaceAll("\\..+$", "");
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
-
-
- /**
- * Get drawables by resource id.
- *
- * @param resourceId Resource id
- * @return Drawables
- */
- protected int[] getDrawableIds(int resourceId) {
- String resourceName = resourceExtractor.getResourceName(resourceId);
- Document document = documents.get(resourceName);
-
- NodeList items = document.getElementsByTagName("item");
- int[] drawableIds = new int[items.getLength()];
-
- for (int i = 0; i < items.getLength(); i++) {
- if (resourceName.startsWith("android:")) {
- drawableIds[i] = -1;
- } else {
- Node item = items.item(i);
- Node drawableName = item.getAttributes().getNamedItem("android:drawable");
- if (drawableName != null) {
- drawableIds[i] = resourceExtractor.getResourceId(drawableName.getNodeValue());
- }
- }
- }
-
- return drawableIds;
- }
-
- public boolean isAnimationDrawable(int resourceId) {
- Document document = documents.get(resourceExtractor.getResourceName(resourceId));
- return "animation-list".equals(document.getDocumentElement().getLocalName());
- }
-
- private StateListDrawable buildStateListDrawable(Document d) {
- StateListDrawable drawable = new StateListDrawable();
- ShadowStateListDrawable shDrawable = Robolectric.shadowOf(drawable);
- NodeList items = d.getElementsByTagName("item");
- for (int i = 0; i < items.getLength(); i++) {
- Node node = items.item(i);
- Node drawableName = node.getAttributes().getNamedItem("android:drawable");
- if (drawableName != null) {
- int resId = resourceExtractor.getResourceId(drawableName.getNodeValue());
- int stateId = getStateId(node);
- shDrawable.addState(stateId, resId);
- }
- }
- return drawable;
- }
-
- private int getStateId(Node node) {
- NamedNodeMap attrs = node.getAttributes();
- for (String state : stateMap.keySet()) {
- Node attr = attrs.getNamedItem(state);
- if (attr != null) {
- return stateMap.get(state);
- }
- }
-
- // if a state wasn't specified, return the default state
- return R.attr.state_active;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/res/IntegerResourceLoader.java b/v1/src/main/java/com/xtremelabs/robolectric/res/IntegerResourceLoader.java
deleted file mode 100644
index 3bc4b24c9..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/res/IntegerResourceLoader.java
+++ /dev/null
@@ -1,52 +0,0 @@
-package com.xtremelabs.robolectric.res;
-
-import org.w3c.dom.Node;
-
-public class IntegerResourceLoader extends XTagXmlResourceLoader implements ResourceValueConverter {
-
- private final ResourceReferenceResolver< Integer > integerResolver = new ResourceReferenceResolver< Integer >( "integer" );
-
- public IntegerResourceLoader( ResourceExtractor resourceExtractor ) {
- super( resourceExtractor, "integer" );
- }
-
- public int getValue( int resourceId ) {
- final String resourceIdDebugString = String.valueOf(resourceId) + " (" + "0x" + Integer.toHexString(resourceId) + ")";
- String resourceName = resourceExtractor.getResourceName(resourceId);
- if (resourceName == null) {
- throw new IllegalArgumentException("No such resource: " + resourceId);
- }
- Integer value = integerResolver.getValue(resourceName);
- if (value == null) { // instead of auto-unboxing NPE
- throw new IllegalArgumentException("Got resource name " + resourceName + " from id " + resourceIdDebugString
- + ", but found no resource by that name");
- }
- return value;
- }
-
- public int getValue( String resourceName, boolean isSystem ) {
- Integer resourceId = resourceExtractor.getResourceId(resourceName, isSystem);
- if (resourceName == null) {
- throw new IllegalArgumentException("No such resource (" + isSystem + "): " + resourceName);
- }
- return getValue(resourceId);
- }
-
- @Override
- public Object convertRawValue( String rawValue ) {
- try {
- // Decode into long, because there are some large hex values in the android resource files
- // (e.g. config_notificationsBatteryLowARGB = 0xFFFF0000 in sdk 14).
- // Integer.decode() does not support large, i.e. negative values in hex numbers.
- return (int) Long.decode(rawValue).longValue();
- } catch ( NumberFormatException nfe ) {
- throw new RuntimeException( rawValue + " is not an integer." , nfe );
- }
- }
-
- @Override
- protected void processNode( Node node, String name, boolean isSystem ) {
- integerResolver.processResource( name, node.getTextContent(), this, isSystem );
- }
-
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/res/MenuLoader.java b/v1/src/main/java/com/xtremelabs/robolectric/res/MenuLoader.java
deleted file mode 100644
index 8f2ba007b..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/res/MenuLoader.java
+++ /dev/null
@@ -1,184 +0,0 @@
-package com.xtremelabs.robolectric.res;
-
-import java.io.File;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.w3c.dom.Document;
-import org.w3c.dom.NamedNodeMap;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-
-import android.content.Context;
-import android.text.TextUtils;
-import android.view.Menu;
-import android.view.MenuItem;
-import android.view.SubMenu;
-
-import com.xtremelabs.robolectric.tester.android.util.TestAttributeSet;
-import com.xtremelabs.robolectric.util.I18nException;
-
-public class MenuLoader extends XmlLoader {
- private Map<String, MenuNode> menuNodesByMenuName = new HashMap<String, MenuNode>();
- private AttrResourceLoader attrResourceLoader;
-
- public MenuLoader(ResourceExtractor resourceExtractor, AttrResourceLoader attrResourceLoader) {
- super(resourceExtractor);
- this.attrResourceLoader = attrResourceLoader;
- }
-
- @Override
- protected void processResourceXml(File xmlFile, Document document, boolean ignored) throws Exception {
- MenuNode topLevelNode = new MenuNode("top-level", new HashMap<String, String>());
-
- NodeList items = document.getChildNodes();
- if (items.getLength() != 1)
- throw new RuntimeException("Expected only one top-level item in menu file " + xmlFile.getName());
- if (items.item(0).getNodeName().compareTo("menu") != 0)
- throw new RuntimeException("Expected a top-level item called 'menu' in menu file " + xmlFile.getName());
-
- processChildren(items.item(0).getChildNodes(), topLevelNode);
- menuNodesByMenuName.put("menu/" + xmlFile.getName().replace(".xml", ""), topLevelNode);
- }
-
- private void processChildren(NodeList childNodes, MenuNode parent) {
- for (int i = 0; i < childNodes.getLength(); i++) {
- Node node = childNodes.item(i);
- processNode(node, parent);
- }
- }
-
- private void processNode(Node node, MenuNode parent) {
- String name = node.getNodeName();
- NamedNodeMap attributes = node.getAttributes();
- Map<String, String> attrMap = new HashMap<String, String>();
- if (attributes != null) {
- int length = attributes.getLength();
- for (int i = 0; i < length; i++) {
- Node attr = attributes.item(i);
- attrMap.put(attr.getNodeName(), attr.getNodeValue());
- }
- }
-
- if (!name.startsWith("#")) {
- MenuNode menuNode = new MenuNode(name, attrMap);
- parent.addChild(menuNode);
- NodeList children = node.getChildNodes();
- if (children != null && children.getLength() != 0) {
- for (int i = 0; i < children.getLength(); i++) {
- Node nodei = children.item(i);
- if (childToIgnore(nodei)) {
- continue;
- } else if (validChildren(nodei)) {
- // recursively add all nodes
- processNode(nodei, menuNode);
- } else {
- throw new RuntimeException("Unknown menu node"
- + nodei.getNodeName());
- }
- }
- }
- }
- }
-
- private static boolean childToIgnore(Node nodei) {
- return TextUtils.isEmpty(nodei.getNodeName())
- || nodei.getNodeName().startsWith("#");
- }
-
- private static boolean validChildren(Node nodei) {
- return nodei.getNodeName().equals("item")
- || nodei.getNodeName().equals("menu")
- || nodei.getNodeName().equals("group");
- }
-
- public void inflateMenu(Context context, String key, Menu root) {
- inflateMenu(context, key, null, root);
- }
-
- public void inflateMenu(Context context, int resourceId, Menu root) {
- inflateMenu(context, resourceExtractor.getResourceName(resourceId),
- root);
- }
-
- private void inflateMenu(Context context, String key,
- Map<String, String> attributes, Menu root) {
- MenuNode menuNode = menuNodesByMenuName.get(key);
- if (menuNode == null) {
- throw new RuntimeException("Could not find menu " + key);
- }
- try {
- if (attributes != null) {
- for (Map.Entry<String, String> entry : attributes.entrySet()) {
- if (!entry.getKey().equals("menu")) {
- menuNode.attributes.put(entry.getKey(),
- entry.getValue());
- }
- }
- }
- menuNode.inflate(context, root);
- } catch (I18nException e) {
- throw e;
- } catch (Exception e) {
- throw new RuntimeException("error inflating " + key, e);
- }
- }
-
- public class MenuNode {
- private String name;
- private final TestAttributeSet attributes;
-
- private List<MenuNode> children = new ArrayList<MenuNode>();
-
- public MenuNode(String name, Map<String, String> attributes) {
- this.name = name;
- this.attributes = new TestAttributeSet(attributes,
- resourceExtractor, attrResourceLoader, null, false);
- }
-
- public List<MenuNode> getChildren() {
- return children;
- }
-
- public void addChild(MenuNode MenuNode) {
- children.add(MenuNode);
- }
-
- private boolean isSubMenuItem(MenuNode child) {
- List<MenuLoader.MenuNode> ch = child.children;
- return ch != null && ch.size() == 1 && "menu".equals(ch.get(0).name);
- }
-
- private void addChildrenInGroup(MenuNode source, int groupId, Menu root) {
- for (MenuNode child : source.children) {
- String name = child.name;
- TestAttributeSet attributes = child.attributes;
- if (strictI18n) {
- attributes.validateStrictI18n();
- }
- if (name.equals("item")) {
- if (isSubMenuItem(child)) {
- SubMenu sub = root.addSubMenu(groupId, attributes
- .getAttributeResourceValue("android", "id", 0),
- 0, attributes.getAttributeValue("android", "title"));
- MenuNode subMenuNode = child.children.get(0);
- addChildrenInGroup(subMenuNode, groupId, sub);
- } else {
- MenuItem menuItem = root.add(groupId, attributes
- .getAttributeResourceValue("android", "id", 0),
- 0, attributes.getAttributeValue("android", "title"));
- }
- } else if (name.equals("group")) {
- int newGroupId = attributes.getAttributeResourceValue("android", "id", 0);
- addChildrenInGroup(child, newGroupId, root);
- }
- }
- }
-
- public void inflate(Context context, Menu root) throws Exception {
- addChildrenInGroup(this, 0, root);
- }
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/res/PluralResourceLoader.java b/v1/src/main/java/com/xtremelabs/robolectric/res/PluralResourceLoader.java
deleted file mode 100644
index 6b4ec85f1..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/res/PluralResourceLoader.java
+++ /dev/null
@@ -1,96 +0,0 @@
-package com.xtremelabs.robolectric.res;
-
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-
-import javax.xml.xpath.XPathConstants;
-import javax.xml.xpath.XPathExpression;
-import javax.xml.xpath.XPathExpressionException;
-import javax.xml.xpath.XPathFactory;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-public class PluralResourceLoader extends XpathResourceXmlLoader implements ResourceValueConverter {
- Map<String, PluralRules> plurals = new HashMap<String, PluralRules>();
- private StringResourceLoader stringResourceLoader;
-
- public PluralResourceLoader(ResourceExtractor resourceExtractor, StringResourceLoader stringResourceLoader) {
- super(resourceExtractor, "/resources/plurals");
- this.stringResourceLoader = stringResourceLoader;
- }
-
- public String getValue(int resourceId, int quantity) {
- String name = resourceExtractor.getResourceName(resourceId);
- PluralRules rules = plurals.get(name);
- if (rules != null) {
- Plural p = rules.find(quantity);
- if (p != null) {
- return p.string;
- }
- }
- return null;
- }
-
- @Override protected void processNode(Node node, String name, boolean isSystem) throws XPathExpressionException {
- XPathExpression itemXPath = XPathFactory.newInstance().newXPath().compile("item");
- NodeList childNodes = (NodeList) itemXPath.evaluate(node, XPathConstants.NODESET);
- PluralRules rules = new PluralRules();
- for (int j = 0; j < childNodes.getLength(); j++) {
- Node childNode = childNodes.item(j);
- String value = childNode.getTextContent();
- String quantity = childNode.getAttributes().getNamedItem("quantity").getTextContent();
- if (value.startsWith("@")) {
- value = value.substring(1);
- rules.add(new Plural(quantity, stringResourceLoader.getValue(value, isSystem)));
- } else {
- rules.add(new Plural(quantity, value));
- }
- }
- plurals.put("plurals/" + name, rules);
- }
-
- @Override public Object convertRawValue(String rawValue) {
- return rawValue;
- }
-
- static class PluralRules {
- List<Plural> plurals = new ArrayList<Plural>();
-
- Plural find(int quantity) {
- for (Plural p : plurals) {
- if (p.num == quantity) return p;
- }
- for (Plural p : plurals) {
- if (p.num == -1) return p;
- }
- return null;
- }
-
- void add(Plural p) {
- plurals.add(p);
- }
- }
-
- static class Plural {
- final String quantity, string;
- final int num;
-
- Plural(String quantity, String string) {
- this.quantity = quantity;
- this.string = string;
- if ("zero".equals(quantity)) {
- num = 0;
- } else if ("one".equals(quantity)) {
- num = 1;
- } else if ("two".equals(quantity)) {
- num = 2;
- } else if ("other".equals(quantity)) {
- num = -1;
- } else {
- num = -1;
- }
- }
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/res/PreferenceLoader.java b/v1/src/main/java/com/xtremelabs/robolectric/res/PreferenceLoader.java
deleted file mode 100644
index 1d80ae490..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/res/PreferenceLoader.java
+++ /dev/null
@@ -1,162 +0,0 @@
-package com.xtremelabs.robolectric.res;
-
-import java.io.File;
-import java.lang.reflect.Constructor;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.w3c.dom.Document;
-import org.w3c.dom.NamedNodeMap;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.tester.android.util.TestAttributeSet;
-import com.xtremelabs.robolectric.util.I18nException;
-
-import android.content.Context;
-import android.preference.Preference;
-import android.preference.PreferenceGroup;
-import android.preference.PreferenceScreen;
-import android.util.AttributeSet;
-
-public class PreferenceLoader extends XmlLoader {
-
- private Map<String, PreferenceNode> prefNodesByResourceName = new HashMap<String, PreferenceNode>();
-
- public PreferenceLoader(ResourceExtractor resourceExtractor) {
- super(resourceExtractor);
- }
-
- @Override
- protected void processResourceXml(File xmlFile, Document document, boolean isSystem) throws Exception {
- PreferenceNode topLevelNode = new PreferenceNode("top-level", new HashMap<String, String>());
- processChildren(document.getChildNodes(), topLevelNode);
- prefNodesByResourceName.put( "xml/" + xmlFile.getName().replace(".xml", ""), topLevelNode.getChildren().get(0));
- }
-
- private void processChildren(NodeList childNodes, PreferenceNode parent) {
- for (int i = 0; i < childNodes.getLength(); i++) {
- Node node = childNodes.item(i);
- processNode(node, parent);
- }
- }
-
- private void processNode(Node node, PreferenceNode parent) {
- String name = node.getNodeName();
- NamedNodeMap attributes = node.getAttributes();
- Map<String, String> attrMap = new HashMap<String, String>();
-
- if (attributes != null) {
- int length = attributes.getLength();
- for (int i = 0; i < length; i++) {
- Node attr = attributes.item(i);
- attrMap.put(attr.getNodeName(), attr.getNodeValue());
- }
- }
-
- if (!name.startsWith("#")) {
- PreferenceNode prefNode = new PreferenceNode(name, attrMap);
- if (parent != null) parent.addChild(prefNode);
-
- processChildren(node.getChildNodes(), prefNode);
- }
- }
-
- public PreferenceScreen inflatePreferences(Context context, int resourceId) {
- return inflatePreferences(context, resourceExtractor.getResourceName(resourceId));
- }
-
- public PreferenceScreen inflatePreferences(Context context, String key) {
- try {
- PreferenceNode prefNode = prefNodesByResourceName.get(key);
- return (PreferenceScreen) prefNode.inflate(context, null);
- } catch (I18nException e) {
- throw e;
- } catch (Exception e) {
- throw new RuntimeException("error inflating " + key, e);
- }
- }
-
- public class PreferenceNode {
- private String name;
- private final Map<String, String> attributes;
-
- private List<PreferenceNode> children = new ArrayList<PreferenceNode>();
-
- public PreferenceNode(String name, Map<String, String> attributes) {
- this.name = name;
- this.attributes = attributes;
- }
-
- public List<PreferenceNode> getChildren() {
- return children;
- }
-
- public void addChild(PreferenceNode prefNode) {
- children.add(prefNode);
- }
-
- public Preference inflate(Context context, Preference parent) throws Exception {
- Preference preference = create(context, (PreferenceGroup) parent);
-
- for (PreferenceNode child : children) {
- child.inflate(context, preference);
- }
-
- return preference;
- }
-
- private Preference create(Context context, PreferenceGroup parent) throws Exception {
- Preference preference = constructPreference(context, parent);
- if (parent != null && parent != preference) {
- parent.addPreference(preference);
- }
- return preference;
- }
-
- private Preference constructPreference(Context context, PreferenceGroup parent) throws Exception {
- Class<? extends Preference> clazz = pickViewClass();
-
- if (clazz.equals(PreferenceScreen.class)) {
- return Robolectric.newInstanceOf(PreferenceScreen.class);
- }
-
- try {
- TestAttributeSet attributeSet = new TestAttributeSet(attributes);
- if (strictI18n) {
- attributeSet.validateStrictI18n();
- }
- return ((Constructor<? extends Preference>) clazz.getConstructor(Context.class, AttributeSet.class)).newInstance(context, attributeSet);
- } catch (NoSuchMethodException e) {
- try {
- return ((Constructor<? extends Preference>) clazz.getConstructor(Context.class)).newInstance(context);
- } catch (NoSuchMethodException e1) {
- return ((Constructor<? extends Preference>) clazz.getConstructor(Context.class, String.class)).newInstance(context, "");
- }
- }
- }
-
- private Class<? extends Preference> pickViewClass() {
- Class<? extends Preference> clazz = loadClass(name);
- if (clazz == null) {
- clazz = loadClass("android.preference." + name);
- }
- if (clazz == null) {
- throw new RuntimeException("couldn't find preference class " + name);
- }
- return clazz;
- }
-
- private Class<? extends Preference> loadClass(String className) {
- try {
- //noinspection unchecked
- return (Class<? extends Preference>) getClass().getClassLoader().loadClass(className);
- } catch (ClassNotFoundException e) {
- return null;
- }
- }
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/res/RawResourceLoader.java b/v1/src/main/java/com/xtremelabs/robolectric/res/RawResourceLoader.java
deleted file mode 100644
index da70f81d3..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/res/RawResourceLoader.java
+++ /dev/null
@@ -1,46 +0,0 @@
-package com.xtremelabs.robolectric.res;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.InputStream;
-
-public class RawResourceLoader {
-
- private ResourceExtractor resourceExtractor;
- private File resourceDir;
-
- public RawResourceLoader(ResourceExtractor resourceExtractor, File resourceDir) {
- this.resourceExtractor = resourceExtractor;
- this.resourceDir = resourceDir;
- }
-
- public InputStream getValue(int resourceId) {
- String resourceFileName = resourceExtractor.getResourceName(resourceId);
- String resourceName = resourceFileName.substring("/raw".length());
-
- File rawResourceDir = new File(resourceDir, "raw");
-
- try {
- File[] files = rawResourceDir.listFiles();
- for (int i = 0; i < files.length; i++) {
- File file = files[i];
- String name = file.getName();
- int dotIndex = name.indexOf(".");
- String fileBaseName = null;
- if (dotIndex >= 0) {
- fileBaseName = name.substring(0, dotIndex);
- } else {
- fileBaseName = name;
- }
- if (fileBaseName.equals(resourceName)) {
- return new FileInputStream(file);
- }
- }
- } catch (FileNotFoundException e) {
- return null;
- }
- return null;
- }
-
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/res/ResourceExtractor.java b/v1/src/main/java/com/xtremelabs/robolectric/res/ResourceExtractor.java
deleted file mode 100644
index 71efc494d..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/res/ResourceExtractor.java
+++ /dev/null
@@ -1,89 +0,0 @@
-package com.xtremelabs.robolectric.res;
-
-import java.lang.reflect.Field;
-import java.lang.reflect.Modifier;
-import java.util.HashMap;
-import java.util.Map;
-
-public class ResourceExtractor {
- private Map<String, Integer> localResourceStringToId = new HashMap<String, Integer>();
- private Map<String, Integer> systemResourceStringToId = new HashMap<String, Integer>();
- private Map<Integer, String> resourceIdToString = new HashMap<Integer, String>();
-
- public void addLocalRClass(Class rClass) throws Exception {
- addRClass(rClass, false);
- }
-
- public void addSystemRClass(Class rClass) throws Exception {
- addRClass(rClass, true);
- }
-
- private void addRClass(Class rClass, boolean isSystemRClass) throws Exception {
- for (Class innerClass : rClass.getClasses()) {
- for (Field field : innerClass.getDeclaredFields()) {
- if (field.getType().equals(Integer.TYPE) && Modifier.isStatic(field.getModifiers())) {
- String section = innerClass.getSimpleName();
- String name = section + "/" + field.getName();
- int value = field.getInt(null);
-
- if (isSystemRClass) {
- name = "android:" + name;
- }
-
- if (!section.equals("styleable")) {
- if (isSystemRClass) {
- systemResourceStringToId.put(name, value);
- } else {
- localResourceStringToId.put(name, value);
- }
-
- if (resourceIdToString.containsKey(value)) {
- throw new RuntimeException(value + " is already defined with name: " + resourceIdToString.get(value) + " can't also call it: " + name);
- }
- resourceIdToString.put(value, name);
- }
- }
- }
- }
- }
-
- public Integer getResourceId(String resourceName) {
- if (resourceName.contains("android:")) { // namespace needed for platform files
- return getResourceId(resourceName, true);
- } else {
- return getResourceId(resourceName, false);
- }
- }
-
- public Integer getLocalResourceId(String value) {
- boolean isSystem = false;
- return getResourceId(value, isSystem);
- }
-
- public Integer getResourceId(String resourceName, boolean isSystemResource) {
- if (resourceName == null ) {
- return null;
- }
- if (resourceName.equals("@null")) {
- return 0;
- }
-
- if (resourceName.startsWith("@+id")) {
- resourceName = resourceName.substring(2);
- } else if (resourceName.startsWith("@+android:id")) {
- resourceName = resourceName.substring(2);
- } else if (resourceName.startsWith("@")) {
- resourceName = resourceName.substring(1);
- }
-
- if (isSystemResource) {
- return systemResourceStringToId.get(resourceName);
- } else {
- return localResourceStringToId.get(resourceName);
- }
- }
-
- public String getResourceName(int resourceId) {
- return resourceIdToString.get(resourceId);
- }
-} \ No newline at end of file
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/res/ResourceLoader.java b/v1/src/main/java/com/xtremelabs/robolectric/res/ResourceLoader.java
deleted file mode 100644
index 3e60961d7..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/res/ResourceLoader.java
+++ /dev/null
@@ -1,557 +0,0 @@
-package com.xtremelabs.robolectric.res;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.shadows.ShadowContextWrapper;
-import com.xtremelabs.robolectric.util.I18nException;
-import com.xtremelabs.robolectric.util.PropertiesHelper;
-
-import android.R;
-import android.content.Context;
-import android.graphics.drawable.AnimationDrawable;
-import android.graphics.drawable.ColorDrawable;
-import android.graphics.drawable.Drawable;
-import android.preference.PreferenceScreen;
-import android.text.TextUtils;
-import android.view.Menu;
-import android.view.View;
-import android.view.ViewGroup;
-
-import java.io.BufferedReader;
-import java.io.File;
-import java.io.FileFilter;
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.lang.reflect.Field;
-import java.util.HashSet;
-import java.util.Properties;
-import java.util.Set;
-
-public class ResourceLoader {
- private static final FileFilter MENU_DIR_FILE_FILTER = new FileFilter() {
- @Override
- public boolean accept( File file ) {
- return isMenuDirectory( file.getPath() );
- }
- };
- private static final FileFilter LAYOUT_DIR_FILE_FILTER = new FileFilter() {
- @Override
- public boolean accept( File file ) {
- return isLayoutDirectory( file.getPath() );
- }
- };
- private static final FileFilter DRAWABLE_DIR_FILE_FILTER = new FileFilter() {
- @Override
- public boolean accept( File file ) {
- return isDrawableDirectory( file.getPath() );
- }
- };
-
- private File resourceDir;
- private File assetsDir;
- private int sdkVersion;
- private Class rClass;
-
- private final ResourceExtractor resourceExtractor;
- private ViewLoader viewLoader;
- private MenuLoader menuLoader;
- private PreferenceLoader preferenceLoader;
- private final StringResourceLoader stringResourceLoader;
- private final PluralResourceLoader pluralResourceLoader;
- private final StringArrayResourceLoader stringArrayResourceLoader;
- private final AttrResourceLoader attrResourceLoader;
- private final ColorResourceLoader colorResourceLoader;
- private final DrawableResourceLoader drawableResourceLoader;
- private final RawResourceLoader rawResourceLoader;
- private final DimenResourceLoader dimenResourceLoader;
- private final IntegerResourceLoader integerResourceLoader;
- private boolean isInitialized = false;
- private boolean strictI18n = false;
- private String locale="";
-
- private final Set<Integer> ninePatchDrawableIds = new HashSet<Integer>();
-
- public ResourceLoader( int sdkVersion, Class rClass, File resourceDir, File assetsDir ) throws Exception {
- this( sdkVersion, rClass, resourceDir, assetsDir, "");
- }
-
- public ResourceLoader( int sdkVersion, Class rClass, File resourceDir, File assetsDir, String locale ) throws Exception {
- this.sdkVersion = sdkVersion;
- this.assetsDir = assetsDir;
- this.rClass = rClass;
- this.locale = locale;
-
- resourceExtractor = new ResourceExtractor();
- if ( rClass != null ) {
- resourceExtractor.addLocalRClass( rClass );
- }
- resourceExtractor.addSystemRClass( R.class );
-
- stringResourceLoader = new StringResourceLoader( resourceExtractor );
- pluralResourceLoader = new PluralResourceLoader( resourceExtractor, stringResourceLoader );
- stringArrayResourceLoader = new StringArrayResourceLoader( resourceExtractor, stringResourceLoader );
- colorResourceLoader = new ColorResourceLoader( resourceExtractor );
- attrResourceLoader = new AttrResourceLoader( resourceExtractor );
- drawableResourceLoader = new DrawableResourceLoader( resourceExtractor, resourceDir );
- rawResourceLoader = new RawResourceLoader( resourceExtractor, resourceDir );
- dimenResourceLoader = new DimenResourceLoader( resourceExtractor );
- integerResourceLoader = new IntegerResourceLoader( resourceExtractor );
-
- this.resourceDir = resourceDir;
- }
-
- public void setStrictI18n( boolean strict ) {
- this.strictI18n = strict;
- if ( viewLoader != null ) {
- viewLoader.setStrictI18n( strict );
- }
- if ( menuLoader != null ) {
- menuLoader.setStrictI18n( strict );
- }
- if ( preferenceLoader != null ) {
- preferenceLoader.setStrictI18n( strict );
- }
- }
-
- public boolean getStrictI18n() {
- return strictI18n;
- }
-
- private void init() {
- if ( isInitialized ) {
- return;
- }
-
- try {
- if ( resourceDir != null ) {
- viewLoader = new ViewLoader( resourceExtractor, attrResourceLoader );
- menuLoader = new MenuLoader( resourceExtractor, attrResourceLoader );
- preferenceLoader = new PreferenceLoader( resourceExtractor );
-
- viewLoader.setStrictI18n( strictI18n );
- menuLoader.setStrictI18n( strictI18n );
- preferenceLoader.setStrictI18n( strictI18n );
-
- File systemResourceDir = getSystemResourceDir( getPathToAndroidResources() );
- File localValueResourceDir = getValueResourceDir( resourceDir );
- File systemValueResourceDir = getValueResourceDir( systemResourceDir );
- File preferenceDir = getPreferenceResourceDir( resourceDir );
-
- loadStringResources( localValueResourceDir, systemValueResourceDir );
- loadPluralsResources( localValueResourceDir, systemValueResourceDir );
- loadValueResources( localValueResourceDir, systemValueResourceDir );
- loadDimenResources( localValueResourceDir, systemValueResourceDir );
- loadIntegerResource( localValueResourceDir, systemValueResourceDir );
- loadViewResources( systemResourceDir, resourceDir );
- loadMenuResources( resourceDir );
- loadDrawableResources( resourceDir );
- loadPreferenceResources( preferenceDir );
-
- listNinePatchResources(ninePatchDrawableIds, resourceDir);
- } else {
- viewLoader = null;
- menuLoader = null;
- preferenceLoader = null;
- }
- } catch ( I18nException e ) {
- throw e;
- } catch ( Exception e ) {
- throw new RuntimeException( e );
- }
- isInitialized = true;
- }
-
- private File getSystemResourceDir( String pathToAndroidResources ) {
- return pathToAndroidResources != null ? new File( pathToAndroidResources ) : null;
- }
-
- private void loadStringResources( File localResourceDir, File systemValueResourceDir ) throws Exception {
- DocumentLoader stringResourceDocumentLoader = new DocumentLoader( this.stringResourceLoader );
- loadValueResourcesFromDirs( stringResourceDocumentLoader, localResourceDir, systemValueResourceDir );
- }
-
- private void loadPluralsResources( File localResourceDir, File systemValueResourceDir ) throws Exception {
- DocumentLoader stringResourceDocumentLoader = new DocumentLoader( this.pluralResourceLoader );
- loadValueResourcesFromDirs( stringResourceDocumentLoader, localResourceDir, systemValueResourceDir );
- }
-
- private void loadValueResources( File localResourceDir, File systemValueResourceDir ) throws Exception {
- DocumentLoader valueResourceLoader = new DocumentLoader( stringArrayResourceLoader, colorResourceLoader,
- attrResourceLoader );
- loadValueResourcesFromDirs( valueResourceLoader, localResourceDir, systemValueResourceDir );
- }
-
- private void loadDimenResources( File localResourceDir, File systemValueResourceDir ) throws Exception {
- DocumentLoader dimenResourceDocumentLoader = new DocumentLoader( this.dimenResourceLoader );
- loadValueResourcesFromDirs( dimenResourceDocumentLoader, localResourceDir, systemValueResourceDir );
- }
-
- private void loadIntegerResource( File localResourceDir, File systemValueResourceDir ) throws Exception {
- DocumentLoader integerResourceDocumentLoader = new DocumentLoader( this.integerResourceLoader );
- loadValueResourcesFromDirs( integerResourceDocumentLoader, localResourceDir, systemValueResourceDir );
- }
-
- private void loadViewResources( File systemResourceDir, File xmlResourceDir ) throws Exception {
- DocumentLoader viewDocumentLoader = new DocumentLoader( viewLoader );
- loadLayoutResourceXmlSubDirs( viewDocumentLoader, xmlResourceDir, false );
- loadLayoutResourceXmlSubDirs( viewDocumentLoader, systemResourceDir, true );
- }
-
- private void loadMenuResources( File xmlResourceDir ) throws Exception {
- DocumentLoader menuDocumentLoader = new DocumentLoader( menuLoader );
- loadMenuResourceXmlDirs( menuDocumentLoader, xmlResourceDir );
- }
-
- private void loadDrawableResources( File xmlResourceDir ) throws Exception {
- DocumentLoader drawableDocumentLoader = new DocumentLoader( drawableResourceLoader );
- loadDrawableResourceXmlDirs( drawableDocumentLoader, xmlResourceDir );
- }
-
- private void loadPreferenceResources( File xmlResourceDir ) throws Exception {
- if ( xmlResourceDir.exists() ) {
- DocumentLoader preferenceDocumentLoader = new DocumentLoader( preferenceLoader );
- preferenceDocumentLoader.loadResourceXmlDir( xmlResourceDir );
- }
- }
-
- private void loadLayoutResourceXmlSubDirs( DocumentLoader layoutDocumentLoader, File xmlResourceDir, boolean isSystem )
- throws Exception {
- if ( xmlResourceDir != null ) {
- layoutDocumentLoader.loadResourceXmlDirs( isSystem, xmlResourceDir.listFiles( LAYOUT_DIR_FILE_FILTER ) );
- }
- }
-
- private void loadMenuResourceXmlDirs( DocumentLoader menuDocumentLoader, File xmlResourceDir ) throws Exception {
- if ( xmlResourceDir != null ) {
- menuDocumentLoader.loadResourceXmlDirs( xmlResourceDir.listFiles( MENU_DIR_FILE_FILTER ) );
- }
- }
-
- private void loadDrawableResourceXmlDirs( DocumentLoader drawableResourceLoader, File xmlResourceDir ) throws Exception {
- if ( xmlResourceDir != null ) {
- drawableResourceLoader.loadResourceXmlDirs( xmlResourceDir.listFiles( DRAWABLE_DIR_FILE_FILTER ) );
- }
- }
-
- private void loadValueResourcesFromDirs( DocumentLoader documentLoader, File localValueResourceDir,
- File systemValueResourceDir ) throws Exception {
- loadValueResourcesFromDir( documentLoader, localValueResourceDir );
- loadSystemResourceXmlDir( documentLoader, systemValueResourceDir );
- }
-
- private void loadValueResourcesFromDir( DocumentLoader documentloader, File xmlResourceDir ) throws Exception {
- if ( xmlResourceDir != null ) {
- documentloader.loadResourceXmlDir( xmlResourceDir );
- }
- }
-
- private void loadSystemResourceXmlDir( DocumentLoader documentLoader, File stringResourceDir ) throws Exception {
- if ( stringResourceDir != null ) {
- documentLoader.loadSystemResourceXmlDir( stringResourceDir );
- }
- }
-
- private File getValueResourceDir( File xmlResourceDir ) {
- String valuesDir = "values";
- if( !TextUtils.isEmpty( locale ) ){
- valuesDir += "-"+ locale;
- }
- File result = ( xmlResourceDir != null ) ? new File( xmlResourceDir, valuesDir ) : null;
- if( result != null && !result.exists() ){
- throw new RuntimeException("Couldn't find value resource directory: " + result.getAbsolutePath() );
- }
- return result;
- }
-
- private File getPreferenceResourceDir( File xmlResourceDir ) {
- return xmlResourceDir != null ? new File( xmlResourceDir, "xml" ) : null;
- }
-
- private String getPathToAndroidResources() {
- String resFolder = getAndroidResourcePathFromLocalProperties();
- if (resFolder == null) {
- resFolder = getAndroidResourcePathFromSystemEnvironment();
- if (resFolder == null) {
- resFolder = getAndroidResourcePathFromSystemProperty();
- if (resFolder == null) {
- resFolder = getAndroidResourcePathByExecingWhichAndroid();
- }
- }
- }
-
- // Go through last 5 sdk versions looking for resource folders.
- if (resFolder != null) {
- for (int i = sdkVersion; i >= sdkVersion - 5 && i >= 4; i--) {
- File resourcePath = new File(resFolder, getAndroidResourceSubPath(i));
- if (resourcePath.exists()) {
- return resourcePath.getAbsolutePath();
- } else {
- System.out.println("WARNING: Unable to find Android resources at: " +
- resourcePath.toString() + " continuing.");
- }
- }
- } else {
- System.out.println("WARNING: Unable to find path to Android SDK");
- }
-
- return null;
- }
-
- private String getAndroidResourcePathFromLocalProperties() {
- // Hand tested
- // This is the path most often taken by IntelliJ
- File rootDir = resourceDir.getParentFile();
- String localPropertiesFileName = "local.properties";
- File localPropertiesFile = new File( rootDir, localPropertiesFileName );
- if ( !localPropertiesFile.exists() ) {
- localPropertiesFile = new File( localPropertiesFileName );
- }
- if ( localPropertiesFile.exists() ) {
- Properties localProperties = new Properties();
- try {
- localProperties.load( new FileInputStream( localPropertiesFile ) );
- PropertiesHelper.doSubstitutions( localProperties );
- return localProperties.getProperty( "sdk.dir" );
- } catch ( IOException e ) {
- // fine, we'll try something else
- }
- }
- return null;
- }
-
- private String getAndroidResourcePathFromSystemEnvironment() {
- // Hand tested
- return System.getenv().get( "ANDROID_HOME" );
- }
-
- private String getAndroidResourcePathFromSystemProperty() {
- // this is used by the android-maven-plugin
- return System.getProperty( "android.sdk.path" );
- }
-
- private String getAndroidResourcePathByExecingWhichAndroid() {
- // Hand tested
- // Should always work from the command line. Often fails in IDEs because
- // they don't pass the full PATH in the environment
- try {
- Process process = Runtime.getRuntime().exec( new String[] { "which", "android" } );
- String sdkPath = new BufferedReader( new InputStreamReader( process.getInputStream() ) ).readLine();
- if ( sdkPath != null && sdkPath.endsWith( "tools/android" ) ) {
- return sdkPath.substring(0, sdkPath.indexOf( "tools/android"));
- }
- } catch ( IOException e ) {
- // fine we'll try something else
- }
- return null;
- }
-
- private static String getAndroidResourceSubPath(int version) {
- return "platforms/android-" + version + "/data/res";
- }
-
- static boolean isLayoutDirectory( String path ) {
- return path.contains( File.separator + "layout" );
- }
-
- static boolean isDrawableDirectory( String path ) {
- return path.contains( File.separator + "drawable" );
- }
-
- static boolean isMenuDirectory( String path ) {
- return path.contains( File.separator + "menu" );
- }
-
- /*
- * For tests only...
- */
- protected ResourceLoader( StringResourceLoader stringResourceLoader ) {
- resourceExtractor = new ResourceExtractor();
- this.stringResourceLoader = stringResourceLoader;
- pluralResourceLoader = null;
- viewLoader = null;
- stringArrayResourceLoader = null;
- attrResourceLoader = null;
- colorResourceLoader = null;
- drawableResourceLoader = null;
- rawResourceLoader = null;
- dimenResourceLoader = null;
- integerResourceLoader = null;
- }
-
- public static ResourceLoader getFrom( Context context ) {
- ResourceLoader resourceLoader = shadowOf( context.getApplicationContext() ).getResourceLoader();
- resourceLoader.init();
- return resourceLoader;
- }
-
- public String getNameForId( int viewId ) {
- init();
- return resourceExtractor.getResourceName( viewId );
- }
-
- public View inflateView( Context context, int resource, ViewGroup viewGroup ) {
- init();
- return viewLoader.inflateView( context, resource, viewGroup );
- }
-
- public int getColorValue( int id ) {
- init();
- return colorResourceLoader.getValue( id );
- }
-
- public String getStringValue( int id ) {
- init();
- return stringResourceLoader.getValue( id );
- }
-
- public String getPluralStringValue( int id, int quantity ) {
- init();
- return pluralResourceLoader.getValue( id, quantity );
- }
-
- public float getDimenValue( int id ) {
- init();
- return dimenResourceLoader.getValue( id );
- }
-
- public int getIntegerValue( int id ) {
- init();
- return integerResourceLoader.getValue( id );
- }
-
- public boolean isDrawableXml( int resourceId ) {
- init();
- return drawableResourceLoader.isXml( resourceId );
- }
-
- public boolean isAnimatableXml( int resourceId ) {
- init();
- return drawableResourceLoader.isAnimationDrawable( resourceId );
- }
-
- public int[] getDrawableIds( int resourceId ) {
- init();
- return drawableResourceLoader.getDrawableIds( resourceId );
- }
-
- public Drawable getXmlDrawable( int resourceId ) {
- return drawableResourceLoader.getXmlDrawable( resourceId );
- }
-
- public Drawable getAnimDrawable( int resourceId ) {
- return getInnerRClassDrawable( resourceId, "$anim", AnimationDrawable.class );
- }
-
- public Drawable getColorDrawable( int resourceId ) {
- return getInnerRClassDrawable( resourceId, "$color", ColorDrawable.class );
- }
-
- @SuppressWarnings("rawtypes")
- private Drawable getInnerRClassDrawable( int drawableResourceId, String suffix, Class returnClass ) {
- ShadowContextWrapper shadowApp = Robolectric.shadowOf( Robolectric.application );
- Class rClass = shadowApp.getResourceLoader().getLocalRClass();
-
- // Check to make sure there is actually an R Class, if not
- // return just a BitmapDrawable
- if ( rClass == null ) {
- return null;
- }
-
- // Load the Inner Class for interrogation
- Class animClass = null;
- try {
- animClass = Class.forName( rClass.getCanonicalName() + suffix );
- } catch ( ClassNotFoundException e ) {
- return null;
- }
-
- // Try to find the passed in resource ID
- try {
- for ( Field field : animClass.getDeclaredFields() ) {
- if ( field.getInt( animClass ) == drawableResourceId ) {
- return ( Drawable ) returnClass.newInstance();
- }
- }
- } catch ( Exception e ) {
- }
-
- return null;
- }
-
- public boolean isNinePatchDrawable(int drawableResourceId) {
- return ninePatchDrawableIds.contains(drawableResourceId);
- }
-
- /**
- * Returns a collection of resource IDs for all nine-patch drawables
- * in the project.
- *
- * @param resourceIds
- * @param dir
- */
- private void listNinePatchResources(Set<Integer> resourceIds, File dir) {
- File[] files = dir.listFiles();
- if (files != null) {
- for (File f : files) {
- if (f.isDirectory() && isDrawableDirectory(f.getPath())) {
- listNinePatchResources(resourceIds, f);
- } else {
- String name = f.getName();
- if (name.endsWith(".9.png")) {
- String[] tokens = name.split("\\.9\\.png$");
- resourceIds.add(resourceExtractor.getResourceId("@drawable/" + tokens[0]));
- }
- }
- }
- }
- }
-
- public InputStream getRawValue( int id ) {
- init();
- return rawResourceLoader.getValue( id );
- }
-
- public String[] getStringArrayValue( int id ) {
- init();
- return stringArrayResourceLoader.getArrayValue( id );
- }
-
- public void inflateMenu( Context context, int resource, Menu root ) {
- init();
- menuLoader.inflateMenu( context, resource, root );
- }
-
- public PreferenceScreen inflatePreferences( Context context, int resourceId ) {
- init();
- return preferenceLoader.inflatePreferences( context, resourceId );
- }
-
- public File getAssetsBase() {
- return assetsDir;
- }
-
- @SuppressWarnings("rawtypes")
- public Class getLocalRClass() {
- return rClass;
- }
-
- public void setLocalRClass( Class clazz ) {
- rClass = clazz;
- }
-
- public ResourceExtractor getResourceExtractor() {
- return resourceExtractor;
- }
-
- public ViewLoader.ViewNode getLayoutViewNode( String layoutName ) {
- return viewLoader.viewNodesByLayoutName.get( layoutName );
- }
-
- public void setLayoutQualifierSearchPath( String... locations ) {
- init();
- viewLoader.setLayoutQualifierSearchPath( locations );
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/res/ResourceReferenceResolver.java b/v1/src/main/java/com/xtremelabs/robolectric/res/ResourceReferenceResolver.java
deleted file mode 100644
index 697eb7716..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/res/ResourceReferenceResolver.java
+++ /dev/null
@@ -1,82 +0,0 @@
-package com.xtremelabs.robolectric.res;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-class ResourceReferenceResolver<T> {
- private Map<String, T> attributeNamesToValues = new HashMap<String, T>();
- private Map<String, List<String>> unresolvedReferences = new HashMap<String, List<String>>();
- private String referenceType;
- private String[] allowedReferenceTypesForRawValues;
-
- ResourceReferenceResolver(String referenceType) {
- this(referenceType, new String[] { referenceType });
- }
-
- ResourceReferenceResolver(String referenceType, String[] allowedReferenceTypesForRawValues) {
- this.referenceType = referenceType;
- this.allowedReferenceTypesForRawValues = allowedReferenceTypesForRawValues;
- }
-
- public T getValue(String resourceName) {
- return attributeNamesToValues.get(resourceName);
- }
-
- public void processResource(String name, String rawValue, ResourceValueConverter loader, boolean isSystem) {
- String valuePointer = referenceType + "/" + name;
-
- boolean isAllowedReferenceType = false;
- for (String allowedReferenceTypesForRawValue : allowedReferenceTypesForRawValues) {
- if (rawValue.startsWith("@")
- && rawValue.contains(allowedReferenceTypesForRawValue + "/")) {
- isAllowedReferenceType = true;
- break;
- }
- }
-
- if (isAllowedReferenceType) {
- addAttributeReference(rawValue, valuePointer);
- } else {
- if (isSystem) {
- valuePointer = "android:" + valuePointer;
- }
- addAttribute(valuePointer, (T) loader.convertRawValue(rawValue));
- }
- }
-
- public void addAttribute(String valuePointer, T value) {
- attributeNamesToValues.put(valuePointer, value);
- resolveUnresolvedReferences(valuePointer, value);
- }
-
- private void resolveUnresolvedReferences(String attributeName, T value) {
- List<String> references = unresolvedReferences.remove(attributeName);
- if (references == null) {
- return;
- }
- for (String reference : references) {
- attributeNamesToValues.put(reference, value);
- }
- }
-
- private void addUnresolvedReference(String valuePointer, String attributeName) {
- List<String> references = unresolvedReferences.get(attributeName);
- if (references == null) {
- references = new ArrayList<String>();
- unresolvedReferences.put(attributeName, references);
- }
- references.add(valuePointer);
- }
-
- private void addAttributeReference(String rawValue, String valuePointer) {
- String attributeName = rawValue.substring(1);
- T value = attributeNamesToValues.get(attributeName);
- if (value == null) {
- addUnresolvedReference(valuePointer, attributeName);
- } else {
- attributeNamesToValues.put(valuePointer, value);
- }
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/res/ResourceValueConverter.java b/v1/src/main/java/com/xtremelabs/robolectric/res/ResourceValueConverter.java
deleted file mode 100644
index 1e1f3ce6e..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/res/ResourceValueConverter.java
+++ /dev/null
@@ -1,5 +0,0 @@
-package com.xtremelabs.robolectric.res;
-
-public interface ResourceValueConverter {
- Object convertRawValue(String rawValue);
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/res/RobolectricPackageManager.java b/v1/src/main/java/com/xtremelabs/robolectric/res/RobolectricPackageManager.java
deleted file mode 100644
index 730dc3dbe..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/res/RobolectricPackageManager.java
+++ /dev/null
@@ -1,221 +0,0 @@
-package com.xtremelabs.robolectric.res;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import android.content.ComponentName;
-import android.content.ContextWrapper;
-import android.content.Intent;
-import android.content.pm.ApplicationInfo;
-import android.content.pm.PackageInfo;
-import android.content.pm.ResolveInfo;
-import android.graphics.drawable.Drawable;
-
-import com.xtremelabs.robolectric.RobolectricConfig;
-import com.xtremelabs.robolectric.tester.android.content.pm.StubPackageManager;
-
-public class RobolectricPackageManager extends StubPackageManager {
-
- private Map<String, PackageInfo> packageList;
- private Map<Intent, List<ResolveInfo>> resolveList = new HashMap<Intent, List<ResolveInfo>>();
- private Map<ComponentName, ComponentState> componentList = new HashMap<ComponentName,ComponentState>();
- private Map<ComponentName, Drawable> drawableList = new HashMap<ComponentName, Drawable>();
- private Map<String, Boolean> systemFeatureList = new HashMap<String, Boolean>();
-
- private ContextWrapper contextWrapper;
- private RobolectricConfig config;
- private ApplicationInfo applicationInfo;
-
- public RobolectricPackageManager(ContextWrapper contextWrapper, RobolectricConfig config) {
- this.contextWrapper = contextWrapper;
- this.config = config;
- initializePackageInfo();
- }
-
- @Override
- public PackageInfo getPackageInfo(String packageName, int flags) throws NameNotFoundException {
- if (packageList.containsKey(packageName)) {
- return packageList.get(packageName);
- }
-
- throw new NameNotFoundException();
- }
-
- @Override
- public ApplicationInfo getApplicationInfo(String packageName, int flags) throws NameNotFoundException {
-
- if (config.getPackageName().equals(packageName)) {
- if (applicationInfo == null) {
- applicationInfo = new ApplicationInfo();
- applicationInfo.flags = config.getApplicationFlags();
- applicationInfo.targetSdkVersion = config.getSdkVersion();
- applicationInfo.packageName = config.getPackageName();
- applicationInfo.processName = config.getProcessName();
- applicationInfo.name = config.getApplicationName();
- }
- return applicationInfo;
- }
-
- PackageInfo info;
- if ((info = packageList.get(packageName)) != null) {
- return info.applicationInfo;
- }
-
- throw new NameNotFoundException();
- }
-
- @Override
- public List<PackageInfo> getInstalledPackages(int flags) {
- return new ArrayList<PackageInfo>(packageList.values());
- }
-
- @Override
- public List<ResolveInfo> queryIntentActivities( Intent intent, int flags ) {
- return queryIntent(intent, flags);
- }
-
- @Override
- public List<ResolveInfo> queryIntentServices( Intent intent, int flags ) {
- return queryIntent(intent, flags);
- }
-
- @Override
- public List<ResolveInfo> queryBroadcastReceivers(Intent intent, int flags) {
- return queryIntent(intent, flags);
- }
-
- @Override
- public ResolveInfo resolveActivity(Intent intent, int flags) {
- List<ResolveInfo> candidates = queryIntentActivities(intent, flags);
- return candidates.isEmpty() ? null : candidates.get(0);
- }
-
- @Override
- public ResolveInfo resolveService(Intent intent, int flags) {
- return resolveActivity(intent, flags);
- }
-
- public void addResolveInfoForIntent( Intent intent, List<ResolveInfo> info ) {
- resolveList.put(intent, info);
- }
-
- public void addResolveInfoForIntent(Intent intent, ResolveInfo info) {
- List<ResolveInfo> l = resolveList.get(intent);
- if (l == null) {
- l = new ArrayList<ResolveInfo>();
- resolveList.put(intent, l);
- }
- l.add(info);
- }
-
- @Override
- public Drawable getActivityIcon(Intent intent) {
- return drawableList.get(intent.getComponent());
- }
-
- @Override
- public Drawable getActivityIcon(ComponentName componentName) {
- return drawableList.get(componentName);
- }
-
- public void addActivityIcon( ComponentName component, Drawable d ) {
- drawableList.put( component, d);
- }
-
- public void addActivityIcon( Intent intent, Drawable d ) {
- drawableList.put( intent.getComponent(), d);
- }
-
- @Override
- public Intent getLaunchIntentForPackage(String packageName) {
- Intent i = new Intent();
- i.setComponent( new ComponentName(packageName, "") );
- return i;
- }
-
- @Override
- public CharSequence getApplicationLabel(ApplicationInfo info) {
- return info.name;
- }
-
- @Override
- public void setComponentEnabledSetting(ComponentName componentName, int newState, int flags) {
- componentList.put(componentName, new ComponentState(newState, flags));
- }
-
- /**
- * Non-Android accessor. Use to make assertions on values passed to
- * setComponentEnabledSetting.
- *
- * @param componentName
- * @return
- */
- public RobolectricPackageManager.ComponentState getComponentState(ComponentName componentName) {
- return componentList.get(componentName);
- }
-
- /**
- * Non-Android accessor. Used to add a package to the list of those
- * already 'installed' on system.
- *
- * @param packageInfo
- */
- public void addPackage( PackageInfo packageInfo ) {
- packageList.put(packageInfo.packageName, packageInfo);
- }
-
- public void addPackage( String packageName ) {
- PackageInfo info = new PackageInfo();
- info.packageName = packageName;
- addPackage( info );
- }
-
- @Override
- public boolean hasSystemFeature(String name) {
- return systemFeatureList.containsKey(name) ? systemFeatureList.get(name) : false;
- }
-
- /**
- * Non-Android accessor. Used to declare a system feature is
- * or is not supported.
- *
- * @param name
- * @param supported
- */
- public void setSystemFeature(String name, boolean supported) {
- systemFeatureList.put(name, supported);
- }
-
- private List<ResolveInfo> queryIntent(Intent intent, int flags) {
- List<ResolveInfo> result = resolveList.get(intent);
- if (result == null) {
- return Collections.emptyList();
- } else {
- return result;
- }
- }
-
- private void initializePackageInfo() {
- if (packageList != null) { return; }
-
- PackageInfo packageInfo = new PackageInfo();
- packageInfo.packageName = contextWrapper.getPackageName();
- packageInfo.versionName = "1.0";
-
- packageList = new HashMap<String, PackageInfo>();
- addPackage( packageInfo );
- }
-
- public class ComponentState {
- public int newState;
- public int flags;
-
- public ComponentState(int newState, int flags) {
- this.newState = newState;
- this.flags = flags;
- }
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/res/StringArrayResourceLoader.java b/v1/src/main/java/com/xtremelabs/robolectric/res/StringArrayResourceLoader.java
deleted file mode 100644
index 1a3988c52..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/res/StringArrayResourceLoader.java
+++ /dev/null
@@ -1,46 +0,0 @@
-package com.xtremelabs.robolectric.res;
-
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-
-import javax.xml.xpath.XPathConstants;
-import javax.xml.xpath.XPathExpression;
-import javax.xml.xpath.XPathExpressionException;
-import javax.xml.xpath.XPathFactory;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-public class StringArrayResourceLoader extends XpathResourceXmlLoader {
- Map<String, String[]> stringArrayValues = new HashMap<String, String[]>();
- private StringResourceLoader stringResourceLoader;
-
- public StringArrayResourceLoader(ResourceExtractor resourceExtractor, StringResourceLoader stringResourceLoader) {
- super(resourceExtractor, "/resources/string-array");
- this.stringResourceLoader = stringResourceLoader;
- }
-
- public String[] getArrayValue(int resourceId) {
- String resourceName = resourceExtractor.getResourceName(resourceId);
- return stringArrayValues.get(resourceName);
- }
-
- @Override protected void processNode(Node node, String name, boolean isSystem) throws XPathExpressionException {
- XPathExpression itemXPath = XPathFactory.newInstance().newXPath().compile("item");
- NodeList childNodes = (NodeList) itemXPath.evaluate(node, XPathConstants.NODESET);
- List<String> arrayValues = new ArrayList<String>();
- for (int j = 0; j < childNodes.getLength(); j++) {
- Node childNode = childNodes.item(j);
-
- String value = childNode.getTextContent();
- if (value.startsWith("@")) {
- arrayValues.add(stringResourceLoader.getValue(value , isSystem));
- } else {
- arrayValues.add(value);
- }
- }
- String valuePointer = (isSystem ? "android:" : "") + "array/" + name;
- stringArrayValues.put(valuePointer, arrayValues.toArray(new String[arrayValues.size()]));
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/res/StringResourceLoader.java b/v1/src/main/java/com/xtremelabs/robolectric/res/StringResourceLoader.java
deleted file mode 100644
index 88058ebb1..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/res/StringResourceLoader.java
+++ /dev/null
@@ -1,27 +0,0 @@
-package com.xtremelabs.robolectric.res;
-
-import org.w3c.dom.Node;
-
-public class StringResourceLoader extends XpathResourceXmlLoader implements ResourceValueConverter {
- private ResourceReferenceResolver<String> stringResolver = new ResourceReferenceResolver<String>("string");
-
- public StringResourceLoader(ResourceExtractor resourceExtractor) {
- super(resourceExtractor, "/resources/string");
- }
-
- public String getValue(int resourceId) {
- return stringResolver.getValue(resourceExtractor.getResourceName(resourceId));
- }
-
- public String getValue(String resourceName, boolean isSystem) {
- return getValue(resourceExtractor.getResourceId(resourceName, isSystem));
- }
-
- @Override protected void processNode(Node node, String name, boolean isSystem) {
- stringResolver.processResource(name, node.getTextContent(), this, isSystem);
- }
-
- @Override public Object convertRawValue(String rawValue) {
- return rawValue;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/res/ViewLoader.java b/v1/src/main/java/com/xtremelabs/robolectric/res/ViewLoader.java
deleted file mode 100644
index 2b54c680f..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/res/ViewLoader.java
+++ /dev/null
@@ -1,308 +0,0 @@
-package com.xtremelabs.robolectric.res;
-
-import android.content.Context;
-import android.os.Build;
-import android.support.v4.app.Fragment;
-import android.support.v4.app.FragmentActivity;
-import android.text.TextUtils;
-import android.util.AttributeSet;
-import android.view.View;
-import android.view.ViewGroup;
-import android.view.ViewParent;
-import android.widget.FrameLayout;
-import com.xtremelabs.robolectric.tester.android.util.TestAttributeSet;
-import com.xtremelabs.robolectric.util.I18nException;
-import org.w3c.dom.Document;
-import org.w3c.dom.NamedNodeMap;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-
-import java.io.File;
-import java.lang.reflect.Constructor;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.util.*;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-
-public class ViewLoader extends XmlLoader {
- protected Map<String, ViewNode> viewNodesByLayoutName = new HashMap<String, ViewNode>();
- private AttrResourceLoader attrResourceLoader;
- private List<String> qualifierSearchPath;
-
- public ViewLoader(ResourceExtractor resourceExtractor, AttrResourceLoader attrResourceLoader) {
- super(resourceExtractor);
- this.attrResourceLoader = attrResourceLoader;
- setLayoutQualifierSearchPath();
- }
-
- @Override
- protected void processResourceXml(File xmlFile, Document document, boolean isSystem) throws Exception {
- ViewNode topLevelNode = new ViewNode("top-level", new HashMap<String, String>(), isSystem);
- processChildren(document.getChildNodes(), topLevelNode);
- String layoutName = xmlFile.getParentFile().getName() + "/" + xmlFile.getName().replace(".xml", "");
- if (isSystem) {
- layoutName = "android:" + layoutName;
- }
- viewNodesByLayoutName.put(layoutName, topLevelNode.getChildren().get(0));
- }
-
- private void processChildren(NodeList childNodes, ViewNode parent) {
- for (int i = 0; i < childNodes.getLength(); i++) {
- Node node = childNodes.item(i);
- processNode(node, parent);
- }
- }
-
- private void processNode(Node node, ViewNode parent) {
- String name = node.getNodeName();
- NamedNodeMap attributes = node.getAttributes();
- Map<String, String> attrMap = new HashMap<String, String>();
- if (attributes != null) {
- int length = attributes.getLength();
- for (int i = 0; i < length; i++) {
- Node attr = attributes.item(i);
- attrMap.put(attr.getNodeName(), attr.getNodeValue());
- }
- }
-
- if (name.equals("requestFocus")) {
- parent.attributes.put("android:focus", "true");
- parent.requestFocusOverride = true;
- } else if (!name.startsWith("#")) {
- ViewNode viewNode = new ViewNode(name, attrMap, parent.isSystem);
- if (parent != null) parent.addChild(viewNode);
-
- processChildren(node.getChildNodes(), viewNode);
- }
- }
-
- public View inflateView(Context context, String key) {
- return inflateView(context, key, null);
- }
-
- public View inflateView(Context context, String key, View parent) {
- return inflateView(context, key, null, parent);
- }
-
- public View inflateView(Context context, int resourceId, View parent) {
- return inflateView(context, resourceExtractor.getResourceName(resourceId), parent);
- }
-
- private View inflateView(Context context, String layoutName, Map<String, String> attributes, View parent) {
- ViewNode viewNode = getViewNodeByLayoutName(layoutName);
- if (viewNode == null) {
- throw new RuntimeException("Could not find layout " + layoutName);
- }
- try {
- if (attributes != null) {
- for (Map.Entry<String, String> entry : attributes.entrySet()) {
- if (!entry.getKey().equals("layout")) {
- viewNode.attributes.put(entry.getKey(), entry.getValue());
- }
- }
- }
- return viewNode.inflate(context, parent);
- } catch (I18nException e) {
- throw e;
- } catch (Exception e) {
- throw new RuntimeException("error inflating " + layoutName, e);
- }
- }
-
- private ViewNode getViewNodeByLayoutName(String layoutName) {
- if (layoutName.startsWith("layout/")) {
- String rawLayoutName = layoutName.substring("layout/".length());
- for (String qualifier : qualifierSearchPath) {
- for (int version = Math.max(Build.VERSION.SDK_INT, 0); version >= 0; version--) {
- ViewNode foundNode = findLayoutViewNode(qualifier, version, rawLayoutName);
- if (foundNode != null) {
- return foundNode;
- }
- }
- }
- }
- return viewNodesByLayoutName.get(layoutName);
- }
-
- private ViewNode findLayoutViewNode(String qualifier, int version, String rawLayoutName) {
- StringBuilder name = new StringBuilder("layout");
- if (!TextUtils.isEmpty(qualifier)) {
- name.append("-").append(qualifier);
- }
- if (version > 0) {
- name.append("-v").append(version);
- }
- name.append("/").append(rawLayoutName);
- return viewNodesByLayoutName.get(name.toString());
- }
-
- public void setLayoutQualifierSearchPath(String... locations) {
- qualifierSearchPath = Arrays.asList(locations);
- if (!qualifierSearchPath.contains("")) {
- qualifierSearchPath = new ArrayList<String>(qualifierSearchPath);
- qualifierSearchPath.add("");
- }
- }
-
- public class ViewNode {
- private String name;
- private final Map<String, String> attributes;
-
- private List<ViewNode> children = new ArrayList<ViewNode>();
- boolean requestFocusOverride = false;
- boolean isSystem = false;
-
- public ViewNode(String name, Map<String, String> attributes, boolean isSystem) {
- this.name = name;
- this.attributes = attributes;
- this.isSystem = isSystem;
- }
-
- public List<ViewNode> getChildren() {
- return children;
- }
-
- public void addChild(ViewNode viewNode) {
- children.add(viewNode);
- }
-
- public View inflate(Context context, View parent) throws Exception {
- View view = create(context, (ViewGroup) parent);
-
- for (ViewNode child : children) {
- child.inflate(context, view);
- }
-
- invokeOnFinishInflate(view);
- return view;
- }
-
- private void invokeOnFinishInflate(View view) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
- Method onFinishInflate = View.class.getDeclaredMethod("onFinishInflate");
- onFinishInflate.setAccessible(true);
- onFinishInflate.invoke(view);
- }
-
- private View create(Context context, ViewGroup parent) throws Exception {
- if (name.equals("include")) {
- String layout = attributes.get("layout");
- View view = inflateView(context, layout.substring(1), attributes, parent);
- return view;
- } else if (name.equals("merge")) {
- return parent;
- } else if (name.equals("fragment")) {
- View fragment = constructFragment(context);
- addToParent(parent, fragment);
- return fragment;
- } else {
- applyFocusOverride(parent);
- View view = constructView(context);
- addToParent(parent, view);
- shadowOf(view).applyFocus();
- return view;
- }
- }
-
- private FrameLayout constructFragment(Context context) throws InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException {
- TestAttributeSet attributeSet = new TestAttributeSet(attributes, resourceExtractor, attrResourceLoader, View.class, isSystem);
- if (strictI18n) {
- attributeSet.validateStrictI18n();
- }
-
- Class<? extends Fragment> clazz = loadFragmentClass(attributes.get("android:name"));
- Fragment fragment = ((Constructor<? extends Fragment>) clazz.getConstructor()).newInstance();
- if (!(context instanceof FragmentActivity)) {
- throw new RuntimeException("Cannot inflate a fragment unless the activity is a FragmentActivity");
- }
-
- FragmentActivity activity = (FragmentActivity) context;
-
- String tag = attributeSet.getAttributeValue("android", "tag");
- int id = attributeSet.getAttributeResourceValue("android", "id", 0);
- // TODO: this should probably be changed to call TestFragmentManager.addFragment so that the
- // inflated fragments don't get started twice (once in the commit, and once in ShadowFragmentActivity's
- // onStart()
- activity.getSupportFragmentManager().beginTransaction().add(id, fragment, tag).commit();
-
- View view = fragment.getView();
-
- FrameLayout container = new FrameLayout(context);
- container.setId(id);
- container.addView(view);
- return container;
- }
-
- private void addToParent(ViewGroup parent, View view) {
- if (parent != null && parent != view) {
- parent.addView(view);
- }
- }
-
- private View constructView(Context context) throws InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException {
- Class<? extends View> clazz = pickViewClass();
- try {
- TestAttributeSet attributeSet = new TestAttributeSet(attributes, resourceExtractor, attrResourceLoader, clazz, isSystem);
- if (strictI18n) {
- attributeSet.validateStrictI18n();
- }
- return ((Constructor<? extends View>) clazz.getConstructor(Context.class, AttributeSet.class)).newInstance(context, attributeSet);
- } catch (NoSuchMethodException e) {
- try {
- return ((Constructor<? extends View>) clazz.getConstructor(Context.class)).newInstance(context);
- } catch (NoSuchMethodException e1) {
- return ((Constructor<? extends View>) clazz.getConstructor(Context.class, String.class)).newInstance(context, "");
- }
- }
- }
-
- private Class<? extends View> pickViewClass() {
- Class<? extends View> clazz = loadViewClass(name);
- if (clazz == null) {
- clazz = loadViewClass("android.view." + name);
- }
- if (clazz == null) {
- clazz = loadViewClass("android.widget." + name);
- }
- if (clazz == null) {
- clazz = loadViewClass("android.webkit." + name);
- }
- if (clazz == null) {
- clazz = loadViewClass("com.google.android.maps." + name);
- }
-
- if (clazz == null) {
- throw new RuntimeException("couldn't find view class " + name);
- }
- return clazz;
- }
-
- private Class loadClass(String className) {
- try {
- return getClass().getClassLoader().loadClass(className);
- } catch (ClassNotFoundException e) {
- return null;
- }
- }
-
- private Class<? extends View> loadViewClass(String className) {
- // noinspection unchecked
- return loadClass(className);
- }
-
- private Class<? extends Fragment> loadFragmentClass(String className) {
- // noinspection unchecked
- return loadClass(className);
- }
-
- public void applyFocusOverride(ViewParent parent) {
- if (requestFocusOverride) {
- View ancestor = (View) parent;
- while (ancestor.getParent() != null) {
- ancestor = (View) ancestor.getParent();
- }
- ancestor.clearFocus();
- }
- }
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/res/XTagXmlResourceLoader.java b/v1/src/main/java/com/xtremelabs/robolectric/res/XTagXmlResourceLoader.java
deleted file mode 100644
index fa068b3fb..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/res/XTagXmlResourceLoader.java
+++ /dev/null
@@ -1,71 +0,0 @@
-package com.xtremelabs.robolectric.res;
-
-import java.io.File;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.List;
-
-import org.w3c.dom.Document;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-
-/**
- *
- * XTagXmlResourceLoader is dedicated for mixed tags xml files.
- *
- */
-public abstract class XTagXmlResourceLoader extends XmlLoader {
-
- private String tag;
-
- private static List< String > xPathXmlFiles = new ArrayList< String >( 6 );
-
- static {
- xPathXmlFiles.add( "values/attrs" );
- xPathXmlFiles.add( "values/colors" );
- xPathXmlFiles.add( "values/strings" );
- xPathXmlFiles.add( "values/string_arrays" );
- xPathXmlFiles.add( "values/plurals" );
- xPathXmlFiles.add( "values/dimens" );
- }
-
- public XTagXmlResourceLoader( ResourceExtractor resourceExtractor, String tag ) {
- super( resourceExtractor );
- this.tag = tag;
- }
-
- @Override
- protected void processResourceXml( File xmlFile, Document document, boolean isSystem ) throws Exception {
-
- String resourceName = toResourceName( xmlFile );
- if ( xPathXmlFiles.contains( resourceName ) )
- return;
-
- NodeList items = document.getElementsByTagName( tag );
- for ( int i = 0; i < items.getLength(); i++ ) {
- Node node = items.item( i );
- String name = node.getAttributes().getNamedItem( "name" ).getNodeValue();
- processNode( node, name, isSystem );
- }
-
- }
-
- /**
- * Convert file name to resource name.
- *
- * @param xmlFile
- * Xml File
- * @return Resource name
- */
- private String toResourceName( File xmlFile ) {
- try {
- return xmlFile.getCanonicalPath().replaceAll( "[/\\\\\\\\]", "/" ).replaceAll( "^.*?/res/", "" )
- .replaceAll( "\\..+$", "" );
- } catch ( IOException e ) {
- throw new RuntimeException( e );
- }
- }
-
- protected abstract void processNode( Node node, String name, boolean isSystem );
-
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/res/XmlLoader.java b/v1/src/main/java/com/xtremelabs/robolectric/res/XmlLoader.java
deleted file mode 100644
index 32a8c3105..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/res/XmlLoader.java
+++ /dev/null
@@ -1,20 +0,0 @@
-package com.xtremelabs.robolectric.res;
-
-import org.w3c.dom.Document;
-
-import java.io.File;
-
-public abstract class XmlLoader {
- protected ResourceExtractor resourceExtractor;
- protected boolean strictI18n = false;
-
- public XmlLoader(ResourceExtractor resourceExtractor) {
- this.resourceExtractor = resourceExtractor;
- }
-
- protected abstract void processResourceXml(File xmlFile, Document document, boolean isSystem) throws Exception;
-
- public void setStrictI18n(boolean strict) {
- this.strictI18n = strict;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/res/XpathResourceXmlLoader.java b/v1/src/main/java/com/xtremelabs/robolectric/res/XpathResourceXmlLoader.java
deleted file mode 100644
index 985779d7f..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/res/XpathResourceXmlLoader.java
+++ /dev/null
@@ -1,32 +0,0 @@
-package com.xtremelabs.robolectric.res;
-
-import org.w3c.dom.Document;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-
-import javax.xml.xpath.XPathConstants;
-import javax.xml.xpath.XPathExpression;
-import javax.xml.xpath.XPathExpressionException;
-import javax.xml.xpath.XPathFactory;
-import java.io.File;
-
-public abstract class XpathResourceXmlLoader extends XmlLoader {
- private String expression;
-
- public XpathResourceXmlLoader(ResourceExtractor resourceExtractor, String expression) {
- super(resourceExtractor);
- this.expression = expression;
- }
-
- @Override protected void processResourceXml(File xmlFile, Document document, boolean isSystem) throws Exception {
- XPathExpression stringsXPath = XPathFactory.newInstance().newXPath().compile(expression);
- NodeList nodes = (NodeList) stringsXPath.evaluate(document, XPathConstants.NODESET);
- for (int i = 0; i < nodes.getLength(); i++) {
- Node node = nodes.item(i);
- String name = node.getAttributes().getNamedItem("name").getNodeValue();
- processNode(node, name, isSystem);
- }
- }
-
- protected abstract void processNode(Node node, String name, boolean isSystem) throws XPathExpressionException;
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/HttpResponseGenerator.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/HttpResponseGenerator.java
deleted file mode 100644
index 70f4b5435..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/HttpResponseGenerator.java
+++ /dev/null
@@ -1,8 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import org.apache.http.HttpRequest;
-import org.apache.http.HttpResponse;
-
-public interface HttpResponseGenerator {
- public HttpResponse getResponse(HttpRequest request);
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/SerializedFragmentState.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/SerializedFragmentState.java
deleted file mode 100644
index 1cf9c0024..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/SerializedFragmentState.java
+++ /dev/null
@@ -1,19 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.support.v4.app.Fragment;
-
-import java.io.Serializable;
-
-public class SerializedFragmentState implements Serializable {
- public final String tag;
- public final int id;
- public final Class<? extends Fragment> fragmentClass;
- public final int containerId;
-
- public SerializedFragmentState(Integer containerId, Fragment fragment) {
- this.containerId = containerId;
- id = fragment.getId();
- tag = fragment.getTag();
- fragmentClass = fragment.getClass();
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowAbsListView.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowAbsListView.java
deleted file mode 100644
index 5ee3c55ac..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowAbsListView.java
+++ /dev/null
@@ -1,65 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.widget.AbsListView;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-@Implements(AbsListView.class)
-public class ShadowAbsListView extends ShadowAdapterView {
- private AbsListView.OnScrollListener onScrollListener;
- private int smoothScrolledPosition;
- private int lastSmoothScrollByDistance;
- private int lastSmoothScrollByDuration;
-
- @Implementation
- public void setOnScrollListener(AbsListView.OnScrollListener l) {
- onScrollListener = l;
- }
-
- @Implementation
- public void smoothScrollToPosition(int position) {
- smoothScrolledPosition = position;
- }
-
- @Implementation
- public void smoothScrollBy(int distance, int duration) {
- this.lastSmoothScrollByDistance = distance;
- this.lastSmoothScrollByDuration = duration;
- }
-
- /**
- * Robolectric accessor for the onScrollListener
- *
- * @return AbsListView.OnScrollListener
- */
- public AbsListView.OnScrollListener getOnScrollListener() {
- return onScrollListener;
- }
-
- /**
- * Robolectric accessor for the last smoothScrolledPosition
- *
- * @return int position
- */
- public int getSmoothScrolledPosition() {
- return smoothScrolledPosition;
- }
-
- /**
- * Robolectric accessor for the last smoothScrollBy distance
- *
- * @return int distance
- */
- public int getLastSmoothScrollByDistance() {
- return lastSmoothScrollByDistance;
- }
-
- /**
- * Robolectric accessor for the last smoothScrollBy duration
- *
- * @return int duration
- */
- public int getLastSmoothScrollByDuration() {
- return lastSmoothScrollByDuration;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowAbsSeekBar.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowAbsSeekBar.java
deleted file mode 100644
index e90f983e3..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowAbsSeekBar.java
+++ /dev/null
@@ -1,12 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.widget.AbsSeekBar;
-
-import com.xtremelabs.robolectric.internal.Implements;
-
-@Implements(AbsSeekBar.class)
-public class ShadowAbsSeekBar extends ShadowProgressBar {
-
- boolean mIsUserSeekable = true;
-
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowAbsSpinner.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowAbsSpinner.java
deleted file mode 100644
index 80c73fe10..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowAbsSpinner.java
+++ /dev/null
@@ -1,46 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-import android.view.View;
-import android.widget.AbsSpinner;
-import android.widget.SpinnerAdapter;
-
-@SuppressWarnings({"UnusedDeclaration"})
-@Implements(AbsSpinner.class)
-public class ShadowAbsSpinner extends ShadowAdapterView {
-
- private boolean animatedTransition;
-
- @Implementation
- public void setAdapter(SpinnerAdapter adapter) {
- super.setAdapter(adapter);
- }
-
- @Override @Implementation
- public SpinnerAdapter getAdapter() {
- return (SpinnerAdapter) super.getAdapter();
- }
-
- @Implementation
- public void setSelection(int position, boolean animate) {
- super.setSelection(position);
- animatedTransition = animate;
- }
-
- @Implementation
- public View getSelectedView() {
- int selectedItemPosition = getSelectedItemPosition();
- if (getCount() == 0 || selectedItemPosition < 0) {
- return null;
- } else {
- return getChildAt(selectedItemPosition);
- }
- }
-
- // Non-implementation helper method
- public boolean isAnimatedTransition() {
- return animatedTransition;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowAbsoluteLayout.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowAbsoluteLayout.java
deleted file mode 100644
index 9460425a5..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowAbsoluteLayout.java
+++ /dev/null
@@ -1,10 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.widget.AbsoluteLayout;
-import com.xtremelabs.robolectric.internal.Implements;
-
-@SuppressWarnings({"UnusedDeclaration"})
-@Implements(AbsoluteLayout.class)
-public class ShadowAbsoluteLayout extends ShadowViewGroup {
-
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowAbstractCursor.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowAbstractCursor.java
deleted file mode 100644
index 11e859715..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowAbstractCursor.java
+++ /dev/null
@@ -1,177 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import android.content.ContentResolver;
-import android.database.AbstractCursor;
-import android.database.CursorWindow;
-import android.net.Uri;
-
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.internal.RealObject;
-
-
-@Implements(AbstractCursor.class)
-public class ShadowAbstractCursor {
- @RealObject
- private AbstractCursor realAbstractCursor;
-
- protected Map<String, Object> currentRow;
- protected int currentRowNumber = -1;
- protected Map<String, Integer> columnNames = new HashMap<String, Integer>();
- protected String[] columnNameArray;
- protected Map<Integer, Map<String, Object>> rows = new HashMap<Integer, Map<String, Object>>();
- protected int rowCount;
- protected Uri notificationUri;
- protected boolean mClosed;
-
- @Implementation
- public int getCount() {
- return rowCount;
- }
-
- @Implementation
- public boolean moveToFirst() {
- setPosition(0);
- return realAbstractCursor.getCount() > 0;
- }
-
- @Implementation
- public boolean moveToLast() {
- if( realAbstractCursor.getCount() == 0 ) {
- return false;
- }
- setPosition( realAbstractCursor.getCount() - 1 );
- return true;
- }
-
- @Implementation
- public int getPosition() {
- return currentRowNumber;
- }
-
-
- @Implementation
- public boolean moveToPosition(int pos) {
- if (pos >= realAbstractCursor.getCount()) {
- return false;
- }
-
- setPosition(pos);
- return true;
- }
-
- /**
- * Set currentRowNumber(Int) and currentRow (Map)
- *
- * @param pos = the position to set
- */
- private void setPosition(int pos) {
- currentRowNumber = pos;
- if ((-1 == currentRowNumber) || (rowCount == currentRowNumber)) {
- currentRow = null;
- } else {
- currentRow = rows.get(currentRowNumber);
- }
- }
-
- @Implementation
- public boolean moveToNext() {
- if (currentRowNumber + 1 >= realAbstractCursor.getCount()) {
- currentRowNumber = realAbstractCursor.getCount();
- return false;
- }
- setPosition(++currentRowNumber);
- return true;
- }
-
- @Implementation
- public boolean moveToPrevious() {
- if (currentRowNumber < 0 || realAbstractCursor.getCount() == 0) {
- return false;
- }
- setPosition(--currentRowNumber);
- return true;
- }
-
- @Implementation
- public CursorWindow getWindow() {
- return null;
- }
-
- @Implementation
- public String[] getColumnNames() {
- return columnNameArray;
- }
-
- @Implementation
- public String getColumnName(int column) {
- return columnNameArray[column];
- }
-
- @Implementation
- public int getColumnIndex(String columnName) {
- for (int i=0; i<columnNameArray.length; i++) {
- if (columnName.equals(columnNameArray[i])) return i;
- }
- return -1;
- }
-
- @Implementation
- public int getColumnIndexOrThrow(String columnName) {
- int idx = getColumnIndex(columnName);
- if (idx >= 0) return idx; else throw new IllegalArgumentException("column does not exist");
- }
-
- @Implementation
- public int getColumnCount() {
- return getColumnNames().length;
- }
-
- @Implementation
- public boolean isFirst() {
- return currentRowNumber == 0;
- }
-
- @Implementation
- public boolean isLast() {
- return currentRowNumber == realAbstractCursor.getCount() - 1;
- }
-
- @Implementation
- public boolean isBeforeFirst() {
- return currentRowNumber < 0;
- }
-
- @Implementation
- public boolean isAfterLast() {
- return currentRowNumber >= realAbstractCursor.getCount();
- }
-
- @Implementation
- public void setNotificationUri(ContentResolver cr, Uri notifyUri) {
- notificationUri = notifyUri;
- }
-
- @Implementation
- public boolean isClosed() {
- return mClosed;
- }
-
- @Implementation
- public void close() {
- mClosed = true;
- }
-
- /**
- * Returns the Uri set by {@code setNotificationUri()}. Method included for testing
- * pre-API 11 projects.
- */
- public Uri getNotificationUri_Compatibility() {
- return notificationUri;
- }
-
-
-} \ No newline at end of file
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowAccount.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowAccount.java
deleted file mode 100644
index 37bd4a4c2..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowAccount.java
+++ /dev/null
@@ -1,86 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.accounts.Account;
-import android.os.Parcel;
-import android.os.Parcelable.Creator;
-import android.text.TextUtils;
-
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.internal.RealObject;
-
-import java.lang.reflect.Field;
-
-@Implements(Account.class)
-public class ShadowAccount {
- @RealObject
- private Account realObject;
-
- public void __constructor__(String name, String type) throws Exception {
- set(name, type);
- }
-
- public void __constructor__(Parcel parcel) throws Exception {
- set(parcel.readString(), parcel.readString());
- }
-
- @Override
- @Implementation
- public String toString() {
- return "Account {name=" + realObject.name + ", type=" + realObject.type + "}";
- }
-
- @Implementation
- public void writeToParcel(Parcel dest, int flags) {
- dest.writeString(realObject.name);
- dest.writeString(realObject.type);
- }
-
- public static final Creator<Account> CREATOR =
- new Creator<Account>() {
- @Override
- public Account createFromParcel(Parcel source) {
- return new Account(source);
- }
-
- @Override
- public Account[] newArray(int size) {
- return new Account[size];
- }
- };
-
- private void set(String name, String type) throws Exception {
- if (TextUtils.isEmpty(name) || TextUtils.isEmpty(type)) throw new IllegalArgumentException();
-
- Field nameF = realObject.getClass().getField("name");
- nameF.setAccessible(true);
- nameF.set(realObject, name);
-
- Field typeF = realObject.getClass().getField("type");
- typeF.setAccessible(true);
- typeF.set(realObject, type);
- }
-
- @Override
- @Implementation
- public boolean equals(Object o) {
- if (o == this) return true;
- if (!(o instanceof Account)) return false;
- final Account other = (Account)o;
- return realObject.name.equals(other.name) && realObject.type.equals(other.type);
- }
-
- @Override
- @Implementation
- public int hashCode() {
- int result = 17;
- result = 31 * result + realObject.name.hashCode();
- result = 31 * result + realObject.type.hashCode();
- return result;
- }
-
- public static void reset() {
- Robolectric.Reflection.setFinalStaticField(Account.class, "CREATOR", CREATOR);
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowAccountManager.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowAccountManager.java
deleted file mode 100644
index e2a0f24e5..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowAccountManager.java
+++ /dev/null
@@ -1,206 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.accounts.Account;
-import android.accounts.AccountManager;
-import android.accounts.AccountManagerCallback;
-import android.accounts.AccountManagerFuture;
-import android.accounts.AuthenticatorException;
-import android.accounts.OperationCanceledException;
-import android.app.Activity;
-import android.content.Context;
-import android.os.Bundle;
-import android.os.Handler;
-
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.internal.RealObject;
-
-import java.io.IOException;
-import java.util.*;
-import java.util.concurrent.TimeUnit;
-
-import static com.xtremelabs.robolectric.Robolectric.newInstanceOf;
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-
-/**
- * Shadows the {@code android.accounts.AccountManager} class.
- */
-@SuppressWarnings({"UnusedDeclaration"})
-@Implements(AccountManager.class)
-public class ShadowAccountManager {
-
- public static final String AUTH_TOKEN_VALUE = "authToken";
-
- private static AccountManager singleton;
-
- private Account[] accounts;
- private HashMap<Account, HashMap<String, String>> cachedAuthTokenValues =
- new HashMap<Account, HashMap<String, String>>();
-
- @Implementation
- public static AccountManager get(Context context) {
- if (singleton == null) {
- singleton = Robolectric.newInstanceOf(AccountManager.class);
- }
- return singleton;
- }
-
- @Implementation
- public AccountManagerFuture<Bundle> getAuthToken(Account account, String authTokenType, Bundle options, Activity activity, AccountManagerCallback<Bundle> callback, Handler handler) {
- //TODO: Add complete activity to perform the account intent dance.
- final Account finalAccount = account;
- return new AccountManagerFuture<Bundle>() {
-
- private boolean isFutureCancelled;
- private boolean isFutureDone;
-
- @Override
- public boolean cancel(boolean mayInterruptIfRunning) {
- if (isFutureDone) {
- return false;
- }
- isFutureCancelled = true;
- return isCancelled();
- }
-
- @Override
- public Bundle getResult(long timeout, TimeUnit unit) throws OperationCanceledException,
- AuthenticatorException, IOException {
- Bundle result = new Bundle();
- if (!isCancelled()) {
- addBundleResults(result, finalAccount);
- isFutureDone = true;
- }
- return result;
- }
-
- @Override
- public Bundle getResult() throws OperationCanceledException,
- AuthenticatorException, IOException {
- Bundle result = new Bundle();
- if (!isCancelled()) {
- addBundleResults(result, finalAccount);
- isFutureDone = true;
- }
- return result;
- }
-
- @Override
- public boolean isCancelled() {
- return isFutureCancelled;
- }
-
- @Override
- public boolean isDone() {
- return isFutureDone || isFutureCancelled;
- }
-
- private void addBundleResults(Bundle bundle, final Account account) {
- bundle.putString(AccountManager.KEY_AUTHTOKEN, AUTH_TOKEN_VALUE);
- bundle.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
- bundle.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
- }
- };
- }
-
- @Implementation
- public AccountManagerFuture<Bundle> getAuthTokenByFeatures(String accountType, String authTokenType, String[] features, Activity activity, Bundle addAccountOptions, Bundle getAuthTokenOptions, AccountManagerCallback<Bundle> callback, Handler handler) {
- //TODO: Add complete activity to perform the account intent dance.
- final String finalAccountType = accountType;
- return new AccountManagerFuture<Bundle>() {
-
- private boolean isFutureCancelled;
- private boolean isFutureDone;
-
- @Override
- public boolean cancel(boolean mayInterruptIfRunning) {
- if (isFutureDone) {
- return false;
- }
- isFutureCancelled = true;
- return isCancelled();
- }
-
- @Override
- public Bundle getResult(long timeout, TimeUnit unit) throws OperationCanceledException,
- AuthenticatorException, IOException {
- Bundle result = new Bundle();
- if (!isCancelled()) {
- addBundleResults(result, finalAccountType);
- isFutureDone = true;
- }
- return result;
- }
-
- @Override
- public Bundle getResult() throws OperationCanceledException,
- AuthenticatorException, IOException {
- Bundle result = new Bundle();
- if (!isCancelled()) {
- addBundleResults(result, finalAccountType);
- isFutureDone = true;
- }
- return result;
- }
-
- @Override
- public boolean isCancelled() {
- return isFutureCancelled;
- }
-
- @Override
- public boolean isDone() {
- return isFutureDone || isFutureCancelled;
- }
-
- private void addBundleResults(Bundle bundle, final String accountType) {
- bundle.putString(AccountManager.KEY_AUTHTOKEN, AUTH_TOKEN_VALUE);
- bundle.putString(AccountManager.KEY_ACCOUNT_TYPE, accountType);
- bundle.putString(AccountManager.KEY_ACCOUNT_NAME, "accountName");
- }
- };
- }
-
- @Implementation
- public void invalidateAuthToken(String accountType, String authToken) {}
-
- @Implementation
- public Account[] getAccounts() {
- return getAccountsByType(null);
- }
-
- @Implementation
- public Account[] getAccountsByType(String accountType) {
- if (accountType == null) {
- return accounts;
- }
-
- ArrayList<Account> accountList = new ArrayList<Account>();
- if (accounts != null) {
- for (Account account : accounts) {
- if (accountType.equals(account.type)) {
- accountList.add(account);
- }
- }
- }
- return accountList.toArray(new Account[accountList.size()]);
- }
-
- @Implementation
- public String peekAuthToken(Account account, String authTokenType) {
- HashMap<String, String> tokens = cachedAuthTokenValues.get(account);
- return (tokens != null) ? tokens.get(authTokenType) : null;
- }
-
- public void setCachedAuthToken(Account account, String authTokenType, String authTokenValue) {
- if (!cachedAuthTokenValues.containsKey(account)) {
- cachedAuthTokenValues.put(account, new HashMap<String, String>());
- }
- cachedAuthTokenValues.get(account).put(authTokenType, authTokenValue);
- }
-
- public void setAccounts(Account[] accounts) {
- this.accounts = accounts;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowActivity.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowActivity.java
deleted file mode 100644
index d3162159e..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowActivity.java
+++ /dev/null
@@ -1,549 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.app.Activity;
-import android.app.Application;
-import android.app.Dialog;
-import android.content.Context;
-import android.content.Intent;
-import android.content.SharedPreferences;
-import android.database.Cursor;
-import android.os.Bundle;
-import android.view.*;
-import android.widget.FrameLayout;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.internal.RealObject;
-import com.xtremelabs.robolectric.tester.android.view.TestWindow;
-
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import javassist.bytecode.Mnemonic;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-
-
-@SuppressWarnings({"UnusedDeclaration"})
-@Implements(Activity.class)
-public class ShadowActivity extends ShadowContextWrapper {
- @RealObject
- protected Activity realActivity;
-
- private Intent intent;
- private FrameLayout contentViewContainer;
- private View contentView;
- private int orientation;
- private int resultCode;
- private Intent resultIntent;
- private Activity parent;
- private boolean finishWasCalled;
- private TestWindow window;
-
- private List<IntentForResult> startedActivitiesForResults = new ArrayList<IntentForResult>();
-
- private Map<Intent, Integer> intentRequestCodeMap = new HashMap<Intent, Integer>();
- private int requestedOrientation = -1;
- private View currentFocus;
- private Integer lastShownDialogId = null;
- private int pendingTransitionEnterAnimResId = -1;
- private int pendingTransitionExitAnimResId = -1;
- private Object lastNonConfigurationInstance;
- private Map<Integer, Dialog> dialogForId = new HashMap<Integer, Dialog>();
- private CharSequence title;
- private boolean onKeyUpWasCalled;
- private ArrayList<Cursor> managedCusors = new ArrayList<Cursor>();
-
- @Implementation
- public final Application getApplication() {
- return Robolectric.application;
- }
-
- @Override
- @Implementation
- public final Application getApplicationContext() {
- return getApplication();
- }
-
- @Implementation
- public void setIntent(Intent intent) {
- this.intent = intent;
- }
-
- @Implementation
- public Intent getIntent() {
- return intent;
- }
-
- @Implementation(i18nSafe = false)
- public void setTitle(CharSequence title) {
- this.title = title;
- }
-
- @Implementation
- public void setTitle(int titleId) {
- this.title = this.getResources().getString(titleId);
- }
-
- @Implementation
- public CharSequence getTitle() {
- return title;
- }
-
- /**
- * Sets the {@code contentView} for this {@code Activity} by invoking the
- * {@link android.view.LayoutInflater}
- *
- * @param layoutResID ID of the layout to inflate
- * @see #getContentView()
- */
- @Implementation
- public void setContentView(int layoutResID) {
- contentView = getLayoutInflater().inflate(layoutResID, new FrameLayout(realActivity));
- realActivity.onContentChanged();
- }
-
- @Implementation
- public void setContentView(View view) {
- contentView = view;
- realActivity.onContentChanged();
- }
-
- @Implementation
- public final void setResult(int resultCode) {
- this.resultCode = resultCode;
- }
-
- @Implementation
- public final void setResult(int resultCode, Intent data) {
- this.resultCode = resultCode;
- this.resultIntent = data;
- }
-
- @Implementation
- public LayoutInflater getLayoutInflater() {
- return LayoutInflater.from(realActivity);
- }
-
- @Implementation
- public MenuInflater getMenuInflater() {
- return new MenuInflater(realActivity);
- }
-
- /**
- * Checks to ensure that the{@code contentView} has been set
- *
- * @param id ID of the view to find
- * @return the view
- * @throws RuntimeException if the {@code contentView} has not been called first
- */
- @Implementation
- public View findViewById(int id) {
- if (id == android.R.id.content) {
- return getContentViewContainer();
- }
- if (contentView != null) {
- return contentView.findViewById(id);
- } else {
- System.out.println("WARNING: you probably should have called setContentView() first");
- Thread.dumpStack();
- return null;
- }
- }
-
- private View getContentViewContainer() {
- if (contentViewContainer == null) {
- contentViewContainer = new FrameLayout(realActivity);
- }
- contentViewContainer.addView(contentView, 0);
- return contentViewContainer;
- }
-
- @Implementation
- public final Activity getParent() {
- return parent;
- }
-
- @Implementation
- public void onBackPressed() {
- finish();
- }
-
- @Implementation
- public void finish() {
- finishWasCalled = true;
- }
-
- public void resetIsFinishing() {
- finishWasCalled = false;
- }
-
- /**
- * @return whether {@link #finish()} was called
- */
- @Implementation
- public boolean isFinishing() {
- return finishWasCalled;
- }
-
- /**
- * Constructs a new Window (a {@link com.xtremelabs.robolectric.tester.android.view.TestWindow}) if no window has previously been
- * set.
- *
- * @return the window associated with this Activity
- */
- @Implementation
- public Window getWindow() {
- if (window == null) {
- window = new TestWindow(realActivity);
- }
- return window;
- }
-
- public void setWindow(TestWindow wind){
- window = wind;
- }
-
- @Implementation
- public void runOnUiThread(Runnable action) {
- Robolectric.getUiThreadScheduler().post(action);
- }
-
- @Implementation
- public void onCreate(Bundle bundle) {
-
- }
-
- /**
- * Checks to see if {@code BroadcastListener}s are still registered.
- *
- * @throws RuntimeException if any listeners are still registered
- * @see #assertNoBroadcastListenersRegistered()
- */
- @Implementation
- public void onDestroy() {
- assertNoBroadcastListenersRegistered();
- }
-
- @Implementation
- public WindowManager getWindowManager() {
- return (WindowManager) Robolectric.application.getSystemService(Context.WINDOW_SERVICE);
- }
-
- @Implementation
- public void setRequestedOrientation(int requestedOrientation) {
- this.requestedOrientation = requestedOrientation;
- }
-
- @Implementation
- public int getRequestedOrientation() {
- return requestedOrientation;
- }
-
- @Implementation
- public SharedPreferences getPreferences(int mode) {
- return ShadowPreferenceManager.getDefaultSharedPreferences(getApplicationContext());
- }
-
- /**
- * Checks the {@code ApplicationContext} to see if {@code BroadcastListener}s are still registered.
- *
- * @throws RuntimeException if any listeners are still registered
- * @see ShadowApplication#assertNoBroadcastListenersRegistered(android.content.Context, String)
- */
- public void assertNoBroadcastListenersRegistered() {
- shadowOf(getApplicationContext()).assertNoBroadcastListenersRegistered(realActivity, "Activity");
- }
-
- /**
- * Non-Android accessor.
- *
- * @return the {@code contentView} set by one of the {@code setContentView()} methods
- */
- public View getContentView() {
- return contentView;
- }
-
- /**
- * Non-Android accessor.
- *
- * @return the {@code resultCode} set by one of the {@code setResult()} methods
- */
- public int getResultCode() {
- return resultCode;
- }
-
- /**
- * Non-Android accessor.
- *
- * @return the {@code Intent} set by {@link #setResult(int, android.content.Intent)}
- */
- public Intent getResultIntent() {
- return resultIntent;
- }
-
- /**
- * Non-Android accessor consumes and returns the next {@code Intent} on the
- * started activities for results stack.
- *
- * @return the next started {@code Intent} for an activity, wrapped in
- * an {@link ShadowActivity.IntentForResult} object
- */
- public IntentForResult getNextStartedActivityForResult() {
- if (startedActivitiesForResults.isEmpty()) {
- return null;
- } else {
- return startedActivitiesForResults.remove(0);
- }
- }
-
- /**
- * Non-Android accessor returns the most recent {@code Intent} started by
- * {@link #startActivityForResult(android.content.Intent, int)} without
- * consuming it.
- *
- * @return the most recently started {@code Intent}, wrapped in
- * an {@link ShadowActivity.IntentForResult} object
- */
- public IntentForResult peekNextStartedActivityForResult() {
- if (startedActivitiesForResults.isEmpty()) {
- return null;
- } else {
- return startedActivitiesForResults.get(0);
- }
- }
-
- @Implementation
- public Object getLastNonConfigurationInstance() {
- return lastNonConfigurationInstance;
- }
-
- public void setLastNonConfigurationInstance(Object lastNonConfigurationInstance) {
- this.lastNonConfigurationInstance = lastNonConfigurationInstance;
- }
-
- /**
- * Non-Android accessor Sets the {@code View} for this {@code Activity}
- *
- * @param view
- */
- public void setCurrentFocus(View view) {
- currentFocus = view;
- }
-
- @Implementation
- public View getCurrentFocus() {
- if (currentFocus != null) {
- return currentFocus;
- } else if (contentView != null) {
- return contentView.findFocus();
- } else {
- return null;
- }
- }
-
- public void clearFocus() {
- currentFocus = null;
- if (contentView != null) {
- contentView.clearFocus();
- }
- }
-
- @Implementation
- public boolean onKeyUp(int keyCode, KeyEvent event) {
- onKeyUpWasCalled = true;
- if (keyCode == KeyEvent.KEYCODE_BACK) {
- onBackPressed();
- return true;
- }
- return false;
- }
-
- public boolean onKeyUpWasCalled() {
- return onKeyUpWasCalled;
- }
-
- public void resetKeyUpWasCalled() {
- onKeyUpWasCalled = false;
- }
-
- /**
- * Container object to hold an Intent, together with the requestCode used
- * in a call to {@code Activity#startActivityForResult(Intent, int)}
- */
- public class IntentForResult {
- public Intent intent;
- public int requestCode;
-
- public IntentForResult(Intent intent, int requestCode) {
- this.intent = intent;
- this.requestCode = requestCode;
- }
- }
-
- @Implementation
- public void startActivityForResult(Intent intent, int requestCode) {
- intentRequestCodeMap.put(intent, requestCode);
- startedActivitiesForResults.add(new IntentForResult(intent, requestCode));
- getApplicationContext().startActivity(intent);
- }
-
- public void receiveResult(Intent requestIntent, int resultCode, Intent resultIntent) {
- Integer requestCode = intentRequestCodeMap.get(requestIntent);
- if (requestCode == null) {
- throw new RuntimeException("No intent matches " + requestIntent + " among " + intentRequestCodeMap.keySet());
- }
-
- final ActivityInvoker invoker = new ActivityInvoker();
- invoker.call("onActivityResult", Integer.TYPE, Integer.TYPE, Intent.class)
- .with(requestCode, resultCode, resultIntent);
- }
-
- @Implementation
- public final void showDialog(int id) {
- showDialog(id, null);
- }
-
- @Implementation
- public final void dismissDialog(int id) {
- final Dialog dialog = dialogForId.get(id);
- if (dialog == null) {
- throw new IllegalArgumentException();
- }
-
- dialog.dismiss();
- }
-
- @Implementation
- public final void removeDialog(int id) {
- dialogForId.remove(id);
- }
-
- @Implementation
- public final boolean showDialog(int id, Bundle bundle) {
- Dialog dialog = null;
- this.lastShownDialogId = id;
-
- dialog = dialogForId.get(id);
-
- if (dialog == null) {
- final ActivityInvoker invoker = new ActivityInvoker();
- dialog = (Dialog) invoker.call("onCreateDialog", Integer.TYPE).with(id);
-
- if (bundle == null) {
- invoker.call("onPrepareDialog", Integer.TYPE, Dialog.class)
- .with(id, dialog);
- } else {
- invoker.call("onPrepareDialog", Integer.TYPE, Dialog.class, Bundle.class)
- .with(id, dialog, bundle);
- }
-
- dialogForId.put(id, dialog);
- }
-
- dialog.show();
-
- return true;
- }
-
- /**
- * Non-Android accessor
- *
- * @return the dialog resource id passed into
- * {@code Activity#showDialog(int, Bundle)} or {@code Activity#showDialog(int)}
- */
- public Integer getLastShownDialogId() {
- return lastShownDialogId;
- }
-
- public boolean hasCancelledPendingTransitions() {
- return pendingTransitionEnterAnimResId == 0 && pendingTransitionExitAnimResId == 0;
- }
-
- @Implementation
- public void overridePendingTransition(int enterAnim, int exitAnim) {
- pendingTransitionEnterAnimResId = enterAnim;
- pendingTransitionExitAnimResId = exitAnim;
- }
-
- public Dialog getDialogById(int dialogId) {
- return dialogForId.get(dialogId);
- }
-
- public void create() {
- final ActivityInvoker invoker = new ActivityInvoker();
-
- final Bundle noInstanceState = null;
- invoker.call("onCreate", Bundle.class).with(noInstanceState);
- invoker.call("onStart").withNothing();
- invoker.call("onPostCreate", Bundle.class).with(noInstanceState);
- invoker.call("onResume").withNothing();
- }
-
- @Implementation
- public void recreate() {
- Bundle outState = new Bundle();
- final ActivityInvoker invoker = new ActivityInvoker();
-
- invoker.call("onSaveInstanceState", Bundle.class).with(outState);
- invoker.call("onPause").withNothing();
- invoker.call("onStop").withNothing();
-
- Object nonConfigInstance = invoker.call("onRetainNonConfigurationInstance").withNothing();
- setLastNonConfigurationInstance(nonConfigInstance);
-
- invoker.call("onDestroy").withNothing();
- invoker.call("onCreate", Bundle.class).with(outState);
- invoker.call("onStart").withNothing();
- invoker.call("onRestoreInstanceState", Bundle.class).with(outState);
- invoker.call("onResume").withNothing();
- }
-
- @Implementation
- public void startManagingCursor(Cursor c) {
- managedCusors.add(c);
- }
-
- @Implementation
- public void stopManagingCursor(Cursor c) {
- managedCusors.remove(c);
- }
-
- public List<Cursor> getManagedCursors() {
- return managedCusors;
- }
-
- private final class ActivityInvoker {
- private Method method;
-
- public ActivityInvoker call(final String methodName, final Class ...argumentClasses) {
- try {
- method = Activity.class.getDeclaredMethod(methodName, argumentClasses);
- method.setAccessible(true);
- return this;
- } catch(NoSuchMethodException e) {
- throw new RuntimeException(e);
- }
- }
-
- public Object withNothing() {
- return with();
- }
-
- public Object with(final Object ...parameters) {
- try {
- return method.invoke(realActivity, parameters);
- } catch(IllegalAccessException e) {
- throw new RuntimeException(e);
- } catch(IllegalArgumentException e) {
- throw new RuntimeException(e);
- } catch(InvocationTargetException e) {
- throw new RuntimeException(e);
- }
- }
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowActivityGroup.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowActivityGroup.java
deleted file mode 100644
index 16ccce62b..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowActivityGroup.java
+++ /dev/null
@@ -1,25 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.app.Activity;
-import android.app.ActivityGroup;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-@Implements(ActivityGroup.class)
-public class ShadowActivityGroup extends ShadowActivity {
- private Activity currentActivity;
-
- @Implementation
- public android.app.Activity getCurrentActivity() {
- return currentActivity;
- }
-
- /**
- * Non-Android accessor Sets the current {@code Activity} for this {@code ActivityGroup}
- *
- * @param activity
- */
- public void setCurrentActivity(Activity activity) {
- currentActivity = activity;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowActivityInfo.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowActivityInfo.java
deleted file mode 100644
index 3f96ac5c2..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowActivityInfo.java
+++ /dev/null
@@ -1,20 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.internal.RealObject;
-
-import android.content.pm.ActivityInfo;
-
-@Implements(ActivityInfo.class)
-public class ShadowActivityInfo {
-
- @RealObject
- private ActivityInfo realInfo;
-
- @Implementation
- public String toString() {
- return realInfo.name;
- }
-
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowActivityManager.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowActivityManager.java
deleted file mode 100644
index 059139f53..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowActivityManager.java
+++ /dev/null
@@ -1,83 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.app.ActivityManager;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Shadow for the Android {@code ActivityManager} class.
- */
-@SuppressWarnings({"UnusedDeclaration"})
-@Implements(ActivityManager.class)
-public class ShadowActivityManager {
-
- private List<ActivityManager.RunningTaskInfo> tasks =
- new ArrayList<ActivityManager.RunningTaskInfo>();
-
- private List<ActivityManager.RunningAppProcessInfo> processes =
- new ArrayList<ActivityManager.RunningAppProcessInfo>();
-
- private String backgroundPackage;
- private ActivityManager.MemoryInfo memoryInfo;
-
- @Implementation
- public List<ActivityManager.RunningTaskInfo> getRunningTasks(int maxNum) {
- return tasks;
- }
-
- @Implementation
- public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses() {
- return processes;
- }
-
- @Implementation
- public void killBackgroundProcesses(String packageName) {
- backgroundPackage = packageName;
- }
-
- @Implementation
- public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) {
- if (memoryInfo != null) {
- outInfo.lowMemory = memoryInfo.lowMemory;
- }
- }
-
- /**
- * Non-Android accessor to set the list of running tasks.
- * @param tasks
- */
- public void setTasks(List<ActivityManager.RunningTaskInfo> tasks) {
- this.tasks = tasks;
- }
-
- /**
- * Non-Android accessor to set the list of running processes.
- * @param processes
- */
- public void setProcesses( List<ActivityManager.RunningAppProcessInfo> processes ) {
- this.processes = processes;
- }
-
- /**
- * Non-Android accessor, for use in assertions.
- */
- public String getBackgroundPackage() {
- return backgroundPackage;
- }
-
- public void setMemoryInfo(ActivityManager.MemoryInfo memoryInfo) {
- this.memoryInfo = memoryInfo;
- }
-
- @Implements(ActivityManager.MemoryInfo.class)
- public static class ShadowMemoryInfo {
- public boolean lowMemory;
-
- public void setLowMemory(boolean lowMemory) {
- this.lowMemory = lowMemory;
- }
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowAdapterView.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowAdapterView.java
deleted file mode 100644
index 7c3b13f77..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowAdapterView.java
+++ /dev/null
@@ -1,343 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.database.DataSetObserver;
-import android.os.Handler;
-import android.view.View;
-import android.widget.Adapter;
-import android.widget.AdapterView;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.internal.RealObject;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-
-@SuppressWarnings({"UnusedDeclaration"})
-@Implements(AdapterView.class)
-public class ShadowAdapterView extends ShadowViewGroup {
- private static int ignoreRowsAtEndOfList = 0;
- private static boolean automaticallyUpdateRowViews = true;
-
- @RealObject
- private AdapterView realAdapterView;
-
- private Adapter adapter;
- private View mEmptyView;
- private AdapterView.OnItemSelectedListener onItemSelectedListener;
- private AdapterView.OnItemClickListener onItemClickListener;
- private AdapterView.OnItemLongClickListener onItemLongClickListener;
- private boolean valid = false;
- private int selectedPosition;
- private int itemCount = 0;
-
- private List<Object> previousItems = new ArrayList<Object>();
-
- @Implementation
- public void setAdapter(Adapter adapter) {
- this.adapter = adapter;
-
- if (null != adapter) {
- adapter.registerDataSetObserver(new AdapterViewDataSetObserver());
- }
-
- invalidateAndScheduleUpdate();
- setSelection(0);
- }
-
- @Implementation
- public void setEmptyView(View emptyView) {
- this.mEmptyView = emptyView;
- updateEmptyStatus(adapter == null || adapter.isEmpty());
- }
-
- @Implementation
- public int getPositionForView(android.view.View view) {
- while (view.getParent() != null && view.getParent() != realView) {
- view = (View) view.getParent();
- }
-
- for (int i = 0; i < getChildCount(); i++) {
- if (view == getChildAt(i)) {
- return i;
- }
- }
-
- return AdapterView.INVALID_POSITION;
- }
-
- private void invalidateAndScheduleUpdate() {
- valid = false;
- itemCount = adapter == null ? 0 : adapter.getCount();
- if (mEmptyView != null) {
- updateEmptyStatus(itemCount == 0);
- }
-
- if (hasOnItemSelectedListener() && itemCount == 0) {
- onItemSelectedListener.onNothingSelected(realAdapterView);
- }
-
- new Handler().post(new Runnable() {
- @Override
- public void run() {
- if (!valid) {
- update();
- valid = true;
- }
- }
- });
- }
-
- private boolean hasOnItemSelectedListener() {
- return onItemSelectedListener != null;
- }
-
- private void updateEmptyStatus(boolean empty) {
- // code taken from the real AdapterView and commented out where not (yet?) applicable
-
- // we don't deal with filterMode yet...
-// if (isInFilterMode()) {
-// empty = false;
-// }
-
- if (empty) {
- if (mEmptyView != null) {
- mEmptyView.setVisibility(View.VISIBLE);
- setVisibility(View.GONE);
- } else {
- // If the caller just removed our empty view, make sure the list view is visible
- setVisibility(View.VISIBLE);
- }
-
- // leave layout for the moment...
-// // We are now GONE, so pending layouts will not be dispatched.
-// // Force one here to make sure that the state of the list matches
-// // the state of the adapter.
-// if (mDataChanged) {
-// this.onLayout(false, mLeft, mTop, mRight, mBottom);
-// }
- } else {
- if (mEmptyView != null) {
- mEmptyView.setVisibility(View.GONE);
- }
- setVisibility(View.VISIBLE);
- }
- }
-
- /**
- * Check if our adapter's items have changed without {@code onChanged()} or {@code onInvalidated()} having been called.
- *
- * @return true if the object is valid, false if not
- * @throws RuntimeException if the items have been changed without notification
- */
- public boolean checkValidity() {
- update();
- return valid;
- }
-
- /**
- * Set to avoid calling getView() on the last row(s) during validation. Useful if you are using a special
- * last row, e.g. one that goes and fetches more list data as soon as it comes into view. This sets a static
- * on the class, so be sure to call it again and set it back to 0 at the end of your test.
- *
- * @param countOfRows The number of rows to ignore at the end of the list.
- * @see com.xtremelabs.robolectric.shadows.ShadowAdapterView#checkValidity()
- */
- public static void ignoreRowsAtEndOfListDuringValidation(int countOfRows) {
- ignoreRowsAtEndOfList = countOfRows;
- }
-
- /**
- * Use this static method to turn off the feature of this class which calls getView() on all of the
- * adapter's rows in setAdapter() and after notifyDataSetChanged() or notifyDataSetInvalidated() is
- * called on the adapter. This feature is turned on by default. This sets a static on the class, so
- * set it back to true at the end of your test to avoid test pollution.
- *
- * @param shouldUpdate false to turn off the feature, true to turn it back on
- */
- public static void automaticallyUpdateRowViews(boolean shouldUpdate) {
- automaticallyUpdateRowViews = shouldUpdate;
- }
-
- @Implementation
- public int getSelectedItemPosition() {
- return selectedPosition;
- }
-
- @Implementation
- public Object getSelectedItem() {
- int pos = getSelectedItemPosition();
- return getItemAtPosition(pos);
- }
-
- @Implementation
- public Adapter getAdapter() {
- return adapter;
- }
-
- @Implementation
- public int getCount() {
- return itemCount;
- }
-
- @Implementation
- public void setOnItemSelectedListener(AdapterView.OnItemSelectedListener listener) {
- this.onItemSelectedListener = listener;
- }
-
- @Implementation
- public final AdapterView.OnItemSelectedListener getOnItemSelectedListener() {
- return onItemSelectedListener;
- }
-
- @Implementation
- public void setOnItemClickListener(AdapterView.OnItemClickListener listener) {
- this.onItemClickListener = listener;
- }
-
- @Implementation
- public final AdapterView.OnItemClickListener getOnItemClickListener() {
- return onItemClickListener;
- }
-
- @Implementation
- public void setOnItemLongClickListener(AdapterView.OnItemLongClickListener listener) {
- this.onItemLongClickListener = listener;
- }
-
- @Implementation
- public AdapterView.OnItemLongClickListener getOnItemLongClickListener() {
- return onItemLongClickListener;
- }
-
- @Implementation
- public Object getItemAtPosition(int position) {
- Adapter adapter = getAdapter();
- return (adapter == null || position < 0) ? null : adapter.getItem(position);
- }
-
- @Implementation
- public long getItemIdAtPosition(int position) {
- Adapter adapter = getAdapter();
- return (adapter == null || position < 0) ? AdapterView.INVALID_ROW_ID : adapter.getItemId(position);
- }
-
- @Implementation
- public void setSelection(final int position) {
- selectedPosition = position;
-
- if (selectedPosition >= 0) {
- new Handler().post(new Runnable() {
- @Override
- public void run() {
- if (hasOnItemSelectedListener()) {
- onItemSelectedListener.onItemSelected(realAdapterView, getChildAt(position), position, getAdapter().getItemId(position));
- }
- }
- });
- }
- }
-
- @Implementation
- public boolean performItemClick(View view, int position, long id) {
- if (onItemClickListener != null) {
- onItemClickListener.onItemClick(realAdapterView, view, position, id);
- return true;
- }
- return false;
- }
-
- public boolean performItemLongClick(View view, int position, long id) {
- if (onItemLongClickListener != null) {
- onItemLongClickListener.onItemLongClick(realAdapterView, view, position, id);
- return true;
- }
- return false;
- }
-
- public boolean performItemClick(int position) {
- return realAdapterView.performItemClick(realAdapterView.getChildAt(position),
- position, realAdapterView.getItemIdAtPosition(position));
- }
-
- public int findIndexOfItemContainingText(String targetText) {
- for (int i = 0; i < realAdapterView.getChildCount(); i++) {
- View childView = realAdapterView.getChildAt(i);
- String innerText = shadowOf(childView).innerText();
- if (innerText.contains(targetText)) {
- return i;
- }
- }
- return -1;
- }
-
- public View findItemContainingText(String targetText) {
- int itemIndex = findIndexOfItemContainingText(targetText);
- if (itemIndex == -1) {
- return null;
- }
- return realAdapterView.getChildAt(itemIndex);
- }
-
- public void clickFirstItemContainingText(String targetText) {
- int itemIndex = findIndexOfItemContainingText(targetText);
- if (itemIndex == -1) {
- throw new IllegalArgumentException("No item found containing text \"" + targetText + "\"");
- }
- performItemClick(itemIndex);
- }
-
- @Implementation
- public View getEmptyView() {
- return mEmptyView;
- }
-
- private void update() {
- if (!automaticallyUpdateRowViews) {
- return;
- }
-
- super.removeAllViews();
- addViews();
- }
-
- protected void addViews() {
- Adapter adapter = getAdapter();
- if (adapter != null) {
- if (valid && (previousItems.size() - ignoreRowsAtEndOfList != adapter.getCount() - ignoreRowsAtEndOfList)) {
- throw new ArrayIndexOutOfBoundsException("view is valid but adapter.getCount() has changed from " + previousItems.size() + " to " + adapter.getCount());
- }
-
- List<Object> newItems = new ArrayList<Object>();
- for (int i = 0; i < adapter.getCount() - ignoreRowsAtEndOfList; i++) {
- View view = adapter.getView(i, null, realAdapterView);
- // don't add null views
- if (view != null) {
- addView(view);
- }
- newItems.add(adapter.getItem(i));
- }
-
- if (valid && !newItems.equals(previousItems)) {
- throw new RuntimeException("view is valid but current items <" + newItems + "> don't match previous items <" + previousItems + ">");
- }
- previousItems = newItems;
- }
- }
-
- /**
- * Simple default implementation of {@code android.database.DataSetObserver}
- */
- protected class AdapterViewDataSetObserver extends DataSetObserver {
- @Override
- public void onChanged() {
- invalidateAndScheduleUpdate();
- }
-
- @Override
- public void onInvalidated() {
- invalidateAndScheduleUpdate();
- }
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowAddress.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowAddress.java
deleted file mode 100644
index 449384fe1..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowAddress.java
+++ /dev/null
@@ -1,105 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.location.Address;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-
-@SuppressWarnings({"UnusedDeclaration"})
-@Implements(Address.class)
-public class ShadowAddress {
- private String addressLine1;
- private String locality;
- private String postalCode;
- private String adminArea;
- private String countryCode;
- private double longitude;
- private double latitude;
- private boolean hasLatitude;
- private boolean hasLongitude;
-
- @Implementation
- public double getLatitude() {
- return latitude;
- }
-
- @Implementation
- public void setLatitude(double latitude) {
- this.latitude = latitude;
- }
-
- @Implementation
- public double getLongitude() {
- return longitude;
- }
-
- @Implementation
- public void setLongitude(double longitude) {
- this.longitude = longitude;
- }
-
- @Implementation
- public void setAddressLine(int index, String line) {
- addressLine1 = line;
- }
-
- @Implementation
- public String getAddressLine(int index) {
- return addressLine1;
- }
-
- @Implementation
- public void setLocality(String locality) {
- this.locality = locality;
- }
-
- @Implementation
- public String getLocality() {
- return locality;
- }
-
- @Implementation
- public String getAdminArea() {
- return adminArea;
- }
-
- @Implementation
- public void setAdminArea(String adminArea) {
- this.adminArea = adminArea;
- }
-
- @Implementation
- public String getPostalCode() {
- return postalCode;
- }
-
- @Implementation
- public void setPostalCode(String postalCode) {
- this.postalCode = postalCode;
- }
-
- @Implementation
- public String getCountryCode() {
- return countryCode;
- }
-
- @Implementation
- public void setCountryCode(String countryCode) {
- this.countryCode = countryCode;
- }
-
- @Implementation
- public boolean hasLatitude() {
- return hasLatitude;
- }
-
- @Implementation
- public boolean hasLongitude() {
- return hasLongitude;
- }
-
- public void setSimulatedHasLatLong(boolean hasLatitude, boolean hasLongitude) {
- this.hasLatitude = hasLatitude;
- this.hasLongitude = hasLongitude;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowAlarmManager.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowAlarmManager.java
deleted file mode 100644
index 3fef768ed..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowAlarmManager.java
+++ /dev/null
@@ -1,111 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.app.AlarmManager;
-import android.app.PendingIntent;
-import android.content.Intent;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-
-/**
- * Shadows the {@code android.app.AlarmManager} class.
- */
-@SuppressWarnings({"UnusedDeclaration"})
-@Implements(AlarmManager.class)
-public class ShadowAlarmManager {
-
- private List<ScheduledAlarm> scheduledAlarms = new ArrayList<ScheduledAlarm>();
-
- @Implementation
- public void set(int type, long triggerAtTime, PendingIntent operation) {
- internalSet(type, triggerAtTime, 0L, operation);
- }
-
- @Implementation
- public void setRepeating (int type, long triggerAtTime, long interval, PendingIntent operation){
- internalSet(type, triggerAtTime, interval, operation);
- }
-
- private void internalSet(int type, long triggerAtTime, long interval, PendingIntent operation) {
- Intent intent = shadowOf(operation).getSavedIntent();
- for (ScheduledAlarm scheduledAlarm : scheduledAlarms) {
- Intent scheduledIntent = shadowOf(scheduledAlarm.operation).getSavedIntent();
- if (scheduledIntent.filterEquals(intent)) {
- scheduledAlarms.remove(scheduledAlarm);
- break;
- }
- }
- scheduledAlarms.add(new ScheduledAlarm(type, triggerAtTime, interval, operation));
- }
-
- /**
- * Non-Android accessor consumes and returns the next scheduled alarm on the
- * AlarmManager's stack.
- *
- * @return the next scheduled alarm, wrapped in a
- * {@link ShadowAlarmManager.ScheduledAlarm} object
- */
- public ScheduledAlarm getNextScheduledAlarm() {
- if (scheduledAlarms.isEmpty()) {
- return null;
- } else {
- return scheduledAlarms.remove(0);
- }
- }
-
- /**
- * Non-Android accessor returns the most recent scheduled alarm without
- * consuming it.
- *
- * @return the most recently scheduled alarm, wrapped in a
- * {@link ShadowAlarmManager.ScheduledAlarm} object
- */
- public ScheduledAlarm peekNextScheduledAlarm() {
- if (scheduledAlarms.isEmpty()) {
- return null;
- } else {
- return scheduledAlarms.get(0);
- }
- }
-
- public List<ScheduledAlarm> getScheduledAlarms() {
- return scheduledAlarms;
- }
-
- @Implementation
- public void cancel(PendingIntent pendingIntent) {
- final Intent intentTypeToRemove = shadowOf(pendingIntent).getSavedIntent();
- for (ScheduledAlarm scheduledAlarm : new ArrayList<ScheduledAlarm>(scheduledAlarms)) {
- final Intent alarmIntent = shadowOf(scheduledAlarm.operation).getSavedIntent();
- if (intentTypeToRemove.filterEquals(alarmIntent)) {
- scheduledAlarms.remove(scheduledAlarm);
- }
- }
- }
-
- /**
- * Container object to hold an PendingIntent, together with the alarm
- * parameters used in a call to {@code AlarmManager}
- */
- public class ScheduledAlarm {
- public int type;
- public long triggerAtTime;
- public long interval;
- public PendingIntent operation;
-
- public ScheduledAlarm(int type, long triggerAtTime, PendingIntent operation) {
- this(type, triggerAtTime, 0, operation);
- }
-
- public ScheduledAlarm(int type, long triggerAtTime, long interval, PendingIntent operation) {
- this.type = type;
- this.triggerAtTime = triggerAtTime;
- this.operation = operation;
- this.interval = interval;
- }
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowAlertDialog.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowAlertDialog.java
deleted file mode 100644
index 53f20f67f..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowAlertDialog.java
+++ /dev/null
@@ -1,470 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.R;
-import android.app.AlertDialog;
-import android.content.Context;
-import android.content.DialogInterface;
-import android.view.View;
-import android.widget.Adapter;
-import android.widget.AdapterView;
-import android.widget.ArrayAdapter;
-import android.widget.Button;
-import android.widget.ListAdapter;
-import android.widget.ListView;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.internal.RealObject;
-
-import java.lang.reflect.Constructor;
-
-import static com.xtremelabs.robolectric.Robolectric.getShadowApplication;
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-
-@SuppressWarnings({"UnusedDeclaration"})
-@Implements(AlertDialog.class)
-public class ShadowAlertDialog extends ShadowDialog {
- @RealObject
- private AlertDialog realAlertDialog;
-
- private CharSequence[] items;
- private String message;
- private DialogInterface.OnClickListener clickListener;
- private boolean isMultiItem;
- private boolean isSingleItem;
- private DialogInterface.OnMultiChoiceClickListener multiChoiceClickListener;
- private boolean[] checkedItems;
- private int checkedItemIndex;
- private Button positiveButton;
- private Button negativeButton;
- private Button neutralButton;
- private View view;
- private View customTitleView;
- private ListAdapter adapter;
- private ListView listView;
-
- /**
- * Non-Android accessor.
- *
- * @return the most recently created {@code AlertDialog}, or null if none has been created during this test run
- */
- public static AlertDialog getLatestAlertDialog() {
- ShadowAlertDialog dialog = Robolectric.getShadowApplication().getLatestAlertDialog();
- return dialog == null ? null : dialog.realAlertDialog;
- }
-
- @Override
- @Implementation
- public View findViewById(int viewId) {
- if(view == null) {
- return super.findViewById(viewId);
- }
-
- return view.findViewById(viewId);
- }
-
- @Implementation
- public void setView(View view) {
- this.view = view;
- }
-
- /**
- * Resets the tracking of the most recently created {@code AlertDialog}
- */
- public static void reset() {
- getShadowApplication().setLatestAlertDialog(null);
- }
-
- /**
- * Simulates a click on the {@code Dialog} item indicated by {@code index}. Handles both multi- and single-choice dialogs, tracks which items are currently
- * checked and calls listeners appropriately.
- *
- * @param index the index of the item to click on
- */
- public void clickOnItem(int index) {
- shadowOf(realAlertDialog.getListView()).performItemClick(index);
- }
-
- @Implementation
- public Button getButton(int whichButton) {
- switch (whichButton) {
- case AlertDialog.BUTTON_POSITIVE:
- return positiveButton;
- case AlertDialog.BUTTON_NEGATIVE:
- return negativeButton;
- case AlertDialog.BUTTON_NEUTRAL:
- return neutralButton;
- }
- throw new RuntimeException("Only positive, negative, or neutral button choices are recognized");
- }
-
- @Implementation
- public void setButton(int whichButton, CharSequence text, DialogInterface.OnClickListener listener) {
- switch (whichButton) {
- case AlertDialog.BUTTON_POSITIVE:
- positiveButton = createButton(context, realAlertDialog, whichButton, text, listener);
- return;
- case AlertDialog.BUTTON_NEGATIVE:
- negativeButton = createButton(context, realAlertDialog, whichButton, text, listener);
- return;
- case AlertDialog.BUTTON_NEUTRAL:
- neutralButton = createButton(context, realAlertDialog, whichButton, text, listener);
- return;
- }
- throw new RuntimeException("Only positive, negative, or neutral button choices are recognized");
- }
-
- private static Button createButton(final Context context, final DialogInterface dialog, final int which, CharSequence text, final DialogInterface.OnClickListener listener) {
- if (text == null && listener == null) {
- return null;
- }
- Button button = new Button(context);
- Robolectric.shadowOf(button).setText(text); // use shadow to skip
- // i18n-strict checking
- button.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- if (listener != null) {
- listener.onClick(dialog, which);
- }
- dialog.dismiss();
- }
- });
- return button;
- }
-
- @Implementation
- public ListView getListView() {
- if (listView == null) {
- listView = new ListView(context);
- listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
- @Override
- public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
- if (isMultiItem) {
- checkedItems[position] = !checkedItems[position];
- multiChoiceClickListener.onClick(realAlertDialog, position, checkedItems[position]);
- } else {
- if (isSingleItem) {
- checkedItemIndex = position;
- }
- clickListener.onClick(realAlertDialog, position);
- }
- }
- });
- }
- return listView;
- }
-
- /**
- * Non-Android accessor.
- *
- * @return the items that are available to be clicked on
- */
- public CharSequence[] getItems() {
- return items;
- }
-
- public Adapter getAdapter() {
- return adapter;
- }
-
- /**
- * Non-Android accessor.
- *
- * @return the message displayed in the dialog
- */
- public String getMessage() {
- return message;
- }
-
- @Implementation
- public void setMessage(CharSequence message) {
- this.message = (message == null ? null : message.toString());
- }
-
- /**
- * Non-Android accessor.
- *
- * @return an array indicating which items are and are not clicked on a multi-choice dialog
- */
- public boolean[] getCheckedItems() {
- return checkedItems;
- }
-
- /**
- * Non-Android accessor.
- *
- * @return return the index of the checked item clicked on a single-choice dialog
- */
- public int getCheckedItemIndex() {
- return checkedItemIndex;
- }
-
- @Implementation
- public void show() {
- super.show();
- if (items != null) {
- adapter = new ArrayAdapter<CharSequence>(context, R.layout.simple_list_item_checked, R.id.text1, items);
- }
-
- if (adapter != null) {
- getListView().setAdapter(adapter);
- }
-
-
- getShadowApplication().setLatestAlertDialog(this);
- }
-
- /**
- * Non-Android accessor.
- *
- * @return return the view set with {@link ShadowAlertDialog.ShadowBuilder#setView(View)}
- */
- public View getView() {
- return view;
- }
-
- /**
- * Non-Android accessor.
- *
- * @return return the view set with {@link ShadowAlertDialog.ShadowBuilder#setCustomTitle(View)}
- */
- public View getCustomTitleView() {
- return customTitleView;
- }
-
- /**
- * Shadows the {@code android.app.AlertDialog.Builder} class.
- */
- @Implements(AlertDialog.Builder.class)
- public static class ShadowBuilder {
- @RealObject
- private AlertDialog.Builder realBuilder;
-
- private CharSequence[] items;
- private ListAdapter adapter;
- private DialogInterface.OnClickListener clickListener;
- private DialogInterface.OnCancelListener cancelListener;
- private String title;
- private String message;
- private Context context;
- private boolean isMultiItem;
- private DialogInterface.OnMultiChoiceClickListener multiChoiceClickListener;
- private boolean[] checkedItems;
- private CharSequence positiveText;
- private DialogInterface.OnClickListener positiveListener;
- private CharSequence negativeText;
- private DialogInterface.OnClickListener negativeListener;
- private CharSequence neutralText;
- private DialogInterface.OnClickListener neutralListener;
- private boolean isCancelable;
- private boolean isSingleItem;
- private int checkedItem;
- private View view;
- private View customTitleView;
-
- /**
- * just stashes the context for later use
- *
- * @param context the context
- */
- public void __constructor__(Context context) {
- this.context = context;
- }
-
- /**
- * Set a list of items to be displayed in the dialog as the content, you will be notified of the selected item via the supplied listener. This should be
- * an array type i.e. R.array.foo
- *
- * @return This Builder object to allow for chaining of calls to set methods
- */
- @Implementation
- public AlertDialog.Builder setItems(int itemsId, final DialogInterface.OnClickListener listener) {
- this.isMultiItem = false;
-
- this.items = context.getResources().getTextArray(itemsId);
- this.clickListener = listener;
- return realBuilder;
- }
-
- @Implementation(i18nSafe=false)
- public AlertDialog.Builder setItems(CharSequence[] items, final DialogInterface.OnClickListener listener) {
- this.isMultiItem = false;
-
- this.items = items;
- this.clickListener = listener;
- return realBuilder;
- }
-
- @Implementation(i18nSafe=false)
- public AlertDialog.Builder setSingleChoiceItems(CharSequence[] items, int checkedItem, final DialogInterface.OnClickListener listener) {
- this.isSingleItem = true;
- this.checkedItem = checkedItem;
- this.items = items;
- this.clickListener = listener;
- return realBuilder;
- }
-
- @Implementation(i18nSafe=false)
- public AlertDialog.Builder setSingleChoiceItems(ListAdapter adapter, int checkedItem, final DialogInterface.OnClickListener listener) {
- this.isSingleItem = true;
- this.checkedItem = checkedItem;
- this.items = null;
- this.adapter = adapter;
- this.clickListener = listener;
- return realBuilder;
- }
-
- @Implementation(i18nSafe=false)
- public AlertDialog.Builder setMultiChoiceItems(CharSequence[] items, boolean[] checkedItems, final DialogInterface.OnMultiChoiceClickListener listener) {
- this.isMultiItem = true;
-
- this.items = items;
- this.multiChoiceClickListener = listener;
-
- if (checkedItems == null) {
- checkedItems = new boolean[items.length];
- } else if (checkedItems.length != items.length) {
- throw new IllegalArgumentException("checkedItems must be the same length as items, or pass null to specify no checked items");
- }
- this.checkedItems = checkedItems;
-
- return realBuilder;
- }
-
- @Implementation(i18nSafe=false)
- public AlertDialog.Builder setTitle(CharSequence title) {
- this.title = title.toString();
- return realBuilder;
- }
-
-
- @Implementation
- public AlertDialog.Builder setCustomTitle(android.view.View customTitleView) {
- this.customTitleView = customTitleView;
- return realBuilder;
- }
-
- @Implementation
- public AlertDialog.Builder setTitle(int titleId) {
- return setTitle(context.getResources().getString(titleId));
- }
-
- @Implementation(i18nSafe=false)
- public AlertDialog.Builder setMessage(CharSequence message) {
- this.message = message.toString();
- return realBuilder;
- }
-
- @Implementation
- public AlertDialog.Builder setMessage(int messageId) {
- setMessage(context.getResources().getString(messageId));
- return realBuilder;
- }
-
- @Implementation
- public AlertDialog.Builder setIcon(int iconId) {
- return realBuilder;
- }
-
- @Implementation
- public AlertDialog.Builder setView(View view) {
- this.view = view;
- return realBuilder;
- }
-
- @Implementation(i18nSafe=false)
- public AlertDialog.Builder setPositiveButton(CharSequence text, final DialogInterface.OnClickListener listener) {
- this.positiveText = text;
- this.positiveListener = listener;
- return realBuilder;
- }
-
- @Implementation
- public AlertDialog.Builder setPositiveButton(int positiveTextId, final DialogInterface.OnClickListener listener) {
- return setPositiveButton(context.getResources().getText(positiveTextId), listener);
- }
-
- @Implementation(i18nSafe=false)
- public AlertDialog.Builder setNegativeButton(CharSequence text, final DialogInterface.OnClickListener listener) {
- this.negativeText = text;
- this.negativeListener = listener;
- return realBuilder;
- }
-
- @Implementation
- public AlertDialog.Builder setNegativeButton(int negativeTextId, final DialogInterface.OnClickListener listener) {
- return setNegativeButton(context.getResources().getString(negativeTextId), listener);
- }
-
- @Implementation(i18nSafe=false)
- public AlertDialog.Builder setNeutralButton(CharSequence text, final DialogInterface.OnClickListener listener) {
- this.neutralText = text;
- this.neutralListener = listener;
- return realBuilder;
- }
-
- @Implementation
- public AlertDialog.Builder setNeutralButton(int neutralTextId, final DialogInterface.OnClickListener listener) {
- return setNeutralButton(context.getResources().getText(neutralTextId), listener);
- }
-
-
- @Implementation
- public AlertDialog.Builder setCancelable(boolean cancelable) {
- this.isCancelable = cancelable;
- return realBuilder;
- }
-
- @Implementation
- public AlertDialog.Builder setOnCancelListener(DialogInterface.OnCancelListener listener) {
- this.cancelListener = listener;
- return realBuilder;
- }
-
- @Implementation
- public AlertDialog create() {
- AlertDialog realDialog;
- try {
- Constructor<AlertDialog> c = AlertDialog.class.getDeclaredConstructor(Context.class);
- c.setAccessible(true);
- realDialog = c.newInstance((Context) null);
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
-
- ShadowAlertDialog latestAlertDialog = shadowOf(realDialog);
- latestAlertDialog.context = context;
- latestAlertDialog.items = items;
- latestAlertDialog.adapter = adapter;
- latestAlertDialog.setTitle(title);
- latestAlertDialog.message = message;
- latestAlertDialog.clickListener = clickListener;
- latestAlertDialog.setOnCancelListener(cancelListener);
- latestAlertDialog.isMultiItem = isMultiItem;
- latestAlertDialog.isSingleItem = isSingleItem;
- latestAlertDialog.checkedItemIndex = checkedItem;
- latestAlertDialog.multiChoiceClickListener = multiChoiceClickListener;
- latestAlertDialog.checkedItems = checkedItems;
- latestAlertDialog.setView(view);
- latestAlertDialog.positiveButton = createButton(context, realDialog, AlertDialog.BUTTON_POSITIVE, positiveText, positiveListener);
- latestAlertDialog.negativeButton = createButton(context, realDialog, AlertDialog.BUTTON_NEGATIVE, negativeText, negativeListener);
- latestAlertDialog.neutralButton = createButton(context, realDialog, AlertDialog.BUTTON_NEUTRAL, neutralText, neutralListener);
- latestAlertDialog.setCancelable(isCancelable);
- latestAlertDialog.customTitleView = customTitleView;
- return realDialog;
- }
-
- @Implementation
- public AlertDialog show() {
- AlertDialog dialog = realBuilder.create();
- dialog.show();
- return dialog;
- }
-
- @Implementation
- public Context getContext() {
- return context;
- }
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowAlphaAnimation.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowAlphaAnimation.java
deleted file mode 100644
index d3648f1d2..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowAlphaAnimation.java
+++ /dev/null
@@ -1,24 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.view.animation.AlphaAnimation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-@SuppressWarnings({"UnusedDeclaration"})
-@Implements(AlphaAnimation.class)
-public class ShadowAlphaAnimation extends ShadowAnimation {
- private float fromAlpha;
- private float toAlpha;
-
- public void __constructor__(float fromAlpha, float toAlpha) {
- this.fromAlpha = fromAlpha;
- this.toAlpha = toAlpha;
- }
-
- public float getFromAlpha() {
- return fromAlpha;
- }
-
- public float getToAlpha() {
- return toAlpha;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowAndroidHttpClient.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowAndroidHttpClient.java
deleted file mode 100644
index 184896ab3..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowAndroidHttpClient.java
+++ /dev/null
@@ -1,89 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.internal.RealObject;
-import org.apache.http.HttpHost;
-import org.apache.http.HttpRequest;
-import org.apache.http.HttpResponse;
-import org.apache.http.client.ClientProtocolException;
-import org.apache.http.client.HttpClient;
-import org.apache.http.client.ResponseHandler;
-import org.apache.http.client.methods.HttpUriRequest;
-import org.apache.http.conn.ClientConnectionManager;
-import org.apache.http.impl.client.DefaultHttpClient;
-import org.apache.http.params.HttpParams;
-import org.apache.http.protocol.HttpContext;
-
-import android.content.Context;
-import android.net.http.AndroidHttpClient;
-
-import java.io.IOException;
-
-@Implements(AndroidHttpClient.class)
-public class ShadowAndroidHttpClient {
- @RealObject private AndroidHttpClient client;
-
- private HttpClient httpClient = new DefaultHttpClient();
-
- @Implementation
- public static AndroidHttpClient newInstance(String userAgent) {
- return Robolectric.newInstanceOf(AndroidHttpClient.class);
- }
-
- @Implementation
- public static AndroidHttpClient newInstance(String userAgent, Context context) {
- return Robolectric.newInstanceOf(AndroidHttpClient.class);
- }
-
- @Implementation
- public HttpParams getParams() {
- return httpClient.getParams();
- }
-
- @Implementation
- public ClientConnectionManager getConnectionManager() {
- return httpClient.getConnectionManager();
- }
-
- @Implementation
- public HttpResponse execute(HttpUriRequest httpUriRequest) throws IOException, ClientProtocolException {
- return httpClient.execute(httpUriRequest);
- }
-
- @Implementation
- public HttpResponse execute(HttpUriRequest httpUriRequest, HttpContext httpContext) throws IOException, ClientProtocolException {
- return httpClient.execute(httpUriRequest, httpContext);
- }
-
- @Implementation
- public HttpResponse execute(HttpHost httpHost, HttpRequest httpRequest) throws IOException, ClientProtocolException {
- return httpClient.execute(httpHost, httpRequest);
- }
-
- @Implementation
- public HttpResponse execute(HttpHost httpHost, HttpRequest httpRequest, HttpContext httpContext) throws IOException, ClientProtocolException {
- return httpClient.execute(httpHost, httpRequest, httpContext);
- }
-
- @Implementation
- public <T> T execute(HttpUriRequest httpUriRequest, ResponseHandler<? extends T> responseHandler) throws IOException, ClientProtocolException {
- return httpClient.execute(httpUriRequest, responseHandler);
- }
-
- @Implementation
- public <T> T execute(HttpUriRequest httpUriRequest, ResponseHandler<? extends T> responseHandler, HttpContext httpContext) throws IOException, ClientProtocolException {
- return httpClient.execute(httpUriRequest, responseHandler, httpContext);
- }
-
- @Implementation
- public <T> T execute(HttpHost httpHost, HttpRequest httpRequest, ResponseHandler<? extends T> responseHandler) throws IOException, ClientProtocolException {
- return httpClient.execute(httpHost, httpRequest, responseHandler);
- }
-
- @Implementation
- public <T> T execute(HttpHost httpHost, HttpRequest httpRequest, ResponseHandler<? extends T> responseHandler, HttpContext httpContext) throws IOException, ClientProtocolException {
- return httpClient.execute(httpHost, httpRequest, responseHandler, httpContext);
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowAnimation.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowAnimation.java
deleted file mode 100644
index ac4f045c7..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowAnimation.java
+++ /dev/null
@@ -1,156 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.view.animation.Animation;
-import android.view.animation.Interpolator;
-import android.view.animation.ShadowAnimationBridge;
-import android.view.animation.Transformation;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.internal.RealObject;
-
-/**
- * Shadow implementation of {@code Animation} that provides support for invoking listener callbacks.
- */
-@SuppressWarnings({"UnusedDeclaration"})
-@Implements(Animation.class)
-public class ShadowAnimation {
-
- private Animation.AnimationListener listener;
- private Interpolator interpolator;
- private boolean startFlag = false;
- private long durationMillis = 0;
- private int repeatCount;
- private int repeatMode;
- private long startOffset;
- private int loadedFromResourceId = -1;
- private boolean fillAfter;
-
- @RealObject
- private Animation realAnimation;
-
- @Implementation
- public void setAnimationListener(Animation.AnimationListener l) {
- listener = l;
- }
-
- @Implementation
- public void start() {
- startFlag = true;
- if (listener != null) {
- listener.onAnimationStart(realAnimation);
- }
- }
-
- @Implementation
- public void cancel() {
- startFlag = false;
- if (listener != null) {
- listener.onAnimationEnd(realAnimation);
- }
- }
-
- @Implementation
- public boolean hasStarted() {
- return startFlag;
- }
-
- @Implementation
- public void setDuration(long durationMillis) {
- this.durationMillis = durationMillis;
- }
-
- @Implementation
- public long getDuration() {
- return durationMillis;
- }
-
- @Implementation
- public void setInterpolator(Interpolator interpolator) {
- this.interpolator = interpolator;
- }
-
- @Implementation
- public Interpolator getInterpolator() {
- return interpolator;
- }
-
- @Implementation
- public void setRepeatCount(int repeatCount) {
- this.repeatCount = repeatCount;
- }
-
- @Implementation
- public int getRepeatCount() {
- return repeatCount;
- }
-
- @Implementation
- public void setRepeatMode(int repeatMode) {
- this.repeatMode = repeatMode;
- }
-
- @Implementation
- public int getRepeatMode() {
- return repeatMode;
- }
-
- @Implementation
- public void setStartOffset(long startOffset) {
- this.startOffset = startOffset;
- }
-
- @Implementation
- public long getStartOffset() {
- return startOffset;
- }
-
- @Implementation
- public void setFillAfter(boolean fillAfter) {
- this.fillAfter = fillAfter;
- }
-
- @Implementation
- public boolean getFillAfter() {
- return fillAfter;
- }
-
- /**
- * Non-Android accessor. Returns most recently set animation listener.
- *
- * @return
- */
- public Animation.AnimationListener getAnimationListener() {
- return listener;
- }
-
- /**
- * Non-Android accessor. Use to simulate repeat loops of animation.
- */
- public void invokeRepeat() {
- if (listener != null) {
- listener.onAnimationRepeat(realAnimation);
- }
- }
-
- /**
- * Non-Android accessor. Use to simulate end of animation.
- */
- public void invokeEnd() {
- if (listener != null) {
- listener.onAnimationEnd(realAnimation);
- }
- new ShadowAnimationBridge(realAnimation).applyTransformation(1.0f, new Transformation());
- }
-
- public void setLoadedFromResourceId(int loadedFromResourceId) {
- this.loadedFromResourceId = loadedFromResourceId;
- }
-
- public int getLoadedFromResourceId() {
- if (loadedFromResourceId == -1) {
- throw new IllegalStateException("not loaded from a resource");
- }
- return loadedFromResourceId;
- }
-
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowAnimationDrawable.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowAnimationDrawable.java
deleted file mode 100644
index 9697c0cb7..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowAnimationDrawable.java
+++ /dev/null
@@ -1,39 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.graphics.drawable.AnimationDrawable;
-import android.graphics.drawable.Drawable;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-import java.util.ArrayList;
-import java.util.List;
-
-@Implements(AnimationDrawable.class)
-public class ShadowAnimationDrawable extends ShadowDrawable {
-
- private List<Drawable> frames = new ArrayList<Drawable>();
- private boolean isStarted;
-
- @Implementation
- public void addFrame(Drawable frame, int duration) {
- frames.add(frame);
- }
-
- @Implementation
- public int getNumberOfFrames() {
- return frames.size();
- }
-
- @Implementation
- public void start() {
- isStarted = true;
- }
-
- public boolean isStarted() {
- return isStarted;
- }
-
- public List<Drawable> getFrames() {
- return frames;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowAnimationSet.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowAnimationSet.java
deleted file mode 100644
index 5160bf8eb..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowAnimationSet.java
+++ /dev/null
@@ -1,30 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import android.view.animation.Animation;
-import android.view.animation.AnimationSet;
-
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.internal.RealObject;
-
-@Implements(AnimationSet.class)
-public class ShadowAnimationSet extends ShadowAnimation {
- private ArrayList<Animation> animationList = new ArrayList<Animation>();
-
- @RealObject
- private AnimationSet realAnimationSet;
-
-
- @Implementation
- public void addAnimation(Animation anim) {
- animationList.add(anim);
- }
-
- @Implementation
- public List<Animation> getAnimations() {
- return animationList;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowAnimationUtils.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowAnimationUtils.java
deleted file mode 100644
index 3e880857b..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowAnimationUtils.java
+++ /dev/null
@@ -1,22 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.content.Context;
-import android.view.animation.Animation;
-import android.view.animation.AnimationUtils;
-import android.view.animation.TranslateAnimation;
-
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-@SuppressWarnings( { "UnusedDeclaration" })
-@Implements(AnimationUtils.class)
-public class ShadowAnimationUtils {
-
- @Implementation
- public static Animation loadAnimation(Context context, int id) {
- Animation anim = new TranslateAnimation(0, 0, 30, 0);
- Robolectric.shadowOf(anim).setLoadedFromResourceId(id);
- return anim;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowAppWidgetManager.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowAppWidgetManager.java
deleted file mode 100644
index e7e49a46a..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowAppWidgetManager.java
+++ /dev/null
@@ -1,225 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.app.Activity;
-import android.app.Application;
-import android.appwidget.AppWidgetManager;
-import android.appwidget.AppWidgetProvider;
-import android.content.ComponentName;
-import android.content.Context;
-import android.view.View;
-import android.widget.RemoteViews;
-import com.xtremelabs.robolectric.internal.AppSingletonizer;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.internal.RealObject;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import static com.xtremelabs.robolectric.Robolectric.newInstanceOf;
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-
-@SuppressWarnings({"UnusedDeclaration"})
-@Implements(AppWidgetManager.class)
-public class ShadowAppWidgetManager {
- private static AppSingletonizer<AppWidgetManager> instances = new AppSingletonizer<AppWidgetManager>(AppWidgetManager.class) {
- @Override
- protected AppWidgetManager get(ShadowApplication shadowApplication) {
- return shadowApplication.appWidgetManager;
- }
-
- @Override
- protected void set(ShadowApplication shadowApplication, AppWidgetManager instance) {
- shadowApplication.appWidgetManager = instance;
- }
-
- @Override
- protected AppWidgetManager createInstance(Application applicationContext) {
- AppWidgetManager appWidgetManager = super.createInstance(applicationContext);
- shadowOf(appWidgetManager).context = applicationContext;
- return appWidgetManager;
- }
- };
-
- @RealObject
- private AppWidgetManager realAppWidgetManager;
-
- private Context context;
- private Map<Integer, WidgetInfo> widgetInfos = new HashMap<Integer, WidgetInfo>();
- private int nextWidgetId = 1;
- private boolean alwaysRecreateViewsDuringUpdate = false;
-
- private static void bind(AppWidgetManager appWidgetManager, Context context) {
- // todo: implement
- }
-
-
- /**
- * Finds or creates an {@code AppWidgetManager} for the given {@code context}
- *
- * @param context the {@code context} for which to produce an assoicated {@code AppWidgetManager}
- * @return the {@code AppWidgetManager} associated with the given {@code context}
- */
- @Implementation
- public static AppWidgetManager getInstance(Context context) {
- return instances.getInstance(context);
- }
-
- @Implementation
- public void updateAppWidget(int[] appWidgetIds, RemoteViews views) {
- for (int appWidgetId : appWidgetIds) {
- updateAppWidget(appWidgetId, views);
- }
- }
-
- /**
- * Simulates updating an {@code AppWidget} with a new set of views
- *
- * @param appWidgetId id of widget
- * @param views views to update
- */
- @Implementation
- public void updateAppWidget(int appWidgetId, RemoteViews views) {
- WidgetInfo widgetInfo = getWidgetInfo(appWidgetId);
- int layoutId = views.getLayoutId();
- if (widgetInfo.layoutId != layoutId || alwaysRecreateViewsDuringUpdate) {
- widgetInfo.view = createWidgetView(layoutId);
- widgetInfo.layoutId = layoutId;
- }
- widgetInfo.lastRemoteViews = views;
- views.reapply(context, widgetInfo.view);
- }
-
- @Implementation
- public int[] getAppWidgetIds(ComponentName provider) {
- List<Integer> idList = new ArrayList<Integer>();
- for (int id : widgetInfos.keySet()) {
- WidgetInfo widgetInfo = widgetInfos.get(id);
- String widgetClass = widgetInfo.appWidgetProvider.getClass().getName();
- String widgetPackage = widgetInfo.appWidgetProvider.getClass().getPackage().getName();
- if (provider.getClassName().equals(widgetClass) && provider.getPackageName().equals(widgetPackage)) {
- idList.add(id);
- }
- }
- int ids[] = new int[idList.size()];
- for (int i = 0; i < idList.size(); i++) {
- ids[i] = idList.get(i);
- }
- return ids;
- }
-
- /**
- * Triggers a reapplication of the most recent set of actions against the widget, which is what happens when the
- * phone is rotated. Does not attempt to simulate a change in screen geometry.
- *
- * @param appWidgetId the ID of the widget to be affected
- */
- public void reconstructWidgetViewAsIfPhoneWasRotated(int appWidgetId) {
- WidgetInfo widgetInfo = getWidgetInfo(appWidgetId);
- widgetInfo.view = createWidgetView(widgetInfo.layoutId);
- widgetInfo.lastRemoteViews.reapply(context, widgetInfo.view);
- }
-
- /**
- * Creates a widget by inflating its layout.
- *
- * @param appWidgetProviderClass the app widget provider class
- * @param widgetLayoutId id of the layout to inflate
- * @return the ID of the new widget
- */
- public int createWidget(Class<? extends AppWidgetProvider> appWidgetProviderClass, int widgetLayoutId) {
- return createWidgets(appWidgetProviderClass, widgetLayoutId, 1)[0];
- }
-
- /**
- * Creates a bunch of widgets by inflating the same layout multiple times.
- *
- * @param appWidgetProviderClass the app widget provider class
- * @param widgetLayoutId id of the layout to inflate
- * @param howManyToCreate number of new widgets to create
- * @return the IDs of the new widgets
- */
- public int[] createWidgets(Class<? extends AppWidgetProvider> appWidgetProviderClass, int widgetLayoutId, int howManyToCreate) {
- AppWidgetProvider appWidgetProvider = newInstanceOf(appWidgetProviderClass);
-
- int[] newWidgetIds = new int[howManyToCreate];
- for (int i = 0; i < howManyToCreate; i++) {
- View widgetView = createWidgetView(widgetLayoutId);
-
- int myWidgetId = nextWidgetId++;
- widgetInfos.put(myWidgetId, new WidgetInfo(widgetView, widgetLayoutId, appWidgetProvider));
- newWidgetIds[i] = myWidgetId;
- }
-
- appWidgetProvider.onUpdate(context, realAppWidgetManager, newWidgetIds);
- return newWidgetIds;
- }
-
- private void createWidgetProvider(Class<? extends AppWidgetProvider> appWidgetProviderClass, int... newWidgetIds) {
- AppWidgetProvider appWidgetProvider = newInstanceOf(appWidgetProviderClass);
- appWidgetProvider.onUpdate(context, realAppWidgetManager, newWidgetIds);
- }
-
- private View createWidgetView(int widgetLayoutId) {
- return new Activity().getLayoutInflater().inflate(widgetLayoutId, null);
- }
-
- /**
- * Non-Android accessor.
- *
- * @param widgetId id of the desired widget
- * @return the widget associated with {@code widgetId}
- */
- public View getViewFor(int widgetId) {
- return getWidgetInfo(widgetId).view;
- }
-
- /**
- * Non-Android accessor.
- *
- * @param widgetId id of the widget whose provider is to be returned
- * @return the {@code AppWidgetProvider} associated with {@code widgetId}
- */
- public AppWidgetProvider getAppWidgetProviderFor(int widgetId) {
- return getWidgetInfo(widgetId).appWidgetProvider;
- }
-
- /**
- * Non-Android mechanism that enables testing of widget behavior when all of the views are recreated on every
- * update. This is useful for ensuring that your widget will behave correctly even if it is restarted by the OS
- * between events.
- *
- * @param alwaysRecreate whether or not to always recreate the views
- */
- public void setAlwaysRecreateViewsDuringUpdate(boolean alwaysRecreate) {
- alwaysRecreateViewsDuringUpdate = alwaysRecreate;
- }
-
- /**
- * Non-Android accessor.
- *
- * @return the state of the{@code alwaysRecreateViewsDuringUpdate} flag
- */
- public boolean getAlwaysRecreateViewsDuringUpdate() {
- return alwaysRecreateViewsDuringUpdate;
- }
-
- private WidgetInfo getWidgetInfo(int widgetId) {
- return widgetInfos.get(widgetId);
- }
-
- private class WidgetInfo {
- private View view;
- private int layoutId;
- private AppWidgetProvider appWidgetProvider;
- private RemoteViews lastRemoteViews;
-
- public WidgetInfo(View view, int layoutId, AppWidgetProvider appWidgetProvider) {
- this.view = view;
- this.layoutId = layoutId;
- this.appWidgetProvider = appWidgetProvider;
- }
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowApplication.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowApplication.java
deleted file mode 100644
index 1b1aa8e7d..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowApplication.java
+++ /dev/null
@@ -1,543 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.app.Application;
-import android.appwidget.AppWidgetManager;
-import android.content.BroadcastReceiver;
-import android.content.ComponentName;
-import android.content.ContentResolver;
-import android.content.Context;
-import android.content.Intent;
-import android.content.IntentFilter;
-import android.content.ServiceConnection;
-import android.content.res.Resources;
-import android.os.IBinder;
-import android.os.Looper;
-import android.view.LayoutInflater;
-import android.widget.Toast;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.internal.RealObject;
-import com.xtremelabs.robolectric.res.ResourceLoader;
-import com.xtremelabs.robolectric.tester.org.apache.http.FakeHttpLayer;
-import com.xtremelabs.robolectric.util.Scheduler;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-import static com.xtremelabs.robolectric.Robolectric.newInstanceOf;
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-
-/**
- * Shadows the {@code android.app.Application} class.
- */
-@SuppressWarnings({"UnusedDeclaration"})
-@Implements(Application.class)
-public class ShadowApplication extends ShadowContextWrapper {
- private static final Map<String, String> SYSTEM_SERVICE_MAP = new HashMap<String, String>();
-
- static {
- // note that these are different!
- // They specify concrete classes within Robolectric for interfaces or abstract classes defined by Android
- SYSTEM_SERVICE_MAP.put(Context.WINDOW_SERVICE, "com.xtremelabs.robolectric.tester.android.view.TestWindowManager");
- SYSTEM_SERVICE_MAP.put(Context.CLIPBOARD_SERVICE, "com.xtremelabs.robolectric.tester.android.text.TestClipboardManager");
- SYSTEM_SERVICE_MAP.put(Context.SENSOR_SERVICE, "android.hardware.TestSensorManager");
- SYSTEM_SERVICE_MAP.put(Context.VIBRATOR_SERVICE, "android.os.TestVibrator");
-
- // the rest are as mapped in docs...
- SYSTEM_SERVICE_MAP.put(Context.LAYOUT_INFLATER_SERVICE, "android.view.LayoutInflater");
- SYSTEM_SERVICE_MAP.put(Context.ACTIVITY_SERVICE, "android.app.ActivityManager");
- SYSTEM_SERVICE_MAP.put(Context.POWER_SERVICE, "android.os.PowerManager");
- SYSTEM_SERVICE_MAP.put(Context.ALARM_SERVICE, "android.app.AlarmManager");
- SYSTEM_SERVICE_MAP.put(Context.NOTIFICATION_SERVICE, "android.app.NotificationManager");
- SYSTEM_SERVICE_MAP.put(Context.KEYGUARD_SERVICE, "android.app.KeyguardManager");
- SYSTEM_SERVICE_MAP.put(Context.LOCATION_SERVICE, "android.location.LocationManager");
- SYSTEM_SERVICE_MAP.put(Context.SEARCH_SERVICE, "android.app.SearchManager");
- SYSTEM_SERVICE_MAP.put(Context.STORAGE_SERVICE, "android.os.storage.StorageManager");
- SYSTEM_SERVICE_MAP.put(Context.CONNECTIVITY_SERVICE, "android.net.ConnectivityManager");
- SYSTEM_SERVICE_MAP.put(Context.WIFI_SERVICE, "android.net.wifi.WifiManager");
- SYSTEM_SERVICE_MAP.put(Context.AUDIO_SERVICE, "android.media.AudioManager");
- SYSTEM_SERVICE_MAP.put(Context.TELEPHONY_SERVICE, "android.telephony.TelephonyManager");
- SYSTEM_SERVICE_MAP.put(Context.INPUT_METHOD_SERVICE, "android.view.inputmethod.InputMethodManager");
- SYSTEM_SERVICE_MAP.put(Context.UI_MODE_SERVICE, "android.app.UiModeManager");
- SYSTEM_SERVICE_MAP.put(Context.DOWNLOAD_SERVICE, "android.app.DownloadManager");
- }
-
- @RealObject private Application realApplication;
-
- private ResourceLoader resourceLoader;
- private ContentResolver contentResolver;
- private Map<String, Object> systemServices = new HashMap<String, Object>();
- private List<Intent> startedActivities = new ArrayList<Intent>();
- private List<Intent> startedServices = new ArrayList<Intent>();
- private List<Intent> stoppedServies = new ArrayList<Intent>();
- private List<Intent> broadcastIntents = new ArrayList<Intent>();
- private List<ServiceConnection> unboundServiceConnections = new ArrayList<ServiceConnection>();
- private List<Wrapper> registeredReceivers = new ArrayList<Wrapper>();
- private Map<String, Intent> stickyIntents = new HashMap<String, Intent>();
- private FakeHttpLayer fakeHttpLayer = new FakeHttpLayer();
- private Looper mainLooper = ShadowLooper.myLooper();
- private Scheduler backgroundScheduler = new Scheduler();
- private Map<String, Map<String, Object>> sharedPreferenceMap = new HashMap<String, Map<String, Object>>();
- private ArrayList<Toast> shownToasts = new ArrayList<Toast>();
- private ShadowAlertDialog latestAlertDialog;
- private ShadowDialog latestDialog;
- private Object bluetoothAdapter = Robolectric.newInstanceOf("android.bluetooth.BluetoothAdapter");
- private Resources resources;
-
- // these are managed by the AppSingletonizier... kinda gross, sorry [xw]
- LayoutInflater layoutInflater;
- AppWidgetManager appWidgetManager;
- private ServiceConnection serviceConnection;
- private ComponentName componentNameForBindService;
- private IBinder serviceForBindService;
- private List<String> unbindableActions = new ArrayList<String>();
-
- /**
- * Associates a {@code ResourceLoader} with an {@code Application} instance
- *
- * @param application application
- * @param resourceLoader resource loader
- * @return the application
- * todo: make this non-static?
- */
- public static Application bind(Application application, ResourceLoader resourceLoader) {
- ShadowApplication shadowApplication = shadowOf(application);
- if (shadowApplication.resourceLoader != null) throw new RuntimeException("ResourceLoader already set!");
- shadowApplication.resourceLoader = resourceLoader;
- shadowApplication.resources = ShadowResources.bind(new Resources(null, null, null), resourceLoader);
- return application;
- }
-
- public List<Toast> getShownToasts() {
- return shownToasts;
- }
-
- public Scheduler getBackgroundScheduler() {
- return backgroundScheduler;
- }
-
- @Override
- @Implementation
- public Context getApplicationContext() {
- return realApplication;
- }
-
- @Override
- @Implementation
- public Resources getResources() {
- if (resources == null ) {
- resources = ShadowResources.bind(new Resources(null, null, null), resourceLoader);
- }
- return resources;
- }
-
- @Implementation
- @Override
- public ContentResolver getContentResolver() {
- if (contentResolver == null) {
- contentResolver = new ContentResolver(realApplication) {
- };
- }
- return contentResolver;
- }
-
- @Implementation
- @Override
- public Object getSystemService(String name) {
- if (name.equals(Context.LAYOUT_INFLATER_SERVICE)) {
- return LayoutInflater.from(realApplication);
- } else {
- Object service = systemServices.get(name);
- if (service == null) {
- String serviceClassName = SYSTEM_SERVICE_MAP.get(name);
- if (serviceClassName != null) {
- try {
- service = newInstanceOf(Class.forName(serviceClassName));
- } catch (ClassNotFoundException e) {
- throw new RuntimeException(e);
- }
- systemServices.put(name, service);
- }
- }
- return service;
- }
- }
-
- @Implementation
- @Override
- public void startActivity(Intent intent) {
- startedActivities.add(intent);
- }
-
- @Implementation
- @Override
- public ComponentName startService(Intent intent) {
- startedServices.add(intent);
- return new ComponentName("some.service.package", "SomeServiceName-FIXME");
- }
-
- @Implementation
- @Override
- public boolean stopService(Intent name) {
- stoppedServies.add(name);
-
- return startedServices.contains(name);
- }
-
- public void setComponentNameAndServiceForBindService(ComponentName name, IBinder service) {
- this.componentNameForBindService = name;
- this.serviceForBindService = service;
- }
-
- @Implementation
- public boolean bindService(Intent intent, final ServiceConnection serviceConnection, int i) {
- if (unbindableActions.contains(intent.getAction())) {
- return false;
- }
- startedServices.add(intent);
- shadowOf(Looper.getMainLooper()).post(new Runnable() {
- @Override
- public void run() {
- serviceConnection.onServiceConnected(componentNameForBindService, serviceForBindService);
- }
- }, 0);
- return true;
- }
-
- @Implementation
- public void unbindService(final ServiceConnection serviceConnection) {
- unboundServiceConnections.add(serviceConnection);
- shadowOf(Looper.getMainLooper()).post(new Runnable() {
- @Override
- public void run() {
- serviceConnection.onServiceDisconnected(componentNameForBindService);
- }
- }, 0);
- }
-
- public List<ServiceConnection> getUnboundServiceConnections() {
- return unboundServiceConnections;
- }
- /**
- * Consumes the most recent {@code Intent} started by {@link #startActivity(android.content.Intent)} and returns it.
- *
- * @return the most recently started {@code Intent}
- */
- @Override
- public Intent getNextStartedActivity() {
- if (startedActivities.isEmpty()) {
- return null;
- } else {
- return startedActivities.remove(0);
- }
- }
-
- /**
- * Returns the most recent {@code Intent} started by {@link #startActivity(android.content.Intent)} without
- * consuming it.
- *
- * @return the most recently started {@code Intent}
- */
- @Override
- public Intent peekNextStartedActivity() {
- if (startedActivities.isEmpty()) {
- return null;
- } else {
- return startedActivities.get(0);
- }
- }
-
- /**
- * Consumes the most recent {@code Intent} started by {@link #startService(android.content.Intent)} and returns it.
- *
- * @return the most recently started {@code Intent}
- */
- @Override
- public Intent getNextStartedService() {
- if (startedServices.isEmpty()) {
- return null;
- } else {
- return startedServices.remove(0);
- }
- }
-
- /**
- * Returns the most recent {@code Intent} started by {@link #startService(android.content.Intent)} without
- * consuming it.
- *
- * @return the most recently started {@code Intent}
- */
- @Override
- public Intent peekNextStartedService() {
- if (startedServices.isEmpty()) {
- return null;
- } else {
- return startedServices.get(0);
- }
- }
-
- /**
- * Clears all {@code Intent} started by {@link #startService(android.content.Intent)}
- */
- @Override
- public void clearStartedServices() {
- startedServices.clear();
- }
-
- /**
- * Consumes the {@code Intent} requested to stop a service by {@link #stopService(android.content.Intent)}
- * from the bottom of the stack of stop requests.
- */
- @Override
- public Intent getNextStoppedService() {
- if (stoppedServies.isEmpty()) {
- return null;
- } else {
- return stoppedServies.remove(0);
- }
- }
-
- /**
- * Non-Android accessor (and a handy way to get a working {@code ResourceLoader}
- *
- * @return the {@code ResourceLoader} associated with this Application
- */
- public ResourceLoader getResourceLoader() {
- return resourceLoader;
- }
-
- /**
- * Broadcasts the {@code Intent} by iterating through the registered receivers, invoking their filters, and calling
- * {@code onRecieve(Application, Intent)} as appropriate. Does not enqueue the {@code Intent} for later inspection.
- *
- * @param intent the {@code Intent} to broadcast
- * todo: enqueue the Intent for later inspection
- */
- @Override
- @Implementation
- public void sendBroadcast(Intent intent) {
- broadcastIntents.add(intent);
-
- List<Wrapper> copy = new ArrayList<Wrapper>();
- copy.addAll(registeredReceivers);
- for (Wrapper wrapper : copy) {
- if (wrapper.intentFilter.matchAction(intent.getAction())) {
- wrapper.broadcastReceiver.onReceive(realApplication, intent);
- }
- }
- }
-
- public List<Intent> getBroadcastIntents() {
- return broadcastIntents;
- }
-
- @Implementation
- public void sendStickyBroadcast(Intent intent) {
- stickyIntents.put(intent.getAction(), intent);
- sendBroadcast(intent);
- }
-
- /**
- * Always returns {@code null}
- *
- * @return {@code null}
- */
- @Override
- @Implementation
- public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter) {
- return registerReceiverWithContext(receiver, filter, realApplication);
- }
-
- Intent registerReceiverWithContext(BroadcastReceiver receiver, IntentFilter filter, Context context) {
- if (receiver != null) {
- registeredReceivers.add(new Wrapper(receiver, filter, context));
- }
- return getStickyIntent(filter);
- }
-
- private Intent getStickyIntent(IntentFilter filter) {
- for (Intent stickyIntent : stickyIntents.values()) {
- String action = null;
- for (int i = 0; i < filter.countActions(); i++) {
- action = filter.getAction(i);
- if (stickyIntent.getAction().equals(action)) {
- return stickyIntent;
- }
- }
- }
-
- return null;
- }
-
- @Override
- @Implementation
- public void unregisterReceiver(BroadcastReceiver broadcastReceiver) {
- boolean found = false;
- Iterator<Wrapper> iterator = registeredReceivers.iterator();
- while (iterator.hasNext()) {
- Wrapper wrapper = iterator.next();
- if (wrapper.broadcastReceiver == broadcastReceiver) {
- iterator.remove();
- found = true;
- }
- }
- if (!found) {
- throw new IllegalArgumentException("Receiver not registered: " + broadcastReceiver);
- }
- }
-
- /**
- * Iterates through all of the registered receivers on this {@code Application} and if any of them match the given
- * {@code Context} object throws a {@code RuntimeException}
- *
- * @param context the {@code Context} to check for on each of the remaining registered receivers
- * @param type the type to report for the context if an exception is thrown
- * @throws RuntimeException if there are any recievers registered with the given {@code Context}
- */
- public void assertNoBroadcastListenersRegistered(Context context, String type) {
- for (Wrapper registeredReceiver : registeredReceivers) {
- if (registeredReceiver.context == context) {
- RuntimeException e = new IllegalStateException(type + " " + context + " leaked has leaked IntentReceiver "
- + registeredReceiver.broadcastReceiver + " that was originally registered here. " +
- "Are you missing a call to unregisterReceiver()?");
- e.setStackTrace(registeredReceiver.exception.getStackTrace());
- throw e;
- }
- }
- }
-
- public void assertNoBroadcastListenersOfActionRegistered(Context context, String action) {
- for (Wrapper registeredReceiver : registeredReceivers) {
- if (registeredReceiver.context == context) {
- Iterator<String> actions = registeredReceiver.intentFilter.actionsIterator();
- while (actions.hasNext()) {
- if (actions.next().equals(action)) {
- RuntimeException e = new IllegalStateException("Unexpected BroadcastReceiver on " + context +
- " with action " + action + " "
- + registeredReceiver.broadcastReceiver + " that was originally registered here:");
- e.setStackTrace(registeredReceiver.exception.getStackTrace());
- throw e;
- }
- }
- }
- }
- }
-
- public boolean hasReceiverForIntent(Intent intent) {
- for (Wrapper wrapper : registeredReceivers) {
- if (wrapper.intentFilter.matchAction(intent.getAction())) {
- return true;
- }
- }
- return false;
- }
-
- public List<BroadcastReceiver> getReceiversForIntent(Intent intent) {
- ArrayList<BroadcastReceiver> broadcastReceivers = new ArrayList<BroadcastReceiver>();
- for (Wrapper wrapper : registeredReceivers) {
- if (wrapper.intentFilter.matchAction(intent.getAction())) {
- broadcastReceivers.add(wrapper.getBroadcastReceiver());
- }
- }
- return broadcastReceivers;
- }
-
- /**
- * Non-Android accessor.
- *
- * @return list of {@link Wrapper}s for registered receivers
- */
- public List<Wrapper> getRegisteredReceivers() {
- return registeredReceivers;
- }
-
- /**
- * Non-Android accessor.
- *
- * @return the layout inflater used by this {@code Application}
- */
- public LayoutInflater getLayoutInflater() {
- return layoutInflater;
- }
-
- /**
- * Non-Android accessor.
- *
- * @return the app widget manager used by this {@code Application}
- */
- public AppWidgetManager getAppWidgetManager() {
- return appWidgetManager;
- }
-
- public FakeHttpLayer getFakeHttpLayer() {
- return fakeHttpLayer;
- }
-
- @Override
- @Implementation
- public Looper getMainLooper() {
- return mainLooper;
- }
-
- public Map<String, Map<String, Object>> getSharedPreferenceMap() {
- return sharedPreferenceMap;
- }
-
- public ShadowAlertDialog getLatestAlertDialog() {
- return latestAlertDialog;
- }
-
- public void setLatestAlertDialog(ShadowAlertDialog latestAlertDialog) {
- this.latestAlertDialog = latestAlertDialog;
- }
-
- public ShadowDialog getLatestDialog() {
- return latestDialog;
- }
-
- public void setLatestDialog(ShadowDialog latestDialog) {
- this.latestDialog = latestDialog;
- }
-
- public Object getBluetoothAdapter() {
- return bluetoothAdapter;
- }
-
- public void declareActionUnbindable(String action) {
- unbindableActions.add(action);
- }
-
- public void setSystemService(String key, Object service) {
- systemServices.put(key, service);
- }
-
- public class Wrapper {
- public BroadcastReceiver broadcastReceiver;
- public IntentFilter intentFilter;
- public Context context;
- public Throwable exception;
-
- public Wrapper(BroadcastReceiver broadcastReceiver, IntentFilter intentFilter, Context context) {
- this.broadcastReceiver = broadcastReceiver;
- this.intentFilter = intentFilter;
- this.context = context;
- exception = new Throwable();
- }
-
- public BroadcastReceiver getBroadcastReceiver() {
- return broadcastReceiver;
- }
-
- public IntentFilter getIntentFilter() {
- return intentFilter;
- }
-
- public Context getContext() {
- return context;
- }
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowArrayAdapter.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowArrayAdapter.java
deleted file mode 100644
index 7990df4b0..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowArrayAdapter.java
+++ /dev/null
@@ -1,182 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.content.Context;
-import android.view.View;
-import android.view.ViewGroup;
-import android.widget.ArrayAdapter;
-import android.widget.Filter;
-import android.widget.TextView;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.res.ResourceLoader;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-
-@SuppressWarnings( { "UnusedDeclaration" })
-@Implements(ArrayAdapter.class)
-public class ShadowArrayAdapter<T> extends ShadowBaseAdapter {
-
- private static final Filter STUB_FILTER = new Filter() {
- @Override
- protected FilterResults performFiltering(CharSequence constraint) {
- return null;
- }
-
- @Override
- protected void publishResults(CharSequence constraint, FilterResults results) {
- }
- };
-
- private Context context;
- private List<T> list;
- private int resource;
- private int textViewResourceId;
- private Filter filter;
- private boolean notifyOnChange = true;
-
- public int getTextViewResourceId() {
- return textViewResourceId;
- }
-
- public int getResourceId() {
- return resource;
- }
-
- public void __constructor__(Context context, int textViewResourceId) {
- init(context, textViewResourceId, 0, new ArrayList<T>());
- }
-
- public void __constructor__(Context context, int resource, int textViewResourceId) {
- init(context, resource, textViewResourceId, new ArrayList<T>());
- }
-
- public void __constructor__(Context context, int textViewResourceId, T[] objects) {
- init(context, textViewResourceId, 0, Arrays.asList(objects));
- }
-
- public void __constructor__(Context context, int resource, int textViewResourceId, T[] objects) {
- init(context, resource, textViewResourceId, Arrays.asList(objects));
- }
-
- public void __constructor__(Context context, int textViewResourceId, List<T> objects) {
- init(context, textViewResourceId, 0, objects);
- }
-
- public void __constructor__(Context context, int resource, int textViewResourceId, List<T> objects) {
- init(context, resource, textViewResourceId, objects);
- }
-
- private void init(Context context, int resource, int textViewResourceId, List<T> objects) {
- this.context = context;
- this.list = objects;
- this.resource = resource;
- this.textViewResourceId = textViewResourceId;
- }
-
- @Implementation
- public void add(T object) {
- list.add(object);
- if (notifyOnChange)
- notifyDataSetChanged();
- }
-
- @Implementation
- public void clear() {
- list.clear();
- if (notifyOnChange)
- notifyDataSetChanged();
- }
-
- @Implementation
- public void remove(T object) {
- list.remove(object);
- if (notifyOnChange)
- notifyDataSetChanged();
- }
-
- @Implementation
- public void insert(T object, int index) {
- list.add(index, object);
- if (notifyOnChange)
- notifyDataSetChanged();
- }
-
- @Implementation
- public Context getContext() {
- return context;
- }
-
- @Implementation
- public int getCount() {
- return list.size();
- }
-
- @Implementation
- public T getItem(int position) {
- return list.get(position);
- }
-
- @Implementation
- public int getPosition(T item) {
- return list.indexOf(item);
- }
-
- @Implementation
- public View getView(int position, View convertView, ViewGroup parent) {
- T item = list.get(position);
- View view;
-
- if (convertView == null) {
- view = getResourceLoader().inflateView(context,resource, null);
- } else {
- view = convertView;
- }
-
- TextView text;
- if (textViewResourceId == 0) {
- text = (TextView) view;
- } else {
- text = (TextView) view.findViewById(textViewResourceId);
- }
-
- if (item instanceof CharSequence) {
- Robolectric.shadowOf(text).setText((CharSequence)item);
- } else {
- Robolectric.shadowOf(text).setText(item.toString());
- }
-
- return view;
- }
-
- @Implementation
- public Filter getFilter() {
- return STUB_FILTER;
- }
-
- @Override
- @Implementation
- public void notifyDataSetChanged() {
- super.notifyDataSetChanged();
- notifyOnChange = true;
- }
-
- @Implementation
- public void setNotifyOnChange(boolean notifyOnChange) {
- this.notifyOnChange = notifyOnChange;
- }
-
- private ResourceLoader getResourceLoader() {
- return shadowOf(Robolectric.application).getResourceLoader();
- }
-
- @Implementation
- public static ArrayAdapter<CharSequence> createFromResource(Context context, int textArrayResId, int textViewResId) {
- CharSequence[] strings = context.getResources().getTextArray(textArrayResId);
- return new ArrayAdapter<CharSequence>(context, textViewResId, strings);
- }
-} \ No newline at end of file
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowAssetManager.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowAssetManager.java
deleted file mode 100644
index 74dd2a2e9..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowAssetManager.java
+++ /dev/null
@@ -1,41 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.content.res.AssetManager;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.res.ResourceLoader;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-
-@SuppressWarnings({"UnusedDeclaration"})
-@Implements(AssetManager.class)
-public final class ShadowAssetManager {
- static AssetManager bind(AssetManager assetManager, ResourceLoader resourceLoader) {
- ShadowAssetManager shadowAssetManager = shadowOf(assetManager);
- if (shadowAssetManager.resourceLoader != null) throw new RuntimeException("ResourceLoader already set!");
- shadowAssetManager.resourceLoader = resourceLoader;
- return assetManager;
- }
-
- private ResourceLoader resourceLoader;
-
- @Implementation
- public final String[] list(String path) throws IOException {
- File file = new File(resourceLoader.getAssetsBase(), path);
- if (file.isDirectory()) {
- return file.list();
- }
- return new String[0];
- }
-
- @Implementation
- public final InputStream open(String fileName) throws IOException {
- return new FileInputStream(new File(resourceLoader.getAssetsBase(), fileName));
- }
-
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowAsyncTask.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowAsyncTask.java
deleted file mode 100644
index 57736e662..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowAsyncTask.java
+++ /dev/null
@@ -1,123 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.os.AsyncTask;
-import android.os.ShadowAsyncTaskBridge;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.internal.RealObject;
-
-import java.util.concurrent.Callable;
-import java.util.concurrent.CancellationException;
-import java.util.concurrent.ExecutionException;
-import java.util.concurrent.FutureTask;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.TimeoutException;
-
-@Implements(AsyncTask.class)
-public class ShadowAsyncTask<Params, Progress, Result> {
-
- @RealObject private AsyncTask<Params, Progress, Result> realAsyncTask;
-
- private final FutureTask<Result> future;
- private final BackgroundWorker worker;
- private AsyncTask.Status status = AsyncTask.Status.PENDING;
-
- public ShadowAsyncTask() {
- worker = new BackgroundWorker();
- future = new FutureTask<Result>(worker) {
- @Override
- protected void done() {
- status = AsyncTask.Status.FINISHED;
- try {
- final Result result = get();
- Robolectric.getUiThreadScheduler().post(new Runnable() {
- @Override public void run() {
- getBridge().onPostExecute(result);
- }
- });
- } catch (CancellationException e) {
- Robolectric.getUiThreadScheduler().post(new Runnable() {
- @Override public void run() {
- getBridge().onCancelled();
- }
- });
- } catch (InterruptedException e) {
- // Ignore.
- } catch (Throwable t) {
- throw new RuntimeException("An error occured while executing doInBackground()",
- t);
- }
- }
- };
- }
-
- @Implementation
- public boolean isCancelled() {
- return future.isCancelled();
- }
-
- @Implementation
- public boolean cancel(boolean mayInterruptIfRunning) {
- return future.cancel(mayInterruptIfRunning);
- }
-
- @Implementation
- public Result get() throws InterruptedException, ExecutionException {
- return future.get();
- }
-
- @Implementation
- public Result get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
- return future.get(timeout, unit);
- }
-
- @Implementation
- public AsyncTask<Params, Progress, Result> execute(final Params... params) {
- status = AsyncTask.Status.RUNNING;
- getBridge().onPreExecute();
-
- worker.params = params;
-
- Robolectric.getBackgroundScheduler().post(new Runnable() {
- @Override public void run() {
- future.run();
- }
- });
-
- return realAsyncTask;
- }
-
- @Implementation
- public AsyncTask.Status getStatus() {
- return status;
- }
-
- /**
- * Enqueue a call to {@link AsyncTask#onProgressUpdate(Object[])} on UI looper (or run it immediately
- * if the looper it is not paused).
- *
- * @param values The progress values to update the UI with.
- * @see AsyncTask#publishProgress(Object[])
- */
- @Implementation
- public void publishProgress(final Progress... values) {
- Robolectric.getUiThreadScheduler().post(new Runnable() {
- @Override public void run() {
- getBridge().onProgressUpdate(values);
- }
- });
- }
-
- private ShadowAsyncTaskBridge<Params, Progress, Result> getBridge() {
- return new ShadowAsyncTaskBridge<Params, Progress, Result>(realAsyncTask);
- }
-
- private final class BackgroundWorker implements Callable<Result> {
- Params[] params;
- @Override
- public Result call() throws Exception {
- return getBridge().doInBackground(params);
- }
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowAudioManager.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowAudioManager.java
deleted file mode 100644
index 5f3de9221..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowAudioManager.java
+++ /dev/null
@@ -1,93 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.media.AudioManager;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-@SuppressWarnings({"UnusedDeclaration"})
-@Implements(AudioManager.class)
-public class ShadowAudioManager {
-
- private int streamMaxVolume = 15;
- private int streamVolume = 7;
- private int flags;
- private AudioFocusRequest lastAudioFocusRequest;
- private int nextResponseValue = AudioManager.AUDIOFOCUS_REQUEST_GRANTED;
- private AudioManager.OnAudioFocusChangeListener lastAbandonedAudioFocusListener;
-
- @Implementation
- public int getStreamMaxVolume(int streamType) {
- return streamMaxVolume;
- }
-
- @Implementation
- public int getStreamVolume(int streamType) {
- return streamVolume;
- }
-
- @Implementation
- public void setStreamVolume(int streamType, int index, int flags) {
- this.streamVolume = index;
- this.flags = flags;
- }
-
- @Implementation
- public int requestAudioFocus(android.media.AudioManager.OnAudioFocusChangeListener l, int streamType, int durationHint) {
- lastAudioFocusRequest = new AudioFocusRequest(l, streamType, durationHint);
- return nextResponseValue;
- }
-
- @Implementation
- public int abandonAudioFocus(AudioManager.OnAudioFocusChangeListener l) {
- lastAbandonedAudioFocusListener = l;
- return nextResponseValue;
- }
-
- public int getStreamMaxVolume() {
- return streamMaxVolume;
- }
-
- public void setStreamMaxVolume(int streamMaxVolume) {
- this.streamMaxVolume = streamMaxVolume;
- }
-
- public int getStreamVolume() {
- return streamVolume;
- }
-
- public void setStreamVolume(int streamVolume) {
- this.streamVolume = streamVolume;
- }
-
- public int getFlags() {
- return flags;
- }
-
- public void setFlags(int flags) {
- this.flags = flags;
- }
-
- public AudioFocusRequest getLastAudioFocusRequest() {
- return lastAudioFocusRequest;
- }
-
- public void setNextFocusRequestResponse(int nextResponseValue) {
- this.nextResponseValue = nextResponseValue;
- }
-
- public AudioManager.OnAudioFocusChangeListener getLastAbandonedAudioFocusListener() {
- return lastAbandonedAudioFocusListener;
- }
-
- public static class AudioFocusRequest {
- public final AudioManager.OnAudioFocusChangeListener listener;
- public final int streamType;
- public final int durationHint;
-
- private AudioFocusRequest(AudioManager.OnAudioFocusChangeListener listener, int streamType, int durationHint) {
- this.listener = listener;
- this.streamType = streamType;
- this.durationHint = durationHint;
- }
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowAutoCompleteTextView.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowAutoCompleteTextView.java
deleted file mode 100644
index 3c0362b21..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowAutoCompleteTextView.java
+++ /dev/null
@@ -1,60 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-import android.widget.AdapterView;
-import android.widget.AdapterView.OnItemClickListener;
-import android.widget.AutoCompleteTextView;
-import android.widget.Filterable;
-import android.widget.ListAdapter;
-
-/**
- * A shadow for AutoCompleteTextView
- */
-@Implements(AutoCompleteTextView.class)
-public class ShadowAutoCompleteTextView extends ShadowEditText {
-
- private ListAdapter adapter;
- private int threshold = 2;
- private OnItemClickListener onItemClickListener;
-
- @Implementation
- public ListAdapter getAdapter() {
- return adapter;
- }
-
- @Implementation
- public <T extends ListAdapter & Filterable> void setAdapter(T adapter) {
- this.adapter = adapter;
- }
-
- @Implementation
- public int getThreshold() {
- return threshold;
- }
-
- @Implementation
- public void setThreshold(int threshold) {
- if (threshold <= 0) {
- threshold = 1;
- }
- this.threshold = threshold;
- }
-
- @Implementation
- public AdapterView.OnItemClickListener getOnItemClickListener() {
- return onItemClickListener;
- }
-
- @Implementation
- public void setOnItemClickListener(AdapterView.OnItemClickListener onItemClickListener) {
- this.onItemClickListener = onItemClickListener;
- }
-
- @Implementation
- public void replaceText(CharSequence text) {
- setText(text);
- setSelection(getText().length());
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowBase64.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowBase64.java
deleted file mode 100644
index a8ed36076..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowBase64.java
+++ /dev/null
@@ -1,22 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-import org.apache.commons.codec.binary.Base64;
-
-@Implements(android.util.Base64.class)
-public class ShadowBase64 {
-
- @Implementation
- public static String encodeToString(byte[] bytes, int flags) {
- Base64 base64 = new Base64();
- return base64.encodeBase64String(bytes);
- }
-
- @Implementation
- public static byte[] decode(String str, int flags) {
- Base64 base64 = new Base64();
- return base64.decodeBase64(str);
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowBaseAdapter.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowBaseAdapter.java
deleted file mode 100644
index 98c3f82a7..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowBaseAdapter.java
+++ /dev/null
@@ -1,82 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.database.DataSetObserver;
-import android.widget.BaseAdapter;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.internal.RealObject;
-
-import java.util.ArrayList;
-import java.util.List;
-
-@SuppressWarnings({"UnusedDeclaration"})
-@Implements(BaseAdapter.class)
-public class ShadowBaseAdapter {
- @RealObject private BaseAdapter realBaseAdapter;
- private final List<DataSetObserver> dataSetObservers = new ArrayList<DataSetObserver>();
- private boolean wasNotifyDataSetChangedCalled;
-
- @Implementation
- public boolean isEmpty() {
- return realBaseAdapter.getCount() == 0;
- }
-
- /**
- * Just returns true
- *
- * @return true
- */
- @Implementation
- public boolean areAllItemsEnabled() {
- return true;
- }
-
- /**
- * Registers the observer.
- *
- * @param observer observer
- */
- @Implementation
- public void registerDataSetObserver(DataSetObserver observer) {
- dataSetObservers.add(observer);
- }
-
- /**
- * Unregisters the observer if it can be found. Nothing otherwise.
- *
- * @param observer observer
- */
- @Implementation
- public void unregisterDataSetObserver(DataSetObserver observer) {
- dataSetObservers.remove(observer);
- }
-
- /**
- * Notifies the registered observers
- */
- @Implementation
- public void notifyDataSetChanged() {
- wasNotifyDataSetChangedCalled = true;
- for (DataSetObserver dataSetObserver : dataSetObservers) {
- dataSetObserver.onChanged();
- }
- }
-
- /**
- * Notifies the registered observers
- */
- @Implementation
- public void notifyDataSetInvalidated() {
- for (DataSetObserver dataSetObserver : dataSetObservers) {
- dataSetObserver.onInvalidated();
- }
- }
-
- public void clearWasDataSetChangedCalledFlag() {
- wasNotifyDataSetChangedCalled = false;
- }
-
- public boolean wasNotifyDataSetChangedCalled() {
- return wasNotifyDataSetChangedCalled;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowBinder.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowBinder.java
deleted file mode 100644
index 0499e52ca..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowBinder.java
+++ /dev/null
@@ -1,53 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.os.Binder;
-import android.os.Parcel;
-import android.os.RemoteException;
-import android.os.ShadowBinderBridge;
-
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.internal.RealObject;
-
-@Implements(android.os.Binder.class)
-public class ShadowBinder {
- @RealObject
- Binder realObject;
-
- private static Integer callingUid;
- private static Integer callingPid;
-
- @Implementation
- public boolean transact(int code, Parcel data, Parcel reply, int flags) throws RemoteException {
- return new ShadowBinderBridge(realObject).onTransact(code, data, reply, flags);
- }
-
- @Implementation
- public static final int getCallingPid() {
- if (callingPid != null) {
- return callingPid;
- }
- return android.os.Process.myPid();
- }
-
- @Implementation
- public static final int getCallingUid() {
- if (callingUid != null) {
- return callingUid;
- }
- return android.os.Process.myUid();
- }
-
- public static void setCallingPid(int pid) {
- ShadowBinder.callingPid = pid;
- }
-
- public static void setCallingUid(int uid) {
- ShadowBinder.callingUid = uid;
- }
-
- public static void reset() {
- ShadowBinder.callingPid = null;
- ShadowBinder.callingUid = null;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowBitmap.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowBitmap.java
deleted file mode 100644
index 20e7553cc..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowBitmap.java
+++ /dev/null
@@ -1,189 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.graphics.Bitmap;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.internal.RealObject;
-
-import java.io.IOException;
-import java.io.OutputStream;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-
-@SuppressWarnings({"UnusedDeclaration"})
-@Implements(Bitmap.class)
-public class ShadowBitmap {
- @RealObject private Bitmap realBitmap;
-
- private int width;
- private int height;
- private Bitmap.Config config;
- private boolean mutable;
- private String description = "";
- private int loadedFromResourceId = -1;
- private boolean recycled = false;
-
- @Implementation
- public boolean compress(Bitmap.CompressFormat format, int quality, OutputStream stream) {
- try {
- stream.write((description + " compressed as " + format + " with quality " + quality).getBytes());
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
-
- return true;
- }
-
- @Implementation
- public static Bitmap createBitmap(int width, int height, Bitmap.Config config) {
- Bitmap scaledBitmap = Robolectric.newInstanceOf(Bitmap.class);
- ShadowBitmap shadowBitmap = shadowOf(scaledBitmap);
- shadowBitmap.appendDescription("Bitmap (" + width + " x " + height + ")");
- shadowBitmap.setWidth(width);
- shadowBitmap.setHeight(height);
- shadowBitmap.setConfig(config);
- return scaledBitmap;
- }
-
- @Implementation
- public static Bitmap createBitmap(Bitmap bitmap) {
- ShadowBitmap shadowBitmap = shadowOf(bitmap);
- shadowBitmap.appendDescription(" created from Bitmap object");
- return bitmap;
- }
-
- @Implementation
- public static Bitmap createScaledBitmap(Bitmap src, int dstWidth, int dstHeight, boolean filter) {
- Bitmap scaledBitmap = Robolectric.newInstanceOf(Bitmap.class);
- ShadowBitmap shadowBitmap = shadowOf(scaledBitmap);
- shadowBitmap.appendDescription(shadowOf(src).getDescription());
- shadowBitmap.appendDescription(" scaled to " + dstWidth + " x " + dstHeight);
- if (filter) {
- shadowBitmap.appendDescription(" with filter " + filter);
- }
- shadowBitmap.setWidth(dstWidth);
- shadowBitmap.setHeight(dstHeight);
- return scaledBitmap;
- }
-
- @Implementation
- public void recycle() {
- recycled = true;
- }
-
- @Implementation
- public final boolean isRecycled() {
- return recycled;
- }
-
- @Implementation
- public Bitmap copy(Bitmap.Config config, boolean isMutable) {
- ShadowBitmap shadowBitmap = shadowOf(realBitmap);
- shadowBitmap.setConfig(config);
- shadowBitmap.setMutable(isMutable);
- return realBitmap;
- }
-
- @Implementation
- public final Bitmap.Config getConfig() {
- return config;
- }
-
- public void setConfig(Bitmap.Config config) {
- this.config = config;
- }
-
- @Implementation
- public final boolean isMutable() {
- return mutable;
- }
-
- public void setMutable(boolean mutable) {
- this.mutable = mutable;
- }
-
- public void appendDescription(String s) {
- description += s;
- }
-
- public void setDescription(String s) {
- description = s;
- }
-
- public String getDescription() {
- return description;
- }
-
- public static Bitmap create(String name) {
- Bitmap bitmap = Robolectric.newInstanceOf(Bitmap.class);
- shadowOf(bitmap).appendDescription(name);
- return bitmap;
- }
-
- public void setLoadedFromResourceId(int loadedFromResourceId) {
- this.loadedFromResourceId = loadedFromResourceId;
- }
-
- public int getLoadedFromResourceId() {
- if (loadedFromResourceId == -1) {
- throw new IllegalStateException("not loaded from a resource");
- }
- return loadedFromResourceId;
- }
-
- public void setWidth(int width) {
- this.width = width;
- }
-
- @Implementation
- public int getWidth() {
- return width;
- }
-
- public void setHeight(int height) {
- this.height = height;
- }
-
- @Implementation
- public int getHeight() {
- return height;
- }
-
- @Override @Implementation
- public boolean equals(Object o) {
- if (this == o) return true;
- if (o == null || getClass() != ShadowBitmap.class) return false;
-
- ShadowBitmap that = shadowOf((Bitmap) o);
-
- if (height != that.height) return false;
- if (width != that.width) return false;
- if (description != null ? !description.equals(that.description) : that.description != null) return false;
-
- return true;
- }
-
- @Override @Implementation
- public int hashCode() {
- int result = width;
- result = 31 * result + height;
- result = 31 * result + (description != null ? description.hashCode() : 0);
- return result;
- }
-
- @Override @Implementation
- public String toString() {
- return "ShadowBitmap{" +
- "description='" + description + '\'' +
- ", width=" + width +
- ", height=" + height +
- '}';
- }
-
- public Bitmap getRealBitmap() {
- return realBitmap;
- }
-
-
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowBitmapDrawable.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowBitmapDrawable.java
deleted file mode 100644
index da4c4e16f..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowBitmapDrawable.java
+++ /dev/null
@@ -1,142 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-
-import android.content.res.Resources;
-import android.graphics.Bitmap;
-import android.graphics.Canvas;
-import android.graphics.ColorFilter;
-import android.graphics.Paint;
-import android.graphics.Shader.TileMode;
-import android.graphics.drawable.BitmapDrawable;
-
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.internal.RealObject;
-
-@SuppressWarnings({"UnusedDeclaration"})
-@Implements(BitmapDrawable.class)
-public class ShadowBitmapDrawable extends ShadowDrawable {
- private Bitmap bitmap;
- private ColorFilter colorFilter;
- private String drawableCreateFromStreamSource;
- private String drawableCreateFromPath;
-
- @RealObject private BitmapDrawable realBitmapDrawable;
- private TileMode tileModeX;
- private TileMode tileModeY;
-
- public void __constructor__(Bitmap bitmap) {
- this.bitmap = bitmap;
- }
-
- public void __constructor__(Resources resources, Bitmap bitmap) {
- this.bitmap = bitmap;
- }
-
- /**
- * Draws the contained bitmap onto the canvas at 0,0 with a default {@code Paint}
- *
- * @param canvas the canvas to draw on
- */
- @Implementation
- public void draw(Canvas canvas) {
- Paint paint = new Paint();
- paint.setColorFilter(colorFilter);
- canvas.drawBitmap(realBitmapDrawable.getBitmap(), 0, 0, paint);
- }
-
- @Implementation
- public void setColorFilter(android.graphics.ColorFilter colorFilter) {
- this.colorFilter = colorFilter;
- }
-
- @Implementation
- public android.graphics.Bitmap getBitmap() {
- return bitmap;
- }
-
- /**
- * Non-Android accessor that tells you the resource id that this {@code BitmapDrawable} was loaded from. This lets
- * your tests assert that the bitmap is correct without having to actually load the bitmap.
- *
- * @return resource id from which this {@code BitmapDrawable} was loaded
- * @deprecated use com.xtremelabs.robolectric.shadows.ShadowBitmap#getLoadedFromResourceId() instead.
- */
- @Deprecated
- @Override
- public int getLoadedFromResourceId() {
- return shadowOf(bitmap).getLoadedFromResourceId();
- }
-
- // Used by ShadowDrawable.createFromStream()
- public void setSource(String drawableCreateFromStreamSource) {
- this.drawableCreateFromStreamSource = drawableCreateFromStreamSource;
- }
-
- public String getSource() {
- return drawableCreateFromStreamSource;
- }
-
- //Used by ShadowDrawable.createFromPath()
- public void setPath(String drawableCreateFromPath) {
- this.drawableCreateFromPath = drawableCreateFromPath;
- }
-
- public String getPath() {
- return drawableCreateFromPath;
- }
-
- @Implementation
- public void setTileModeX(TileMode mode) {
- tileModeX = mode;
- }
-
- @Implementation
- public TileMode getTileModeX() {
- return tileModeX;
- }
-
- @Implementation
- public void setTileModeY(TileMode mode) {
- tileModeY = mode;
- }
-
- @Implementation
- public TileMode getTileModeY() {
- return tileModeY;
- }
-
- @Implementation
- public void setTileModeXY(TileMode modeX, TileMode modeY) {
- setTileModeX(modeX);
- setTileModeY(modeY);
- }
-
- @Override
- @Implementation
- public boolean equals(Object o) {
- if (this == o) return true;
- if (o == null || getClass() != ShadowBitmapDrawable.class) return false;
-
- ShadowBitmapDrawable that = shadowOf((BitmapDrawable) o);
-
- if (bitmap != null ? !bitmap.equals(that.bitmap) : that.bitmap != null) return false;
-
- return super.equals(o);
- }
-
- @Override
- @Implementation
- public int hashCode() {
- return bitmap != null ? bitmap.hashCode() : 0;
- }
-
- @Override
- @Implementation
- public String toString() {
- return "ShadowBitmapDrawable{" +
- "bitmap=" + bitmap +
- '}';
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowBitmapFactory.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowBitmapFactory.java
deleted file mode 100644
index f804eb113..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowBitmapFactory.java
+++ /dev/null
@@ -1,116 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.content.res.Resources;
-import android.graphics.Bitmap;
-import android.graphics.BitmapFactory;
-import android.graphics.Point;
-import android.graphics.Rect;
-import android.net.Uri;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.util.Join;
-
-import java.io.InputStream;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-
-@SuppressWarnings({"UnusedDeclaration"})
-@Implements(BitmapFactory.class)
-public class ShadowBitmapFactory {
- private static Map<String, Point> widthAndHeightMap = new HashMap<String, Point>();
-
- @Implementation
- public static Bitmap decodeResource(Resources res, int id) {
- Bitmap bitmap = create("resource:" + getResourceName(id));
- shadowOf(bitmap).setLoadedFromResourceId(id);
- return bitmap;
- }
-
- @Implementation
- public static Bitmap decodeResource(Resources res, int id, BitmapFactory.Options options) {
- Bitmap bitmap = create("resource:" + getResourceName(id), options);
- shadowOf(bitmap).setLoadedFromResourceId(id);
- return bitmap;
- }
-
- private static String getResourceName(int id) {
- return shadowOf(Robolectric.application).getResourceLoader().getNameForId(id);
- }
-
- @Implementation
- public static Bitmap decodeFile(String pathName) {
- return create("file:" + pathName);
- }
-
- @Implementation
- public static Bitmap decodeFile(String pathName, BitmapFactory.Options options) {
- return create("file:" + pathName, options);
- }
-
- @Implementation
- public static Bitmap decodeStream(InputStream is) {
- return decodeStream(is, null, new BitmapFactory.Options());
- }
-
- @Implementation
- public static Bitmap decodeStream(InputStream is, Rect outPadding, BitmapFactory.Options opts) {
- return create(is.toString().replaceFirst("stream for ", ""), opts);
- }
-
- static Bitmap create(String name) {
- return create(name, new BitmapFactory.Options());
- }
-
- public static Bitmap create(String name, BitmapFactory.Options options) {
- Bitmap bitmap = Robolectric.newInstanceOf(Bitmap.class);
- ShadowBitmap shadowBitmap = shadowOf(bitmap);
- shadowBitmap.appendDescription("Bitmap for " + name);
-
- String optionsString = stringify(options);
- if (optionsString.length() > 0) {
- shadowBitmap.appendDescription(" with options ");
- shadowBitmap.appendDescription(optionsString);
- }
-
- Point widthAndHeight = widthAndHeightMap.get(name);
- if (widthAndHeight == null) {
- widthAndHeight = new Point(100, 100);
- }
-
- shadowBitmap.setWidth(widthAndHeight.x);
- shadowBitmap.setHeight(widthAndHeight.y);
- options.outWidth = widthAndHeight.x;
- options.outHeight = widthAndHeight.y;
- return bitmap;
- }
-
- public static void provideWidthAndHeightHints(Uri uri, int width, int height) {
- widthAndHeightMap.put(uri.toString(), new Point(width, height));
- }
-
- public static void provideWidthAndHeightHints(int resourceId, int width, int height) {
- widthAndHeightMap.put("resource:" + getResourceName(resourceId), new Point(width, height));
- }
-
- public static void provideWidthAndHeightHints(String file, int width, int height) {
- widthAndHeightMap.put("file:" + file, new Point(width, height));
- }
-
- private static String stringify(BitmapFactory.Options options) {
- List<String> opts = new ArrayList<String>();
-
- if (options.inJustDecodeBounds) opts.add("inJustDecodeBounds");
- if (options.inSampleSize > 1) opts.add("inSampleSize=" + options.inSampleSize);
-
- return Join.join(", ", opts);
- }
-
- public static void reset() {
- widthAndHeightMap.clear();
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowBluetoothAdapter.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowBluetoothAdapter.java
deleted file mode 100644
index e15a0fdfd..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowBluetoothAdapter.java
+++ /dev/null
@@ -1,53 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.bluetooth.BluetoothAdapter;
-import android.bluetooth.BluetoothDevice;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.Set;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-
-@SuppressWarnings({"UnusedDeclaration"})
-@Implements(BluetoothAdapter.class)
-public class ShadowBluetoothAdapter {
-
- private Set<BluetoothDevice> bondedDevices = new HashSet<BluetoothDevice>();
- private boolean isDiscovering;
-
- @Implementation
- public static BluetoothAdapter getDefaultAdapter() {
- return (BluetoothAdapter) shadowOf(Robolectric.application).getBluetoothAdapter();
- }
-
- @Implementation
- public Set<BluetoothDevice> getBondedDevices() {
- return Collections.unmodifiableSet(bondedDevices);
- }
-
- public void setBondedDevices(Set<BluetoothDevice> bluetoothDevices) {
- bondedDevices = bluetoothDevices;
- }
-
- @Implementation
- public boolean startDiscovery() {
- isDiscovering = true;
- return true;
- }
-
- @Implementation
- public boolean cancelDiscovery() {
- isDiscovering = false;
- return true;
- }
-
- @Implementation
- public boolean isDiscovering() {
- return isDiscovering;
- }
-
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowBluetoothDevice.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowBluetoothDevice.java
deleted file mode 100644
index de7068c5f..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowBluetoothDevice.java
+++ /dev/null
@@ -1,20 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.bluetooth.BluetoothDevice;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-@Implements(BluetoothDevice.class)
-public class ShadowBluetoothDevice {
-
- private String name;
-
- public void setName(String name) {
- this.name = name;
- }
-
- @Implementation
- public String getName() {
- return name;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowBundle.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowBundle.java
deleted file mode 100644
index 02ddf898f..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowBundle.java
+++ /dev/null
@@ -1,457 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf_;
-
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.Map;
-import java.util.Set;
-import java.util.TreeMap;
-
-import android.os.Build;
-import android.os.Bundle;
-import android.os.Parcelable;
-
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-@SuppressWarnings({ "UnusedDeclaration" })
-@Implements(Bundle.class)
-public class ShadowBundle {
- Map<String, Object> map = new TreeMap<String, Object>();
-
- public void __constructor__(Bundle b) {
- putAll(b);
- }
-
- @Implementation
- public void clear() {
- map.clear();
- }
-
- @Implementation
- public void remove(String key) {
- map.remove(key);
- }
-
- @Implementation
- public Object get(String key) {
- return map.get(key);
- }
-
- @Implementation
- public void putString(String key, String value) {
- map.put(key, value);
- }
-
- @Implementation
- public String getString(String key) {
- Object value = map.get(key);
- return value == null || !(value instanceof String) ? null : (String) value;
- }
-
- @Implementation
- public String getString(String key, String defaultValue) {
- if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB_MR1) {
- throw new RuntimeException(new NoSuchMethodException("Requires API_12"));
- }
- Object value = map.get(key);
- return value == null || !(value instanceof String) ? defaultValue : (String) value;
- }
-
- @Implementation
- public void putLong(String key, long value) {
- map.put(key, value);
- }
-
- @Implementation
- public long getLong(String key) {
- return getLong(key, 0);
- }
-
- @Implementation
- public long getLong(String key, long defaultValue) {
- Object value = map.get(key);
- return value == null || !(value instanceof Long) ? defaultValue : (Long) value;
- }
-
- @Implementation
- public void putInt(String key, int value) {
- map.put(key, value);
- }
-
- @Implementation
- public int getInt(String key) {
- return getInt(key, 0);
- }
-
- @Implementation
- public int getInt(String key, int defaultValue) {
- Object value = map.get(key);
- return value == null || !(value instanceof Integer) ? defaultValue : (Integer) value;
- }
-
- @Implementation
- public void putDouble(String key, double value) {
- map.put(key, value);
- }
-
- @Implementation
- public double getDouble(String key) {
- return getDouble(key, 0);
- }
-
- @Implementation
- public double getDouble(String key, double defaultValue) {
- Object value = map.get(key);
- return value == null || !(value instanceof Double) ? defaultValue : (Double) value;
- }
-
- @Implementation
- public void putByte(String key, byte value) {
- map.put(key, value);
- }
-
- @Implementation
- public byte getByte(String key) {
- return getByte(key, (byte) 0);
- }
-
- @Implementation
- public Byte getByte(String key, byte defaultValue) {
- Object value = map.get(key);
- return value == null || !(value instanceof Byte) ? defaultValue : (Byte) value;
- }
-
- @Implementation
- public void putBoolean(String key, boolean value) {
- map.put(key, value);
- }
-
- @Implementation
- public boolean getBoolean(String key) {
- return getBoolean(key, false);
- }
-
- @Implementation
- public boolean getBoolean(String key, boolean defaultValue) {
- Object value = map.get(key);
- return value == null || !(value instanceof Boolean) ? defaultValue : (Boolean) value;
- }
-
- @Implementation
- public void putChar(String key, char value) {
- map.put(key, value);
- }
-
- @Implementation
- public char getChar(String key) {
- return getChar(key, (char) 0);
- }
-
- @Implementation
- public char getChar(String key, char defaultValue) {
- Object value = map.get(key);
- return value == null || !(value instanceof Character) ? defaultValue : (Character) value;
- }
-
- @Implementation
- public void putCharSequence(String key, CharSequence value) {
- map.put(key, value);
- }
-
- @Implementation
- public CharSequence getCharSequence(String key) {
- Object value = map.get(key);
- return value == null || !(value instanceof CharSequence) ? null : (CharSequence) value;
- }
-
- @Implementation
- public void putShort(String key, short value) {
- map.put(key, value);
- }
-
- @Implementation
- public short getShort(String key) {
- return getShort(key, (short) 0);
- }
-
- @Implementation
- public short getShort(String key, short defaultValue) {
- Object value = map.get(key);
- return value == null || !(value instanceof Short) ? defaultValue : (Short) value;
- }
-
- @Implementation
- public void putFloat(String key, float value) {
- map.put(key, value);
- }
-
- @Implementation
- public float getFloat(String key) {
- return getFloat(key, 0);
- }
-
- @Implementation
- public float getFloat(String key, float defaultValue) {
- Object value = map.get(key);
- return value == null || !(value instanceof Float) ? defaultValue : (Float) value;
- }
-
- @Implementation
- public void putSerializable(String key, Serializable value) {
- map.put(key, value);
- }
-
- @Implementation
- public Serializable getSerializable(String key) {
- Object value = map.get(key);
- return value == null || !(value instanceof Serializable) ? null : (Serializable) value;
- }
-
- @Implementation
- public void putParcelable(String key, Parcelable value) {
- map.put(key, value);
- }
-
- @Implementation
- public void putParcelableArrayList(String key, ArrayList<? extends Parcelable> value) {
- map.put(key, value);
- }
-
- @Implementation
- public Parcelable getParcelable(String key) {
- Object value = map.get(key);
- return value == null || !(value instanceof Parcelable) ? null : (Parcelable) value;
- }
-
- @Implementation
- public ArrayList<Parcelable> getParcelableArrayList(String key) {
- Object value = map.get(key);
- return value == null || !(value instanceof ArrayList) ? null
- : (ArrayList<Parcelable>) value;
- }
-
- @Implementation
- public Parcelable[] getParcelableArray(String key) {
- Object value = map.get(key);
- return value == null || !(value instanceof Parcelable[]) ? null : (Parcelable[]) value;
- }
-
- @Implementation
- public void putParcelableArray(String key, Parcelable[] value) {
- map.put(key, value);
- }
-
- @Implementation
- public void putStringArrayList(String key, ArrayList<String> value) {
- map.put(key, value);
- }
-
- @Implementation
- public ArrayList<String> getStringArrayList(String key) {
- Object value = map.get(key);
- return value == null || !(value instanceof ArrayList) ? null : (ArrayList<String>) value;
- }
-
- @Implementation
- public void putCharSequenceArrayList(String key, ArrayList<CharSequence> value) {
- map.put(key, value);
- }
-
- @Implementation
- public ArrayList<CharSequence> getCharSequenceArrayList(String key) {
- Object value = map.get(key);
- return value == null || !(value instanceof ArrayList) ? null
- : (ArrayList<CharSequence>) value;
- }
-
- @Implementation
- public void putIntegerArrayList(String key, ArrayList<Integer> value) {
- map.put(key, value);
- }
-
- @Implementation
- public ArrayList<Integer> getIntegerArrayList(String key) {
- Object value = map.get(key);
- return value == null || !(value instanceof ArrayList) ? null : (ArrayList<Integer>) value;
- }
-
- @Implementation
- public void putBundle(String key, Bundle value) {
- map.put(key, value);
- }
-
- @Implementation
- public Bundle getBundle(String key) {
- Object value = map.get(key);
- return value == null || !(value instanceof Bundle) ? null : (Bundle) value;
- }
-
- @Implementation
- public void putBooleanArray(String key, boolean[] value) {
- map.put(key, value);
- }
-
- @Implementation
- public boolean[] getBooleanArray(String key) {
- Object value = map.get(key);
- return value == null || !(value instanceof boolean[]) ? null : (boolean[]) value;
- }
-
- @Implementation
- public void putByteArray(String key, byte[] value) {
- map.put(key, value);
- }
-
- @Implementation
- public byte[] getByteArray(String key) {
- Object value = map.get(key);
- return value == null || !(value instanceof byte[]) ? null : (byte[]) value;
- }
-
- @Implementation
- public void putCharArray(String key, char[] value) {
- map.put(key, value);
- }
-
- @Implementation
- public char[] getCharArray(String key) {
- Object value = map.get(key);
- return value == null || !(value instanceof char[]) ? null : (char[]) value;
- }
-
- @Implementation
- public void putDoubleArray(String key, double[] value) {
- map.put(key, value);
- }
-
- @Implementation
- public double[] getDoubleArray(String key) {
- Object value = map.get(key);
- return value == null || !(value instanceof double[]) ? null : (double[]) value;
- }
-
- @Implementation
- public void putFloatArray(String key, float[] value) {
- map.put(key, value);
- }
-
- @Implementation
- public float[] getFloatArray(String key) {
- Object value = map.get(key);
- return value == null || !(value instanceof float[]) ? null : (float[]) value;
- }
-
- @Implementation
- public void putIntArray(String key, int[] value) {
- map.put(key, value);
- }
-
- @Implementation
- public int[] getIntArray(String key) {
- Object value = map.get(key);
- return value == null || !(value instanceof int[]) ? null : (int[]) value;
- }
-
- @Implementation
- public void putLongArray(String key, long[] value) {
- map.put(key, value);
- }
-
- @Implementation
- public long[] getLongArray(String key) {
- Object value = map.get(key);
- return value == null || !(value instanceof long[]) ? null : (long[]) value;
- }
-
- @Implementation
- public void putShortArray(String key, short[] value) {
- map.put(key, value);
- }
-
- @Implementation
- public short[] getShortArray(String key) {
- Object value = map.get(key);
- return value == null || !(value instanceof short[]) ? null : (short[]) value;
- }
-
- @Implementation
- public void putAll(Bundle bundle) {
- map.putAll(((ShadowBundle) Robolectric.shadowOf_(bundle)).map);
- }
-
- @Implementation
- public void putStringArray(String key, String[] value) {
- map.put(key, value);
- }
-
- @Implementation
- public String[] getStringArray(String key) {
- Object value = map.get(key);
- return value == null || !(value instanceof String[]) ? null : (String[]) value;
- }
-
- @Implementation
- public void putCharSequenceArray(String key, CharSequence[] value) {
- map.put(key, value);
- }
-
- @Implementation
- public CharSequence[] getCharSequenceArray(String key) {
- Object value = map.get(key);
- return value == null || !(value instanceof CharSequence[]) ? null : (CharSequence[]) value;
- }
-
- @Implementation
- public boolean containsKey(String key) {
- return map.containsKey(key);
- }
-
- @Implementation
- public boolean isEmpty() {
- return map.isEmpty();
- }
-
- @Implementation
- public Set<String> keySet() {
- return map.keySet();
- }
-
- @Implementation
- public int size() {
- return map.size();
- }
-
- @Override
- @Implementation
- public boolean equals(Object o) {
- if (o == null)
- return false;
- o = shadowOf_(o);
- if (o == null)
- return false;
- if (this == o)
- return true;
- if (getClass() != o.getClass())
- return false;
-
- ShadowBundle that = (ShadowBundle) o;
-
- if (map != null ? !map.equals(that.map) : that.map != null)
- return false;
-
- return true;
- }
-
- @Override
- @Implementation
- public int hashCode() {
- return map != null ? map.hashCode() : 0;
- }
-
- public static void reset() {
- Robolectric.Reflection.setFinalStaticField(Bundle.class, "EMPTY", new Bundle());
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowButton.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowButton.java
deleted file mode 100644
index cefe303f2..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowButton.java
+++ /dev/null
@@ -1,17 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.widget.Button;
-import android.widget.TextView;
-import com.xtremelabs.robolectric.internal.Implements;
-
-@Implements(Button.class)
-public class ShadowButton extends ShadowTextView {
-
- @Override
- public void applyAttributes() {
- super.applyAttributes();
- if (getBackground() == null) {
- setBackgroundColor(android.R.color.transparent);
- }
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowCamera.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowCamera.java
deleted file mode 100644
index 16248a2ba..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowCamera.java
+++ /dev/null
@@ -1,157 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import android.hardware.Camera;
-import android.view.SurfaceHolder;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.internal.RealObject;
-
-/**
- * Shadows the Android {@code Camera} class.
- */
-@Implements(Camera.class)
-public class ShadowCamera {
-
- private boolean locked;
- private boolean previewing;
- private boolean released;
- private Camera.Parameters parameters;
- private Camera.PreviewCallback previewCallback;
- private SurfaceHolder surfaceHolder;
-
- private static Map<Integer, Camera.CameraInfo> cameras = new HashMap<Integer,Camera.CameraInfo>();
-
- @RealObject
- private Camera realCamera;
-
- public void __constructor__() {
- locked = true;
- previewing = false;
- released = false;
- }
-
- @Implementation
- public static Camera open() {
- return Robolectric.newInstanceOf(Camera.class);
- }
-
- @Implementation
- public void unlock() {
- locked = false;
- }
-
- @Implementation
- public void reconnect() {
- locked = true;
- }
-
- @Implementation
- public Camera.Parameters getParameters() {
- if (null == parameters) {
- parameters = Robolectric.newInstanceOf(Camera.Parameters.class);
- }
- return parameters;
- }
-
- @Implementation
- public void setParameters(Camera.Parameters params) {
- parameters = params;
- }
-
- @Implementation
- public void setPreviewDisplay(SurfaceHolder holder) {
- surfaceHolder = holder;
- }
-
- @Implementation
- public void startPreview() {
- previewing = true;
- }
-
- @Implementation
- public void stopPreview() {
- previewing = false;
- }
-
- @Implementation
- public void release() {
- released = true;
- }
-
- @Implementation
- public void setPreviewCallback(Camera.PreviewCallback cb) {
- previewCallback = cb;
- }
-
- @Implementation
- public void setOneShotPreviewCallback(Camera.PreviewCallback cb) {
- previewCallback = cb;
- }
-
- @Implementation
- public void setPreviewCallbackWithBuffer(Camera.PreviewCallback cb) {
- previewCallback = cb;
- }
-
- @Implementation
- public static void getCameraInfo(int cameraId, Camera.CameraInfo cameraInfo ) {
- Camera.CameraInfo foundCam = cameras.get( cameraId );
- cameraInfo.facing = foundCam.facing;
- cameraInfo.orientation = foundCam.orientation;
- }
-
- @Implementation
- public static int getNumberOfCameras() {
- return cameras.size();
- }
-
- /**
- * Allows test cases to invoke the preview callback, to simulate a frame of camera data.
- *
- * @param data byte buffer of simulated camera data
- */
- public void invokePreviewCallback(byte[] data) {
- if (previewCallback != null) {
- previewCallback.onPreviewFrame(data, realCamera);
- }
- }
-
- public boolean isLocked() {
- return locked;
- }
-
- public boolean isPreviewing() {
- return previewing;
- }
-
- public boolean isReleased() {
- return released;
- }
-
- public SurfaceHolder getPreviewDisplay() {
- return surfaceHolder;
- }
-
- /**
- * Add a mock {@code Camera.CameraInfo} object to simulate
- * the existence of one or more cameras. By default, no
- * cameras are defined.
- *
- * @param id
- * @param camInfo
- */
- public static void addCameraInfo(int id, Camera.CameraInfo camInfo) {
- cameras.put(id, camInfo);
- }
-
- public static void clearCameraInfo() {
- cameras.clear();
- }
-
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowCameraParameters.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowCameraParameters.java
deleted file mode 100644
index 4ed4437e8..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowCameraParameters.java
+++ /dev/null
@@ -1,167 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.graphics.ImageFormat;
-import android.hardware.Camera;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Shadows the Android {@code Camera.Parameters} class.
- */
-@Implements(Camera.Parameters.class)
-public class ShadowCameraParameters {
-
- private int pictureWidth = 1280;
- private int pictureHeight = 960;
- private int previewWidth = 640;
- private int previewHeight = 480;
- private int previewFormat = ImageFormat.NV21;
- private int previewFpsMin = 10;
- private int previewFpsMax = 30;
- private int previewFps = 30;
-
- @Implementation
- public Camera.Size getPictureSize() {
- Camera.Size pictureSize = Robolectric.newInstanceOf(Camera.class).new Size(0, 0);
- pictureSize.width = pictureWidth;
- pictureSize.height = pictureHeight;
- return pictureSize;
- }
-
- @Implementation
- public int getPreviewFormat() {
- return previewFormat;
- }
-
- @Implementation
- public void getPreviewFpsRange(int[] range) {
- range[0] = previewFpsMin;
- range[1] = previewFpsMax;
- }
-
- @Implementation
- public int getPreviewFrameRate() {
- return previewFps;
- }
-
- @Implementation
- public Camera.Size getPreviewSize() {
- Camera.Size previewSize = Robolectric.newInstanceOf(Camera.class).new Size(0, 0);
- previewSize.width = previewWidth;
- previewSize.height = previewHeight;
- return previewSize;
- }
-
- @Implementation
- public List<Camera.Size> getSupportedPictureSizes() {
- List<Camera.Size> supportedSizes = new ArrayList<Camera.Size>();
- addSize(supportedSizes, 320, 240);
- addSize(supportedSizes, 640, 480);
- addSize(supportedSizes, 800, 600);
- return supportedSizes;
- }
-
- @Implementation
- public List<Integer> getSupportedPictureFormats() {
- List<Integer> formats = new ArrayList<Integer>();
- formats.add(ImageFormat.NV21);
- formats.add(ImageFormat.JPEG);
- return formats;
- }
-
- @Implementation
- public List<Integer> getSupportedPreviewFormats() {
- List<Integer> formats = new ArrayList<Integer>();
- formats.add(ImageFormat.NV21);
- formats.add(ImageFormat.JPEG);
- return formats;
- }
-
- @Implementation
- public List<int[]> getSupportedPreviewFpsRange() {
- List<int[]> supportedRanges = new ArrayList<int[]>();
- addRange(supportedRanges, 15000, 15000);
- addRange(supportedRanges, 10000, 30000);
- return supportedRanges;
- }
-
- @Implementation
- public List<Integer> getSupportedPreviewFrameRates() {
- List<Integer> supportedRates = new ArrayList<Integer>();
- supportedRates.add(10);
- supportedRates.add(15);
- supportedRates.add(30);
- return supportedRates;
- }
-
- @Implementation
- public List<Camera.Size> getSupportedPreviewSizes() {
- List<Camera.Size> supportedSizes = new ArrayList<Camera.Size>();
- addSize(supportedSizes, 320, 240);
- addSize(supportedSizes, 640, 480);
- return supportedSizes;
- }
-
- @Implementation
- public void setPictureSize(int width, int height) {
- pictureWidth = width;
- pictureHeight = height;
- }
-
- @Implementation
- public void setPreviewFormat(int pixel_format) {
- previewFormat = pixel_format;
- }
-
- @Implementation
- public void setPreviewFpsRange(int min, int max) {
- previewFpsMin = min;
- previewFpsMax = max;
- }
-
- @Implementation
- public void setPreviewFrameRate(int fps) {
- previewFps = fps;
- }
-
- @Implementation
- public void setPreviewSize(int width, int height) {
- previewWidth = width;
- previewHeight = height;
- }
-
- public int getPreviewWidth() {
- return previewWidth;
- }
-
- public int getPreviewHeight() {
- return previewHeight;
- }
-
- public int getPictureWidth() {
- return pictureWidth;
- }
-
- public int getPictureHeight() {
- return pictureHeight;
- }
-
- private void addSize(List<Camera.Size> sizes, int width, int height) {
- Camera.Size newSize = Robolectric.newInstanceOf(Camera.class).new Size(0, 0);
- newSize.width = width;
- newSize.height = height;
- sizes.add(newSize);
- }
-
- private void addRange(List<int[]> ranges, int min, int max) {
- int[] range = new int[2];
- range[0] = min;
- range[1] = max;
- ranges.add(range);
- }
-
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowCameraSize.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowCameraSize.java
deleted file mode 100644
index 43f4aaf38..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowCameraSize.java
+++ /dev/null
@@ -1,18 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.hardware.Camera;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.internal.RealObject;
-
-/**
- * Shadow for the Android {@code Camera.Size} value object.
- */
-@Implements(Camera.Size.class)
-public class ShadowCameraSize {
- @RealObject private Camera.Size realCameraSize;
-
- public void __constructor__(Camera camera, int width, int height) {
- realCameraSize.width = width;
- realCameraSize.height = height;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowCanvas.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowCanvas.java
deleted file mode 100644
index e67515fb7..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowCanvas.java
+++ /dev/null
@@ -1,181 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.graphics.*;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import static com.xtremelabs.robolectric.Robolectric.newInstanceOf;
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-
-/**
- * Shadows the {@code android.graphics.Canvas} class.
- * <p/>
- * Broken.
- * This implementation is very specific to the application for which it was developed.
- * Todo: Reimplement. Consider using the same strategy of collecting a history of draw events and providing methods for writing queries based on type, number, and order of events.
- */
-@SuppressWarnings({"UnusedDeclaration"})
-@Implements(Canvas.class)
-public class ShadowCanvas {
- private List<PathPaintHistoryEvent> pathPaintEvents = new ArrayList<PathPaintHistoryEvent>();
- private List<CirclePaintHistoryEvent> circlePaintEvents = new ArrayList<CirclePaintHistoryEvent>();
- private Paint drawnPaint;
- private Bitmap targetBitmap = newInstanceOf(Bitmap.class);
- private float translateX;
- private float translateY;
- private float scaleX = 1;
- private float scaleY = 1;
-
- public void __constructor__(Bitmap bitmap) {
- this.targetBitmap = bitmap;
- }
-
- public void appendDescription(String s) {
- shadowOf(targetBitmap).appendDescription(s);
- }
-
- public String getDescription() {
- return shadowOf(targetBitmap).getDescription();
- }
-
- @Implementation
- public void translate(float x, float y) {
- this.translateX = x;
- this.translateY = y;
- }
-
- @Implementation
- public void scale(float sx, float sy) {
- this.scaleX = sx;
- this.scaleY = sy;
- }
-
- @Implementation
- public void scale(float sx, float sy, float px, float py) {
- this.scaleX = sx;
- this.scaleY = sy;
- }
-
- @Implementation
- public void drawPaint(Paint paint) {
- drawnPaint = paint;
- }
-
- @Implementation
- public void drawColor(int color) {
- appendDescription("draw color " + color);
- }
-
- @Implementation
- public void drawBitmap(Bitmap bitmap, float left, float top, Paint paint) {
- describeBitmap(bitmap, paint);
-
- int x = (int) (left + translateX);
- int y = (int) (top + translateY);
- if (x != 0 && y != 0) {
- appendDescription(" at (" + x + "," + y + ")");
- }
-
- if (scaleX != 1 && scaleY != 1) {
- appendDescription(" scaled by (" + scaleX + "," + scaleY + ")");
- }
- }
-
- @Implementation
- public void drawPath(Path path, Paint paint) {
- pathPaintEvents.add(new PathPaintHistoryEvent(path, paint));
-
- separateLines();
- appendDescription("Path " + shadowOf(path).getPoints().toString());
- }
-
- private void describeBitmap(Bitmap bitmap, Paint paint) {
- separateLines();
-
- appendDescription(shadowOf(bitmap).getDescription());
-
- if (paint != null) {
- ColorFilter colorFilter = paint.getColorFilter();
- if (colorFilter != null) {
- appendDescription(" with " + colorFilter);
- }
- }
- }
-
- private void separateLines() {
- if (getDescription().length() != 0) {
- appendDescription("\n");
- }
- }
-
- @Implementation
- public void drawBitmap(Bitmap bitmap, Matrix matrix, Paint paint) {
- describeBitmap(bitmap, paint);
-
- appendDescription(" transformed by matrix");
- }
-
- public int getPathPaintHistoryCount() {
- return pathPaintEvents.size();
- }
-
- public int getCirclePaintHistoryCount() {
- return circlePaintEvents.size();
- }
-
- public boolean hasDrawnPath() {
- return getPathPaintHistoryCount() > 0;
- }
-
- public boolean hasDrawnCircle() {
- return circlePaintEvents.size() > 0;
- }
-
- public Paint getDrawnPathPaint(int i) {
- return pathPaintEvents.get(i).pathPaint;
- }
-
- public Path getDrawnPath(int i) {
- return pathPaintEvents.get(i).drawnPath;
- }
-
- public CirclePaintHistoryEvent getDrawnCircle(int i) {
- return circlePaintEvents.get(i);
- }
-
- public void resetCanvasHistory() {
- pathPaintEvents.clear();
- circlePaintEvents.clear();
- }
-
- public Paint getDrawnPaint() {
- return drawnPaint;
- }
-
- private static class PathPaintHistoryEvent {
- private Path drawnPath;
- private Paint pathPaint;
-
- PathPaintHistoryEvent(Path drawnPath, Paint pathPaint) {
- this.drawnPath = drawnPath;
- this.pathPaint = pathPaint;
- }
- }
-
- public static class CirclePaintHistoryEvent {
- public Paint paint;
- public float centerX;
- public float centerY;
- public float radius;
-
- private CirclePaintHistoryEvent(float centerX, float centerY, float radius, Paint paint) {
- this.paint = paint;
- this.centerX = centerX;
- this.centerY = centerY;
- this.radius = radius;
- }
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowCheckedTextView.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowCheckedTextView.java
deleted file mode 100644
index 2fc8141ca..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowCheckedTextView.java
+++ /dev/null
@@ -1,28 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.widget.CheckedTextView;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-@SuppressWarnings({"UnusedDeclaration"})
-@Implements(CheckedTextView.class)
-public class ShadowCheckedTextView extends ShadowTextView {
-
- private boolean checked;
-
- @Implementation
- public void toggle() {
- checked = !checked;
- }
-
- @Implementation
- public boolean isChecked() {
- return checked;
- }
-
- @Implementation
- public void setChecked(boolean checked) {
- this.checked = checked;
- }
-
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowClipboardManager.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowClipboardManager.java
deleted file mode 100644
index de204fc25..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowClipboardManager.java
+++ /dev/null
@@ -1,25 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.text.ClipboardManager;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-@Implements(ClipboardManager.class)
-public class ShadowClipboardManager {
- private CharSequence text;
-
- @Implementation
- public void setText(CharSequence text) {
- this.text = text;
- }
-
- @Implementation
- public CharSequence getText() {
- return text;
- }
-
- @Implementation
- public boolean hasText() {
- return text != null && text.length() > 0;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowColor.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowColor.java
deleted file mode 100644
index 5ca4375a4..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowColor.java
+++ /dev/null
@@ -1,19 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.graphics.Color;
-
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-@Implements(Color.class)
-public class ShadowColor {
- @Implementation
- public static int rgb(int red, int green, int blue) {
- return argb(0xff, red, green, blue);
- }
-
- @Implementation
- public static int argb(int alpha, int red, int green, int blue) {
- return (alpha << 24) | (red << 16) | (green << 8) | blue;
- }
-} \ No newline at end of file
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowColorDrawable.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowColorDrawable.java
deleted file mode 100644
index 200d51d43..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowColorDrawable.java
+++ /dev/null
@@ -1,39 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-
-import android.graphics.drawable.ColorDrawable;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-
-@Implements(ColorDrawable.class)
-public class ShadowColorDrawable extends ShadowDrawable {
-
- int colorResourceId;
-
- public void __constructor__(int color) {
- colorResourceId = color;
- }
-
- @Override @Implementation
- public boolean equals(Object o) {
- if (realObject == o) return true;
- if (o == null || realObject.getClass() != o.getClass()) return false;
-
- if (!super.equals(o)) return false;
-
- ShadowColorDrawable that = shadowOf((ColorDrawable)o);
-
- if (colorResourceId != that.colorResourceId) return false;
-
- return true;
- }
-
- @Override @Implementation
- public int hashCode() {
- int result = super.hashCode();
- result = 31 * result + colorResourceId;
- return result;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowColorMatrix.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowColorMatrix.java
deleted file mode 100644
index 2d8db51b9..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowColorMatrix.java
+++ /dev/null
@@ -1,70 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.graphics.ColorMatrix;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.util.Join;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-
-@SuppressWarnings({"UnusedDeclaration"})
-@Implements(ColorMatrix.class)
-public class ShadowColorMatrix {
-
- private float[] src;
-
- public void __constructor__(float[] src) {
- this.src = src;
- }
-
- public void __constructor__() {
- reset();
- }
-
- public void __constructor__(ColorMatrix src) {
- this.src = shadowOf(src).src;
- }
-
- @Implementation
- public void reset() {
- src = new float[20];
- src[0] = src[6] = src[12] = src[18] = 1;
- }
-
- @Implementation
- public void setSaturation(float sat) {
- reset();
- float[] m = src;
-
- final float invSat = 1 - sat;
- final float R = 0.213f * invSat;
- final float G = 0.715f * invSat;
- final float B = 0.072f * invSat;
-
- m[0] = R + sat;
- m[1] = G;
- m[2] = B;
-
- m[5] = R;
- m[6] = G + sat;
- m[7] = B;
-
- m[10] = R;
- m[11] = G;
- m[12] = B + sat;
- }
-
- @Override @Implementation
- public String toString() {
- List<String> floats = new ArrayList<String>();
- for (float f : src) {
- String format = String.format("%.2f", f);
- format = format.replace(".00", "");
- floats.add(format);
- }
- return Join.join(",", floats);
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowColorMatrixColorFilter.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowColorMatrixColorFilter.java
deleted file mode 100644
index 2090dca84..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowColorMatrixColorFilter.java
+++ /dev/null
@@ -1,27 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.graphics.ColorMatrix;
-import android.graphics.ColorMatrixColorFilter;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-@SuppressWarnings({"UnusedDeclaration"})
-@Implements(ColorMatrixColorFilter.class)
-public class ShadowColorMatrixColorFilter {
- private ColorMatrix matrix;
-
- @Implementation
- public void __constructor__(ColorMatrix matrix) {
- this.matrix = matrix;
- }
-
- @Implementation
- public void __constructor__(float[] array) {
- this.matrix = new ColorMatrix(array);
- }
-
- @Override @Implementation
- public String toString() {
- return "ColorMatrixColorFilter<" + matrix + ">";
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowColorStateList.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowColorStateList.java
deleted file mode 100644
index 012c45738..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowColorStateList.java
+++ /dev/null
@@ -1,14 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.content.res.ColorStateList;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-@SuppressWarnings({"UnusedDeclaration"})
-@Implements(ColorStateList.class)
-public class ShadowColorStateList {
- @Implementation
- public static ColorStateList valueOf(int color) {
- return new ColorStateList(null, null);
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowComponentName.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowComponentName.java
deleted file mode 100644
index 882766c3a..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowComponentName.java
+++ /dev/null
@@ -1,107 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.content.ComponentName;
-import android.content.Context;
-import android.os.Parcel;
-
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf_;
-
-/**
- * Shadows the {@code android.content.ComponentName} class.
- * <p/>
- * Just keeps track of the package and class names, and then gives them back when you ask for them.
- */
-@SuppressWarnings({"UnusedDeclaration"})
-@Implements(ComponentName.class)
-public class ShadowComponentName {
- private String pkg;
- private String cls;
-
- public void __constructor__(String pkg, String cls) {
- if (pkg == null) throw new NullPointerException("package name is null");
- if (cls == null) throw new NullPointerException("class name is null");
- this.pkg = pkg;
- this.cls = cls;
- }
-
- public void __constructor__(Context pkg, String cls) {
- if (cls == null) throw new NullPointerException("class name is null");
- this.pkg = pkg.getPackageName();
- this.cls = cls;
- }
-
- public void __constructor__(Context pkg, Class<?> cls) {
- this.pkg = pkg.getPackageName();
- this.cls = cls.getName();
- }
-
- @Implementation
- public String getPackageName() {
- return pkg;
- }
-
- @Implementation
- public String getClassName() {
- return cls;
- }
-
- @Implementation
- public static ComponentName readFromParcel(Parcel in) {
- if (in.readInt() == 0) {
- return null;
- }
- String pkg = in.readString();
- String cls = in.readString();
- return new ComponentName(pkg, cls);
- }
-
- @Implementation
- public void writeToParcel(Parcel out, int flags) {
- out.writeInt(1);
- out.writeString(pkg);
- out.writeString(cls);
- }
-
- @Implementation
- public static void writeToParcel(ComponentName c, Parcel out) {
- if (c == null) {
- out.writeInt(0);
- } else {
- c.writeToParcel(out, 0);
- }
- }
-
- @Override @Implementation
- public boolean equals(Object o) {
- if (o == null) return false;
- o = shadowOf_(o);
- if (o == null) return false;
- if (this == o) return true;
- if (getClass() != o.getClass()) return false;
-
- ShadowComponentName that = (ShadowComponentName) o;
-
- if (cls != null ? !cls.equals(that.cls) : that.cls != null) return false;
- if (pkg != null ? !pkg.equals(that.pkg) : that.pkg != null) return false;
-
- return true;
- }
-
- @Override @Implementation
- public int hashCode() {
- int result = pkg != null ? pkg.hashCode() : 0;
- result = 31 * result + (cls != null ? cls.hashCode() : 0);
- return result;
- }
-
- @Override @Implementation
- public String toString() {
- return "ComponentName{" +
- "pkg='" + pkg + '\'' +
- ", cls='" + cls + '\'' +
- '}';
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowCompoundButton.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowCompoundButton.java
deleted file mode 100644
index e00dca55b..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowCompoundButton.java
+++ /dev/null
@@ -1,58 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.widget.Checkable;
-import android.widget.CompoundButton;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-/**
- * Shadows the {@code android.widget.CompoundButton} class.
- * <p/>
- * Keeps track of whether or not its "checked" state is set and deals with listeners in an appropriate way.
- */
-@SuppressWarnings({"UnusedDeclaration"})
-@Implements(CompoundButton.class)
-public class ShadowCompoundButton extends ShadowTextView implements Checkable {
- private boolean checked;
- private CompoundButton.OnCheckedChangeListener onCheckedChangeListener;
-
- @Override public void applyAttributes() {
- super.applyAttributes();
- setChecked(this.attributeSet.getAttributeBooleanValue("android", "checked", false));
- }
-
- @Implementation
- @Override public void toggle() {
- setChecked(!checked);
- }
-
- @Implementation
- @Override public boolean performClick() {
- toggle();
- return super.performClick();
- }
-
- @Implementation
- @Override public boolean isChecked() {
- return checked;
- }
-
- @Implementation
- @Override public void setChecked(boolean checked) {
- if (this.checked != checked) {
- this.checked = checked;
- if (onCheckedChangeListener != null) {
- onCheckedChangeListener.onCheckedChanged((CompoundButton) realView, this.checked);
- }
- }
- }
-
- @Implementation
- public void setOnCheckedChangeListener(CompoundButton.OnCheckedChangeListener listener) {
- onCheckedChangeListener = listener;
- }
-
- public CompoundButton.OnCheckedChangeListener getOnCheckedChangeListener() {
- return onCheckedChangeListener;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowConfiguration.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowConfiguration.java
deleted file mode 100644
index e94e2e7b2..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowConfiguration.java
+++ /dev/null
@@ -1,30 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import java.util.Locale;
-
-import android.content.res.Configuration;
-
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.internal.RealObject;
-
-@Implements(Configuration.class)
-public class ShadowConfiguration {
-
- @RealObject
- private Configuration realConfiguration;
-
- public int screenLayout;
- public int touchscreen;
- public int orientation;
-
- @Implementation
- public void setToDefaults() {
- realConfiguration.screenLayout = Configuration.SCREENLAYOUT_LONG_NO |
- Configuration.SCREENLAYOUT_SIZE_NORMAL;
- }
-
- public void setLocale( Locale l ) {
- realConfiguration.locale = l;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowConnectivityManager.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowConnectivityManager.java
deleted file mode 100644
index f3c1548a0..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowConnectivityManager.java
+++ /dev/null
@@ -1,64 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.net.ConnectivityManager;
-import android.net.NetworkInfo;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-import java.util.HashMap;
-import java.util.Map;
-
-/**
- * Shadow of {@code ConnectivityManager} that provides for the simulation of
- * the active connection status.
- */
-
-@Implements(ConnectivityManager.class)
-public class ShadowConnectivityManager {
-
- private NetworkInfo activeNetwork;
- private boolean backgroundDataSetting;
-
- private Map<Integer, NetworkInfo> networkTypeToNetworkInfo = new HashMap<Integer, NetworkInfo>();
-
- public void __constructor__() {
- setActiveNetworkInfo(ShadowNetworkInfo.newInstance());
- }
-
- @Implementation
- public NetworkInfo getActiveNetworkInfo() {
- return activeNetwork;
- }
-
- @Implementation
- public NetworkInfo[] getAllNetworkInfo() {
- return networkTypeToNetworkInfo.values().toArray(new NetworkInfo[networkTypeToNetworkInfo.size()]);
- }
-
- @Implementation
- public NetworkInfo getNetworkInfo(int networkType) {
- return networkTypeToNetworkInfo.get(networkType);
- }
-
- @Implementation
- public boolean getBackgroundDataSetting() {
- return backgroundDataSetting;
- }
-
- public void setNetworkInfo(int networkType, NetworkInfo networkInfo) {
- networkTypeToNetworkInfo.put(networkType, networkInfo);
- }
-
- public void setBackgroundDataSetting(boolean b) {
- backgroundDataSetting = b;
- }
-
- public void setActiveNetworkInfo(NetworkInfo info) {
- activeNetwork = info;
- if (info != null) {
- networkTypeToNetworkInfo.put(info.getType(), info);
- } else {
- networkTypeToNetworkInfo.clear();
- }
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowContentProvider.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowContentProvider.java
deleted file mode 100644
index 700fbae3e..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowContentProvider.java
+++ /dev/null
@@ -1,18 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.content.ContentProvider;
-import android.content.Context;
-
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-@Implements(ContentProvider.class)
-public class ShadowContentProvider {
-
- @Implementation
- public final Context getContext() {
- return Robolectric.application;
- }
-
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowContentProviderOperation.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowContentProviderOperation.java
deleted file mode 100644
index 73cee46bc..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowContentProviderOperation.java
+++ /dev/null
@@ -1,99 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import android.content.ContentProviderOperation;
-import android.content.ContentProviderOperation.Builder;
-import android.net.Uri;
-
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-@Implements(ContentProviderOperation.class)
-public class ShadowContentProviderOperation {
- private final Map<String, Object> values = new HashMap<String, Object>();
- private final Map<String, String[]> selections = new HashMap<String, String[]>();
- private final Map<String, Integer> withValueBackReferences = new HashMap<String, Integer>();
- private Uri uri;
- private boolean isInsert;
- private boolean isUpdate;
- private boolean isDelete;
-
- @Implementation
- public static Builder newInsert(Uri uri) {
- Builder builder = Robolectric.newInstanceOf(Builder.class);
- ShadowContentProviderOperationBuilder shadowBuilder = Robolectric.shadowOf(builder);
- shadowBuilder.setUri(uri);
- shadowBuilder.setInsert(true);
- return builder;
- }
-
- @Implementation
- public static Builder newUpdate(Uri uri) {
- Builder builder = Robolectric.newInstanceOf(Builder.class);
- ShadowContentProviderOperationBuilder shadowBuilder = Robolectric.shadowOf(builder);
- shadowBuilder.setUri(uri);
- shadowBuilder.setUpdate(true);
- return builder;
- }
-
- @Implementation
- public static Builder newDelete(Uri uri) {
- Builder builder = Robolectric.newInstanceOf(Builder.class);
- ShadowContentProviderOperationBuilder shadowBuilder = Robolectric.shadowOf(builder);
- shadowBuilder.setUri(uri);
- shadowBuilder.setDelete(true);
- return builder;
- }
-
- @Implementation
- public Uri getUri() {
- return uri;
- }
-
- public void setUri(Uri uri) {
- this.uri = uri;
- }
-
- public Map<String, Object> getValues() {
- return values;
- }
-
- public Map<String, String[]> getSelections() {
- return selections;
- }
-
- public boolean isInsert() {
- return isInsert;
- }
-
- public void setInsert(boolean value) {
- isInsert = value;
- }
-
- public boolean isUpdate() {
- return isUpdate;
- }
-
- public void setUpdate(boolean value) {
- isUpdate = value;
- }
-
- public boolean isDelete() {
- return isDelete;
- }
-
- public void setDelete(boolean value) {
- isDelete = value;
- }
-
- public void setWithValueBackReference(String key, int previousResult) {
- withValueBackReferences.put(key, previousResult);
- }
-
- public int getWithValueBackReference(String key) {
- return withValueBackReferences.get(key);
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowContentProviderOperationBuilder.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowContentProviderOperationBuilder.java
deleted file mode 100644
index 2f69a8cd9..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowContentProviderOperationBuilder.java
+++ /dev/null
@@ -1,91 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import java.util.Map;
-
-import android.content.ContentProviderOperation;
-import android.content.ContentProviderOperation.Builder;
-import android.net.Uri;
-
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.internal.RealObject;
-
-@Implements(ContentProviderOperation.Builder.class)
-public class ShadowContentProviderOperationBuilder {
- @RealObject private Builder realBuilder;
- private ContentProviderOperation contentProviderOperation;
- private ShadowContentProviderOperation shadowContentProviderOperation;
-
- public void __constructor__() {
- contentProviderOperation = Robolectric.newInstanceOf(ContentProviderOperation.class);
- shadowContentProviderOperation = Robolectric.shadowOf(contentProviderOperation);
- }
-
- @Implementation
- public Builder withValue(String key, Object value) {
- shadowContentProviderOperation.getValues().put(key, value);
- return realBuilder;
- }
-
- @Implementation
- public Builder withSelection(String selection, String[] selectionArgs) {
- shadowContentProviderOperation.getSelections().put(selection, selectionArgs);
- return realBuilder;
- }
-
- @Implementation
- public Builder withValueBackReference(String key, int previousResult) {
- shadowContentProviderOperation.setWithValueBackReference(key, previousResult);
- return realBuilder;
- }
-
- @Implementation
- public ContentProviderOperation build() {
- return contentProviderOperation;
- }
-
- public Uri getUri() {
- return shadowContentProviderOperation.getUri();
- }
-
- public void setUri(Uri uri) {
- shadowContentProviderOperation.setUri(uri);
- }
-
- public Map<String, Object> getValues() {
- return shadowContentProviderOperation.getValues();
- }
-
- public Map<String, String[]> getSelections() {
- return shadowContentProviderOperation.getSelections();
- }
-
- public boolean isInsert() {
- return shadowContentProviderOperation.isInsert();
- }
-
- public void setInsert(boolean value) {
- shadowContentProviderOperation.setInsert(value);
- }
-
- public boolean isUpdate() {
- return shadowContentProviderOperation.isUpdate();
- }
-
- public void setUpdate(boolean value) {
- shadowContentProviderOperation.setUpdate(value);
- }
-
- public boolean isDelete() {
- return shadowContentProviderOperation.isDelete();
- }
-
- public void setDelete(boolean value) {
- shadowContentProviderOperation.setDelete(value);
- }
-
- public int getWithValueBackReference(String key) {
- return shadowContentProviderOperation.getWithValueBackReference(key);
- }
-} \ No newline at end of file
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowContentProviderResult.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowContentProviderResult.java
deleted file mode 100644
index cf9e9236c..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowContentProviderResult.java
+++ /dev/null
@@ -1,26 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import java.lang.reflect.Field;
-
-import android.content.ContentProviderResult;
-import android.net.Uri;
-
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.internal.RealObject;
-
-@Implements(ContentProviderResult.class)
-public class ShadowContentProviderResult {
- @RealObject ContentProviderResult realResult;
-
- public void __constructor__(Uri uri) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
- Field field = realResult.getClass().getField("uri");
- field.setAccessible(true);
- field.set(realResult, uri);
- }
-
- public void __constructor__(int count) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
- Field field = realResult.getClass().getField("count");
- field.setAccessible(true);
- field.set(realResult, count);
- }
-} \ No newline at end of file
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowContentResolver.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowContentResolver.java
deleted file mode 100644
index 8c5e4bde2..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowContentResolver.java
+++ /dev/null
@@ -1,415 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.accounts.Account;
-import android.content.*;
-import android.database.ContentObserver;
-import android.database.Cursor;
-import android.net.Uri;
-import android.os.Bundle;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.tester.android.database.TestCursor;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.util.*;
-
-@Implements(ContentResolver.class)
-public class ShadowContentResolver {
- private int nextDatabaseIdForInserts;
- private int nextDatabaseIdForUpdates;
-
- private TestCursor cursor;
- private final List<InsertStatement> insertStatements = new ArrayList<InsertStatement>();
- private final List<UpdateStatement> updateStatements = new ArrayList<UpdateStatement>();
- private final List<DeleteStatement> deleteStatements = new ArrayList<DeleteStatement>();
- private List<NotifiedUri> notifiedUris = new ArrayList<NotifiedUri>();
- private HashMap<Uri, TestCursor> uriCursorMap = new HashMap<Uri, TestCursor>();
- private final Map<String, ArrayList<ContentProviderOperation>> contentProviderOperations = new HashMap<String, ArrayList<ContentProviderOperation>>();
- private ContentProviderResult[] contentProviderResults;
-
- private static final Map<String, Map<Account, Status>> syncableAccounts =
- new HashMap<String, Map<Account, Status>>();
- private static final Map<String, ContentProvider> providers = new HashMap<String, ContentProvider>();
- private static boolean masterSyncAutomatically;
-
- public static void reset() {
- syncableAccounts.clear();
- providers.clear();
- masterSyncAutomatically = false;
- }
-
- public static class NotifiedUri {
- public final Uri uri;
- public final boolean syncToNetwork;
- public final ContentObserver observer;
-
- public NotifiedUri(Uri uri, ContentObserver observer, boolean syncToNetwork) {
- this.uri = uri;
- this.syncToNetwork = syncToNetwork;
- this.observer = observer;
- }
- }
-
- public static class Status {
- public int syncRequests;
- public int state = -1;
- public boolean syncAutomatically;
- public Bundle syncExtras;
- public List<PeriodicSync> syncs = new ArrayList<PeriodicSync>();
- }
-
- @Implementation
- public final InputStream openInputStream(final Uri uri) {
- return new InputStream() {
- @Override
- public int read() throws IOException {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public String toString() {
- return "stream for " + uri;
- }
- };
- }
-
- @Implementation
- public final OutputStream openOutputStream(final Uri uri) {
- return new OutputStream() {
-
- @Override
- public void write(int arg0) throws IOException {
- }
-
- @Override
- public String toString() {
- return "outputstream for " + uri;
- }
- };
- }
-
- @Implementation
- public final Uri insert(Uri url, ContentValues values) {
- ContentProvider provider = getProvider(url);
- if (provider != null) {
- return provider.insert(url, values);
- } else {
- InsertStatement insertStatement = new InsertStatement(url, new ContentValues(values));
- insertStatements.add(insertStatement);
- return Uri.parse(url.toString() + "/" + nextDatabaseIdForInserts++);
- }
- }
-
- @Implementation
- public int update(Uri uri, ContentValues values, String where, String[] selectionArgs) {
- ContentProvider provider = getProvider(uri);
- if (provider != null) {
- return provider.update(uri, values, where, selectionArgs);
- } else {
- UpdateStatement updateStatement = new UpdateStatement(uri, new ContentValues(values), where, selectionArgs);
- updateStatements.add(updateStatement);
- return nextDatabaseIdForUpdates++;
- }
- }
-
- @Implementation
- public final Cursor query(Uri uri, String[] projection, String selection,
- String[] selectionArgs, String sortOrder) {
- ContentProvider provider = getProvider(uri);
- if (provider != null) {
- return provider.query(uri, projection, selection, selectionArgs, sortOrder);
- } else {
- TestCursor returnCursor = getCursor(uri);
- if (returnCursor == null) {
- return null;
- }
-
- returnCursor.setQuery(uri, projection, selection, selectionArgs,
- sortOrder);
- return returnCursor;
- }
- }
-
- @Implementation
- public final int delete(Uri url, String where, String[] selectionArgs) {
- ContentProvider provider = getProvider(url);
- if (provider != null) {
- return provider.delete(url, where, selectionArgs);
- } else {
- DeleteStatement deleteStatement = new DeleteStatement(url, where, selectionArgs);
- deleteStatements.add(deleteStatement);
- return 1;
- }
- }
-
- @Implementation
- public final int bulkInsert(Uri url, ContentValues[] values) {
- ContentProvider provider = getProvider(url);
- if (provider != null) {
- return provider.bulkInsert(url, values);
- } else {
- return 0;
- }
- }
-
- @Implementation
- public void notifyChange(Uri uri, ContentObserver observer, boolean syncToNetwork) {
- notifiedUris.add(new NotifiedUri(uri, observer, syncToNetwork));
- }
-
- @Implementation
- public void notifyChange(Uri uri, ContentObserver observer) {
- notifyChange(uri, observer, false);
- }
-
- @Implementation
- public ContentProviderResult[] applyBatch(String authority, ArrayList<ContentProviderOperation> operations) {
- contentProviderOperations.put(authority, operations);
- return contentProviderResults;
- }
-
- @Implementation
- public static void requestSync(Account account, String authority, Bundle extras) {
- validateSyncExtrasBundle(extras);
- Status status = getStatus(account, authority, true);
- status.syncRequests++;
- status.syncExtras = extras;
- }
-
- @Implementation
- public static void setIsSyncable(Account account, String authority, int syncable) {
- getStatus(account, authority, true).state = syncable;
- }
-
- @Implementation
- public static int getIsSyncable(Account account, String authority) {
- return getStatus(account, authority, true).state;
- }
-
- @Implementation
- public static boolean getSyncAutomatically(Account account, String authority) {
- return getStatus(account, authority, true).syncAutomatically;
- }
-
- @Implementation
- public static void setSyncAutomatically(Account account, String authority, boolean sync) {
- getStatus(account, authority, true).syncAutomatically = sync;
- }
-
- @Implementation
- public static void addPeriodicSync(Account account, String authority, Bundle extras,
- long pollFrequency) {
-
- validateSyncExtrasBundle(extras);
- getStatus(account, authority, true).syncs.add(new PeriodicSync(account, authority, extras, pollFrequency));
- }
-
- @Implementation
- public static void removePeriodicSync(Account account, String authority, Bundle extras) {
- validateSyncExtrasBundle(extras);
- Status status = getStatus(account, authority);
- if (status != null) status.syncs.clear();
- }
-
- @Implementation
- public static List<PeriodicSync> getPeriodicSyncs(Account account, String authority) {
- return getStatus(account, authority, true).syncs;
- }
-
- @Implementation
- public static void validateSyncExtrasBundle(Bundle extras) {
- for (String key : extras.keySet()) {
- Object value = extras.get(key);
- if (value == null) continue;
- if (value instanceof Long) continue;
- if (value instanceof Integer) continue;
- if (value instanceof Boolean) continue;
- if (value instanceof Float) continue;
- if (value instanceof Double) continue;
- if (value instanceof String) continue;
- if (value instanceof Account) continue;
- throw new IllegalArgumentException("unexpected value type: "
- + value.getClass().getName());
- }
- }
-
- @Implementation
- public static void setMasterSyncAutomatically(boolean sync) {
- masterSyncAutomatically = sync;
-
- }
-
- @Implementation
- public static boolean getMasterSyncAutomatically() {
- return masterSyncAutomatically;
- }
-
-
- public static ContentProvider getProvider(Uri uri) {
- if (uri == null) {
- return null;
- } else if (!ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
- return null;
- } else {
- return providers.get(uri.getAuthority());
- }
- }
-
- public static void registerProvider(String authority, ContentProvider provider) {
- providers.put(authority, provider);
- }
-
- public static Status getStatus(Account account, String authority) {
- return getStatus(account, authority, false);
- }
-
- public static Status getStatus(Account account, String authority, boolean create) {
- Map<Account, Status> map = syncableAccounts.get(authority);
- if (map == null) {
- map = new HashMap<Account, Status>();
- syncableAccounts.put(authority, map);
- }
- Status status = map.get(account);
- if (status == null && create) {
- status = new Status();
- map.put(account, status);
- }
- return status;
- }
-
- public void setCursor(TestCursor cursor) {
- this.cursor = cursor;
- }
-
- public void setCursor(Uri uri, TestCursor cursorForUri) {
- this.uriCursorMap.put(uri, cursorForUri);
- }
-
- public void setNextDatabaseIdForInserts(int nextId) {
- nextDatabaseIdForInserts = nextId;
- }
-
- public void setNextDatabaseIdForUpdates(int nextId) {
- nextDatabaseIdForUpdates = nextId;
- }
-
- public List<InsertStatement> getInsertStatements() {
- return insertStatements;
- }
-
- public List<UpdateStatement> getUpdateStatements() {
- return updateStatements;
- }
-
- public List<Uri> getDeletedUris() {
- List<Uri> uris = new ArrayList<Uri>();
- for (DeleteStatement deleteStatement : deleteStatements) {
- uris.add(deleteStatement.getUri());
- }
- return uris;
- }
-
- public List<DeleteStatement> getDeleteStatements() {
- return deleteStatements;
- }
-
- public List<NotifiedUri> getNotifiedUris() {
- return notifiedUris;
- }
-
- public ArrayList<ContentProviderOperation> getContentProviderOperations(String authority) {
- ArrayList<ContentProviderOperation> operations = contentProviderOperations.get(authority);
- if (operations == null)
- return new ArrayList<ContentProviderOperation>();
- return operations;
- }
-
-
- public void setContentProviderResult(ContentProviderResult[] contentProviderResults) {
- this.contentProviderResults = contentProviderResults;
- }
-
- private TestCursor getCursor(Uri uri) {
- if (uriCursorMap.get(uri) != null) {
- return uriCursorMap.get(uri);
- } else if (cursor != null) {
- return cursor;
- } else {
- return null;
- }
- }
-
- public static class InsertStatement {
- private final Uri uri;
- private final ContentValues contentValues;
-
- public InsertStatement(Uri uri, ContentValues contentValues) {
- this.uri = uri;
- this.contentValues = contentValues;
- }
-
- public Uri getUri() {
- return uri;
- }
-
- public ContentValues getContentValues() {
- return contentValues;
- }
- }
-
- public static class UpdateStatement {
- private final Uri uri;
- private final ContentValues values;
- private final String where;
- private final String[] selectionArgs;
-
- public UpdateStatement(Uri uri, ContentValues values, String where, String[] selectionArgs) {
- this.uri = uri;
- this.values = values;
- this.where = where;
- this.selectionArgs = selectionArgs;
- }
-
- public Uri getUri() {
- return uri;
- }
-
- public ContentValues getContentValues() {
- return values;
- }
-
- public String getWhere() {
- return where;
- }
-
- public String[] getSelectionArgs() {
- return selectionArgs;
- }
- }
-
- public static class DeleteStatement {
- private final Uri uri;
- private final String where;
- private final String[] selectionArgs;
-
- public DeleteStatement(Uri uri, String where, String[] selectionArgs) {
- this.uri = uri;
- this.where = where;
- this.selectionArgs = selectionArgs;
- }
-
- public Uri getUri() {
- return uri;
- }
-
- public String getWhere() {
- return where;
- }
-
- public String[] getSelectionArgs() {
- return selectionArgs;
- }
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowContentUris.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowContentUris.java
deleted file mode 100644
index fce641ed7..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowContentUris.java
+++ /dev/null
@@ -1,27 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.content.ContentUris;
-import android.net.Uri;
-
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-@Implements(ContentUris.class)
-public class ShadowContentUris {
-
- @Implementation
- public static Uri withAppendedId(Uri contentUri, long id) {
- return Uri.withAppendedPath(contentUri, String.valueOf(id));
- }
-
- @Implementation
- public static long parseId(Uri contentUri) {
- if (!contentUri.isHierarchical()) {
- throw new UnsupportedOperationException();
- }
- String path = contentUri.getLastPathSegment();
- if (path == null) return -1;
- return Long.parseLong(path);
- }
-
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowContentValues.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowContentValues.java
deleted file mode 100644
index 0c2bf1c05..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowContentValues.java
+++ /dev/null
@@ -1,316 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.xtremelabs.robolectric.shadows;
-
-import android.content.ContentValues;
-import android.util.Log;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Set;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-import static com.xtremelabs.robolectric.Robolectric.shadowOf_;
-
-/**
- * Shadows the {@code android.content.ContentValues} class.
- * <p/>
- * This is a fancy map from String to... something. Works just like the Android class it shadows.
- */
-@SuppressWarnings({"UnusedDeclaration"})
-@Implements(ContentValues.class)
-public final class ShadowContentValues {
- private static final String TAG = "ShadowContentValues";
- private HashMap<String, Object> values = new HashMap<String, Object>();
-
- public void __constructor__(ContentValues from) {
- values = new HashMap<String, Object>(shadowOf(from).values);
- }
-
- @Implementation
- public void put(String key, String value) {
- values.put(key, value);
- }
-
- @Implementation
- public void putAll(ContentValues other) {
- values.putAll(shadowOf(other).values);
- }
-
- @Implementation
- public void put(String key, Byte value) {
- values.put(key, value);
- }
-
- @Implementation
- public void put(String key, Short value) {
- values.put(key, value);
- }
-
- @Implementation
- public void put(String key, Integer value) {
- values.put(key, value);
- }
-
- @Implementation
- public void put(String key, Long value) {
- values.put(key, value);
- }
-
- @Implementation
- public void put(String key, Float value) {
- values.put(key, value);
- }
-
- @Implementation
- public void put(String key, Double value) {
- values.put(key, value);
- }
-
- @Implementation
- public void put(String key, Boolean value) {
- values.put(key, value);
- }
-
- @Implementation
- public void put(String key, byte[] value) {
- values.put(key, value);
- }
-
- @Implementation
- public void putNull(String key) {
- values.put(key, null);
- }
-
- @Implementation
- public int size() {
- return values.size();
- }
-
- @Implementation
- public void remove(String key) {
- values.remove(key);
- }
-
- @Implementation
- public void clear() {
- values.clear();
- }
-
- @Implementation
- public boolean containsKey(String key) {
- return values.containsKey(key);
- }
-
- @Implementation
- public Object get(String key) {
- return values.get(key);
- }
-
- @Implementation
- public String getAsString(String key) {
- Object value = values.get(key);
- return value != null ? value.toString() : null;
- }
-
- @Implementation
- public Long getAsLong(String key) {
- Object value = values.get(key);
- try {
- return value != null ? ((Number) value).longValue() : null;
- } catch (ClassCastException e) {
- if (value instanceof CharSequence) {
- try {
- return Long.valueOf(value.toString());
- } catch (NumberFormatException e2) {
- Log.e(TAG, "Cannot parse Long value for " + value + " at key " + key);
- return null;
- }
- } else {
- Log.e(TAG, "Cannot cast value for " + key + " to a Long: " + value, e);
- return null;
- }
- }
- }
-
- @Implementation
- public Integer getAsInteger(String key) {
- Object value = values.get(key);
- try {
- return value != null ? ((Number) value).intValue() : null;
- } catch (ClassCastException e) {
- if (value instanceof CharSequence) {
- try {
- return Integer.valueOf(value.toString());
- } catch (NumberFormatException e2) {
- Log.e(TAG, "Cannot parse Integer value for " + value + " at key " + key);
- return null;
- }
- } else {
- Log.e(TAG, "Cannot cast value for " + key + " to a Integer: " + value, e);
- return null;
- }
- }
- }
-
- @Implementation
- public Short getAsShort(String key) {
- Object value = values.get(key);
- try {
- return value != null ? ((Number) value).shortValue() : null;
- } catch (ClassCastException e) {
- if (value instanceof CharSequence) {
- try {
- return Short.valueOf(value.toString());
- } catch (NumberFormatException e2) {
- Log.e(TAG, "Cannot parse Short value for " + value + " at key " + key);
- return null;
- }
- } else {
- Log.e(TAG, "Cannot cast value for " + key + " to a Short: " + value, e);
- return null;
- }
- }
- }
-
- @Implementation
- public Byte getAsByte(String key) {
- Object value = values.get(key);
- try {
- return value != null ? ((Number) value).byteValue() : null;
- } catch (ClassCastException e) {
- if (value instanceof CharSequence) {
- try {
- return Byte.valueOf(value.toString());
- } catch (NumberFormatException e2) {
- Log.e(TAG, "Cannot parse Byte value for " + value + " at key " + key);
- return null;
- }
- } else {
- Log.e(TAG, "Cannot cast value for " + key + " to a Byte: " + value, e);
- return null;
- }
- }
- }
-
- @Implementation
- public Double getAsDouble(String key) {
- Object value = values.get(key);
- try {
- return value != null ? ((Number) value).doubleValue() : null;
- } catch (ClassCastException e) {
- if (value instanceof CharSequence) {
- try {
- return Double.valueOf(value.toString());
- } catch (NumberFormatException e2) {
- Log.e(TAG, "Cannot parse Double value for " + value + " at key " + key);
- return null;
- }
- } else {
- Log.e(TAG, "Cannot cast value for " + key + " to a Double: " + value, e);
- return null;
- }
- }
- }
-
- @Implementation
- public Float getAsFloat(String key) {
- Object value = values.get(key);
- try {
- return value != null ? ((Number) value).floatValue() : null;
- } catch (ClassCastException e) {
- if (value instanceof CharSequence) {
- try {
- return Float.valueOf(value.toString());
- } catch (NumberFormatException e2) {
- Log.e(TAG, "Cannot parse Float value for " + value + " at key " + key);
- return null;
- }
- } else {
- Log.e(TAG, "Cannot cast value for " + key + " to a Float: " + value, e);
- return null;
- }
- }
- }
-
- @Implementation
- public Boolean getAsBoolean(String key) {
- Object value = values.get(key);
- try {
- return (Boolean) value;
- } catch (ClassCastException e) {
- if (value instanceof CharSequence) {
- return Boolean.valueOf(value.toString());
- } else {
- Log.e(TAG, "Cannot cast value for " + key + " to a Boolean: " + value, e);
- return null;
- }
- }
- }
-
- @Implementation
- public byte[] getAsByteArray(String key) {
- Object value = values.get(key);
- if (value instanceof byte[]) {
- return (byte[]) value;
- } else {
- return null;
- }
- }
-
- @Implementation
- public Set<Map.Entry<String, Object>> valueSet() {
- return values.entrySet();
- }
-
- @Implementation
- public int describeContents() {
- return 0;
- }
-
- @Override @Implementation
- public boolean equals(Object object) {
- if (object == null) return false;
- Object o = shadowOf_(object);
- if (o == null) return false;
- if (this == o) return true;
- if (getClass() != o.getClass()) return false;
-
- if (!(o instanceof ContentValues)) {
- return false;
- }
- return values.equals(shadowOf((ContentValues) o).values);
- }
-
- @Override @Implementation
- public int hashCode() {
- return values.hashCode();
- }
-
- @Override @Implementation
- public String toString() {
- StringBuilder sb = new StringBuilder();
- for (String name : values.keySet()) {
- String value = getAsString(name);
- if (sb.length() > 0) sb.append(" ");
- sb.append(name + "=" + value);
- }
- return sb.toString();
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowContext.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowContext.java
deleted file mode 100644
index 23a978903..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowContext.java
+++ /dev/null
@@ -1,177 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.app.Application;
-import android.content.Context;
-import android.content.res.Resources;
-import android.content.res.TypedArray;
-import android.util.AttributeSet;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.internal.RealObject;
-import com.xtremelabs.robolectric.res.ResourceLoader;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.io.IOException;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-
-/**
- * Calls through to the {@code resourceLoader} to actually load resources.
- */
-@SuppressWarnings({"UnusedDeclaration"})
-@Implements(Context.class)
-abstract public class ShadowContext {
- public static final File CACHE_DIR = createTempDir("android-cache");
- public static final File EXTERNAL_CACHE_DIR = createTempDir("android-external-cache");
- public static final File FILES_DIR = createTempDir("android-tmp");
- public static final File EXTERNAL_FILES_DIR = createTempDir("android-external-files");
-
- @RealObject private Context realContext;
-
- @Implementation
- public File getDir(String name, int mode) {
- // TODO: honor operating mode.
- File file = new File(FILES_DIR, name);
- if (!file.exists()) {
- file.mkdir();
- }
- return file;
- }
-
- @Implementation
- public String getString(int resId) {
- return realContext.getResources().getString(resId);
- }
-
- @Implementation
- public CharSequence getText(int resId) {
- return realContext.getResources().getText(resId);
- }
-
- @Implementation
- public String getString(int resId, Object... formatArgs) {
- return realContext.getResources().getString(resId, formatArgs);
- }
-
- @Implementation
- abstract public Resources.Theme getTheme();
-
- @Implementation
- public final TypedArray obtainStyledAttributes(
- int[] attrs) {
- return getTheme().obtainStyledAttributes(attrs);
- }
-
- @Implementation
- public final TypedArray obtainStyledAttributes(
- int resid, int[] attrs) throws Resources.NotFoundException {
- return getTheme().obtainStyledAttributes(resid, attrs);
- }
-
- @Implementation
- public final TypedArray obtainStyledAttributes(
- AttributeSet set, int[] attrs) {
- return getTheme().obtainStyledAttributes(set, attrs, 0, 0);
- }
-
- @Implementation
- public final TypedArray obtainStyledAttributes(
- AttributeSet set, int[] attrs, int defStyleAttr, int defStyleRes) {
- return getTheme().obtainStyledAttributes(
- set, attrs, defStyleAttr, defStyleRes);
- }
-
- @Implementation
- public File getCacheDir() {
- CACHE_DIR.mkdirs();
- return CACHE_DIR;
- }
-
- @Implementation
- public File getFilesDir() {
- FILES_DIR.mkdirs();
- return FILES_DIR;
- }
-
- @Implementation
- public File getExternalCacheDir() {
- EXTERNAL_CACHE_DIR.mkdir();
- return EXTERNAL_CACHE_DIR;
- }
-
- @Implementation
- public File getExternalFilesDir(String type) {
- File f = (type == null) ? EXTERNAL_FILES_DIR : new File( EXTERNAL_FILES_DIR, type );
- f.mkdirs();
- return f;
- }
-
- @Implementation
- public FileInputStream openFileInput(String path) throws FileNotFoundException {
- return new FileInputStream(getFileStreamPath(path));
- }
-
- @Implementation
- public FileOutputStream openFileOutput(String path, int mode) throws FileNotFoundException {
- return new FileOutputStream(getFileStreamPath(path));
- }
-
- @Implementation
- public File getFileStreamPath(String name) {
- if (name.contains(File.separator)) {
- throw new IllegalArgumentException("File " + name + " contains a path separator");
- }
- return new File(getFilesDir(), name);
- }
-
- @Implementation
- public boolean deleteFile(String name) {
- return getFileStreamPath(name).delete();
- }
-
- /**
- * Non-Android accessor.
- *
- * @return the {@code ResourceLoader} associated with this {@code Context}
- */
- public ResourceLoader getResourceLoader() {
- return shadowOf((Application) realContext.getApplicationContext()).getResourceLoader();
- }
-
- public static void clearFilesAndCache() {
- clearFiles(FILES_DIR);
- clearFiles(CACHE_DIR);
- clearFiles(EXTERNAL_CACHE_DIR);
- clearFiles(EXTERNAL_FILES_DIR);
- }
-
- public static void clearFiles(File dir) {
- if (dir != null && dir.isDirectory()) {
- File[] files = dir.listFiles();
- if (files != null) {
- for (File f : files) {
- if (f.isDirectory()) {
- clearFiles(f);
- }
- f.delete();
- }
- }
- }
- }
-
- private static File createTempDir(String name) {
- try {
- File tmp = File.createTempFile(name, "robolectric");
- if (!tmp.delete()) throw new IOException("could not delete "+tmp);
- if (!tmp.mkdirs()) throw new IOException("could not create "+tmp);
- tmp.deleteOnExit();
-
- return tmp;
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowContextThemeWrapper.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowContextThemeWrapper.java
deleted file mode 100644
index 28ae8a489..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowContextThemeWrapper.java
+++ /dev/null
@@ -1,13 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.content.Context;
-import android.view.ContextThemeWrapper;
-import com.xtremelabs.robolectric.internal.Implements;
-
-@SuppressWarnings({"UnusedDeclaration"})
-@Implements(ContextThemeWrapper.class)
-public class ShadowContextThemeWrapper extends ShadowContextWrapper {
- public void __constructor__(Context baseContext, int themesres) {
- super.__constructor__(baseContext);
- }
-} \ No newline at end of file
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowContextWrapper.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowContextWrapper.java
deleted file mode 100644
index 9724e6b41..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowContextWrapper.java
+++ /dev/null
@@ -1,264 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.content.BroadcastReceiver;
-import android.content.ComponentName;
-import android.content.ContentResolver;
-import android.content.Context;
-import android.content.ContextWrapper;
-import android.content.Intent;
-import android.content.IntentFilter;
-import android.content.ServiceConnection;
-import android.content.SharedPreferences;
-import android.content.pm.ApplicationInfo;
-import android.content.pm.PackageManager;
-import android.content.res.AssetManager;
-import android.content.res.Resources;
-import android.os.Looper;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.internal.RealObject;
-import com.xtremelabs.robolectric.tester.android.content.TestSharedPreferences;
-
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-import static android.content.pm.PackageManager.PERMISSION_DENIED;
-import static android.content.pm.PackageManager.PERMISSION_GRANTED;
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-
-@SuppressWarnings({"UnusedDeclaration"})
-@Implements(ContextWrapper.class)
-public class ShadowContextWrapper extends ShadowContext {
- @RealObject private ContextWrapper realContextWrapper;
- protected Context baseContext;
-
- private PackageManager packageManager;
-
- private String appName;
- private String packageName;
- private Set<String> grantedPermissions = new HashSet<String>();
-
- public void __constructor__(Context baseContext) {
- this.baseContext = baseContext;
- }
-
- @Implementation
- public Context getApplicationContext() {
- return baseContext.getApplicationContext();
- }
-
- @Implementation
- public Resources.Theme getTheme() {
- return getResources().newTheme();
- }
-
- @Implementation
- public Resources getResources() {
- return getApplicationContext().getResources();
- }
-
- @Implementation
- public ContentResolver getContentResolver() {
- return getApplicationContext().getContentResolver();
- }
-
- @Implementation
- public Object getSystemService(String name) {
- return getApplicationContext().getSystemService(name);
- }
-
- @Implementation
- public void sendBroadcast(Intent intent) {
- getApplicationContext().sendBroadcast(intent);
- }
-
- public List<Intent> getBroadcastIntents() {
- return ((ShadowApplication) shadowOf(getApplicationContext())).getBroadcastIntents();
- }
-
- @Implementation
- public int checkPermission(java.lang.String permission, int pid, int uid) {
- return grantedPermissions.contains(permission) ? PERMISSION_GRANTED : PERMISSION_DENIED;
- }
-
- @Implementation
- public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter) {
- return ((ShadowApplication) shadowOf(getApplicationContext())).registerReceiverWithContext(receiver, filter, realContextWrapper);
- }
-
- @Implementation
- public void unregisterReceiver(BroadcastReceiver broadcastReceiver) {
- getApplicationContext().unregisterReceiver(broadcastReceiver);
- }
-
- @Implementation
- public String getPackageName() {
- return realContextWrapper == getApplicationContext() ? packageName : getApplicationContext().getPackageName();
- }
-
- @Implementation
- public ApplicationInfo getApplicationInfo() {
- ApplicationInfo appInfo = new ApplicationInfo();
- appInfo.name = appName;
- appInfo.packageName = packageName;
- appInfo.processName = packageName;
- return appInfo;
- }
-
- /**
- * Non-Android accessor to set the application name.
- *
- * @param name
- */
- public void setApplicationName(String name) {
- appName = name;
- }
-
- /**
- * Implements Android's {@code PackageManager}.
- *
- * @return a {@code RobolectricPackageManager}
- */
- @Implementation
- public PackageManager getPackageManager() {
- return realContextWrapper == getApplicationContext() ? packageManager : getApplicationContext().getPackageManager();
- }
-
- @Implementation
- public ComponentName startService(Intent service) {
- return getApplicationContext().startService(service);
- }
-
- @Implementation
- public boolean stopService(Intent name) {
- return getApplicationContext().stopService(name);
- }
-
- @Implementation
- public void startActivity(Intent intent) {
- getApplicationContext().startActivity(intent);
- }
-
- @Implementation
- public SharedPreferences getSharedPreferences(String name, int mode) {
- return new TestSharedPreferences(getShadowApplication().getSharedPreferenceMap(), name, mode);
- }
-
- @Implementation
- public AssetManager getAssets() {
- return getResources().getAssets();
- }
-
- /**
- * Non-Android accessor that delegates to the application to consume and return the next {@code Intent} on the
- * started activities stack.
- *
- * @return the next started {@code Intent} for an activity
- */
- public Intent getNextStartedActivity() {
- return getShadowApplication().getNextStartedActivity();
- }
-
- /**
- * Non-Android accessor that delegates to the application to return (without consuming) the next {@code Intent} on
- * the started activities stack.
- *
- * @return the next started {@code Intent} for an activity
- */
- public Intent peekNextStartedActivity() {
- return getShadowApplication().peekNextStartedActivity();
- }
-
- /**
- * Non-Android accessor that delegates to the application to consume and return the next {@code Intent} on the
- * started services stack.
- *
- * @return the next started {@code Intent} for a service
- */
- public Intent getNextStartedService() {
- return getShadowApplication().getNextStartedService();
- }
-
- /**
- * Non-android accessor that delefates to the application to clear the stack of started
- * service intents.
- */
- public void clearStartedServices() {
- getShadowApplication().clearStartedServices();
- }
-
- /**
- * Return (without consuming) the next {@code Intent} on the started services stack.
- *
- * @return the next started {@code Intent} for a service
- */
- public Intent peekNextStartedService() {
- return getShadowApplication().peekNextStartedService();
- }
-
- /**
- * Non-Android accessor that delegates to the application to return the next {@code Intent} to stop
- * a service (irrespective of if the service was running)
- *
- * @return {@code Intent} for the next service requested to be stopped
- */
- public Intent getNextStoppedService() {
- return getShadowApplication().getNextStoppedService();
- }
-
- /**
- * Non-Android accessor that is used at start-up to set the package name
- *
- * @param packageName the package name
- */
- public void setPackageName(String packageName) {
- this.packageName = packageName;
- }
-
- /**
- * Non-Android accessor that is used at start-up to set the packageManager =
- *
- * @param packageManager the package manager
- */
- public void setPackageManager(PackageManager packageManager) {
- this.packageManager = packageManager;
- }
-
-
- @Implementation
- public Looper getMainLooper() {
- return getShadowApplication().getMainLooper();
- }
-
- @Implementation
- public Context getBaseContext() {
- return baseContext;
- }
-
- @Implementation
- public void attachBaseContext(Context context) {
- baseContext = context;
- }
-
- private ShadowApplication getShadowApplication() {
- return ((ShadowApplication) shadowOf(getApplicationContext()));
- }
-
- @Implementation
- public boolean bindService(Intent intent, final ServiceConnection serviceConnection, int i) {
- return getShadowApplication().bindService(intent, serviceConnection, i);
- }
-
- /**
- * Non-Android accessor that is used to grant permissions checked via
- * {@link android.content.ContextWrapper#checkPermission(String, int, int)}
- *
- * @param permissionNames permission names that should be granted
- */
- public void grantPermissions(String... permissionNames) {
- for (String permissionName : permissionNames) {
- grantedPermissions.add(permissionName);
- }
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowCookieManager.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowCookieManager.java
deleted file mode 100644
index 0a0c24a9a..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowCookieManager.java
+++ /dev/null
@@ -1,53 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.webkit.CookieManager;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-import java.util.HashMap;
-import java.util.Map;
-
-/**
- * Shadows the {@code android.telephony.TelephonyManager} class.
- */
-@SuppressWarnings({"UnusedDeclaration"})
-@Implements(CookieManager.class)
-public class ShadowCookieManager {
- private static CookieManager sRef;
- private Map<String,String> cookies = new HashMap<String, String>();
- private boolean accept;
-
- @Implementation
- public static CookieManager getInstance() {
- if (sRef == null) {
- sRef = Robolectric.newInstanceOf(CookieManager.class);
- }
- return sRef;
- }
-
- @Implementation
- public void setCookie(String url, String value) {
- cookies.put(url, value);
- }
-
- @Implementation
- public String getCookie(String url) {
- return cookies.get(url);
- }
-
- @Implementation
- public void setAcceptCookie(boolean accept) {
- this.accept = accept;
- }
-
- @Implementation
- public boolean acceptCookie() {
- return this.accept;
- }
-
- @Implementation
- public void removeAllCookie() {
- cookies.clear();
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowCookieSyncManager.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowCookieSyncManager.java
deleted file mode 100644
index 2c910c2e3..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowCookieSyncManager.java
+++ /dev/null
@@ -1,48 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.content.Context;
-import android.webkit.CookieSyncManager;
-
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-/**
- * Shadows the {@code android.webkit.CookieSyncManager} class.
- */
-@Implements(CookieSyncManager.class)
-public class ShadowCookieSyncManager {
-
- private static CookieSyncManager sRef;
-
- private boolean synced = false;
-
- @Implementation
- public static synchronized CookieSyncManager createInstance(Context ctx) {
- if (sRef == null) {
- sRef = Robolectric.newInstanceOf(CookieSyncManager.class);
- }
- return sRef;
- }
-
- @Implementation
- public static CookieSyncManager getInstance() {
- if (sRef == null) {
- throw new IllegalStateException("createInstance must be called first");
- }
- return sRef;
- }
-
- @Implementation
- public void sync() {
- synced = true;
- }
-
- public boolean synced() {
- return synced;
- }
-
- public void reset() {
- synced = false;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowCountDownTimer.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowCountDownTimer.java
deleted file mode 100644
index 62ac448d5..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowCountDownTimer.java
+++ /dev/null
@@ -1,61 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.internal.RealObject;
-
-import android.os.CountDownTimer;
-
-@Implements(CountDownTimer.class)
-public class ShadowCountDownTimer {
-
- private boolean started;
- private long countDownInterval;
- private long millisInFuture;
-
- @RealObject CountDownTimer countDownTimer;
-
- public void __constructor__(long millisInFuture, long countDownInterval) {
- this.countDownInterval = countDownInterval;
- this.millisInFuture = millisInFuture;
- this.started = false;
- }
-
- @Implementation
- public final synchronized CountDownTimer start() {
- started = true;
- return countDownTimer;
- }
-
-
- @Implementation
- public final void cancel() {
- started = false;
- }
-
-
- /**
- * ******************************************************
- * Non-implementation methods for firing abstract methods
- * *******************************************************
- */
- public void invokeTick(long millisUntilFinished) {
- countDownTimer.onTick(millisUntilFinished);
- }
-
- public void invokeFinish() {
- countDownTimer.onFinish();
- }
-
- public boolean hasStarted() {
- return started;
- }
-
- public long getCountDownInterval() {
- return countDownInterval;
- }
-
- public long getMillisInFuture() {
- return millisInFuture;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowCriteria.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowCriteria.java
deleted file mode 100644
index 0a2ffa4d9..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowCriteria.java
+++ /dev/null
@@ -1,54 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.location.Criteria;
-
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-@Implements(Criteria.class)
-public class ShadowCriteria {
- private int accuracy = Criteria.NO_REQUIREMENT;
-// private int bearingAccuracy;
-// private int horizontalAccuracy;
-// private int verticalAccuracy;
-// private int speedAccuracy;
- private int powerRequirement = Criteria.NO_REQUIREMENT;
-
- public void __constructor__(Criteria criteria) {
- accuracy = criteria.getAccuracy();
- powerRequirement = criteria.getPowerRequirement();
- }
-
- @Implementation
- public int getAccuracy() {
- return accuracy;
- }
-
- @Implementation
- public void setAccuracy(int accuracy) {
- this.accuracy = accuracy;
- }
-
- @Implementation
- public int getPowerRequirement() {
- return powerRequirement;
- }
-
- @Implementation
- public void setPowerRequirement(int powerRequirement) {
- this.powerRequirement = powerRequirement;
- }
-
- @Implementation
- @Override
- public boolean equals(Object obj) {
- if (!(obj instanceof Criteria)) {
- return false;
- }
- Criteria criteria = (Criteria) obj;
- if (criteria.getAccuracy() == accuracy && criteria.getPowerRequirement() == powerRequirement) {
- return true;
- }
- return false;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowCursorAdapter.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowCursorAdapter.java
deleted file mode 100644
index 20714071a..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowCursorAdapter.java
+++ /dev/null
@@ -1,444 +0,0 @@
-/*
- * Copyright (C) 2006 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.xtremelabs.robolectric.shadows;
-
-
-import android.content.Context;
-import android.database.ContentObserver;
-import android.database.Cursor;
-import android.database.DataSetObserver;
-import android.os.Handler;
-import android.util.Config;
-import android.util.Log;
-import android.view.View;
-import android.view.ViewGroup;
-import android.widget.CursorAdapter;
-import android.widget.FilterQueryProvider;
-
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Adapter that exposes data from a {@link android.database.Cursor Cursor} to a
- * {@link android.widget.ListView ListView} widget. The Cursor must include
- * a column named "_id" or this class will not work.
- */
-@Implements(CursorAdapter.class)
-public class ShadowCursorAdapter extends ShadowBaseAdapter {
-
- private List<View> views = new ArrayList<View>();
-
- @Implementation
- public View getView(int position, View convertView, ViewGroup parent) {
- // if the cursor is null OR there are no views to dispense return null
- if (this.mCursor == null || views.size() == 0 ) {
- return null;
- }
-
- if (convertView != null) {
- return convertView;
- }
-
- return views.get(position);
- }
-
- /**
- * Non-Android API. Set a list of views to be returned for successive
- * calls to getView().
- *
- * @param views
- */
- public void setViews(List<View> views) {
- this.views = views;
- }
-
- /**
- * This field should be made private, so it is hidden from the SDK.
- * {@hide}
- */
- protected boolean mDataValid;
- /**
- * This field should be made private, so it is hidden from the SDK.
- * {@hide}
- */
- protected boolean mAutoRequery;
- /**
- * This field should be made private, so it is hidden from the SDK.
- * {@hide}
- */
- protected Cursor mCursor;
- /**
- * This field should be made private, so it is hidden from the SDK.
- * {@hide}
- */
- protected Context mContext;
- /**
- * This field should be made private, so it is hidden from the SDK.
- * {@hide}
- */
- protected int mRowIDColumn;
- /**
- * This field should be made private, so it is hidden from the SDK.
- * {@hide}
- */
- protected ChangeObserver mChangeObserver;
- /**
- * This field should be made private, so it is hidden from the SDK.
- * {@hide}
- */
- protected DataSetObserver mDataSetObserver = new MyDataSetObserver();
-// /**
-// * This field should be made private, so it is hidden from the SDK.
-// * {@hide}
-// */
-// protected CursorFilter__FromAndroid mCursorFilter;
- /**
- * This field should be made private, so it is hidden from the SDK.
- * {@hide}
- */
- protected FilterQueryProvider mFilterQueryProvider;
-
- /**
- * Constructor. The adapter will call requery() on the cursor whenever
- * it changes so that the most recent data is always displayed.
- *
- * @param c The cursor from which to get the data.
- * @param context The context
- */
- public void __constructor__(Context context, Cursor c) {
- initialize(context, c, true);
- }
-
- /**
- * Constructor
- *
- * @param c The cursor from which to get the data.
- * @param context The context
- * @param autoRequery If true the adapter will call requery() on the
- * cursor whenever it changes so the most recent
- * data is always displayed.
- */
- public void __constructor__(Context context, Cursor c, boolean autoRequery) {
- initialize(context, c, autoRequery);
- }
-
- // renamed from Android source so as not to conflict with RobolectricWiringTest
- private void initialize(Context context, Cursor c, boolean autoRequery) {
- boolean cursorPresent = c != null;
- mAutoRequery = autoRequery;
- mCursor = c;
- mDataValid = cursorPresent;
- mContext = context;
- mRowIDColumn = cursorPresent ? c.getColumnIndexOrThrow("_id") : -1;
- mChangeObserver = new ChangeObserver();
- if (cursorPresent) {
- c.registerContentObserver(mChangeObserver);
- c.registerDataSetObserver(mDataSetObserver);
- }
- }
-
- /**
- * Returns the cursor.
- *
- * @return the cursor.
- */
- @Implementation
- public Cursor getCursor() {
- return mCursor;
- }
-
- /**
- * @see android.widget.ListAdapter#getCount()
- */
- @Implementation
- public int getCount() {
- if (mDataValid && mCursor != null) {
- return mCursor.getCount();
- } else {
- return 0;
- }
- }
-
- /**
- * @see android.widget.ListAdapter#getItem(int)
- */
- @Implementation
- public Object getItem(int position) {
- if (mDataValid && mCursor != null) {
- mCursor.moveToPosition(position);
- return mCursor;
- } else {
- return null;
- }
- }
-
- /**
- * @see android.widget.ListAdapter#getItemId(int)
- */
- @Implementation
- public long getItemId(int position) {
- if (mDataValid && mCursor != null) {
- this.mCursor.getColumnIndexOrThrow("_id");
- if (mCursor.moveToPosition(position)) {
- return mCursor.getLong(mRowIDColumn);
- } else {
- return 0;
- }
- } else {
- return 0;
- }
- }
-
- @Implementation
- public boolean hasStableIds() {
- return true;
- }
-
-// /**
-// * @see android.widget.ListAdapter#getView(int, View, ViewGroup)
-// */
-// @Implementation
-// public View getView(int position, View convertView, ViewGroup parent) {
-// if (!mDataValid) {
-// throw new IllegalStateException("this should only be called when the cursor is valid");
-// }
-// if (!mCursor.moveToPosition(position)) {
-// throw new IllegalStateException("couldn't move cursor to position " + position);
-// }
-// View v;
-// if (convertView == null) {
-// v = newView(mContext, mCursor, parent);
-// } else {
-// v = convertView;
-// }
-// bindView(v, mContext, mCursor);
-// return v;
-// }
-//
-// @Implementation
-// public View getDropDownView(int position, View convertView, ViewGroup parent) {
-// if (mDataValid) {
-// mCursor.moveToPosition(position);
-// View v;
-// if (convertView == null) {
-// v = newDropDownView(mContext, mCursor, parent);
-// } else {
-// v = convertView;
-// }
-// bindView(v, mContext, mCursor);
-// return v;
-// } else {
-// return null;
-// }
-// }
-
-// /**
-// * Makes a new view to hold the data pointed to by cursor.
-// * @param context Interface to application's global information
-// * @param cursor The cursor from which to get the data. The cursor is already
-// * moved to the correct position.
-// * @param parent The parent to which the new view is attached to
-// * @return the newly created view.
-// */
-// public abstract View newView(Context context, Cursor cursor, ViewGroup parent);
-
-// /**
-// * Makes a new drop down view to hold the data pointed to by cursor.
-// * @param context Interface to application's global information
-// * @param cursor The cursor from which to get the data. The cursor is already
-// * moved to the correct position.
-// * @param parent The parent to which the new view is attached to
-// * @return the newly created view.
-// */
-// @Implementation
-// public View newDropDownView(Context context, Cursor cursor, ViewGroup parent) {
-// return newView(context, cursor, parent);
-// }
-
-// /**
-// * Bind an existing view to the data pointed to by cursor
-// * @param view Existing view, returned earlier by newView
-// * @param context Interface to application's global information
-// * @param cursor The cursor from which to get the data. The cursor is already
-// * moved to the correct position.
-// */
-// public abstract void bindView(View view, Context context, Cursor cursor);
-
- /**
- * Change the underlying cursor to a new cursor. If there is an existing cursor it will be
- * closed.
- *
- * @param cursor the new cursor to be used
- */
- @Implementation
- public void changeCursor(Cursor cursor) {
- if (cursor == mCursor) {
- return;
- }
- if (mCursor != null) {
- mCursor.unregisterContentObserver(mChangeObserver);
- mCursor.unregisterDataSetObserver(mDataSetObserver);
- mCursor.close();
- }
- mCursor = cursor;
- if (cursor != null) {
- cursor.registerContentObserver(mChangeObserver);
- cursor.registerDataSetObserver(mDataSetObserver);
- mRowIDColumn = cursor.getColumnIndexOrThrow("_id");
- mDataValid = true;
- // notify the observers about the new cursor
- notifyDataSetChanged();
- } else {
- mRowIDColumn = -1;
- mDataValid = false;
- // notify the observers about the lack of a data set
- notifyDataSetInvalidated();
- }
- }
-
- /**
- * <p>Converts the cursor into a CharSequence. Subclasses should override this
- * method to convert their results. The default implementation returns an
- * empty String for null values or the default String representation of
- * the value.</p>
- *
- * @param cursor the cursor to convert to a CharSequence
- * @return a CharSequence representing the value
- */
- @Implementation
- public CharSequence convertToString(Cursor cursor) {
- return cursor == null ? "" : cursor.toString();
- }
-
- /**
- * Runs a query with the specified constraint. This query is requested
- * by the filter attached to this adapter.
- * <p/>
- * The query is provided by a
- * {@link android.widget.FilterQueryProvider}.
- * If no provider is specified, the current cursor is not filtered and returned.
- * <p/>
- * After this method returns the resulting cursor is passed to {@link #changeCursor(Cursor)}
- * and the previous cursor is closed.
- * <p/>
- * This method is always executed on a background thread, not on the
- * application's main thread (or UI thread.)
- * <p/>
- * Contract: when constraint is null or empty, the original results,
- * prior to any filtering, must be returned.
- *
- * @param constraint the constraint with which the query must be filtered
- * @return a Cursor representing the results of the new query
- * @see #getFilter()
- * @see #getFilterQueryProvider()
- * @see #setFilterQueryProvider(android.widget.FilterQueryProvider)
- */
- @Implementation
- public Cursor runQueryOnBackgroundThread(CharSequence constraint) {
- if (mFilterQueryProvider != null) {
- return mFilterQueryProvider.runQuery(constraint);
- }
-
- return mCursor;
- }
-
-// @Implementation
-// public Filter getFilter() {
-// if (mCursorFilter == null) {
-// mCursorFilter = new CursorFilter__FromAndroid(this);
-// }
-// return mCursorFilter;
-// }
-
- /**
- * Returns the query filter provider used for filtering. When the
- * provider is null, no filtering occurs.
- *
- * @return the current filter query provider or null if it does not exist
- * @see #setFilterQueryProvider(android.widget.FilterQueryProvider)
- * @see #runQueryOnBackgroundThread(CharSequence)
- */
- @Implementation
- public FilterQueryProvider getFilterQueryProvider() {
- return mFilterQueryProvider;
- }
-
- /**
- * Sets the query filter provider used to filter the current Cursor.
- * The provider's
- * {@link android.widget.FilterQueryProvider#runQuery(CharSequence)}
- * method is invoked when filtering is requested by a client of
- * this adapter.
- *
- * @param filterQueryProvider the filter query provider or null to remove it
- * @see #getFilterQueryProvider()
- * @see #runQueryOnBackgroundThread(CharSequence)
- */
- @Implementation
- public void setFilterQueryProvider(FilterQueryProvider filterQueryProvider) {
- mFilterQueryProvider = filterQueryProvider;
- }
-
- /**
- * Called when the {@link ContentObserver} on the cursor receives a change notification.
- * The default implementation provides the auto-requery logic, but may be overridden by
- * sub classes.
- *
- * @see ContentObserver#onChange(boolean)
- */
- // renamed from Android source so as not to conflict with RobolectricWiringTest
- protected void onContentChangedInternal() {
- if (mAutoRequery && mCursor != null && !mCursor.isClosed()) {
- if (Config.LOGV) Log.v("Cursor", "Auto requerying " + mCursor + " due to update");
- mDataValid = mCursor.requery();
- }
- }
-
- private class ChangeObserver extends ContentObserver {
- public ChangeObserver() {
- super(new Handler());
- }
-
- @Override
- public boolean deliverSelfNotifications() {
- return true;
- }
-
- @Override
- public void onChange(boolean selfChange) {
- onContentChangedInternal();
- }
- }
-
- private class MyDataSetObserver extends DataSetObserver {
- @Override
- public void onChanged() {
- mDataValid = true;
- notifyDataSetChanged();
- }
-
- @Override
- public void onInvalidated() {
- mDataValid = false;
- notifyDataSetInvalidated();
- }
- }
-
-} \ No newline at end of file
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowCursorLoader.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowCursorLoader.java
deleted file mode 100644
index 8b2d94f07..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowCursorLoader.java
+++ /dev/null
@@ -1,81 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.content.Context;
-import android.net.Uri;
-import android.support.v4.content.CursorLoader;
-
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-@Implements(CursorLoader.class)
-public class ShadowCursorLoader {
- private Context context;
- private Uri uri;
- private String[] projection;
- private String selection;
- private String[] selectionArgs;
- private String sortOrder;
-
- public void __constructor__(Context context) {
- this.context = context;
- }
-
- public void __constructor__(Context context, Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
- this.context = context;
- this.uri = uri;
- this.projection = projection;
- this.selection = selection;
- this.selectionArgs = selectionArgs;
- this.sortOrder = sortOrder;
- }
-
- @Implementation
- public Uri getUri() {
- return uri;
- }
-
- @Implementation
- public void setUri(Uri uri) {
- this.uri = uri;
- }
-
- @Implementation
- public String[] getProjection() {
- return projection;
- }
-
- @Implementation
- public void setProjection(String[] projection) {
- this.projection = projection;
- }
-
- @Implementation
- public String getSelection() {
- return selection;
- }
-
- @Implementation
- public void setSelection(String selection) {
- this.selection = selection;
- }
-
- @Implementation
- public String[] getSelectionArgs() {
- return selectionArgs;
- }
-
- @Implementation
- public void setSelectionArgs(String[] selectionArgs) {
- this.selectionArgs = selectionArgs;
- }
-
- @Implementation
- public String getSortOrder() {
- return sortOrder;
- }
-
- @Implementation
- public void setSortOrder(String sortOrder) {
- this.sortOrder = sortOrder;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowCursorWrapper.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowCursorWrapper.java
deleted file mode 100644
index 9456c6bb3..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowCursorWrapper.java
+++ /dev/null
@@ -1,218 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.content.ContentResolver;
-import android.database.*;
-import android.net.Uri;
-import android.os.Bundle;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-@Implements(CursorWrapper.class)
-public class ShadowCursorWrapper implements Cursor {
- private Cursor wrappedCursor;
-
- public void __constructor__(Cursor c) {
- wrappedCursor = c;
- }
-
- @Implementation
- public int getCount() {
- return wrappedCursor.getCount();
- }
-
- @Implementation
- public int getPosition() {
- return wrappedCursor.getPosition();
- }
-
- @Implementation
- public boolean move(int i) {
- return wrappedCursor.move(i);
- }
-
- @Implementation
- public boolean moveToPosition(int i) {
- return wrappedCursor.moveToPosition(i);
- }
-
- @Implementation
- public boolean moveToFirst() {
- return wrappedCursor.moveToFirst();
- }
-
- @Implementation
- public boolean moveToLast() {
- return wrappedCursor.moveToLast();
- }
-
- @Implementation
- public boolean moveToNext() {
- return wrappedCursor.moveToNext();
- }
-
- @Implementation
- public boolean moveToPrevious() {
- return wrappedCursor.moveToPrevious();
- }
-
- @Implementation
- public boolean isFirst() {
- return wrappedCursor.isFirst();
- }
-
- @Implementation
- public boolean isLast() {
- return wrappedCursor.isLast();
- }
-
- @Implementation
- public boolean isBeforeFirst() {
- return wrappedCursor.isBeforeFirst();
- }
-
- @Implementation
- public boolean isAfterLast() {
- return wrappedCursor.isAfterLast();
- }
-
- @Implementation
- public int getColumnIndex(String s) {
- return wrappedCursor.getColumnIndex(s);
- }
-
- @Implementation
- public int getColumnIndexOrThrow(String s) throws IllegalArgumentException {
- return wrappedCursor.getColumnIndexOrThrow(s);
- }
-
- @Implementation
- public String getColumnName(int i) {
- return wrappedCursor.getColumnName(i);
- }
-
- @Implementation
- public String[] getColumnNames() {
- return wrappedCursor.getColumnNames();
- }
-
- @Implementation
- public int getColumnCount() {
- return wrappedCursor.getColumnCount();
- }
-
- @Implementation
- public byte[] getBlob(int i) {
- return wrappedCursor.getBlob(i);
- }
-
- @Implementation
- public String getString(int i) {
- return wrappedCursor.getString(i);
- }
-
- @Implementation
- public void copyStringToBuffer(int i, CharArrayBuffer charArrayBuffer) {
- wrappedCursor.copyStringToBuffer(i, charArrayBuffer);
- }
-
- @Implementation
- public short getShort(int i) {
- return wrappedCursor.getShort(i);
- }
-
- @Implementation
- public int getInt(int i) {
- return wrappedCursor.getInt(i);
- }
-
- @Implementation
- public long getLong(int i) {
- return wrappedCursor.getLong(i);
- }
-
- @Implementation
- public float getFloat(int i) {
- return wrappedCursor.getFloat(i);
- }
-
- @Implementation
- public double getDouble(int i) {
- return wrappedCursor.getDouble(i);
- }
-
- @Implementation
- public boolean isNull(int i) {
- return wrappedCursor.isNull(i);
- }
-
- @Implementation
- public void deactivate() {
- wrappedCursor.deactivate();
- }
-
- @Implementation
- public boolean requery() {
- return wrappedCursor.requery();
- }
-
- @Implementation
- public void close() {
- wrappedCursor.close();
- }
-
- @Implementation
- public boolean isClosed() {
- return wrappedCursor.isClosed();
- }
-
- @Implementation
- public void registerContentObserver(ContentObserver contentObserver) {
- wrappedCursor.registerContentObserver(contentObserver);
- }
-
- @Implementation
- public void unregisterContentObserver(ContentObserver contentObserver) {
- wrappedCursor.unregisterContentObserver(contentObserver);
- }
-
- @Implementation
- public void registerDataSetObserver(DataSetObserver dataSetObserver) {
- wrappedCursor.registerDataSetObserver(dataSetObserver);
- }
-
- @Implementation
- public void unregisterDataSetObserver(DataSetObserver dataSetObserver) {
- wrappedCursor.unregisterDataSetObserver(dataSetObserver);
- }
-
- @Implementation
- public void setNotificationUri(ContentResolver contentResolver, Uri uri) {
- wrappedCursor.setNotificationUri(contentResolver, uri);
- }
-
- @Implementation
- public boolean getWantsAllOnMoveCalls() {
- return wrappedCursor.getWantsAllOnMoveCalls();
- }
-
- @Implementation
- public Bundle getExtras() {
- return wrappedCursor.getExtras();
- }
-
- @Implementation
- public Bundle respond(Bundle bundle) {
- return wrappedCursor.respond(bundle);
- }
-
- @Implementation
- public int getType(int columnIndex) {
- return 0;
- }
-
- @Implementation
- public Cursor getWrappedCursor() {
- return wrappedCursor;
- }
-
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowDatabaseUtils.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowDatabaseUtils.java
deleted file mode 100644
index cdff98845..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowDatabaseUtils.java
+++ /dev/null
@@ -1,44 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.database.DatabaseUtils;
-import android.database.sqlite.SQLiteProgram;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-@Implements(DatabaseUtils.class)
-public class ShadowDatabaseUtils {
-
- @Implementation
- public static void bindObjectToProgram(SQLiteProgram prog, int index,
- Object value) {
- if (value == null) {
- prog.bindNull(index);
- } else if (value instanceof Double || value instanceof Float) {
- prog.bindDouble(index, ((Number) value).doubleValue());
- } else if (value instanceof Number) {
- prog.bindLong(index, ((Number) value).longValue());
- } else if (value instanceof Boolean) {
- Boolean bool = (Boolean) value;
- if (bool) {
- prog.bindLong(index, 1);
- } else {
- prog.bindLong(index, 0);
- }
- } else if (value instanceof byte[]) {
- prog.bindBlob(index, (byte[]) value);
- } else {
- prog.bindString(index, value.toString());
- }
- }
-
- @Implementation
- public static String sqlEscapeString( String value ) {
- StringBuilder builder = new StringBuilder();
-
- // SQLite quoting conventions are used.
- value = value.replaceAll( "'", "''" );
- builder.append( "'" ).append( value ).append( "'" );
-
- return builder.toString();
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowDateFormat.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowDateFormat.java
deleted file mode 100644
index 7a5a42ec2..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowDateFormat.java
+++ /dev/null
@@ -1,16 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.content.Context;
-import android.text.format.DateFormat;
-
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-@Implements(DateFormat.class)
-public class ShadowDateFormat {
-
- @Implementation
- public final static java.text.DateFormat getDateFormat(Context context) {
- return java.text.DateFormat.getDateInstance();
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowDefaultRequestDirector.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowDefaultRequestDirector.java
deleted file mode 100644
index d377e9a93..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowDefaultRequestDirector.java
+++ /dev/null
@@ -1,206 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.internal.RealObject;
-import com.xtremelabs.robolectric.tester.org.apache.http.HttpRequestInfo;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.http.ConnectionReuseStrategy;
-import org.apache.http.HttpException;
-import org.apache.http.HttpHost;
-import org.apache.http.HttpRequest;
-import org.apache.http.HttpResponse;
-import org.apache.http.client.AuthenticationHandler;
-import org.apache.http.client.HttpRequestRetryHandler;
-import org.apache.http.client.RedirectHandler;
-import org.apache.http.client.UserTokenHandler;
-import org.apache.http.conn.ClientConnectionManager;
-import org.apache.http.conn.ConnectionKeepAliveStrategy;
-import org.apache.http.conn.routing.HttpRoutePlanner;
-import org.apache.http.impl.client.DefaultRequestDirector;
-import org.apache.http.params.HttpParams;
-import org.apache.http.protocol.HttpContext;
-import org.apache.http.protocol.HttpProcessor;
-import org.apache.http.protocol.HttpRequestExecutor;
-
-import java.io.IOException;
-
-@SuppressWarnings({"UnusedDeclaration"})
-@Implements(DefaultRequestDirector.class)
-public class ShadowDefaultRequestDirector {
- @RealObject DefaultRequestDirector realObject;
-
- protected Log log;
- protected ClientConnectionManager connectionManager;
- protected HttpRoutePlanner httpRoutePlanner;
- protected ConnectionReuseStrategy connectionReuseStrategy;
- protected ConnectionKeepAliveStrategy connectionKeepAliveStrategy;
- protected HttpRequestExecutor httpRequestExecutor;
- protected HttpProcessor httpProcessor;
- protected HttpRequestRetryHandler httpRequestRetryHandler;
- protected RedirectHandler redirectHandler;
- protected AuthenticationHandler targetAuthenticationHandler;
- protected AuthenticationHandler proxyAuthenticationHandler;
- protected UserTokenHandler userTokenHandler;
- protected HttpParams httpParams;
-
- com.xtremelabs.robolectric.tester.org.apache.http.impl.client.DefaultRequestDirector redirector;
-
- public void __constructor__(
- Log log,
- HttpRequestExecutor requestExec,
- ClientConnectionManager conman,
- ConnectionReuseStrategy reustrat,
- ConnectionKeepAliveStrategy kastrat,
- HttpRoutePlanner rouplan,
- HttpProcessor httpProcessor,
- HttpRequestRetryHandler retryHandler,
- RedirectHandler redirectHandler,
- AuthenticationHandler targetAuthHandler,
- AuthenticationHandler proxyAuthHandler,
- UserTokenHandler userTokenHandler,
- HttpParams params) {
- this.log = log;
- this.httpRequestExecutor = requestExec;
- this.connectionManager = conman;
- this.connectionReuseStrategy = reustrat;
- this.connectionKeepAliveStrategy = kastrat;
- this.httpRoutePlanner = rouplan;
- this.httpProcessor = httpProcessor;
- this.httpRequestRetryHandler = retryHandler;
- this.redirectHandler = redirectHandler;
- this.targetAuthenticationHandler = targetAuthHandler;
- this.proxyAuthenticationHandler = proxyAuthHandler;
- this.userTokenHandler = userTokenHandler;
- this.httpParams = params;
-
- try {
- redirector = new com.xtremelabs.robolectric.tester.org.apache.http.impl.client.DefaultRequestDirector(
- log,
- requestExec,
- conman,
- reustrat,
- kastrat,
- rouplan,
- httpProcessor,
- retryHandler,
- redirectHandler,
- targetAuthHandler,
- proxyAuthHandler,
- userTokenHandler,
- params
- );
- } catch (IllegalArgumentException ignored) {
- Robolectric.getFakeHttpLayer().interceptHttpRequests(true);
- }
- }
-
- public void __constructor__(
- HttpRequestExecutor requestExec,
- ClientConnectionManager conman,
- ConnectionReuseStrategy reustrat,
- ConnectionKeepAliveStrategy kastrat,
- HttpRoutePlanner rouplan,
- HttpProcessor httpProcessor,
- HttpRequestRetryHandler retryHandler,
- RedirectHandler redirectHandler,
- AuthenticationHandler targetAuthHandler,
- AuthenticationHandler proxyAuthHandler,
- UserTokenHandler userTokenHandler,
- HttpParams params) {
- __constructor__(
- LogFactory.getLog(DefaultRequestDirector.class),
- requestExec,
- conman,
- reustrat,
- kastrat,
- rouplan,
- httpProcessor,
- retryHandler,
- redirectHandler,
- targetAuthHandler,
- proxyAuthHandler,
- userTokenHandler,
- params);
- }
-
- public static HttpRequest getSentHttpRequest(int index) {
- return getSentHttpRequestInfo(index).getHttpRequest();
- }
-
- public static HttpRequest getLatestSentHttpRequest() {
- return getLatestSentHttpRequestInfo().getHttpRequest();
- }
-
- public static HttpRequestInfo getLatestSentHttpRequestInfo() {
- int requestCount = Robolectric.getFakeHttpLayer().getSentHttpRequestInfos().size();
- return Robolectric.getFakeHttpLayer().getSentHttpRequestInfo(requestCount - 1);
- }
-
- public static HttpRequestInfo getSentHttpRequestInfo(int index) {
- return Robolectric.getFakeHttpLayer().getSentHttpRequestInfo(index);
- }
-
- @Implementation
- public HttpResponse execute(HttpHost httpHost, HttpRequest httpRequest, HttpContext httpContext) throws HttpException, IOException {
- if (Robolectric.getFakeHttpLayer().isInterceptingHttpRequests()) {
- return Robolectric.getFakeHttpLayer().emulateRequest(httpHost, httpRequest, httpContext, realObject);
- } else {
- return redirector.execute(httpHost, httpRequest, httpContext);
- }
- }
-
- public Log getLog() {
- return log;
- }
-
- public ClientConnectionManager getConnectionManager() {
- return connectionManager;
- }
-
- public HttpRoutePlanner getHttpRoutePlanner() {
- return httpRoutePlanner;
- }
-
- public ConnectionReuseStrategy getConnectionReuseStrategy() {
- return connectionReuseStrategy;
- }
-
- public ConnectionKeepAliveStrategy getConnectionKeepAliveStrategy() {
- return connectionKeepAliveStrategy;
- }
-
- public HttpRequestExecutor getHttpRequestExecutor() {
- return httpRequestExecutor;
- }
-
- public HttpProcessor getHttpProcessor() {
- return httpProcessor;
- }
-
- public HttpRequestRetryHandler getHttpRequestRetryHandler() {
- return httpRequestRetryHandler;
- }
-
- public RedirectHandler getRedirectHandler() {
- return redirectHandler;
- }
-
- public AuthenticationHandler getTargetAuthenticationHandler() {
- return targetAuthenticationHandler;
- }
-
- public AuthenticationHandler getProxyAuthenticationHandler() {
- return proxyAuthenticationHandler;
- }
-
- public UserTokenHandler getUserTokenHandler() {
- return userTokenHandler;
- }
-
- public HttpParams getHttpParams() {
- return httpParams;
- }
-} \ No newline at end of file
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowDialog.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowDialog.java
deleted file mode 100644
index 0f317a290..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowDialog.java
+++ /dev/null
@@ -1,266 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.app.Activity;
-import android.app.Dialog;
-import android.content.Context;
-import android.content.DialogInterface;
-import android.os.Bundle;
-import android.view.LayoutInflater;
-import android.view.View;
-import android.view.ViewGroup;
-import android.view.Window;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.internal.RealObject;
-import com.xtremelabs.robolectric.tester.android.view.TestWindow;
-
-import java.lang.reflect.Method;
-import java.util.ArrayList;
-import java.util.List;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-
-@SuppressWarnings({"UnusedDeclaration"})
-@Implements(Dialog.class)
-public class ShadowDialog {
-
- @RealObject private Dialog realDialog;
-
- private boolean isShowing;
- Context context;
- private int layoutId;
- private int themeId;
- private View inflatedView;
- private boolean hasBeenDismissed;
- private DialogInterface.OnDismissListener onDismissListener;
- protected CharSequence title;
- private DialogInterface.OnCancelListener onCancelListener;
- private Window window;
- private Activity ownerActivity;
- private boolean isCancelable = true;
- private boolean hasShownBefore;
- private static final ArrayList<Dialog> shownDialogs = new ArrayList<Dialog>();
- private boolean isCancelableOnTouchOutside;
-
- public static void reset() {
- setLatestDialog(null);
- shownDialogs.clear();
- }
-
- public static Dialog getLatestDialog() {
- ShadowDialog dialog = Robolectric.getShadowApplication().getLatestDialog();
- return dialog == null ? null : dialog.realDialog;
- }
-
- public static void setLatestDialog(ShadowDialog latestDialog) {
- Robolectric.getShadowApplication().setLatestDialog(latestDialog);
- }
-
- public void __constructor__(Context context) {
- __constructor__(context, -1);
- }
-
- public void __constructor__(Context context, int themeId) {
- this.context = context;
- this.themeId = themeId;
- }
-
- @Implementation
- public void setContentView(int layoutResID) {
- layoutId = layoutResID;
- }
-
- @Implementation
- public void setContentView(View view) {
- inflatedView = view;
- }
-
- @Implementation
- public void setTitle(int stringResourceId) {
- this.title = context.getResources().getText(stringResourceId);
- }
-
- @Implementation(i18nSafe = false)
- public void setTitle(CharSequence title) {
- this.title = title;
- }
-
- @Implementation
- public void setOwnerActivity(Activity activity) {
- this.ownerActivity = activity;
- }
-
- @Implementation
- public Activity getOwnerActivity() {
- return this.ownerActivity;
- }
-
- @Implementation
- public Context getContext() {
- return context;
- }
-
- @Implementation
- public void onBackPressed() {
- cancel();
- }
-
- @Implementation
- public void show() {
- setLatestDialog(this);
- shownDialogs.add(realDialog);
- isShowing = true;
- try {
- if (!hasShownBefore) {
- Method onCreateMethod = Dialog.class.getDeclaredMethod("onCreate", Bundle.class);
- onCreateMethod.setAccessible(true);
- onCreateMethod.invoke(realDialog, (Bundle) null);
- }
-
- Method onStartMethod = Dialog.class.getDeclaredMethod("onStart");
- onStartMethod.setAccessible(true);
- onStartMethod.invoke(realDialog);
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- hasShownBefore = true;
- }
-
- @Implementation
- public void hide() {
- isShowing = false;
- }
-
- @Implementation
- public boolean isShowing() {
- return isShowing;
- }
-
- @Implementation
- public void dismiss() {
- isShowing = false;
- hasBeenDismissed = true;
-
- if (onDismissListener != null) {
- onDismissListener.onDismiss(realDialog);
- }
- }
-
- @Implementation
- public View findViewById(int viewId) {
- if (inflatedView != null) {
- return inflatedView.findViewById(viewId);
- }
- if (layoutId > 0 && context != null) {
- inflatedView = ShadowLayoutInflater.from(context).inflate(layoutId, null);
- return inflatedView.findViewById(viewId);
- }
- return null;
- }
-
- public void clickOn(int viewId) {
- findViewById(viewId).performClick();
- }
-
- @Implementation
- public void setOnDismissListener(DialogInterface.OnDismissListener onDismissListener) {
- this.onDismissListener = onDismissListener;
- }
-
- @Implementation
- public void setCancelable(boolean flag) {
- isCancelable = flag;
- }
-
- @Implementation
- public void setCanceledOnTouchOutside(boolean flag) {
- isCancelableOnTouchOutside = flag;
- }
-
- public boolean isCancelable() {
- return isCancelable;
- }
-
- public boolean isCancelableOnTouchOutside() {
- return isCancelableOnTouchOutside;
- }
-
- @Implementation
- public void cancel() {
- if (onCancelListener != null) {
- onCancelListener.onCancel(realDialog);
- }
- realDialog.dismiss();
- }
-
- @Implementation
- public void setOnCancelListener(DialogInterface.OnCancelListener listener) {
- this.onCancelListener = listener;
- }
-
- public DialogInterface.OnCancelListener getOnCancelListener() {
- return onCancelListener;
- }
-
- @Implementation
- public Window getWindow() {
- if (window == null) {
- window = new TestWindow(realDialog.getContext());
- }
- return window;
- }
-
-
- @Implementation
- public LayoutInflater getLayoutInflater() {
- return LayoutInflater.from(realDialog.getContext());
- }
-
- public int getLayoutId() {
- return layoutId;
- }
-
- public int getThemeId() {
- return themeId;
- }
-
- public boolean hasBeenDismissed() {
- return hasBeenDismissed;
- }
-
- public CharSequence getTitle() {
- return title;
- }
-
- public void clickOnText(int textId) {
- if (inflatedView == null) {
- inflatedView = ShadowLayoutInflater.from(context).inflate(layoutId, null);
- }
- String text = getContext().getResources().getString(textId);
- if (!clickOnText(inflatedView, text)) {
- throw new IllegalArgumentException("Text not found: " + text);
- }
- }
-
- private boolean clickOnText(View view, String text) {
- if (text.equals(shadowOf(view).innerText())) {
- view.performClick();
- return true;
- }
- if (view instanceof ViewGroup) {
- ViewGroup viewGroup = (ViewGroup) view;
- for (int i = 0; i < viewGroup.getChildCount(); i++) {
- View child = viewGroup.getChildAt(i);
- if (clickOnText(child, text)) {
- return true;
- }
- }
- }
- return false;
- }
-
- public static List<Dialog> getShownDialogs() {
- return shownDialogs;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowDialogFragment.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowDialogFragment.java
deleted file mode 100644
index 11538a2a5..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowDialogFragment.java
+++ /dev/null
@@ -1,95 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.app.Dialog;
-import android.support.v4.app.DialogFragment;
-import android.support.v4.app.FragmentActivity;
-import android.support.v4.app.FragmentManager;
-import android.support.v4.app.FragmentTransaction;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.internal.RealObject;
-import com.xtremelabs.robolectric.tester.android.util.TestFragmentManager;
-import com.xtremelabs.robolectric.tester.android.util.TestFragmentTransaction;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-
-/**
- * Shadow implementation of the {@link DialogFragment}.
- */
-@Implements(DialogFragment.class)
-public class ShadowDialogFragment extends ShadowFragment {
- private static DialogFragment latestDialogFragment;
-
- private Dialog dialog;
- private boolean cancelable = true; // defaults to true
-
- @RealObject
- private DialogFragment realDialogFragment;
-
- @Implementation
- public int show(FragmentTransaction transaction, String tag) {
- show(((TestFragmentTransaction)transaction).getManager(), tag);
- return 0;
- }
-
- @Implementation
- public void show(FragmentManager manager, String tag) {
- TestFragmentManager testFragmentManager = (TestFragmentManager) manager;
- FragmentActivity activityFromManager = testFragmentManager.getActivity();
-
- shadowOf(realDialogFragment).setActivity(activityFromManager);
-
- realDialogFragment.onAttach(activity);
- realDialogFragment.onCreate(null);
- dialog = realDialogFragment.onCreateDialog(null);
- view = realDialogFragment.onCreateView(ShadowLayoutInflater.from(activity), null, null);
- if (dialog == null) {
- dialog = new Dialog(activityFromManager);
- dialog.setContentView(view);
- }
- dialog.setCancelable(cancelable);
- testFragmentManager.addDialogFragment(tag, realDialogFragment);
- realDialogFragment.onViewCreated(view, null);
- realDialogFragment.onActivityCreated(null);
- realDialogFragment.onStart();
- realDialogFragment.onResume();
-
- latestDialogFragment = realDialogFragment;
- }
-
- @Implementation
- public void onStart() {
- if (dialog != null) {
- dialog.show();
- }
- }
-
- @Implementation
- public void dismiss() {
- if (dialog != null) {
- dialog.dismiss();
- }
- }
-
- @Implementation
- public Dialog getDialog() {
- return dialog;
- }
-
- @Implementation
- public boolean isCancelable() {
- return cancelable;
- }
-
- @Implementation
- public void setCancelable(boolean cancelable) {
- this.cancelable = cancelable;
- if (dialog != null) {
- dialog.setCancelable(cancelable);
- }
- }
-
- public static DialogFragment getLatestDialogFragment() {
- return latestDialogFragment;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowDialogPreference.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowDialogPreference.java
deleted file mode 100644
index 50145ae53..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowDialogPreference.java
+++ /dev/null
@@ -1,18 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-import android.preference.DialogPreference;
-
-@Implements(DialogPreference.class)
-public class ShadowDialogPreference extends ShadowPreference {
-
- private static final String ANDROID_NS = "http://schemas.android.com/apk/res/android";
-
- @Implementation
- public CharSequence getDialogMessage() {
- return attrs.getAttributeValue(ANDROID_NS,"dialogMessage");
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowDisplay.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowDisplay.java
deleted file mode 100644
index fe0914fcb..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowDisplay.java
+++ /dev/null
@@ -1,133 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.graphics.PixelFormat;
-import android.util.DisplayMetrics;
-import android.view.Display;
-import android.view.Surface;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-/**
- * A shadow for Display with some reasonable defaults
- */
-@SuppressWarnings({"UnusedDeclaration"})
-@Implements(Display.class)
-public class ShadowDisplay {
- private int displayId;
- private int width = 480;
- private int height = 800;
- private float density = 1.5f;
- private int densityDpi = DisplayMetrics.DENSITY_HIGH;
- private float xdpi = 240.0f;
- private float ydpi = 240.0f;
- private float scaledDensity = 1.0f;
- private float refreshRate = 60.0f;
- private int rotation = Surface.ROTATION_0;
- private int pixelFormat = PixelFormat.RGBA_4444;
-
- @Implementation
- public int getHeight() {
- return height;
- }
-
- @Implementation
- public void getMetrics(DisplayMetrics outMetrics) {
- outMetrics.density = density;
- outMetrics.densityDpi = densityDpi;
- outMetrics.scaledDensity = scaledDensity;
- outMetrics.widthPixels = width;
- outMetrics.heightPixels = height;
- outMetrics.xdpi = xdpi;
- outMetrics.ydpi = ydpi;
- }
-
- @Implementation
- public int getWidth() {
- return width;
- }
-
- @Implementation
- public int getDisplayId() {
- return displayId;
- }
-
- @Implementation
- public float getRefreshRate() {
- return refreshRate;
- }
-
- @Implementation
- public int getRotation() {
- return rotation;
- }
-
- @Implementation
- public int getPixelFormat() {
- return pixelFormat;
- }
-
- public float getDensity() {
- return density;
- }
-
- public void setDensity(float density) {
- this.density = density;
- }
-
- public int getDensityDpi() {
- return densityDpi;
- }
-
- public void setDensityDpi(int densityDpi) {
- this.densityDpi = densityDpi;
- }
-
- public float getXdpi() {
- return xdpi;
- }
-
- public void setXdpi(float xdpi) {
- this.xdpi = xdpi;
- }
-
- public float getYdpi() {
- return ydpi;
- }
-
- public void setYdpi(float ydpi) {
- this.ydpi = ydpi;
- }
-
- public float getScaledDensity() {
- return scaledDensity;
- }
-
- public void setScaledDensity(float scaledDensity) {
- this.scaledDensity = scaledDensity;
- }
-
- public void setDisplayId(int displayId) {
- this.displayId = displayId;
- }
-
- public void setWidth(int width) {
- this.width = width;
- }
-
- public void setHeight(int height) {
- this.height = height;
- }
-
- public void setRefreshRate(float refreshRate) {
- this.refreshRate = refreshRate;
- }
-
- public void setRotation(int rotation) {
- this.rotation = rotation;
- }
-
- public void setPixelFormat(int pixelFormat) {
- this.pixelFormat = pixelFormat;
- }
-
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowDrawable.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowDrawable.java
deleted file mode 100644
index b5d791283..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowDrawable.java
+++ /dev/null
@@ -1,204 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.content.res.Resources;
-import android.graphics.Bitmap;
-import android.graphics.BitmapFactory;
-import android.graphics.Rect;
-import android.graphics.drawable.BitmapDrawable;
-import android.graphics.drawable.Drawable;
-import android.util.TypedValue;
-
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.internal.RealObject;
-
-import java.io.InputStream;
-import java.util.ArrayList;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-
-@SuppressWarnings({"UnusedDeclaration"})
-@Implements(Drawable.class)
-public class ShadowDrawable {
- private static int defaultIntrinsicWidth = -1;
- private static int defaultIntrinsicHeight = -1;
- static ArrayList<String> corruptStreamSources = new ArrayList<String>();
-
- @RealObject Drawable realObject;
-
- private Rect bounds = new Rect(0, 0, 0, 0);
- private int intrinsicWidth = defaultIntrinsicWidth;
- private int intrinsicHeight = defaultIntrinsicHeight;
- private int alpha;
- private InputStream inputStream;
- private int level;
- private int loadedFromResourceId = -1;
- private boolean wasInvalidated;
-
- @Implementation
- public static Drawable createFromStream(InputStream is, String srcName) {
- if (corruptStreamSources.contains(srcName)) {
- return null;
- }
- BitmapDrawable drawable = new BitmapDrawable(Robolectric.newInstanceOf(Bitmap.class));
- shadowOf(drawable).setSource(srcName);
- shadowOf(drawable).setInputStream(is);
- return drawable;
- }
-
- @Implementation
- public static Drawable createFromResourceStream(Resources res, TypedValue value, InputStream is, String srcName) {
- return createFromStream(is, srcName);
- }
-
- @Implementation
- public static Drawable createFromResourceStream(Resources res, TypedValue value, InputStream is, String srcName, BitmapFactory.Options opts) {
- return createFromStream(is, srcName);
- }
-
- @Implementation
- public static Drawable createFromPath(String pathName) {
- BitmapDrawable drawable = new BitmapDrawable(Robolectric.newInstanceOf(Bitmap.class));
- shadowOf(drawable).setPath(pathName);
- return drawable;
- }
-
- public static Drawable createFromResourceId(int resourceId) {
- Bitmap bitmap = Robolectric.newInstanceOf(Bitmap.class);
- shadowOf(bitmap).setLoadedFromResourceId(resourceId);
- BitmapDrawable drawable = new BitmapDrawable(bitmap);
- return drawable;
- }
-
- @Implementation
- public final Rect getBounds() {
- return bounds;
- }
-
- @Implementation
- public void setBounds(Rect rect) {
- this.bounds = rect;
- }
-
- @Implementation
- public void setBounds(int left, int top, int right, int bottom) {
- bounds = new Rect(left, top, right, bottom);
- }
-
- @Implementation
- public Rect copyBounds() {
- Rect bounds = new Rect();
- copyBounds(bounds);
- return bounds;
- }
-
- @Implementation
- public void copyBounds(Rect bounds) {
- bounds.set(getBounds());
- }
-
- @Implementation
- public int getIntrinsicWidth() {
- return intrinsicWidth;
- }
-
- @Implementation
- public int getIntrinsicHeight() {
- return intrinsicHeight;
- }
-
- public static void addCorruptStreamSource(String src) {
- corruptStreamSources.add(src);
- }
-
- public static void setDefaultIntrinsicWidth(int defaultIntrinsicWidth) {
- ShadowDrawable.defaultIntrinsicWidth = defaultIntrinsicWidth;
- }
-
- public static void setDefaultIntrinsicHeight(int defaultIntrinsicHeight) {
- ShadowDrawable.defaultIntrinsicHeight = defaultIntrinsicHeight;
- }
-
- public void setIntrinsicWidth(int intrinsicWidth) {
- this.intrinsicWidth = intrinsicWidth;
- }
-
- public void setIntrinsicHeight(int intrinsicHeight) {
- this.intrinsicHeight = intrinsicHeight;
- }
-
- public InputStream getInputStream() {
- return inputStream;
- }
-
- public void setInputStream(InputStream inputStream) {
- this.inputStream = inputStream;
- }
-
- @Implementation
- public int getLevel() {
- return level;
- }
-
- @Implementation
- public boolean setLevel(int level) {
- this.level = level;
- // This should return true if the new level causes a layout change.
- // Doing this in robolectric would require parsing level sets which
- // is not currently supported.
- return false;
- }
-
- @Override @Implementation
- public boolean equals(Object o) {
- if (realObject == o) return true;
- if (o == null || realObject.getClass() != o.getClass()) return false;
-
- ShadowDrawable that = shadowOf((Drawable) o);
-
- if (intrinsicHeight != that.intrinsicHeight) return false;
- if (intrinsicWidth != that.intrinsicWidth) return false;
- if (bounds != null ? !bounds.equals(that.bounds) : that.bounds != null) return false;
-
- return true;
- }
-
- @Override @Implementation
- public int hashCode() {
- int result = bounds != null ? bounds.hashCode() : 0;
- result = 31 * result + intrinsicWidth;
- result = 31 * result + intrinsicHeight;
- return result;
- }
-
- @Implementation
- public void setAlpha(int alpha) {
- this.alpha = alpha;
- }
-
- @Implementation
- public void invalidateSelf() {
- wasInvalidated = true;
- }
-
- public int getAlpha() {
- return alpha;
- }
-
- public static void reset() {
- corruptStreamSources.clear();
- }
-
- public int getLoadedFromResourceId() {
- return loadedFromResourceId;
- }
-
- public void setLoadedFromResourceId(int resourceId) {
- loadedFromResourceId = resourceId;
- }
-
- public boolean wasInvalidated() {
- return wasInvalidated;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowEditText.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowEditText.java
deleted file mode 100644
index 50cf45528..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowEditText.java
+++ /dev/null
@@ -1,60 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.text.Editable;
-import android.text.SpannableStringBuilder;
-import android.text.TextUtils;
-import android.widget.EditText;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-/**
- * A shadow for EditText that provides support for listeners
- */
-@SuppressWarnings({"UnusedDeclaration"})
-@Implements(EditText.class)
-public class ShadowEditText extends ShadowTextView {
-
- private int maxLength = Integer.MAX_VALUE;
-
- public ShadowEditText() {
- focusable = true;
- focusableInTouchMode = true;
- }
-
- @Override
- public void applyAttributes() {
- super.applyAttributes();
- maxLength = attributeSet.getAttributeIntValue("android", "maxLength", Integer.MAX_VALUE);
- }
-
- @Override
- @Implementation(i18nSafe = true)
- public void setText(CharSequence str) {
- if ( !TextUtils.isEmpty(str) && str.length() > maxLength) {
- str = str.subSequence(0, maxLength);
- }
- super.setText(str);
- }
-
- @Override
- @Implementation
- public Editable getText() {
- CharSequence text = super.getText();
- if (!(text instanceof Editable)) {
- return new SpannableStringBuilder(text);
- }
- return (Editable) text;
- }
-
- @Override
- @Implementation
- public void setSelection(int index) {
- super.setSelection(index);
- }
-
- @Override
- @Implementation
- public void setSelection(int start, int end) {
- super.setSelection(start, end);
- }
-} \ No newline at end of file
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowEnvironment.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowEnvironment.java
deleted file mode 100644
index 27d49b7ab..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowEnvironment.java
+++ /dev/null
@@ -1,37 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import java.io.File;
-
-import android.os.Environment;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-@Implements(Environment.class)
-public class ShadowEnvironment {
-
- private static final String MEDIA_REMOVED = "removed";
-
- private static String externalStorageState = MEDIA_REMOVED;
-
- @Implementation
- public static String getExternalStorageState() {
- return externalStorageState;
- }
-
- public static void setExternalStorageState(String externalStorageState) {
- ShadowEnvironment.externalStorageState = externalStorageState;
- }
-
- @Implementation
- public static File getExternalStorageDirectory() {
- ShadowContext.EXTERNAL_CACHE_DIR.mkdirs();
- return ShadowContext.EXTERNAL_CACHE_DIR;
- }
-
- @Implementation
- public static File getExternalStoragePublicDirectory(String type) {
- File f = (type == null) ? ShadowContext.EXTERNAL_FILES_DIR : new File( ShadowContext.EXTERNAL_FILES_DIR, type );
- f.mkdirs();
- return f;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowExpandableListView.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowExpandableListView.java
deleted file mode 100644
index 5de3bac92..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowExpandableListView.java
+++ /dev/null
@@ -1,29 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.view.View;
-import android.widget.ExpandableListView;
-import android.widget.ExpandableListView.OnChildClickListener;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.internal.RealObject;
-
-@Implements(ExpandableListView.class)
-public class ShadowExpandableListView extends ShadowListView {
- @RealObject private ExpandableListView mExpandable;
- private OnChildClickListener mChildClickListener;
-
- @Implementation
- @Override
- public boolean performItemClick(View view, int position, long id) {
- if (mChildClickListener != null) {
- mChildClickListener.onChildClick(mExpandable, null, 0, position, id);
- return true;
- }
- return false;
- }
-
- @Implementation
- public void setOnChildClickListener(OnChildClickListener clildListener) {
- mChildClickListener = clildListener;
- }
-} \ No newline at end of file
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowFilter.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowFilter.java
deleted file mode 100644
index 6076f59fd..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowFilter.java
+++ /dev/null
@@ -1,10 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.widget.Filter;
-import com.xtremelabs.robolectric.internal.Implements;
-
-@SuppressWarnings({"UnusedDeclaration"})
-@Implements(Filter.class)
-public class ShadowFilter {
-
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowFloatMath.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowFloatMath.java
deleted file mode 100644
index 2a4f6b2f9..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowFloatMath.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.xtremelabs.robolectric.shadows;
-
-import android.util.FloatMath;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-@SuppressWarnings({"UnusedDeclaration"})
-@Implements(FloatMath.class)
-public class ShadowFloatMath {
- @Implementation
- public static float floor(float value) {
- return (float) Math.floor(value);
- }
-
- @Implementation
- public static float ceil(float value) {
- return (float) Math.ceil(value);
- }
-
- @Implementation
- public static float sin(float angle) {
- return (float) Math.sin(angle);
- }
-
- @Implementation
- public static float cos(float angle) {
- return (float) Math.cos(angle);
- }
-
- @Implementation
- public static float sqrt(float value) {
- return (float) Math.sqrt(value);
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowFragment.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowFragment.java
deleted file mode 100644
index 22c0aed87..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowFragment.java
+++ /dev/null
@@ -1,168 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.content.Intent;
-import android.content.res.Resources;
-import android.os.Bundle;
-import android.support.v4.app.Fragment;
-import android.support.v4.app.FragmentActivity;
-import android.support.v4.app.FragmentManager;
-import android.view.View;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.internal.RealObject;
-
-@Implements(Fragment.class)
-public class ShadowFragment {
- @RealObject
- protected Fragment realFragment;
-
- protected View view;
- protected FragmentActivity activity;
- private String tag;
- private Bundle savedInstanceState;
- private int containerViewId;
- private boolean shouldReplace;
- private Bundle arguments;
- private boolean attached;
- private boolean hidden;
- private boolean added;
-
- public void setView(View view) {
- this.view = view;
- }
-
- public void setActivity(FragmentActivity activity) {
- this.activity = activity;
- }
-
- @Implementation
- public View getView() {
- return view;
- }
-
- @Implementation
- public FragmentActivity getActivity() {
- return activity;
- }
-
- @Implementation
- public void startActivity(Intent intent) {
- new FragmentActivity().startActivity(intent);
- }
-
- @Implementation
- public void startActivityForResult(Intent intent, int requestCode) {
- activity.startActivityForResult(intent, requestCode);
- }
-
- @Implementation
- public FragmentManager getFragmentManager() {
- return activity.getSupportFragmentManager();
- }
-
- @Implementation
- public FragmentManager getChildFragmentManager() {
- // Doesn't follow support library behavior, but is correct enough
- // for robolectric v1.
- return getFragmentManager();
- }
-
- @Implementation
- public String getTag() {
- return tag;
- }
-
- @Implementation
- public Resources getResources() {
- if (activity == null) {
- throw new IllegalStateException("Fragment " + this + " not attached to Activity");
- }
- return activity.getResources();
- }
-
- public void setTag(String tag) {
- this.tag = tag;
- }
-
- public void setSavedInstanceState(Bundle savedInstanceState) {
- this.savedInstanceState = savedInstanceState;
- }
-
- public Bundle getSavedInstanceState() {
- return savedInstanceState;
- }
-
- public void setContainerViewId(int containerViewId) {
- this.containerViewId = containerViewId;
- }
-
- public int getContainerViewId() {
- return containerViewId;
- }
-
- public void setShouldReplace(boolean shouldReplace) {
- this.shouldReplace = shouldReplace;
- }
-
- public boolean getShouldReplace() {
- return shouldReplace;
- }
-
- @Implementation
- public Bundle getArguments() {
- return arguments;
- }
-
- @Implementation
- public void setArguments(Bundle arguments) {
- this.arguments = arguments;
- }
-
- @Implementation
- public final String getString(int resId) {
- if (activity == null) {
- throw new IllegalStateException("Fragment " + this + " not attached to Activity");
- }
- return activity.getString(resId);
- }
-
- @Implementation
- public final String getString(int resId, Object... formatArgs) {
- if (activity == null) {
- throw new IllegalStateException("Fragment " + this + " not attached to Activity");
- }
- return activity.getString(resId, formatArgs);
- }
-
- public void setAttached(boolean isAttached) {
- attached = isAttached;
- }
-
- public boolean isAttached() {
- return attached;
- }
-
- public void setHidden(boolean isHidden) {
- hidden = isHidden;
- }
-
- public void setAdded(boolean isAdded) {
- added = isAdded;
- }
-
- @Implementation
- public boolean isAdded() {
- return getActivity() != null && added;
- }
-
- @Implementation
- public boolean isHidden() {
- return hidden;
- }
-
- @Implementation
- public boolean isVisible() {
- return isAdded() && !isHidden() && getView() != null
- && getView().getVisibility() == View.VISIBLE;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowFragmentActivity.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowFragmentActivity.java
deleted file mode 100644
index 98172b7f7..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowFragmentActivity.java
+++ /dev/null
@@ -1,121 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.os.Bundle;
-import android.support.v4.app.Fragment;
-import android.support.v4.app.FragmentActivity;
-import android.support.v4.app.FragmentManager;
-import android.view.View;
-
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.internal.RealObject;
-import com.xtremelabs.robolectric.tester.android.util.TestFragmentManager;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-
-@Implements(FragmentActivity.class)
-public class ShadowFragmentActivity extends ShadowActivity {
- @RealObject
- FragmentActivity realObject;
-
- private TestFragmentManager fragmentManager;
- public static final String FRAGMENTS_TAG = "android:fragments";
-
- public void __constructor__() {
- fragmentManager = new TestFragmentManager(realObject);
- }
-
- @Implementation
- public void onCreate(Bundle bundle) {
- super.onCreate(bundle);
-
- if (bundle != null && bundle.containsKey(FRAGMENTS_TAG)) {
- Object[] fragments = (Object[]) bundle.getSerializable(FRAGMENTS_TAG);
-
- for (Object o : fragments) {
- SerializedFragmentState fragmentState = (SerializedFragmentState) o;
-
- try {
- Fragment fragment = fragmentState.fragmentClass.newInstance();
- shadowOf(fragment).setSavedInstanceState(bundle);
-
- fragmentManager.addFragment(fragmentState.containerId, fragmentState.tag, fragment, true);
- } catch (InstantiationException e) {
- throw new RuntimeException(e);
- } catch (IllegalAccessException e) {
- throw new RuntimeException(e);
- }
- }
- }
- }
-
- @Implementation
- public void onStart() {
- for (Fragment fragment : fragmentManager.getFragments()) {
- fragmentManager.startFragment(fragment);
- }
- }
-
- @Implementation
- public void onPause() {
- for(Fragment fragment : fragmentManager.getFragments()) {
- fragment.onPause();
- }
- }
-
- @Implementation
- public FragmentManager getSupportFragmentManager() {
- return fragmentManager;
- }
-
- @Implementation
- public void onSaveInstanceState(Bundle outState) {
- // We cannot figure out how to pass the RobolectricWiring test without doing this incredibly
- // terrible looking hack. I am very sorry.
- List<SerializedFragmentState> fragmentStates = new ArrayList<SerializedFragmentState>();
-
- for (Map.Entry<Integer, Fragment> entry : fragmentManager.getFragmentsById().entrySet()) {
- Fragment fragment = entry.getValue();
- fragment.onSaveInstanceState(outState);
- fragmentStates.add(new SerializedFragmentState(entry.getKey(), fragment));
- }
-
- outState.putSerializable(FRAGMENTS_TAG, fragmentStates.toArray());
- }
-
- @Implementation
- @Override
- public View getCurrentFocus() {
- View focusedView = super.getCurrentFocus();
- if (focusedView != null) {
- return focusedView;
- }
-
- for (Fragment fragment : fragmentManager.getFragments()) {
- View view = shadowOf(fragment).view;
- if (view != null) {
- focusedView = view.findFocus();
- if (focusedView != null) {
- return focusedView;
- }
- }
- }
- return null;
- }
-
- @Override
- public void clearFocus() {
- super.clearFocus();
-
- for (Fragment fragment : fragmentManager.getFragments()) {
- View view = shadowOf(fragment).view;
- if (view != null) {
- view.clearFocus();
- }
- }
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowFragmentPagerAdapter.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowFragmentPagerAdapter.java
deleted file mode 100644
index d919ba502..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowFragmentPagerAdapter.java
+++ /dev/null
@@ -1,32 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.support.v4.app.Fragment;
-import android.support.v4.app.FragmentManager;
-import android.support.v4.app.FragmentPagerAdapter;
-import android.view.ViewGroup;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.internal.RealObject;
-
-@Implements(FragmentPagerAdapter.class)
-public class ShadowFragmentPagerAdapter extends ShadowPagerAdapter{
- @RealObject
- private FragmentPagerAdapter realAdapter;
-
- private FragmentManager fragmentManager;
-
- @Implementation
- public void __constructor__(FragmentManager fm) {
- this.fragmentManager = fm;
- }
-
- @Implementation
- public void setPrimaryItem(ViewGroup container, int position, Object object) {
- fragmentManager.beginTransaction().add(container.getId(), (Fragment) object).commit();
- }
-
- @Implementation
- public Object instantiateItem(ViewGroup container, int position) {
- return realAdapter.getItem(position);
- }
-} \ No newline at end of file
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowFrameLayout.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowFrameLayout.java
deleted file mode 100644
index d96ca345f..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowFrameLayout.java
+++ /dev/null
@@ -1,31 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.content.Context;
-import android.util.AttributeSet;
-import android.view.View.MeasureSpec;
-import android.view.ViewGroup;
-import android.widget.FrameLayout;
-
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-/**
- * Shadow for {@link FrameLayout} that simulates its implementation.
- */
-@SuppressWarnings("UnusedDeclaration")
-@Implements(FrameLayout.class)
-public class ShadowFrameLayout extends ShadowViewGroup {
-
- public void __constructor__(Context context, AttributeSet attributeSet, int defStyle) {
- setLayoutParams(new ViewGroup.MarginLayoutParams(0, 0));
- super.__constructor__(context, attributeSet, defStyle);
- }
-
- @Implementation
- public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
- int width = MeasureSpec.getSize(widthMeasureSpec);
- int height = MeasureSpec.getSize(heightMeasureSpec);
-
- layout(right, top, right + width, top + height);
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowGallery.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowGallery.java
deleted file mode 100644
index 43dbcebda..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowGallery.java
+++ /dev/null
@@ -1,27 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.view.KeyEvent;
-import android.widget.Gallery;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.internal.RealObject;
-
-@Implements(Gallery.class)
-public class ShadowGallery extends ShadowAbsSpinner {
-
- @RealObject Gallery gallery;
-
- @Implementation
- public boolean onKeyDown(int keyCode, KeyEvent event) {
- switch (keyCode) {
- case KeyEvent.KEYCODE_DPAD_RIGHT:
- case KeyEvent.KEYCODE_DPAD_LEFT:
- if (onKeyListener != null) {
- onKeyListener.onKey(gallery, keyCode, event);
- }
- return true;
- }
- return false;
- }
-
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowGeoPoint.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowGeoPoint.java
deleted file mode 100644
index 03652b453..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowGeoPoint.java
+++ /dev/null
@@ -1,69 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import com.google.android.maps.GeoPoint;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf_;
-import static com.xtremelabs.robolectric.shadows.ShadowMapView.fromE6;
-
-@SuppressWarnings({"UnusedDeclaration"})
-@Implements(GeoPoint.class)
-public class ShadowGeoPoint {
- private int lat;
- private int lng;
-
- public void __constructor__(int lat, int lng) {
- this.lat = lat;
- this.lng = lng;
- }
-
- @Implementation
- public int getLatitudeE6() {
- return lat;
- }
-
- @Implementation
- public int getLongitudeE6() {
- return lng;
- }
-
- @Override @Implementation
- public boolean equals(Object o) {
- if (o == null) return false;
- o = shadowOf_(o);
- if (o == null) return false;
- if (this == o) return true;
- if (getClass() != o.getClass()) return false;
-
- ShadowGeoPoint that = (ShadowGeoPoint) o;
-
- if (lat != that.lat) return false;
- if (lng != that.lng) return false;
-
- return true;
- }
-
- @Override @Implementation
- public int hashCode() {
- int result = lat;
- result = 31 * result + lng;
- return result;
- }
-
- @Override @Implementation
- public String toString() {
- return "ShadowGeoPoint{" +
- "lat=" + fromE6(lat) +
- ", lng=" + fromE6(lng) +
- '}';
- }
-
- public int getLat() {
- return lat;
- }
-
- public int getLng() {
- return lng;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowGeocoder.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowGeocoder.java
deleted file mode 100644
index bbc6bb064..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowGeocoder.java
+++ /dev/null
@@ -1,156 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.location.Address;
-import android.location.Geocoder;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Locale;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-
-/**
- * A shadow for Geocoder that supports simulated responses and failures
- */
-@SuppressWarnings({"UnusedDeclaration"})
-@Implements(Geocoder.class)
-public class ShadowGeocoder {
- private String addressLine1;
- private String city;
- private String state;
- private String zip;
- private String countryCode;
- private boolean wasCalled;
- private double lastLatitude;
- private double lastLongitude;
- private String lastLocationName;
- private double simulatedLatitude;
- private double simulatedLongitude;
- private boolean shouldSimulateGeocodeException;
- private boolean hasLatitude;
- private boolean hasLongitude;
- private boolean returnNoResults = false;
- private boolean didResolution;
-
- @Implementation
- public List<Address> getFromLocation(double latitude, double longitude, int maxResults) throws IOException {
- wasCalled = true;
- this.lastLatitude = latitude;
- this.lastLongitude = longitude;
- if (shouldSimulateGeocodeException) {
- throw new IOException("Simulated geocode exception");
- }
- Address address = makeAddress();
- address.setAddressLine(0, addressLine1);
- address.setLocality(city);
- address.setAdminArea(state);
- address.setPostalCode(zip);
- address.setCountryCode(countryCode);
- return oneElementList(address);
- }
-
- @Implementation
- public List<Address> getFromLocationName(String locationName, int maxResults) throws IOException {
- didResolution = true;
- this.lastLocationName = locationName;
- if (shouldSimulateGeocodeException) {
- throw new IOException("Simulated geocode exception");
- }
- if (returnNoResults) {
- return new ArrayList<Address>();
- } else {
- Address address = makeAddress();
- address.setLatitude(simulatedLatitude);
- address.setLongitude(simulatedLongitude);
- return oneElementList(address);
- }
- }
-
- private Address makeAddress() {
- Address address = new Address(Locale.getDefault());
- shadowOf(address).setSimulatedHasLatLong(hasLatitude, hasLongitude);
- return address;
- }
-
- /**
- * Sets up a simulated response for {@link #getFromLocation(double, double, int)}
- *
- * @param address the address for the response
- * @param city the city for the response
- * @param state the state for the response
- * @param zip the zip code for the response
- * @param countryCode the country code for the response
- */
- public void setSimulatedResponse(String address, String city, String state, String zip, String countryCode) {
- this.addressLine1 = address;
- this.city = city;
- this.state = state;
- this.zip = zip;
- this.countryCode = countryCode;
- }
-
-
- /**
- * Sets up a simulated response for {@link #getFromLocationName(String, int)}}
- *
- * @param lat latitude for simulated response
- * @param lng longitude for simulated response
- */
- public void setSimulatedLatLong(double lat, double lng) {
- this.simulatedLatitude = lat;
- this.simulatedLongitude = lng;
- }
-
- /**
- * Sets a flag to indicate whether or not {@link #getFromLocationName(String, int)} should throw an exception to
- * simulate a failure.
- *
- * @param shouldSimulateException whether or not an exception should be thrown from {@link #getFromLocationName(String, int)}
- */
- public void setShouldSimulateGeocodeException(boolean shouldSimulateException) {
- this.shouldSimulateGeocodeException = true;
- }
-
- /**
- * Non-Android accessor that indicates whether {@link #getFromLocation(double, double, int)} was called.
- *
- * @return whether {@link #getFromLocation(double, double, int)} was called.
- */
- public boolean wasGetFromLocationCalled() {
- return wasCalled;
- }
-
- public double getLastLongitude() {
- return lastLongitude;
- }
-
- public double getLastLatitude() {
- return lastLatitude;
- }
-
- public String getLastLocationName() {
- return lastLocationName;
- }
-
- private List<Address> oneElementList(Address address) {
- ArrayList<Address> addresses = new ArrayList<Address>();
- addresses.add(address);
- return addresses;
- }
-
- public void setSimulatedHasLatLong(boolean hasLatitude, boolean hasLongitude) {
- this.hasLatitude = hasLatitude;
- this.hasLongitude = hasLongitude;
- }
-
- public void setReturnNoResults(boolean returnNoResults) {
- this.returnNoResults = returnNoResults;
- }
-
- public boolean didResolution() {
- return didResolution;
- }
-} \ No newline at end of file
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowGridView.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowGridView.java
deleted file mode 100644
index e69a19b35..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowGridView.java
+++ /dev/null
@@ -1,18 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.widget.GridView;
-import android.widget.ListAdapter;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.internal.RealObject;
-
-@SuppressWarnings({"UnusedDeclaration"})
-@Implements(GridView.class)
-public class ShadowGridView extends ShadowAdapterView {
- @RealObject private GridView realGridView;
-
- @Implementation
- public void setAdapter(ListAdapter adapter) {
- super.setAdapter(adapter);
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowHandler.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowHandler.java
deleted file mode 100644
index 51265f36c..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowHandler.java
+++ /dev/null
@@ -1,231 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.os.Handler;
-import android.os.Looper;
-import android.os.Message;
-
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.internal.RealObject;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-
-/**
- * Shadow for Handler that puts posted {@link Runnable}s into a queue instead of sending them to be handled on a
- * separate thread.{@link Runnable}s that are scheduled to be executed immediately can be triggered by calling
- * {@link #idleMainLooper()}.
- * todo: add utility method to advance time and trigger execution of Runnables scheduled for a time in the future
- */
-@SuppressWarnings({"UnusedDeclaration"})
-@Implements(Handler.class)
-public class ShadowHandler {
- @RealObject
- private Handler realHandler;
- private Looper looper = Looper.myLooper();
- private List<Message> messages = new ArrayList<Message>();
- private Handler.Callback callback;
-
- public void __constructor__() {
- this.looper = Looper.myLooper();
- }
-
- public void __constructor__(Looper looper) {
- this.looper = looper;
- }
-
- public void __constructor__(Handler.Callback callback) {
- this.callback = callback;
- }
-
- @Implementation
- public boolean post(Runnable r) {
- return postDelayed(r, 0);
- }
-
- @Implementation
- public boolean postDelayed(Runnable r, long delayMillis) {
- return shadowOf(looper).post(r, delayMillis);
- }
-
- @Implementation
- public final boolean postAtFrontOfQueue(Runnable runnable) {
- return shadowOf(looper).postAtFrontOfQueue(runnable);
- }
-
- @Implementation
- public Message obtainMessage() {
- return obtainMessage(0);
- }
-
- @Implementation
- public Message obtainMessage(int what) {
- return obtainMessage(what, null);
- }
-
- @Implementation
- public Message obtainMessage(int what, Object obj) {
- return obtainMessage(what, 0, 0, obj);
- }
-
- @Implementation
- public Message obtainMessage(int what, int arg1, int arg2) {
- return obtainMessage(what, arg1, arg2, null);
- }
-
- @Implementation
- public Message obtainMessage(int what, int arg1, int arg2, Object obj) {
- Message message = new Message();
- message.what = what;
- message.arg1 = arg1;
- message.arg2 = arg2;
- message.obj = obj;
- message.setTarget(realHandler);
- return message;
- }
-
- @Implementation
- public final boolean sendMessage(final Message msg) {
- return sendMessageDelayed(msg, 0L);
- }
-
- @Implementation
- public final boolean sendMessageDelayed(final Message msg, long delayMillis) {
- Robolectric.shadowOf(msg).setWhen(Robolectric.shadowOf(looper).getScheduler().getCurrentTime()+delayMillis);
- messages.add(msg);
- postDelayed(new Runnable() {
- @Override
- public void run() {
- if (messages.contains(msg)) {
- messages.remove(msg);
- routeMessage(msg);
- }
- }
- }, delayMillis);
- return true;
- }
-
- private void routeMessage(Message msg) {
- if(callback != null) {
- callback.handleMessage(msg);
- } else {
- realHandler.handleMessage(msg);
- }
- }
-
- @Implementation
- public final boolean sendEmptyMessage(int what) {
- return sendEmptyMessageDelayed(what, 0L);
- }
-
- @Implementation
- public final boolean sendEmptyMessageDelayed(int what, long delayMillis) {
- final Message msg = new Message();
- msg.what = what;
- return sendMessageDelayed(msg, delayMillis);
- }
-
- @Implementation
- public final boolean sendMessageAtFrontOfQueue(final Message msg) {
- Robolectric.shadowOf(msg).setWhen(Robolectric.shadowOf(looper).getScheduler().getCurrentTime());
- messages.add(0, msg);
- postAtFrontOfQueue(new Runnable() {
- @Override
- public void run() {
- if (messages.contains(msg)) {
- messages.remove(msg);
- routeMessage(msg);
- }
- }
- });
- return true;
- }
-
- @Implementation
- public final Looper getLooper() {
- return looper;
- }
-
- @Implementation
- public final void removeCallbacks(java.lang.Runnable r) {
- shadowOf(looper).getScheduler().remove(r);
- }
-
- @Implementation
- public final boolean hasMessages(int what) {
- for (Message message : messages) {
- if (message.what == what) {
- return true;
- }
- }
- return false;
- }
-
- @Implementation
- public final boolean hasMessages(int what, Object object) {
- for (Message message : messages) {
- if(message.what == what && message.obj == object) {
- return true;
- }
- }
- return false;
- }
-
-
- @Implementation
- public final void removeMessages(int what) {
- removeMessages(what, null);
- }
-
- @Implementation
- public final void removeMessages(int what, Object object) {
- for (Iterator<Message> iterator = messages.iterator(); iterator.hasNext(); ) {
- Message message = iterator.next();
- if (message.what == what && (object == null || object.equals(message.obj))) {
- iterator.remove();
- }
- }
- }
-
-
-
- /**
- * @deprecated use {@link #idleMainLooper()} instead
- */
- public static void flush() {
- idleMainLooper();
- }
-
- /**
- * @see com.xtremelabs.robolectric.shadows.ShadowLooper#idle()
- */
- public static void idleMainLooper() {
- shadowOf(Looper.myLooper()).idle();
- }
-
- /**
- * @see ShadowLooper#runToEndOfTasks() ()
- */
- public static void runMainLooperToEndOfTasks() {
- shadowOf(Looper.myLooper()).runToEndOfTasks();
- }
-
-
- /**
- * @see ShadowLooper#runOneTask() ()
- */
- public static void runMainLooperOneTask() {
- shadowOf(Looper.myLooper()).runOneTask();
- }
-
- /**
- * @see ShadowLooper#runToNextTask() ()
- */
- public static void runMainLooperToNextTask() {
- shadowOf(Looper.myLooper()).runToNextTask();
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowHandlerThread.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowHandlerThread.java
deleted file mode 100644
index 1bcfa0fce..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowHandlerThread.java
+++ /dev/null
@@ -1,80 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.internal.RealObject;
-
-import android.os.HandlerThread;
-import android.os.Looper;
-
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-
-@Implements(HandlerThread.class)
-public class ShadowHandlerThread {
- private Looper looper;
-
- @RealObject
- private HandlerThread thread;
-
- public void __constructor__(String name) {
- __constructor__(name, -1);
- }
-
- @SuppressWarnings("UnusedParameters")
- public void __constructor__(String name, int priority) {
- }
-
- @Implementation
- public void run() {
- Looper.prepare();
- synchronized (this) {
- looper = Looper.myLooper();
- onLooperPrepared();
- notifyAll();
- }
- Looper.loop();
- }
-
- @Implementation
- public Looper getLooper() {
- if (!thread.isAlive()) {
- return null;
- }
-
- // If the thread has been started, wait until the looper has been created.
- synchronized (this) {
- while (thread.isAlive() && looper == null) {
- try {
- wait();
- } catch (InterruptedException ignored) {
- }
- }
- }
- return looper;
- }
-
- @Implementation
- public boolean quit() {
- Looper looper = getLooper();
- if (looper != null) {
- looper.quit();
- return true;
- }
- return false;
- }
-
- @Implementation
- public void onLooperPrepared() {
- Method prepared;
- try {
- prepared = HandlerThread.class.getDeclaredMethod("onLooperPrepared");
- prepared.setAccessible(true);
- prepared.invoke(thread);
- } catch (NoSuchMethodException ignored) {
- } catch (InvocationTargetException ignored) {
- } catch (IllegalAccessException ignored) {
- }
- }
-
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowHtml.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowHtml.java
deleted file mode 100644
index a89641f9e..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowHtml.java
+++ /dev/null
@@ -1,87 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.text.Html;
-import android.text.Spanned;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-@SuppressWarnings({"UnusedDeclaration"})
-@Implements(Html.class)
-public class ShadowHtml {
-
- @Implementation
- public static Spanned fromHtml(String source) {
- if (source == null) {
- /*
- * Mimic the behavior of the real fromHtml() method. It uses a
- * StringReader that throws a NullPointerException when a null
- * string is passed in.
- */
- throw new NullPointerException();
- }
- return new SpannedThatActsLikeString(source);
- }
-
- private static class SpannedThatActsLikeString implements Spanned {
- String source;
-
- private SpannedThatActsLikeString(String source) {
- this.source = source;
- }
-
- @Override
- public <T> T[] getSpans(int start, int end, Class<T> type) {
- return null;
- }
-
- @Override
- public int getSpanStart(Object tag) {
- return 0;
- }
-
- @Override
- public int getSpanEnd(Object tag) {
- return 0;
- }
-
- @Override
- public int getSpanFlags(Object tag) {
- return 0;
- }
-
- @Override
- public int nextSpanTransition(int start, int limit, Class type) {
- return 0;
- }
-
- @Override
- public int length() {
- return source.length();
- }
-
- @Override
- public char charAt(int i) {
- return source.charAt(i);
- }
-
- @Override
- public CharSequence subSequence(int i, int i1) {
- return null;
- }
-
- @Override
- public String toString() {
- return source;
- }
-
- @Override
- public boolean equals(Object o) {
- return source.equals(o);
- }
-
- @Override
- public int hashCode() {
- return source != null ? source.hashCode() : 0;
- }
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowImageView.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowImageView.java
deleted file mode 100644
index 9963cdf7b..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowImageView.java
+++ /dev/null
@@ -1,178 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.graphics.Bitmap;
-import android.graphics.BitmapFactory;
-import android.graphics.Canvas;
-import android.graphics.Matrix;
-import android.graphics.drawable.AnimationDrawable;
-import android.graphics.drawable.BitmapDrawable;
-import android.graphics.drawable.Drawable;
-import android.graphics.drawable.LayerDrawable;
-import android.widget.ImageView;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.res.ResourceLoader;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-
-@Implements(ImageView.class)
-public class ShadowImageView extends ShadowView {
- private Drawable imageDrawable;
- private int alpha;
- private int resourceId;
- private Bitmap imageBitmap;
- private ImageView.ScaleType scaleType;
- private Matrix matrix;
- private int imageLevel;
-
- @Override
- public void applyAttributes() {
- super.applyAttributes();
- applyImageAttribute();
- }
-
- @Implementation
- public void setImageBitmap(Bitmap imageBitmap) {
- setImageDrawable(new BitmapDrawable(imageBitmap));
- this.imageBitmap = imageBitmap;
- }
-
- @Deprecated
- public Bitmap getImageBitmap() {
- return imageBitmap;
- }
-
- @Implementation
- public void setImageDrawable(Drawable drawable) {
- this.imageDrawable = drawable;
- }
-
- @Implementation
- public void setImageResource(int resId) {
- this.resourceId = resId;
- setImageDrawable(buildDrawable(resId));
- }
-
- /**
- * Build drawable, either LayerDrawable or BitmapDrawable.
- *
- * @param resourceId Resource id
- * @return Drawable
- */
- protected Drawable buildDrawable(int resourceId) {
- if (isDrawableXml(resourceId)) {
- ResourceLoader resourceLoader = shadowOf(Robolectric.application).getResourceLoader();
- int[] resourceIds = resourceLoader.getDrawableIds(resourceId);
- Drawable[] drawables = new Drawable[resourceIds.length];
-
- for (int i = 0; i < resourceIds.length; i++) {
- drawables[i] = buildDrawable(resourceIds[i]);
- }
- if (resourceLoader.isAnimatableXml(resourceId)) {
- AnimationDrawable animationDrawable = new AnimationDrawable();
- for (Drawable drawable : drawables) {
- animationDrawable.addFrame(drawable, -1);
- }
- return animationDrawable;
- } else {
- LayerDrawable layerDrawable = new LayerDrawable(drawables);
- shadowOf(layerDrawable).setLoadedFromResourceId(resourceId);
- return layerDrawable;
- }
- } else {
- return new BitmapDrawable(BitmapFactory.decodeResource(
- getResources(), resourceId));
- }
- }
-
- /**
- * Does the resource id point to xml resource.
- *
- * @param resourceId Resource id
- * @return Boolean
- */
- private boolean isDrawableXml(int resourceId) {
- return shadowOf(Robolectric.application).getResourceLoader()
- .isDrawableXml(resourceId);
- }
-
- @Implementation
- public void setAlpha(int alpha) {
- this.alpha = alpha;
- }
-
- @Implementation
- public ImageView.ScaleType getScaleType() {
- return scaleType;
- }
-
- @Implementation
- public void setScaleType(ImageView.ScaleType scaleType) {
- this.scaleType = scaleType;
- }
-
- @Implementation
- public Drawable getDrawable() {
- return imageDrawable;
- }
-
- /**
- * @return the image drawable
- * @deprecated Use android.widget.ImageView#getDrawable() instead.
- */
- @Deprecated
- public Drawable getImageDrawable() {
- return imageDrawable;
- }
-
- @Implementation
- public int getAlpha() {
- return alpha;
- }
-
- @Deprecated
- public int getResourceId() {
- return resourceId;
- }
-
- @Implementation
- public void setImageMatrix(Matrix matrix) {
- this.matrix = new Matrix(matrix);
- }
-
- @Implementation
- public void draw(Canvas canvas) {
- if (matrix != null) {
- canvas.translate(shadowOf(matrix).getTransX(), shadowOf(matrix)
- .getTransY());
- canvas.scale(shadowOf(matrix).getScaleX(), shadowOf(matrix)
- .getScaleY());
- }
- imageDrawable.draw(canvas);
- }
-
- private void applyImageAttribute() {
- String source = attributeSet.getAttributeValue("android", "src");
- if (source != null) {
- if (source.startsWith("@drawable/")) {
- setImageResource(attributeSet.getAttributeResourceValue(
- "android", "src", 0));
- }
- }
- }
-
- @Implementation
- public void setImageLevel(int imageLevel) {
- this.imageLevel = imageLevel;
- }
-
- /**
- * Non-Android accessor.
- *
- * @return the imageLevel set in {@code setImageLevel(int)}
- */
- public int getImageLevel() {
- return imageLevel;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowInputMethodManager.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowInputMethodManager.java
deleted file mode 100644
index 16546dcb7..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowInputMethodManager.java
+++ /dev/null
@@ -1,41 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.os.IBinder;
-import android.os.ResultReceiver;
-import android.view.View;
-import android.view.inputmethod.InputMethodManager;
-
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-@Implements(InputMethodManager.class)
-public class ShadowInputMethodManager {
-
- private boolean softInputVisible;
-
- @Implementation
- public boolean showSoftInput(View view, int flags) {
- return showSoftInput(view, flags, null);
- }
-
- @Implementation
- public boolean showSoftInput(View view, int flags, ResultReceiver resultReceiver) {
- softInputVisible = true;
- return true;
- }
-
- @Implementation
- public boolean hideSoftInputFromWindow(IBinder windowToken, int flags) {
- return hideSoftInputFromWindow(windowToken, flags, null);
- }
-
- @Implementation
- public boolean hideSoftInputFromWindow(IBinder windowToken, int flags, ResultReceiver resultReceiver) {
- softInputVisible = false;
- return true;
- }
-
- public boolean isSoftInputVisible() {
- return softInputVisible;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowIntent.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowIntent.java
deleted file mode 100644
index 56d198ebd..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowIntent.java
+++ /dev/null
@@ -1,683 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.content.ComponentName;
-import android.content.Context;
-import android.content.Intent;
-import android.net.Uri;
-import android.os.Bundle;
-import android.os.Parcel;
-import android.os.Parcelable;
-import android.os.Parcelable.Creator;
-
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.internal.RealObject;
-import com.xtremelabs.robolectric.util.Join;
-
-import java.io.*;
-import java.util.*;
-
-import static android.content.Intent.*;
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-
-@SuppressWarnings({"UnusedDeclaration"})
-@Implements(Intent.class)
-public class ShadowIntent {
- @RealObject private Intent realIntent;
-
- private final Bundle extras = new Bundle();
- private String action;
- private ComponentName componentName;
- private String type;
- private Uri data;
- private int flags;
- private Class<?> intentClass;
- private String packageName;
- private final Set<String> categories = new HashSet<String>();
-
- public void __constructor__(Context packageContext, Class cls) {
- componentName = new ComponentName(packageContext, cls);
- intentClass = cls;
- }
-
- public void __constructor__(String action, Uri uri) {
- this.action = action;
- data = uri;
- }
-
- public void __constructor__(String action) {
- __constructor__(action, null);
- }
-
- public void __constructor__(Intent intent) {
- ShadowIntent other = shadowOf(intent);
- extras.putAll(other.extras);
- action = other.action;
- componentName = other.componentName;
- type = other.type;
- data = other.data;
- flags = other.flags;
- intentClass = other.intentClass;
- packageName = other.packageName;
- categories.addAll(other.categories);
- }
-
- @Implementation
- public static Intent createChooser(Intent target, CharSequence title) {
- Intent intent = new Intent(Intent.ACTION_CHOOSER);
- intent.putExtra(Intent.EXTRA_INTENT, target);
- if (title != null) {
- intent.putExtra(Intent.EXTRA_TITLE, title);
- }
- return intent;
- }
-
- @Implementation
- public Intent setAction(String action) {
- this.action = action;
- return realIntent;
- }
-
- @Implementation
- public String getAction() {
- return action;
- }
-
- @Implementation
- public Intent setType(String type) {
- this.type = type;
- this.data = null;
- return realIntent;
- }
-
- @Implementation
- public Intent setDataAndType(Uri data, String type) {
- this.data = data;
- this.type = type;
- return realIntent;
- }
-
- @Implementation
- public String getType() {
- return type;
- }
-
- @Implementation
- public Intent addCategory(String category) {
- categories.add(category);
- return realIntent;
- }
-
- @Implementation
- public void removeCategory(String category) {
- categories.remove(category);
- }
-
- @Implementation
- public boolean hasCategory(String category) {
- return categories.contains(category);
- }
-
- @Implementation
- public Set<String> getCategories() {
- return categories;
- }
-
- @Implementation
- public Intent setPackage(String packageName) {
- this.packageName = packageName;
- return realIntent;
- }
-
- @Implementation
- public String getPackage() {
- return packageName;
- }
-
- @Implementation
- public Uri getData() {
- return data;
- }
-
- @Implementation
- public Intent setClass(Context packageContext, Class<?> cls) {
- this.intentClass = cls;
- return realIntent;
- }
-
- @Implementation
- public Intent setClassName(String packageName, String className) {
- componentName = new ComponentName(packageName, className);
- try {
- this.intentClass = Class.forName(className);
- } catch (ClassNotFoundException e) {
- // ignore
- }
- return realIntent;
- }
-
- @Implementation
- public Intent setClassName(Context packageContext, String className) {
- componentName = new ComponentName(packageContext.getPackageName(), className);
- return realIntent;
- }
-
- @Implementation
- public Intent setData(Uri data) {
- this.data = data;
- this.type = null;
- return realIntent;
- }
-
- @Implementation
- public int getFlags() {
- return flags;
- }
-
- @Implementation
- public Intent setFlags(int flags) {
- this.flags = flags;
- return realIntent;
- }
-
- @Implementation
- public Intent addFlags(int flags) {
- this.flags |= flags;
- return realIntent;
- }
-
- @Implementation
- public Intent putExtras(Bundle src) {
- extras.putAll(src);
- return realIntent;
- }
-
- @Implementation
- public Intent putExtras(Intent src) {
- ShadowIntent srcShadowIntent = shadowOf(src);
- extras.putAll(srcShadowIntent.extras);
- return realIntent;
- }
-
- @Implementation
- public Bundle getExtras() {
- return extras != null ? new Bundle(extras) : null;
- }
-
- @Implementation
- public Intent putExtra(String key, int value) {
- extras.putInt(key, value);
- return realIntent;
- }
-
- @Implementation
- public Intent putExtra(String key, double value) {
- extras.putDouble(key, value);
- return realIntent;
- }
-
- @Implementation
- public Intent putExtra(String key, float value) {
- extras.putFloat(key, value);
- return realIntent;
- }
-
- @Implementation
- public Intent putExtra(String key, long value) {
- extras.putLong(key, value);
- return realIntent;
- }
-
- @Implementation
- public Intent putExtra(String key, Serializable value) {
- extras.putSerializable(key, serializeCycle(value));
- return realIntent;
- }
-
- @Implementation
- public Intent putExtra(String key, Parcelable value) {
- extras.putParcelable(key, value);
- return realIntent;
- }
-
- @Implementation
- public Intent putExtra(String key, Parcelable[] value) {
- extras.putParcelableArray(key, value);
- return realIntent;
- }
-
- @Implementation
- public Intent putExtra(String key, String value) {
- extras.putString(key, value);
- return realIntent;
- }
-
- @Implementation
- public Intent putExtra(String key, String[] value) {
- extras.putStringArray(key, value);
- return realIntent;
- }
-
- @Implementation
- public Intent putExtra(String key, Bundle value) {
- extras.putBundle(key, value);
- return realIntent;
- }
-
- @Implementation
- public Intent putExtra(String key, boolean value) {
- extras.putBoolean(key, value);
- return realIntent;
- }
-
- @Implementation
- public Intent putExtra(String key, int[] value) {
- extras.putIntArray(key, value);
- return realIntent;
- }
-
- @Implementation
- public Intent putExtra(String key, long[] value) {
- extras.putLongArray(key, value);
- return realIntent;
- }
-
- @Implementation
- public int[] getIntArrayExtra(String name) {
- return extras.getIntArray(name);
- }
-
- @Implementation
- public long[] getLongArrayExtra(String name) {
- return extras.getLongArray(name);
- }
-
- @Implementation
- public boolean getBooleanExtra(String name, boolean defaultValue) {
- return extras.getBoolean(name, defaultValue);
- }
-
- @Implementation
- public String[] getStringArrayExtra(String name) {
- return extras.getStringArray(name);
- }
-
- @Implementation
- public Intent putExtra(String key, CharSequence value) {
- extras.putCharSequence(key, value);
- return realIntent;
- }
-
- @Implementation
- public CharSequence getCharSequenceExtra(String name) {
- return extras.getCharSequence(name);
- }
-
- @Implementation
- public void putExtra(String key, byte[] value) {
- extras.putByteArray(key, value);
- }
-
- @Implementation
- public Intent putStringArrayListExtra(String key, ArrayList<String> value) {
- extras.putStringArrayList(key, value);
- return realIntent;
- }
-
- @Implementation
- public ArrayList<String> getStringArrayListExtra(String name) {
- return extras.getStringArrayList(name);
- }
-
- @Implementation
- public Intent putIntegerArrayListExtra(String key, ArrayList<Integer> value) {
- extras.putIntegerArrayList(key, value);
- return realIntent;
- }
-
- @Implementation
- public ArrayList<Integer> getIntegerArrayListExtra(String name) {
- return extras.getIntegerArrayList(name);
- }
-
- @Implementation
- public Intent putParcelableArrayListExtra(String key, ArrayList<Parcelable> value) {
- extras.putParcelableArrayList(key, value);
- return realIntent;
- }
-
- @Implementation
- public ArrayList<Parcelable> getParcelableArrayListExtra(String key) {
- return extras.getParcelableArrayList(key);
- }
-
- @Implementation
- public boolean hasExtra(String name) {
- return extras.containsKey(name);
- }
-
- @Implementation
- public String getStringExtra(String name) {
- return extras.getString(name);
- }
-
- @Implementation
- public Parcelable getParcelableExtra(String name) {
- return extras.getParcelable(name);
- }
-
- @Implementation
- public Parcelable[] getParcelableArrayExtra(String name) {
- return extras.getParcelableArray(name);
- }
-
- @Implementation
- public int getIntExtra(String name, int defaultValue) {
- return extras.getInt(name, defaultValue);
- }
-
- @Implementation
- public long getLongExtra(String name, long defaultValue) {
- return extras.getLong(name, defaultValue);
- }
-
- @Implementation
- public double getDoubleExtra(String name, double defaultValue) {
- return extras.getDouble(name, defaultValue);
- }
-
- @Implementation
- public Bundle getBundleExtra(String name) {
- return extras.getBundle(name);
- }
-
- @Implementation
- public float getFloatExtra(String name, float defaultValue) {
- return extras.getFloat(name, defaultValue);
- }
-
- @Implementation
- public byte[] getByteArrayExtra(String name) {
- return extras.getByteArray(name);
- }
-
- @Implementation
- public Serializable getSerializableExtra(String name) {
- return extras.getSerializable(name);
- }
-
- @Implementation
- public void removeExtra(String name) {
- extras.remove(name);
- }
-
- @Implementation
- public Intent setComponent(ComponentName componentName) {
- this.componentName = componentName;
- return realIntent;
- }
-
- @Implementation
- public ComponentName getComponent() {
- return componentName;
- }
-
- @Implementation
- public int fillIn(Intent otherIntent, int flags) {
- int changes = 0;
- ShadowIntent other = shadowOf(otherIntent);
-
- if (other.action != null && (action == null || (flags & FILL_IN_ACTION) != 0)) {
- action = other.action;
- changes |= FILL_IN_ACTION;
- }
- if ((other.data != null || other.type != null)
- && ((data == null && type == null) || (flags & FILL_IN_DATA) != 0)) {
- data = other.data;
- type = other.type;
- changes |= FILL_IN_DATA;
- }
- if (!other.categories.isEmpty()
- && (categories.isEmpty() || (flags & FILL_IN_CATEGORIES) != 0)) {
- categories.addAll(other.categories);
- changes |= FILL_IN_CATEGORIES;
- }
- if (other.packageName != null
- && (packageName == null || (flags & FILL_IN_PACKAGE) != 0)) {
- packageName = other.packageName;
- changes |= FILL_IN_PACKAGE;
- }
- if (other.componentName != null && (flags & FILL_IN_COMPONENT) != 0) {
- componentName = other.componentName;
- changes |= FILL_IN_COMPONENT;
- }
-
- extras.putAll(other.extras);
- return changes;
- }
-
- @Implementation
- // cribbed from Android source
- public boolean filterEquals(Intent other) {
- if (other == null) {
- return false;
- }
- if (getAction() != other.getAction()) {
- if (getAction() != null) {
- if (!getAction().equals(other.getAction())) {
- return false;
- }
- } else {
- if (!other.getAction().equals(getAction())) {
- return false;
- }
- }
- }
- if (getData() != other.getData()) {
- if (getData() != null) {
- if (!getData().equals(other.getData())) {
- return false;
- }
- } else {
- if (!other.getData().equals(getData())) {
- return false;
- }
- }
- }
- if (getType() != other.getType()) {
- if (getType() != null) {
- if (!getType().equals(other.getType())) {
- return false;
- }
- } else {
- if (!other.getType().equals(getType())) {
- return false;
- }
- }
- }
- if (getPackage() != other.getPackage()) {
- if (getPackage() != null) {
- if (!getPackage().equals(other.getPackage())) {
- return false;
- }
- } else {
- if (!other.getPackage().equals(getPackage())) {
- return false;
- }
- }
- }
- if (getComponent() != other.getComponent()) {
- if (getComponent() != null) {
- if (!getComponent().equals(other.getComponent())) {
- return false;
- }
- } else {
- if (!other.getComponent().equals(getComponent())) {
- return false;
- }
- }
- }
- if (getCategories() != other.getCategories()) {
- if (getCategories() != null) {
- if (!getCategories().equals(other.getCategories())) {
- return false;
- }
- } else {
- if (!other.getCategories().equals(getCategories())) {
- return false;
- }
- }
- }
-
- return true;
- }
-
- /**
- * Compares an {@code Intent} with a {@code ShadowIntent} (obtained via a call to
- * {@link Robolectric#shadowOf(android.content.Intent)})
- *
- * @param o a {@code ShadowIntent}
- * @return whether they are equivalent
- */
- @Deprecated
- public boolean realIntentEquals(ShadowIntent o) {
- if (this == o) return true;
- if (o == null || getClass() != o.getClass()) return false;
-
- if (action != null ? !action.equals(o.action) : o.action != null) return false;
- if (componentName != null ? !componentName.equals(o.componentName) : o.componentName != null)
- return false;
- if (data != null ? !data.equals(o.data) : o.data != null) return false;
- if (extras != null ? !extras.equals(o.extras) : o.extras != null) return false;
- if (type != null ? !type.equals(o.type) : o.type != null) return false;
- if (categories != null ? !categories.equals(o.categories) : o.categories != null) return false;
-
- return true;
- }
-
- @Override
- @Implementation
- public int hashCode() {
- int result = extras != null ? extras.hashCode() : 0;
- result = 31 * result + (action != null ? action.hashCode() : 0);
- result = 31 * result + (componentName != null ? componentName.hashCode() : 0);
- result = 31 * result + (data != null ? data.hashCode() : 0);
- result = 31 * result + (type != null ? type.hashCode() : 0);
- result = 31 * result + flags;
- return result;
- }
-
- @Override
- @Implementation
- public boolean equals(Object o) {
- if (!(o instanceof Intent)) return false;
- return realIntentEquals(shadowOf((Intent) o));
- }
-
- /**
- * Non-Android accessor that returns the {@code Class} object set by
- * {@link #setClass(android.content.Context, Class)}
- *
- * @return the {@code Class} object set by
- * {@link #setClass(android.content.Context, Class)}
- */
- public Class<?> getIntentClass() {
- return intentClass;
- }
-
- @Override
- @Implementation
- public String toString() {
- return "Intent{" +
- Join.join(
- ", ",
- ifWeHave(componentName, "componentName"),
- ifWeHave(action, "action"),
- ifWeHave(extras, "extras"),
- ifWeHave(data, "data"),
- ifWeHave(type, "type")
- ) +
- '}';
- }
-
- @Implementation
- public void writeToParcel(Parcel out, int flags) {
- out.writeString(action);
- if (data != null) {
- out.writeInt(1);
- Uri.writeToParcel(out, data);
- } else {
- out.writeInt(-1);
- }
- out.writeString(type);
- out.writeInt(flags);
- out.writeString(packageName);
- ComponentName.writeToParcel(componentName, out);
- out.writeInt(categories.size());
-
- for (String category : categories) {
- out.writeString(category);
- }
- out.writeBundle(extras);
- }
-
- @Implementation
- public void readFromParcel(Parcel in) {
- setAction(in.readString());
- if (in.readInt() == 1) {
- data = Uri.CREATOR.createFromParcel(in);
- }
- type = in.readString();
- flags = in.readInt();
- packageName = in.readString();
- componentName = ComponentName.readFromParcel(in);
- int N = in.readInt();
- for (int i = 0; i < N; i++) {
- categories.add(in.readString().intern());
- }
- extras.putAll(in.readBundle());
- }
-
- private Serializable serializeCycle(Serializable serializable) {
- try {
- ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
- ObjectOutputStream output = new ObjectOutputStream(byteArrayOutputStream);
- output.writeObject(serializable);
- output.close();
-
- byte[] bytes = byteArrayOutputStream.toByteArray();
- ObjectInputStream input = new ObjectInputStream(new ByteArrayInputStream(bytes));
- return (Serializable) input.readObject();
- } catch (IOException e) {
- throw new RuntimeException(e);
- } catch (ClassNotFoundException e) {
- throw new RuntimeException(e);
- }
- }
-
- private String ifWeHave(Object o, String name) {
- if (o == null) return null;
- if (o instanceof Map && ((Map) o).isEmpty()) return null;
- return name + "=" + o;
- }
-
- public static final Creator<Intent> CREATOR =
- new Creator<Intent>() {
- @Override
- public Intent createFromParcel(Parcel source) {
- Intent intent = new Intent();
- intent.readFromParcel(source);
- return intent;
- }
-
- @Override
- public Intent[] newArray(int size) {
- return new Intent[size];
- }
- };
-
- public static void reset() {
- Robolectric.Reflection.setFinalStaticField(Intent.class, "CREATOR", CREATOR);
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowIntentFilter.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowIntentFilter.java
deleted file mode 100644
index fe8519819..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowIntentFilter.java
+++ /dev/null
@@ -1,69 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.content.IntentFilter;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-/**
- * Shadow of {@code IntentFilter} implemented with a {@link java.util.List}
- */
-@SuppressWarnings({"UnusedDeclaration"})
-@Implements(IntentFilter.class)
-public class ShadowIntentFilter {
- List<String> actions = new ArrayList<String>();
- List<String> schemes = new ArrayList<String>();
- List<IntentFilter.AuthorityEntry> authoritites = new ArrayList<IntentFilter.AuthorityEntry>();
-
- public void __constructor__(String action) {
- actions.add(action);
- }
-
- @Implementation
- public void addAction(String action) {
- actions.add(action);
- }
-
- @Implementation
- public String getAction(int index) {
- return actions.get(index);
- }
-
- @Implementation
- public int countActions() {
- return actions.size();
- }
-
- @Implementation
- public Iterator<String> actionsIterator() {
- return actions.iterator();
- }
-
- @Implementation
- public boolean matchAction(String action) {
- return actions.contains(action);
- }
-
- @Implementation
- public void addDataAuthority(String host, String port) {
- authoritites.add(new IntentFilter.AuthorityEntry(host, port));
- }
-
- @Implementation
- public final IntentFilter.AuthorityEntry getDataAuthority(int index) {
- return authoritites.get(index);
- }
-
- @Implementation
- public void addDataScheme(String scheme) {
- schemes.add(scheme);
- }
-
- @Implementation
- public String getDataScheme(int index) {
- return schemes.get(index);
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowIntentFilterAuthorityEntry.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowIntentFilterAuthorityEntry.java
deleted file mode 100644
index 5ebb4c1e3..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowIntentFilterAuthorityEntry.java
+++ /dev/null
@@ -1,30 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.content.IntentFilter;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-@Implements(IntentFilter.AuthorityEntry.class)
-public class ShadowIntentFilterAuthorityEntry {
- private String host;
- private int port;
-
- public void __constructor__(String host, String port) {
- this.host = host;
- if (port == null) {
- this.port = -1;
- } else {
- this.port = Integer.parseInt(port);
- }
- }
-
- @Implementation
- public String getHost() {
- return host;
- }
-
- @Implementation
- public int getPort() {
- return port;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowItemizedOverlay.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowItemizedOverlay.java
deleted file mode 100644
index 5c845fbe5..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowItemizedOverlay.java
+++ /dev/null
@@ -1,92 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.graphics.drawable.Drawable;
-import com.google.android.maps.ItemizedOverlay;
-import com.google.android.maps.OverlayItem;
-import com.google.android.maps.ShadowItemizedOverlayBridge;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.internal.RealObject;
-
-import java.util.ArrayList;
-
-/**
- * Shadow for {@code ItemizedOverlay} that keeps track of what has been called and enables the return value for
- * {@link #hitTest(com.google.android.maps.OverlayItem, android.graphics.drawable.Drawable, int, int)} to be set up by
- * tests.
- */
-@Implements(ItemizedOverlay.class)
-public class ShadowItemizedOverlay<Item extends OverlayItem> {
- private boolean isPopulated;
- private boolean shouldHit;
- private boolean lastFocusedIndexWasReset;
- private ArrayList<Item> items = new ArrayList<Item>();
-
- @RealObject
- private ItemizedOverlay<Item> realObject;
-
- @Implementation
- public final void populate() {
- isPopulated = true;
-
- items.clear();
- for (int i = 0; i < realObject.size(); i++) {
- items.add(getBridge().createItem(i));
- }
- }
-
- @Implementation
- public final Item getItem(int position) {
- return items.get(position);
- }
-
- @Implementation
- public boolean hitTest(OverlayItem item, android.graphics.drawable.Drawable drawable, int i, int i1) {
- return shouldHit;
- }
-
- @Implementation
- public void setLastFocusedIndex(int i) {
- lastFocusedIndexWasReset = (i == -1);
- }
-
- @Implementation
- public static Drawable boundCenterBottom(Drawable drawable) {
- return drawable;
- }
-
- /**
- * Non-Android accessor that indicates whether {@link #setLastFocusedIndex(int)} has been called with a value other
- * than -1.
- *
- * @return whether {@link #setLastFocusedIndex(int)} has been called with a value other
- * than -1
- */
- public boolean lastFocusedIndexWasReset() {
- return lastFocusedIndexWasReset;
- }
-
- public void setIsPopulated(boolean isPopulated) {
- this.isPopulated = isPopulated;
- }
-
- public boolean isPopulated() {
- return isPopulated;
- }
-
- /**
- * Sets up the return value for
- * {@link #hitTest(com.google.android.maps.OverlayItem, android.graphics.drawable.Drawable, int, int)}
- *
- * @param shouldHit the value that
- * {@link #hitTest(com.google.android.maps.OverlayItem, android.graphics.drawable.Drawable, int, int)}
- * should return
- */
- public void setShouldHit(boolean shouldHit) {
- this.shouldHit = shouldHit;
- }
-
- private ShadowItemizedOverlayBridge<Item> getBridge() {
- return new ShadowItemizedOverlayBridge<Item>(realObject);
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowJsPromptResult.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowJsPromptResult.java
deleted file mode 100644
index dfdf43879..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowJsPromptResult.java
+++ /dev/null
@@ -1,13 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.webkit.JsPromptResult;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.internal.Implements;
-
-@Implements(JsPromptResult.class)
-public class ShadowJsPromptResult extends ShadowJsResult{
-
- public static JsPromptResult newInstance() {
- return Robolectric.newInstanceOf(JsPromptResult.class);
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowJsResult.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowJsResult.java
deleted file mode 100644
index 88868dcfa..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowJsResult.java
+++ /dev/null
@@ -1,20 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.webkit.JsResult;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-@Implements(JsResult.class)
-public class ShadowJsResult {
-
- private boolean wasCancelled;
-
- @Implementation
- public void cancel() {
- wasCancelled = true;
- }
-
- public boolean wasCancelled() {
- return wasCancelled;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowKeyEvent.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowKeyEvent.java
deleted file mode 100644
index bc83e6f3f..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowKeyEvent.java
+++ /dev/null
@@ -1,27 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.view.KeyEvent;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-@SuppressWarnings({"UnusedDeclaration"})
-@Implements(KeyEvent.class)
-public class ShadowKeyEvent {
- private int action;
- private int code;
-
- public void __constructor__(int action, int code) {
- this.action = action;
- this.code = code;
- }
-
- @Implementation
- public final int getAction() {
- return action;
- }
-
- @Implementation
- public final int getKeyCode() {
- return code;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowKeyGuardLock.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowKeyGuardLock.java
deleted file mode 100644
index 0df3a336a..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowKeyGuardLock.java
+++ /dev/null
@@ -1,24 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.app.KeyguardManager;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-@Implements(KeyguardManager.KeyguardLock.class)
-public class ShadowKeyGuardLock {
- private boolean keyguardEnabled = true;
-
- @Implementation
- public void disableKeyguard() {
- keyguardEnabled = false;
- }
-
- @Implementation
- public void reenableKeyguard() {
- keyguardEnabled = true;
- }
-
- public boolean isEnabled() {
- return keyguardEnabled;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowKeyguardManager.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowKeyguardManager.java
deleted file mode 100644
index ac350de8c..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowKeyguardManager.java
+++ /dev/null
@@ -1,33 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.app.KeyguardManager;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.internal.RealObject;
-
-/**
- * Shadows the {@code android.app.KeyguardManager} class.
- */
-@Implements(KeyguardManager.class)
-public class ShadowKeyguardManager {
- @RealObject private KeyguardManager realKeyguardManager;
-
- private KeyguardManager.KeyguardLock keyguardLock = Robolectric.newInstanceOf(KeyguardManager.KeyguardLock.class);
-
- private boolean inRestrictedInputMode = false;
-
- @Implementation
- public boolean inKeyguardRestrictedInputMode() {
- return inRestrictedInputMode;
- }
-
- @Implementation
- public KeyguardManager.KeyguardLock newKeyguardLock(String tag) {
- return keyguardLock;
- }
-
- public void setinRestrictedInputMode(boolean restricted) {
- inRestrictedInputMode = restricted;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowLayerDrawable.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowLayerDrawable.java
deleted file mode 100644
index d5bde0907..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowLayerDrawable.java
+++ /dev/null
@@ -1,51 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.graphics.drawable.Drawable;
-import android.graphics.drawable.LayerDrawable;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.internal.RealObject;
-
-import java.util.HashMap;
-import java.util.Map;
-
-@Implements(LayerDrawable.class)
-public class ShadowLayerDrawable extends ShadowDrawable {
- @RealObject
- protected LayerDrawable realLayerDrawable;
-
- protected Drawable[] drawables;
- private Map<Integer, Integer> indexForId = new HashMap<Integer, Integer>();
-
- public void __constructor__(Drawable[] drawables) {
- this.drawables = drawables;
- }
-
- @Implementation
- public int getNumberOfLayers() {
- return drawables.length;
- }
-
- @Implementation
- public Drawable getDrawable( int idx ) {
- Drawable d = null;
- if( idx < drawables.length && idx >= 0 ) {
- d = drawables[ idx ];
- }
- return d;
- }
-
- @Implementation
- public boolean setDrawableByLayerId(int id, Drawable drawable) {
- if (!indexForId.containsKey(id)) {
- return false;
- }
- drawables[indexForId.get(id)] = drawable;
- return true;
- }
-
- @Implementation
- public void setId(int index, int id) {
- indexForId.put(id, index);
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowLayoutInflater.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowLayoutInflater.java
deleted file mode 100644
index b15844194..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowLayoutInflater.java
+++ /dev/null
@@ -1,82 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.app.Application;
-import android.content.Context;
-import android.view.LayoutInflater;
-import android.view.View;
-import android.view.ViewGroup;
-import com.xtremelabs.robolectric.internal.AppSingletonizer;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.res.ResourceLoader;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-
-/**
- * Shadow of {@code LayoutInflater} that actually inflates layouts into {@code View}s that are functional enough to
- * support testing.
- */
-
-@Implements(LayoutInflater.class)
-public class ShadowLayoutInflater {
- private static AppSingletonizer<LayoutInflater> instances = new LayoutInflaterAppSingletonizer();
-
- private Context context;
-
- private static LayoutInflater bind(LayoutInflater layoutInflater, Context context) {
- shadowOf(layoutInflater).context = context;
- return layoutInflater;
- }
-
- @Implementation
- public static LayoutInflater from(Context context) {
- return bind(instances.getInstance(context), context);
- }
-
- @Implementation
- public Context getContext() {
- return context;
- }
-
- @Implementation
- public View inflate(int resource, ViewGroup root, boolean attachToRoot) {
- return getResourceLoader().inflateView(context, resource, attachToRoot ? root : null);
- }
-
- @Implementation
- public View inflate(int resource, ViewGroup root) {
- return inflate(resource, root, root != null);
- }
-
- private ResourceLoader getResourceLoader() {
- return shadowOf(context.getApplicationContext()).getResourceLoader();
- }
-
- private static class LayoutInflaterAppSingletonizer extends AppSingletonizer<LayoutInflater> {
- public LayoutInflaterAppSingletonizer() {
- super(LayoutInflater.class);
- }
-
- @Override protected LayoutInflater get(ShadowApplication shadowApplication) {
- return shadowApplication.getLayoutInflater();
- }
-
- @Override protected void set(ShadowApplication shadowApplication, LayoutInflater instance) {
- shadowApplication.layoutInflater = instance;
- }
-
- @Override protected LayoutInflater createInstance(Application applicationContext) {
- return new MyLayoutInflater(applicationContext);
- }
-
- private static class MyLayoutInflater extends LayoutInflater {
- public MyLayoutInflater(Context context) {
- super(context);
- }
-
- @Override public LayoutInflater cloneInContext(Context newContext) {
- return bind(new MyLayoutInflater(newContext), newContext);
- }
- }
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowLayoutParams.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowLayoutParams.java
deleted file mode 100644
index 88ee85aab..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowLayoutParams.java
+++ /dev/null
@@ -1,16 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.view.ViewGroup;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.internal.RealObject;
-
-@SuppressWarnings({"UnusedDeclaration"})
-@Implements(ViewGroup.LayoutParams.class)
-public class ShadowLayoutParams {
- @RealObject private ViewGroup.LayoutParams realLayoutParams;
-
- public void __constructor__(int w, int h) {
- realLayoutParams.width = w;
- realLayoutParams.height = h;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowLinearLayout.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowLinearLayout.java
deleted file mode 100644
index 2a4ab572d..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowLinearLayout.java
+++ /dev/null
@@ -1,13 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.widget.LinearLayout;
-import com.xtremelabs.robolectric.internal.Implements;
-
-@Implements(LinearLayout.class)
-public class ShadowLinearLayout extends ShadowViewGroup {
-
- public ShadowLinearLayout() {
- setLayoutParams(new LinearLayout.LayoutParams(0, 0));
- }
-
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowLinkMovementMethod.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowLinkMovementMethod.java
deleted file mode 100644
index eea2223c2..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowLinkMovementMethod.java
+++ /dev/null
@@ -1,15 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.text.method.LinkMovementMethod;
-import android.text.method.MovementMethod;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-@SuppressWarnings({"UnusedDeclaration"})
-@Implements(LinkMovementMethod.class)
-public class ShadowLinkMovementMethod {
- @Implementation
- public static MovementMethod getInstance() {
- return new LinkMovementMethod();
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowListActivity.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowListActivity.java
deleted file mode 100644
index f57ab6ec4..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowListActivity.java
+++ /dev/null
@@ -1,81 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.app.ListActivity;
-import android.view.View;
-import android.view.ViewGroup;
-import android.widget.AdapterView;
-import android.widget.ListAdapter;
-import android.widget.ListView;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-
-/**
- * Shadow of {@code ListActivity} that supports the retrieval of {@code ListViews}
- */
-
-@SuppressWarnings({"UnusedDeclaration"})
-@Implements(ListActivity.class)
-public class ShadowListActivity extends ShadowActivity {
- private ListView listView;
- private ListAdapter listAdapter;
-
- @Implementation
- public ListView getListView() {
- if (listView == null) {
- if ((listView = findListView(getContentView())) == null) {
- throw new RuntimeException("No ListView found under content view");
- }
- }
- return listView;
- }
-
- public void setListView(ListView view) {
- listView = view;
- }
-
- @Implementation
- public void setListAdapter(ListAdapter listAdapter) {
- this.listAdapter = listAdapter;
- ListView lv = findListView(getContentView());
- if (lv != null) {
- lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
- @Override
- public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
- try {
- Method handler = realActivity.getClass().getDeclaredMethod("onListItemClick",
- ListView.class, View.class, int.class, long.class);
- handler.setAccessible(true);
- handler.invoke(realActivity, parent, view, position, id);
- } catch (NoSuchMethodException ignored) {
- } catch (InvocationTargetException ignored) {
- } catch (IllegalAccessException ignored) {
- }
- }
- });
- lv.setAdapter(listAdapter);
- }
- }
-
- @Implementation
- public ListAdapter getListAdapter() {
- return listAdapter;
- }
-
- private ListView findListView(View parent) {
- if (parent instanceof ListView) {
- return (ListView) parent;
- } else if (parent instanceof ViewGroup) {
- ViewGroup viewGroup = (ViewGroup) parent;
- for (int i = 0; i < viewGroup.getChildCount(); i++) {
- ListView listView = findListView(viewGroup.getChildAt(i));
- if (listView != null) {
- return listView;
- }
- }
- }
- return null;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowListFragment.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowListFragment.java
deleted file mode 100644
index d5a8d9a1e..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowListFragment.java
+++ /dev/null
@@ -1,32 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.support.v4.app.ListFragment;
-import android.view.View;
-import android.view.ViewGroup;
-import android.widget.AdapterView;
-import android.widget.ListAdapter;
-import android.widget.ListView;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-
-/**
- * Shadow of {@code ListFragment}
- */
-@Implements(ListFragment.class)
-public class ShadowListFragment extends ShadowFragment {
-
- private ListAdapter listAdapter;
-
- @Implementation
- public ListAdapter getListAdapter() {
- return listAdapter;
- }
-
- @Implementation
- public void setListAdapter(ListAdapter listAdapter) {
- this.listAdapter = listAdapter;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowListPreference.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowListPreference.java
deleted file mode 100644
index b324e8554..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowListPreference.java
+++ /dev/null
@@ -1,55 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.preference.ListPreference;
-
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-@Implements(ListPreference.class)
-public class ShadowListPreference extends ShadowDialogPreference {
-
- CharSequence[] entries;
- CharSequence[] entryValues;
-
- String value;
-
- @Implementation
- public CharSequence[] getEntries() {
- return entries;
- }
-
- @Implementation
- public void setEntries(CharSequence[] entries) {
- this.entries = entries;
- }
-
- @Implementation
- public void setEntries(int entriesResId) {
- this.entries = context.getResources().getStringArray(entriesResId);
- }
-
- @Implementation
- public CharSequence[] getEntryValues() {
- return entryValues;
- }
-
- @Implementation
- public void setEntryValues(CharSequence[] entryValues) {
- this.entryValues = entryValues;
- }
-
- @Implementation
- public void setEntryValues(int entryValuesResId) {
- this.entryValues = context.getResources().getStringArray(entryValuesResId);
- }
-
- @Implementation
- public void setValue(String value) {
- this.value = value;
- }
-
- @Implementation
- public String getValue() {
- return value;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowListView.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowListView.java
deleted file mode 100644
index d591e2fdf..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowListView.java
+++ /dev/null
@@ -1,209 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import android.util.SparseBooleanArray;
-import android.view.View;
-import android.widget.ListAdapter;
-import android.widget.ListView;
-
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.internal.RealObject;
-
-@SuppressWarnings({"UnusedDeclaration"})
-@Implements(ListView.class)
-public class ShadowListView extends ShadowAbsListView {
- @RealObject private ListView realListView;
-
- private boolean itemsCanFocus;
- private List<View> headerViews = new ArrayList<View>();
- private List<View> footerViews = new ArrayList<View>();
-
- private int choiceMode;
- private SparseBooleanArray checkedItemPositions = new SparseBooleanArray();
-
- @Implementation
- @Override
- public View findViewById(int id) {
- View child = super.findViewById(id);
- if (child == null) {
- child = findView(headerViews, id);
-
- if (child == null) {
- child = findView(footerViews, id);
- }
- }
- return child;
- }
-
- private View findView(List<View> views, int viewId) {
- View child = null;
- for (View v : views) {
- child = v.findViewById(viewId);
- if (child != null) {
- break;
- }
- }
- return child;
- }
-
-
- @Implementation
- public void setItemsCanFocus(boolean itemsCanFocus) {
- this.itemsCanFocus = itemsCanFocus;
- }
-
- @Implementation
- @Override
- public boolean performItemClick(View view, int position, long id) {
- boolean handled = false;
- if (choiceMode != ListView.CHOICE_MODE_NONE) {
- handled = true;
-
- if (choiceMode == ListView.CHOICE_MODE_MULTIPLE) {
- boolean newValue = !checkedItemPositions.get(position, false);
- checkedItemPositions.put(position, newValue);
- } else {
- boolean newValue = !checkedItemPositions.get(position, false);
- if (newValue) {
- checkedItemPositions.clear();
- checkedItemPositions.put(position, true);
- }
- }
- }
-
- handled |= super.performItemClick(view, position, id);
- return handled;
- }
-
- @Implementation
- public void setAdapter(ListAdapter adapter) {
- super.setAdapter(adapter);
- }
-
- @Implementation
- public void addHeaderView(View headerView) {
- addHeaderView(headerView, null, true);
- }
-
- @Implementation
- public void addHeaderView(View headerView, Object data, boolean isSelectable) {
- ensureAdapterNotSet("header");
- headerViews.add(headerView);
- realListView.addView(headerView);
- }
-
- @Implementation
- public int getHeaderViewsCount() {
- return headerViews.size();
- }
-
- @Implementation
- public int getFooterViewsCount() {
- return footerViews.size();
- }
-
- @Implementation
- public void addFooterView(View footerView, Object data, boolean isSelectable) {
- ensureAdapterNotSet("footer");
- footerViews.add(footerView);
- realListView.addView(footerView);
- }
-
- @Implementation
- public void addFooterView(View footerView) {
- addFooterView(footerView, null, false);
- }
-
- @Implementation
- public void removeAllViews() {
- throw new UnsupportedOperationException();
- }
-
- @Implementation
- public void removeView(View view) {
- throw new UnsupportedOperationException();
- }
-
- @Implementation
- public void removeViewAt(int index) {
- throw new UnsupportedOperationException();
- }
-
- private void ensureAdapterNotSet(String view) {
- if (getAdapter() != null) {
- throw new IllegalStateException("Cannot add " + view + " view to list -- setAdapter has already been called");
- }
- }
-
- public boolean isItemsCanFocus() {
- return itemsCanFocus;
- }
-
- public List<View> getHeaderViews() {
- return headerViews;
- }
-
- public void setHeaderViews(List<View> headerViews) {
- this.headerViews = headerViews;
- }
-
- public List<View> getFooterViews() {
- return footerViews;
- }
-
- public void setFooterViews(List<View> footerViews) {
- this.footerViews = footerViews;
- }
-
- @Override
- protected void addViews() {
- for (View headerView : headerViews) {
- addView(headerView);
- }
-
- super.addViews();
-
- for (View footerView : footerViews) {
- addView(footerView);
- }
- }
-
- @Implementation
- public int getChoiceMode() {
- return choiceMode;
- }
-
- @Implementation
- public void setChoiceMode(int choiceMode) {
- this.choiceMode = choiceMode;
- }
-
- @Implementation
- public void setItemChecked(int position, boolean value) {
- if (choiceMode == ListView.CHOICE_MODE_SINGLE) {
- checkedItemPositions.clear();
- checkedItemPositions.put(position, value);
- } else if (choiceMode == ListView.CHOICE_MODE_MULTIPLE) {
- checkedItemPositions.put(position, value);
- }
- }
-
- @Implementation
- public int getCheckedItemPosition() {
- if (choiceMode != ListView.CHOICE_MODE_SINGLE || checkedItemPositions.size() != 1)
- return ListView.INVALID_POSITION;
-
- return checkedItemPositions.keyAt(0);
- }
-
- @Implementation
- public SparseBooleanArray getCheckedItemPositions() {
- if (choiceMode == ListView.CHOICE_MODE_NONE)
- return null;
-
- return checkedItemPositions;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowLocalBroadcastManager.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowLocalBroadcastManager.java
deleted file mode 100644
index 668d9b001..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowLocalBroadcastManager.java
+++ /dev/null
@@ -1,14 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.support.v4.content.LocalBroadcastManager;
-import com.xtremelabs.robolectric.Robolectric;
-
-/**
- * This class is not a a real shadow for now - we just use the real LocalBroadcastManager and
- * reset its state after each test run.
- */
-public class ShadowLocalBroadcastManager {
- public static void reset() {
- Robolectric.Reflection.setFinalStaticField(LocalBroadcastManager.class, "mInstance", null);
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowLocation.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowLocation.java
deleted file mode 100644
index 07a48126c..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowLocation.java
+++ /dev/null
@@ -1,437 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.location.Location;
-import android.os.Bundle;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf_;
-
-/**
- * Shadow of {@code Location} that treats it primarily as a data-holder
- * todo: support Location's static utility methods
- */
-
-@SuppressWarnings({"UnusedDeclaration"})
-@Implements(Location.class)
-public class ShadowLocation {
- private long time;
- private String provider;
- private double latitude;
- private double longitude;
- private float accuracy;
- private float bearing;
- private double altitude;
- private float speed;
- private boolean hasAccuracy;
- private boolean hasAltitude;
- private boolean hasBearing;
- private boolean hasSpeed;
-
- // Cache the inputs and outputs of computeDistanceAndBearing
- // so calls to distanceTo() and bearingTo() can share work
- private double mLat1 = 0.0;
- private double mLon1 = 0.0;
- private double mLat2 = 0.0;
- private double mLon2 = 0.0;
- private float mDistance = 0.0f;
- private float mInitialBearing = 0.0f;
- // Scratchpad
- private final float[] mResults = new float[2];
-
- private Bundle extras = new Bundle();
-
- public void __constructor__(Location l) {
- set(l);
- }
-
- public void __constructor__(String provider) {
- this.provider = provider;
- time = System.currentTimeMillis();
- }
-
- @Implementation
- public void set(Location l) {
- time = l.getTime();
- provider = l.getProvider();
- latitude = l.getLatitude();
- longitude = l.getLongitude();
- accuracy = l.getAccuracy();
- bearing = l.getBearing();
- altitude = l.getAltitude();
- speed = l.getSpeed();
-
- hasAccuracy = l.hasAccuracy();
- hasAltitude = l.hasAltitude();
- hasBearing = l.hasBearing();
- hasSpeed = l.hasSpeed();
- }
-
- @Implementation
- public String getProvider() {
- return provider;
- }
-
- @Implementation
- public void setProvider(String provider) {
- this.provider = provider;
- }
-
- @Implementation
- public long getTime() {
- return time;
- }
-
- @Implementation
- public void setTime(long time) {
- this.time = time;
- }
-
- @Implementation
- public float getAccuracy() {
- return accuracy;
- }
-
- @Implementation
- public void setAccuracy(float accuracy) {
- this.accuracy = accuracy;
- this.hasAccuracy = true;
- }
-
- @Implementation
- public void removeAccuracy() {
- this.accuracy = 0.0f;
- this.hasAccuracy = false;
- }
-
- @Implementation
- public boolean hasAccuracy() {
- return hasAccuracy;
- }
-
- @Implementation
- public double getAltitude() {
- return altitude;
- }
-
- @Implementation
- public void setAltitude(double altitude) {
- this.altitude = altitude;
- this.hasAltitude = true;
- }
-
- @Implementation
- public void removeAltitude() {
- this.altitude = 0.0d;
- this.hasAltitude = false;
- }
-
- @Implementation
- public boolean hasAltitude() {
- return hasAltitude;
- }
-
- @Implementation
- public float getBearing() {
- return bearing;
- }
-
- @Implementation
- public void setBearing(float bearing) {
- this.bearing = bearing;
- this.hasBearing = true;
- }
-
- @Implementation
- public void removeBearing() {
- this.bearing = 0.0f;
- this.hasBearing = false;
- }
-
- @Implementation
- public boolean hasBearing() {
- return hasBearing;
- }
-
-
- @Implementation
- public double getLatitude() {
- return latitude;
- }
-
- @Implementation
- public void setLatitude(double latitude) {
- this.latitude = latitude;
- }
-
- @Implementation
- public double getLongitude() {
- return longitude;
- }
-
- @Implementation
- public void setLongitude(double longitude) {
- this.longitude = longitude;
- }
-
- @Implementation
- public float getSpeed() {
- return speed;
- }
-
- @Implementation
- public void setSpeed(float speed) {
- this.speed = speed;
- this.hasSpeed = true;
- }
-
- @Implementation
- public void removeSpeed() {
- this.hasSpeed = false;
- this.speed = 0.0f;
- }
-
- @Implementation
- public boolean hasSpeed() {
- return hasSpeed;
- }
-
- @Override @Implementation
- public boolean equals(Object o) {
- if (o == null) return false;
- o = shadowOf_(o);
- if (o == null) return false;
- if (getClass() != o.getClass()) return false;
- if (this == o) return true;
-
- ShadowLocation that = (ShadowLocation) o;
-
- if (Double.compare(that.latitude, latitude) != 0) return false;
- if (Double.compare(that.longitude, longitude) != 0) return false;
- if (time != that.time) return false;
- if (provider != null ? !provider.equals(that.provider) : that.provider != null) return false;
- if (accuracy != that.accuracy) return false;
- return true;
- }
-
- @Override @Implementation
- public int hashCode() {
- int result;
- long temp;
- result = (int) (time ^ (time >>> 32));
- result = 31 * result + (provider != null ? provider.hashCode() : 0);
- temp = latitude != +0.0d ? Double.doubleToLongBits(latitude) : 0L;
- result = 31 * result + (int) (temp ^ (temp >>> 32));
- temp = longitude != +0.0d ? Double.doubleToLongBits(longitude) : 0L;
- result = 31 * result + (int) (temp ^ (temp >>> 32));
- temp = accuracy != 0f ? Float.floatToIntBits(accuracy) : 0;
- result = 31 * result + (int) (temp ^ (temp >>> 32));
- return result;
- }
-
- @Override @Implementation
- public String toString() {
- return "Location{" +
- "time=" + time +
- ", provider='" + provider + '\'' +
- ", latitude=" + latitude +
- ", longitude=" + longitude +
- ", accuracy=" + accuracy +
- '}';
- }
-
- private static void computeDistanceAndBearing(double lat1, double lon1,
- double lat2, double lon2, float[] results) {
- // Based on http://www.ngs.noaa.gov/PUBS_LIB/inverse.pdf
- // using the "Inverse Formula" (section 4)
-
- int MAXITERS = 20;
- // Convert lat/long to radians
- lat1 *= Math.PI / 180.0;
- lat2 *= Math.PI / 180.0;
- lon1 *= Math.PI / 180.0;
- lon2 *= Math.PI / 180.0;
-
- double a = 6378137.0; // WGS84 major axis
- double b = 6356752.3142; // WGS84 semi-major axis
- double f = (a - b) / a;
- double aSqMinusBSqOverBSq = (a * a - b * b) / (b * b);
-
- double L = lon2 - lon1;
- double A = 0.0;
- double U1 = Math.atan((1.0 - f) * Math.tan(lat1));
- double U2 = Math.atan((1.0 - f) * Math.tan(lat2));
-
- double cosU1 = Math.cos(U1);
- double cosU2 = Math.cos(U2);
- double sinU1 = Math.sin(U1);
- double sinU2 = Math.sin(U2);
- double cosU1cosU2 = cosU1 * cosU2;
- double sinU1sinU2 = sinU1 * sinU2;
-
- double sigma = 0.0;
- double deltaSigma = 0.0;
- double cosSqAlpha = 0.0;
- double cos2SM = 0.0;
- double cosSigma = 0.0;
- double sinSigma = 0.0;
- double cosLambda = 0.0;
- double sinLambda = 0.0;
-
- double lambda = L; // initial guess
- for (int iter = 0; iter < MAXITERS; iter++) {
- double lambdaOrig = lambda;
- cosLambda = Math.cos(lambda);
- sinLambda = Math.sin(lambda);
- double t1 = cosU2 * sinLambda;
- double t2 = cosU1 * sinU2 - sinU1 * cosU2 * cosLambda;
- double sinSqSigma = t1 * t1 + t2 * t2; // (14)
- sinSigma = Math.sqrt(sinSqSigma);
- cosSigma = sinU1sinU2 + cosU1cosU2 * cosLambda; // (15)
- sigma = Math.atan2(sinSigma, cosSigma); // (16)
- double sinAlpha = (sinSigma == 0) ? 0.0 :
- cosU1cosU2 * sinLambda / sinSigma; // (17)
- cosSqAlpha = 1.0 - sinAlpha * sinAlpha;
- cos2SM = (cosSqAlpha == 0) ? 0.0 :
- cosSigma - 2.0 * sinU1sinU2 / cosSqAlpha; // (18)
-
- double uSquared = cosSqAlpha * aSqMinusBSqOverBSq; // defn
- A = 1 + (uSquared / 16384.0) * // (3)
- (4096.0 + uSquared *
- (-768 + uSquared * (320.0 - 175.0 * uSquared)));
- double B = (uSquared / 1024.0) * // (4)
- (256.0 + uSquared *
- (-128.0 + uSquared * (74.0 - 47.0 * uSquared)));
- double C = (f / 16.0) *
- cosSqAlpha *
- (4.0 + f * (4.0 - 3.0 * cosSqAlpha)); // (10)
- double cos2SMSq = cos2SM * cos2SM;
- deltaSigma = B * sinSigma * // (6)
- (cos2SM + (B / 4.0) *
- (cosSigma * (-1.0 + 2.0 * cos2SMSq) -
- (B / 6.0) * cos2SM *
- (-3.0 + 4.0 * sinSigma * sinSigma) *
- (-3.0 + 4.0 * cos2SMSq)));
-
- lambda = L +
- (1.0 - C) * f * sinAlpha *
- (sigma + C * sinSigma *
- (cos2SM + C * cosSigma *
- (-1.0 + 2.0 * cos2SM * cos2SM))); // (11)
-
- double delta = (lambda - lambdaOrig) / lambda;
- if (Math.abs(delta) < 1.0e-12) {
- break;
- }
- }
-
- float distance = (float) (b * A * (sigma - deltaSigma));
- results[0] = distance;
- if (results.length > 1) {
- float initialBearing = (float) Math.atan2(cosU2 * sinLambda,
- cosU1 * sinU2 - sinU1 * cosU2 * cosLambda);
- initialBearing *= 180.0 / Math.PI;
- results[1] = initialBearing;
- if (results.length > 2) {
- float finalBearing = (float) Math.atan2(cosU1 * sinLambda,
- -sinU1 * cosU2 + cosU1 * sinU2 * cosLambda);
- finalBearing *= 180.0 / Math.PI;
- results[2] = finalBearing;
- }
- }
- }
-
- /**
- * Computes the approximate distance in meters between two
- * locations, and optionally the initial and final bearings of the
- * shortest path between them. Distance and bearing are defined using the
- * WGS84 ellipsoid.
- *
- * <p> The computed distance is stored in results[0]. If results has length
- * 2 or greater, the initial bearing is stored in results[1]. If results has
- * length 3 or greater, the final bearing is stored in results[2].
- *
- * @param startLatitude the starting latitude
- * @param startLongitude the starting longitude
- * @param endLatitude the ending latitude
- * @param endLongitude the ending longitude
- * @param results an array of floats to hold the results
- *
- * @throws IllegalArgumentException if results is null or has length < 1
- */
- @Implementation
- public static void distanceBetween(double startLatitude, double startLongitude,
- double endLatitude, double endLongitude, float[] results) {
- if (results == null || results.length < 1) {
- throw new IllegalArgumentException("results is null or has length < 1");
- }
- computeDistanceAndBearing(startLatitude, startLongitude,
- endLatitude, endLongitude, results);
- }
-
- /**
- * Returns the approximate distance in meters between this
- * location and the given location. Distance is defined using
- * the WGS84 ellipsoid.
- *
- * @param dest the destination location
- * @return the approximate distance in meters
- */
- @Implementation
- public float distanceTo(Location dest) {
- // See if we already have the result
- synchronized (mResults) {
- if (latitude != mLat1 || longitude != mLon1 ||
- dest.getLatitude() != mLat2 || dest.getLongitude() != mLon2) {
- computeDistanceAndBearing(latitude, longitude,
- dest.getLatitude(), dest.getLongitude(), mResults);
- mLat1 = latitude;
- mLon1 = longitude;
- mLat2 = dest.getLatitude();
- mLon2 = dest.getLongitude();
- mDistance = mResults[0];
- mInitialBearing = mResults[1];
- }
- return mDistance;
- }
- }
-
- /**
- * Returns the approximate initial bearing in degrees East of true
- * North when traveling along the shortest path between this
- * location and the given location. The shortest path is defined
- * using the WGS84 ellipsoid. Locations that are (nearly)
- * antipodal may produce meaningless results.
- *
- * @param dest the destination location
- * @return the initial bearing in degrees
- */
- @Implementation
- public float bearingTo(Location dest) {
- synchronized (mResults) {
- // See if we already have the result
- if (latitude != mLat1 || longitude != mLon1 ||
- dest.getLatitude() != mLat2 || dest.getLongitude() != mLon2) {
- computeDistanceAndBearing(latitude, longitude,
- dest.getLatitude(), dest.getLongitude(), mResults);
- mLat1 = latitude;
- mLon1 = longitude;
- mLat2 = dest.getLatitude();
- mLon2 = dest.getLongitude();
- mDistance = mResults[0];
- mInitialBearing = mResults[1];
- }
- return mInitialBearing;
- }
- }
-
- @Implementation
- public Bundle getExtras() {
- return extras;
- }
-
- @Implementation
- public void setExtras(Bundle extras) {
- this.extras = extras;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowLocationManager.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowLocationManager.java
deleted file mode 100644
index 4c4fdf509..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowLocationManager.java
+++ /dev/null
@@ -1,391 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.app.PendingIntent;
-import android.app.PendingIntent.CanceledException;
-import android.content.Intent;
-import android.location.Criteria;
-import android.location.GpsStatus.Listener;
-import android.location.Location;
-import android.location.LocationListener;
-import android.location.LocationManager;
-import android.os.Looper;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-import java.util.*;
-
-/**
- * Shadow of {@code LocationManager} that provides for the simulation of different location providers being enabled and
- * disabled.
- */
-@Implements(LocationManager.class)
-public class ShadowLocationManager {
- private final Map<String, LocationProviderEntry> providersEnabled = new LinkedHashMap<String, LocationProviderEntry>();
- private final Map<String, Location> lastKnownLocations = new HashMap<String, Location>();
- private final Map<PendingIntent, Criteria> requestLocationUdpateCriteriaPendingIntents = new HashMap<PendingIntent, Criteria>();
- private final Map<PendingIntent, String> requestLocationUdpateProviderPendingIntents = new HashMap<PendingIntent, String>();
-
- private final ArrayList<Listener> gpsStatusListeners = new ArrayList<Listener>();
- private Criteria lastBestProviderCriteria;
- private boolean lastBestProviderEnabled;
- private String bestEnabledProvider, bestDisabledProvider;
- private final Map<LocationListener, Set<String>> requestLocationUpdateListenersMap = new LinkedHashMap<LocationListener, Set<String>>();
-
- @Implementation
- public boolean isProviderEnabled(String provider) {
- LocationProviderEntry map = providersEnabled.get(provider);
- if (map != null) {
- Boolean isEnabled = map.getKey();
- return isEnabled == null ? true : isEnabled;
- }
- return false;
- }
-
- @Implementation
- public List<String> getAllProviders() {
- Set<String> allKnownProviders = new LinkedHashSet<String>(providersEnabled.keySet());
- allKnownProviders.add(LocationManager.GPS_PROVIDER);
- allKnownProviders.add(LocationManager.NETWORK_PROVIDER);
- allKnownProviders.add(LocationManager.PASSIVE_PROVIDER);
-
- return new ArrayList<String>(allKnownProviders);
- }
-
- /**
- * Sets the value to return from {@link #isProviderEnabled(String)} for the given {@code provider}
- *
- * @param provider
- * name of the provider whose status to set
- * @param isEnabled
- * whether that provider should appear enabled
- */
- public void setProviderEnabled(String provider, boolean isEnabled) {
- setProviderEnabled(provider, isEnabled, null);
- }
-
- public void setProviderEnabled(String provider, boolean isEnabled, List<Criteria> criteria) {
- LocationProviderEntry providerEntry = providersEnabled.get(provider);
- if (providerEntry == null) {
- providerEntry = new LocationProviderEntry();
- }
- providerEntry.enabled = isEnabled;
- providerEntry.criteria = criteria;
- providersEnabled.put(provider, providerEntry);
- List<LocationListener> locationUpdateListeners = new ArrayList<LocationListener>(requestLocationUpdateListenersMap.keySet());
- for (LocationListener locationUpdateListener : locationUpdateListeners) {
- if (isEnabled) {
- locationUpdateListener.onProviderEnabled(provider);
- } else {
- locationUpdateListener.onProviderDisabled(provider);
- }
- }
- // Send intent to notify about provider status
- final Intent intent = new Intent();
- intent.putExtra(LocationManager.KEY_PROVIDER_ENABLED, isEnabled);
- Robolectric.getShadowApplication().sendBroadcast(intent);
- Set<PendingIntent> requestLocationUdpatePendingIntentSet = requestLocationUdpateCriteriaPendingIntents
- .keySet();
- for (PendingIntent requestLocationUdpatePendingIntent : requestLocationUdpatePendingIntentSet) {
- try {
- requestLocationUdpatePendingIntent.send();
- } catch (CanceledException e) {
- requestLocationUdpateCriteriaPendingIntents
- .remove(requestLocationUdpatePendingIntent);
- }
- }
- // if this provider gets disabled and it was the best active provider, then it's not anymore
- if (provider.equals(bestEnabledProvider) && !isEnabled) {
- bestEnabledProvider = null;
- }
- }
-
- @Implementation
- public List<String> getProviders(boolean enabledOnly) {
- ArrayList<String> enabledProviders = new ArrayList<String>();
- for (String provider : providersEnabled.keySet()) {
- if (!enabledOnly || providersEnabled.get(provider).getKey()) {
- enabledProviders.add(provider);
- }
- }
- return enabledProviders;
- }
-
- @Implementation
- public Location getLastKnownLocation(String provider) {
- return lastKnownLocations.get(provider);
- }
-
- @Implementation
- public boolean addGpsStatusListener(Listener listener) {
- if (!gpsStatusListeners.contains(listener)) {
- gpsStatusListeners.add(listener);
- }
- return true;
- }
-
- @Implementation
- public void removeGpsStatusListener(Listener listener) {
- gpsStatusListeners.remove(listener);
- }
-
- /**
- * Returns the best provider with respect to the passed criteria (if any) and its status. If no criteria are passed
- *
- * NB: Gps is considered the best provider for fine accuracy and high power consumption, network is considered the
- * best provider for coarse accuracy and low power consumption.
- *
- * @param criteria
- * @param enabled
- * @return
- */
- @Implementation
- public String getBestProvider(Criteria criteria, boolean enabled) {
- lastBestProviderCriteria = criteria;
- lastBestProviderEnabled = enabled;
-
- if (criteria == null) {
- return getBestProviderWithNoCriteria(enabled);
- }
-
- return getBestProviderWithCriteria(criteria, enabled);
- }
-
- private String getBestProviderWithCriteria(Criteria criteria, boolean enabled) {
- List<String> providers = getProviders(enabled);
- int powerRequirement = criteria.getPowerRequirement();
- int accuracy = criteria.getAccuracy();
- for (String provider : providers) {
- LocationProviderEntry locationProviderEntry = providersEnabled.get(provider);
- if (locationProviderEntry == null) {
- continue;
- }
- List<Criteria> criteriaList = locationProviderEntry.getValue();
- if (criteriaList == null) {
- continue;
- }
- for (Criteria criteriaListItem : criteriaList) {
- if (criteria.equals(criteriaListItem)) {
- return provider;
- } else if (criteriaListItem.getAccuracy() == accuracy) {
- return provider;
- } else if (criteriaListItem.getPowerRequirement() == powerRequirement) {
- return provider;
- }
- }
- }
- // TODO: these conditions are incomplete
- for (String provider : providers) {
- if (provider.equals(LocationManager.NETWORK_PROVIDER) && (accuracy == Criteria.ACCURACY_COARSE || powerRequirement == Criteria.POWER_LOW)) {
- return provider;
- } else if (provider.equals(LocationManager.GPS_PROVIDER) && accuracy == Criteria.ACCURACY_FINE && powerRequirement != Criteria.POWER_LOW) {
- return provider;
- }
- }
-
- // No enabled provider found with the desired criteria, then return the the first registered provider(?)
- return providers.isEmpty()? null : providers.get(0);
- }
-
- private String getBestProviderWithNoCriteria(boolean enabled) {
- List<String> providers = getProviders(enabled);
-
- if (enabled && bestEnabledProvider != null) {
- return bestEnabledProvider;
- } else if (bestDisabledProvider != null) {
- return bestDisabledProvider;
- } else if (providers.contains(LocationManager.GPS_PROVIDER)) {
- return LocationManager.GPS_PROVIDER;
- } else if (providers.contains(LocationManager.NETWORK_PROVIDER)) {
- return LocationManager.NETWORK_PROVIDER;
- }
- return null;
- }
-
- @Implementation
- public void requestLocationUpdates(String provider, long minTime, float minDistance, LocationListener listener) {
- addLocationListener(provider, listener);
- }
-
- private void addLocationListener(String provider, LocationListener listener) {
- if (!requestLocationUpdateListenersMap.containsKey(listener)) {
- requestLocationUpdateListenersMap.put(listener, new HashSet<String>());
- }
- requestLocationUpdateListenersMap.get(listener).add(provider);
- }
-
- @Implementation
- public void requestLocationUpdates(String provider, long minTime, float minDistance, LocationListener listener,
- Looper looper) {
- addLocationListener(provider, listener);
- }
-
- @Implementation
- public void requestLocationUpdates(long minTime, float minDistance, Criteria criteria, PendingIntent pendingIntent) {
- if (pendingIntent == null) {
- throw new IllegalStateException("Intent must not be null");
- }
- if (getBestProvider(criteria, true) == null) {
- throw new IllegalArgumentException("no providers found for criteria");
- }
- requestLocationUdpateCriteriaPendingIntents.put(pendingIntent, criteria);
- }
-
- @Implementation
- public void requestLocationUpdates(String provider, long minTime, float minDistance,
- PendingIntent pendingIntent) {
- if (pendingIntent == null) {
- throw new IllegalStateException("Intent must not be null");
- }
- if (!providersEnabled.containsKey(provider)) {
- throw new IllegalArgumentException("no providers found");
- }
-
- requestLocationUdpateProviderPendingIntents.put(pendingIntent, provider);
- }
-
- @Implementation
- public void removeUpdates(LocationListener listener) {
- requestLocationUpdateListenersMap.remove(listener);
- }
-
- @Implementation
- public void removeUpdates(PendingIntent pendingIntent) {
- while (requestLocationUdpateCriteriaPendingIntents.remove(pendingIntent) != null);
- while (requestLocationUdpateProviderPendingIntents.remove(pendingIntent) != null);
- }
-
- public boolean hasGpsStatusListener(Listener listener) {
- return gpsStatusListeners.contains(listener);
- }
-
- /**
- * Non-Android accessor.
- * <p/>
- * Gets the criteria value used in the last call to {@link #getBestProvider(android.location.Criteria, boolean)}
- *
- * @return the criteria used to find the best provider
- */
- public Criteria getLastBestProviderCriteria() {
- return lastBestProviderCriteria;
- }
-
- /**
- * Non-Android accessor.
- * <p/>
- * Gets the enabled value used in the last call to {@link #getBestProvider(android.location.Criteria, boolean)}
- *
- * @return the enabled value used to find the best provider
- */
- public boolean getLastBestProviderEnabledOnly() {
- return lastBestProviderEnabled;
- }
-
- /**
- * Sets the value to return from {@link #getBestProvider(android.location.Criteria, boolean)} for the given
- * {@code provider}
- *
- * @param provider
- * name of the provider who should be considered best
- * @throws Exception
- *
- */
- public boolean setBestProvider(String provider, boolean enabled, List<Criteria> criteria) throws Exception {
- if (!getAllProviders().contains(provider)) {
- throw new IllegalStateException("Best provider is not a known provider");
- }
- // If provider is not enabled but it is supposed to be set as the best enabled provider don't set it.
- for (String prvdr : providersEnabled.keySet()) {
- if (provider.equals(prvdr) && providersEnabled.get(prvdr).enabled != enabled) {
- return false;
- }
- }
-
- if (enabled) {
- bestEnabledProvider = provider;
- if (provider.equals(bestDisabledProvider)) {
- bestDisabledProvider = null;
- }
- } else {
- bestDisabledProvider = provider;
- if (provider.equals(bestEnabledProvider)) {
- bestEnabledProvider = null;
- }
- }
- if (criteria == null) {
- return true;
- }
- LocationProviderEntry entry;
- if (!providersEnabled.containsKey(provider)) {
- entry = new LocationProviderEntry();
- entry.enabled = enabled;
- entry.criteria = criteria;
- } else {
- entry = providersEnabled.get(provider);
- }
- providersEnabled.put(provider, entry);
-
- return true;
- }
-
- public boolean setBestProvider(String provider, boolean enabled) throws Exception {
- return setBestProvider(provider, enabled, null);
- }
-
- /**
- * Sets the value to return from {@link #getLastKnownLocation(String)} for the given {@code provider}
- *
- * @param provider
- * name of the provider whose location to set
- * @param location
- * the last known location for the provider
- */
- public void setLastKnownLocation(String provider, Location location) {
- lastKnownLocations.put(provider, location);
- }
-
- /**
- * Non-Android accessor.
- *
- * @return lastRequestedLocationUpdatesLocationListener
- */
- public List<LocationListener> getRequestLocationUpdateListeners() {
- return new ArrayList<LocationListener>(requestLocationUpdateListenersMap.keySet());
- }
-
- public Map<PendingIntent, Criteria> getRequestLocationUdpateCriteriaPendingIntents() {
- return requestLocationUdpateCriteriaPendingIntents;
- }
-
- public Map<PendingIntent, String> getRequestLocationUdpateProviderPendingIntents() {
- return requestLocationUdpateProviderPendingIntents;
- }
-
- public Collection<String> getProvidersForListener(LocationListener listener) {
- Set<String> providers = requestLocationUpdateListenersMap.get(listener);
- return providers == null ? Collections.<String>emptyList() : new ArrayList<String>(providers);
- }
-
- final private class LocationProviderEntry implements Map.Entry<Boolean, List<Criteria>> {
- private Boolean enabled;
- private List<Criteria> criteria;
-
- @Override
- public Boolean getKey() {
- return enabled;
- }
-
- @Override
- public List<Criteria> getValue() {
- return criteria;
- }
-
- @Override
- public List<Criteria> setValue(List<Criteria> criteria) {
- List<Criteria> oldCriteria = this.criteria;
- this.criteria = criteria;
- return oldCriteria;
- }
- }
-
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowLog.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowLog.java
deleted file mode 100644
index 0e49bf9cb..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowLog.java
+++ /dev/null
@@ -1,133 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.util.Log;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-import java.io.PrintStream;
-import java.util.ArrayList;
-import java.util.List;
-
-@Implements(Log.class)
-public class ShadowLog {
- private static List<LogItem> logs = new ArrayList<LogItem>();
- public static PrintStream stream;
-
- @Implementation
- public static void e(String tag, String msg) {
- e(tag, msg, null);
- }
-
- @Implementation
- public static void e(String tag, String msg, Throwable throwable) {
- addLog(Log.ERROR, tag, msg, throwable);
- }
-
- @Implementation
- public static void d(String tag, String msg) {
- d(tag, msg, null);
- }
-
- @Implementation
- public static void d(String tag, String msg, Throwable throwable) {
- addLog(Log.DEBUG, tag, msg, throwable);
- }
-
- @Implementation
- public static void i(String tag, String msg) {
- i(tag, msg, null);
- }
-
- @Implementation
- public static void i(String tag, String msg, Throwable throwable) {
- addLog(Log.INFO, tag, msg, throwable);
- }
-
- @Implementation
- public static void v(String tag, String msg) {
- v(tag, msg, null);
- }
-
- @Implementation
- public static void v(String tag, String msg, Throwable throwable) {
- addLog(Log.VERBOSE, tag, msg, throwable);
- }
-
- @Implementation
- public static void w(String tag, String msg) {
- w(tag, msg, null);
- }
-
- @Implementation
- public static void w(String tag, Throwable throwable) {
- w(tag, null, throwable);
- }
-
-
- @Implementation
- public static void w(String tag, String msg, Throwable throwable) {
- addLog(Log.WARN, tag, msg, throwable);
- }
-
- @Implementation
- public static void wtf(String tag, String msg) {
- wtf(tag, msg, null);
- }
-
- @Implementation
- public static void wtf(String tag, String msg, Throwable throwable) {
- addLog(Log.ASSERT, tag, msg, throwable);
- }
-
- @Implementation
- public static boolean isLoggable(String tag, int level) {
- return stream != null || level >= Log.INFO;
- }
-
- private static void addLog(int level, String tag, String msg, Throwable throwable) {
- if (stream != null) {
- logToStream(stream, level, tag, msg, throwable);
- }
- logs.add(new LogItem(level, tag, msg, throwable));
- }
-
-
- private static void logToStream(PrintStream ps, int level, String tag, String msg, Throwable throwable) {
- final char c;
- switch (level) {
- case Log.ASSERT: c = 'A'; break;
- case Log.DEBUG: c = 'D'; break;
- case Log.ERROR: c = 'E'; break;
- case Log.WARN: c = 'W'; break;
- case Log.INFO: c = 'I'; break;
- case Log.VERBOSE:c = 'V'; break;
- default: c = '?';
- }
- ps.println(c + "/" + tag + ": " + msg);
- if (throwable != null) {
- throwable.printStackTrace(ps);
- }
- }
-
- public static List<LogItem> getLogs() {
- return logs;
- }
-
- public static void reset() {
- logs.clear();
- }
-
- public static class LogItem {
- public final int type;
- public final String tag;
- public final String msg;
- public final Throwable throwable;
-
- public LogItem(int type, String tag, String msg, Throwable throwable) {
- this.type = type;
- this.tag = tag;
- this.msg = msg;
- this.throwable = throwable;
- }
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowLooper.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowLooper.java
deleted file mode 100644
index 99126e2f3..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowLooper.java
+++ /dev/null
@@ -1,193 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.os.Looper;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.util.Scheduler;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-
-/**
- * Shadow for {@code Looper} that enqueues posted {@link Runnable}s to be run (on this thread) later. {@code Runnable}s
- * that are scheduled to run immediately can be triggered by calling {@link #idle()}
- * todo: provide better support for advancing the clock and running queued tasks
- */
-
-@SuppressWarnings({"UnusedDeclaration"})
-@Implements(Looper.class)
-public class ShadowLooper {
- private static ThreadLocal<Looper> looperForThread = makeThreadLocalLoopers();
- private Scheduler scheduler = new Scheduler();
- private Thread myThread = Thread.currentThread();
-
- boolean quit;
-
- private static synchronized ThreadLocal<Looper> makeThreadLocalLoopers() {
- return new ThreadLocal<Looper>() {
- @Override
- protected Looper initialValue() {
- return Robolectric.Reflection.newInstanceOf(Looper.class);
- }
- };
- }
-
- public static void resetThreadLoopers() {
- looperForThread = makeThreadLocalLoopers();
- }
-
- @Implementation
- public static Looper getMainLooper() {
- return Robolectric.getShadowApplication().getMainLooper();
- }
-
- @Implementation
- public static void loop() {
- final ShadowLooper looper = shadowOf(myLooper());
- if (looper != shadowOf(getMainLooper())) {
- while (!looper.quit) {
- try {
- synchronized (looper) {
- looper.wait();
- }
- } catch (InterruptedException ignore) {
- }
- }
- }
- }
-
- @Implementation
- public static synchronized Looper myLooper() {
- return looperForThread.get();
- }
-
- @Implementation
- public void quit() {
- if (this == shadowOf(getMainLooper())) throw new RuntimeException("Main thread not allowed to quit");
- synchronized (this) {
- quit = true;
- scheduler.reset();
- notify();
- }
- }
-
- @Implementation
- public Thread getThread() {
- return myThread;
- }
-
- public boolean hasQuit() {
- return quit;
- }
-
- public static void pauseLooper(Looper looper) {
- shadowOf(looper).pause();
- }
-
- public static void unPauseLooper(Looper looper) {
- shadowOf(looper).unPause();
- }
-
- public static void pauseMainLooper() {
- pauseLooper(Looper.getMainLooper());
- }
-
- public static void unPauseMainLooper() {
- unPauseLooper(Looper.getMainLooper());
- }
-
- public static void idleMainLooper(long interval) {
- shadowOf(Looper.getMainLooper()).idle(interval);
- }
-
- /**
- * Causes {@link Runnable}s that have been scheduled to run immediately to actually run. Does not advance the
- * scheduler's clock;
- */
- public void idle() {
- scheduler.advanceBy(0);
- }
-
- /**
- * Causes {@link Runnable}s that have been scheduled to run within the next {@code intervalMillis} milliseconds to
- * run while advancing the scheduler's clock.
- *
- * @param intervalMillis milliseconds to advance
- */
- public void idle(long intervalMillis) {
- scheduler.advanceBy(intervalMillis);
- }
-
- /**
- * Causes all of the {@link Runnable}s that have been scheduled to run while advancing the scheduler's clock to the
- * start time of the last scheduled {@link Runnable}.
- */
- public void runToEndOfTasks() {
- scheduler.advanceToLastPostedRunnable();
- }
-
- /**
- * Causes the next {@link Runnable}(s) that have been scheduled to run while advancing the scheduler's clock to its
- * start time. If more than one {@link Runnable} is scheduled to run at this time then they will all be run.
- */
- public void runToNextTask() {
- scheduler.advanceToNextPostedRunnable();
- }
-
- /**
- * Causes only one of the next {@link Runnable}s that have been scheduled to run while advancing the scheduler's
- * clock to its start time. Only one {@link Runnable} will run even if more than one has ben scheduled to run at the
- * same time.
- */
- public void runOneTask() {
- scheduler.runOneTask();
- }
-
- /**
- * Enqueue a task to be run later.
- *
- * @param runnable the task to be run
- * @param delayMillis how many milliseconds into the (virtual) future to run it
- */
- public boolean post(Runnable runnable, long delayMillis) {
- if (!quit) {
- scheduler.postDelayed(runnable, delayMillis);
- return true;
- } else {
- return false;
- }
- }
-
- public boolean postAtFrontOfQueue(Runnable runnable) {
- if (!quit) {
- scheduler.postAtFrontOfQueue(runnable);
- return true;
- } else {
- return false;
- }
- }
-
- public void pause() {
- scheduler.pause();
- }
-
- public void unPause() {
- scheduler.unPause();
- }
-
- /**
- * Causes all enqueued tasks to be discarded
- */
- public void reset() {
- scheduler.reset();
- }
-
- /**
- * Returns the {@link com.xtremelabs.robolectric.util.Scheduler} that is being used to manage the enqueued tasks.
- *
- * @return the {@link com.xtremelabs.robolectric.util.Scheduler} that is being used to manage the enqueued tasks.
- */
- public Scheduler getScheduler() {
- return scheduler;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowMapActivity.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowMapActivity.java
deleted file mode 100644
index 1baa7ff56..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowMapActivity.java
+++ /dev/null
@@ -1,40 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.content.BroadcastReceiver;
-import android.content.Context;
-import android.content.Intent;
-import android.content.IntentFilter;
-import com.google.android.maps.MapActivity;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-/**
- * Shadow {@code MapActivity} that registers and unregisters a {@code BroadcastReciever} when {@link #onResume()} and
- * {@link #onPause()} are called respectively.
- */
-
-@SuppressWarnings({"UnusedDeclaration"})
-@Implements(MapActivity.class)
-public class ShadowMapActivity extends ShadowActivity {
- private ConnectivityBroadcastReceiver connectivityBroadcastReceiver = new ConnectivityBroadcastReceiver();
-
- @Implementation
- public void onResume() {
- registerReceiver(connectivityBroadcastReceiver, new IntentFilter());
- }
-
- @Implementation
- public void onPause() {
- unregisterReceiver(connectivityBroadcastReceiver);
- }
-
- @Implementation
- public boolean isRouteDisplayed() {
- return false;
- }
-
- private static class ConnectivityBroadcastReceiver extends BroadcastReceiver {
- @Override public void onReceive(Context context, Intent intent) {
- }
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowMapController.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowMapController.java
deleted file mode 100644
index fac5f9f53..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowMapController.java
+++ /dev/null
@@ -1,86 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import com.google.android.maps.GeoPoint;
-import com.google.android.maps.MapController;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-/**
- * A Shadow of {@code MapController} that tracks its own state and keeps the state of the {@code MapView} it controlls
- * up to date.
- */
-@SuppressWarnings({"UnusedDeclaration"})
-@Implements(MapController.class)
-public class ShadowMapController {
- private ShadowMapView shadowMapView;
- private GeoPoint geoPointAnimatedTo;
-
- @Implementation
- public void animateTo(com.google.android.maps.GeoPoint geoPoint) {
- setCenter(geoPoint);
- geoPointAnimatedTo = geoPoint;
- }
-
- @Implementation
- public void animateTo(com.google.android.maps.GeoPoint geoPoint, java.lang.Runnable runnable) {
- animateTo(geoPoint);
- runnable.run();
- }
-
- @Implementation
- public void setCenter(com.google.android.maps.GeoPoint geoPoint) {
- shadowMapView.mapCenter = geoPoint;
- }
-
- @Implementation
- public void zoomToSpan(int latSpan, int lngSpan) {
- shadowMapView.latitudeSpan = latSpan;
- shadowMapView.longitudeSpan = lngSpan;
- }
-
- @Implementation
- public boolean zoomIn() {
- shadowMapView.zoomLevel++;
- return true;
- }
-
- @Implementation
- public boolean zoomOut() {
- shadowMapView.zoomLevel--;
- return true;
- }
-
- @Implementation
- public int setZoom(int i) {
- shadowMapView.zoomLevel = i;
- return i;
- }
-
- /**
- * Non-Android accessor that returns the {@code MapView} that is being controlled
- *
- * @return the {@code MapView} that is being controlled
- */
- public ShadowMapView getShadowMapView() {
- return shadowMapView;
- }
-
- /**
- * Non-Android accessor that returns the most recent value set by a call to either version of {@code animateTo()}
- *
- * @return the most recent value set by a call to either version of {@code animateTo()}
- */
- public GeoPoint getGeoPointAnimatedTo() {
- return geoPointAnimatedTo;
- }
-
- /**
- * Non-Android accessor that allows the {@code MapView} being controlled to be set explicitly.
- *
- * @param shadowMapView the {@link ShadowMapView} to be controlled (either created explicitly or obtained via a call
- * to {@link com.xtremelabs.robolectric.RobolectricForMaps.shadowOf(com.google.android.maps.MapView)})
- */
- void setShadowMapView(ShadowMapView shadowMapView) {
- this.shadowMapView = shadowMapView;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowMapView.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowMapView.java
deleted file mode 100644
index b9e3458ed..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowMapView.java
+++ /dev/null
@@ -1,271 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.content.Context;
-import android.graphics.Point;
-import android.view.MotionEvent;
-import android.widget.ZoomButtonsController;
-import com.google.android.maps.GeoPoint;
-import com.google.android.maps.MapController;
-import com.google.android.maps.MapView;
-import com.google.android.maps.Overlay;
-import com.google.android.maps.Projection;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import static com.xtremelabs.robolectric.RobolectricForMaps.shadowOf;
-
-/**
- * Shadow of {@code MapView} that simulates the internal state of a {@code MapView}. Supports {@code Projection}s,
- * {@code Overlay}s, and {@code TouchEvent}s
- */
-@SuppressWarnings({"UnusedDeclaration"})
-@Implements(MapView.class)
-public class ShadowMapView extends ShadowViewGroup {
- private boolean satelliteOn;
- private MapController mapController;
- private List<Overlay> overlays = new ArrayList<Overlay>();
- GeoPoint mapCenter = new GeoPoint(10, 10);
- int longitudeSpan = 20;
- int latitudeSpan = 30;
- int zoomLevel = 1;
- private ShadowMapController shadowMapController;
- private ZoomButtonsController zoomButtonsController;
- private MapView realMapView;
- private Projection projection;
- private boolean useBuiltInZoomMapControls;
- private boolean mouseDownOnMe = false;
- private Point lastTouchEventPoint;
- private GeoPoint mouseDownCenter;
- private boolean preLoadWasCalled;
- private boolean canCoverCenter = true;
-
- public ShadowMapView(MapView mapView) {
- realMapView = mapView;
- zoomButtonsController = new ZoomButtonsController(mapView);
- }
-
- public void __constructor__(Context context, String title) {
- super.__constructor__(context);
- }
-
- public static int toE6(double d) {
- return (int) (d * 1e6);
- }
-
- public static double fromE6(int i) {
- return i / 1e6;
- }
-
- @Implementation
- public void setSatellite(boolean satelliteOn) {
- this.satelliteOn = satelliteOn;
- }
-
- @Implementation
- public boolean isSatellite() {
- return satelliteOn;
- }
-
- @Implementation
- public boolean canCoverCenter() {
- return canCoverCenter;
- }
-
- @Implementation
- public MapController getController() {
- if (mapController == null) {
- try {
- mapController = Robolectric.newInstanceOf(MapController.class);
- shadowMapController = shadowOf(mapController);
- shadowMapController.setShadowMapView(this);
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
- return mapController;
- }
-
- @Implementation
- public ZoomButtonsController getZoomButtonsController() {
- return zoomButtonsController;
- }
-
- @Implementation
- public void setBuiltInZoomControls(boolean useBuiltInZoomMapControls) {
- this.useBuiltInZoomMapControls = useBuiltInZoomMapControls;
- }
-
- @Implementation
- public com.google.android.maps.Projection getProjection() {
- if (projection == null) {
- projection = new Projection() {
- @Override public Point toPixels(GeoPoint geoPoint, Point point) {
- if (point == null) {
- point = new Point();
- }
-
- point.y = scaleDegree(geoPoint.getLatitudeE6(), bottom, top, mapCenter.getLatitudeE6(), latitudeSpan);
- point.x = scaleDegree(geoPoint.getLongitudeE6(), left, right, mapCenter.getLongitudeE6(), longitudeSpan);
- return point;
- }
-
- @Override public GeoPoint fromPixels(int x, int y) {
- int lat = scalePixel(y, bottom, -realMapView.getHeight(), mapCenter.getLatitudeE6(), latitudeSpan);
- int lng = scalePixel(x, left, realMapView.getWidth(), mapCenter.getLongitudeE6(), longitudeSpan);
- return new GeoPoint(lat, lng);
- }
-
- @Override public float metersToEquatorPixels(float v) {
- return 0;
- }
- };
- }
- return projection;
- }
-
- private int scalePixel(int pixel, int minPixel, int maxPixel, int centerDegree, int spanDegrees) {
- int offsetPixels = pixel - minPixel;
- double ratio = offsetPixels / ((double) maxPixel);
- int minDegrees = centerDegree - spanDegrees / 2;
- return (int) (minDegrees + spanDegrees * ratio);
- }
-
- private int scaleDegree(int degree, int minPixel, int maxPixel, int centerDegree, int spanDegrees) {
- int minDegree = centerDegree - spanDegrees / 2;
- int offsetDegrees = degree - minDegree;
- double ratio = offsetDegrees / ((double) spanDegrees);
- int spanPixels = maxPixel - minPixel;
- return (int) (minPixel + spanPixels * ratio);
- }
-
- @Implementation
- public List<Overlay> getOverlays() {
- return overlays;
- }
-
- @Implementation
- public GeoPoint getMapCenter() {
- return mapCenter;
- }
-
- @Implementation
- public int getLatitudeSpan() {
- return latitudeSpan;
- }
-
- @Implementation
- public int getLongitudeSpan() {
- return longitudeSpan;
- }
-
- @Implementation
- public int getZoomLevel() {
- return zoomLevel;
- }
-
- @Implementation
- @Override public boolean dispatchTouchEvent(MotionEvent event) {
- for (Overlay overlay : overlays) {
- if (overlay.onTouchEvent(event, realMapView)) {
- return true;
- }
- }
-
- GeoPoint mouseGeoPoint = getProjection().fromPixels((int) event.getX(), (int) event.getY());
- int diffX = 0;
- int diffY = 0;
- if (mouseDownOnMe) {
- diffX = (int) event.getX() - lastTouchEventPoint.x;
- diffY = (int) event.getY() - lastTouchEventPoint.y;
- }
-
- switch (event.getAction()) {
- case MotionEvent.ACTION_DOWN:
- mouseDownOnMe = true;
- mouseDownCenter = getMapCenter();
- break;
- case MotionEvent.ACTION_MOVE:
- if (mouseDownOnMe) {
- moveByPixels(-diffX, -diffY);
- }
- break;
- case MotionEvent.ACTION_UP:
- if (mouseDownOnMe) {
- moveByPixels(-diffX, -diffY);
- mouseDownOnMe = false;
- }
- break;
-
- case MotionEvent.ACTION_CANCEL:
- getController().setCenter(mouseDownCenter);
- mouseDownOnMe = false;
- break;
- }
-
- lastTouchEventPoint = new Point((int) event.getX(), (int) event.getY());
-
- return super.dispatchTouchEvent(event);
- }
-
- @Implementation
- public void preLoad() {
- preLoadWasCalled = true;
- }
-
- private void moveByPixels(int x, int y) {
- Point center = getProjection().toPixels(mapCenter, null);
- center.offset(x, y);
- mapCenter = getProjection().fromPixels(center.x, center.y);
- }
-
- /**
- * Non-Android accessor.
- *
- * @return whether to use built in zoom map controls
- */
- public boolean getUseBuiltInZoomMapControls() {
- return useBuiltInZoomMapControls;
- }
-
- /**
- * Non-Android accessor.
- *
- * @return whether {@link #preLoad()} has been called on this {@code MapView}
- */
- public boolean preLoadWasCalled() {
- return preLoadWasCalled;
- }
-
- /**
- * Non-Android accessor to set the latitude span (the absolute value of the difference between the Northernmost and
- * Southernmost latitudes visible on the map) of this {@code MapView}
- *
- * @param latitudeSpan the new latitude span for this {@code MapView}
- */
- public void setLatitudeSpan(int latitudeSpan) {
- this.latitudeSpan = latitudeSpan;
- }
-
- /**
- * Non-Android accessor to set the longitude span (the absolute value of the difference between the Easternmost and
- * Westernmost longitude visible on the map) of this {@code MapView}
- *
- * @param longitudeSpan the new latitude span for this {@code MapView}
- */
- public void setLongitudeSpan(int longitudeSpan) {
- this.longitudeSpan = longitudeSpan;
- }
-
- /**
- * Non-Android accessor that controls the value to be returned by {@link #canCoverCenter()}
- *
- * @param canCoverCenter the value to be returned by {@link #canCoverCenter()}
- */
- public void setCanCoverCenter(boolean canCoverCenter) {
- this.canCoverCenter = canCoverCenter;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowMarginLayoutParams.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowMarginLayoutParams.java
deleted file mode 100644
index 760456058..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowMarginLayoutParams.java
+++ /dev/null
@@ -1,26 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.internal.RealObject;
-
-import android.view.ViewGroup;
-
-/**
- * Shadow for {@link ViewGroup.MarginLayoutParams} that simulates its implementation.
- */
-@SuppressWarnings("UnusedDeclaration")
-@Implements(ViewGroup.MarginLayoutParams.class)
-public class ShadowMarginLayoutParams extends ShadowLayoutParams {
-
- @RealObject
- private ViewGroup.MarginLayoutParams realMarginLayoutParams;
-
- @Implementation
- public void setMargins(int left, int top, int right, int bottom) {
- realMarginLayoutParams.leftMargin = left;
- realMarginLayoutParams.topMargin = top;
- realMarginLayoutParams.rightMargin = right;
- realMarginLayoutParams.bottomMargin = bottom;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowMatrix.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowMatrix.java
deleted file mode 100644
index baf76c270..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowMatrix.java
+++ /dev/null
@@ -1,74 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.graphics.Matrix;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-
-@SuppressWarnings({"UnusedDeclaration"})
-@Implements(Matrix.class)
-public class ShadowMatrix {
- private float scaleX = 1;
- private float transX;
-
- private float scaleY = 1;
- private float transY;
-
- // scaleX=0, skewX=1, transX=2
- // skewY=3, scaleY=4, transY=5
- // persp0=6, persp1=7, persp2=8
-
- // identity: Matrix{[1.0, 0.0, 0.0][0.0, 1.0, 0.0][0.0, 0.0, 1.0]}
-
- // drag down: Matrix{[1.0, 0.0, -1.3872986][0.0, 1.0, 0.37722778][0.0, 0.0, 1.0]}
-
-
- public void __constructor__(Matrix src) {
- set(src);
- }
-
- @Implementation
- public void set(Matrix src) {
- transX = shadowOf(src).transX;
- scaleX = shadowOf(src).scaleX;
-
- transY = shadowOf(src).transY;
- scaleY = shadowOf(src).scaleY;
- }
-
- @Implementation
- public void setTranslate(float dx, float dy) {
- transX = dx;
- transY = dy;
- }
-
- @Implementation
- public void postTranslate(float dx, float dy) {
- transX += dx;
- transY += dy;
- }
-
- public float getTransX() {
- return transX;
- }
-
- public float getTransY() {
- return transY;
- }
-
- @Implementation
- public boolean postScale(float sx, float sy, float px, float py) {
- scaleX *= sx;
- scaleY *= sy;
- return true;
- }
-
- public float getScaleX() {
- return scaleX;
- }
-
- public float getScaleY() {
- return scaleY;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowMatrixCursor.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowMatrixCursor.java
deleted file mode 100644
index 870b96cc1..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowMatrixCursor.java
+++ /dev/null
@@ -1,88 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-import android.database.CursorIndexOutOfBoundsException;
-import android.database.MatrixCursor;
-
-import java.util.ArrayList;
-import java.util.List;
-
-@Implements(MatrixCursor.class)
-public class ShadowMatrixCursor extends ShadowAbstractCursor {
- private List<Object[]> data = new ArrayList<Object[]>();
-
- public void __constructor__(String[] columns) {
- __constructor__(columns, 0);
- }
-
- public void __constructor__(String[] columns, int initialCapacity) {
- columnNameArray = columns;
- }
-
- @Implementation
- public void addRow(Object[] data) {
- rowCount++;
- this.data.add(data);
- }
-
- @Implementation
- public String getString(int column) {
- Object columnValue = get(column);
- return columnValue == null ? null : columnValue.toString();
- }
-
- @Implementation
- public long getLong(int column) {
- Number numberValue = (Number) get(column);
- return numberValue == null ? 0 : numberValue.longValue();
- }
-
- @Implementation
- public short getShort(int column) {
- Number numberValue = (Number) get(column);
- return numberValue == null ? 0 : numberValue.shortValue();
- }
-
- @Implementation
- public int getInt(int column) {
- Number numberValue = (Number) get(column);
- return numberValue == null ? 0 : numberValue.intValue();
- }
-
- @Implementation
- public float getFloat(int column) {
- Number numberValue = (Number) get(column);
- return numberValue == null ? 0.0f : numberValue.floatValue();
- }
-
- @Implementation
- public double getDouble(int column) {
- Number numberValue = (Number) get(column);
- return numberValue == null ? 0.0 : numberValue.doubleValue();
- }
-
- @Implementation
- public byte[] getBlob(int column) {
- return (byte[]) get(column);
- }
-
- @Implementation
- public boolean isNull(int column) {
- return get(column) == null;
- }
-
- private Object get(int column) {
- if (column < 0 || column >= columnNameArray.length) {
- throw new CursorIndexOutOfBoundsException(null);
- }
- if (currentRowNumber < 0) {
- throw new CursorIndexOutOfBoundsException("Before first row.");
- }
- if (currentRowNumber >= rowCount) {
- throw new CursorIndexOutOfBoundsException("After last row.");
- }
- return data.get(currentRowNumber)[column];
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowMediaPlayer.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowMediaPlayer.java
deleted file mode 100644
index e33a17b71..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowMediaPlayer.java
+++ /dev/null
@@ -1,181 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.content.Context;
-import android.media.MediaPlayer;
-import android.net.Uri;
-
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.internal.RealObject;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-
-/**
- * Shadows the Android {@code MediaPlayer} class.
- */
-@Implements(MediaPlayer.class)
-public class ShadowMediaPlayer {
-
- @RealObject private MediaPlayer player;
-
- private boolean playing;
- private boolean prepared;
- private int currentPosition;
- private Uri sourceUri;
- private int sourceResId;
- private MediaPlayer.OnCompletionListener completionListener;
- private MediaPlayer.OnPreparedListener preparedListener;
-
- @Implementation
- public static MediaPlayer create(Context context, int resId) {
- MediaPlayer mp = new MediaPlayer();
- shadowOf(mp).sourceResId = resId;
- try {
- mp.prepare();
- } catch (Exception e) { return null; }
-
- return mp;
- }
-
- @Implementation
- public static MediaPlayer create(Context context, Uri uri) {
- MediaPlayer mp = new MediaPlayer();
- try {
- mp.setDataSource(context, uri);
- mp.prepare();
- } catch (Exception e) { return null; }
-
- return mp;
- }
-
- public void __constructor__() {
- playing = true;
- }
-
- @Implementation
- public void setDataSource(Context context, Uri uri) {
- this.sourceUri = uri;
- }
-
- @Implementation
- public void setOnCompletionListener(MediaPlayer.OnCompletionListener listener) {
- completionListener = listener;
- }
-
- @Implementation
- public void setOnPreparedListener(MediaPlayer.OnPreparedListener listener) {
- preparedListener = listener;
- }
-
- @Implementation
- public boolean isPlaying() {
- return playing;
- }
-
- @Implementation
- public void prepare() {
- prepared = true;
- invokePreparedListener();
- }
-
- /**
- * Test cases are expected to simulate completion of the 'prepare' phase
- * by manually invoking {@code #invokePreparedListener}.
- */
- @Implementation
- public void prepareAsync() {
- prepared = true;
- }
-
- @Implementation
- public void start() {
- playing = true;
- }
-
- @Implementation
- public void pause() {
- playing = false;
- }
-
- @Implementation
- public void release() {
- playing = false;
- prepared = false;
- }
-
- @Implementation
- public void reset() {
- playing = false;
- prepared = false;
- }
-
- @Implementation
- public void stop() {
- playing = false;
- }
-
- @Implementation
- public int getCurrentPosition() {
- return currentPosition;
- }
-
- public void setCurrentPosition(int position) {
- currentPosition = position;
- }
-
- /**
- * Non-Android accessor. Use for assertions.
- * @return
- */
- public Uri getSourceUri() {
- return sourceUri;
- }
-
- /**
- * Non-Android accessor. Use for assertions.
- * @return
- */
- public int getSourceResId() {
- return sourceResId;
- }
-
- /**
- * Non-Android accessor. Use for assertions.
- * @return
- */
- public boolean isPrepared() {
- return prepared;
- }
-
- /**
- * Non-Android accessor. Use for assertions.
- * @return
- */
- public MediaPlayer.OnCompletionListener getOnCompletionListener() {
- return completionListener;
- }
-
- /**
- * Non-Android accessor. Use for assertions.
- * @return
- */
- public MediaPlayer.OnPreparedListener getOnPreparedListener() {
- return preparedListener;
- }
-
- /**
- * Allows test cases to simulate 'prepared' state by invoking callback.
- */
- public void invokePreparedListener() {
- if (preparedListener == null) return;
- preparedListener.onPrepared( player );
- }
-
- /**
- * Allows test cases to simulate 'completed' state by invoking callback.
- */
- public void invokeCompletionListener() {
- if (completionListener == null) return;
- completionListener.onCompletion( player );
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowMediaRecorder.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowMediaRecorder.java
deleted file mode 100644
index 95884c886..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowMediaRecorder.java
+++ /dev/null
@@ -1,256 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.hardware.Camera;
-import android.media.MediaRecorder;
-import android.view.Surface;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-/**
- * Shadows the {@code MediaRecorder} class.
- */
-@Implements(MediaRecorder.class)
-public class ShadowMediaRecorder {
-
- // Recording machine state, as per:
- // http://developer.android.com/reference/android/media/MediaRecorder.html
- public static final int STATE_ERROR = -1;
- public static final int STATE_INITIAL = 1;
- public static final int STATE_INITIALIZED = 2;
- public static final int STATE_DATA_SOURCE_CONFIGURED = 3;
- public static final int STATE_PREPARED = 4;
- public static final int STATE_RECORDING = 5;
- public static final int STATE_RELEASED = 6;
-
- private int state;
-
- private Camera camera;
- private int audioChannels;
- private int audioEncoder;
- private int audioBitRate;
- private int audioSamplingRate;
- private int audioSource;
- private int maxDuration;
- private long maxFileSize;
- private String outputPath;
- private int outputFormat;
- private int videoEncoder;
- private int videoBitRate;
- private int videoFrameRate;
- private int videoWidth;
- private int videoHeight;
- private int videoSource;
-
- private Surface previewDisplay;
- private MediaRecorder.OnErrorListener errorListener;
- private MediaRecorder.OnInfoListener infoListener;
-
- public void __constructor__() {
- state = STATE_INITIAL;
- }
-
- @Implementation
- public void setAudioChannels(int numChannels) {
- audioChannels = numChannels;
- }
-
- @Implementation
- public void setAudioEncoder(int audio_encoder) {
- audioEncoder = audio_encoder;
- state = STATE_DATA_SOURCE_CONFIGURED;
- }
-
- @Implementation
- public void setAudioEncodingBitRate(int bitRate) {
- audioBitRate = bitRate;
- }
-
- @Implementation
- public void setAudioSamplingRate(int samplingRate) {
- audioSamplingRate = samplingRate;
- }
-
- @Implementation
- public void setAudioSource(int audio_source) {
- audioSource = audio_source;
- state = STATE_INITIALIZED;
- }
-
- @Implementation
- public void setCamera(Camera c) {
- camera = c;
- }
-
- @Implementation
- public void setMaxDuration(int max_duration_ms) {
- maxDuration = max_duration_ms;
- }
-
- @Implementation
- public void setMaxFileSize(long max_filesize_bytes) {
- maxFileSize = max_filesize_bytes;
- }
-
- @Implementation
- public void setOnErrorListener(MediaRecorder.OnErrorListener l) {
- errorListener = l;
- }
-
- @Implementation
- public void setOnInfoListener(MediaRecorder.OnInfoListener listener) {
- infoListener = listener;
- }
-
- @Implementation
- public void setOutputFile(String path) {
- outputPath = path;
- state = STATE_DATA_SOURCE_CONFIGURED;
- }
-
- @Implementation
- public void setOutputFormat(int output_format) {
- outputFormat = output_format;
- state = STATE_DATA_SOURCE_CONFIGURED;
- }
-
- @Implementation
- public void setPreviewDisplay(Surface sv) {
- previewDisplay = sv;
- state = STATE_DATA_SOURCE_CONFIGURED;
- }
-
- @Implementation
- public void setVideoEncoder(int video_encoder) {
- videoEncoder = video_encoder;
- state = STATE_DATA_SOURCE_CONFIGURED;
- }
-
- @Implementation
- public void setVideoEncodingBitRate(int bitRate) {
- videoBitRate = bitRate;
- }
-
- @Implementation
- public void setVideoFrameRate(int rate) {
- videoFrameRate = rate;
- state = STATE_DATA_SOURCE_CONFIGURED;
- }
-
- @Implementation
- public void setVideoSize(int width, int height) {
- videoWidth = width;
- videoHeight = height;
- state = STATE_DATA_SOURCE_CONFIGURED;
- }
-
- @Implementation
- public void setVideoSource(int video_source) {
- videoSource = video_source;
- state = STATE_INITIALIZED;
- }
-
- @Implementation
- public void prepare() {
- state = STATE_PREPARED;
- }
-
- @Implementation
- public void start() {
- state = STATE_RECORDING;
- }
-
- @Implementation
- public void stop() {
- state = STATE_INITIAL;
- }
-
- @Implementation
- public void reset() {
- state = STATE_INITIAL;
- }
-
- @Implementation
- public void release() {
- state = STATE_RELEASED;
- }
-
- public Camera getCamera() {
- return camera;
- }
-
- public int getAudioChannels() {
- return audioChannels;
- }
-
- public int getAudioEncoder() {
- return audioEncoder;
- }
-
- public int getAudioEncodingBitRate() {
- return audioBitRate;
- }
-
- public int getAudioSamplingRate() {
- return audioSamplingRate;
- }
-
- public int getAudioSource() {
- return audioSource;
- }
-
- public int getMaxDuration() {
- return maxDuration;
- }
-
- public long getMaxFileSize() {
- return maxFileSize;
- }
-
- public String getOutputPath() {
- return outputPath;
- }
-
- public int getOutputFormat() {
- return outputFormat;
- }
-
- public int getVideoEncoder() {
- return videoEncoder;
- }
-
- public int getVideoEncodingBitRate() {
- return videoBitRate;
- }
-
- public int getVideoFrameRate() {
- return videoFrameRate;
- }
-
- public int getVideoWidth() {
- return videoWidth;
- }
-
- public int getVideoHeight() {
- return videoHeight;
- }
-
- public int getVideoSource() {
- return videoSource;
- }
-
- public Surface getPreviewDisplay() {
- return previewDisplay;
- }
-
- public MediaRecorder.OnErrorListener getErrorListener() {
- return errorListener;
- }
-
- public MediaRecorder.OnInfoListener getInfoListener() {
- return infoListener;
- }
-
- public int getState() {
- return state;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowMediaStore.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowMediaStore.java
deleted file mode 100644
index a0c93f52b..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowMediaStore.java
+++ /dev/null
@@ -1,39 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.content.ContentResolver;
-import android.graphics.Bitmap;
-import android.net.Uri;
-import android.provider.MediaStore;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-@SuppressWarnings({"UnusedDeclaration"})
-@Implements(MediaStore.class)
-public class ShadowMediaStore {
-
- @Implements(MediaStore.Images.class)
- public static class ShadowImages {
- @Implements(MediaStore.Images.Media.class)
- public static class ShadowMedia {
- @Implementation
- public static Bitmap getBitmap(ContentResolver cr, Uri url) {
- return ShadowBitmapFactory.create(url.toString());
- }
- }
- }
-
- public static void reset() {
- Robolectric.Reflection.setFinalStaticField(MediaStore.Images.Media.class, "EXTERNAL_CONTENT_URI",
- Uri.parse("content://media/external/images/media"));
-
- Robolectric.Reflection.setFinalStaticField(MediaStore.Images.Media.class, "INTERNAL_CONTENT_URI",
- Uri.parse("content://media/internal/images/media"));
-
- Robolectric.Reflection.setFinalStaticField(MediaStore.Video.Media.class, "EXTERNAL_CONTENT_URI",
- Uri.parse("content://media/external/video/media"));
-
- Robolectric.Reflection.setFinalStaticField(MediaStore.Video.Media.class, "INTERNAL_CONTENT_URI",
- Uri.parse("content://media/internal/video/media"));
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowMenuInflater.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowMenuInflater.java
deleted file mode 100644
index c39c45aba..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowMenuInflater.java
+++ /dev/null
@@ -1,29 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.content.Context;
-import android.view.Menu;
-import android.view.MenuInflater;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-
-/**
- * Shadow of {@code MenuInflater} that actually inflates menus into {@code View}s that are functional enough to
- * support testing.
- */
-
-@Implements(MenuInflater.class)
-public class ShadowMenuInflater {
- private Context context;
-
- public void __constructor__(Context context) {
- this.context = context;
- }
-
- @Implementation
- public void inflate(int resource, Menu root) {
- shadowOf(context.getApplicationContext()).getResourceLoader().inflateMenu(context, resource, root);
- }
-
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowMessage.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowMessage.java
deleted file mode 100644
index d1588c023..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowMessage.java
+++ /dev/null
@@ -1,121 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.internal.RealObject;
-
-import android.os.Bundle;
-import android.os.Handler;
-import android.os.Message;
-
-@Implements(Message.class)
-public class ShadowMessage {
- private Bundle data;
- private Handler target;
- private long when;
-
- @RealObject
- private Message message;
-
- @Implementation
- public void setData(Bundle data) {
- this.data = data;
- }
-
- @Implementation
- public void setTarget(Handler target) {
- this.target = target;
- }
-
- @Implementation
- public Bundle peekData() {
- return data;
- }
-
- @Implementation
- public Bundle getData() {
- if (data == null) {
- data = new Bundle();
- }
- return data;
- }
-
- @Implementation
- public Handler getTarget() {
- return target;
- }
-
- @Implementation
- public void copyFrom(Message m) {
- message.arg1 = m.arg1;
- message.arg2 = m.arg2;
- message.obj = m.obj;
- message.what = m.what;
- message.setData(m.getData());
- }
-
- @Implementation
- public static Message obtain() {
- return new Message();
- }
-
- @Implementation
- public static Message obtain(Handler h) {
- Message m = new Message();
- m.setTarget(h);
- return m;
- }
-
- @Implementation
- public static Message obtain(Handler h, int what) {
- Message m = obtain(h);
- m.what = what;
- return m;
- }
-
- @Implementation
- public static Message obtain(Handler h, int what, Object obj) {
- Message m = obtain(h, what);
- m.obj = obj;
- return m;
- }
-
- @Implementation
- public static Message obtain(Handler h, int what, int arg1, int arg2) {
- Message m = obtain(h, what);
- m.arg1 = arg1;
- m.arg2 = arg2;
- return m;
- }
-
- @Implementation
- public static Message obtain(Handler h, int what, int arg1, int arg2, Object obj) {
- Message m = obtain(h, what, arg1, arg2);
- m.obj = obj;
- return m;
- }
-
- @Implementation
- public static Message obtain(Message msg) {
- Message m = new Message();
- m.copyFrom(msg);
- m.setTarget(msg.getTarget());
- return m;
- }
-
- @Implementation
- public void sendToTarget() {
- target.sendMessage(message);
- }
-
- @Implementation
- public long getWhen() {
- return when;
- }
-
- public void setWhen(long when) {
- this.when = when;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowMessenger.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowMessenger.java
deleted file mode 100644
index eb22e46f3..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowMessenger.java
+++ /dev/null
@@ -1,27 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.internal.RealObject;
-
-import android.os.Bundle;
-import android.os.Handler;
-import android.os.Message;
-import android.os.Messenger;
-import android.os.RemoteException;
-
-@Implements(Messenger.class)
-public class ShadowMessenger {
-
- private Handler handler;
-
- public void __constructor__(Handler handler) {
- this.handler = handler;
- }
-
- @Implementation
- public void send(Message message) throws RemoteException {
- message.setTarget(handler);
- message.sendToTarget();
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowMimeTypeMap.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowMimeTypeMap.java
deleted file mode 100644
index c344b6616..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowMimeTypeMap.java
+++ /dev/null
@@ -1,77 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.webkit.MimeTypeMap;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-
-/**
- * Shadow for {@code MimeTypeMap} that allows custom extension <-> mimetype mapping to be set up by tests.
- */
-@Implements(MimeTypeMap.class)
-public class ShadowMimeTypeMap {
-
- Map<String, String> extensionToMimeTypeMap = new HashMap<String, String>();
- Map<String, String> mimeTypeToExtensionMap = new HashMap<String, String>();
-
- static MimeTypeMap sSingleton = null;
- static Object sSingletonLock = new Object();
-
- @Implementation
- public static MimeTypeMap getSingleton() {
- if (sSingleton == null) {
- synchronized (sSingletonLock) {
- if (sSingleton == null) {
- sSingleton = Robolectric.newInstanceOf(MimeTypeMap.class);
- }
- }
- }
-
- return sSingleton;
- }
-
- public static void reset() {
- shadowOf(getSingleton()).clearMappings();
- }
-
- @Implementation
- public String getMimeTypeFromExtension(String extension) {
- if (extensionToMimeTypeMap.containsKey(extension))
- return extensionToMimeTypeMap.get(extension);
-
- return null;
- }
-
- @Implementation
- public String getExtensionFromMimeType(String mimeType) {
- if (mimeTypeToExtensionMap.containsKey(mimeType))
- return mimeTypeToExtensionMap.get(mimeType);
-
- return null;
- }
-
- public void addExtensionMimeTypMapping(String extension, String mimeType) {
- extensionToMimeTypeMap.put(extension, mimeType);
- mimeTypeToExtensionMap.put(mimeType, extension);
- }
-
- public void clearMappings() {
- extensionToMimeTypeMap.clear();
- mimeTypeToExtensionMap.clear();
- }
-
- @Implementation
- public boolean hasExtension(String extension) {
- return extensionToMimeTypeMap.containsKey(extension);
- }
-
- @Implementation
- public boolean hasMimeType(String mimeType) {
- return mimeTypeToExtensionMap.containsKey(mimeType);
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowMotionEvent.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowMotionEvent.java
deleted file mode 100644
index c9a71875a..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowMotionEvent.java
+++ /dev/null
@@ -1,155 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.view.MotionEvent;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.internal.RealObject;
-
-import java.lang.reflect.Constructor;
-
-/**
- * Shadow for {@code MotionEvent} that uses reflection to create {@code MotionEvent} objects, which cannot otherwise
- * be constructed.
- */
-@SuppressWarnings({"UnusedDeclaration"})
-@Implements(MotionEvent.class)
-public class ShadowMotionEvent {
- @RealObject private MotionEvent realObject;
-
- private int action;
- private float[] x = new float[2];
- private float[] y = new float[2];
- private int pointerCount = 1;
- private long downTime;
- private long eventTime;
- private int[] pointerIds = new int[2];
- private int pointerIndex;
-
- @Implementation
- public static MotionEvent obtain(long downTime, long eventTime, int action, float x, float y, int metaState) {
- try {
- Constructor<MotionEvent> constructor = MotionEvent.class.getDeclaredConstructor();
- constructor.setAccessible(true);
- MotionEvent motionEvent = constructor.newInstance();
- ShadowMotionEvent shadowMotionEvent = (ShadowMotionEvent) Robolectric.shadowOf_(motionEvent);
- shadowMotionEvent.x[0] = x;
- shadowMotionEvent.y[0] = y;
- shadowMotionEvent.action = action;
- shadowMotionEvent.downTime = downTime;
- shadowMotionEvent.eventTime = eventTime;
- return motionEvent;
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
-
- @Implementation
- public static MotionEvent obtain(MotionEvent motionEvent) {
- return obtain(motionEvent.getDownTime(), motionEvent.getEventTime(), motionEvent.getAction(), motionEvent.getX(), motionEvent.getY(), motionEvent.getMetaState());
- }
-
- @Implementation
- public int getAction() {
- return action | (pointerIndex << MotionEvent.ACTION_POINTER_ID_SHIFT);
- }
-
- @Implementation
- public float getRawX() {
- return getX();
- }
-
- @Implementation
- public float getRawY() {
- return getY();
- }
-
- @Implementation
- public final float getX() {
- return getX(0);
- }
-
- @Implementation
- public final float getY() {
- return getY(0);
- }
-
- @Implementation
- public final float getX(int pointerIndex) {
- return x[pointerIndex];
- }
-
- @Implementation
- public final float getY(int pointerIndex) {
- return y[pointerIndex];
- }
-
- @Implementation
- public final int getPointerCount() {
- return pointerCount;
- }
-
- @Implementation
- public final long getEventTime() {
- return eventTime;
- }
-
- @Implementation
- public final long getDownTime() {
- return downTime;
- }
-
- @Implementation
- public final int getPointerId(int index) {
- return pointerIds[index];
- }
-
- @Implementation
- public final int findPointerIndex(int id) {
- for (int i = 0; i < pointerIds.length; i++) {
- int pointerId = pointerIds[i];
-
- if (pointerId == id) {
- return i;
- }
- }
- return -1;
- }
-
- @Implementation
- public final int getActionMasked() {
- return action;
- }
-
- @Implementation
- public final int getActionIndex() {
- return pointerIndex;
- }
-
- @Implementation
- public final float getPressure(int pointerIndex) {
- return 1.0f;
- }
-
- @Implementation
- public final void setLocation(float x, float y) {
- this.x[0] = x;
- this.y[0] = y;
- }
-
- public MotionEvent setPointer2(float x, float y) {
- this.x[1] = x;
- this.y[1] = y;
- pointerCount = 2;
- return realObject;
- }
-
- public void setPointerIndex(int pointerIndex) {
- this.pointerIndex = pointerIndex;
- }
-
- public void setPointerIds(int index0PointerId, int index1PointerId) {
- pointerIds[0] = index0PointerId;
- pointerIds[1] = index1PointerId;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowNdefMessage.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowNdefMessage.java
deleted file mode 100644
index d3a0cff80..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowNdefMessage.java
+++ /dev/null
@@ -1,24 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.nfc.NdefMessage;
-import android.nfc.NdefRecord;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.internal.RealObject;
-
-@Implements(NdefMessage.class)
-public class ShadowNdefMessage {
- @RealObject
- private NdefMessage realNdefMessage;
-
- private NdefRecord[] ndefRecords;
-
- public void __constructor__(NdefRecord[] ndefRecords) {
- this.ndefRecords = ndefRecords;
- }
-
- @Implementation
- public NdefRecord[] getRecords() {
- return ndefRecords;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowNdefRecord.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowNdefRecord.java
deleted file mode 100644
index 60eec86e4..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowNdefRecord.java
+++ /dev/null
@@ -1,23 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.nfc.NdefRecord;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.internal.RealObject;
-
-@Implements(NdefRecord.class)
-public class ShadowNdefRecord {
- @RealObject
- private NdefRecord realNdefRecord;
-
- private byte[] data;
-
- public void __constructor__(byte[] data) {
- this.data = data;
- }
-
- @Implementation
- public byte[] getPayload() {
- return data;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowNetworkInfo.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowNetworkInfo.java
deleted file mode 100644
index 7446b970e..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowNetworkInfo.java
+++ /dev/null
@@ -1,117 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.net.ConnectivityManager;
-import android.net.NetworkInfo;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-
-/**
- * Shadow of {@code NetworkInfo} which is used by ShadowConnectivityManager.
- */
-
-@Implements(NetworkInfo.class)
-public class ShadowNetworkInfo {
- private boolean isAvailable;
- private boolean isConnected;
- private int connectionType;
- private int connectionSubType;
- private NetworkInfo.DetailedState detailedState;
-
- public static NetworkInfo newInstance() {
- return newInstance(null);
- }
-
- public static NetworkInfo newInstance(NetworkInfo.DetailedState detailedState) {
- return newInstance(detailedState, ConnectivityManager.TYPE_MOBILE, 0, true, true);
- }
-
- public static NetworkInfo newInstance(NetworkInfo.DetailedState detailedState, int type, int subType,
- boolean isAvailable,
- boolean isConnected) {
- NetworkInfo networkInfo = Robolectric.newInstanceOf(NetworkInfo.class);
- final ShadowNetworkInfo info = shadowOf(networkInfo);
- info.setConnectionType(type);
- info.setSubType(subType);
- info.setDetailedState(detailedState);
- info.setAvailableStatus(isAvailable);
- info.setConnectionStatus(isConnected);
- return networkInfo;
- }
-
- @Implementation
- public boolean isConnected() {
- return isConnected;
- }
-
- @Implementation
- public boolean isConnectedOrConnecting() {
- return isConnected;
- }
-
- @Implementation
- public NetworkInfo.State getState() {
- return isConnected ? NetworkInfo.State.CONNECTED :
- NetworkInfo.State.DISCONNECTED;
- }
-
- @Implementation
- public NetworkInfo.DetailedState getDetailedState() {
- return detailedState;
- }
-
- @Implementation
- public int getType(){
- return connectionType;
- }
-
- @Implementation
- public int getSubtype() {
- return connectionSubType;
- }
-
- @Implementation
- public boolean isAvailable() {
- return isAvailable;
- }
-
- /**
- * Non-Android accessor
- * Sets up the return value of {@link #isAvailable()}.
- *
- * @param isAvailable the value that {@link #isAvailable()} will return.
- */
- public void setAvailableStatus(boolean isAvailable) {
- this.isAvailable = isAvailable;
- }
-
- /**
- * Non-Android accessor
- * Sets up the return value of {@link #isConnectedOrConnecting()} and {@link @isConnected()}.
- *
- * @param isConnected the value that {@link #isConnectedOrConnecting()} and {@link #isConnected()} will return.
- */
- public void setConnectionStatus(boolean isConnected) {
- this.isConnected = isConnected;
- }
-
- /**
- * Non-Android accessor
- * Sets up the return value of {@link #getType()}.
- *
- * @param connectionType the value that {@link #getType()} will return.
- */
- public void setConnectionType(int connectionType){
- this.connectionType = connectionType;
- }
-
- public void setSubType(int subType) {
- this.connectionSubType = subType;
- }
-
- public void setDetailedState(NetworkInfo.DetailedState detailedState) {
- this.detailedState = detailedState;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowNfcAdapter.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowNfcAdapter.java
deleted file mode 100644
index 6ff7a524c..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowNfcAdapter.java
+++ /dev/null
@@ -1,73 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.app.Activity;
-import android.app.PendingIntent;
-import android.content.Context;
-import android.content.IntentFilter;
-import android.nfc.NfcAdapter;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.internal.RealObject;
-
-import java.lang.reflect.Constructor;
-import java.lang.reflect.InvocationTargetException;
-
-@Implements(NfcAdapter.class)
-public class ShadowNfcAdapter {
- @RealObject NfcAdapter nfcAdapter;
- private Activity enabledActivity;
- private PendingIntent intent;
- private IntentFilter[] filters;
- private String[][] techLists;
- private Activity disabledActivity;
-
- @Implementation
- public static NfcAdapter getDefaultAdapter(Context context) {
- try {
- Constructor<NfcAdapter> constructor = NfcAdapter.class.getDeclaredConstructor();
- constructor.setAccessible(true);
- return constructor.newInstance();
- } catch (InstantiationException e) {
- throw new RuntimeException(e);
- } catch (IllegalAccessException e) {
- throw new RuntimeException(e);
- } catch (InvocationTargetException e) {
- throw new RuntimeException(e);
- } catch (NoSuchMethodException e) {
- throw new RuntimeException(e);
- }
- }
-
- @Implementation
- public void enableForegroundDispatch(Activity activity, PendingIntent intent, IntentFilter[] filters, String[][] techLists) {
- this.enabledActivity = activity;
- this.intent = intent;
- this.filters = filters;
- this.techLists = techLists;
- }
-
- @Implementation
- public void disableForegroundDispatch(Activity activity) {
- disabledActivity = activity;
- }
-
- public Activity getEnabledActivity() {
- return enabledActivity;
- }
-
- public PendingIntent getIntent() {
- return intent;
- }
-
- public IntentFilter[] getFilters() {
- return filters;
- }
-
- public String[][] getTechLists() {
- return techLists;
- }
-
- public Activity getDisabledActivity() {
- return disabledActivity;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowNotification.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowNotification.java
deleted file mode 100644
index 75bc06f86..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowNotification.java
+++ /dev/null
@@ -1,63 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.app.Notification;
-import android.app.PendingIntent;
-import android.content.Context;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.internal.RealObject;
-
-@SuppressWarnings({"UnusedDeclaration"})
-@Implements(Notification.class)
-public class ShadowNotification {
-
- public Notification getRealNotification() {
- return realNotification;
- }
-
- @RealObject
- Notification realNotification;
-
- private LatestEventInfo latestEventInfo;
-
- public void __constructor__(int icon, CharSequence tickerText, long when) {
- realNotification.icon = icon;
- realNotification.tickerText = tickerText;
- realNotification.when = when;
- }
-
- @Implementation
- public void setLatestEventInfo(Context context, CharSequence contentTitle,
- CharSequence contentText, PendingIntent contentIntent) {
- latestEventInfo = new LatestEventInfo(contentTitle, contentText, contentIntent);
- realNotification.contentIntent = contentIntent;
- }
-
- public LatestEventInfo getLatestEventInfo() {
- return latestEventInfo;
- }
-
- public static class LatestEventInfo {
- private final CharSequence contentTitle;
- private final CharSequence contentText;
- private final PendingIntent contentIntent;
-
- private LatestEventInfo(CharSequence contentTitle, CharSequence contentText, PendingIntent contentIntent) {
- this.contentTitle = contentTitle;
- this.contentText = contentText;
- this.contentIntent = contentIntent;
- }
-
- public CharSequence getContentTitle() {
- return contentTitle;
- }
-
- public CharSequence getContentText() {
- return contentText;
- }
-
- public PendingIntent getContentIntent() {
- return contentIntent;
- }
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowNotificationManager.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowNotificationManager.java
deleted file mode 100644
index e06065f9b..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowNotificationManager.java
+++ /dev/null
@@ -1,73 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.app.Notification;
-import android.app.NotificationManager;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-@SuppressWarnings({"UnusedDeclaration"})
-@Implements(NotificationManager.class)
-public class ShadowNotificationManager {
-
- private Map<Integer, Notification> notifications = new HashMap<Integer, Notification>();
- private Map<String, Integer> idForTag = new HashMap<String, Integer>();
-
- @Implementation
- public void notify(int id, Notification notification)
- {
- notify(null, id, notification);
- }
-
- @Implementation
- public void notify(String tag, int id, Notification notification) {
- if (tag != null) {
- idForTag.put(tag, id);
- }
- notifications.put(id, notification);
- }
-
- @Implementation
- public void cancel(int id)
- {
- cancel(null, id);
- }
-
- @Implementation
- public void cancel(String tag, int id) {
- // I can't make sense of this method signature. I'm guessing that the id is optional and if it's bogus you are supposed to use the tag instead, but that references to both should be gone. PG
- Integer tagId = idForTag.remove(tag);
- if (notifications.containsKey(id)) {
- notifications.remove(id);
- } else {
- notifications.remove(tagId);
- }
- }
-
- @Implementation
- public void cancelAll() {
- notifications.clear();
- idForTag.clear();
- }
-
- public int size() {
- return notifications.size();
- }
-
- public Notification getNotification(int id) {
- return notifications.get(id);
- }
-
- public Notification getNotification(String tag) {
- Integer id = idForTag.get(tag);
- return notifications.get(id);
- }
-
- public List<Notification> getAllNotifications() {
- return new ArrayList<Notification>(notifications.values());
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowOverlayItem.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowOverlayItem.java
deleted file mode 100644
index 9e7edc0bd..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowOverlayItem.java
+++ /dev/null
@@ -1,63 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf_;
-
-import com.google.android.maps.GeoPoint;
-import com.google.android.maps.OverlayItem;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.util.Strings;
-
-@SuppressWarnings({"UnusedDeclaration"})
-@Implements(OverlayItem.class)
-public class ShadowOverlayItem {
- private GeoPoint geoPoint;
- private String title;
- private String snippet;
-
- public void __constructor__(GeoPoint geoPoint, String title, String snippet) {
- this.geoPoint = geoPoint;
- this.title = title;
- this.snippet = snippet;
- }
-
- @Implementation
- public GeoPoint getPoint() {
- return geoPoint;
- }
-
- @Implementation
- public String getTitle() {
- return title;
- }
-
- @Implementation
- public String getSnippet() {
- return snippet;
- }
-
- @Override @Implementation
- public boolean equals(Object o) {
- if (o == null) return false;
- o = shadowOf_(o);
- if (o == null) return false;
- if (this == o) return true;
- if (getClass() != o.getClass()) return false;
-
- ShadowOverlayItem that = (ShadowOverlayItem) o;
-
- return Strings.equals(title, that.title)
- && Strings.equals(snippet, that.snippet)
- && geoPoint == null ? that.geoPoint == null :
- geoPoint.equals(that.geoPoint);
- }
-
- @Override @Implementation
- public int hashCode() {
- int result = 13;
- result = title == null ? result : 19 * result + title.hashCode();
- result = snippet == null ? result : 19 * result + snippet.hashCode();
- result = geoPoint == null ? result : 19 * result + geoPoint.hashCode();
- return result;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowPagerAdapter.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowPagerAdapter.java
deleted file mode 100644
index 949d2c29d..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowPagerAdapter.java
+++ /dev/null
@@ -1,23 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.database.DataSetObserver;
-import android.support.v4.view.PagerAdapter;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-@Implements(PagerAdapter.class)
-public class ShadowPagerAdapter {
- private DataSetObserver dataSetObserver;
-
- @Implementation
- public void registerDataSetObserver(DataSetObserver dataSetObserver) {
- this.dataSetObserver = dataSetObserver;
- }
-
- @Implementation
- public void notifyDataSetChanged() {
- if (dataSetObserver != null) {
- dataSetObserver.onChanged();
- }
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowPaint.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowPaint.java
deleted file mode 100644
index f7c29cfb3..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowPaint.java
+++ /dev/null
@@ -1,219 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.graphics.ColorFilter;
-import android.graphics.Paint;
-import android.graphics.Shader;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.internal.RealObject;
-
-/**
- * Shadow of {@code Paint} that has some extra accessors so that tests can tell whether a {@code Paint} object was
- * created with the expected parameters.
- */
-@SuppressWarnings({"UnusedDeclaration"})
-@Implements(Paint.class)
-public class ShadowPaint {
-
- private int color;
- private Paint.Style style;
- private Paint.Cap cap;
- private Paint.Join join;
- private float width;
- private float shadowRadius;
- private float shadowDx;
- private float shadowDy;
- private int shadowColor;
- private Shader shader;
- private int alpha;
- private ColorFilter filter;
- private boolean antiAlias;
- private boolean dither;
- private int flags;
-
- @RealObject Paint paint;
-
- public void __constructor__(int flags) {
- this.flags = flags;
- antiAlias = ( flags & Paint.ANTI_ALIAS_FLAG ) == Paint.ANTI_ALIAS_FLAG;
- }
-
- @Implementation
- public int getFlags() {
- return flags;
- }
-
- @Implementation
- public Shader setShader(Shader shader) {
- this.shader = shader;
- return shader;
- }
-
- @Implementation
- public int getAlpha() {
- return alpha;
- }
-
- @Implementation
- public void setAlpha(int alpha) {
- this.alpha = alpha;
- }
-
-
- @Implementation
- public Shader getShader() {
- return shader;
- }
-
- @Implementation
- public void setColor(int color) {
- this.color = color;
- }
-
- @Implementation
- public int getColor() {
- return color;
- }
-
- @Implementation
- public void setStyle(Paint.Style style) {
- this.style = style;
- }
-
- @Implementation
- public Paint.Style getStyle() {
- return style;
- }
-
- @Implementation
- public void setStrokeCap(Paint.Cap cap) {
- this.cap = cap;
- }
-
- @Implementation
- public Paint.Cap getStrokeCap() {
- return cap;
- }
-
- @Implementation
- public void setStrokeJoin(Paint.Join join) {
- this.join = join;
- }
-
- @Implementation
- public Paint.Join getStrokeJoin() {
- return join;
- }
-
- @Implementation
- public void setStrokeWidth(float width) {
- this.width = width;
- }
-
- @Implementation
- public float getStrokeWidth() {
- return width;
- }
-
- @Implementation
- public void setShadowLayer(float radius, float dx, float dy, int color) {
- shadowRadius = radius;
- shadowDx = dx;
- shadowDy = dy;
- shadowColor = color;
- }
-
- /**
- * Non-Android accessor.
- *
- * @return shadow radius (Paint related shadow, not Robolectric Shadow)
- */
- public float getShadowRadius() {
- return shadowRadius;
- }
-
- /**
- * Non-Android accessor.
- *
- * @return shadow Dx (Paint related shadow, not Robolectric Shadow)
- */
- public float getShadowDx() {
- return shadowDx;
- }
-
- /**
- * Non-Android accessor.
- *
- * @return shadow Dx (Paint related shadow, not Robolectric Shadow)
- */
- public float getShadowDy() {
- return shadowDy;
- }
-
- /**
- * Non-Android accessor.
- *
- * @return shadow color (Paint related shadow, not Robolectric Shadow)
- */
- public int getShadowColor() {
- return shadowColor;
- }
-
- /**
- * Non-Android accessor.
- *
- * @return cap
- */
- public Paint.Cap getCap() {
- return cap;
- }
-
- /**
- * Non-Android accessor.
- *
- * @return join
- */
- public Paint.Join getJoin() {
- return join;
- }
-
- /**
- * Non-Android accessor.
- *
- * @return width
- */
- public float getWidth() {
- return width;
- }
-
- @Implementation
- public ColorFilter getColorFilter() {
- return filter;
- }
-
- @Implementation
- public ColorFilter setColorFilter(ColorFilter filter) {
- this.filter = filter;
- return filter;
- }
-
- @Implementation
- public void setAntiAlias(boolean antiAlias) {
- this.antiAlias = antiAlias;
- }
-
- @Implementation
- public void setDither(boolean dither) {
- this.dither = dither;
- }
-
- @Implementation
- public final boolean isDither() {
- return dither;
- }
-
- @Implementation
- public final boolean isAntiAlias() {
- return antiAlias;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowPair.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowPair.java
deleted file mode 100644
index a477fa95a..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowPair.java
+++ /dev/null
@@ -1,58 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.internal.RealObject;
-
-import android.util.Pair;
-
-import java.lang.reflect.Field;
-
-/**
- * Shadow of {@code Pair}
- */
-@SuppressWarnings({"UnusedDeclaration"})
-@Implements(Pair.class)
-public class ShadowPair {
- @RealObject private Pair realPair;
-
- public void __constructor__(Object first, Object second) {
- setFields(realPair, first, second);
- }
-
- @Implementation
- public static <F, S> Pair<F, S> create(F f, S s) {
- return new Pair<F, S>(f, s);
- }
-
- @Override @Implementation
- public int hashCode() {
- return realPair.first.hashCode() + realPair.second.hashCode();
- }
-
- @Override @Implementation
- public boolean equals(Object o) {
- if (o == this) return true;
- if (!(o instanceof Pair)) return false;
- final Pair other = (Pair) o;
- return realPair.first.equals(other.first) && realPair.second.equals(other.second);
- }
-
- private static void setFields(Pair p, Object first, Object second) {
- try {
- Field f = Pair.class.getDeclaredField("first");
- f.setAccessible(true);
- f.set(p, first);
-
- Field s = Pair.class.getDeclaredField("second");
- s.setAccessible(true);
- s.set(p, second);
- } catch (NoSuchFieldException e) {
- throw new RuntimeException(e);
- } catch (IllegalAccessException e) {
- throw new RuntimeException(e);
- }
- }
-}
-
-
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowParcel.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowParcel.java
deleted file mode 100644
index a6e7bbbcb..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowParcel.java
+++ /dev/null
@@ -1,1009 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-
-import android.os.Bundle;
-import android.os.Parcel;
-import android.os.Parcelable;
-import android.text.TextUtils;
-import android.util.Log;
-import android.util.Pair;
-
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.bytecode.ShadowWrangler;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.internal.RealObject;
-
-import java.lang.reflect.Field;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-@Implements(Parcel.class)
-@SuppressWarnings("unchecked")
-public class ShadowParcel {
-
- private static final int VAL_NULL = -1;
- private static final int VAL_STRING = 0;
- private static final int VAL_INTEGER = 1;
- private static final int VAL_MAP = 2;
- private static final int VAL_BUNDLE = 3;
- private static final int VAL_PARCELABLE = 4;
- private static final int VAL_SHORT = 5;
- private static final int VAL_LONG = 6;
- private static final int VAL_FLOAT = 7;
- private static final int VAL_DOUBLE = 8;
- private static final int VAL_BOOLEAN = 9;
- private static final int VAL_CHARSEQUENCE = 10;
- private static final int VAL_LIST = 11;
- private static final int VAL_BYTEARRAY = 13;
- private static final int VAL_STRINGARRAY = 14;
- private static final int VAL_PARCELABLEARRAY = 16;
- private static final int VAL_OBJECTARRAY = 17;
- private static final int VAL_INTARRAY = 18;
- private static final int VAL_LONGARRAY = 19;
- private static final int VAL_BYTE = 20;
- private static final int VAL_BOOLEANARRAY = 23;
- private static final int VAL_CHARSEQUENCEARRAY = 24;
-
- private final ArrayList<Pair<Integer, ?>> parcelData = new ArrayList<Pair<Integer, ?>>();
- private int index = 0;
-
- @RealObject
- private Parcel realParcel;
-
- @Implementation
- public static Parcel obtain() {
- return Robolectric.newInstanceOf(Parcel.class);
- }
-
- @Implementation
- public int dataAvail() {
- return dataSize() - dataPosition();
- }
-
- @Implementation
- public int dataPosition() {
- return calculateSizeToIndex(index);
- }
-
- @Implementation
- public int dataSize() {
- return calculateSizeToIndex(parcelData.size());
- }
-
- @Implementation
- public int dataCapacity() {
- return dataSize();
- }
-
- @Implementation
- public void setDataPosition(int pos) {
- index = calculateIndexFromSizePosition(pos);
- }
-
- private int calculateSizeToIndex(int index) {
- int size = 0;
- for (int i = 0; i < index; i++) {
- size += parcelData.get(i).first;
- }
- return size;
- }
-
- private int calculateIndexFromSizePosition(int pos) {
- int size = 0;
- for (int i = 0; i < parcelData.size(); i++) {
- if (size >= pos) {
- return i;
- }
- size += parcelData.get(i).first;
- }
- return parcelData.size();
- }
-
- @Implementation
- public void writeString(String str) {
- if (str == null) {
- writeInt(-1);
- } else {
- writeInt(str.length());
- addValueToList(Pair.create(str.length(), str));
- }
- }
-
- @Implementation
- public String readString() {
- int N = readInt();
- if (N < 0) {
- return null;
- } else {
- return readValueFromList(null);
- }
- }
-
- @Implementation
- public CharSequence readCharSequence() {
- return TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(realParcel);
- }
-
- @Implementation
- public void writeCharSequence(CharSequence val) {
- TextUtils.writeToParcel(val, realParcel, 0);
- }
-
- @Implementation
- public void writeInt(int i) {
- addValueToList(Pair.create(Integer.SIZE / 8, i));
- }
-
- @Implementation
- public int readInt() {
- return readValueFromList(0);
- }
-
- @Implementation
- public void writeLong(long i) {
- addValueToList(Pair.create(Long.SIZE / 8, i));
- }
-
- @Implementation
- public long readLong() {
- return readValueFromList((long) 0);
- }
-
- @Implementation
- public void writeFloat(float f) {
- addValueToList(Pair.create(Float.SIZE / 8, f));
- }
-
- @Implementation
- public float readFloat() {
- return readValueFromList((float) 0);
- }
-
- @Implementation
- public void writeDouble(double f) {
- addValueToList(Pair.create(Double.SIZE / 8, f));
- }
-
- @Implementation
- public double readDouble() {
- return readValueFromList((double) 0);
- }
-
- public void writeBoolean(boolean b) {
- addValueToList(Pair.create(1, b));
- }
-
- public boolean readBoolean() {
- return readValueFromList(false);
- }
-
- public void writeChar(char c) {
- addValueToList(Pair.create(Character.SIZE / 8, c));
- }
-
- public char readChar() {
- return readValueFromList((char) 0);
- }
-
- @Implementation
- @SuppressWarnings("unchecked")
- public void writeByte(byte b) {
- addValueToList(Pair.create(Byte.SIZE / 8, b));
- }
-
- @Implementation
- public byte readByte() {
- return readValueFromList((byte) 0);
- }
-
- @Implementation
- public void readBooleanArray(boolean[] val) {
- int N = readInt();
- if (val.length != N)
- throw new RuntimeException("bad array lengths");
- for (int i = 0; i < val.length; i++) {
- val[i] = readBoolean();
- }
- }
-
- @Implementation
- public void writeBooleanArray(boolean[] val) {
- if (val == null) {
- writeInt(-1);
- return;
- }
- writeInt(val.length);
- for (boolean b : val)
- writeBoolean(b);
- }
-
- @Implementation
- public boolean[] createBooleanArray() {
- int N = readInt();
- if (N < 0) {
- return null;
- }
- boolean[] val = new boolean[N];
- for (int i = 0; i < val.length; i++) {
- val[i] = readBoolean();
- }
- return val;
- }
-
- @Implementation
- public void readCharArray(char[] val) {
- int N = readInt();
- if (val.length != N)
- throw new RuntimeException("bad array lengths");
- for (int i = 0; i < val.length; i++) {
- val[i] = readChar();
- }
- }
-
- @Implementation
- public void writeCharArray(char[] val) {
- if (val == null) {
- writeInt(-1);
- return;
- }
- writeInt(val.length);
- for (char b : val)
- writeChar(b);
- }
-
- @Implementation
- public char[] createCharArray() {
- int N = readInt();
- if (N < 0) {
- return null;
- }
- char[] val = new char[N];
- for (int i = 0; i < val.length; i++) {
- val[i] = readChar();
- }
- return val;
- }
-
- @Implementation
- public void readFloatArray(float[] val) {
- int N = readInt();
- if (val.length != N)
- throw new RuntimeException("bad array lengths");
- for (int i = 0; i < val.length; i++) {
- val[i] = readFloat();
- }
- }
-
- @Implementation
- public void writeFloatArray(float[] val) {
- if (val == null) {
- writeInt(-1);
- return;
- }
- writeInt(val.length);
- for (float f : val)
- writeFloat(f);
- }
-
- @Implementation
- public float[] createFloatArray() {
- int N = readInt();
- if (N < 0) {
- return null;
- }
- float[] val = new float[N];
- for (int i = 0; i < val.length; i++) {
- val[i] = readFloat();
- }
- return val;
- }
-
- @Implementation
- public void writeDoubleArray(double[] val) {
- if (val == null) {
- writeInt(-1);
- return;
- }
- writeInt(val.length);
- for (double f : val)
- writeDouble(f);
- }
-
- @Implementation
- public void readDoubleArray(double[] val) {
- int N = readInt();
- if (val.length != N)
- throw new RuntimeException("bad array lengths");
- for (int i = 0; i < val.length; i++) {
- val[i] = readDouble();
- }
- }
-
- @Implementation
- public double[] createDoubleArray() {
- int N = readInt();
- if (N < 0) {
- return null;
- }
- double[] val = new double[N];
- for (int i = 0; i < val.length; i++) {
- val[i] = readDouble();
- }
- return val;
- }
-
- @Implementation
- public void writeIntArray(int[] val) {
- if (val == null) {
- writeInt(-1);
- return;
- }
- writeInt(val.length);
- for (int f : val)
- writeInt(f);
- }
-
- @Implementation
- public void readIntArray(int[] val) {
- int N = readInt();
- if (val.length != N)
- throw new RuntimeException("bad array lengths");
- for (int i = 0; i < val.length; i++) {
- val[i] = readInt();
- }
- }
-
- @Implementation
- public int[] createIntArray() {
- int N = readInt();
- if (N < 0) {
- return null;
- }
- int[] val = new int[N];
- for (int i = 0; i < val.length; i++) {
- val[i] = readInt();
- }
- return val;
- }
-
- @Implementation
- public void writeByteArray(byte[] val) {
- if (val == null) {
- writeInt(-1);
- return;
- }
- writeInt(val.length);
- for (byte f : val)
- writeByte(f);
- }
-
- @Implementation
- public void readByteArray(byte[] val) {
- int N = readInt();
- if (val.length != N)
- throw new RuntimeException("bad array lengths");
- for (int i = 0; i < val.length; i++) {
- val[i] = readByte();
- }
- }
-
- @Implementation
- public byte[] createByteArray() {
- int N = readInt();
- if (N < 0) {
- return null;
- }
- byte[] val = new byte[N];
- for (int i = 0; i < val.length; i++) {
- val[i] = readByte();
- }
- return val;
- }
-
- @Implementation
- public void writeLongArray(long[] val) {
- if (val == null) {
- writeInt(-1);
- return;
- }
- writeInt(val.length);
- for (long f : val)
- writeLong(f);
- }
-
- @Implementation
- public void readLongArray(long[] val) {
- int N = readInt();
- if (val.length != N)
- throw new RuntimeException("bad array lengths");
- for (int i = 0; i < val.length; i++) {
- val[i] = readLong();
- }
- }
-
- @Implementation
- public long[] createLongArray() {
- int N = readInt();
- if (N < 0) {
- return null;
- }
- long[] val = new long[N];
- for (int i = 0; i < val.length; i++) {
- val[i] = readLong();
- }
- return val;
- }
-
- @Implementation
- public void writeStringArray(String[] val) {
- if (val == null) {
- writeInt(-1);
- return;
- }
- writeInt(val.length);
- for (String f : val)
- writeString(f);
- }
-
- @Implementation
- public String[] createStringArray() {
- String[] array = null;
-
- int N = readInt();
- if (N >= 0) {
- array = new String[N];
- for (int i = 0; i < N; i++) {
- array[i] = readString();
- }
- }
- return array;
- }
-
- @Implementation
- public void readStringArray(String[] dest) {
- int N = readInt();
- if (dest.length != N)
- throw new RuntimeException("bad array lengths");
- for (int i = 0; i < dest.length; i++) {
- dest[i] = readString();
- }
- }
-
- @Implementation
- public void writeStringList(List<String> strings) {
- if (strings == null) {
- writeInt(-1);
- return;
- }
- int count = strings.size();
- int i = 0;
- writeInt(count);
- while (i < count) {
- writeString(strings.get(i));
- i++;
- }
- }
-
- @Implementation
- public void readStringList(List<String> list) {
- int listSizeBeforeChange = list.size();
- int addCount = readInt();
- int i = 0;
- for (; i < listSizeBeforeChange && i < addCount; i++) {
- list.set(i, readString());
- }
- for (; i < addCount; i++) {
- list.add(readString());
- }
- for (; i < listSizeBeforeChange; i++) {
- list.remove(addCount);
- }
- }
-
- @Implementation
- public ArrayList<String> createStringArrayList() {
- int N = readInt();
- if (N < 0) {
- return null;
- }
-
- ArrayList<String> l = new ArrayList<String>(N);
- while (N > 0) {
- l.add(readString());
- N--;
- }
- return l;
- }
-
- @Implementation
- public void writeCharSequenceArray(CharSequence[] val) {
- if (val != null) {
- int N = val.length;
- writeInt(N);
- for (int i=0; i<N; i++) {
- writeCharSequence(val[i]);
- }
- } else {
- writeInt(-1);
- }
- }
-
- @Implementation
- public CharSequence[] readCharSequenceArray() {
- CharSequence[] array = null;
-
- int length = readInt();
- if (length >= 0)
- {
- array = new CharSequence[length];
-
- for (int i = 0 ; i < length ; i++)
- {
- array[i] = readCharSequence();
- }
- }
-
- return array;
- }
-
- @Implementation
- public void writeList(List val) {
- if (val == null) {
- writeInt(-1);
- return;
- }
- int N = val.size();
- int i = 0;
- writeInt(N);
- while (i < N) {
- writeValue(val.get(i));
- i++;
- }
- }
-
- @Implementation
- public void readList(List outVal, ClassLoader loader) {
- int N = readInt();
- readListInternal(outVal, N, loader);
- }
-
- @Implementation
- public ArrayList readArrayList(ClassLoader loader) {
- int N = readInt();
- if (N < 0) {
- return null;
- }
- ArrayList l = new ArrayList(N);
- readListInternal(l, N, loader);
- return l;
- }
-
- @Implementation
- public void writeArray(Object[] values) {
- if (values == null) {
- writeInt(-1);
- return;
- }
- int N = values.length;
- writeInt(N);
- for (Object value : values) {
- writeValue(value);
- }
- }
-
- @Implementation
- public Object[] readArray(ClassLoader loader) {
- int N = readInt();
- if (N < 0) {
- return null;
- }
- Object[] l = new Object[N];
- readArrayInternal(l, N, loader);
- return l;
- }
-
- @Implementation
- public void writeValue(Object v) {
- if (v == null) {
- writeInt(VAL_NULL);
- } else if (v instanceof String) {
- writeInt(VAL_STRING);
- writeString((String) v);
- } else if (v instanceof Integer) {
- writeInt(VAL_INTEGER);
- writeInt((Integer) v);
- } else if (v instanceof Map) {
- writeInt(VAL_MAP);
- writeMap((Map) v);
- } else if (v instanceof Bundle) {
- // Must be before Parcelable
- writeInt(VAL_BUNDLE);
- writeBundle((Bundle) v);
- } else if (v instanceof Parcelable) {
- writeInt(VAL_PARCELABLE);
- writeParcelable((Parcelable) v, 0);
- } else if (v instanceof Short) {
- writeInt(VAL_SHORT);
- writeInt(((Short) v).intValue());
- } else if (v instanceof Long) {
- writeInt(VAL_LONG);
- writeLong((Long) v);
- } else if (v instanceof Float) {
- writeInt(VAL_FLOAT);
- writeFloat((Float) v);
- } else if (v instanceof Double) {
- writeInt(VAL_DOUBLE);
- writeDouble((Double) v);
- } else if (v instanceof Boolean) {
- writeInt(VAL_BOOLEAN);
- writeInt((Boolean) v ? 1 : 0);
- } else if (v instanceof CharSequence) {
- // Must be after String
- writeInt(VAL_CHARSEQUENCE);
- writeCharSequence((CharSequence) v);
- } else if (v instanceof List) {
- writeInt(VAL_LIST);
- writeList((List) v);
- } else if (v instanceof boolean[]) {
- writeInt(VAL_BOOLEANARRAY);
- writeBooleanArray((boolean[]) v);
- } else if (v instanceof byte[]) {
- writeInt(VAL_BYTEARRAY);
- writeByteArray((byte[]) v);
- } else if (v instanceof String[]) {
- writeInt(VAL_STRINGARRAY);
- writeStringArray((String[]) v);
- } else if (v instanceof CharSequence[]) {
- // Must be after String[] and before Object[]
- writeInt(VAL_CHARSEQUENCEARRAY);
- writeCharSequenceArray((CharSequence[]) v);
- } else if (v instanceof Parcelable[]) {
- writeInt(VAL_PARCELABLEARRAY);
- writeParcelableArray((Parcelable[]) v, 0);
- } else if (v instanceof Object[]) {
- writeInt(VAL_OBJECTARRAY);
- writeArray((Object[]) v);
- } else if (v instanceof int[]) {
- writeInt(VAL_INTARRAY);
- writeIntArray((int[]) v);
- } else if (v instanceof long[]) {
- writeInt(VAL_LONGARRAY);
- writeLongArray((long[]) v);
- } else if (v instanceof Byte) {
- writeInt(VAL_BYTE);
- writeByte((Byte) v);
- } else {
- throw new RuntimeException(
- "Parcel: unable to marshal value with type" + v.getClass().getName());
- }
- }
-
- @Implementation
- public Object readValue(ClassLoader loader) {
- int type = readInt();
-
- switch (type) {
- case VAL_NULL:
- return null;
-
- case VAL_STRING:
- return readString();
-
- case VAL_INTEGER:
- return readInt();
-
- case VAL_MAP:
- return readHashMap(loader);
-
- case VAL_PARCELABLE:
- return readParcelable(loader);
-
- case VAL_SHORT:
- return (short) readInt();
-
- case VAL_LONG:
- return readLong();
-
- case VAL_FLOAT:
- return readFloat();
-
- case VAL_DOUBLE:
- return readDouble();
-
- case VAL_BOOLEAN:
- return readInt() == 1;
-
- case VAL_CHARSEQUENCE:
- return readCharSequence();
-
- case VAL_LIST:
- return readArrayList(loader);
-
- case VAL_BOOLEANARRAY:
- return createBooleanArray();
-
- case VAL_BYTEARRAY:
- return createByteArray();
-
- case VAL_STRINGARRAY:
- return createStringArray();
-
- case VAL_CHARSEQUENCEARRAY:
- return readCharSequenceArray();
-
- case VAL_OBJECTARRAY:
- return readArray(loader);
-
- case VAL_INTARRAY:
- return createIntArray();
-
- case VAL_LONGARRAY:
- return createLongArray();
-
- case VAL_BYTE:
- return readByte();
-
- case VAL_PARCELABLEARRAY:
- return readParcelableArray(loader);
-
- case VAL_BUNDLE:
- return readBundle(loader); // loading will be deferred
-
- default:
- int off = dataPosition() - 4;
- throw new RuntimeException(
- "Parcel " + this + ": Unmarshalling unknown type code " + type
- + " at offset " + off);
- }
- }
-
- @Implementation
- public Bundle readBundle() {
- return readBundle(null);
- }
-
- @Implementation
- public Bundle readBundle(ClassLoader loader) {
- int offset = dataPosition();
- int N = readInt();
- if (N < 0) {
- return null;
- }
- int magic = readInt();
- if (magic != 0x4C444E42) {
- throw new RuntimeException("Magic number missing from bundle stream");
- }
-
- Bundle bundle = new Bundle();
-
- // Read map
- HashMap m = new HashMap();
- readMap(m, null);
-
- shadowOf(bundle).map.putAll(m);
-
- return bundle;
- }
-
- @Implementation
- public void writeBundle(Bundle val) {
- if (val == null) {
- writeInt(-1);
- return;
- }
-
- writeInt(-1); // dummy, will hold length
- int oldPos = dataPosition();
- writeInt(0x4C444E42); // 'B' 'N' 'D' 'L'
-
- writeMapInternal(shadowOf(val).map);
- int newPos = dataPosition();
-
- // Backpatch length
- setDataPosition(oldPos - 4);
- int N = newPos - oldPos;
- writeInt(N);
- setDataPosition(newPos);
- }
-
- @Implementation
- public void writeParcelable(Parcelable p, int flags) {
- if (p == null) {
- writeString(null);
- return;
- }
- String name = p.getClass().getName();
- writeString(name);
- p.writeToParcel(realParcel, flags);
- }
-
- @Implementation
- public <T extends Parcelable> T readParcelable(ClassLoader loader) {
- String name = readString();
- if (name == null) {
- return null;
- }
- Parcelable.Creator<T> creator;
- try {
- Class c = loader == null ? Class.forName(name) : Class.forName(name, true, loader);
- Field f = c.getField("CREATOR");
- creator = (Parcelable.Creator) f.get(null);
- } catch (IllegalAccessException e) {
- Log.e("Parcel", "Class not found when unmarshalling: " + name + ", e: " + e);
- throw new RuntimeException("IllegalAccessException when unmarshalling: " + name);
- } catch (ClassNotFoundException e) {
- Log.e("Parcel", "Class not found when unmarshalling: " + name + ", e: " + e);
- throw new RuntimeException("ClassNotFoundException when unmarshalling: " + name);
- } catch (ClassCastException e) {
- throw new RuntimeException("Parcelable protocol requires a "
- + "Parcelable.Creator object called " + " CREATOR on class " + name);
- } catch (NoSuchFieldException e) {
- throw new RuntimeException("Parcelable protocol requires a "
- + "Parcelable.Creator object called " + " CREATOR on class " + name);
- }
- if (creator == null) {
- throw new RuntimeException("Parcelable protocol requires a "
- + "Parcelable.Creator object called " + " CREATOR on class " + name);
- }
-
- return creator.createFromParcel(realParcel);
- }
-
- @Implementation
- public ArrayList createTypedArrayList(Parcelable.Creator c) {
- int N = readInt();
- if (N < 0) {
- return null;
- }
-
- ArrayList l = new ArrayList(N);
-
- while (N > 0) {
- if (readInt() != 0) {
- l.add(c.createFromParcel(realParcel));
- } else {
- l.add(null);
- }
- N--;
- }
- return l;
- }
-
- @Implementation
- public void writeTypedList(List val) {
- if (val == null) {
- writeInt(-1);
- return;
- }
-
- int N = val.size();
- int i = 0;
- writeInt(N);
- while (i < N) {
- Object item = val.get(i);
- if (item != null) {
- writeInt(1);
- ((Parcelable) item).writeToParcel(realParcel, 0);
- } else {
- writeInt(0);
- }
- i++;
- }
- }
-
- @Implementation
- public <T extends Parcelable> void writeParcelableArray(T[] value,
- int parcelableFlags) {
- if (value != null) {
- int N = value.length;
- writeInt(N);
- for (int i=0; i<N; i++) {
- writeParcelable(value[i], parcelableFlags);
- }
- } else {
- writeInt(-1);
- }
- }
-
- @Implementation
- public Parcelable[] readParcelableArray(ClassLoader loader) {
- int N = readInt();
- if (N < 0) {
- return null;
- }
- Parcelable[] p = new Parcelable[N];
- for (int i = 0; i < N; i++) {
- p[i] = readParcelable(loader);
- }
- return p;
- }
-
- @Implementation
- public void writeMap(Map val) {
- writeMapInternal(val);
- }
-
- @Implementation
- public void readMap(Map outVal, ClassLoader loader) {
- int N = readInt();
- readMapInternal(outVal, N, loader);
- }
-
- @Implementation
- public HashMap readHashMap(ClassLoader loader) {
- int N = readInt();
- if (N < 0) {
- return null;
- }
- HashMap m = new HashMap(N);
- readMapInternal(m, N, loader);
- return m;
- }
-
- private void writeMapInternal(Map<String, Object> val) {
- if (val == null) {
- writeInt(-1);
- return;
- }
-
- Set<Map.Entry<String, Object>> entries = val.entrySet();
- writeInt(entries.size());
- for (Map.Entry<String, Object> e : entries) {
- writeValue(e.getKey());
- writeValue(e.getValue());
- }
- }
-
- private void readMapInternal(Map outVal, int N, ClassLoader loader) {
- for (int i = 0; i < N; i++) {
- Object key = readValue(loader);
- Object value = readValue(loader);
- outVal.put(key, value);
- }
- }
-
- private void readListInternal(List outVal, int N, ClassLoader loader) {
- while (N > 0) {
- Object value = readValue(loader);
- outVal.add(value);
- N--;
- }
- }
-
- private void readArrayInternal(Object[] outVal, int N, ClassLoader loader) {
- for (int i = 0; i < N; i++) {
- Object value = readValue(loader);
- outVal[i] = value;
- }
- }
-
- private void addValueToList(Pair<Integer, ?> value) {
- if (index < parcelData.size()) {
- parcelData.set(index, value);
- } else {
- parcelData.add(value);
- }
- index++;
- }
-
- private <T extends Object> T readValueFromList(T defaultValue) {
- if (index < parcelData.size()) {
- return (T) parcelData.get(index++).second;
- } else {
- return defaultValue;
- }
- }
-
- public int getIndex() {
- return index;
- }
-
- public List getParcelData() {
- return parcelData;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowPasswordTransformationMethod.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowPasswordTransformationMethod.java
deleted file mode 100644
index 69235d577..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowPasswordTransformationMethod.java
+++ /dev/null
@@ -1,37 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.graphics.Rect;
-import android.text.method.PasswordTransformationMethod;
-import android.text.method.TransformationMethod;
-import android.view.View;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-@Implements(PasswordTransformationMethod.class)
-public class ShadowPasswordTransformationMethod implements TransformationMethod {
-
- private static ShadowPasswordTransformationMethod transformationMethod;
-
- @Implementation
- public CharSequence getTransformation(CharSequence charSequence, View view) {
- if(isEmpty(charSequence)) {
- return "";
- }
- return String.format(String.format("%%0%dd", charSequence.length()), 0).replace("0", "\u2022");
- }
-
- @Implementation
- public static ShadowPasswordTransformationMethod getInstance() {
- if(transformationMethod == null){
- transformationMethod = new ShadowPasswordTransformationMethod();
- }
- return transformationMethod;
- }
-
- @Implementation @Override
- public void onFocusChanged(View view, CharSequence charSequence, boolean b, int i, Rect rect) { }
-
- private boolean isEmpty(CharSequence value) {
- return (value == null || value.length() == 0);
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowPath.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowPath.java
deleted file mode 100644
index 3e382565b..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowPath.java
+++ /dev/null
@@ -1,121 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.graphics.Path;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import static com.xtremelabs.robolectric.shadows.ShadowPath.Point.Type.LINE_TO;
-import static com.xtremelabs.robolectric.shadows.ShadowPath.Point.Type.MOVE_TO;
-
-/**
- * Shadow of {@code Path} that contains a simplified implementation of the original class that only supports
- * straight-line {@code Path}s.
- */
-@SuppressWarnings({"UnusedDeclaration"})
-@Implements(Path.class)
-public class ShadowPath {
- private List<Point> points = new ArrayList<Point>();
- private List<Point> pointsMovedTo = new ArrayList<Point>();
- private List<Point> pointsLinedTo = new ArrayList<Point>();
- private Point wasMovedTo;
- private String quadDescription = "";
-
- @Implementation
- public void moveTo(float x, float y) {
- Point p = new Point(x, y, MOVE_TO);
- points.add(p);
- wasMovedTo = p;
- }
-
- @Implementation
- public void lineTo(float x, float y) {
- Point point = new Point(x, y, LINE_TO);
- points.add(point);
- }
-
- @Implementation
- public void quadTo(float x1, float y1, float x2, float y2) {
- quadDescription = "Add a quadratic bezier from last point, approaching (" + x1 + "," + y1 + "), " +
- "ending at (" +x2+","+ y2 + ")";
- }
-
- public String getQuadDescription() {
- return quadDescription;
- }
-
- /**
- * Non-Android accessor.
- *
- * @return all the points that have been added to the {@code Path}
- */
- public List<Point> getPoints() {
- return points;
- }
-
- /**
- * Non-Android accessor.
- *
- * @return whether the {@link #moveTo(float, float)} method was called
- */
- public Point getWasMovedTo() {
- return wasMovedTo;
- }
-
- public static class Point {
- float x, y;
- private Type type;
-
- public enum Type {
- MOVE_TO,
- LINE_TO
- }
-
- public Point(float x, float y, Type type) {
- this.x = x;
- this.y = y;
- this.type = type;
- }
-
- @Override
- public boolean equals(Object o) {
- if (this == o) return true;
- if (!(o instanceof Point)) return false;
-
- Point point = (Point) o;
-
- if (Float.compare(point.x, x) != 0) return false;
- if (Float.compare(point.y, y) != 0) return false;
- if (type != point.type) return false;
-
- return true;
- }
-
- @Override
- public int hashCode() {
- int result = (x != +0.0f ? Float.floatToIntBits(x) : 0);
- result = 31 * result + (y != +0.0f ? Float.floatToIntBits(y) : 0);
- result = 31 * result + (type != null ? type.hashCode() : 0);
- return result;
- }
-
- @Override
- public String toString() {
- return "Point(" + x + "," + y + "," + type + ")";
- }
-
- public float getX() {
- return x;
- }
-
- public float getY() {
- return y;
- }
-
- public Type getType() {
- return type;
- }
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowPatterns.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowPatterns.java
deleted file mode 100644
index 45971eadd..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowPatterns.java
+++ /dev/null
@@ -1,135 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.regex.Pattern;
-
-import android.util.Patterns;
-
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.internal.Implements;
-
-@Implements(Patterns.class)
-public class ShadowPatterns {
-
- public static final String TOP_LEVEL_DOMAIN_STR =
- "((aero|arpa|asia|a[cdefgilmnoqrstuwxz])"
- + "|(biz|b[abdefghijmnorstvwyz])"
- + "|(cat|com|coop|c[acdfghiklmnoruvxyz])"
- + "|d[ejkmoz]"
- + "|(edu|e[cegrstu])"
- + "|f[ijkmor]"
- + "|(gov|g[abdefghilmnpqrstuwy])"
- + "|h[kmnrtu]"
- + "|(info|int|i[delmnoqrst])"
- + "|(jobs|j[emop])"
- + "|k[eghimnprwyz]"
- + "|l[abcikrstuvy]"
- + "|(mil|mobi|museum|m[acdeghklmnopqrstuvwxyz])"
- + "|(name|net|n[acefgilopruz])"
- + "|(org|om)"
- + "|(pro|p[aefghklmnrstwy])"
- + "|qa"
- + "|r[eosuw]"
- + "|s[abcdeghijklmnortuvyz]"
- + "|(tel|travel|t[cdfghjklmnoprtvwz])"
- + "|u[agksyz]"
- + "|v[aceginu]"
- + "|w[fs]"
- + "|(\u03b4\u03bf\u03ba\u03b9\u03bc\u03ae|\u0438\u0441\u043f\u044b\u0442\u0430\u043d\u0438\u0435|\u0440\u0444|\u0441\u0440\u0431|\u05d8\u05e2\u05e1\u05d8|\u0622\u0632\u0645\u0627\u06cc\u0634\u06cc|\u0625\u062e\u062a\u0628\u0627\u0631|\u0627\u0644\u0627\u0631\u062f\u0646|\u0627\u0644\u062c\u0632\u0627\u0626\u0631|\u0627\u0644\u0633\u0639\u0648\u062f\u064a\u0629|\u0627\u0644\u0645\u063a\u0631\u0628|\u0627\u0645\u0627\u0631\u0627\u062a|\u0628\u06be\u0627\u0631\u062a|\u062a\u0648\u0646\u0633|\u0633\u0648\u0631\u064a\u0629|\u0641\u0644\u0633\u0637\u064a\u0646|\u0642\u0637\u0631|\u0645\u0635\u0631|\u092a\u0930\u0940\u0915\u094d\u0937\u093e|\u092d\u093e\u0930\u0924|\u09ad\u09be\u09b0\u09a4|\u0a2d\u0a3e\u0a30\u0a24|\u0aad\u0abe\u0ab0\u0aa4|\u0b87\u0ba8\u0bcd\u0ba4\u0bbf\u0baf\u0bbe|\u0b87\u0bb2\u0b99\u0bcd\u0b95\u0bc8|\u0b9a\u0bbf\u0b99\u0bcd\u0b95\u0baa\u0bcd\u0baa\u0bc2\u0bb0\u0bcd|\u0baa\u0bb0\u0bbf\u0b9f\u0bcd\u0b9a\u0bc8|\u0c2d\u0c3e\u0c30\u0c24\u0c4d|\u0dbd\u0d82\u0d9a\u0dcf|\u0e44\u0e17\u0e22|\u30c6\u30b9\u30c8|\u4e2d\u56fd|\u4e2d\u570b|\u53f0\u6e7e|\u53f0\u7063|\u65b0\u52a0\u5761|\u6d4b\u8bd5|\u6e2c\u8a66|\u9999\u6e2f|\ud14c\uc2a4\ud2b8|\ud55c\uad6d|xn\\-\\-0zwm56d|xn\\-\\-11b5bs3a9aj6g|xn\\-\\-3e0b707e|xn\\-\\-45brj9c|xn\\-\\-80akhbyknj4f|xn\\-\\-90a3ac|xn\\-\\-9t4b11yi5a|xn\\-\\-clchc0ea0b2g2a9gcd|xn\\-\\-deba0ad|xn\\-\\-fiqs8s|xn\\-\\-fiqz9s|xn\\-\\-fpcrj9c3d|xn\\-\\-fzc2c9e2c|xn\\-\\-g6w251d|xn\\-\\-gecrj9c|xn\\-\\-h2brj9c|xn\\-\\-hgbk6aj7f53bba|xn\\-\\-hlcj6aya9esc7a|xn\\-\\-j6w193g|xn\\-\\-jxalpdlp|xn\\-\\-kgbechtv|xn\\-\\-kprw13d|xn\\-\\-kpry57d|xn\\-\\-lgbbat1ad8j|xn\\-\\-mgbaam7a8h|xn\\-\\-mgbayh7gpa|xn\\-\\-mgbbh1a71e|xn\\-\\-mgbc0a9azcg|xn\\-\\-mgberp4a5d4ar|xn\\-\\-o3cw4h|xn\\-\\-ogbpf8fl|xn\\-\\-p1ai|xn\\-\\-pgbs0dh|xn\\-\\-s9brj9c|xn\\-\\-wgbh1c|xn\\-\\-wgbl6a|xn\\-\\-xkc2al3hye2a|xn\\-\\-xkc2dl3a5ee0h|xn\\-\\-yfro4i67o|xn\\-\\-ygbi2ammx|xn\\-\\-zckzah|xxx)"
- + "|y[et]"
- + "|z[amw])";
-
- public static final Pattern TOP_LEVEL_DOMAIN =
- Pattern.compile(TOP_LEVEL_DOMAIN_STR);
-
- public static final String TOP_LEVEL_DOMAIN_STR_FOR_WEB_URL =
- "(?:"
- + "(?:aero|arpa|asia|a[cdefgilmnoqrstuwxz])"
- + "|(?:biz|b[abdefghijmnorstvwyz])"
- + "|(?:cat|com|coop|c[acdfghiklmnoruvxyz])"
- + "|d[ejkmoz]"
- + "|(?:edu|e[cegrstu])"
- + "|f[ijkmor]"
- + "|(?:gov|g[abdefghilmnpqrstuwy])"
- + "|h[kmnrtu]"
- + "|(?:info|int|i[delmnoqrst])"
- + "|(?:jobs|j[emop])"
- + "|k[eghimnprwyz]"
- + "|l[abcikrstuvy]"
- + "|(?:mil|mobi|museum|m[acdeghklmnopqrstuvwxyz])"
- + "|(?:name|net|n[acefgilopruz])"
- + "|(?:org|om)"
- + "|(?:pro|p[aefghklmnrstwy])"
- + "|qa"
- + "|r[eosuw]"
- + "|s[abcdeghijklmnortuvyz]"
- + "|(?:tel|travel|t[cdfghjklmnoprtvwz])"
- + "|u[agksyz]"
- + "|v[aceginu]"
- + "|w[fs]"
- + "|(?:\u03b4\u03bf\u03ba\u03b9\u03bc\u03ae|\u0438\u0441\u043f\u044b\u0442\u0430\u043d\u0438\u0435|\u0440\u0444|\u0441\u0440\u0431|\u05d8\u05e2\u05e1\u05d8|\u0622\u0632\u0645\u0627\u06cc\u0634\u06cc|\u0625\u062e\u062a\u0628\u0627\u0631|\u0627\u0644\u0627\u0631\u062f\u0646|\u0627\u0644\u062c\u0632\u0627\u0626\u0631|\u0627\u0644\u0633\u0639\u0648\u062f\u064a\u0629|\u0627\u0644\u0645\u063a\u0631\u0628|\u0627\u0645\u0627\u0631\u0627\u062a|\u0628\u06be\u0627\u0631\u062a|\u062a\u0648\u0646\u0633|\u0633\u0648\u0631\u064a\u0629|\u0641\u0644\u0633\u0637\u064a\u0646|\u0642\u0637\u0631|\u0645\u0635\u0631|\u092a\u0930\u0940\u0915\u094d\u0937\u093e|\u092d\u093e\u0930\u0924|\u09ad\u09be\u09b0\u09a4|\u0a2d\u0a3e\u0a30\u0a24|\u0aad\u0abe\u0ab0\u0aa4|\u0b87\u0ba8\u0bcd\u0ba4\u0bbf\u0baf\u0bbe|\u0b87\u0bb2\u0b99\u0bcd\u0b95\u0bc8|\u0b9a\u0bbf\u0b99\u0bcd\u0b95\u0baa\u0bcd\u0baa\u0bc2\u0bb0\u0bcd|\u0baa\u0bb0\u0bbf\u0b9f\u0bcd\u0b9a\u0bc8|\u0c2d\u0c3e\u0c30\u0c24\u0c4d|\u0dbd\u0d82\u0d9a\u0dcf|\u0e44\u0e17\u0e22|\u30c6\u30b9\u30c8|\u4e2d\u56fd|\u4e2d\u570b|\u53f0\u6e7e|\u53f0\u7063|\u65b0\u52a0\u5761|\u6d4b\u8bd5|\u6e2c\u8a66|\u9999\u6e2f|\ud14c\uc2a4\ud2b8|\ud55c\uad6d|xn\\-\\-0zwm56d|xn\\-\\-11b5bs3a9aj6g|xn\\-\\-3e0b707e|xn\\-\\-45brj9c|xn\\-\\-80akhbyknj4f|xn\\-\\-90a3ac|xn\\-\\-9t4b11yi5a|xn\\-\\-clchc0ea0b2g2a9gcd|xn\\-\\-deba0ad|xn\\-\\-fiqs8s|xn\\-\\-fiqz9s|xn\\-\\-fpcrj9c3d|xn\\-\\-fzc2c9e2c|xn\\-\\-g6w251d|xn\\-\\-gecrj9c|xn\\-\\-h2brj9c|xn\\-\\-hgbk6aj7f53bba|xn\\-\\-hlcj6aya9esc7a|xn\\-\\-j6w193g|xn\\-\\-jxalpdlp|xn\\-\\-kgbechtv|xn\\-\\-kprw13d|xn\\-\\-kpry57d|xn\\-\\-lgbbat1ad8j|xn\\-\\-mgbaam7a8h|xn\\-\\-mgbayh7gpa|xn\\-\\-mgbbh1a71e|xn\\-\\-mgbc0a9azcg|xn\\-\\-mgberp4a5d4ar|xn\\-\\-o3cw4h|xn\\-\\-ogbpf8fl|xn\\-\\-p1ai|xn\\-\\-pgbs0dh|xn\\-\\-s9brj9c|xn\\-\\-wgbh1c|xn\\-\\-wgbl6a|xn\\-\\-xkc2al3hye2a|xn\\-\\-xkc2dl3a5ee0h|xn\\-\\-yfro4i67o|xn\\-\\-ygbi2ammx|xn\\-\\-zckzah|xxx)"
- + "|y[et]"
- + "|z[amw]))";
-
- public static final String GOOD_IRI_CHAR =
- "a-zA-Z0-9\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF";
-
- public static final Pattern WEB_URL = Pattern.compile(
- "((?:(http|https|Http|Https|rtsp|Rtsp):\\/\\/(?:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)"
- + "\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,64}(?:\\:(?:[a-zA-Z0-9\\$\\-\\_"
- + "\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,25})?\\@)?)?"
- + "((?:(?:[" + GOOD_IRI_CHAR + "][" + GOOD_IRI_CHAR + "\\-]{0,64}\\.)+" // named host
- + TOP_LEVEL_DOMAIN_STR_FOR_WEB_URL
- + "|(?:(?:25[0-5]|2[0-4]" // or ip address
- + "[0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\.(?:25[0-5]|2[0-4][0-9]"
- + "|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(?:25[0-5]|2[0-4][0-9]|[0-1]"
- + "[0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(?:25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}"
- + "|[1-9][0-9]|[0-9])))"
- + "(?:\\:\\d{1,5})?)" // plus option port number
- + "(\\/(?:(?:[" + GOOD_IRI_CHAR + "\\;\\/\\?\\:\\@\\&\\=\\#\\~" // plus option query params
- + "\\-\\.\\+\\!\\*\\'\\(\\)\\,\\_])|(?:\\%[a-fA-F0-9]{2}))*)?"
- + "(?:\\b|$)"); // and finally, a word boundary or end of
- // input. This is to stop foo.sure from
- // matching as foo.su
-
- public static final Pattern IP_ADDRESS
- = Pattern.compile(
- "((25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\.(25[0-5]|2[0-4]"
- + "[0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1]"
- + "[0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}"
- + "|[1-9][0-9]|[0-9]))");
-
- public static final Pattern DOMAIN_NAME
- = Pattern.compile(
- "(((([" + GOOD_IRI_CHAR + "][" + GOOD_IRI_CHAR + "\\-]*)*[" + GOOD_IRI_CHAR + "]\\.)+"
- + TOP_LEVEL_DOMAIN + ")|"
- + IP_ADDRESS + ")");
-
- public static final Pattern EMAIL_ADDRESS
- = Pattern.compile(
- "[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}" +
- "\\@" +
- "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" +
- "(" +
- "\\." +
- "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" +
- ")+"
- );
-
- public static final Pattern PHONE
- = Pattern.compile( // sdd = space, dot, or dash
- "(\\+[0-9]+[\\- \\.]*)?" // +<digits><sdd>*
- + "(\\([0-9]+\\)[\\- \\.]*)?" // (<digits>)<sdd>*
- + "([0-9][0-9\\- \\.]+[0-9])"); // <digit><digit|sdd>+<digit>
-
- public static void reset() {
- Robolectric.Reflection.setFinalStaticField(Patterns.class, "DOMAIN_NAME", DOMAIN_NAME);
- Robolectric.Reflection.setFinalStaticField(Patterns.class, "EMAIL_ADDRESS", EMAIL_ADDRESS);
- Robolectric.Reflection.setFinalStaticField(Patterns.class, "IP_ADDRESS", IP_ADDRESS);
- Robolectric.Reflection.setFinalStaticField(Patterns.class, "PHONE", PHONE);
- Robolectric.Reflection.setFinalStaticField(Patterns.class, "TOP_LEVEL_DOMAIN",
- TOP_LEVEL_DOMAIN);
- Robolectric.Reflection.setFinalStaticField(Patterns.class, "WEB_URL", WEB_URL);
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowPendingIntent.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowPendingIntent.java
deleted file mode 100644
index 3df65a7d6..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowPendingIntent.java
+++ /dev/null
@@ -1,198 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.app.PendingIntent;
-import android.app.PendingIntent.CanceledException;
-import android.content.Context;
-import android.content.Intent;
-import android.content.IntentSender;
-import android.content.TestIntentSender;
-import android.os.Parcel;
-
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-/**
- * Shadow of {@code PendingIntent} that creates and sends {@code Intent}s appropriately.
- */
-@Implements(PendingIntent.class)
-public class ShadowPendingIntent {
- private Intent savedIntent;
- private Context savedContext;
- private boolean isActivityIntent;
- private boolean isBroadcastIntent;
- private boolean isServiceIntent;
- private int requestCode;
-
- @Implementation
- public static PendingIntent getActivity(Context context, int requestCode, Intent intent, int flags) {
- return create(context, intent, true, false, false, requestCode);
- }
-
- @Implementation
- public static PendingIntent getBroadcast(Context context, int requestCode, Intent intent, int flags) {
- return create(context, intent, false, true, false, requestCode);
- }
-
- @Implementation
- public static PendingIntent getService(Context context, int requestCode, Intent intent, int flags) {
- return create(context, intent, false, false, true, requestCode);
- }
-
- @Implementation
- public void send() throws CanceledException {
- send(savedContext, 0, savedIntent);
- }
-
- @Implementation
- public void send(Context context, int code, Intent intent) throws CanceledException {
- savedIntent.fillIn(intent, 0 );
- if (isActivityIntent) {
- context.startActivity(savedIntent);
- } else if (isBroadcastIntent) {
- context.sendBroadcast(savedIntent);
- } else if (isServiceIntent) {
- context.startService(savedIntent);
- }
- }
-
- @Implementation
- public IntentSender getIntentSender() {
- TestIntentSender testIntentSender = new TestIntentSender();
- testIntentSender.intent = savedIntent;
- return testIntentSender;
- }
-
- @Implementation
- public static void writePendingIntentOrNullToParcel(PendingIntent sender, Parcel out) {
- if (sender == null) {
- out.writeInt(0);
- return;
- }
- sender.writeToParcel(out, 0);
- }
-
- @Implementation
- public static PendingIntent readPendingIntentOrNullFromParcel(Parcel in) {
- if (in.readInt() == 0) {
- return null;
- }
- boolean isActivity = readBooleanFromParcel(in);
- boolean isBroadcast = readBooleanFromParcel(in);
- boolean isService = readBooleanFromParcel(in);
- int requestCode = in.readInt();
- Intent intent = null;
- if (in.readInt() != 0) {
- intent = new Intent();
- intent.readFromParcel(in);
- }
- return create(null, intent, isActivity, isBroadcast, isService, requestCode);
- }
-
- @Implementation
- public void writeToParcel(Parcel out, int flags) {
- out.writeInt(1);
- writeBooleanToParcel(isActivityIntent, out);
- writeBooleanToParcel(isBroadcastIntent, out);
- writeBooleanToParcel(isServiceIntent, out);
- out.writeInt(requestCode);
- if (savedIntent != null) {
- out.writeInt(1);
- savedIntent.writeToParcel(out, flags);
- } else {
- out.writeInt(0);
- }
- }
-
- @Override
- @Implementation
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + (isActivityIntent ? 1231 : 1237);
- result = prime * result + (isBroadcastIntent ? 1231 : 1237);
- result = prime * result + (isServiceIntent ? 1231 : 1237);
- result = prime * result + requestCode;
- result = prime * result + ((savedIntent == null) ? 0 : savedIntent.hashCode());
- return result;
- }
-
- @Override
- @Implementation
- public boolean equals(Object obj) {
- if (obj == null) {
- return false;
- }
- if (obj instanceof PendingIntent) {
- return shadowEquals(Robolectric.shadowOf((PendingIntent) obj));
- }
- return false;
- }
-
- private boolean shadowEquals(ShadowPendingIntent other) {
- if (isActivityIntent != other.isActivityIntent) {
- return false;
- }
- if (isBroadcastIntent != other.isBroadcastIntent) {
- return false;
- }
- if (isServiceIntent != other.isServiceIntent) {
- return false;
- }
- if (requestCode != other.requestCode) {
- return false;
- }
- if (savedIntent == null) {
- if (other.savedIntent != null) {
- return false;
- }
- } else if (!savedIntent.equals(other.savedIntent)) {
- return false;
- }
- return true;
- }
-
- public boolean isActivityIntent() {
- return isActivityIntent;
- }
-
- public boolean isBroadcastIntent() {
- return isBroadcastIntent;
- }
-
- public boolean isServiceIntent() {
- return isServiceIntent;
- }
-
- public Context getSavedContext() {
- return savedContext;
- }
-
- public Intent getSavedIntent() {
- return savedIntent;
- }
-
- public int getRequestCode() {
- return requestCode;
- }
-
- private static PendingIntent create(Context context, Intent intent, boolean isActivity, boolean isBroadcast, boolean isService, int requestCode) {
- PendingIntent pendingIntent = Robolectric.newInstanceOf(PendingIntent.class);
- ShadowPendingIntent shadowPendingIntent = Robolectric.shadowOf(pendingIntent);
- shadowPendingIntent.savedIntent = intent;
- shadowPendingIntent.isActivityIntent = isActivity;
- shadowPendingIntent.isBroadcastIntent = isBroadcast;
- shadowPendingIntent.isServiceIntent = isService;
- shadowPendingIntent.savedContext = context;
- shadowPendingIntent.requestCode = requestCode;
- return pendingIntent;
- }
-
- private static void writeBooleanToParcel(boolean b, Parcel out) {
- out.writeInt(b ? 1 : 0);
- }
-
- private static boolean readBooleanFromParcel(Parcel in) {
- return in.readInt() != 0;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowPeriodicSync.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowPeriodicSync.java
deleted file mode 100644
index 2bcd5b059..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowPeriodicSync.java
+++ /dev/null
@@ -1,30 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.accounts.Account;
-import android.content.PeriodicSync;
-import android.os.Bundle;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.internal.RealObject;
-
-import java.lang.reflect.Field;
-
-@Implements(PeriodicSync.class)
-public class ShadowPeriodicSync {
-
- @RealObject
- private PeriodicSync realObject;
-
- public void __constructor__(Account account, String authority, Bundle extras, long period) throws Exception {
- setField("account", account);
- setField("authority", authority);
- setField("period", period);
- setField("extras", extras);
- }
-
-
- private void setField(String name, Object obj) throws Exception {
- Field f = realObject.getClass().getField(name);
- f.setAccessible(true);
- f.set(realObject, obj);
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowPhoneNumberUtils.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowPhoneNumberUtils.java
deleted file mode 100644
index 5cfc5f9ad..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowPhoneNumberUtils.java
+++ /dev/null
@@ -1,19 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.telephony.PhoneNumberUtils;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-@Implements(PhoneNumberUtils.class)
-public class ShadowPhoneNumberUtils {
-
- @Implementation
- public static java.lang.String formatNumber(java.lang.String source) {
- return source + "-formatted";
- }
-
- @Implementation
- public static java.lang.String stripSeparators(java.lang.String source) {
- return source + "-stripped";
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowPoint.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowPoint.java
deleted file mode 100644
index 7c265939d..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowPoint.java
+++ /dev/null
@@ -1,80 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.graphics.Point;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.internal.RealObject;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf_;
-
-/**
- * Shadow implementation of {@code Point}
- */
-@Implements(Point.class)
-public class ShadowPoint {
- @RealObject private Point realPoint;
-
- public void __constructor__(int x, int y) {
- realPoint.x = x;
- realPoint.y = y;
- }
-
- public void __constructor__(Point src) {
- realPoint.x = src.x;
- realPoint.y = src.y;
- }
-
- @Implementation
- public void set(int x, int y) {
- realPoint.x = x;
- realPoint.y = y;
- }
-
- @Implementation
- public final void negate() {
- realPoint.x = -realPoint.x;
- realPoint.y = -realPoint.y;
- }
-
- @Implementation
- public final void offset(int dx, int dy) {
- realPoint.x += dx;
- realPoint.y += dy;
- }
-
- @Override @Implementation
- public boolean equals(Object object) {
- if (object == null) return false;
- Object o = shadowOf_(object);
- if (o == null) return false;
- if (this == o) return true;
- if (getClass() != o.getClass()) return false;
-
- ShadowPoint that = (ShadowPoint) o;
- if (this.realPoint.x == that.realPoint.x && this.realPoint.y == that.realPoint.y) return true;
-
- return false;
- }
-
- @Override @Implementation
- public int hashCode() {
- return realPoint.x * 32713 + realPoint.y;
- }
-
- @Override @Implementation
- public String toString() {
- return "Point(" + realPoint.x + ", " + realPoint.y + ")";
- }
-
- /**
- * Non-Android utility method for comparing a point to a well-known value
- *
- * @param x x
- * @param y y
- * @return this.x == x && this.y == y
- */
- @Implementation
- public final boolean equals(int x, int y) {
- return realPoint.x == x && realPoint.y == y;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowPointF.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowPointF.java
deleted file mode 100644
index 38dd7416f..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowPointF.java
+++ /dev/null
@@ -1,82 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.graphics.Point;
-import android.graphics.PointF;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.internal.RealObject;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf_;
-
-/**
- * Shadow implementation of {@code Point}
- */
-@SuppressWarnings({"UnusedDeclaration"})
-@Implements(PointF.class)
-public class ShadowPointF {
- @RealObject private PointF realPointF;
-
- public void __constructor__(float x, float y) {
- realPointF.x = x;
- realPointF.y = y;
- }
-
- public void __constructor__(Point src) {
- realPointF.x = src.x;
- realPointF.y = src.y;
- }
-
- @Implementation
- public void set(float x, float y) {
- realPointF.x = x;
- realPointF.y = y;
- }
-
- @Implementation
- public final void negate() {
- realPointF.x = -realPointF.x;
- realPointF.y = -realPointF.y;
- }
-
- @Implementation
- public final void offset(float dx, float dy) {
- realPointF.x += dx;
- realPointF.y += dy;
- }
-
- @Override @Implementation
- public boolean equals(Object object) {
- if (object == null) return false;
- Object o = shadowOf_(object);
- if (o == null) return false;
- if (this == o) return true;
- if (getClass() != o.getClass()) return false;
-
- ShadowPointF that = (ShadowPointF) o;
- if (this.realPointF.x == that.realPointF.x && this.realPointF.y == that.realPointF.y) return true;
-
- return false;
- }
-
- @Override @Implementation
- public int hashCode() {
- return (int) (realPointF.x * 32713 + realPointF.y);
- }
-
- @Override @Implementation
- public String toString() {
- return "Point(" + realPointF.x + ", " + realPointF.y + ")";
- }
-
- /**
- * Non-Android utility method for comparing a point to a well-known value
- *
- * @param x x
- * @param y y
- * @return this.x == x && this.y == y
- */
- @Implementation
- public final boolean equals(float x, float y) {
- return realPointF.x == x && realPointF.y == y;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowPopupWindow.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowPopupWindow.java
deleted file mode 100644
index b3c378414..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowPopupWindow.java
+++ /dev/null
@@ -1,173 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.content.Context;
-import android.graphics.drawable.Drawable;
-import android.view.MotionEvent;
-import android.view.View;
-import android.view.WindowManager;
-import android.widget.LinearLayout;
-import android.widget.PopupWindow;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.internal.RealObject;
-
-@SuppressWarnings({"UnusedDeclaration"})
-@Implements(PopupWindow.class)
-public class ShadowPopupWindow {
- @RealObject
- protected PopupWindow realPopupWindow;
- private View contentView;
- private int width;
- private int height;
- private boolean focusable;
- private boolean touchable;
- private boolean outSideTouchable;
- private boolean showing;
- private Drawable background;
- private View.OnTouchListener onTouchInterceptor;
- private Context context;
- private LinearLayout containerView;
- private int xOffset;
- private int yOffset;
-
- public void __constructor__(View contentView) {
- setContentView(contentView);
- getWindowManager();
- }
-
- public void __constructor__(View contentView, int width, int height, boolean focusable) {
- __constructor__(contentView);
- this.width = width;
- this.height = height;
- this.focusable = focusable;
- }
-
- @Implementation
- public void setContentView(View contentView) {
- this.contentView = contentView;
- context = contentView.getContext();
- }
-
- @Implementation
- public View getContentView() {
- return contentView;
- }
-
- @Implementation
- public void setWidth(int width) {
- this.width = width;
- }
-
- @Implementation
- public int getWidth() {
- return width;
- }
-
- @Implementation
- public void setHeight(int height) {
- this.height = height;
- }
-
- @Implementation
- public int getHeight() {
- return height;
- }
-
- @Implementation
- public void setFocusable(boolean focusable) {
- this.focusable = focusable;
- }
-
- @Implementation
- public boolean isFocusable() {
- return focusable;
- }
-
- @Implementation
- public void setTouchable(boolean touchable) {
- this.touchable = touchable;
- }
-
- @Implementation
- public boolean isTouchable() {
- return touchable;
- }
-
- @Implementation
- public void setOutsideTouchable(boolean touchable) {
- outSideTouchable = touchable;
- }
-
- @Implementation
- public boolean isOutsideTouchable() {
- return outSideTouchable;
- }
-
- /**
- * non-android setter for testing
- *
- * @param showing true if popup window is showing
- */
- public void setShowing(boolean showing) {
- this.showing = showing;
- }
-
- @Implementation
- public boolean isShowing() {
- return showing;
- }
-
- @Implementation
- public void dismiss() {
- if (context != null) {
- getWindowManager().removeView(containerView);
- }
- showing = false;
- }
-
- @Implementation
- public void setBackgroundDrawable(Drawable background) {
- this.background = background;
- }
-
- @Implementation
- public Drawable getBackground() {
- return background;
- }
-
- @Implementation
- public void setTouchInterceptor(android.view.View.OnTouchListener l) {
- onTouchInterceptor = l;
- }
-
- @Implementation
- public void showAsDropDown(View anchor) {
- containerView = new LinearLayout(context);
- containerView.addView(contentView);
- containerView.setBackgroundDrawable(background);
- getWindowManager().addView(containerView, null);
- }
-
- @Implementation
- public void showAsDropDown(View anchor, int xoff, int yoff) {
- xOffset = xoff;
- yOffset = yoff;
- showAsDropDown(anchor);
- }
-
- public boolean dispatchTouchEvent(MotionEvent e) {
- return onTouchInterceptor != null && onTouchInterceptor.onTouch(realPopupWindow.getContentView(), e);
- }
-
- private WindowManager getWindowManager() {
- return (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
- }
-
- public int getXOffset() {
- return xOffset;
- }
-
- public int getYOffset() {
- return yOffset;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowPowerManager.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowPowerManager.java
deleted file mode 100644
index cc72a7f38..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowPowerManager.java
+++ /dev/null
@@ -1,70 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.os.PowerManager;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-/**
- * Shadows the {@code android.os.PowerManager} class.
- */
-@Implements(PowerManager.class)
-public class ShadowPowerManager {
-
- private boolean isScreenOn = true;
-
- @Implementation
- public PowerManager.WakeLock newWakeLock(int flags, String tag) {
- return Robolectric.newInstanceOf(PowerManager.WakeLock.class);
- }
-
- @Implementation
- public boolean isScreenOn() {
- return isScreenOn;
- }
-
- public void setIsScreenOn(boolean screenOn) {
- isScreenOn = screenOn;
- }
-
- @Implements(PowerManager.WakeLock.class)
- public static class ShadowWakeLock {
- private boolean refCounted = true;
- private int refCount;
- private boolean locked;
-
- @Implementation
- public void acquire() {
- acquire(0);
-
- }
-
- @Implementation
- public synchronized void acquire(long timeout) {
- if (refCounted) {
- refCount++;
- } else {
- locked = true;
- }
- }
-
- @Implementation
- public synchronized void release() {
- if (refCounted) {
- if (--refCount < 0) throw new RuntimeException("WakeLock under-locked");
- } else {
- locked = false;
- }
- }
-
- @Implementation
- public synchronized boolean isHeld() {
- return refCounted ? refCount > 0 : locked;
- }
-
- @Implementation
- public void setReferenceCounted(boolean value) {
- refCounted = value;
- }
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowPreference.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowPreference.java
deleted file mode 100644
index b68e50e35..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowPreference.java
+++ /dev/null
@@ -1,205 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.content.Context;
-import android.content.Intent;
-import android.preference.Preference;
-import android.util.AttributeSet;
-
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.internal.RealObject;
-
-@Implements(Preference.class)
-public class ShadowPreference {
-
- @RealObject private Preference realPreference;
-
- protected Context context;
- protected AttributeSet attrs;
- protected int defStyle;
-
- protected String key;
- protected CharSequence title;
- protected CharSequence summary;
- protected Object defaultValue;
- protected int order;
- protected boolean enabled = true;
- protected String dependencyKey;
- protected boolean persistent = false;
- protected int persistedInt;
- protected Object callChangeListenerValue = null;
-
- protected Preference.OnPreferenceClickListener onClickListener;
- private Intent intent;
-
- public void __constructor__(Context context) {
- __constructor__(context, null, 0);
- }
-
- public void __constructor__(Context context, AttributeSet attributeSet) {
- __constructor__(context, attributeSet, 0);
- }
-
- public void __constructor__(Context context, AttributeSet attributeSet, int defStyle) {
- this.context = context;
- this.attrs = attributeSet;
- this.defStyle = defStyle;
-
- if (attributeSet != null) {
- key = attributeSet.getAttributeValue("android", "key");
- }
- }
-
- @Implementation
- public Context getContext() {
- return context;
- }
-
- public AttributeSet getAttrs() {
- return attrs;
- }
-
- public int getDefStyle() {
- return defStyle;
- }
-
- @Implementation
- public void setEnabled(boolean enabled) {
- this.enabled = enabled;
- }
-
- @Implementation
- public boolean isEnabled() {
- return enabled;
- }
-
- @Implementation
- public boolean shouldPersist() {
- return persistent;
- }
-
- @Implementation
- public boolean isPersistent() {
- return persistent;
- }
-
- @Implementation
- public void setPersistent(boolean persistent) {
- this.persistent = persistent;
- }
-
- @Implementation
- public int getPersistedInt(int defaultReturnValue) {
- return persistent ? persistedInt : defaultReturnValue;
- }
-
- @Implementation
- public boolean persistInt(int value) {
- this.persistedInt = value;
- return persistent;
- }
-
- @Implementation
- public boolean callChangeListener(Object newValue) {
- callChangeListenerValue = newValue;
- return true;
- }
-
- public Object getCallChangeListenerValue() {
- return callChangeListenerValue;
- }
-
- @Implementation
- public void setSummary(int summaryResId) {
- this.summary = context.getResources().getText(summaryResId);
- }
-
- @Implementation
- public void setSummary(CharSequence summary) {
- this.summary = summary;
- }
-
- @Implementation
- public CharSequence getSummary() {
- return summary;
- }
-
- @Implementation
- public void setTitle(int titleResId) {
- this.title = context.getResources().getText(titleResId);
- }
-
- @Implementation
- public void setTitle(CharSequence title) {
- this.title = title;
- }
-
- @Implementation
- public CharSequence getTitle() {
- return title;
- }
-
- @Implementation
- public void setKey(String key) {
- this.key = key;
- }
-
- @Implementation
- public String getKey() {
- return key;
- }
-
- @Implementation
- public void setDefaultValue(Object defaultValue) {
- this.defaultValue = defaultValue;
- }
-
- public Object getDefaultValue() {
- return defaultValue;
- }
-
- @Implementation
- public int getOrder() {
- return order;
- }
-
- @Implementation
- public void setOrder(int order) {
- this.order = order;
- }
-
- @Implementation
- public void setOnPreferenceClickListener( Preference.OnPreferenceClickListener onPreferenceClickListener ) {
- this.onClickListener = onPreferenceClickListener;
- }
-
- @Implementation
- public Preference.OnPreferenceClickListener getOnPreferenceClickListener() {
- return onClickListener;
- }
-
- public boolean click() {
- return onClickListener.onPreferenceClick(realPreference);
- }
-
- @Implementation
- public void setIntent(Intent i) {
- this.intent = i;
- }
-
- @Implementation
- public Intent getIntent() {
- return this.intent;
-
- }
-
- @Implementation
- public void setDependency(String dependencyKey) {
- this.dependencyKey = dependencyKey;
- }
-
- @Implementation
- public String getDependency() {
- return this.dependencyKey;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowPreferenceActivity.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowPreferenceActivity.java
deleted file mode 100644
index 44bd0cf59..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowPreferenceActivity.java
+++ /dev/null
@@ -1,30 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.preference.PreferenceActivity;
-import android.preference.PreferenceScreen;
-import android.widget.ListView;
-
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-@Implements(PreferenceActivity.class)
-public class ShadowPreferenceActivity extends ShadowListActivity {
-
- private int preferencesResId = -1;
- private PreferenceScreen preferenceScreen;
-
- @Implementation
- public void addPreferencesFromResource(int preferencesResId) {
- this.preferencesResId = preferencesResId;
- preferenceScreen = getResourceLoader().inflatePreferences(getApplicationContext(), preferencesResId);
- }
-
- public int getPreferencesResId() {
- return preferencesResId;
- }
-
- @Implementation
- public PreferenceScreen getPreferenceScreen() {
- return preferenceScreen;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowPreferenceCategory.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowPreferenceCategory.java
deleted file mode 100644
index e1bc8f425..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowPreferenceCategory.java
+++ /dev/null
@@ -1,10 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.preference.PreferenceCategory;
-
-import com.xtremelabs.robolectric.internal.Implements;
-
-@Implements(PreferenceCategory.class)
-public class ShadowPreferenceCategory extends ShadowPreferenceGroup {
-
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowPreferenceGroup.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowPreferenceGroup.java
deleted file mode 100644
index 90664ec2f..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowPreferenceGroup.java
+++ /dev/null
@@ -1,103 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import java.util.ArrayList;
-
-import android.preference.Preference;
-import android.preference.PreferenceGroup;
-import android.text.TextUtils;
-
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.internal.RealObject;
-
-/**
- * See: http://android.git.kernel.org/?p=platform/frameworks/base.git;a=blob_plain;f=core/java/android/preference/PreferenceGroup.java;hb=HEAD
- */
-@Implements(PreferenceGroup.class)
-public class ShadowPreferenceGroup extends ShadowPreference {
-
- @RealObject private PreferenceGroup realPreferenceGroup;
-
- private ArrayList<Preference> preferenceList = new ArrayList<Preference>();
-
- @Implementation
- public void addItemFromInflater(Preference preference) {
- addPreference(preference);
- }
-
- @Implementation
- public boolean addPreference(Preference preference) {
- if (preferenceList.contains(preference)) {
- return true;
- }
-
- // TODO currently punting on ordering logic
- preferenceList.add(preference);
-
- return true;
- }
-
- @Implementation
- public Preference getPreference(int index) {
- return preferenceList.get(index);
- }
-
- @Implementation
- public int getPreferenceCount() {
- return preferenceList.size();
- }
-
- @Implementation
- public boolean removePreference(Preference preference) {
- return preferenceList.remove(preference);
- }
-
- @Implementation
- public void removeAll() {
- preferenceList.clear();
- }
-
- /**
- * Note: copied wholesale from Android source
- * @param key
- * @return
- */
- @Implementation
- public Preference findPreference(CharSequence key) {
- if (TextUtils.equals(getKey(), key)) {
- return realPreferenceGroup;
- }
- final int preferenceCount = getPreferenceCount();
- for (int i = 0; i < preferenceCount; i++) {
- final Preference preference = getPreference(i);
- final String curKey = preference.getKey();
-
- if (curKey != null && curKey.equals(key)) {
- return preference;
- }
-
- if (preference instanceof PreferenceGroup) {
- final Preference returnedPreference = ((PreferenceGroup)preference)
- .findPreference(key);
- if (returnedPreference != null) {
- return returnedPreference;
- }
- }
- }
-
- return null;
- }
-
- /**
- * Note: copied wholesale from Android source
- */
- @Implementation
- public void setEnabled(boolean enabled) {
- super.setEnabled(enabled);
-
- final int preferenceCount = getPreferenceCount();
- for (int i = 0; i < preferenceCount; i++) {
- getPreference(i).setEnabled(enabled);
- }
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowPreferenceManager.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowPreferenceManager.java
deleted file mode 100644
index 21e2aed03..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowPreferenceManager.java
+++ /dev/null
@@ -1,25 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.app.Application;
-import android.content.Context;
-import android.content.SharedPreferences;
-import android.preference.PreferenceManager;
-import com.xtremelabs.robolectric.tester.android.content.TestSharedPreferences;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-
-/**
- * Shadow for {@code PreferenceManager} that returns instances of the {@link com.xtremelabs.robolectric.tester.android.content.TestSharedPreferences} utility class
- */
-@Implements(PreferenceManager.class)
-public class ShadowPreferenceManager {
-
- @Implementation
- public static SharedPreferences getDefaultSharedPreferences(Context context) {
- ShadowApplication shadowApplication = shadowOf((Application) context.getApplicationContext());
- return new TestSharedPreferences(shadowApplication.getSharedPreferenceMap(), "__default__", Context.MODE_PRIVATE);
- }
-
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowPreferenceScreen.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowPreferenceScreen.java
deleted file mode 100644
index 4cbefdd7e..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowPreferenceScreen.java
+++ /dev/null
@@ -1,22 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.app.Dialog;
-import android.preference.PreferenceScreen;
-
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-@Implements(PreferenceScreen.class)
-public class ShadowPreferenceScreen extends ShadowPreferenceGroup {
-
- private Dialog dialog;
-
- @Implementation
- public Dialog getDialog() {
- return dialog;
- }
-
- public void setDialog(Dialog dialog) {
- this.dialog = dialog;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowProcess.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowProcess.java
deleted file mode 100644
index be0cf7785..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowProcess.java
+++ /dev/null
@@ -1,26 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-@Implements(android.os.Process.class)
-public class ShadowProcess {
-
- private static Integer pid;
-
- @Implementation
- public static final int myPid() {
- if (pid != null) {
- return pid;
- }
- return 0;
- }
-
- public static void setPid(int pid) {
- ShadowProcess.pid = pid;
- }
-
- public static void reset() {
- ShadowProcess.pid = null;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowProgressBar.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowProgressBar.java
deleted file mode 100644
index b1783017b..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowProgressBar.java
+++ /dev/null
@@ -1,78 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-import android.widget.ProgressBar;
-
-@Implements(ProgressBar.class)
-public class ShadowProgressBar extends ShadowView {
-
- private int progress;
- private int secondaryProgress;
- private int max = 100;
- private boolean isIndeterminate;
-
- @Override
- public void applyAttributes() {
- super.applyAttributes();
-
- final int max = attributeSet.getAttributeIntValue("android", "max", this.max);
-
- if (max >= 0)
- setMax(max);
- }
-
- @Implementation
- public void setMax(int max) {
- this.max = max;
- if (progress > max) {
- progress = max;
- }
- }
-
- @Implementation
- public int getMax() {
- return max;
- }
-
- @Implementation
- public void setProgress(int progress) {
- if (!isIndeterminate()) this.progress = Math.min(max, progress);
- }
-
- @Implementation
- public int getProgress() {
- return isIndeterminate ? 0 : progress;
- }
-
- @Implementation
- public void setSecondaryProgress(int secondaryProgress) {
- if (!isIndeterminate()) this.secondaryProgress = Math.min(max, secondaryProgress);
- }
-
- @Implementation
- public int getSecondaryProgress() {
- return isIndeterminate ? 0 : secondaryProgress;
- }
-
- @Implementation
- public void setIndeterminate(boolean indeterminate) {
- this.isIndeterminate = indeterminate;
- }
-
- @Implementation
- public boolean isIndeterminate() {
- return isIndeterminate;
- }
-
- @Implementation
- public void incrementProgressBy(int diff) {
- if (!isIndeterminate()) setProgress(progress + diff);
- }
-
- @Implementation
- public void incrementSecondaryProgressBy(int diff) {
- if (!isIndeterminate()) setSecondaryProgress(secondaryProgress + diff);
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowProgressDialog.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowProgressDialog.java
deleted file mode 100644
index 243ebbb6f..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowProgressDialog.java
+++ /dev/null
@@ -1,54 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-
-import android.app.ProgressDialog;
-import android.content.Context;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-
-@Implements(ProgressDialog.class)
-public class ShadowProgressDialog extends ShadowAlertDialog {
-
- private boolean indeterminate;
-
- @Implementation
- public static ProgressDialog show(Context context, CharSequence title, CharSequence message) {
- return show(context, title, message, false);
- }
-
- @Implementation
- public static ProgressDialog show(Context context, CharSequence title, CharSequence message, boolean indeterminate) {
- return show(context, title, message, indeterminate, false, null);
- }
-
- @Implementation
- public static ProgressDialog show(Context context, CharSequence title, CharSequence message, boolean indeterminate, boolean cancelable) {
- return show(context, title, message, indeterminate, cancelable, null);
- }
-
- @Implementation
- public static ProgressDialog show(Context context, CharSequence title, CharSequence message, boolean indeterminate, boolean cancelable, ProgressDialog.OnCancelListener onCancelListener) {
- ProgressDialog progressDialog = new ProgressDialog(context);
- progressDialog.setTitle(title);
- progressDialog.setMessage(message);
- progressDialog.setIndeterminate(indeterminate);
- progressDialog.setCancelable(cancelable);
- progressDialog.setOnCancelListener(onCancelListener);
- progressDialog.show();
- Robolectric.getShadowApplication().setLatestAlertDialog(shadowOf(progressDialog));
- return progressDialog;
- }
-
- @Implementation
- public void setIndeterminate(boolean indeterminate) {
- this.indeterminate = indeterminate;
- }
-
- @Implementation
- public boolean isIndeterminate() {
- return indeterminate;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowRadioButton.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowRadioButton.java
deleted file mode 100644
index c83f15cb9..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowRadioButton.java
+++ /dev/null
@@ -1,28 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.view.ViewParent;
-import android.widget.RadioButton;
-import android.widget.RadioGroup;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-/**
- * Shadows the {@code android.widget.RadioButton} class.
- */
-@SuppressWarnings({"UnusedDeclaration"})
-@Implements(RadioButton.class)
-public class ShadowRadioButton extends ShadowCompoundButton {
-
- @Implementation
- @Override public void setChecked(boolean checked) {
- super.setChecked(checked);
- ViewParent viewParent = getParent();
-
- /* This simulates the listener a parent RadioGroup would have, listening to the
- checked state it's child RadioButtons. Feel free to implement properly.
- */
- if (viewParent instanceof RadioGroup) {
- ((RadioGroup) viewParent).check(getId());
- }
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowRadioGroup.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowRadioGroup.java
deleted file mode 100644
index 31e36885b..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowRadioGroup.java
+++ /dev/null
@@ -1,51 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.widget.RadioGroup;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.internal.RealObject;
-
-import static android.widget.RadioGroup.OnCheckedChangeListener;
-
-@SuppressWarnings({"UnusedDeclaration"})
-@Implements(RadioGroup.class)
-public class ShadowRadioGroup extends ShadowLinearLayout {
- @RealObject
- protected RadioGroup realGroup;
-
- private int checkedRadioButtonId = -1;
- private OnCheckedChangeListener onCheckedChangeListener;
-
- @Implementation
- public int getCheckedRadioButtonId() {
- return checkedRadioButtonId;
- }
-
- @Implementation
- public void check(int id) {
- checkedRadioButtonId = id;
- notifyListener();
- }
-
- @Implementation
- public void clearCheck() {
- notifyListener();
- checkedRadioButtonId = -1;
- notifyListener();
- }
-
- private void notifyListener() {
- if (onCheckedChangeListener != null) {
- onCheckedChangeListener.onCheckedChanged(realGroup, checkedRadioButtonId);
- }
- }
-
- @Implementation
- public void setOnCheckedChangeListener(OnCheckedChangeListener listener) {
- onCheckedChangeListener = listener;
- }
-
- public OnCheckedChangeListener getOnCheckedChangeListener() {
- return onCheckedChangeListener;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowRatingBar.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowRatingBar.java
deleted file mode 100644
index 54e1c34eb..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowRatingBar.java
+++ /dev/null
@@ -1,118 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.widget.RatingBar;
-import android.widget.RatingBar.OnRatingBarChangeListener;
-
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.internal.RealObject;
-
-@Implements(RatingBar.class)
-public class ShadowRatingBar extends ShadowAbsSeekBar {
-
- @RealObject
- private RatingBar realRatingBar;
- private int mNumStars = 5;
- private OnRatingBarChangeListener listener;
-
- @Override public void applyAttributes() {
- super.applyAttributes();
-
- setIsIndicator(attributeSet.getAttributeBooleanValue("android", "isIndicator", false));
- final int numStars = attributeSet.getAttributeIntValue("android", "numStars", mNumStars);
- final float rating = attributeSet.getAttributeFloatValue("android", "rating", -1);
- final float stepSize = attributeSet.getAttributeFloatValue("android", "stepSize", -1);
-
- if (numStars > 0 && numStars != mNumStars) {
- setNumStars(numStars);
- }
-
- if (stepSize >= 0) {
- setStepSize(stepSize);
- } else {
- setStepSize(0.5f);
- }
-
- if (rating >= 0) {
- setRating(rating);
- }
- }
-
- @Implementation
- public void setNumStars(final int numStars) {
- if (numStars <= 0) {
- return;
- }
-
- mNumStars = numStars;
- }
-
- @Implementation
- public int getNumStars() {
- return mNumStars;
- }
-
- @Implementation
- public void setRating(float rating) {
- setProgress(Math.round(rating * getProgressPerStar()));
- }
-
- @Implementation
- public float getRating() {
- return getProgress() / getProgressPerStar();
- }
-
- @Implementation
- public void setIsIndicator(boolean isIndicator) {
- mIsUserSeekable = !isIndicator;
- setFocusable(!isIndicator);
- }
-
- @Implementation
- public boolean isIndicator() {
- return !mIsUserSeekable;
- }
-
- @Implementation
- public void setStepSize(float stepSize) {
- if (stepSize <= 0) {
- return;
- }
-
- final float newMax = mNumStars / stepSize;
- final int newProgress = (int) (newMax / getMax() * getProgress());
- setMax((int) newMax);
- setProgress(newProgress);
- }
-
- @Implementation
- public float getStepSize() {
- return (float) getNumStars() / getMax();
- }
-
- private float getProgressPerStar() {
- if (mNumStars > 0) {
- return 1f * getMax() / mNumStars;
- } else {
- return 1;
- }
- }
-
- @Implementation
- @Override
- public void setProgress(int progress) {
- super.setProgress(progress);
- if (listener != null)
- listener.onRatingChanged(realRatingBar, getRating(), true);
- }
-
- @Implementation
- public void setOnRatingBarChangeListener(OnRatingBarChangeListener listener) {
- this.listener = listener;
- }
-
- @Implementation
- public OnRatingBarChangeListener getOnRatingBarChangeListener() {
- return listener;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowRect.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowRect.java
deleted file mode 100644
index 3573aafd0..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowRect.java
+++ /dev/null
@@ -1,115 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.graphics.Rect;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.internal.RealObject;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf_;
-
-@Implements(Rect.class)
-public class ShadowRect {
- @RealObject Rect realRect;
-
- public void __constructor__(int left, int top, int right, int bottom) {
- realRect.left = left;
- realRect.top = top;
- realRect.right = right;
- realRect.bottom = bottom;
- }
-
- public void __constructor__(Rect otherRect) {
- realRect.left = otherRect.left;
- realRect.top = otherRect.top;
- realRect.right = otherRect.right;
- realRect.bottom = otherRect.bottom;
- }
-
- @Implementation
- public void set(Rect rect) {
- set(rect.left, rect.top, rect.right, rect.bottom);
- }
-
- @Implementation
- public void set(int left, int top, int right, int bottom) {
- realRect.left = left;
- realRect.top = top;
- realRect.right = right;
- realRect.bottom = bottom;
- }
-
- @Implementation
- public int width() {
- return realRect.right - realRect.left;
- }
-
- @Implementation
- public int height() {
- return realRect.bottom - realRect.top;
- }
-
- @Implementation
- public boolean equals(Object obj) {
- if (obj == null) return false;
- Object o = shadowOf_(obj);
- if (o == null) return false;
- if (getClass() != o.getClass()) return false;
- if (this == o) return true;
-
- Rect r = (Rect) obj;
- return realRect.left == r.left && realRect.top == r.top && realRect.right == r.right
- && realRect.bottom == r.bottom;
- }
-
- @Implementation
- public String toString() {
- StringBuilder sb = new StringBuilder(32);
- sb.append("Rect(");
- sb.append(realRect.left);
- sb.append(", ");
- sb.append(realRect.top);
- sb.append(" - ");
- sb.append(realRect.right);
- sb.append(", ");
- sb.append(realRect.bottom);
- sb.append(")");
- return sb.toString();
- }
-
- @Implementation
- public boolean contains(int x, int y) {
- return x > realRect.left && x < realRect.right
- && y >= realRect.top && y <= realRect.bottom;
- }
-
- @Implementation
- public boolean contains(Rect r) {
- return equals(r)
- || (contains(r.left, r.top) && contains(r.right, r.top)
- && contains(r.left, r.bottom) && contains(r.right, r.bottom));
- }
-
- @Implementation
- public static boolean intersects(Rect a, Rect b) {
- return a.left < b.right && b.left < a.right
- && a.top < b.bottom && b.top < a.bottom;
- }
-
- @Implementation
- public boolean intersect(Rect r) {
- return intersects(realRect, r);
- }
-
- @Implementation
- public boolean intersect(int left, int top, int right, int bottom) {
- return intersect(new Rect(left, top, right, bottom));
- }
-
- @Implementation
- public void offset(int dx, int dy) {
- realRect.left += dx;
- realRect.right += dx;
- realRect.top += dy;
- realRect.bottom += dy;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowRemoteCallbackList.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowRemoteCallbackList.java
deleted file mode 100644
index b2fcee90d..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowRemoteCallbackList.java
+++ /dev/null
@@ -1,137 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import java.util.HashMap;
-
-import android.os.IBinder;
-import android.os.IInterface;
-import android.os.RemoteCallbackList;
-import android.os.RemoteException;
-
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-@Implements(RemoteCallbackList.class)
-public class ShadowRemoteCallbackList<E extends IInterface> {
- private HashMap<IBinder, Callback> callbacks = new HashMap<IBinder, Callback>();
- private Object[] activeBroadcast;
- private int broadcastCount = -1;
- private boolean killed = false;
-
- private final class Callback implements IBinder.DeathRecipient {
- final E callback;
- final Object cookie;
-
- Callback(E callback, Object cookie) {
- this.callback = callback;
- this.cookie = cookie;
- }
-
- public void binderDied() {
- synchronized (callbacks) {
- callbacks.remove(callback.asBinder());
- }
- onCallbackDied(callback, cookie);
- }
- }
-
- @Implementation
- public boolean register(E callback) {
- return register(callback, null);
- }
-
- @Implementation
- public boolean register(E callback, Object cookie) {
- synchronized (callbacks) {
- if (killed) {
- return false;
- }
- IBinder binder = callback.asBinder();
- try {
- Callback cb = new Callback(callback, cookie);
- binder.linkToDeath(cb, 0);
- callbacks.put(binder, cb);
- return true;
- } catch (RemoteException e) {
- return false;
- }
- }
- }
-
- @Implementation
- public boolean unregister(E callback) {
- synchronized (callbacks) {
- Callback cb = callbacks.remove(callback.asBinder());
- if (cb != null) {
- cb.callback.asBinder().unlinkToDeath(cb, 0);
- return true;
- }
- return false;
- }
- }
-
- @Implementation
- public void kill() {
- synchronized (callbacks) {
- for (Callback cb : callbacks.values()) {
- cb.callback.asBinder().unlinkToDeath(cb, 0);
- }
- callbacks.clear();
- killed = true;
- }
- }
-
- @Implementation
- public void onCallbackDied(E callback) {}
-
- @Implementation
- public void onCallbackDied(E callback, Object cookie) {
- onCallbackDied(callback);
- }
-
- @Implementation
- public int beginBroadcast() {
- synchronized (callbacks) {
- if (broadcastCount > 0) {
- throw new IllegalStateException("beginBroadcast() called while already in a broadcast");
- }
- final int N = broadcastCount = callbacks.size();
- if (N <= 0) {
- return 0;
- }
- Object[] active = activeBroadcast;
- if (active == null || active.length < N) {
- activeBroadcast = active = new Object[N];
- }
- int i = 0;
- for (Callback cb : callbacks.values()) {
- active[i++] = cb;
- }
- return i;
- }
- }
-
- @Implementation
- public E getBroadcastItem(int index) {
- return ((Callback) activeBroadcast[index]).callback;
- }
-
- @Implementation
- public Object getBroadcastCookie(int index) {
- return ((Callback) activeBroadcast[index]).cookie;
- }
-
- @Implementation
- public void finishBroadcast() {
- if (broadcastCount < 0) {
- throw new IllegalStateException("finishBroadcast() called outside of a broadcast");
- }
- Object[] active = activeBroadcast;
- if (active != null) {
- final int N = broadcastCount;
- for (int i = 0; i < N; i++) {
- active[i] = null;
- }
- }
- broadcastCount = -1;
- }
-} \ No newline at end of file
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowRemoteViews.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowRemoteViews.java
deleted file mode 100644
index 8cfe38b47..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowRemoteViews.java
+++ /dev/null
@@ -1,127 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.app.PendingIntent;
-import android.content.Context;
-import android.graphics.Bitmap;
-import android.view.View;
-import android.widget.ImageView;
-import android.widget.RemoteViews;
-import android.widget.TextView;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.res.ResourceLoader;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Shadow for {@code RemoteViews} that simulates its implementation. Supports pending intents for events, changing
- * visibility, setting text, updating etc...
- */
-@SuppressWarnings({"UnusedDeclaration"})
-@Implements(RemoteViews.class)
-public class ShadowRemoteViews {
- private String packageName;
- private int layoutId;
- private List<ViewUpdater> viewUpdaters = new ArrayList<ViewUpdater>();
-
- public void __constructor__(String packageName, int layoutId) {
- this.packageName = packageName;
- this.layoutId = layoutId;
- }
-
- @Implementation
- public String getPackage() {
- return packageName;
- }
-
- @Implementation
- public int getLayoutId() {
- return layoutId;
- }
-
- @Implementation
- public void setTextViewText(int viewId, final CharSequence text) {
- viewUpdaters.add(new ViewUpdater(viewId) {
- @Override
- public void doUpdate(View view) {
- ((TextView) view).setText(text);
- }
- });
- }
-
- @Implementation
- public void setOnClickPendingIntent(int viewId, final PendingIntent pendingIntent) {
- viewUpdaters.add(new ViewUpdater(viewId) {
- @Override void doUpdate(final View view) {
- view.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- try {
- pendingIntent.send(view.getContext(), 0, null);
- } catch (PendingIntent.CanceledException e) {
- throw new RuntimeException(e);
- }
- }
- });
- }
- });
- }
-
- @Implementation
- public void setViewVisibility(int viewId, final int visibility) {
- viewUpdaters.add(new ViewUpdater(viewId) {
- @Override
- public void doUpdate(View view) {
- view.setVisibility(visibility);
- }
- });
- }
-
- @Implementation
- public void setImageViewResource(int viewId, final int resourceId) {
- viewUpdaters.add(new ViewUpdater(viewId) {
- @Override
- public void doUpdate(View view) {
- ((ImageView) view).setImageResource(resourceId);
- }
- });
- }
-
- @Implementation
- public void setImageViewBitmap(int viewId, final Bitmap bitmap) {
- viewUpdaters.add(new ViewUpdater(viewId) {
- @Override
- public void doUpdate(View view) {
- ((ImageView) view).setImageBitmap(bitmap);
- }
- });
- }
-
- @Implementation
- public void reapply(Context context, View v) {
- for (ViewUpdater viewUpdater : viewUpdaters) {
- viewUpdater.update(v);
- }
- }
-
- private abstract class ViewUpdater {
- private int viewId;
-
- public ViewUpdater(int viewId) {
- this.viewId = viewId;
- }
-
- final void update(View parent) {
-
- View view = parent.findViewById(viewId);
- if (view == null) {
- throw new NullPointerException("couldn't find view " + viewId
- + " (" + ResourceLoader.getFrom(parent.getContext()).getNameForId(viewId) + ")");
- }
- doUpdate(view);
- }
-
- abstract void doUpdate(View view);
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowResolveInfo.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowResolveInfo.java
deleted file mode 100644
index 1ef9033ad..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowResolveInfo.java
+++ /dev/null
@@ -1,52 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.content.pm.ActivityInfo;
-import android.content.pm.PackageManager;
-import android.content.pm.ResolveInfo;
-
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-@Implements( ResolveInfo.class )
-public class ShadowResolveInfo {
-
- private String label;
-
- @Implementation
- public String loadLabel( PackageManager mgr ) { return label; }
-
- /**
- * Non-Android accessor used to set the value returned by {@link loadLabel}
- */
- public void setLabel( String l ) { label = l; }
-
- /**
- * Non-Android accessor used for creating ResolveInfo objects
- * @param displayName
- * @param packageName
- * @return
- */
- public static ResolveInfo newResolveInfo( String displayName, String packageName ) {
- return newResolveInfo( displayName, packageName, null);
- }
-
- /**
- * Non-Android accessor used for creating ResolveInfo objects
- * @param displayName
- * @param packageName
- * @return
- */
- public static ResolveInfo newResolveInfo( String displayName, String packageName, String activityName ) {
-
- ResolveInfo resInfo = new ResolveInfo();
- ActivityInfo actInfo = new ActivityInfo();
- actInfo.packageName = packageName;
- actInfo.name = activityName;
- resInfo.activityInfo = actInfo;
-
- ShadowResolveInfo shResolve = Robolectric.shadowOf(resInfo );
- shResolve.setLabel( displayName );
- return resInfo;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowResourceCursorAdapter.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowResourceCursorAdapter.java
deleted file mode 100644
index 4402e758f..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowResourceCursorAdapter.java
+++ /dev/null
@@ -1,111 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.xtremelabs.robolectric.shadows;
-
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-import android.content.Context;
-import android.database.Cursor;
-import android.view.LayoutInflater;
-import android.view.View;
-import android.view.ViewGroup;
-import android.widget.ResourceCursorAdapter;
-
-
-/**
- * An easy adapter that creates views defined in an XML file. You can specify
- * the XML file that defines the appearance of the views.
- */
-@Implements(ResourceCursorAdapter.class)
-public class ShadowResourceCursorAdapter extends ShadowCursorAdapter {
- private int mLayout;
-
- private int mDropDownLayout;
-
- private LayoutInflater mInflater;
-
- /**
- * Constructor.
- *
- * @param context The context where the ListView associated with this
- * SimpleListItemFactory is running
- * @param layout resource identifier of a layout file that defines the views
- * for this list item. Unless you override them later, this will
- * define both the item views and the drop down views.
- */
- public void __constructor__(Context context, int layout, Cursor c) {
- super.__constructor__(context, c);
- mLayout = mDropDownLayout = layout;
- mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
- }
-
- /**
- * Constructor.
- *
- * @param context The context where the ListView associated with this
- * SimpleListItemFactory is running
- * @param layout resource identifier of a layout file that defines the views
- * for this list item. Unless you override them later, this will
- * define both the item views and the drop down views.
- * @param c The cursor from which to get the data.
- * @param autoRequery If true the adapter will call requery() on the
- * cursor whenever it changes so the most recent
- * data is always displayed.
- */
- public void __constructor__(Context context, int layout, Cursor c, boolean autoRequery) {
- super.__constructor__(context, c, autoRequery);
- mLayout = mDropDownLayout = layout;
- mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
- }
-
- /**
- * Inflates view(s) from the specified XML file.
- *
- * @see android.widget.CursorAdapter#newView(android.content.Context,
- * android.database.Cursor, ViewGroup)
- */
- @Implementation
- public View newView(Context context, Cursor cursor, ViewGroup parent) {
- return mInflater.inflate(mLayout, parent, false);
- }
-
- @Implementation
- public View newDropDownView(Context context, Cursor cursor, ViewGroup parent) {
- return mInflater.inflate(mDropDownLayout, parent, false);
- }
-
- /**
- * <p>Sets the layout resource of the item views.</p>
- *
- * @param layout the layout resources used to create item views
- */
- @Implementation
- public void setViewResource(int layout) {
- mLayout = layout;
- }
-
- /**
- * <p>Sets the layout resource of the drop down views.</p>
- *
- * @param dropDownLayout the layout resources used to create drop down views
- */
- @Implementation
- public void setDropDownViewResource(int dropDownLayout) {
- mDropDownLayout = dropDownLayout;
- }
-} \ No newline at end of file
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowResources.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowResources.java
deleted file mode 100644
index 12e6ea13b..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowResources.java
+++ /dev/null
@@ -1,246 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.content.res.AssetManager;
-import android.content.res.Configuration;
-import android.content.res.Resources;
-import android.content.res.TypedArray;
-import android.graphics.BitmapFactory;
-import android.graphics.drawable.BitmapDrawable;
-import android.graphics.drawable.Drawable;
-import android.graphics.drawable.NinePatchDrawable;
-import android.util.AttributeSet;
-import android.util.DisplayMetrics;
-import android.util.TypedValue;
-import android.view.Display;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.internal.RealObject;
-import com.xtremelabs.robolectric.res.ResourceExtractor;
-import com.xtremelabs.robolectric.res.ResourceLoader;
-
-import java.io.InputStream;
-import java.util.HashMap;
-import java.util.Locale;
-
-import static com.xtremelabs.robolectric.Robolectric.newInstanceOf;
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-
-/**
- * Shadow of {@code Resources} that simulates the loading of resources
- *
- * @see com.xtremelabs.robolectric.RobolectricTestRunner#RobolectricTestRunner(Class, String, String)
- */
-@SuppressWarnings({"UnusedDeclaration"})
-@Implements(Resources.class)
-public class ShadowResources {
- private float density = 1.0f;
- Configuration configuration = null;
- private DisplayMetrics displayMetrics;
- private Display display;
-
- static Resources bind(Resources resources, ResourceLoader resourceLoader) {
- ShadowResources shadowResources = shadowOf(resources);
- if (shadowResources.resourceLoader != null) throw new RuntimeException("ResourceLoader already set!");
- shadowResources.resourceLoader = resourceLoader;
- return resources;
- }
-
- @RealObject
- Resources realResources;
- private ResourceLoader resourceLoader;
-
- @Implementation
- public int getIdentifier(String name, String defType, String defPackage) {
- Integer index = 0;
-
- ResourceExtractor resourceExtractor = resourceLoader.getResourceExtractor();
-
- index = resourceExtractor.getResourceId(defType + "/" + name);
- if (index == null) {
- return 0;
- }
- return index;
- }
-
- @Implementation
- public int getColor(int id) throws Resources.NotFoundException {
- return resourceLoader.getColorValue(id);
- }
-
- @Implementation
- public Configuration getConfiguration() {
- if (configuration == null) {
- configuration = new Configuration();
- configuration.setToDefaults();
- }
- if (configuration.locale == null) {
- configuration.locale = Locale.getDefault();
- }
- return configuration;
- }
-
- @Implementation
- public String getString(int id) throws Resources.NotFoundException {
- return resourceLoader.getStringValue(id);
- }
-
- @Implementation
- public String getString(int id, Object... formatArgs) throws Resources.NotFoundException {
- String raw = getString(id);
- return String.format(Locale.ENGLISH, raw, formatArgs);
- }
-
- @Implementation
- public String getQuantityString(int id, int quantity, Object... formatArgs) throws Resources.NotFoundException {
- String raw = getQuantityString(id, quantity);
- return String.format(Locale.ENGLISH, raw, formatArgs);
- }
-
- @Implementation
- public String getQuantityString(int id, int quantity) throws Resources.NotFoundException {
- return resourceLoader.getPluralStringValue(id, quantity);
- }
-
- @Implementation
- public InputStream openRawResource(int id) throws Resources.NotFoundException {
- return resourceLoader.getRawValue(id);
- }
-
- @Implementation
- public String[] getStringArray(int id) throws Resources.NotFoundException {
- String[] arrayValue = resourceLoader.getStringArrayValue(id);
- if (arrayValue == null) {
- throw new Resources.NotFoundException();
- }
- return arrayValue;
- }
-
- @Implementation
- public CharSequence[] getTextArray(int id) throws Resources.NotFoundException {
- return getStringArray(id);
- }
-
- @Implementation
- public CharSequence getText(int id) throws Resources.NotFoundException {
- return getString(id);
- }
-
- public void setDensity(float density) {
- this.density = density;
- }
-
- public void setDisplay(Display display) {
- this.display = display;
- displayMetrics = null;
- }
-
- @Implementation
- public DisplayMetrics getDisplayMetrics() {
- if (displayMetrics == null) {
- if (display == null) {
- display = Robolectric.newInstanceOf(Display.class);
- }
-
- displayMetrics = new DisplayMetrics();
- display.getMetrics(displayMetrics);
- }
- displayMetrics.density = this.density;
- return displayMetrics;
- }
-
- @Implementation
- public Drawable getDrawable(int drawableResourceId) throws Resources.NotFoundException {
-
- ResourceLoader resLoader = Robolectric.shadowOf(Robolectric.application).getResourceLoader();
-
- Drawable xmlDrawable = resLoader.getXmlDrawable(drawableResourceId);
- if (xmlDrawable != null) {
- return xmlDrawable;
- }
-
- Drawable animDrawable = resLoader.getAnimDrawable(drawableResourceId);
- if (animDrawable != null) {
- return animDrawable;
- }
-
- Drawable colorDrawable = resLoader.getColorDrawable(drawableResourceId);
- if (colorDrawable != null) {
- return colorDrawable;
- }
-
- if (resLoader.isNinePatchDrawable(drawableResourceId)) {
- return new NinePatchDrawable(realResources, null);
- }
-
- return new BitmapDrawable(realResources, BitmapFactory.decodeResource(realResources, drawableResourceId));
- }
-
- @Implementation
- public float getDimension(int id) throws Resources.NotFoundException {
- return resourceLoader.getDimenValue(id);
- }
-
- @Implementation
- public int getInteger(int id) throws Resources.NotFoundException {
- return resourceLoader.getIntegerValue( id );
- }
-
- @Implementation
- public int getDimensionPixelSize(int id) throws Resources.NotFoundException {
- // The int value returned from here is probably going to be handed to TextView.setTextSize(),
- // which takes a float. Avoid int-to-float conversion errors by returning a value generated from this
- // resource ID but which isn't too big (resource values in R.java are all greater than 0x7f000000).
-
- return (int) getDimension(id);
- }
-
- @Implementation
- public int getDimensionPixelOffset(int id) throws Resources.NotFoundException {
- return (int) getDimension(id);
- }
-
- @Implementation
- public AssetManager getAssets() {
- return ShadowAssetManager.bind(Robolectric.newInstanceOf(AssetManager.class), resourceLoader);
- }
-
- @Implementation
- public final android.content.res.Resources.Theme newTheme() {
- return newInstanceOf(Resources.Theme.class);
- }
-
- @Implements(Resources.Theme.class)
- public static class ShadowTheme {
- HashMap<Integer, TypedValue> attrMap = new HashMap<Integer, TypedValue>();
-
- @Implementation
- public TypedArray obtainStyledAttributes(int[] attrs) {
- return obtainStyledAttributes(0, attrs);
- }
-
- @Implementation
- public TypedArray obtainStyledAttributes(int resid, int[] attrs) throws android.content.res.Resources.NotFoundException {
- return obtainStyledAttributes(null, attrs, 0, 0);
- }
-
- @Implementation
- public TypedArray obtainStyledAttributes(AttributeSet set, int[] attrs, int defStyleAttr, int defStyleRes) {
- return newInstanceOf(TypedArray.class);
- }
-
- @Implementation
- public boolean resolveAttribute (int resid, TypedValue outValue, boolean resolveRefs) {
- TypedValue foundValue = attrMap.get(resid);
- if (foundValue != null) {
- outValue.setTo(foundValue);
- return true;
- }
- return false;
- }
-
- public void setAttribue(int attrId, TypedValue value) {
- attrMap.put(attrId, value);
- }
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowResultReceiver.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowResultReceiver.java
deleted file mode 100644
index 78e055c4c..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowResultReceiver.java
+++ /dev/null
@@ -1,32 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.os.Bundle;
-import android.os.ResultReceiver;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.internal.RealObject;
-
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-
-@Implements(ResultReceiver.class)
-public class ShadowResultReceiver {
- // TODO: Use handler to make asynchronous
-
- @RealObject private ResultReceiver realResultReceiver;
-
- @Implementation
- public void send(int resultCode, android.os.Bundle resultData) {
- try {
- Method onReceiveResult = ResultReceiver.class.getDeclaredMethod("onReceiveResult", Integer.TYPE, Bundle.class);
- onReceiveResult.setAccessible(true);
- onReceiveResult.invoke(realResultReceiver, resultCode, resultData);
- } catch (NoSuchMethodException e) {
- throw new RuntimeException(e);
- } catch (InvocationTargetException e) {
- throw new RuntimeException(e);
- } catch (IllegalAccessException e) {
- throw new RuntimeException(e);
- }
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSQLiteCloseable.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSQLiteCloseable.java
deleted file mode 100644
index 52a0df5bd..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSQLiteCloseable.java
+++ /dev/null
@@ -1,20 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.database.sqlite.SQLiteClosable;
-
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-/**
- * Shadow for {@code SQLiteCloseable}. Though {@code SQLiteCloseable} is an abstract
- * class, a shadow is necessary. Its methods that are overridden in subclasses
- * require this shadow in order to be properly instrumented.
- */
-@Implements(SQLiteClosable.class)
-public class ShadowSQLiteCloseable {
-
- @Implementation
- public void close() {
- }
-
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSQLiteCursor.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSQLiteCursor.java
deleted file mode 100644
index 84431491e..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSQLiteCursor.java
+++ /dev/null
@@ -1,262 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.database.sqlite.SQLiteCursor;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-import java.sql.Clob;
-import java.sql.Connection;
-import java.sql.ResultSet;
-import java.sql.ResultSetMetaData;
-import java.sql.SQLException;
-import java.sql.Statement;
-import java.util.HashMap;
-import java.util.Map;
-
-/**
- * Simulates an Android Cursor object, by wrapping a JDBC ResultSet.
- */
-@Implements(SQLiteCursor.class)
-public class ShadowSQLiteCursor extends ShadowAbstractCursor {
-
- private ResultSet resultSet;
-
-
- /**
- * Stores the column names so they are retrievable after the resultSet has closed
- */
- private void cacheColumnNames(ResultSet rs) {
- try {
- ResultSetMetaData metaData = rs.getMetaData();
- int columnCount = metaData.getColumnCount();
- columnNameArray = new String[columnCount];
- for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) {
- String cName = metaData.getColumnName(columnIndex).toLowerCase();
- this.columnNames.put(cName, columnIndex-1);
- this.columnNameArray[columnIndex-1]=cName;
- }
- } catch (SQLException e) {
- throw new RuntimeException("SQL exception in cacheColumnNames", e);
- }
- }
-
-
-
-
- private Integer getColIndex(String columnName) {
- if (columnName == null) {
- return -1;
- }
-
- Integer i = this.columnNames.get(columnName.toLowerCase());
- if (i==null) return -1;
- return i;
- }
-
- @Implementation
- public int getColumnIndex(String columnName) {
- return getColIndex(columnName);
- }
-
- @Implementation
- public int getColumnIndexOrThrow(String columnName) {
- Integer columnIndex = getColIndex(columnName);
- if (columnIndex == -1) {
- throw new IllegalArgumentException("Column index does not exist");
- }
- return columnIndex;
- }
-
- @Implementation
- @Override
- public final boolean moveToLast() {
- return super.moveToLast();
- }
-
- @Implementation
- @Override
- public final boolean moveToFirst() {
- return super.moveToFirst();
- }
-
- @Implementation
- @Override
- public boolean moveToNext() {
- return super.moveToNext();
- }
-
- @Implementation
- @Override
- public boolean moveToPrevious() {
- return super.moveToPrevious();
- }
-
- @Implementation
- @Override
- public boolean moveToPosition(int pos) {
- return super.moveToPosition(pos);
- }
-
- @Implementation
- public byte[] getBlob(int columnIndex) {
- checkPosition();
- return (byte[]) this.currentRow.get(getColumnNames()[columnIndex]);
- }
-
- @Implementation
- public String getString(int columnIndex) {
- checkPosition();
- Object value = this.currentRow.get(getColumnNames()[columnIndex]);
- if (value instanceof Clob) {
- try {
- return ((Clob) value).getSubString(1, (int)((Clob) value).length());
- } catch (SQLException x) {
- throw new RuntimeException(x);
- }
- } else {
- return (String)value;
- }
- }
-
- @Implementation
- public short getShort(int columnIndex) {
- checkPosition();
- Object o =this.currentRow.get(getColumnNames()[columnIndex]);
- if (o==null) return 0;
- return new Short(o.toString());
- }
-
- @Implementation
- public int getInt(int columnIndex) {
- checkPosition();
- Object o =this.currentRow.get(getColumnNames()[columnIndex]);
- if (o==null) return 0;
- return new Integer(o.toString());
- }
-
- @Implementation
- public long getLong(int columnIndex) {
- checkPosition();
- Object o =this.currentRow.get(getColumnNames()[columnIndex]);
- if (o==null) return 0;
- return new Long(o.toString());
- }
-
- @Implementation
- public float getFloat(int columnIndex) {
- checkPosition();
- Object o =this.currentRow.get(getColumnNames()[columnIndex]);
- if (o==null) return 0;
- return new Float(o.toString());
-
- }
-
- @Implementation
- public double getDouble(int columnIndex) {
- checkPosition();
- Object o =this.currentRow.get(getColumnNames()[columnIndex]);
- if (o==null) return 0;
- return new Double(o.toString());
- }
-
- private void checkPosition() {
- if (-1 == currentRowNumber || getCount() == currentRowNumber) {
- throw new IndexOutOfBoundsException(currentRowNumber + " " + getCount());
- }
- }
-
- @Implementation
- public void close() {
- if (resultSet == null) {
- return;
- }
-
- try {
- resultSet.close();
- resultSet = null;
- rows = null;
- currentRow = null;
- } catch (SQLException e) {
- throw new RuntimeException("SQL exception in close", e);
- }
- }
-
- @Implementation
- public boolean isClosed() {
- return (resultSet == null);
- }
-
- @Implementation
- public boolean isNull(int columnIndex) {
- Object o = this.currentRow.get(getColumnNames()[columnIndex]);
- return o == null;
- }
-
- /**
- * Allows test cases access to the underlying JDBC ResultSet, for use in
- * assertions.
- *
- * @return the result set
- */
- public ResultSet getResultSet() {
- return resultSet;
- }
-
- /**
- * Allows test cases access to the underlying JDBC ResultSetMetaData, for use in
- * assertions. Available even if cl
- *
- * @return the result set
- */
- public ResultSet getResultSetMetaData() {
- return resultSet;
- }
-
- /**
- * loads a row's values
- * @param rs
- * @return
- * @throws SQLException
- */
- private Map<String,Object> fillRowValues(ResultSet rs) throws SQLException {
- Map<String,Object> row = new HashMap<String,Object>();
- for (String s : getColumnNames()) {
- row.put(s, rs.getObject(s));
- }
- return row;
- }
- private void fillRows(String sql, Connection connection) throws SQLException {
- //ResultSets in SQLite\Android are only TYPE_FORWARD_ONLY. Android caches results in the WindowedCursor to allow moveToPrevious() to function.
- //Robolectric will have to cache the results too. In the rows map.
- Statement statement = connection.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
- ResultSet rs = statement.executeQuery(sql);
- int count = 0;
- if (rs.next()) {
- do {
- Map<String,Object> row = fillRowValues(rs);
- rows.put(count, row);
- count++;
- } while (rs.next());
- } else {
- rs.close();
- }
-
- rowCount = count;
-
- }
-
- public void setResultSet(ResultSet result, String sql) {
- this.resultSet = result;
- rowCount = 0;
-
- //Cache all rows. Caching rows should be thought of as a simple replacement for ShadowCursorWindow
- if (resultSet != null) {
- cacheColumnNames(resultSet);
- try {
- fillRows(sql, result.getStatement().getConnection());
- } catch (SQLException e) {
- throw new RuntimeException("SQL exception in setResultSet", e);
- }
- }
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSQLiteDatabase.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSQLiteDatabase.java
deleted file mode 100644
index 44755043b..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSQLiteDatabase.java
+++ /dev/null
@@ -1,381 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.content.ContentValues;
-import android.database.Cursor;
-import android.database.DatabaseUtils;
-import android.database.sqlite.*;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.internal.RealObject;
-import com.xtremelabs.robolectric.util.DatabaseConfig;
-import com.xtremelabs.robolectric.util.SQLite.SQLStringAndBindings;
-
-import java.sql.Connection;
-import java.sql.PreparedStatement;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.sql.Statement;
-import java.util.Iterator;
-import java.util.WeakHashMap;
-import java.util.concurrent.locks.ReentrantLock;
-
-import static com.xtremelabs.robolectric.Robolectric.newInstanceOf;
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-import static com.xtremelabs.robolectric.util.SQLite.buildDeleteString;
-import static com.xtremelabs.robolectric.util.SQLite.buildInsertString;
-import static com.xtremelabs.robolectric.util.SQLite.buildUpdateString;
-import static com.xtremelabs.robolectric.util.SQLite.buildWhereClause;
-
-/**
- * Shadow for {@code SQLiteDatabase} that simulates the movement of a {@code Cursor} through database tables.
- * Implemented as a wrapper around an embedded SQL database, accessed via JDBC. The JDBC connection is
- * made available to test cases for use in fixture setup and assertions.
- */
-@Implements(SQLiteDatabase.class)
-public class ShadowSQLiteDatabase {
- @RealObject SQLiteDatabase realSQLiteDatabase;
- private static Connection connection;
- private final ReentrantLock mLock = new ReentrantLock(true);
- private boolean mLockingEnabled = true;
- private WeakHashMap<SQLiteClosable, Object> mPrograms;
- private boolean inTransaction = false;
- private boolean transactionSuccess = false;
- private boolean throwOnInsert;
-
- @Implementation
- public void setLockingEnabled(boolean lockingEnabled) {
- mLockingEnabled = lockingEnabled;
- }
-
- public void lock() {
- if (!mLockingEnabled) return;
- mLock.lock();
- }
-
- public void unlock() {
- if (!mLockingEnabled) return;
- mLock.unlock();
- }
-
- public void setThrowOnInsert(boolean throwOnInsert) {
- this.throwOnInsert = throwOnInsert;
- }
-
- @Implementation
- public static SQLiteDatabase openDatabase(String path, SQLiteDatabase.CursorFactory factory, int flags) {
- connection = DatabaseConfig.getMemoryConnection();
- return newInstanceOf(SQLiteDatabase.class);
- }
-
- @Implementation
- public long insert(String table, String nullColumnHack, ContentValues values) {
- return insertWithOnConflict(table, nullColumnHack, values, SQLiteDatabase.CONFLICT_NONE);
- }
-
- @Implementation
- public long insertOrThrow(String table, String nullColumnHack, ContentValues values) {
- if (throwOnInsert)
- throw new android.database.SQLException();
- return insertWithOnConflict(table, nullColumnHack, values, SQLiteDatabase.CONFLICT_NONE);
- }
-
- @Implementation
- public long replace(String table, String nullColumnHack, ContentValues values) {
- return insertWithOnConflict(table, nullColumnHack, values, SQLiteDatabase.CONFLICT_REPLACE);
- }
-
- @Implementation
- public long insertWithOnConflict(String table, String nullColumnHack,
- ContentValues initialValues, int conflictAlgorithm) {
-
- try {
- SQLStringAndBindings sqlInsertString = buildInsertString(table, initialValues, conflictAlgorithm);
- PreparedStatement insert = connection.prepareStatement(sqlInsertString.sql, Statement.RETURN_GENERATED_KEYS);
- Iterator<Object> columns = sqlInsertString.columnValues.iterator();
- int i = 1;
- long result = -1;
- while (columns.hasNext()) {
- insert.setObject(i++, columns.next());
- }
- insert.executeUpdate();
- ResultSet resultSet = insert.getGeneratedKeys();
- if (resultSet.next()) {
- result = resultSet.getLong(1);
- }
- resultSet.close();
- return result;
- } catch (SQLException e) {
- return -1; // this is how SQLite behaves, unlike H2 which throws exceptions
- }
- }
-
- @Implementation
- public Cursor query(boolean distinct, String table, String[] columns,
- String selection, String[] selectionArgs, String groupBy,
- String having, String orderBy, String limit) {
-
- String where = selection;
- if (selection != null && selectionArgs != null) {
- where = buildWhereClause(selection, selectionArgs);
- }
-
- String sql = SQLiteQueryBuilder.buildQueryString(distinct, table,
- columns, where, groupBy, having, orderBy, limit);
-
- ResultSet resultSet;
- try {
- Statement statement = connection.createStatement(DatabaseConfig.getResultSetType(), ResultSet.CONCUR_READ_ONLY);
- resultSet = statement.executeQuery(sql);
- } catch (SQLException e) {
- throw new RuntimeException("SQL exception in query", e);
- }
-
- SQLiteCursor cursor = new SQLiteCursor(null, null, null, null);
- shadowOf(cursor).setResultSet(resultSet,sql);
- return cursor;
- }
-
- @Implementation
- public Cursor query(String table, String[] columns, String selection,
- String[] selectionArgs, String groupBy, String having,
- String orderBy) {
- return query(false, table, columns, selection, selectionArgs, groupBy, having, orderBy, null);
- }
-
- @Implementation
- public Cursor query(String table, String[] columns, String selection,
- String[] selectionArgs, String groupBy, String having,
- String orderBy, String limit) {
- return query(false, table, columns, selection, selectionArgs, groupBy, having, orderBy, limit);
- }
-
- @Implementation
- public int update(String table, ContentValues values, String whereClause, String[] whereArgs) {
- SQLStringAndBindings sqlUpdateString = buildUpdateString(table, values, whereClause, whereArgs);
-
- try {
- PreparedStatement statement = connection.prepareStatement(sqlUpdateString.sql);
- Iterator<Object> columns = sqlUpdateString.columnValues.iterator();
- int i = 1;
- while (columns.hasNext()) {
- statement.setObject(i++, columns.next());
- }
-
- return statement.executeUpdate();
- } catch (SQLException e) {
- throw new RuntimeException("SQL exception in update", e);
- }
- }
-
- @Implementation
- public int delete(String table, String whereClause, String[] whereArgs) {
- String sql = buildDeleteString(table, whereClause, whereArgs);
-
- try {
- return connection.prepareStatement(sql).executeUpdate();
- } catch (SQLException e) {
- throw new RuntimeException("SQL exception in delete", e);
- }
- }
-
- @Implementation
- public void execSQL(String sql) throws android.database.SQLException {
- if (!isOpen()) {
- throw new IllegalStateException("database not open");
- }
-
- try {
- String scrubbedSql= DatabaseConfig.getScrubSQL(sql);
- connection.createStatement().execute(scrubbedSql);
- } catch (java.sql.SQLException e) {
- android.database.SQLException ase = new android.database.SQLException();
- ase.initCause(e);
- throw ase;
- }
- }
-
- @Implementation
- public void execSQL(String sql, Object[] bindArgs) throws SQLException {
- if (bindArgs == null) {
- throw new IllegalArgumentException("Empty bindArgs");
- }
- String scrubbedSql= DatabaseConfig.getScrubSQL(sql);
-
-
- SQLiteStatement statement = null;
- try {
- statement =compileStatement(scrubbedSql);
- if (bindArgs != null) {
- int numArgs = bindArgs.length;
- for (int i = 0; i < numArgs; i++) {
- DatabaseUtils.bindObjectToProgram(statement, i + 1, bindArgs[i]);
- }
- }
- statement.execute();
- } catch (SQLiteDatabaseCorruptException e) {
- throw e;
- } finally {
- if (statement != null) {
- statement.close();
- }
- }
- }
-
-
- @Implementation
- public Cursor rawQuery (String sql, String[] selectionArgs) {
- return rawQueryWithFactory( new SQLiteDatabase.CursorFactory() {
- @Override
- public Cursor newCursor(SQLiteDatabase db,
- SQLiteCursorDriver masterQuery, String editTable, SQLiteQuery query) {
- return new SQLiteCursor(db, masterQuery, editTable, query);
- }
-
- }, sql, selectionArgs, null );
- }
-
- @Implementation
- public Cursor rawQueryWithFactory (SQLiteDatabase.CursorFactory cursorFactory, String sql, String[] selectionArgs, String editTable) {
- String sqlBody = sql;
- if (sql != null) {
- sqlBody = buildWhereClause(sql, selectionArgs);
- }
-
- ResultSet resultSet;
- try {
- SQLiteStatement stmt = compileStatement(sql);
-
- int numArgs = selectionArgs == null ? 0
- : selectionArgs.length;
- for (int i = 0; i < numArgs; i++) {
- stmt.bindString(i + 1, selectionArgs[i]);
- }
-
- resultSet = Robolectric.shadowOf(stmt).getStatement().executeQuery();
- } catch (SQLException e) {
- throw new RuntimeException("SQL exception in query", e);
- }
- //TODO: assert rawquery with args returns actual values
-
- SQLiteCursor cursor = (SQLiteCursor) cursorFactory.newCursor(null, null, null, null);
- shadowOf(cursor).setResultSet(resultSet, sqlBody);
- return cursor;
- }
-
- @Implementation
- public boolean isOpen() {
- return (connection != null);
- }
-
- @Implementation
- public void close() {
- if (!isOpen()) {
- return;
- }
- try {
- connection.close();
- connection = null;
- } catch (SQLException e) {
- throw new RuntimeException("SQL exception in close", e);
- }
- }
-
- @Implementation
- public void beginTransaction() {
- try {
- connection.setAutoCommit(false);
- } catch (SQLException e) {
- throw new RuntimeException("SQL exception in beginTransaction", e);
- } finally {
- inTransaction = true;
- }
- }
-
- @Implementation
- public void setTransactionSuccessful() {
- if (!isOpen()) {
- throw new IllegalStateException("connection is not opened");
- } else if (transactionSuccess) {
- throw new IllegalStateException("transaction already successfully");
- }
- transactionSuccess = true;
- }
-
- @Implementation
- public void endTransaction() {
- try {
- if (transactionSuccess) {
- transactionSuccess = false;
- connection.commit();
- } else {
- connection.rollback();
- }
- connection.setAutoCommit(true);
- } catch (SQLException e) {
- throw new RuntimeException("SQL exception in beginTransaction", e);
- } finally {
- inTransaction = false;
- }
- }
-
- @Implementation
- public boolean inTransaction() {
- return inTransaction;
- }
-
- /**
- * Allows tests cases to query the transaction state
- * @return
- */
- public boolean isTransactionSuccess() {
- return transactionSuccess;
- }
-
- /**
- * Allows test cases access to the underlying JDBC connection, for use in
- * setup or assertions.
- *
- * @return the connection
- */
- public Connection getConnection() {
- return connection;
- }
-
- @Implementation
- public SQLiteStatement compileStatement(String sql) throws SQLException {
- lock();
- String scrubbedSql= DatabaseConfig.getScrubSQL(sql);
- try {
- SQLiteStatement stmt = Robolectric.newInstanceOf(SQLiteStatement.class);
- Robolectric.shadowOf(stmt).init(realSQLiteDatabase, scrubbedSql);
- return stmt;
- } catch (Exception e){
- throw new RuntimeException(e);
- } finally {
- unlock();
- }
- }
-
- /**
- * @param closable
- */
- void addSQLiteClosable(SQLiteClosable closable) {
- lock();
- try {
- mPrograms.put(closable, null);
- } finally {
- unlock();
- }
- }
-
- void removeSQLiteClosable(SQLiteClosable closable) {
- lock();
- try {
- mPrograms.remove(closable);
- } finally {
- unlock();
- }
- }
-
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSQLiteOpenHelper.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSQLiteOpenHelper.java
deleted file mode 100644
index cbcdda093..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSQLiteOpenHelper.java
+++ /dev/null
@@ -1,58 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.content.Context;
-import android.database.sqlite.SQLiteDatabase;
-import android.database.sqlite.SQLiteDatabase.CursorFactory;
-import android.database.sqlite.SQLiteOpenHelper;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.internal.RealObject;
-
-/**
- * Shadow for {@code SQLiteOpenHelper}. Provides basic support for retrieving
- * databases and partially implements the subclass contract. (Currently,
- * support for {@code #onUpgrade} is missing).
- */
-@Implements(SQLiteOpenHelper.class)
-public class ShadowSQLiteOpenHelper {
-
- @RealObject private SQLiteOpenHelper realHelper;
- private static SQLiteDatabase database;
-
- public void __constructor__(Context context, String name, CursorFactory factory, int version) {
- if (database != null) {
- database.close();
- }
- database = null;
- }
-
- @Implementation
- public synchronized void close() {
- if (database != null) {
- database.close();
- }
- database = null;
- }
-
- @Implementation
- public synchronized SQLiteDatabase getReadableDatabase() {
- if (database == null) {
- database = SQLiteDatabase.openDatabase("path", null, 0);
- realHelper.onCreate(database);
- }
-
- realHelper.onOpen(database);
- return database;
- }
-
- @Implementation
- public synchronized SQLiteDatabase getWritableDatabase() {
- if (database == null) {
- database = SQLiteDatabase.openDatabase("path", null, 0);
- realHelper.onCreate(database);
- }
-
- realHelper.onOpen(database);
- return database;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSQLiteProgram.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSQLiteProgram.java
deleted file mode 100644
index d903bfe13..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSQLiteProgram.java
+++ /dev/null
@@ -1,150 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.database.sqlite.SQLiteDatabase;
-import android.database.sqlite.SQLiteProgram;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.internal.RealObject;
-
-import java.sql.Connection;
-import java.sql.PreparedStatement;
-import java.sql.SQLException;
-import java.sql.Statement;
-
-@Implements(SQLiteProgram.class)
-public abstract class ShadowSQLiteProgram {
- @RealObject SQLiteProgram realSQLiteProgram;
- protected SQLiteDatabase mDatabase;
- Connection connection;
- PreparedStatement actualDBstatement;
- public void init(SQLiteDatabase db, String sql) {
- mDatabase = db;
- connection = Robolectric.shadowOf(db).getConnection();
-
- try {
- actualDBstatement = connection.prepareStatement(sql,
- Statement.RETURN_GENERATED_KEYS);
- } catch (SQLException e) {
- throw new RuntimeException(e);
- }
- }
-
- /**
- * Bind a NULL value to this statement. The value remains bound until
- * {@link #clearBindings} is called.
- *
- * @param index The 1-based index to the parameter to bind null to
- */
- @Implementation
- public void bindNull(int index) {
- checkDatabaseIsOpen();
- try {
- // SQLite ignores typecode
- // typecode is also ignored in H2 when using the two parameter setNUll()
- actualDBstatement.setNull(index,java.sql.Types.NULL);
- } catch (SQLException e) {
- throw new RuntimeException(e);
- }
- }
-
- /**
- * Bind a long value to this statement. The value remains bound until
- * {@link #clearBindings} is called.
- *
- * @param index The 1-based index to the parameter to bind
- * @param value The value to bind
- */
- @Implementation
- public void bindLong(int index, long value) {
- checkDatabaseIsOpen();
-
- try {
- actualDBstatement.setLong(index,value);
- } catch (SQLException e) {
- throw new RuntimeException(e);
- }
- }
-
- private void checkDatabaseIsOpen() {
- if (!mDatabase.isOpen()) {
- throw new IllegalStateException("database " + mDatabase.getPath() + " already closed");
- }
- }
-
- public PreparedStatement getStatement() {
- return actualDBstatement;
- }
-
- /**
- * Bind a double value to this statement. The value remains bound until
- * {@link #clearBindings} is called.
- *
- * @param index The 1-based index to the parameter to bind
- * @param value The value to bind
- */
- @Implementation
- public void bindDouble(int index, double value) {
- checkDatabaseIsOpen();
- try {
- actualDBstatement.setDouble(index,value);
- } catch (SQLException e) {
- throw new RuntimeException(e);
- }
- }
-
- /**
- * Bind a String value to this statement. The value remains bound until
- * {@link #clearBindings} is called.
- *
- * @param index The 1-based index to the parameter to bind
- * @param value The value to bind
- */
- @Implementation
- public void bindString(int index, String value) {
- if (value == null) {
- throw new IllegalArgumentException("the bind value at index " + index + " is null");
- }
- checkDatabaseIsOpen();
- try {
- actualDBstatement.setString(index,value);
- } catch (SQLException e) {
- throw new RuntimeException(e);
- }
- }
-
- /**
- * Bind a byte array value to this statement. The value remains bound until
- * {@link #clearBindings} is called.
- *
- * @param index The 1-based index to the parameter to bind
- * @param value The value to bind
- */
- @Implementation
- public void bindBlob(int index, byte[] value) {
- if (value == null) {
- throw new IllegalArgumentException("the bind value at index " + index + " is null");
- }
- checkDatabaseIsOpen();
- try {
- actualDBstatement.setBytes(index,value);
- } catch (SQLException e) {
- throw new RuntimeException(e);
- }
-
- }
-
- /**
- * Clears all existing bindings. Unset bindings are treated as NULL.
- */
- @Implementation
- public void clearBindings() {
- checkDatabaseIsOpen();
-
- try {
- actualDBstatement.clearParameters();
- } catch (SQLException e) {
- throw new RuntimeException(e);
- }
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSQLiteQueryBuilder.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSQLiteQueryBuilder.java
deleted file mode 100644
index 5881b1b05..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSQLiteQueryBuilder.java
+++ /dev/null
@@ -1,50 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.database.sqlite.SQLiteQueryBuilder;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.util.Join;
-
-/**
- * Shadow for {@code SQLiteQueryBuilder}.
- */
-@Implements(SQLiteQueryBuilder.class)
-public class ShadowSQLiteQueryBuilder {
-
- @Implementation
- public static String buildQueryString(boolean distinct, String tables,
- String[] columns, String where, String groupBy, String having,
- String orderBy, String limit) {
-
- StringBuilder sb = new StringBuilder("SELECT ");
-
- if (distinct) {
- sb.append("DISTINCT ");
- }
-
- if (columns != null) {
- sb.append(Join.join(", ", (Object[]) columns));
- } else {
- sb.append("*");
- }
-
- sb.append(" FROM ");
- sb.append(tables);
-
- conditionallyAppend(sb, " WHERE ", where);
- conditionallyAppend(sb, " GROUP BY ", groupBy);
- conditionallyAppend(sb, " HAVING ", having);
- conditionallyAppend(sb, " ORDER BY ", orderBy);
- conditionallyAppend(sb, " LIMIT ", limit);
-
- return sb.toString();
- }
-
- private static void conditionallyAppend(StringBuilder sb, String keyword, String value) {
- if (value != null) {
- sb.append(keyword);
- sb.append(value);
- }
- }
-
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSQLiteStatement.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSQLiteStatement.java
deleted file mode 100644
index 2bbdce66e..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSQLiteStatement.java
+++ /dev/null
@@ -1,84 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.database.sqlite.SQLiteDatabase;
-import android.database.sqlite.SQLiteDoneException;
-import android.database.sqlite.SQLiteStatement;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-import java.sql.ResultSet;
-import java.sql.SQLException;
-
-@Implements(SQLiteStatement.class)
-public class ShadowSQLiteStatement extends ShadowSQLiteProgram {
- String mSql;
-
- public void init(SQLiteDatabase db, String sql) {
- super.init(db, sql);
- mSql = sql;
- }
-
- @Implementation
- public void execute() {
- if (!mDatabase.isOpen()) {
- throw new IllegalStateException("database " + mDatabase.getPath() + " already closed");
- }
- try {
- actualDBstatement.execute();
- } catch (SQLException e) {
- throw new RuntimeException(e);
- }
- }
-
- @Implementation
- public long executeInsert() {
- try {
- actualDBstatement.executeUpdate();
- ResultSet resultSet = actualDBstatement.getGeneratedKeys();
-
- if (resultSet.next()) {
- return resultSet.getLong(1);
- } else {
- throw new RuntimeException("Could not retrive generatedKeys");
- }
- } catch (SQLException e) {
- throw new RuntimeException(e);
- }
- }
-
- @Implementation
- public long simpleQueryForLong() {
- ResultSet rs;
- try {
- rs = actualDBstatement.executeQuery();
- rs.next();
- return rs.getLong(1);
- } catch (SQLException e) {
- handleException(e);
- throw new RuntimeException(e);
- }
- }
-
- @Implementation
- public String simpleQueryForString() {
- ResultSet rs;
- try {
- rs = actualDBstatement.executeQuery();
- rs.next();
- return rs.getString(1);
- } catch (SQLException e) {
- handleException(e);
- throw new RuntimeException(e);
- }
- }
-
- private void handleException(SQLException e) {
- if (e.getMessage().contains("No data is available")) {
- //if the query returns zero rows
- throw new SQLiteDoneException("No data is available");
- } else if (e.getMessage().contains("ResultSet closed")) {
- //if the query returns zero rows (SQLiteMap)
- throw new SQLiteDoneException("ResultSet closed,(probably, no data available)");
- }
- }
-} \ No newline at end of file
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSSLCertificateSocketFactory.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSSLCertificateSocketFactory.java
deleted file mode 100644
index f69c3bc71..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSSLCertificateSocketFactory.java
+++ /dev/null
@@ -1,21 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-import org.apache.http.conn.ssl.SSLSocketFactory;
-
-import android.net.SSLCertificateSocketFactory;
-import android.net.SSLSessionCache;
-
-@Implements(SSLCertificateSocketFactory.class)
-public class ShadowSSLCertificateSocketFactory {
-
- // TODO: Support more features when necessary
- @Implementation
- public static SSLSocketFactory getHttpSocketFactory(
- int handshakeTimeoutMillis,
- SSLSessionCache cache) {
- return SSLSocketFactory.getSocketFactory();
- }
-} \ No newline at end of file
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowScanResult.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowScanResult.java
deleted file mode 100644
index 31b66912d..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowScanResult.java
+++ /dev/null
@@ -1,39 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.net.wifi.ScanResult;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.internal.RealObject;
-
-@Implements(ScanResult.class)
-public class ShadowScanResult {
-
- @RealObject ScanResult realObject;
-
- public static ScanResult newInstance(String SSID, String BSSID, String caps, int level, int frequency) {
- ScanResult scanResult = Robolectric.newInstanceOf(ScanResult.class);
- scanResult.SSID = SSID;
- scanResult.BSSID = BSSID;
- scanResult.capabilities = caps;
- scanResult.level = level;
- scanResult.frequency = frequency;
- return scanResult;
- }
-
- @Override @Implementation
- public String toString() {
- return new StringBuffer()
- .append("SSID: ").append(valueOrNone(realObject.SSID))
- .append(", BSSID: ").append(valueOrNone(realObject.BSSID))
- .append(", capabilities: ").append(valueOrNone(realObject.capabilities))
- .append(", level: ").append(realObject.level)
- .append(", frequency: ").append(realObject.frequency)
- .toString();
- }
-
- private String valueOrNone(String value) {
- return value == null ? "<none>" : value;
- }
-}
-
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSeekBar.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSeekBar.java
deleted file mode 100644
index 31f368409..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSeekBar.java
+++ /dev/null
@@ -1,34 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.widget.SeekBar;
-
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.internal.RealObject;
-
-@Implements(SeekBar.class)
-public class ShadowSeekBar extends ShadowAbsSeekBar {
-
- @RealObject
- private SeekBar realSeekBar;
-
- private SeekBar.OnSeekBarChangeListener listener;
-
- @Implementation
- public void setOnSeekBarChangeListener(SeekBar.OnSeekBarChangeListener listener) {
- this.listener = listener;
- }
-
- @Override
- @Implementation
- public void setProgress(int progress) {
- super.setProgress(progress);
- if(listener != null) {
- listener.onProgressChanged( realSeekBar, progress, true);
- }
- }
-
- public SeekBar.OnSeekBarChangeListener getOnSeekBarChangeListener() {
- return this.listener;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSensorManager.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSensorManager.java
deleted file mode 100644
index 99bba883a..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSensorManager.java
+++ /dev/null
@@ -1,48 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.hardware.Sensor;
-import android.hardware.SensorEvent;
-import android.hardware.SensorEventListener;
-import android.hardware.SensorManager;
-import android.os.Handler;
-
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-import java.util.ArrayList;
-import java.util.List;
-
-
-@Implements(SensorManager.class)
-public class ShadowSensorManager {
-
- private ArrayList<SensorEventListener> listeners = new ArrayList<SensorEventListener>();
-
- public boolean forceListenersToFail = false;
-
- @Implementation
- public boolean registerListener(SensorEventListener listener, Sensor sensor, int rate) {
-
- if(forceListenersToFail)
- return false;
-
- if(!listeners.contains(listener))
- listeners.add(listener);
-
- return true;
- }
-
- @Implementation
- public void unregisterListener(SensorEventListener listener, Sensor sensor) {
- listeners.remove(listener);
- }
-
- public boolean hasListener(SensorEventListener listener) {
- return listeners.contains(listener);
- }
-
- public SensorEvent createSensorEvent() {
- return Robolectric.newInstanceOf(SensorEvent.class);
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowService.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowService.java
deleted file mode 100644
index 74a9cc1ca..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowService.java
+++ /dev/null
@@ -1,94 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.app.Application;
-import android.app.Notification;
-import android.app.Service;
-import android.content.Context;
-import android.content.ServiceConnection;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.internal.RealObject;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-
-@SuppressWarnings({"UnusedDeclaration"})
-@Implements(Service.class)
-public class ShadowService extends ShadowContextWrapper {
- @RealObject Service realService;
-
- private Notification lastForegroundNotification;
- private boolean selfStopped = false;
- private boolean unbindServiceShouldThrowIllegalArgument = false;
- private boolean foregroundStopped;
- private boolean notificationShouldRemoved;
-
- @Implementation
- public final Application getApplication() {
- return Robolectric.application;
- }
-
- @Implementation @Override
- public Context getApplicationContext() {
- return Robolectric.application;
- }
-
- @Implementation
- public void onDestroy() {
- assertNoBroadcastListenersRegistered();
- }
-
- @Implementation
- public void unbindService(ServiceConnection conn) {
- if (unbindServiceShouldThrowIllegalArgument) {
- throw new IllegalArgumentException();
- }
- }
-
- @Implementation
- public void stopSelf() {
- selfStopped = true;
- }
-
- public void setUnbindServiceShouldThrowIllegalArgument(boolean flag) {
- unbindServiceShouldThrowIllegalArgument = flag;
- }
-
- @Implementation
- public final void startForeground(int id, Notification notification) {
- lastForegroundNotification = notification;
- }
-
- @Implementation
- public void stopForeground(boolean removeNotification) {
- foregroundStopped = true;
- notificationShouldRemoved = removeNotification;
- }
-
- public Notification getLastForegroundNotification() {
- return lastForegroundNotification;
- }
-
- /**
- * Utility method that throws a {@code RuntimeException} if any {@code BroadcastListener}s are still registered.
- */
- public void assertNoBroadcastListenersRegistered() {
- ((ShadowApplication) shadowOf(getApplicationContext())).assertNoBroadcastListenersRegistered(realService, "Service");
- }
-
- /**
- * Non-Android accessor, to use in assertions.
- * @return
- */
- public boolean isStoppedBySelf() {
- return selfStopped;
- }
-
- public boolean isForegroundStopped() {
- return foregroundStopped;
- }
-
- public boolean getNotificationShouldRemoved() {
- return notificationShouldRemoved;
- }
-} \ No newline at end of file
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSettings.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSettings.java
deleted file mode 100644
index f8787eacd..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSettings.java
+++ /dev/null
@@ -1,160 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.content.ContentResolver;
-import android.provider.Settings;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-import java.util.HashMap;
-import java.util.Map;
-import java.util.WeakHashMap;
-
-/**
- * Shadow of {@code Settings} that allows the status of various System and Secure settings to be simulated, changed and
- * queried.
- */
-@SuppressWarnings({"UnusedDeclaration"})
-@Implements(Settings.class)
-public class ShadowSettings {
- @Implements(Settings.class)
- private static class SettingsImpl {
- private static final WeakHashMap<ContentResolver, Map<String, Object>> dataMap = new WeakHashMap<ContentResolver, Map<String, Object>>();
-
- @Implementation
- public static boolean putInt(ContentResolver cr, String name, int value) {
- get(cr).put(name, value);
- return true;
- }
-
- @Implementation
- public static int getInt(ContentResolver cr, String name, int def) {
- if (get(cr).get(name) instanceof Integer) {
- return (Integer) get(cr).get(name);
- } else {
- return def;
- }
- }
-
- @Implementation
- public static int getInt(ContentResolver cr, String name) throws Settings.SettingNotFoundException {
- if (get(cr).get(name) instanceof Integer) {
- return (Integer) get(cr).get(name);
- } else {
- throw new Settings.SettingNotFoundException(name);
- }
- }
-
- @Implementation
- public static boolean putString(ContentResolver cr, String name, String value) {
- get(cr).put(name, value);
- return true;
- }
-
- @Implementation
- public static String getString(ContentResolver cr, String name) {
- if (get(cr).get(name) instanceof String) {
- return (String) get(cr).get(name);
- } else {
- return null;
- }
- }
-
- @Implementation
- public static boolean putLong(ContentResolver cr, String name, long value) {
- get(cr).put(name, value);
- return true;
- }
-
- @Implementation
- public static long getLong(ContentResolver cr, String name, long def) {
- if (get(cr).get(name) instanceof Long) {
- return (Long) get(cr).get(name);
- } else {
- return def;
- }
- }
-
- @Implementation
- public static long getLong(ContentResolver cr, String name) throws Settings.SettingNotFoundException {
- if (get(cr).get(name) instanceof Long) {
- return (Long) get(cr).get(name);
- } else {
- throw new Settings.SettingNotFoundException(name);
- }
- }
-
- @Implementation
- public static boolean putFloat(ContentResolver cr, String name, float value) {
- get(cr).put(name, value);
- return true;
- }
-
- @Implementation
- public static float getFloat(ContentResolver cr, String name, float def) {
- if (get(cr).get(name) instanceof Float) {
- return (Float) get(cr).get(name);
- } else {
- return def;
- }
- }
-
- @Implementation
- public static float getFloat(ContentResolver cr, String name) throws Settings.SettingNotFoundException {
- if (get(cr).get(name) instanceof Float) {
- return (Float) get(cr).get(name);
- } else {
- throw new Settings.SettingNotFoundException(name);
- }
- }
-
- @Implementation
- private static Map<String, Object> get(ContentResolver cr) {
- Map<String, Object> map = dataMap.get(cr);
- if (map == null) {
- map = new HashMap<String, Object>();
- dataMap.put(cr, map);
- }
- return map;
- }
- }
-
- @Implements(Settings.System.class)
- public static class ShadowSystem extends SettingsImpl {
- }
-
- @Implements(Settings.Secure.class)
- public static class ShadowSecure extends SettingsImpl {
- }
-
- @Implements(Settings.Global.class)
- public static class ShadowGlobal extends SettingsImpl {
- }
-
- /**
- * Non-Android accessor that allows the value of the AIRPLANE_MODE_ON setting to be set.
- *
- * @param isAirplaneMode new status for airplane mode
- */
- public static void setAirplaneMode(boolean isAirplaneMode) {
- Settings.System.putInt(Robolectric.application.getContentResolver(), Settings.System.AIRPLANE_MODE_ON, isAirplaneMode ? 1 : 0);
- }
-
- /**
- * Non-Android accessor that allows the value of the WIFI_ON setting to be set.
- *
- * @param isOn new status for wifi mode
- */
- public static void setWifiOn(boolean isOn) {
- Settings.Secure.putInt(Robolectric.application.getContentResolver(), Settings.Secure.WIFI_ON, isOn ? 1 : 0);
- }
-
- /**
- * Non-Android accessor thatallows the value of the TIME_12_24 setting to be set.
- *
- * @param use24HourTimeFormat new status for the time setting
- */
- public static void set24HourTimeFormat(boolean use24HourTimeFormat) {
- Settings.System.putInt(Robolectric.application.getContentResolver(), Settings.System.TIME_12_24, use24HourTimeFormat ? 24 : 12);
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowShapeDrawable.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowShapeDrawable.java
deleted file mode 100644
index d7a8e3c01..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowShapeDrawable.java
+++ /dev/null
@@ -1,17 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.graphics.Paint;
-import android.graphics.drawable.ShapeDrawable;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-@Implements(ShapeDrawable.class)
-public class ShadowShapeDrawable extends ShadowDrawable {
-
- private Paint paint = new Paint();
-
- @Implementation
- public android.graphics.Paint getPaint() {
- return paint;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSignature.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSignature.java
deleted file mode 100644
index b643c1728..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSignature.java
+++ /dev/null
@@ -1,72 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-import android.content.pm.Signature;
-import android.os.Parcel;
-import android.os.Parcelable.Creator;
-
-import java.util.Arrays;
-
-@Implements(Signature.class)
-public class ShadowSignature {
-
- private byte[] mSignature;
-
- public void __constructor__(byte[] signature) {
- mSignature = signature.clone();
- }
-
- @Implementation
- public byte[] toByteArray() {
- byte[] bytes = new byte[mSignature.length];
- System.arraycopy(mSignature, 0, bytes, 0, mSignature.length);
- return bytes;
- }
-
- @Override
- @Implementation
- public boolean equals(Object obj) {
- if (this == obj) {
- return true;
- }
- if (!(obj instanceof Signature)) {
- return false;
- }
- ShadowSignature otherShadow = shadowOf((Signature) obj);
- return Arrays.equals(mSignature, otherShadow.mSignature);
- }
-
- @Override
- @Implementation
- public int hashCode() {
- return Arrays.hashCode(mSignature);
- }
-
- @Implementation
- public void writeToParcel(Parcel dest, int flags) {
- dest.writeByteArray(mSignature);
- }
-
- public static final Creator<Signature> CREATOR =
- new Creator<Signature>() {
- @Override
- public Signature createFromParcel(Parcel source) {
- byte[] signature = source.createByteArray();
- return new Signature(signature);
- }
-
- @Override
- public Signature[] newArray(int size) {
- return new Signature[size];
- }
- };
-
- public static void reset() {
- Robolectric.Reflection.setFinalStaticField(Signature.class, "CREATOR", CREATOR);
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSimpleCursorAdapter.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSimpleCursorAdapter.java
deleted file mode 100644
index 29c9322a7..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSimpleCursorAdapter.java
+++ /dev/null
@@ -1,407 +0,0 @@
-/*
- * Copyright (C) 2006 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.xtremelabs.robolectric.shadows;
-
-import android.content.Context;
-import android.database.Cursor;
-import android.net.Uri;
-import android.view.View;
-import android.view.ViewGroup;
-import android.widget.ImageView;
-import android.widget.SimpleCursorAdapter;
-import android.widget.SimpleCursorAdapter.CursorToStringConverter;
-import android.widget.SimpleCursorAdapter.ViewBinder;
-import android.widget.TextView;
-
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.internal.RealObject;
-
-/**
- * An easy adapter to map columns from a cursor to TextViews or ImageViews
- * defined in an XML file. You can specify which columns you want, which
- * views you want to display the columns, and the XML file that defines
- * the appearance of these views.
- *
- * Binding occurs in two phases. First, if a
- * {@link com.xtremelabs.robolectric.shadows.ShadowSimpleCursorAdapter.ViewBinder} is available,
- * {@link ViewBinder#setViewValue(android.view.View, android.database.Cursor, int)}
- * is invoked. If the returned value is true, binding has occured. If the
- * returned value is false and the view to bind is a TextView,
- * {@link #setViewText(TextView, String)} is invoked. If the returned value
- * is false and the view to bind is an ImageView,
- * {@link #setViewImage(ImageView, String)} is invoked. If no appropriate
- * binding can be found, an {@link IllegalStateException} is thrown.
- *
- * If this adapter is used with filtering, for instance in an
- * {@link android.widget.AutoCompleteTextView}, you can use the
- * {@link com.xtremelabs.robolectric.shadows.ShadowSimpleCursorAdapter.CursorToStringConverter} and the
- * {@link android.widget.FilterQueryProvider} interfaces
- * to get control over the filtering process. You can refer to
- * {@link #convertToString(android.database.Cursor)} and
- * {@link #runQueryOnBackgroundThread(CharSequence)} for more information.
- */
-@Implements(SimpleCursorAdapter.class)
-public class ShadowSimpleCursorAdapter extends ShadowResourceCursorAdapter {
- @RealObject private SimpleCursorAdapter realSimpleCursorAdapter;
-
- /**
- * A list of columns containing the data to bind to the UI.
- * This field should be made private, so it is hidden from the SDK.
- * {@hide}
- */
- protected int[] mFrom;
- /**
- * A list of View ids representing the views to which the data must be bound.
- * This field should be made private, so it is hidden from the SDK.
- * {@hide}
- */
- protected int[] mTo;
-
- private int mStringConversionColumn = -1;
- private CursorToStringConverter mCursorToStringConverter;
- private ViewBinder mViewBinder;
- private String[] mOriginalFrom;
-
- /**
- * Constructor.
- *
- * @param context The context where the ListView associated with this
- * SimpleListItemFactory is running
- * @param layout resource identifier of a layout file that defines the views
- * for this list item. The layout file should include at least
- * those named views defined in "to"
- * @param c The database cursor. Can be null if the cursor is not available yet.
- * @param from A list of column names representing the data to bind to the UI. Can be null
- * if the cursor is not available yet.
- * @param to The views that should display column in the "from" parameter.
- * These should all be TextViews. The first N views in this list
- * are given the values of the first N columns in the from
- * parameter. Can be null if the cursor is not available yet.
- */
- public void __constructor__(Context context, int layout, Cursor c, String[] from, int[] to) {
- super.__constructor__(context, layout, c);
- mTo = to;
- mOriginalFrom = from;
- findColumns(from);
- }
-
- /**
- * Binds all of the field names passed into the "to" parameter of the
- * constructor with their corresponding cursor columns as specified in the
- * "from" parameter.
- *
- * Binding occurs in two phases. First, if a
- * {@link com.xtremelabs.robolectric.shadows.ShadowSimpleCursorAdapter.ViewBinder} is available,
- * {@link ViewBinder#setViewValue(android.view.View, android.database.Cursor, int)}
- * is invoked. If the returned value is true, binding has occured. If the
- * returned value is false and the view to bind is a TextView,
- * {@link #setViewText(TextView, String)} is invoked. If the returned value is
- * false and the view to bind is an ImageView,
- * {@link #setViewImage(ImageView, String)} is invoked. If no appropriate
- * binding can be found, an {@link IllegalStateException} is thrown.
- *
- * @throws IllegalStateException if binding cannot occur
- *
- * @see android.widget.CursorAdapter#bindView(android.view.View,
- * android.content.Context, android.database.Cursor)
- * @see #getViewBinder()
- * @see #setViewBinder(com.xtremelabs.robolectric.shadows.ShadowSimpleCursorAdapter.ViewBinder)
- * @see #setViewImage(ImageView, String)
- * @see #setViewText(TextView, String)
- */
- @Implementation
- public void bindView(View view, Context context, Cursor cursor) {
- final ViewBinder binder = mViewBinder;
- final int count = mTo.length;
- final int[] from = mFrom;
- final int[] to = mTo;
-
- for (int i = 0; i < count; i++) {
- final View v = view.findViewById(to[i]);
- if (v != null) {
- boolean bound = false;
- if (binder != null) {
- bound = binder.setViewValue(v, cursor, from[i]);
- }
-
- if (!bound) {
- String text = cursor.getString(from[i]);
- if (text == null) {
- text = "";
- }
-
- if (v instanceof TextView) {
- setViewText((TextView) v, text);
- } else if (v instanceof ImageView) {
- setViewImage((ImageView) v, text);
- } else {
- throw new IllegalStateException(v.getClass().getName() + " is not a " +
- " view that can be bounds by this SimpleCursorAdapter");
- }
- }
- }
- }
- }
-
- /**
- * Returns the {@link ViewBinder} used to bind data to views.
- *
- * @return a ViewBinder or null if the binder does not exist
- *
- * @see #bindView(android.view.View, android.content.Context, android.database.Cursor)
- * @see #setViewBinder(com.xtremelabs.robolectric.shadows.ShadowSimpleCursorAdapter.ViewBinder)
- */
- @Implementation
- public ViewBinder getViewBinder() {
- return mViewBinder;
- }
-
- /**
- * Sets the binder used to bind data to views.
- *
- * @param viewBinder the binder used to bind data to views, can be null to
- * remove the existing binder
- *
- * @see #bindView(android.view.View, android.content.Context, android.database.Cursor)
- * @see #getViewBinder()
- */
- @Implementation
- public void setViewBinder(ViewBinder viewBinder) {
- mViewBinder = viewBinder;
- }
-
- /**
- * Called by bindView() to set the image for an ImageView but only if
- * there is no existing ViewBinder or if the existing ViewBinder cannot
- * handle binding to an ImageView.
- *
- * By default, the value will be treated as an image resource. If the
- * value cannot be used as an image resource, the value is used as an
- * image Uri.
- *
- * Intended to be overridden by Adapters that need to filter strings
- * retrieved from the database.
- *
- * @param v ImageView to receive an image
- * @param value the value retrieved from the cursor
- */
- @Implementation
- public void setViewImage(ImageView v, String value) {
- try {
- v.setImageResource(Integer.parseInt(value));
- } catch (NumberFormatException nfe) {
- v.setImageURI(Uri.parse(value));
- }
- }
-
- /**
- * Called by bindView() to set the text for a TextView but only if
- * there is no existing ViewBinder or if the existing ViewBinder cannot
- * handle binding to an TextView.
- *
- * Intended to be overridden by Adapters that need to filter strings
- * retrieved from the database.
- *
- * @param v TextView to receive text
- * @param text the text to be set for the TextView
- */
- @Implementation
- public void setViewText(TextView v, String text) {
- v.setText(text);
- }
-
- /**
- * Return the index of the column used to get a String representation
- * of the Cursor.
- *
- * @return a valid index in the current Cursor or -1
- *
- * @see android.widget.CursorAdapter#convertToString(android.database.Cursor)
- * @see #setStringConversionColumn(int)
- * @see #setCursorToStringConverter(com.xtremelabs.robolectric.shadows.ShadowSimpleCursorAdapter.CursorToStringConverter)
- * @see #getCursorToStringConverter()
- */
- @Implementation
- public int getStringConversionColumn() {
- return mStringConversionColumn;
- }
-
- /**
- * Defines the index of the column in the Cursor used to get a String
- * representation of that Cursor. The column is used to convert the
- * Cursor to a String only when the current CursorToStringConverter
- * is null.
- *
- * @param stringConversionColumn a valid index in the current Cursor or -1 to use the default
- * conversion mechanism
- *
- * @see android.widget.CursorAdapter#convertToString(android.database.Cursor)
- * @see #getStringConversionColumn()
- * @see #setCursorToStringConverter(com.xtremelabs.robolectric.shadows.ShadowSimpleCursorAdapter.CursorToStringConverter)
- * @see #getCursorToStringConverter()
- */
- @Implementation
- public void setStringConversionColumn(int stringConversionColumn) {
- mStringConversionColumn = stringConversionColumn;
- }
-
- /**
- * Returns the converter used to convert the filtering Cursor
- * into a String.
- *
- * @return null if the converter does not exist or an instance of
- * {@link com.xtremelabs.robolectric.shadows.ShadowSimpleCursorAdapter.CursorToStringConverter}
- *
- * @see #setCursorToStringConverter(com.xtremelabs.robolectric.shadows.ShadowSimpleCursorAdapter.CursorToStringConverter)
- * @see #getStringConversionColumn()
- * @see #setStringConversionColumn(int)
- * @see android.widget.CursorAdapter#convertToString(android.database.Cursor)
- */
- @Implementation
- public CursorToStringConverter getCursorToStringConverter() {
- return mCursorToStringConverter;
- }
-
- /**
- * Sets the converter used to convert the filtering Cursor
- * into a String.
- *
- * @param cursorToStringConverter the Cursor to String converter, or
- * null to remove the converter
- *
- * @see #setCursorToStringConverter(com.xtremelabs.robolectric.shadows.ShadowSimpleCursorAdapter.CursorToStringConverter)
- * @see #getStringConversionColumn()
- * @see #setStringConversionColumn(int)
- * @see android.widget.CursorAdapter#convertToString(android.database.Cursor)
- */
- @Implementation
- public void setCursorToStringConverter(CursorToStringConverter cursorToStringConverter) {
- mCursorToStringConverter = cursorToStringConverter;
- }
-
- /**
- * Returns a CharSequence representation of the specified Cursor as defined
- * by the current CursorToStringConverter. If no CursorToStringConverter
- * has been set, the String conversion column is used instead. If the
- * conversion column is -1, the returned String is empty if the cursor
- * is null or Cursor.toString().
- *
- * @param cursor the Cursor to convert to a CharSequence
- *
- * @return a non-null CharSequence representing the cursor
- */
- @Implementation
- public CharSequence convertToString(Cursor cursor) {
- if (mCursorToStringConverter != null) {
- return mCursorToStringConverter.convertToString(cursor);
- } else if (mStringConversionColumn > -1) {
- return cursor.getString(mStringConversionColumn);
- }
-
- return realSimpleCursorAdapter.convertToString(cursor);
- }
-
- /**
- * Create a map from an array of strings to an array of column-id integers in mCursor.
- * If mCursor is null, the array will be discarded.
- *
- * @param from the Strings naming the columns of interest
- */
- private void findColumns(String[] from) {
- if (mCursor != null) {
- int i;
- int count = from.length;
- if (mFrom == null || mFrom.length != count) {
- mFrom = new int[count];
- }
- for (i = 0; i < count; i++) {
- mFrom[i] = mCursor.getColumnIndexOrThrow(from[i]);
- }
- } else {
- mFrom = null;
- }
- }
-
- @Implementation
- public void changeCursor(Cursor c) {
- realSimpleCursorAdapter.changeCursor(c);
- // rescan columns in case cursor layout is different
- findColumns(mOriginalFrom);
- }
-
- /**
- * Change the cursor and change the column-to-view mappings at the same time.
- *
- * @param c The database cursor. Can be null if the cursor is not available yet.
- * @param from A list of column names representing the data to bind to the UI. Can be null
- * if the cursor is not available yet.
- * @param to The views that should display column in the "from" parameter.
- * These should all be TextViews. The first N views in this list
- * are given the values of the first N columns in the from
- * parameter. Can be null if the cursor is not available yet.
- */
- @Implementation
- public void changeCursorAndColumns(Cursor c, String[] from, int[] to) {
- mOriginalFrom = from;
- mTo = to;
- realSimpleCursorAdapter.changeCursor(c);
- findColumns(mOriginalFrom);
- }
-
- ///////////////////////////////////////////////////////////////////////////////////////////////
- // Implementation from CursorAdapter
-
- /**
- * @see android.widget.ListAdapter#getView(int, View, ViewGroup)
- */
- @Implementation
- public View getView(int position, View convertView, ViewGroup parent) {
- if (!mDataValid) {
- throw new IllegalStateException("this should only be called when the cursor is valid");
- }
- if (!mCursor.moveToPosition(position)) {
- throw new IllegalStateException("couldn't move cursor to position " + position);
- }
- View v;
- if (convertView == null) {
- v = newView(mContext, mCursor, parent);
- } else {
- v = convertView;
- }
- bindView(v, mContext, mCursor);
- return v;
- }
-
- @Implementation
- public View getDropDownView(int position, View convertView, ViewGroup parent) {
- if (mDataValid) {
- mCursor.moveToPosition(position);
- View v;
- if (convertView == null) {
- v = newDropDownView(mContext, mCursor, parent);
- } else {
- v = convertView;
- }
- bindView(v, mContext, mCursor);
- return v;
- } else {
- return null;
- }
- }
-
-} \ No newline at end of file
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSmsManager.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSmsManager.java
deleted file mode 100644
index 3c4cca763..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSmsManager.java
+++ /dev/null
@@ -1,89 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.app.PendingIntent;
-import android.telephony.SmsManager;
-import android.text.TextUtils;
-
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.internal.RealObject;
-
-@Implements(SmsManager.class)
-public class ShadowSmsManager {
-
- @RealObject
- private static SmsManager realManager = Robolectric.newInstanceOf(SmsManager.class);
-
- private TextSmsParams lastTextSmsParams = null;
-
- @Implementation
- public static SmsManager getDefault() {
- return realManager;
- }
-
- @Implementation
- public void sendTextMessage(
- String destinationAddress, String scAddress, String text,
- PendingIntent sentIntent, PendingIntent deliveryIntent) {
-
- if (TextUtils.isEmpty(destinationAddress))
- throw new IllegalArgumentException("Invalid destinationAddress");
-
- if (TextUtils.isEmpty(text))
- throw new IllegalArgumentException("Invalid message body");
-
- lastTextSmsParams = new TextSmsParams(
- destinationAddress,
- scAddress,
- text,
- sentIntent,
- deliveryIntent );
- }
-
- public TextSmsParams getLastSentTextMessageParams() {
- return lastTextSmsParams;
- }
-
- public void clearLastSentTextMessageParams() {
- lastTextSmsParams = null;
- }
-
- public class TextSmsParams {
- private String destinationAddress;
- private String scAddress;
- private String text;
- private PendingIntent sentIntent;
- private PendingIntent deliveryIntent;
-
- public TextSmsParams(
- String destinationAddress, String scAddress, String text,
- PendingIntent sentIntent, PendingIntent deliveryIntent) {
- this.destinationAddress = destinationAddress;
- this.scAddress = scAddress;
- this.text = text;
- this.sentIntent = sentIntent;
- this.deliveryIntent = deliveryIntent;
- }
-
- public String getDestinationAddress() {
- return destinationAddress;
- }
-
- public String getScAddress() {
- return scAddress;
- }
-
- public String getText() {
- return text;
- }
-
- public PendingIntent getSentIntent() {
- return sentIntent;
- }
-
- public PendingIntent getDeliveryIntent() {
- return deliveryIntent;
- }
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSpannableString.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSpannableString.java
deleted file mode 100644
index 5f1bafb24..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSpannableString.java
+++ /dev/null
@@ -1,86 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import java.lang.reflect.Array;
-import java.util.ArrayList;
-import java.util.HashMap;
-
-import android.text.SpannableString;
-
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-@Implements(SpannableString.class)
-public class ShadowSpannableString {
-
- private CharSequence text = "";
- private HashMap<Object, SpanHolder> spans = new HashMap<Object, SpanHolder>();
-
- public void __constructor__(CharSequence source) {
- text = source;
- }
-
- @Implementation
- public String toString() {
- return text.toString();
- }
-
- @Implementation
- public void setSpan(Object what, int start, int end, int flags) {
- spans.put(what, new SpanHolder(start, end, flags) );
- }
-
- @Implementation
- public void removeSpan(Object what) {
- spans.remove(what);
- }
-
- @Implementation
- public <T> T[] getSpans(int queryStart, int queryEnd, Class<T> kind) {
- ArrayList<T> retVal = new ArrayList<T>();
-
- for (Object s : spans.keySet()) {
- if (kind.isInstance(s)) {
- SpanHolder h = spans.get(s);
- if ( (h.start <= queryStart && h.end >= queryStart) ||
- (h.start <= queryEnd && h.end >= queryEnd) ||
- (h.start >= queryStart && h.end <= queryEnd) ) {
- retVal.add((T) s);
- }
- }
- }
- T[] array = (T[]) Array.newInstance(kind, retVal.size());
- return retVal.toArray(array);
- }
-
- @Implementation
- public int getSpanStart(Object what) {
- SpanHolder spanHolder = spans.get(what);
- if (spanHolder != null) {
- return spanHolder.start;
- } else {
- return -1;
- }
- }
-
- @Implementation
- public int getSpanEnd(Object what) {
- SpanHolder spanHolder = spans.get(what);
- if (spanHolder != null) {
- return spanHolder.end;
- } else {
- return -1;
- }
- }
-
- private class SpanHolder {
- public int start;
- public int end;
- public int flags;
-
- public SpanHolder(int start, int end, int flags) {
- this.start = start;
- this.end = end;
- this.flags = flags;
- }
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSpannableStringBuilder.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSpannableStringBuilder.java
deleted file mode 100644
index 89d631a6b..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSpannableStringBuilder.java
+++ /dev/null
@@ -1,72 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.text.Editable;
-import android.text.SpannableStringBuilder;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.internal.RealObject;
-
-/**
- * Shadow of {@code SpannableStringBuilder} implemented using a regular {@code StringBuilder}
- */
-@SuppressWarnings({"UnusedDeclaration"})
-@Implements(SpannableStringBuilder.class)
-public class ShadowSpannableStringBuilder implements CharSequence {
- @RealObject private SpannableStringBuilder realSpannableStringBuilder;
-
- private StringBuilder builder = new StringBuilder();
-
- public void __constructor__(CharSequence text) {
- builder.append(text);
- }
-
- @Implementation
- public SpannableStringBuilder append(char text) {
- builder.append(text);
- return realSpannableStringBuilder;
- }
-
- @Implementation
- public Editable replace(int st, int en, CharSequence text) {
- builder.replace(st, en, text.toString());
- return realSpannableStringBuilder;
- }
-
- @Implementation
- public Editable insert(int where, CharSequence text) {
- builder.insert(where, text.toString());
- return realSpannableStringBuilder;
- }
-
- @Implementation
- public SpannableStringBuilder append(CharSequence text) {
- builder.append(text.toString());
- return realSpannableStringBuilder;
- }
-
- @Implementation
- @Override public int length() {
- return builder.length();
- }
-
- @Implementation
- @Override public char charAt(int index) {
- return builder.charAt(index);
- }
-
- @Implementation
- @Override public CharSequence subSequence(int start, int end) {
- return builder.subSequence(start, end);
- }
-
- @Implementation
- public String toString() {
- return builder.toString();
- }
-
- @Implementation
- public SpannableStringBuilder delete( int start, int end ) {
- builder.delete( start, end );
- return realSpannableStringBuilder;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSparseArray.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSparseArray.java
deleted file mode 100644
index d46b3b77a..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSparseArray.java
+++ /dev/null
@@ -1,395 +0,0 @@
-/*
- * Copyright (C) 2006 The Android Open Source Project
- * Copyright (C) 2011 Eric Bowman
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.xtremelabs.robolectric.shadows;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-
-import java.util.Arrays;
-
-import android.util.SparseArray;
-
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.internal.RealObject;
-
-/**
- * Shadow implementation of SparseArray. Basically copied & pasted the
- * real SparseArray implementation, without depending on the ArrayUtils
- * class that is not in the SDK.
- *
- * @author Eric Bowman (ebowman@boboco.ie)
- * @since 2011-02-25 11:01
- */
-@SuppressWarnings({"JavaDoc"})
-@Implements(SparseArray.class)
-public class ShadowSparseArray<E> {
-
- private static final Object DELETED = new Object();
- private boolean mGarbage = false;
-
- @RealObject
- private SparseArray<E> realObject;
-
- public void __constructor__() {
- __constructor__(10);
- }
-
- /**
- * Creates a new SparseArray containing no mappings that will not
- * require any additional memory allocation to store the specified
- * number of mappings.
- */
- public void __constructor__(int initialCapacity) {
- initialCapacity = idealIntArraySize(initialCapacity);
- mKeys = new int[initialCapacity];
- mValues = new Object[initialCapacity];
- mSize = 0;
- }
-
-
-
- /**
- * Gets the Object mapped from the specified key, or <code>null</code>
- * if no such mapping has been made.
- */
- @Implementation
- public E get(int key) {
- return get(key, null);
- }
-
- /**
- * Gets the Object mapped from the specified key, or the specified Object
- * if no such mapping has been made.
- */
- @Implementation
- public E get(int key, E valueIfKeyNotFound) {
- int i = binarySearch(mKeys, 0, mSize, key);
-
- if (i < 0 || mValues[i] == DELETED) {
- return valueIfKeyNotFound;
- } else {
- //noinspection unchecked
- return (E) mValues[i];
- }
- }
-
- /**
- * Removes the mapping from the specified key, if there was any.
- */
- @Implementation
- public void delete(int key) {
- int i = binarySearch(mKeys, 0, mSize, key);
-
- if (i >= 0) {
- if (mValues[i] != DELETED) {
- mValues[i] = DELETED;
- mGarbage = true;
- }
- }
- }
-
- /**
- * Alias for {@link #delete(int)}.
- */
- @Implementation
- public void remove(int key) {
- delete(key);
- }
-
- private void gc() {
- // Log.e("SparseArray", "gc start with " + mSize);
-
- int n = mSize;
- int o = 0;
- int[] keys = mKeys;
- Object[] values = mValues;
-
- for (int i = 0; i < n; i++) {
- Object val = values[i];
-
- if (val != DELETED) {
- if (i != o) {
- keys[o] = keys[i];
- values[o] = val;
- }
-
- o++;
- }
- }
-
- mGarbage = false;
- mSize = o;
-
- // Log.e("SparseArray", "gc end with " + mSize);
- }
-
- /**
- * Adds a mapping from the specified key to the specified value,
- * replacing the previous mapping from the specified key if there
- * was one.
- */
- @Implementation
- public void put(int key, E value) {
- int i = binarySearch(mKeys, 0, mSize, key);
-
- if (i >= 0) {
- mValues[i] = value;
- } else {
- i = ~i;
-
- if (i < mSize && mValues[i] == DELETED) {
- mKeys[i] = key;
- mValues[i] = value;
- return;
- }
-
- if (mGarbage && mSize >= mKeys.length) {
- gc();
-
- // Search again because indices may have changed.
- i = ~binarySearch(mKeys, 0, mSize, key);
- }
-
- if (mSize >= mKeys.length) {
- int n = idealIntArraySize(mSize + 1);
-
- int[] nkeys = new int[n];
- Object[] nvalues = new Object[n];
-
- // Log.e("SparseArray", "grow " + mKeys.length + " to " + n);
- System.arraycopy(mKeys, 0, nkeys, 0, mKeys.length);
- System.arraycopy(mValues, 0, nvalues, 0, mValues.length);
-
- mKeys = nkeys;
- mValues = nvalues;
- }
-
- if (mSize - i != 0) {
- // Log.e("SparseArray", "move " + (mSize - i));
- System.arraycopy(mKeys, i, mKeys, i + 1, mSize - i);
- System.arraycopy(mValues, i, mValues, i + 1, mSize - i);
- }
-
- mKeys[i] = key;
- mValues[i] = value;
- mSize++;
- }
- }
-
- /**
- * Returns the number of key-value mappings that this SparseArray
- * currently stores.
- */
- @Implementation
- public int size() {
- if (mGarbage) {
- gc();
- }
-
- return mSize;
- }
-
- /**
- * Given an index in the range <code>0...size()-1</code>, returns
- * the key from the <code>index</code>th key-value mapping that this
- * SparseArray stores.
- */
- @Implementation
- public int keyAt(int index) {
- if (mGarbage) {
- gc();
- }
-
- return mKeys[index];
- }
-
- /**
- * Given an index in the range <code>0...size()-1</code>, returns
- * the value from the <code>index</code>th key-value mapping that this
- * SparseArray stores.
- */
- @Implementation
- public E valueAt(int index) {
- if (mGarbage) {
- gc();
- }
-
- //noinspection unchecked
- return (E) mValues[index];
- }
-
- /**
- * Given an index in the range <code>0...size()-1</code>, sets a new
- * value for the <code>index</code>th key-value mapping that this
- * SparseArray stores.
- */
- @Implementation
- public void setValueAt(int index, E value) {
- if (mGarbage) {
- gc();
- }
-
- mValues[index] = value;
- }
-
- /**
- * Returns the index for which {@link #keyAt} would return the
- * specified key, or a negative number if the specified
- * key is not mapped.
- */
- @Implementation
- public int indexOfKey(int key) {
- if (mGarbage) {
- gc();
- }
-
- return binarySearch(mKeys, 0, mSize, key);
- }
-
- /**
- * Returns an index for which {@link #valueAt} would return the
- * specified key, or a negative number if no keys map to the
- * specified value.
- * Beware that this is a linear search, unlike lookups by key,
- * and that multiple keys can map to the same value and this will
- * find only one of them.
- */
- @Implementation
- public int indexOfValue(E value) {
- if (mGarbage) {
- gc();
- }
-
- for (int i = 0; i < mSize; i++)
- if (mValues[i] == value)
- return i;
-
- return -1;
- }
-
- /**
- * Removes all key-value mappings from this SparseArray.
- */
- @Implementation
- public void clear() {
- int n = mSize;
- Object[] values = mValues;
-
- for (int i = 0; i < n; i++) {
- values[i] = null;
- }
-
- mSize = 0;
- mGarbage = false;
- }
-
- /**
- * Puts a key/value pair into the array, optimizing for the case where
- * the key is greater than all existing keys in the array.
- */
- @Implementation
- public void append(int key, E value) {
- if (mSize != 0 && key <= mKeys[mSize - 1]) {
- put(key, value);
- return;
- }
-
- if (mGarbage && mSize >= mKeys.length) {
- gc();
- }
-
- int pos = mSize;
- if (pos >= mKeys.length) {
- int n = idealIntArraySize(pos + 1);
-
- int[] nkeys = new int[n];
- Object[] nvalues = new Object[n];
-
- // Log.e("SparseArray", "grow " + mKeys.length + " to " + n);
- System.arraycopy(mKeys, 0, nkeys, 0, mKeys.length);
- System.arraycopy(mValues, 0, nvalues, 0, mValues.length);
-
- mKeys = nkeys;
- mValues = nvalues;
- }
-
- mKeys[pos] = key;
- mValues[pos] = value;
- mSize = pos + 1;
- }
-
- private static int binarySearch(int[] a, int start, int len, int key) {
- int high = start + len, low = start - 1, guess;
-
- while (high - low > 1) {
- guess = (high + low) / 2;
-
- if (a[guess] < key)
- low = guess;
- else
- high = guess;
- }
-
- if (high == start + len)
- return ~(start + len);
- else if (a[high] == key)
- return high;
- else
- return ~high;
- }
-
- private void checkIntegrity() {
- for (int i = 1; i < mSize; i++) {
- if (mKeys[i] <= mKeys[i - 1]) {
- for (int j = 0; j < mSize; j++) {
- System.err.println(
- "FAIL: " + j + ": " + mKeys[j] + " -> " + mValues[j]);
- }
-
- throw new RuntimeException();
- }
- }
- }
-
- public static int idealIntArraySize(int need) {
- return idealByteArraySize(need * 4) / 4;
- }
-
- public static int idealByteArraySize(int need) {
- for (int i = 4; i < 32; i++)
- if (need <= (1 << i) - 12)
- return (1 << i) - 12;
-
- return need;
- }
-
- @Implementation
- @Override
- public boolean equals(Object o) {
- if (o == null || o.getClass() != realObject.getClass())
- return false;
-
- ShadowSparseArray<?> target = (ShadowSparseArray<?>) shadowOf((SparseArray<?>) o);
- return Arrays.equals(mKeys, target.mKeys) && Arrays.deepEquals(mValues, target.mValues);
- }
-
- private int[] mKeys;
- private Object[] mValues;
- private int mSize;
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSparseBooleanArray.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSparseBooleanArray.java
deleted file mode 100644
index dfe148425..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSparseBooleanArray.java
+++ /dev/null
@@ -1,99 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.internal.RealObject;
-
-import android.util.SparseArray;
-import android.util.SparseBooleanArray;
-
-@Implements(SparseBooleanArray.class)
-public class ShadowSparseBooleanArray {
- private SparseArray<Boolean> sparseArray = new SparseArray<Boolean>();
-
- @RealObject
- private SparseBooleanArray realObject;
-
- @Implementation
- public boolean get(int key) {
- return get(key, false);
- }
-
- @Implementation
- public boolean get(int key, boolean valueIfKeyNotFound) {
- return sparseArray.get(key, valueIfKeyNotFound);
- }
-
- @Implementation
- public void delete(int key) {
- sparseArray.delete(key);
- }
-
- @Implementation
- public void put(int key, boolean value) {
- sparseArray.put(key, value);
- }
-
- @Implementation
- public int size() {
- return sparseArray.size();
- }
-
- @Implementation
- public int keyAt(int index) {
- return sparseArray.keyAt(index);
- }
-
- @Implementation
- public boolean valueAt(int index) {
- return sparseArray.valueAt(index);
- }
-
- @Implementation
- public int indexOfKey(int key) {
- return sparseArray.indexOfKey(key);
- }
-
- @Implementation
- public int indexOfValue(boolean value) {
- return sparseArray.indexOfValue(value);
- }
-
- @Implementation
- public void clear() {
- sparseArray.clear();
- }
-
- @Implementation
- public void append(int key, boolean value) {
- sparseArray.append(key, value);
- }
-
- @Implementation
- @Override
- public SparseBooleanArray clone() {
- SparseBooleanArray clone = new SparseBooleanArray();
- for (int i = 0, length = size(); i < length; i++) {
- clone.put(keyAt(i), valueAt(i));
- }
- return clone;
- }
-
- @Implementation
- @Override
- public int hashCode() {
- return sparseArray.hashCode();
- }
-
- @Implementation
- @Override
- public boolean equals(Object o) {
- if (o == null || o.getClass() != realObject.getClass())
- return false;
-
- ShadowSparseBooleanArray target = (ShadowSparseBooleanArray) shadowOf((SparseBooleanArray) o);
- return sparseArray.equals(target.sparseArray);
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSparseIntArray.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSparseIntArray.java
deleted file mode 100644
index fe7c8d185..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSparseIntArray.java
+++ /dev/null
@@ -1,62 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.util.SparseArray;
-import android.util.SparseIntArray;
-
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.internal.RealObject;
-
-@Implements(SparseIntArray.class)
-public class ShadowSparseIntArray {
-
- private SparseArray<Integer> sparseArray = new SparseArray<Integer>();
-
- @RealObject
- private SparseIntArray realObject;
-
- @Implementation
- public int get( int key ){
- return get( key, 0 );
- }
-
- @Implementation
- public int get(int key, int valueIfKeyNotFound){
- return sparseArray.get( key, valueIfKeyNotFound );
- }
-
- @Implementation
- public void put( int key, int value ){
- sparseArray.put( key, value );
- }
-
- @Implementation
- public int size() {
- return sparseArray.size();
- }
-
- @Implementation
- public int indexOfValue( int value ) {
- return sparseArray.indexOfValue( value );
- }
-
- @Implementation
- public int keyAt( int index ){
- return sparseArray.keyAt( index );
- }
-
- @Implementation
- public int valueAt( int index ){
- return sparseArray.valueAt( index );
- }
-
- @Implementation
- @Override
- public SparseIntArray clone() {
- SparseIntArray clone = new SparseIntArray();
- for (int i = 0, length = size(); i < length; i++) {
- clone.put( keyAt(i), valueAt(i) );
- }
- return clone;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSpinner.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSpinner.java
deleted file mode 100644
index 08037d322..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSpinner.java
+++ /dev/null
@@ -1,22 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.widget.Spinner;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-@SuppressWarnings({"UnusedDeclaration"})
-@Implements(Spinner.class)
-public class ShadowSpinner extends ShadowAbsSpinner {
-
- private CharSequence prompt;
-
- @Implementation
- public void setPrompt(CharSequence prompt) {
- this.prompt = prompt;
- }
-
- @Implementation
- public CharSequence getPrompt() {
- return prompt;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSslErrorHandler.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSslErrorHandler.java
deleted file mode 100644
index f24db96d5..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSslErrorHandler.java
+++ /dev/null
@@ -1,31 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.webkit.SslErrorHandler;
-
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-@Implements(SslErrorHandler.class)
-public class ShadowSslErrorHandler extends ShadowHandler {
-
- private boolean cancelCalled = false;
- private boolean proceedCalled = false;
-
- @Implementation
- public void cancel() {
- cancelCalled = true;
- }
-
- public boolean wasCancelCalled() {
- return cancelCalled;
- }
-
- @Implementation
- public void proceed() {
- proceedCalled = true;
- }
-
- public boolean wasProceedCalled() {
- return proceedCalled;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowStatFs.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowStatFs.java
deleted file mode 100644
index bea724ef0..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowStatFs.java
+++ /dev/null
@@ -1,71 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-import android.os.StatFs;
-
-import java.io.File;
-import java.util.HashMap;
-import java.util.Map;
-
-@Implements(StatFs.class)
-public class ShadowStatFs {
- public static final int BLOCK_SIZE = 4096;
- private static final Stats DEFAULT_STATS = new Stats(0, 0, 0);
- private static Map<String, Stats> stats = new HashMap<String, Stats>();
- private Stats stat;
-
- public void __constructor__(String path) {
- restat(path);
- }
-
- @Implementation
- public int getBlockSize() {
- return BLOCK_SIZE;
- }
-
- @Implementation
- public int getBlockCount() {
- return stat.blockCount;
- }
-
- @Implementation
- public int getFreeBlocks() {
- return stat.freeBlocks;
- }
-
- @Implementation
- public int getAvailableBlocks() {
- return stat.availableBlocks;
- }
-
- @Implementation
- public void restat(String path) {
- stat = stats.get(path);
- if (stat == null) {
- stat = DEFAULT_STATS;
- }
- }
-
- public static void registerStats(File path, int blockCount, int freeBlocks, int availableBlocks) {
- registerStats(path.getAbsolutePath(), blockCount, freeBlocks, availableBlocks);
- }
-
- public static void registerStats(String path, int blockCount, int freeBlocks, int availableBlocks) {
- stats.put(path, new Stats(blockCount, freeBlocks, availableBlocks));
- }
-
- public static void reset() {
- stats.clear();
- }
-
- private static class Stats {
- Stats(int blockCount, int freeBlocks, int availableBlocks) {
- this.blockCount = blockCount;
- this.freeBlocks = freeBlocks;
- this.availableBlocks = availableBlocks;
- }
- int blockCount, freeBlocks, availableBlocks;
- }
-} \ No newline at end of file
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowStateListDrawable.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowStateListDrawable.java
deleted file mode 100644
index 8922af8f6..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowStateListDrawable.java
+++ /dev/null
@@ -1,60 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.graphics.drawable.Drawable;
-import android.graphics.drawable.StateListDrawable;
-import android.util.StateSet;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-@Implements(StateListDrawable.class)
-public class ShadowStateListDrawable extends ShadowDrawable {
-
- private Map<Integer, Integer> stateToResource;
- private Map<List<Integer>, Drawable> stateToDrawable;
-
- public void __constructor__() {
- stateToResource = new HashMap<Integer, Integer>();
- stateToDrawable = new HashMap<List<Integer>, Drawable>();
- }
-
- public void addState(int stateId, int resId) {
- stateToResource.put(stateId, resId);
- }
-
- public int getResourceIdForState(int stateId) {
- return stateToResource.get(stateId);
- }
-
- @Implementation
- public void addState(int[] stateSet, Drawable drawable) {
- stateToDrawable.put(createStateList(stateSet), drawable);
- }
-
- /**
- * Non Android accessor to retrieve drawable added for a specific state.
- *
- * @param stateSet Int array describing the state
- * @return Drawable added via {@link #addState(int[], android.graphics.drawable.Drawable)}
- */
- public Drawable getDrawableForState(int[] stateSet) {
- return stateToDrawable.get(createStateList(stateSet));
- }
-
- private List<Integer> createStateList(int[] stateSet) {
- List<Integer> stateList = new ArrayList<Integer>();
- if (stateSet == StateSet.WILD_CARD) {
- stateList.add(-1);
- } else {
- for (int state : stateSet) {
- stateList.add(state);
- }
- }
-
- return stateList;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSurfaceView.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSurfaceView.java
deleted file mode 100644
index 217e48ba1..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSurfaceView.java
+++ /dev/null
@@ -1,62 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.graphics.Canvas;
-import android.graphics.Rect;
-import android.view.Surface;
-import android.view.SurfaceHolder;
-import android.view.SurfaceView;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-@Implements(SurfaceView.class)
-@SuppressWarnings({"UnusedDeclaration"})
-public class ShadowSurfaceView extends ShadowView {
- @Implementation
- public SurfaceHolder getHolder() {
- return new SurfaceHolder() {
- @Override public void addCallback(Callback callback) {
- }
-
- @Override public void removeCallback(Callback callback) {
- }
-
- @Override public boolean isCreating() {
- return false;
- }
-
- @Override public void setType(int i) {
- }
-
- @Override public void setFixedSize(int i, int i1) {
- }
-
- @Override public void setSizeFromLayout() {
- }
-
- @Override public void setFormat(int i) {
- }
-
- @Override public void setKeepScreenOn(boolean b) {
- }
-
- @Override public Canvas lockCanvas() {
- return null;
- }
-
- @Override public Canvas lockCanvas(Rect rect) {
- return null;
- }
-
- @Override public void unlockCanvasAndPost(Canvas canvas) {
- }
-
- @Override public Rect getSurfaceFrame() {
- return null;
- }
-
- @Override public Surface getSurface() {
- return null;
- }
- };
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSyncResult.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSyncResult.java
deleted file mode 100644
index 758af75e3..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowSyncResult.java
+++ /dev/null
@@ -1,91 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.internal.RealObject;
-
-import android.content.SyncResult;
-import android.content.SyncStats;
-
-import java.lang.reflect.Field;
-
-@Implements(SyncResult.class)
-public class ShadowSyncResult {
- @RealObject
- private SyncResult result;
-
- public void __constructor__() {
- try {
- Field f = SyncResult.class.getDeclaredField("stats");
- f.setAccessible(true);
- f.set(result, new SyncStats());
- } catch (NoSuchFieldException e) {
- throw new RuntimeException(e);
- } catch (IllegalAccessException e) {
- throw new RuntimeException(e);
- }
- }
-
- @Implementation
- public boolean hasSoftError() {
- return result.syncAlreadyInProgress || result.stats.numIoExceptions > 0;
- }
-
- @Implementation
- public boolean hasHardError() {
- return result.stats.numParseExceptions > 0
- || result.stats.numConflictDetectedExceptions > 0
- || result.stats.numAuthExceptions > 0
- || result.tooManyDeletions
- || result.tooManyRetries
- || result.databaseError;
- }
-
- @Implementation
- public boolean hasError() {
- return hasSoftError() || hasHardError();
- }
-
- @Implementation
- public boolean madeSomeProgress() {
- return ((result.stats.numDeletes > 0) && !result.tooManyDeletions)
- || result.stats.numInserts > 0
- || result.stats.numUpdates > 0;
- }
-
- @Implementation
- public void clear() {
- if (result.syncAlreadyInProgress) {
- throw new UnsupportedOperationException(
- "you are not allowed to clear the ALREADY_IN_PROGRESS SyncStats");
- }
- result.tooManyDeletions = false;
- result.tooManyRetries = false;
- result.databaseError = false;
- result.fullSyncRequested = false;
- result.partialSyncUnavailable = false;
- result.moreRecordsToGet = false;
- result.delayUntil = 0;
- result.stats.clear();
- }
-
-
- @Implements(SyncStats.class)
- public static class ShadowSyncStats {
- @RealObject
- private SyncStats stats;
-
- @Implementation
- public void clear() {
- stats.numAuthExceptions = 0;
- stats.numIoExceptions = 0;
- stats.numParseExceptions = 0;
- stats.numConflictDetectedExceptions = 0;
- stats.numInserts = 0;
- stats.numUpdates = 0;
- stats.numDeletes = 0;
- stats.numEntries = 0;
- stats.numSkippedEntries = 0;
- }
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowTabActivity.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowTabActivity.java
deleted file mode 100644
index 18ac47538..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowTabActivity.java
+++ /dev/null
@@ -1,28 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.app.TabActivity;
-import android.widget.TabHost;
-import android.widget.TabWidget;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.internal.RealObject;
-
-@SuppressWarnings({"UnusedDeclaration"})
-@Implements(TabActivity.class)
-public class ShadowTabActivity extends ShadowActivityGroup {
-
- @RealObject TabActivity realTabActivity;
- TabHost tabhost;
- @Implementation
- public TabHost getTabHost() {
- if (tabhost==null) {
- tabhost = new TabHost(realTabActivity);
- }
- return tabhost;
- }
-
- @Implementation
- public TabWidget getTabWidget() {
- return getTabHost().getTabWidget();
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowTabHost.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowTabHost.java
deleted file mode 100644
index 1d7671f90..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowTabHost.java
+++ /dev/null
@@ -1,122 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.R;
-import android.app.Activity;
-import android.view.View;
-import android.widget.TabHost;
-import android.widget.TabHost.TabSpec;
-import android.widget.TabWidget;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.internal.RealObject;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-
-@SuppressWarnings({"UnusedDeclaration"})
-@Implements(TabHost.class)
-public class ShadowTabHost extends ShadowFrameLayout {
- private List<TabHost.TabSpec> tabSpecs = new ArrayList<TabHost.TabSpec>();
- private TabHost.OnTabChangeListener listener;
- private int currentTab = -1;
-
- @RealObject
- TabHost realObject;
-
- @Implementation
- public android.widget.TabHost.TabSpec newTabSpec(java.lang.String tag) {
- TabSpec realTabSpec = Robolectric.newInstanceOf(TabHost.TabSpec.class);
- shadowOf(realTabSpec).setTag(tag);
- return realTabSpec;
- }
-
- @Implementation
- public void addTab(android.widget.TabHost.TabSpec tabSpec) {
- tabSpecs.add(tabSpec);
- View indicatorAsView = shadowOf(tabSpec).getIndicatorAsView();
- if (indicatorAsView != null) {
- realObject.addView(indicatorAsView);
- }
- }
-
- @Implementation
- public void setCurrentTab(int index) {
- currentTab = index;
- if (listener != null) {
- listener.onTabChanged(getCurrentTabTag());
- }
- }
-
- @Implementation
- public void setCurrentTabByTag(String tag) {
- for (int x = 0; x < tabSpecs.size(); x++) {
- TabSpec tabSpec = tabSpecs.get(x);
- if (tabSpec.getTag().equals(tag)) {
- currentTab = x;
- }
- }
- if (listener != null) {
- listener.onTabChanged(getCurrentTabTag());
- }
- }
-
- @Implementation
- public int getCurrentTab() {
- if (currentTab == -1 && tabSpecs.size() > 0) currentTab = 0;
- return currentTab;
- }
-
- public TabSpec getCurrentTabSpec() {
- return tabSpecs.get(getCurrentTab());
- }
-
- @Implementation
- public String getCurrentTabTag() {
- int i = getCurrentTab();
- if (i >= 0 && i < tabSpecs.size()) {
- return tabSpecs.get(i).getTag();
- }
- return null;
- }
-
- @Implementation
- public void setOnTabChangedListener(android.widget.TabHost.OnTabChangeListener listener) {
- this.listener = listener;
- }
-
- @Implementation
- public View getCurrentView() {
- ShadowTabSpec ts = Robolectric.shadowOf(getCurrentTabSpec());
- View v = ts.getContentView();
- if (v == null) {
- int viewId = ts.getContentViewId();
- if (getContext() instanceof Activity) {
- v = ((Activity) getContext()).findViewById(viewId);
- } else {
- return null;
- }
- }
- return v;
- }
-
- @Implementation
- public TabWidget getTabWidget() {
- if (context instanceof Activity) {
- return (TabWidget) ((Activity)context).findViewById(R.id.tabs);
- } else {
- return null;
- }
- }
-
- public TabHost.TabSpec getSpecByTag(String tag) {
- for (TabHost.TabSpec tabSpec : tabSpecs) {
- if (tag.equals(tabSpec.getTag())) {
- return tabSpec;
- }
- }
- return null;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowTabSpec.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowTabSpec.java
deleted file mode 100644
index 06d27fe92..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowTabSpec.java
+++ /dev/null
@@ -1,117 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.content.Intent;
-import android.graphics.drawable.Drawable;
-import android.view.View;
-import android.widget.TabHost;
-import android.widget.TabHost.TabContentFactory;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.internal.RealObject;
-
-@SuppressWarnings({"UnusedDeclaration"})
-@Implements(TabHost.TabSpec.class)
-public class ShadowTabSpec {
-
- @RealObject
- TabHost.TabSpec realObject;
- private String tag;
- private View indicatorView;
- private Intent intent;
- private int viewId;
- private View contentView;
- private CharSequence label;
- private Drawable icon;
-
- /**
- * Non-Android accessor, sets the tag on the TabSpec
- */
- public void setTag(String tag) {
- this.tag = tag;
- }
-
- @Implementation
- public java.lang.String getTag() {
- return tag;
- }
-
- /**
- * Non-Android accessor
- *
- * @return the view object set in a call to {@code TabSpec#setIndicator(View)}
- */
- public View getIndicatorAsView() {
- return this.indicatorView;
- }
-
- public String getIndicatorLabel() {
- return this.label.toString();
- }
-
- public Drawable getIndicatorIcon() {
- return this.icon;
- }
-
- /**
- * Same as GetIndicatorLabel()
- * @return
- */
- public String getText() {
- return label.toString();
- }
- @Implementation
- public TabHost.TabSpec setIndicator(View view) {
- this.indicatorView = view;
- return realObject;
- }
-
- @Implementation
- public TabHost.TabSpec setIndicator(CharSequence label) {
- this.label = label;
- return realObject;
- }
-
- @Implementation
- public TabHost.TabSpec setIndicator(CharSequence label, Drawable icon) {
- this.label = label;
- this.icon = icon;
- return realObject;
- }
-
- /**
- * Non-Android accessor
- *
- * @return the intent object set in a call to {@code TabSpec#setContent(Intent)}
- */
- public Intent getContentAsIntent() {
- return intent;
- }
-
- @Implementation
- public android.widget.TabHost.TabSpec setContent(Intent intent) {
- this.intent = intent;
- return realObject;
- }
-
- @Implementation
- public android.widget.TabHost.TabSpec setContent(TabContentFactory factory) {
- contentView = factory.createTabContent(this.tag);
- return realObject;
- }
-
-
- @Implementation
- public android.widget.TabHost.TabSpec setContent(int viewId) {
- this.viewId = viewId;
- return realObject;
- }
-
- public int getContentViewId() {
- return viewId;
- }
-
- public View getContentView() {
- return contentView;
- }
-
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowTelephonyManager.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowTelephonyManager.java
deleted file mode 100644
index a4899a4fa..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowTelephonyManager.java
+++ /dev/null
@@ -1,110 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.telephony.PhoneStateListener;
-import android.telephony.TelephonyManager;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-@Implements(TelephonyManager.class)
-public class ShadowTelephonyManager {
-
- private PhoneStateListener listener;
- private int eventFlags;
- private String deviceId;
- private String networkOperatorName;
- private String networkCountryIso;
- private String networkOperator;
- private boolean readPhoneStatePermission = true;
- private int phoneType = TelephonyManager.PHONE_TYPE_GSM;
- private String simCountryIso;
-
- @Implementation
- public void listen(PhoneStateListener listener, int events) {
- this.listener = listener;
- this.eventFlags = events;
- }
-
- /**
- * Non-Android accessor. Returns the most recent listener
- * passed to #listen().
- *
- * @return
- */
- public PhoneStateListener getListener() {
- return listener;
- }
-
- /**
- * Non-Android accessor. Returns the most recent flags
- * passed to #listen().
- * @return
- */
- public int getEventFlags() {
- return eventFlags;
- }
-
- @Implementation
- public String getDeviceId() {
- checkReadPhoneStatePermission();
- return deviceId;
- }
-
- public void setDeviceId(String newDeviceId) {
- deviceId = newDeviceId;
- }
-
- public void setNetworkOperatorName(String networkOperatorName) {
- this.networkOperatorName = networkOperatorName;
- }
-
- @Implementation
- public String getNetworkOperatorName() {
- return networkOperatorName;
- }
-
- public void setNetworkCountryIso(String networkCountryIso) {
- this.networkCountryIso = networkCountryIso;
- }
-
- @Implementation
- public String getNetworkCountryIso() {
- return networkCountryIso;
- }
-
- public void setNetworkOperator(String networkOperator) {
- this.networkOperator = networkOperator;
- }
-
- @Implementation
- public String getNetworkOperator() {
- return networkOperator;
- }
-
- @Implementation
- public String getSimCountryIso() {
- return simCountryIso;
- }
-
- public void setSimCountryIso(String simCountryIso) {
- this.simCountryIso = simCountryIso;
- }
-
- public void setReadPhoneStatePermission(boolean readPhoneStatePermission) {
- this.readPhoneStatePermission = readPhoneStatePermission;
- }
-
- private void checkReadPhoneStatePermission() {
- if (!readPhoneStatePermission) {
- throw new SecurityException();
- }
- }
-
- @Implementation
- public int getPhoneType() {
- return phoneType;
- }
-
- public void setPhoneType(int phoneType) {
- this.phoneType = phoneType;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowTextPaint.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowTextPaint.java
deleted file mode 100644
index 2364adc42..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowTextPaint.java
+++ /dev/null
@@ -1,13 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.text.TextPaint;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-@Implements(TextPaint.class)
-public class ShadowTextPaint extends ShadowPaint {
- @Implementation
- public float measureText(String text) {
- return text.length();
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowTextUtils.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowTextUtils.java
deleted file mode 100644
index abf5491fd..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowTextUtils.java
+++ /dev/null
@@ -1,75 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.text.TextUtils;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.util.Join;
-
-import java.util.Collection;
-
-@SuppressWarnings({"UnusedDeclaration"})
-@Implements(TextUtils.class)
-public class ShadowTextUtils {
- @Implementation
- public static CharSequence expandTemplate(CharSequence template,
- CharSequence... values) {
- String s = template.toString();
- for (int i = 0, valuesLength = values.length; i < valuesLength; i++) {
- CharSequence value = values[i];
- s = s.replace("^" + (i + 1), value);
- }
- return s;
- }
-
- @Implementation
- public static boolean isEmpty(CharSequence s) {
- return (s == null || s.length() == 0);
- }
-
- @Implementation
- public static int getTrimmedLength(CharSequence s) {
- int len = s.length();
-
- int start = 0;
- while (start < len && s.charAt(start) <= ' ') {
- start++;
- }
-
- int end = len;
- while (end > start && s.charAt(end - 1) <= ' ') {
- end--;
- }
-
- return end - start;
- }
-
- @Implementation
- public static String join(CharSequence delimiter, Iterable tokens) {
- return Join.join((String) delimiter, (Collection) tokens);
- }
-
- @Implementation
- public static String join(CharSequence delimiter, Object[] tokens) {
- return Join.join((String) delimiter, tokens);
- }
-
- @Implementation
- public static boolean isDigitsOnly(CharSequence str) {
- final int len = str.length();
- for (int i = 0; i < len; i++) {
- if (!Character.isDigit(str.charAt(i))) {
- return false;
- }
- }
- return true;
- }
-
- @Implementation
- public static String[] split(String text, String expression) {
- if(text.length() == 0) {
- return new String[]{};
- }
-
- return text.split(expression);
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowTextView.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowTextView.java
deleted file mode 100644
index 3027fcc4a..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowTextView.java
+++ /dev/null
@@ -1,603 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.content.Context;
-import android.graphics.Typeface;
-import android.graphics.drawable.Drawable;
-import android.text.Layout;
-import android.text.SpannableStringBuilder;
-import android.text.TextPaint;
-import android.text.TextWatcher;
-import android.text.method.MovementMethod;
-import android.text.method.TransformationMethod;
-import android.text.style.URLSpan;
-import android.text.util.Linkify;
-import android.view.KeyEvent;
-import android.view.MotionEvent;
-import android.view.inputmethod.EditorInfo;
-import android.widget.TextView;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import static android.view.View.VISIBLE;
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-import static com.xtremelabs.robolectric.Robolectric.shadowOf_;
-
-@SuppressWarnings({"UnusedDeclaration"})
-@Implements(TextView.class)
-public class ShadowTextView extends ShadowView {
- private CharSequence text = "";
- private CompoundDrawables compoundDrawablesImpl = new CompoundDrawables(0, 0, 0, 0);
- private Integer textColorHexValue;
- private Integer hintColorHexValue;
- private float textSize = 14.0f;
- private boolean autoLinkPhoneNumbers;
- private int autoLinkMask;
- private CharSequence hintText;
- private CharSequence errorText;
- private int compoundDrawablePadding;
- private MovementMethod movementMethod;
- private boolean linksClickable;
- private int gravity;
- private TextView.OnEditorActionListener onEditorActionListener;
- private int imeOptions = EditorInfo.IME_NULL;
- private int textAppearanceId;
- private TransformationMethod transformationMethod;
- private int inputType;
- protected int selectionStart = 0;
- protected int selectionEnd = 0;
- private Typeface typeface;
-
- private List<TextWatcher> watchers = new ArrayList<TextWatcher>();
- private List<Integer> previousKeyCodes = new ArrayList<Integer>();
- private List<KeyEvent> previousKeyEvents = new ArrayList<KeyEvent>();
- private Layout layout;
-
- @Override
- public void applyAttributes() {
- super.applyAttributes();
- applyTextAttribute();
- applyTextColorAttribute();
- applyHintAttribute();
- applyHintColorAttribute();
- applyCompoundDrawablesWithIntrinsicBoundsAttributes();
- }
-
- @Implementation(i18nSafe = false)
- public void setText(CharSequence text) {
- if (text == null) {
- text = "";
- }
-
- sendBeforeTextChanged(text);
-
- CharSequence oldValue = this.text;
- this.text = text;
-
- sendOnTextChanged(oldValue);
- sendAfterTextChanged();
- }
-
- @Implementation
- public final void append(CharSequence text) {
- boolean isSelectStartAtEnd = selectionStart == this.text.length();
- boolean isSelectEndAtEnd = selectionEnd == this.text.length();
- CharSequence oldValue = this.text;
- StringBuffer sb = new StringBuffer(this.text);
- sb.append(text);
-
- sendBeforeTextChanged(sb.toString());
- this.text = sb.toString();
-
- if (isSelectStartAtEnd) {
- selectionStart = this.text.length();
- }
- if (isSelectEndAtEnd) {
- selectionEnd = this.text.length();
- }
-
- sendOnTextChanged(oldValue);
- sendAfterTextChanged();
- }
-
- @Implementation
- public void setText(int textResourceId) {
- sendBeforeTextChanged(text);
-
- CharSequence oldValue = this.text;
- this.text = getResources().getText(textResourceId);
-
- sendOnTextChanged(oldValue);
- sendAfterTextChanged();
- }
-
- private void sendAfterTextChanged() {
- for (TextWatcher watcher : watchers) {
- watcher.afterTextChanged(new SpannableStringBuilder(getText()));
- }
- }
-
- private void sendOnTextChanged(CharSequence oldValue) {
- for (TextWatcher watcher : watchers) {
- watcher.onTextChanged(text, 0, oldValue.length(), text.length());
- }
- }
-
- private void sendBeforeTextChanged(CharSequence newValue) {
- for (TextWatcher watcher : watchers) {
- watcher.beforeTextChanged(this.text, 0, this.text.length(), newValue.length());
- }
- }
-
- @Implementation
- public CharSequence getText() {
- return text;
- }
-
- @Implementation
- public Typeface getTypeface() {
- return typeface;
- }
-
- @Implementation
- public void setTypeface(Typeface typeface) {
- this.typeface = typeface;
- }
-
- @Implementation
- public int length() {
- return text.length();
- }
-
- @Implementation
- public void setTextColor(int color) {
- textColorHexValue = color;
- }
-
- @Implementation
- public void setTextSize(float size) {
- textSize = size;
- }
-
- @Implementation
- public void setTextAppearance(Context context, int resid) {
- textAppearanceId = resid;
- }
-
- @Implementation
- public void setInputType(int type) {
- this.inputType = type;
- }
-
- @Implementation
- public int getInputType() {
- return this.inputType;
- }
-
- @Implementation
- public final void setHint(int resId) {
- this.hintText = getResources().getText(resId);
- }
-
- @Implementation(i18nSafe = false)
- public final void setHint(CharSequence hintText) {
- this.hintText = hintText;
- }
-
- @Implementation
- public CharSequence getHint() {
- return hintText;
- }
-
- @Implementation
- public final void setHintTextColor(int color) {
- hintColorHexValue = color;
- }
-
- @Implementation
- public final boolean getLinksClickable() {
- return linksClickable;
- }
-
- @Implementation
- public final void setLinksClickable(boolean whether) {
- linksClickable = whether;
- }
-
- @Implementation
- public final MovementMethod getMovementMethod() {
- return movementMethod;
- }
-
- @Implementation
- public final void setMovementMethod(MovementMethod movement) {
- movementMethod = movement;
- }
-
- @Implementation
- public URLSpan[] getUrls() {
- String[] words = text.toString().split("\\s+");
- List<URLSpan> urlSpans = new ArrayList<URLSpan>();
- for (String word : words) {
- if (word.startsWith("http://")) {
- urlSpans.add(new URLSpan(word));
- }
- }
- return urlSpans.toArray(new URLSpan[urlSpans.size()]);
- }
-
- @Implementation
- public final void setAutoLinkMask(int mask) {
- autoLinkMask = mask;
-
- autoLinkPhoneNumbers = (mask & Linkify.PHONE_NUMBERS) != 0;
- }
-
- @Implementation
- public void setCompoundDrawablesWithIntrinsicBounds(int left, int top, int right, int bottom) {
- compoundDrawablesImpl = new CompoundDrawables(left, top, right, bottom);
- }
-
- @Implementation
- public void setCompoundDrawablesWithIntrinsicBounds(Drawable left, Drawable top,
- Drawable right, Drawable bottom) {
- compoundDrawablesImpl = new CompoundDrawables(left, top, right, bottom);
- }
-
- @Implementation
- public void setCompoundDrawables(Drawable left, Drawable top, Drawable right, Drawable bottom) {
- compoundDrawablesImpl = new CompoundDrawables(left, top, right, bottom);
- }
-
- @Implementation
- public Drawable[] getCompoundDrawables() {
- if (compoundDrawablesImpl == null) {
- return new Drawable[]{null, null, null, null};
- }
- return new Drawable[]{
- compoundDrawablesImpl.leftDrawable,
- compoundDrawablesImpl.topDrawable,
- compoundDrawablesImpl.rightDrawable,
- compoundDrawablesImpl.bottomDrawable
- };
- }
-
- @Implementation
- public void setCompoundDrawablePadding(int compoundDrawablePadding) {
- this.compoundDrawablePadding = compoundDrawablePadding;
- }
-
- @Implementation
- public int getCompoundDrawablePadding() {
- return compoundDrawablePadding;
- }
-
- @Implementation
- public boolean onKeyDown(int keyCode, KeyEvent event) {
- previousKeyCodes.add(keyCode);
- previousKeyEvents.add(event);
- if (onKeyListener != null) {
- return onKeyListener.onKey(realView, keyCode, event);
- } else {
- return false;
- }
- }
-
- @Implementation
- public boolean onKeyUp(int keyCode, KeyEvent event) {
- previousKeyCodes.add(keyCode);
- previousKeyEvents.add(event);
- if (onKeyListener != null) {
- return onKeyListener.onKey(realView, keyCode, event);
- } else {
- return false;
- }
- }
-
- public int getPreviousKeyCode(int index) {
- return previousKeyCodes.get(index);
- }
-
- public KeyEvent getPreviousKeyEvent(int index) {
- return previousKeyEvents.get(index);
- }
-
- @Implementation
- public int getGravity() {
- return gravity;
- }
-
- @Implementation
- public void setGravity(int gravity) {
- this.gravity = gravity;
- }
-
-
- @Implementation
- public int getImeOptions() {
- return imeOptions;
- }
-
- @Implementation
- public void setImeOptions(int imeOptions) {
- this.imeOptions = imeOptions;
- }
-
- /**
- * Returns the text string of this {@code TextView}.
- * <p/>
- * Robolectric extension.
- */
- @Override
- public String innerText() {
- return (text == null || getVisibility() != VISIBLE) ? "" : text.toString();
- }
-
- @Implementation
- public void setError(CharSequence error) {
- errorText = error;
- }
-
- @Implementation
- public CharSequence getError() {
- return errorText;
- }
-
- @Override
- @Implementation
- public boolean equals(Object o) {
- return super.equals(shadowOf_(o));
- }
-
- @Override
- @Implementation
- public int hashCode() {
- return super.hashCode();
- }
-
- public CompoundDrawables getCompoundDrawablesImpl() {
- return compoundDrawablesImpl;
- }
-
- void setCompoundDrawablesImpl(CompoundDrawables compoundDrawablesImpl) {
- this.compoundDrawablesImpl = compoundDrawablesImpl;
- }
-
- public Integer getTextColorHexValue() {
- return textColorHexValue;
- }
-
- public int getTextAppearanceId() {
- return textAppearanceId;
- }
-
- public Integer getHintColorHexValue() {
- return hintColorHexValue;
- }
-
- @Implementation
- public float getTextSize() {
- return textSize;
- }
-
- public boolean isAutoLinkPhoneNumbers() {
- return autoLinkPhoneNumbers;
- }
-
- private void applyTextAttribute() {
- String text = attributeSet.getAttributeValue("android", "text");
- if (text != null) {
- if (text.startsWith("@string/")) {
- int textResId = attributeSet.getAttributeResourceValue("android", "text", 0);
- text = context.getResources().getString(textResId);
- }
- setText(text);
- }
- }
-
- private void applyTextColorAttribute() {
- String colorValue = attributeSet.getAttributeValue("android", "textColor");
- if (colorValue != null) {
- if (colorValue.startsWith("@color/") || colorValue.startsWith("@android:color/")) {
- int colorResId = attributeSet.getAttributeResourceValue("android", "textColor", 0);
- setTextColor(context.getResources().getColor(colorResId));
- } else if (colorValue.startsWith("#")) {
- int colorFromHex = (int) Long.valueOf(colorValue.replaceAll("#", ""), 16).longValue();
- setTextColor(colorFromHex);
- }
- }
- }
-
- private void applyHintAttribute() {
- String hint = attributeSet.getAttributeValue("android", "hint");
- if (hint != null) {
- if (hint.startsWith("@string/")) {
- int textResId = attributeSet.getAttributeResourceValue("android", "hint", 0);
- hint = context.getResources().getString(textResId);
-
- }
- setHint(hint);
- }
- }
-
- private void applyHintColorAttribute() {
- String colorValue = attributeSet.getAttributeValue("android", "hintColor");
- if (colorValue != null) {
- if (colorValue.startsWith("@color/") || colorValue.startsWith("@android:color/")) {
- int colorResId = attributeSet.getAttributeResourceValue("android", "hintColor", 0);
- setHintTextColor(context.getResources().getColor(colorResId));
- } else if (colorValue.startsWith("#")) {
- int colorFromHex = (int) Long.valueOf(colorValue.replaceAll("#", ""), 16).longValue();
- setHintTextColor(colorFromHex);
- }
- }
- }
-
- private void applyCompoundDrawablesWithIntrinsicBoundsAttributes() {
- setCompoundDrawablesWithIntrinsicBounds(
- attributeSet.getAttributeResourceValue("android", "drawableLeft", 0),
- attributeSet.getAttributeResourceValue("android", "drawableTop", 0),
- attributeSet.getAttributeResourceValue("android", "drawableRight", 0),
- attributeSet.getAttributeResourceValue("android", "drawableBottom", 0));
- }
-
- @Implementation
- public void setOnEditorActionListener(android.widget.TextView.OnEditorActionListener onEditorActionListener) {
- this.onEditorActionListener = onEditorActionListener;
- }
-
- public boolean triggerEditorAction(int imeAction) {
- if (onEditorActionListener != null) {
- return onEditorActionListener.onEditorAction((TextView) realView, imeAction, null);
- }
- return false;
- }
-
- @Implementation
- public void setTransformationMethod(TransformationMethod transformationMethod) {
- this.transformationMethod = transformationMethod;
- }
-
- @Implementation
- public TransformationMethod getTransformationMethod() {
- return transformationMethod;
- }
-
- @Implementation
- public void addTextChangedListener(TextWatcher watcher) {
- this.watchers.add(watcher);
- }
-
- @Implementation
- public void removeTextChangedListener(TextWatcher watcher) {
- this.watchers.remove(watcher);
- }
-
- @Implementation
- public TextPaint getPaint() {
- return new TextPaint();
- }
-
- @Implementation
- public Layout getLayout() {
- return this.layout;
- }
-
- public void setSelection(int index) {
- setSelection(index, index);
- }
-
- public void setSelection(int start, int end) {
- selectionStart = start;
- selectionEnd = end;
- }
-
- @Implementation
- public int getSelectionStart() {
- return selectionStart;
- }
-
- @Implementation
- public int getSelectionEnd() {
- return selectionEnd;
- }
-
- @Implementation
- public boolean onTouchEvent(MotionEvent event) {
- boolean superResult = super.onTouchEvent(event);
-
- if (movementMethod != null) {
- boolean handled = movementMethod.onTouchEvent(null, null, event);
-
- if (handled) {
- return true;
- }
- }
-
- return superResult;
- }
-
- /**
- * @return the list of currently registered watchers/listeners
- */
- public List<TextWatcher> getWatchers() {
- return watchers;
- }
-
- public void setLayout(Layout layout) {
- this.layout = layout;
- }
-
- public static class CompoundDrawables {
- public Drawable leftDrawable;
- public Drawable topDrawable;
- public Drawable rightDrawable;
- public Drawable bottomDrawable;
-
- public CompoundDrawables(Drawable left, Drawable top, Drawable right, Drawable bottom) {
- leftDrawable = left;
- topDrawable = top;
- rightDrawable = right;
- bottomDrawable = bottom;
- }
-
- public CompoundDrawables(int left, int top, int right, int bottom) {
- leftDrawable = left != 0 ? ShadowDrawable.createFromResourceId(left) : null;
- topDrawable = top != 0 ? ShadowDrawable.createFromResourceId(top) : null;
- rightDrawable = right != 0 ? ShadowDrawable.createFromResourceId(right) : null;
- bottomDrawable = bottom != 0 ? ShadowDrawable.createFromResourceId(bottom) : null;
- }
-
- @Override
- public boolean equals(Object o) {
- if (this == o) return true;
- if (o == null || getClass() != o.getClass()) return false;
-
- CompoundDrawables that = (CompoundDrawables) o;
-
- if (getBottom() != that.getBottom()) return false;
- if (getLeft() != that.getLeft()) return false;
- if (getRight() != that.getRight()) return false;
- if (getTop() != that.getTop()) return false;
-
- return true;
- }
-
- @Override
- public int hashCode() {
- int result = getLeft();
- result = 31 * result + getTop();
- result = 31 * result + getRight();
- result = 31 * result + getBottom();
- return result;
- }
-
- @Override
- public String toString() {
- return "CompoundDrawables{" +
- "left=" + getLeft() +
- ", top=" + getTop() +
- ", right=" + getRight() +
- ", bottom=" + getBottom() +
- '}';
- }
-
- public int getLeft() {
- return shadowOf(leftDrawable).getLoadedFromResourceId();
- }
-
- public int getTop() {
- return shadowOf(topDrawable).getLoadedFromResourceId();
- }
-
- public int getRight() {
- return shadowOf(rightDrawable).getLoadedFromResourceId();
- }
-
- public int getBottom() {
- return shadowOf(bottomDrawable).getLoadedFromResourceId();
- }
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowTime.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowTime.java
deleted file mode 100755
index c8bbaf260..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowTime.java
+++ /dev/null
@@ -1,502 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-
-import android.text.format.Time;
-import android.util.TimeFormatException;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.internal.RealObject;
-
-import java.lang.reflect.Constructor;
-import java.lang.reflect.InvocationTargetException;
-import java.text.ParseException;
-import java.text.SimpleDateFormat;
-import java.util.*;
-
-@Implements(Time.class)
-public class ShadowTime {
- @RealObject
- private Time time;
-
- private static final long SECOND_IN_MILLIS = 1000;
- private static final long MINUTE_IN_MILLIS = SECOND_IN_MILLIS * 60;
- private static final long HOUR_IN_MILLIS = MINUTE_IN_MILLIS * 60;
- private static final long DAY_IN_MILLIS = HOUR_IN_MILLIS * 24;
-
- public void __constructor__() {
- __constructor__(getCurrentTimezone());
- }
-
- public void __constructor__(String timezone) {
- if (timezone == null) {
- throw new NullPointerException("timezone is null!");
- }
- time.timezone = timezone;
- time.year = 1970;
- time.monthDay = 1;
- time.isDst = -1;
- }
-
- public void __constructor__(Time other) {
- set(other);
- }
-
- @Implementation
- public void set(Time other) {
- time.timezone = other.timezone;
- time.second = other.second;
- time.minute = other.minute;
- time.hour = other.hour;
- time.monthDay = other.monthDay;
- time.month = other.month;
- time.year = other.year;
- time.weekDay = other.weekDay;
- time.yearDay = other.yearDay;
- time.isDst = other.isDst;
- time.gmtoff = other.gmtoff;
- }
-
- @Implementation
- public void setToNow() {
- set(System.currentTimeMillis());
- }
-
-
- @Implementation
- public static boolean isEpoch(Time time) {
- long millis = time.toMillis(true);
- return getJulianDay(millis, 0) == Time.EPOCH_JULIAN_DAY;
- }
-
-
- @Implementation
- public static int getJulianDay(long millis, long gmtoff) {
- long offsetMillis = gmtoff * 1000;
- long julianDay = (millis + offsetMillis) / DAY_IN_MILLIS;
- return (int) julianDay + Time.EPOCH_JULIAN_DAY;
- }
-
- @Implementation
- public long setJulianDay(int julianDay) {
- // Don't bother with the GMT offset since we don't know the correct
- // value for the given Julian day. Just get close and then adjust
- // the day.
- //long millis = (julianDay - EPOCH_JULIAN_DAY) * DateUtils.DAY_IN_MILLIS;
- long millis = (julianDay - Time.EPOCH_JULIAN_DAY) * DAY_IN_MILLIS;
- set(millis);
-
- // Figure out how close we are to the requested Julian day.
- // We can't be off by more than a day.
- int approximateDay = getJulianDay(millis, time.gmtoff);
- int diff = julianDay - approximateDay;
- time.monthDay += diff;
-
- // Set the time to 12am and re-normalize.
- time.hour = 0;
- time.minute = 0;
- time.second = 0;
- millis = time.normalize(true);
- return millis;
- }
-
- @Implementation
- public void set(long millis) {
- Calendar c = getCalendar();
- c.setTimeInMillis(millis);
- set(
- c.get(Calendar.SECOND),
- c.get(Calendar.MINUTE),
- c.get(Calendar.HOUR_OF_DAY),
- c.get(Calendar.DAY_OF_MONTH),
- c.get(Calendar.MONTH),
- c.get(Calendar.YEAR)
- );
- }
-
- @Implementation
- public long toMillis(boolean ignoreDst) {
- Calendar c = getCalendar();
- return c.getTimeInMillis();
- }
-
- @Implementation
- public void set(int second, int minute, int hour, int monthDay, int month, int year) {
- time.second = second;
- time.minute = minute;
- time.hour = hour;
- time.monthDay = monthDay;
- time.month = month;
- time.year = year;
- time.weekDay = 0;
- time.yearDay = 0;
- time.isDst = -1;
- time.gmtoff = 0;
- }
-
- @Implementation
- public void set(int monthDay, int month, int year) {
- set(0, 0, 0, monthDay, month, year);
- }
-
- @Implementation
- public void clear(String timezone) {
- if (timezone == null) {
- throw new NullPointerException("timezone is null!");
- }
- time.timezone = timezone;
- time.allDay = false;
- time.second = 0;
- time.minute = 0;
- time.hour = 0;
- time.monthDay = 0;
- time.month = 0;
- time.year = 0;
- time.weekDay = 0;
- time.yearDay = 0;
- time.gmtoff = 0;
- time.isDst = -1;
- }
-
- @Implementation
- public static String getCurrentTimezone() {
- return TimeZone.getDefault().getID();
- }
-
- @Implementation
- public static int compare(Time a, Time b) {
- long ams = a.toMillis(false);
- long bms = b.toMillis(false);
- if (ams == bms) {
- return 0;
- } else if (ams < bms) {
- return -1;
- } else {
- return 1;
- }
- }
-
- @Implementation
- public boolean before(Time other) {
- return Time.compare(time, other) < 0;
- }
-
- @Implementation
- public boolean after(Time other) {
- return Time.compare(time, other) > 0;
- }
-
- @Implementation
- public boolean parse(String timeString) {
- TimeZone tz;
- if (timeString.endsWith("Z")) {
- timeString = timeString.substring(0, timeString.length() - 1);
- tz = TimeZone.getTimeZone("UTC");
- } else {
- tz = TimeZone.getTimeZone(time.timezone);
- }
- SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd'T'HHmmss", Locale.ENGLISH);
- SimpleDateFormat dfShort = new SimpleDateFormat("yyyyMMdd", Locale.ENGLISH);
- df.setTimeZone(tz);
- dfShort.setTimeZone(tz);
- time.timezone = tz.getID();
- try {
- set(df.parse(timeString).getTime());
- } catch (ParseException e) {
- try {
- set(dfShort.parse(timeString).getTime());
- } catch (ParseException e2) {
- throwTimeFormatException();
- }
- }
- return "UTC".equals(tz.getID());
- }
-
- @Implementation
- public String format(String format) {
- Strftime strftime = new Strftime(format, Locale.getDefault());
- strftime.setTimeZone(TimeZone.getTimeZone(time.timezone));
- return strftime.format(new Date(toMillis(false)));
- }
-
- @Implementation
- public String format2445() {
- return format("%Y%m%dT%H%M%S");
- }
-
- @Implementation
- public String format3339(boolean allDay) {
- if (allDay) {
- return format("%Y-%m-%d");
- } else if ("UTC".equals(time.timezone)) {
- return format("%Y-%m-%dT%H:%M:%S.000Z");
- } else {
- String base = format("%Y-%m-%dT%H:%M:%S.000");
- String sign = (time.gmtoff < 0) ? "-" : "+";
- int offset = (int) Math.abs(time.gmtoff);
- int minutes = (offset % 3600) / 60;
- int hours = offset / 3600;
- return String.format("%s%s%02d:%02d", base, sign, hours, minutes);
- }
- }
-
- private void throwTimeFormatException() {
- try {
- Constructor<TimeFormatException> c = TimeFormatException.class.getDeclaredConstructor();
- c.setAccessible(true);
- throw c.newInstance();
- } catch (InvocationTargetException e) {
- throw new RuntimeException(e);
- } catch (InstantiationException e) {
- throw new RuntimeException(e);
- } catch (IllegalAccessException e) {
- throw new RuntimeException(e);
- } catch (NoSuchMethodException e) {
- throw new RuntimeException(e);
- }
- }
-
- private Calendar getCalendar() {
- Calendar c = Calendar.getInstance(TimeZone.getTimeZone(time.timezone));
- c.set(time.year, time.month, time.monthDay, time.hour, time.minute, time.second);
- c.set(Calendar.MILLISECOND, 0);
- return c;
- }
-
- // taken from org.apache.catalina.util.Strftime.java
- // see http://javasourcecode.org/html/open-source/tomcat/tomcat-6.0.32/org/apache/catalina/util/Strftime.java.html
- /*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
- public static class Strftime {
- protected static Properties translate;
- protected SimpleDateFormat simpleDateFormat;
-
- /**
- * Initialize our pattern translation
- */
- static {
- translate = new Properties();
- translate.put("a", "EEE");
- translate.put("A", "EEEE");
- translate.put("b", "MMM");
- translate.put("B", "MMMM");
- translate.put("c", "EEE MMM d HH:mm:ss yyyy");
-
- //There's no way to specify the century in SimpleDateFormat. We don't want to hard-code
- //20 since this could be wrong for the pre-2000 files.
- //translate.put("C", "20");
- translate.put("d", "dd");
- translate.put("D", "MM/dd/yy");
- translate.put("e", "dd"); //will show as '03' instead of ' 3'
- translate.put("F", "yyyy-MM-dd");
- translate.put("g", "yy");
- translate.put("G", "yyyy");
- translate.put("H", "HH");
- translate.put("h", "MMM");
- translate.put("I", "hh");
- translate.put("j", "DDD");
- translate.put("k", "HH"); //will show as '07' instead of ' 7'
- translate.put("l", "hh"); //will show as '07' instead of ' 7'
- translate.put("m", "MM");
- translate.put("M", "mm");
- translate.put("n", "\n");
- translate.put("p", "a");
- translate.put("P", "a"); //will show as pm instead of PM
- translate.put("r", "hh:mm:ss a");
- translate.put("R", "HH:mm");
- //There's no way to specify this with SimpleDateFormat
- //translate.put("s","seconds since ecpoch");
- translate.put("S", "ss");
- translate.put("t", "\t");
- translate.put("T", "HH:mm:ss");
- //There's no way to specify this with SimpleDateFormat
- //translate.put("u","day of week ( 1-7 )");
-
- //There's no way to specify this with SimpleDateFormat
- //translate.put("U","week in year with first sunday as first day...");
-
- translate.put("V", "ww"); //I'm not sure this is always exactly the same
-
- //There's no way to specify this with SimpleDateFormat
- //translate.put("W","week in year with first monday as first day...");
-
- //There's no way to specify this with SimpleDateFormat
- //translate.put("w","E");
- translate.put("X", "HH:mm:ss");
- translate.put("x", "MM/dd/yy");
- translate.put("y", "yy");
- translate.put("Y", "yyyy");
- translate.put("Z", "z");
- translate.put("z", "Z");
- translate.put("%", "%");
- }
-
-
- /**
- * Create an instance of this date formatting class
- *
- * @see #Strftime(String, Locale)
- */
- public Strftime(String origFormat) {
- String convertedFormat = convertDateFormat(origFormat);
- simpleDateFormat = new SimpleDateFormat(convertedFormat);
- }
-
- /**
- * Create an instance of this date formatting class
- *
- * @param origFormat the strftime-style formatting string
- * @param locale the locale to use for locale-specific conversions
- */
- public Strftime(String origFormat, Locale locale) {
- String convertedFormat = convertDateFormat(origFormat);
- simpleDateFormat = new SimpleDateFormat(convertedFormat, locale);
- }
-
- /**
- * Format the date according to the strftime-style string given in the constructor.
- *
- * @param date the date to format
- * @return the formatted date
- */
- public String format(Date date) {
- return simpleDateFormat.format(date);
- }
-
- /**
- * Get the timezone used for formatting conversions
- *
- * @return the timezone
- */
- public TimeZone getTimeZone() {
- return simpleDateFormat.getTimeZone();
- }
-
- /**
- * Change the timezone used to format dates
- *
- * @see SimpleDateFormat#setTimeZone
- */
- public void setTimeZone(TimeZone timeZone) {
- simpleDateFormat.setTimeZone(timeZone);
- }
-
- /**
- * Search the provided pattern and get the C standard
- * Date/Time formatting rules and convert them to the
- * Java equivalent.
- *
- * @param pattern The pattern to search
- * @return The modified pattern
- */
- protected String convertDateFormat(String pattern) {
- boolean inside = false;
- boolean mark = false;
- boolean modifiedCommand = false;
-
- StringBuffer buf = new StringBuffer();
-
- for (int i = 0; i < pattern.length(); i++) {
- char c = pattern.charAt(i);
-
- if (c == '%' && !mark) {
- mark = true;
- } else {
- if (mark) {
- if (modifiedCommand) {
- //don't do anything--we just wanted to skip a char
- modifiedCommand = false;
- mark = false;
- } else {
- inside = translateCommand(buf, pattern, i, inside);
- //It's a modifier code
- if (c == 'O' || c == 'E') {
- modifiedCommand = true;
- } else {
- mark = false;
- }
- }
- } else {
- if (!inside && c != ' ') {
- //We start a literal, which we need to quote
- buf.append("'");
- inside = true;
- }
-
- buf.append(c);
- }
- }
- }
-
- if (buf.length() > 0) {
- char lastChar = buf.charAt(buf.length() - 1);
-
- if (lastChar != '\'' && inside) {
- buf.append('\'');
- }
- }
- return buf.toString();
- }
-
- protected String quote(String str, boolean insideQuotes) {
- String retVal = str;
- if (!insideQuotes) {
- retVal = '\'' + retVal + '\'';
- }
- return retVal;
- }
-
- /**
- * Try to get the Java Date/Time formatting associated with
- * the C standard provided.
- *
- * @param buf The buffer
- * @param pattern The date/time pattern
- * @param index The char index
- * @param oldInside Flag value
- * @return True if new is inside buffer
- */
- protected boolean translateCommand(StringBuffer buf, String pattern, int index, boolean oldInside) {
- char firstChar = pattern.charAt(index);
- boolean newInside = oldInside;
-
- //O and E are modifiers, they mean to present an alternative representation of the next char
- //we just handle the next char as if the O or E wasn't there
- if (firstChar == 'O' || firstChar == 'E') {
- if (index + 1 < pattern.length()) {
- newInside = translateCommand(buf, pattern, index + 1, oldInside);
- } else {
- buf.append(quote("%" + firstChar, oldInside));
- }
- } else {
- String command = translate.getProperty(String.valueOf(firstChar));
-
- //If we don't find a format, treat it as a literal--That's what apache does
- if (command == null) {
- buf.append(quote("%" + firstChar, oldInside));
- } else {
- //If we were inside quotes, close the quotes
- if (oldInside) {
- buf.append('\'');
- }
- buf.append(command);
- newInside = false;
- }
- }
- return newInside;
- }
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowToast.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowToast.java
deleted file mode 100644
index f0bf9d484..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowToast.java
+++ /dev/null
@@ -1,148 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.content.Context;
-import android.view.View;
-import android.widget.TextView;
-import android.widget.Toast;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.internal.RealObject;
-
-import java.util.List;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-
-/**
- * Shadow of {@code Toast} that tracks {@code Toast} requests. Hear hear! (*clink*)
- */
-@SuppressWarnings({"UnusedDeclaration"})
-@Implements(Toast.class)
-public class ShadowToast {
- private String text;
- private int duration;
- private int gravity;
- private View view;
-
- @RealObject Toast toast;
-
- @Implementation
- public static Toast makeText(Context context, int resId, int duration) {
- return makeText(context, context.getResources().getString(resId), duration);
- }
-
- @Implementation(i18nSafe=false)
- public static Toast makeText(Context context, CharSequence text, int duration) {
- Toast toast = new Toast(null);
- toast.setDuration(duration);
- shadowOf(toast).text = text.toString();
- return toast;
- }
-
- @Implementation
- public void show() {
- Robolectric.getShadowApplication().getShownToasts().add(toast);
- }
-
- @Implementation
- public void setView(View view) {
- this.view = view;
- }
-
- @Implementation
- public View getView() {
- return view;
- }
-
- @Implementation
- public void setGravity(int gravity, int xOffset, int yOffset) {
- this.gravity = gravity;
- }
-
- @Implementation
- public int getGravity() {
- return gravity;
- }
-
- @Implementation
- public void setDuration(int duration) {
- this.duration = duration;
- }
-
- @Implementation
- public int getDuration() {
- return duration;
- }
-
- /**
- * Non-Android accessor that discards the recorded {@code Toast}s
- */
- public static void reset() {
- Robolectric.getShadowApplication().getShownToasts().clear();
- }
-
- /**
- * Non-Android accessor that returns the number of {@code Toast} requests that have been made during this test run
- * or since {@link #reset()} has been called.
- *
- * @return the number of {@code Toast} requests that have been made during this test run
- * or since {@link #reset()} has been called.
- */
- public static int shownToastCount() {
- return Robolectric.getShadowApplication().getShownToasts().size();
- }
-
- /**
- * Non-Android query method that returns whether or not a particular custom {@code Toast} has been shown.
- *
- * @param message the message to search for
- * @param layoutResourceIdToCheckForMessage
- * the id of the resource that contains the toast messages
- * @return whether the {@code Toast} was requested
- */
- public static boolean showedCustomToast(CharSequence message, int layoutResourceIdToCheckForMessage) {
- for (Toast toast : Robolectric.getShadowApplication().getShownToasts()) {
- String text = ((TextView) toast.getView().findViewById(layoutResourceIdToCheckForMessage)).getText().toString();
- if (text.equals(message.toString())) {
- return true;
- }
- }
- return false;
- }
-
- /**
- * query method that returns whether or not a particular {@code Toast} has been shown.
- *
- * @param message the message to search for
- * @return whether the {@code Toast} was requested
- */
- public static boolean showedToast(CharSequence message) {
- for (Toast toast : Robolectric.getShadowApplication().getShownToasts()) {
- String text = shadowOf(toast).text;
- if (text != null && text.equals(message.toString())) {
- return true;
- }
- }
- return false;
- }
-
- /**
- * Non-Android accessor that returns the text of the most recently shown {@code Toast}
- *
- * @return the text of the most recently shown {@code Toast}
- */
- public static String getTextOfLatestToast() {
- List<Toast> shownToasts = Robolectric.getShadowApplication().getShownToasts();
- return (shownToasts.size() == 0) ? null : shadowOf(shownToasts.get(shownToasts.size() - 1)).text;
- }
-
- /**
- * Non-Android accessor that returns the most recently shown {@code Toast}
- *
- * @return the most recently shown {@code Toast}
- */
- public static Toast getLatestToast() {
- List<Toast> shownToasts = Robolectric.getShadowApplication().getShownToasts();
- return (shownToasts.size() == 0) ? null : shownToasts.get(shownToasts.size() - 1);
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowTranslateAnimation.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowTranslateAnimation.java
deleted file mode 100644
index f0beafe03..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowTranslateAnimation.java
+++ /dev/null
@@ -1,74 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.view.animation.TranslateAnimation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-@SuppressWarnings({"UnusedDeclaration"})
-@Implements(TranslateAnimation.class)
-public class ShadowTranslateAnimation extends ShadowAnimation {
-
- private int fromXType;
- private float fromXValue;
- private int toXType;
- private float toXValue;
- private int fromYType;
- private float fromYValue;
- private int toYType;
- private float toYValue;
-
- public void __constructor__(float fromXValue, float toXValue,
- float fromYValue, float toYValue) {
- this.fromXType = TranslateAnimation.ABSOLUTE;
- this.fromXValue = fromXValue;
- this.toXType = TranslateAnimation.ABSOLUTE;
- this.toXValue = toXValue;
- this.fromYType = TranslateAnimation.ABSOLUTE;
- this.fromYValue = fromYValue;
- this.toYType = TranslateAnimation.ABSOLUTE;
- this.toYValue = toYValue;
- }
-
- public void __constructor__(int fromXType, float fromXValue, int toXType, float toXValue,
- int fromYType, float fromYValue, int toYType, float toYValue) {
- this.fromXType = fromXType;
- this.fromXValue = fromXValue;
- this.toXType = toXType;
- this.toXValue = toXValue;
- this.fromYType = fromYType;
- this.fromYValue = fromYValue;
- this.toYType = toYType;
- this.toYValue = toYValue;
- }
-
- public int getFromXType() {
- return fromXType;
- }
-
- public float getFromXValue() {
- return fromXValue;
- }
-
- public int getToXType() {
- return toXType;
- }
-
- public float getToXValue() {
- return toXValue;
- }
-
- public int getFromYType() {
- return fromYType;
- }
-
- public float getFromYValue() {
- return fromYValue;
- }
-
- public int getToYType() {
- return toYType;
- }
-
- public float getToYValue() {
- return toYValue;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowTypedArray.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowTypedArray.java
deleted file mode 100644
index 48731482a..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowTypedArray.java
+++ /dev/null
@@ -1,61 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.content.res.Resources;
-import android.content.res.TypedArray;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-@SuppressWarnings({"UnusedDeclaration"})
-@Implements(TypedArray.class)
-public class ShadowTypedArray {
- @Implementation
- public Resources getResources() {
- return Robolectric.application.getResources();
- }
-
- @Implementation
- public boolean getBoolean(int index, boolean defValue) {
- return defValue;
- }
-
- @Implementation
- public float getFloat(int index, float defValue) {
- return defValue;
- }
-
- @Implementation
- public int getInt(int index, int defValue) {
- return defValue;
- }
-
- @Implementation
- public int getInteger(int index, int defValue) {
- return defValue;
- }
-
- @Implementation
- public float getDimension(int index, float defValue) {
- return defValue;
- }
-
- @Implementation
- public int getDimensionPixelOffset(int index, int defValue) {
- return defValue;
- }
-
- @Implementation
- public int getDimensionPixelSize(int index, int defValue) {
- return defValue;
- }
-
- @Implementation
- public int getLayoutDimension(int index, int defValue) {
- return defValue;
- }
-
- @Implementation
- public int getResourceId(int index, int defValue) {
- return defValue;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowTypedValue.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowTypedValue.java
deleted file mode 100644
index 512706c44..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowTypedValue.java
+++ /dev/null
@@ -1,218 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.util.DisplayMetrics;
-import android.util.TypedValue;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.internal.RealObject;
-
-import static android.util.TypedValue.*;
-
-
-/**
- * Portions of this file were copied from the Android source code,
- * licenced under the Apache License, Version 2.0
- *
- * http://www.google.com/codesearch/p?hl=en#uX1GffpyOZk/core/java/android/util/TypedValue.java
- */
-
-@SuppressWarnings({"UnusedDeclaration"})
-@Implements(TypedValue.class)
-public class ShadowTypedValue {
-
- @RealObject TypedValue typedValue;
-
- @Implementation
- public final float getFloat() {
- return Float.intBitsToFloat(typedValue.data);
- }
-
- private static final float MANTISSA_MULT =
- 1.0f / (1<<TypedValue.COMPLEX_MANTISSA_SHIFT);
- private static final float[] RADIX_MULTS = new float[] {
- 1.0f*MANTISSA_MULT, 1.0f/(1<<7)*MANTISSA_MULT,
- 1.0f/(1<<15)*MANTISSA_MULT, 1.0f/(1<<23)*MANTISSA_MULT
- };
-
- @Implementation
- public static float complexToFloat(int complex)
- {
- return (complex&(TypedValue.COMPLEX_MANTISSA_MASK
- <<TypedValue.COMPLEX_MANTISSA_SHIFT))
- * RADIX_MULTS[(complex>>TypedValue.COMPLEX_RADIX_SHIFT)
- & TypedValue.COMPLEX_RADIX_MASK];
- }
-
- @Implementation
- public static float complexToDimension(int data, DisplayMetrics metrics)
- {
- return applyDimension(
- (data>>COMPLEX_UNIT_SHIFT)&COMPLEX_UNIT_MASK,
- complexToFloat(data),
- metrics);
- }
-
- @Implementation
- public static int complexToDimensionPixelOffset(int data,
- DisplayMetrics metrics)
- {
- return (int)applyDimension(
- (data>>COMPLEX_UNIT_SHIFT)&COMPLEX_UNIT_MASK,
- complexToFloat(data),
- metrics);
- }
-
- @Implementation
- public static int complexToDimensionPixelSize(int data,
- DisplayMetrics metrics)
- {
- final float value = complexToFloat(data);
- final float f = applyDimension(
- (data>>COMPLEX_UNIT_SHIFT)&COMPLEX_UNIT_MASK,
- value,
- metrics);
- final int res = (int)(f+0.5f);
- if (res != 0) return res;
- if (value == 0) return 0;
- if (value > 0) return 1;
- return -1;
- }
-
- @Implementation
- public static float complexToDimensionNoisy(int data, DisplayMetrics metrics)
- {
- float res = complexToDimension(data, metrics);
- System.out.println(
- "Dimension (0x" + ((data>>TypedValue.COMPLEX_MANTISSA_SHIFT)
- & TypedValue.COMPLEX_MANTISSA_MASK)
- + "*" + (RADIX_MULTS[(data>>TypedValue.COMPLEX_RADIX_SHIFT)
- & TypedValue.COMPLEX_RADIX_MASK] / MANTISSA_MULT)
- + ")" + DIMENSION_UNIT_STRS[(data>>COMPLEX_UNIT_SHIFT)
- & COMPLEX_UNIT_MASK]
- + " = " + res);
- return res;
- }
-
- @Implementation
- public static float applyDimension(int unit, float value, DisplayMetrics metrics) {
- switch (unit) {
- case COMPLEX_UNIT_PX:
- return value;
- case COMPLEX_UNIT_DIP:
- return value * metrics.density;
- case COMPLEX_UNIT_SP:
- return value * metrics.scaledDensity;
- case COMPLEX_UNIT_PT:
- return value * metrics.xdpi * (1.0f / 72);
- case COMPLEX_UNIT_IN:
- return value * metrics.xdpi;
- case COMPLEX_UNIT_MM:
- return value * metrics.xdpi * (1.0f / 25.4f);
- }
- return 0;
- }
-
- @Implementation
- public float getDimension(DisplayMetrics metrics)
- {
- return complexToDimension(typedValue.data, metrics);
- }
-
- @Implementation
- public static float complexToFraction(int data, float base, float pbase)
- {
- switch ((data>>COMPLEX_UNIT_SHIFT)&COMPLEX_UNIT_MASK) {
- case COMPLEX_UNIT_FRACTION:
- return complexToFloat(data) * base;
- case COMPLEX_UNIT_FRACTION_PARENT:
- return complexToFloat(data) * pbase;
- }
- return 0;
- }
-
- @Implementation
- public float getFraction(float base, float pbase)
- {
- return complexToFraction(typedValue.data, base, pbase);
- }
-
- @Implementation
- public final CharSequence coerceToString()
- {
- int t = typedValue.type;
- if (t == TYPE_STRING) {
- return typedValue.string;
- }
- return coerceToString(t, typedValue.data);
- }
-
- private static final String[] DIMENSION_UNIT_STRS = new String[] {
- "px", "dip", "sp", "pt", "in", "mm"
- };
- private static final String[] FRACTION_UNIT_STRS = new String[] {
- "%", "%p"
- };
-
- @Implementation
- public static final String coerceToString(int type, int data)
- {
- switch (type) {
- case TYPE_NULL:
- return null;
- case TYPE_REFERENCE:
- return "@" + data;
- case TYPE_ATTRIBUTE:
- return "?" + data;
- case TYPE_FLOAT:
- return Float.toString(Float.intBitsToFloat(data));
- case TYPE_DIMENSION:
- return Float.toString(complexToFloat(data)) + DIMENSION_UNIT_STRS[
- (data>>COMPLEX_UNIT_SHIFT)&COMPLEX_UNIT_MASK];
- case TYPE_FRACTION:
- return Float.toString(complexToFloat(data)*100) + FRACTION_UNIT_STRS[
- (data>>COMPLEX_UNIT_SHIFT)&COMPLEX_UNIT_MASK];
- case TYPE_INT_HEX:
- return "0x" + Integer.toHexString(data);
- case TYPE_INT_BOOLEAN:
- return data != 0 ? "true" : "false";
- }
-
- if (type >= TYPE_FIRST_COLOR_INT && type <= TYPE_LAST_COLOR_INT) {
- return "#" + Integer.toHexString(data);
- } else if (type >= TYPE_FIRST_INT && type <= TYPE_LAST_INT) {
- return Integer.toString(data);
- }
-
- return null;
- }
-
- @Implementation
- public void setTo(TypedValue other)
- {
- typedValue.type = other.type;
- typedValue.string = other.string;
- typedValue.data = other.data;
- typedValue.assetCookie = other.assetCookie;
- typedValue.resourceId = other.resourceId;
- typedValue.density = other.density;
- }
-
- @Implementation
- public String toString()
- {
- StringBuilder sb = new StringBuilder();
- sb.append("TypedValue{t=0x").append(Integer.toHexString(typedValue.type));
- sb.append("/d=0x").append(Integer.toHexString(typedValue.data));
- if (typedValue.type == TYPE_STRING) {
- sb.append(" \"").append(typedValue.string != null ? typedValue.string : "<null>").append("\"");
- }
- if (typedValue.assetCookie != 0) {
- sb.append(" a=").append(typedValue.assetCookie);
- }
- if (typedValue.resourceId != 0) {
- sb.append(" r=0x").append(Integer.toHexString(typedValue.resourceId));
- }
- sb.append("}");
- return sb.toString();
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowURLSpan.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowURLSpan.java
deleted file mode 100644
index b4519f5c8..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowURLSpan.java
+++ /dev/null
@@ -1,20 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.text.style.URLSpan;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-@SuppressWarnings({"UnusedDeclaration"})
-@Implements(URLSpan.class)
-public class ShadowURLSpan {
- private String url;
-
- public void __constructor__(String url) {
- this.url = url;
- }
-
- @Implementation
- public String getURL() {
- return url;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowUriMatcher.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowUriMatcher.java
deleted file mode 100644
index 0e16db0a3..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowUriMatcher.java
+++ /dev/null
@@ -1,116 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.List;
-
-import android.content.UriMatcher;
-import android.net.Uri;
-
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-@Implements(UriMatcher.class)
-public class ShadowUriMatcher {
-
- public static class MatchNode {
- public int code = UriMatcher.NO_MATCH;
- public HashMap<String, MatchNode> map = new HashMap<String, ShadowUriMatcher.MatchNode>();
- public MatchNode number;
- public MatchNode text;
-
- public MatchNode(int code) {
- this.code = code;
- }
- }
-
- public MatchNode rootNode;
-
- public void __constructor__(int code) {
- rootNode = new MatchNode(code);
- }
-
- @Implementation
- public void addURI(String authority, String path, int code) {
- MatchNode authNode = rootNode.map.get(authority);
- if (authNode == null) {
- authNode = new MatchNode(rootNode.code);
- rootNode.map.put(authority, authNode);
- }
-
- String[] segments = path.split("/");
- addNodes(authNode, Arrays.asList(segments), code);
- }
-
- @Implementation
- public int match(Uri uri) {
- String auth = uri.getAuthority();
- List<String> segments = uri.getPathSegments();
-
- if (!rootNode.map.containsKey(auth)) {
- return rootNode.code;
- }
-
- return matchSegments(rootNode.map.get(auth), segments);
- }
-
- private int matchSegments(MatchNode node, List<String> segments) {
- if (segments.isEmpty()) return node.code;
- String segment = segments.get(0);
- segments = segments.subList(1, segments.size());
-
- if (node.map.containsKey(segment)) {
- return matchSegments(node.map.get(segment), segments);
- }
- if (node.number != null) {
- long id;
- try {
- id = Long.parseLong(segment);
- if (id >= 0) {
- return matchSegments(node.number, segments);
- }
- }
- catch (NumberFormatException e) {}
- }
- if (node.text != null) {
- return matchSegments(node.text, segments);
- }
-
- return rootNode.code;
- }
-
- private void addNodes(MatchNode baseNode, List<String> segments, int code) {
- MatchNode nextNode = null;
- String segment = segments.get(0);
-
- if (segment.equals("#")) {
- nextNode = baseNode.number;
- if (nextNode == null) {
- nextNode = new MatchNode(rootNode.code);
- baseNode.number = nextNode;
- }
- }
- else if (segment.equals("*")) {
- nextNode = baseNode.text;
- if (nextNode == null) {
- nextNode = new MatchNode(rootNode.code);
- baseNode.text = nextNode;
- }
- }
- else {
- nextNode = baseNode.map.get(segment);
- if (nextNode == null) {
- nextNode = new MatchNode(rootNode.code);
- baseNode.map.put(segment, nextNode);
- }
- }
-
- if (segments.size() > 1) {
- addNodes(nextNode, segments.subList(1, segments.size()), code);
- }
- else {
- nextNode.code = code;
- }
- }
-
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowVibrator.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowVibrator.java
deleted file mode 100644
index 2120379f9..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowVibrator.java
+++ /dev/null
@@ -1,54 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.os.Vibrator;
-
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-@Implements(Vibrator.class)
-public class ShadowVibrator {
- private boolean vibrating;
- private boolean cancelled;
- private long milliseconds;
- private long[] pattern;
- private int repeat;
-
- @Implementation
- public void vibrate(long milliseconds) {
- vibrating = true;
- this.milliseconds = milliseconds;
- }
-
- @Implementation
- public void vibrate(long[] pattern, int repeat) {
- vibrating = true;
- this.pattern = pattern;
- this.repeat = repeat;
- }
-
- @Implementation
- public void cancel() {
- cancelled = true;
- vibrating = false;
- }
-
- public boolean isVibrating() {
- return vibrating;
- }
-
- public boolean isCancelled() {
- return cancelled;
- }
-
- public long getMilliseconds() {
- return milliseconds;
- }
-
- public long[] getPattern() {
- return pattern;
- }
-
- public int getRepeat() {
- return repeat;
- }
-} \ No newline at end of file
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowVideoView.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowVideoView.java
deleted file mode 100644
index 2ff11329d..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowVideoView.java
+++ /dev/null
@@ -1,160 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import static org.junit.Assert.assertThat;
-import android.media.MediaPlayer;
-import android.net.Uri;
-import android.widget.VideoView;
-
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-@Implements(VideoView.class)
-@SuppressWarnings({"UnusedDeclaration"})
-public class ShadowVideoView extends ShadowSurfaceView {
-
- private MediaPlayer.OnCompletionListener completionListner;
- private MediaPlayer.OnErrorListener errorListener;
- private MediaPlayer.OnPreparedListener preparedListener;
-
- private Uri uri;
- private String path;
-
- public static final int STOP = 0;
- public static final int START = 1;
- public static final int SUSPEND = 2;
- public static final int PAUSE = 3;
- public static final int RESUME = 4;
-
- private int currentState = -1;
- private int prevState;
-
- @Implementation
- public void setOnPreparedListener(MediaPlayer.OnPreparedListener l) {
- preparedListener = l;
- }
-
- @Implementation
- public void setOnErrorListener(MediaPlayer.OnErrorListener l) {
- errorListener = l;
- }
-
- @Implementation
- public void setOnCompletionListener(MediaPlayer.OnCompletionListener l) {
- completionListner = l;
- }
-
- @Implementation
- public void setVideoPath(String path) {
- this.path = path;
- }
-
- @Implementation
- public void setVideoURI(Uri uri) {
- this.uri = uri;
- }
-
- @Implementation
- public void start() {
- savePrevState();
- currentState = ShadowVideoView.START;
- }
-
- @Implementation
- public void stopPlayback() {
- savePrevState();
- currentState = ShadowVideoView.STOP;
- }
-
- @Implementation
- public void suspend() {
- savePrevState();
- currentState = ShadowVideoView.SUSPEND;
- }
-
- @Implementation
- public void pause() {
- savePrevState();
- currentState = ShadowVideoView.PAUSE;
- }
-
- @Implementation
- public void resume() {
- savePrevState();
- currentState = ShadowVideoView.RESUME;
- }
-
- @Implementation
- public boolean isPlaying() {
- return (currentState == ShadowVideoView.START);
- }
-
- @Implementation
- public boolean canPause() {
- return (currentState != ShadowVideoView.PAUSE &&
- currentState != ShadowVideoView.STOP &&
- currentState != ShadowVideoView.SUSPEND);
- }
-
- /**
- * Non-Android accessor.
- */
- public MediaPlayer.OnPreparedListener getOnPreparedListener() {
- return preparedListener;
- }
-
- /**
- * Non-Android accessor.
- * @return
- */
- public MediaPlayer.OnErrorListener getOnErrorListener() {
- return errorListener;
- }
-
- /**
- * Non-Android accessor.
- * @return
- */
- public MediaPlayer.OnCompletionListener getOnCompletionListener() {
- return completionListner;
- }
-
- /**
- * Non-Android accessor.
- * @return
- */
- public String getVideoPath() {
- return path;
- }
-
- /**
- * Non-Android accessor.
- * @return
- */
- public String getVideoURIString() {
- return uri == null ? null : uri.toString();
- }
-
- /**
- * Non-Android accessor.
- * @return
- */
- public int getCurrentVideoState() {
- return currentState;
- }
-
- /**
- * Non-Android accessor.
- * @return
- */
- public int getPrevVideoState() {
- return prevState;
- }
-
- /**
- * Non-Android accessor.
- */
- private void savePrevState() {
- prevState = currentState;
- }
-
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowView.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowView.java
deleted file mode 100644
index c5aa97254..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowView.java
+++ /dev/null
@@ -1,1011 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-import static com.xtremelabs.robolectric.Robolectric.Reflection.newInstanceOf;
-
-import android.content.Context;
-import android.content.res.Resources;
-import android.graphics.Bitmap;
-import android.graphics.Point;
-import android.graphics.drawable.ColorDrawable;
-import android.graphics.drawable.Drawable;
-import android.util.AttributeSet;
-import android.view.KeyEvent;
-import android.view.MotionEvent;
-import android.view.View;
-import android.view.View.MeasureSpec;
-import android.view.ViewGroup;
-import android.view.ViewParent;
-import android.view.ViewTreeObserver;
-import android.view.animation.Animation;
-
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.internal.RealObject;
-
-import java.io.PrintStream;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.util.HashMap;
-import java.util.Map;
-
-/**
- * Shadow implementation of {@code View} that simulates the behavior of this
- * class.
- * <p/>
- * Supports listeners, focusability (but not focus order), resource loading,
- * visibility, onclick, tags, and tracks the size and shape of the view.
- */
-@SuppressWarnings({"UnusedDeclaration"})
-@Implements(View.class)
-public class ShadowView {
- @RealObject
- protected View realView;
-
- private int id;
- ShadowView parent;
- protected Context context;
- private boolean selected;
- private View.OnClickListener onClickListener;
- private View.OnLongClickListener onLongClickListener;
- private Object tag;
- private boolean enabled = true;
- private int visibility = View.VISIBLE;
- private boolean filterTouchesWhenObscured = false;
- int left;
- int top;
- int right;
- int bottom;
- private int paddingLeft;
- private int paddingTop;
- private int paddingRight;
- private int paddingBottom;
- private ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(0, 0);
- private final Map<Integer, Object> tags = new HashMap<Integer, Object>();
- private boolean clickable;
- protected boolean focusable;
- boolean focusableInTouchMode;
- private int backgroundResourceId = -1;
- private int backgroundColor;
- protected View.OnKeyListener onKeyListener;
- private boolean isFocused;
- private View.OnFocusChangeListener onFocusChangeListener;
- private boolean wasInvalidated;
- private View.OnTouchListener onTouchListener;
- protected AttributeSet attributeSet;
- private boolean drawingCacheEnabled;
- public Point scrollToCoordinates;
- private boolean didRequestLayout;
- private Drawable background;
- private Animation animation;
- private ViewTreeObserver viewTreeObserver;
- private MotionEvent lastTouchEvent;
- private int nextFocusDownId = View.NO_ID;
- private CharSequence contentDescription = null;
- private int measuredWidth = 0;
- private int measuredHeight = 0;
-
- public void __constructor__(Context context) {
- __constructor__(context, null);
- }
-
- public void __constructor__(Context context, AttributeSet attributeSet) {
- __constructor__(context, attributeSet, 0);
- }
-
- public void __constructor__(Context context, AttributeSet attributeSet, int defStyle) {
- this.context = context;
- this.attributeSet = attributeSet;
-
- if (attributeSet != null) {
- applyAttributes();
- }
- }
-
- public void applyAttributes() {
- applyIdAttribute();
- applyVisibilityAttribute();
- applyFilterTouchesWhenObscuredAttribute();
- applyClickableAttribute();
- applyFocusableAttribute();
- applyEnabledAttribute();
- applyBackgroundAttribute();
- applyTagAttribute();
- applyOnClickAttribute();
- applyContentDescriptionAttribute();
- }
-
- @Implementation
- public void setId(int id) {
- this.id = id;
- }
-
- @Implementation
- public void setClickable(boolean clickable) {
- this.clickable = clickable;
- }
-
- /**
- * Also sets focusable in touch mode to false if {@code focusable} is false, which is the Android behavior.
- *
- * @param focusable the new status of the {@code View}'s focusability
- */
- @Implementation
- public void setFocusable(boolean focusable) {
- this.focusable = focusable;
- if (!focusable) {
- setFocusableInTouchMode(false);
- }
- }
-
- @Implementation
- public final boolean isFocusableInTouchMode() {
- return focusableInTouchMode;
- }
-
- /**
- * Also sets focusable to true if {@code focusableInTouchMode} is true, which is the Android behavior.
- *
- * @param focusableInTouchMode the new status of the {@code View}'s touch mode focusability
- */
- @Implementation
- public void setFocusableInTouchMode(boolean focusableInTouchMode) {
- this.focusableInTouchMode = focusableInTouchMode;
- if (focusableInTouchMode) {
- setFocusable(true);
- }
- }
-
- @Implementation(i18nSafe = false)
- public void setContentDescription(CharSequence contentDescription) {
- this.contentDescription = contentDescription;
- }
-
- @Implementation
- public boolean isFocusable() {
- return focusable;
- }
-
- @Implementation
- public int getId() {
- return id;
- }
-
- @Implementation
- public CharSequence getContentDescription() {
- return contentDescription;
- }
-
- /**
- * Simulates the inflating of the requested resource.
- *
- * @param context the context from which to obtain a layout inflater
- * @param resource the ID of the resource to inflate
- * @param root the {@code ViewGroup} to add the inflated {@code View} to
- * @return the inflated View
- */
- @Implementation
- public static View inflate(Context context, int resource, ViewGroup root) {
- return ShadowLayoutInflater.from(context).inflate(resource, root);
- }
-
- /**
- * Finds this {@code View} if it's ID is passed in, returns {@code null} otherwise
- *
- * @param id the id of the {@code View} to find
- * @return the {@code View}, if found, {@code null} otherwise
- */
- @Implementation
- public View findViewById(int id) {
- if (id == this.id) {
- return realView;
- }
-
- return null;
- }
-
- @Implementation
- public View findViewWithTag(Object obj) {
- if (obj.equals(realView.getTag())) {
- return realView;
- }
-
- return null;
- }
-
- @Implementation
- public View getRootView() {
- ShadowView root = this;
- while (root.parent != null) {
- root = root.parent;
- }
- return root.realView;
- }
-
- @Implementation
- public ViewGroup.LayoutParams getLayoutParams() {
- return layoutParams;
- }
-
- @Implementation
- public void setLayoutParams(ViewGroup.LayoutParams params) {
- layoutParams = params;
- }
-
- @Implementation
- public final ViewParent getParent() {
- return parent == null ? null : (ViewParent) parent.realView;
- }
-
- @Implementation
- public final Context getContext() {
- return context;
- }
-
- @Implementation
- public Resources getResources() {
- return context.getResources();
- }
-
- @Implementation
- public void setBackgroundResource(int backgroundResourceId) {
- this.backgroundResourceId = backgroundResourceId;
- setBackgroundDrawable(getResources().getDrawable(backgroundResourceId));
- }
-
- /**
- * Non-Android accessor.
- *
- * @return the resource ID of this views background
- */
- public int getBackgroundResourceId() {
- return backgroundResourceId;
- }
-
- @Implementation
- public void setBackgroundColor(int color) {
- backgroundColor = color;
- setBackgroundDrawable(new ColorDrawable(getResources().getColor(color)));
- }
-
- /**
- * Non-Android accessor.
- *
- * @return the resource color ID of this views background
- */
- public int getBackgroundColor() {
- return backgroundColor;
- }
-
- @Implementation
- public void setBackgroundDrawable(Drawable d) {
- this.background = d;
- }
-
- @Implementation
- public Drawable getBackground() {
- return background;
- }
-
- @Implementation
- public int getVisibility() {
- return visibility;
- }
-
- @Implementation
- public void setVisibility(int visibility) {
- this.visibility = visibility;
- }
-
- @Implementation
- public boolean getFilterTouchesWhenObscured() {
- return filterTouchesWhenObscured;
- }
-
- @Implementation
- public void setFilterTouchesWhenObscured(boolean enabled) {
- this.filterTouchesWhenObscured = enabled;
- }
-
- @Implementation
- public void setSelected(boolean selected) {
- this.selected = selected;
- }
-
- @Implementation
- public boolean isSelected() {
- return this.selected;
- }
-
- @Implementation
- public boolean isEnabled() {
- return this.enabled;
- }
-
- @Implementation
- public void setEnabled(boolean enabled) {
- this.enabled = enabled;
- }
-
- @Implementation
- public void setOnClickListener(View.OnClickListener onClickListener) {
- this.onClickListener = onClickListener;
- }
-
- @Implementation
- public boolean performClick() {
- if (onClickListener != null) {
- onClickListener.onClick(realView);
- return true;
- } else {
- return false;
- }
- }
-
- @Implementation
- public void setOnLongClickListener(View.OnLongClickListener onLongClickListener) {
- this.onLongClickListener = onLongClickListener;
- }
-
- @Implementation
- public boolean performLongClick() {
- if (onLongClickListener != null) {
- onLongClickListener.onLongClick(realView);
- return true;
- } else {
- return false;
- }
- }
-
- @Implementation
- public void setOnKeyListener(View.OnKeyListener onKeyListener) {
- this.onKeyListener = onKeyListener;
- }
-
- @Implementation
- public Object getTag() {
- return this.tag;
- }
-
- @Implementation
- public void setTag(Object tag) {
- this.tag = tag;
- }
-
- @Implementation
- public final int getHeight() {
- return bottom - top;
- }
-
- @Implementation
- public final int getWidth() {
- return right - left;
- }
-
- @Implementation
- public final int getMeasuredWidth() {
- return measuredWidth;
- }
-
- @Implementation
- public final int getMeasuredHeight() {
- return measuredHeight;
- }
-
- @Implementation
- public final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
- this.measuredWidth = measuredWidth;
- this.measuredHeight = measuredHeight;
- }
-
- @Implementation
- public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
- setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec),
- MeasureSpec.getSize(heightMeasureSpec));
- }
-
- @Implementation
- public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
- // We really want to invoke the onMeasure method of the real view,
- // as the real View likely contains an implementation of onMeasure
- // worthy of test, rather the default shadow implementation.
- // But Android declares onMeasure as protected.
- try {
- Method onMeasureMethod = realView.getClass().getDeclaredMethod("onMeasure", Integer.TYPE, Integer.TYPE );
- onMeasureMethod.setAccessible(true);
- onMeasureMethod.invoke( realView, widthMeasureSpec, heightMeasureSpec );
- } catch ( NoSuchMethodException e ) {
- // use default shadow implementation
- onMeasure(widthMeasureSpec, heightMeasureSpec);
- } catch ( IllegalAccessException e ) {
- throw new RuntimeException(e);
- } catch ( InvocationTargetException e ) {
- throw new RuntimeException(e);
- }
- }
-
- @Implementation
- public final void layout(int l, int t, int r, int b) {
- left = l;
- top = t;
- right = r;
- bottom = b;
-// todo: realView.onLayout();
- }
-
- @Implementation
- public void setPadding(int left, int top, int right, int bottom) {
- paddingLeft = left;
- paddingTop = top;
- paddingRight = right;
- paddingBottom = bottom;
- }
-
- @Implementation
- public int getPaddingTop() {
- return paddingTop;
- }
-
- @Implementation
- public int getPaddingLeft() {
- return paddingLeft;
- }
-
- @Implementation
- public int getPaddingRight() {
- return paddingRight;
- }
-
- @Implementation
- public int getPaddingBottom() {
- return paddingBottom;
- }
-
- @Implementation
- public Object getTag(int key) {
- return tags.get(key);
- }
-
- @Implementation
- public void setTag(int key, Object value) {
- tags.put(key, value);
- }
-
- @Implementation
- public void requestLayout() {
- didRequestLayout = true;
- }
-
- public boolean didRequestLayout() {
- return didRequestLayout;
- }
-
- @Implementation
- public final boolean requestFocus() {
- return requestFocus(View.FOCUS_DOWN);
- }
-
- @Implementation
- public final boolean requestFocus(int direction) {
- setViewFocus(true);
- return true;
- }
-
- public void setViewFocus(boolean hasFocus) {
- this.isFocused = hasFocus;
-
- try {
- Class rectClass = Class.forName("android.graphics.Rect");
- Method method = View.class.getDeclaredMethod("onFocusChanged", Boolean.TYPE, Integer.TYPE,
- rectClass);
- method.setAccessible(true);
- method.invoke(realView, this.isFocused, 0, null);
- } catch (IllegalAccessException e) {
- throw new RuntimeException(e);
- } catch (InvocationTargetException e) {
- throw new RuntimeException(e);
- } catch (NoSuchMethodException e) {
- throw new RuntimeException(e);
- } catch (ClassNotFoundException e) {
- throw new RuntimeException(e);
- }
-
- if (onFocusChangeListener != null) {
- onFocusChangeListener.onFocusChange(realView, hasFocus);
- }
- }
-
- @Implementation
- public int getNextFocusDownId() {
- return nextFocusDownId;
- }
-
- @Implementation
- public void setNextFocusDownId(int nextFocusDownId) {
- this.nextFocusDownId = nextFocusDownId;
- }
-
- @Implementation
- public boolean isFocused() {
- return isFocused;
- }
-
- @Implementation
- public boolean hasFocus() {
- return isFocused;
- }
-
- @Implementation
- public void clearFocus() {
- setViewFocus(false);
- }
-
- @Implementation
- public View findFocus() {
- return hasFocus() ? realView : null;
- }
-
- @Implementation
- public void setOnFocusChangeListener(View.OnFocusChangeListener listener) {
- onFocusChangeListener = listener;
- }
-
- @Implementation
- public View.OnFocusChangeListener getOnFocusChangeListener() {
- return onFocusChangeListener;
- }
-
- @Implementation
- public void invalidate() {
- wasInvalidated = true;
- }
-
- @Implementation
- public boolean onTouchEvent(MotionEvent event) {
- lastTouchEvent = event;
- return false;
- }
-
- @Implementation
- public void setOnTouchListener(View.OnTouchListener onTouchListener) {
- this.onTouchListener = onTouchListener;
- }
-
- @Implementation
- public boolean dispatchTouchEvent(MotionEvent event) {
- if (onTouchListener != null && onTouchListener.onTouch(realView, event)) {
- return true;
- }
- return realView.onTouchEvent(event);
- }
-
- public MotionEvent getLastTouchEvent() {
- return lastTouchEvent;
- }
-
- @Implementation
- public boolean dispatchKeyEvent(KeyEvent event) {
- if (onKeyListener != null) {
- return onKeyListener.onKey(realView, event.getKeyCode(), event);
- }
- return false;
- }
-
- /**
- * Returns a string representation of this {@code View}. Unless overridden, it will be an empty string.
- * <p/>
- * Robolectric extension.
- */
- public String innerText() {
- return "";
- }
-
- /**
- * Dumps the status of this {@code View} to {@code System.out}
- */
- public void dump() {
- dump(System.out, 0);
- }
-
- /**
- * Dumps the status of this {@code View} to {@code System.out} at the given indentation level
- */
- public void dump(PrintStream out, int indent) {
- dumpFirstPart(out, indent);
- out.println("/>");
- }
-
- protected void dumpFirstPart(PrintStream out, int indent) {
- dumpIndent(out, indent);
-
- out.print("<" + realView.getClass().getSimpleName());
- if (id > 0) {
- out.print(" id=\"" + shadowOf(context).getResourceLoader().getNameForId(id) + "\"");
- }
- }
-
- protected void dumpIndent(PrintStream out, int indent) {
- for (int i = 0; i < indent; i++) out.print(" ");
- }
-
- /**
- * @return left side of the view
- */
- @Implementation
- public int getLeft() {
- return left;
- }
-
- /**
- * @return top coordinate of the view
- */
- @Implementation
- public int getTop() {
- return top;
- }
-
- /**
- * @return right side of the view
- */
- @Implementation
- public int getRight() {
- return right;
- }
-
- /**
- * @return bottom coordinate of the view
- */
- @Implementation
- public int getBottom() {
- return bottom;
- }
-
- /**
- * @return whether the view is clickable
- */
- @Implementation
- public boolean isClickable() {
- return clickable;
- }
-
- /**
- * Non-Android accessor.
- *
- * @return whether or not {@link #invalidate()} has been called
- */
- public boolean wasInvalidated() {
- return wasInvalidated;
- }
-
- /**
- * Clears the wasInvalidated flag
- */
- public void clearWasInvalidated() {
- wasInvalidated = false;
- }
-
- @Implementation
- public void setLeft(int left) {
- this.left = left;
- }
-
- @Implementation
- public void setTop(int top) {
- this.top = top;
- }
-
- @Implementation
- public void setRight(int right) {
- this.right = right;
- }
-
- @Implementation
- public void setBottom(int bottom) {
- this.bottom = bottom;
- }
-
- /**
- * Non-Android accessor.
- */
- public void setPaddingLeft(int paddingLeft) {
- this.paddingLeft = paddingLeft;
- }
-
- /**
- * Non-Android accessor.
- */
- public void setPaddingTop(int paddingTop) {
- this.paddingTop = paddingTop;
- }
-
- /**
- * Non-Android accessor.
- */
- public void setPaddingRight(int paddingRight) {
- this.paddingRight = paddingRight;
- }
-
- /**
- * Non-Android accessor.
- */
- public void setPaddingBottom(int paddingBottom) {
- this.paddingBottom = paddingBottom;
- }
-
- /**
- * Non-Android accessor.
- */
- public void setFocused(boolean focused) {
- isFocused = focused;
- }
-
- /**
- * Non-Android accessor.
- *
- * @return true if this object and all of its ancestors are {@code View.VISIBLE}, returns false if this or
- * any ancestor is not {@code View.VISIBLE}
- */
- public boolean derivedIsVisible() {
- View parent = realView;
- while (parent != null) {
- if (parent.getVisibility() != View.VISIBLE) {
- return false;
- }
- parent = (View) parent.getParent();
- }
- return true;
- }
-
- /**
- * Utility method for clicking on views exposing testing scenarios that are not possible when using the actual app.
- *
- * @throws RuntimeException if the view is disabled or if the view or any of its parents are not visible.
- */
- public boolean checkedPerformClick() {
- if (!derivedIsVisible()) {
- throw new RuntimeException("View is not visible and cannot be clicked");
- }
- if (!realView.isEnabled()) {
- throw new RuntimeException("View is not enabled and cannot be clicked");
- }
-
- return realView.performClick();
- }
-
- public void applyFocus() {
- if (noParentHasFocus(realView)) {
- Boolean focusRequested = attributeSet.getAttributeBooleanValue("android", "focus", false);
- if (focusRequested || realView.isFocusableInTouchMode()) {
- realView.requestFocus();
- }
- }
- }
-
- private void applyIdAttribute() {
- Integer id = attributeSet.getAttributeResourceValue("android", "id", 0);
- if (getId() == 0) {
- setId(id);
- }
- }
-
- private void applyTagAttribute() {
- Object tag = attributeSet.getAttributeValue("android", "tag");
- if (tag != null) {
- setTag(tag);
- }
- }
-
- private void applyVisibilityAttribute() {
- String visibility = attributeSet.getAttributeValue("android", "visibility");
- if (visibility != null) {
- if (visibility.equals("gone")) {
- setVisibility(View.GONE);
- } else if (visibility.equals("invisible")) {
- setVisibility(View.INVISIBLE);
- }
- }
- }
-
- private void applyFilterTouchesWhenObscuredAttribute() {
- setFilterTouchesWhenObscured(attributeSet.getAttributeBooleanValue(
- "android", "filterTouchesWhenObscured", false));
- }
-
- private void applyClickableAttribute() {
- setClickable(attributeSet.getAttributeBooleanValue("android", "clickable", false));
- }
-
- private void applyFocusableAttribute() {
- setFocusable(attributeSet.getAttributeBooleanValue("android", "focusable", false));
- }
-
- private void applyEnabledAttribute() {
- setEnabled(attributeSet.getAttributeBooleanValue("android", "enabled", true));
- }
-
- private void applyBackgroundAttribute() {
- String source = attributeSet.getAttributeValue("android", "background");
- if (source != null) {
- if (source.startsWith("@drawable/")) {
- setBackgroundResource(attributeSet.getAttributeResourceValue("android", "background", 0));
- }
- }
- }
-
- private void applyOnClickAttribute() {
- final String handlerName = attributeSet.getAttributeValue("android",
- "onClick");
- if (handlerName == null) {
- return;
- }
-
- /* good part of following code has been directly copied from original
- * android source */
- setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- Method mHandler;
- try {
- mHandler = getContext().getClass().getMethod(handlerName,
- View.class);
- } catch (NoSuchMethodException e) {
- int id = getId();
- String idText = id == View.NO_ID ? "" : " with id '"
- + shadowOf(context).getResourceLoader()
- .getNameForId(id) + "'";
- throw new IllegalStateException("Could not find a method " +
- handlerName + "(View) in the activity "
- + getContext().getClass() + " for onClick handler"
- + " on view " + realView.getClass() + idText, e);
- }
-
- try {
- mHandler.invoke(getContext(), realView);
- } catch (IllegalAccessException e) {
- throw new IllegalStateException("Could not execute non "
- + "public method of the activity", e);
- } catch (InvocationTargetException e) {
- throw new IllegalStateException("Could not execute "
- + "method of the activity", e);
- }
- }
- });
- }
-
- private void applyContentDescriptionAttribute() {
- String contentDescription = attributeSet.getAttributeValue("android", "contentDescription");
- if (contentDescription != null) {
- if (contentDescription.startsWith("@string/")) {
- int resId = attributeSet.getAttributeResourceValue("android", "contentDescription", 0);
- contentDescription = context.getResources().getString(resId);
- }
- setContentDescription(contentDescription);
- }
- }
-
- private boolean noParentHasFocus(View view) {
- while (view != null) {
- if (view.hasFocus()) return false;
- view = (View) view.getParent();
- }
- return true;
- }
-
- /**
- * Non-android accessor. Returns touch listener, if set.
- *
- * @return
- */
- public View.OnTouchListener getOnTouchListener() {
- return onTouchListener;
- }
-
- /**
- * Non-android accessor. Returns click listener, if set.
- *
- * @return
- */
- public View.OnClickListener getOnClickListener() {
- return onClickListener;
- }
-
- @Implementation
- public void setDrawingCacheEnabled(boolean drawingCacheEnabled) {
- this.drawingCacheEnabled = drawingCacheEnabled;
- }
-
- @Implementation
- public boolean isDrawingCacheEnabled() {
- return drawingCacheEnabled;
- }
-
- @Implementation
- public Bitmap getDrawingCache() {
- return Robolectric.newInstanceOf(Bitmap.class);
- }
-
- @Implementation
- public void post(Runnable action) {
- Robolectric.getUiThreadScheduler().post(action);
- }
-
- @Implementation
- public void postDelayed(Runnable action, long delayMills) {
- Robolectric.getUiThreadScheduler().postDelayed(action, delayMills);
- }
-
- @Implementation
- public void postInvalidateDelayed(long delayMilliseconds) {
- Robolectric.getUiThreadScheduler().postDelayed(new Runnable() {
- @Override
- public void run() {
- realView.invalidate();
- }
- }, delayMilliseconds);
- }
-
- @Implementation
- public Animation getAnimation() {
- return animation;
- }
-
- @Implementation
- public void setAnimation(Animation anim) {
- animation = anim;
- }
-
- @Implementation
- public void startAnimation(Animation anim) {
- setAnimation(anim);
- animation.start();
- }
-
- @Implementation
- public void clearAnimation() {
- if (animation != null) {
- animation.cancel();
- animation = null;
- }
- }
-
- @Implementation
- public void scrollTo(int x, int y) {
- this.scrollToCoordinates = new Point(x, y);
- }
-
- @Implementation
- public int getScrollX() {
- return scrollToCoordinates != null ? scrollToCoordinates.x : 0;
- }
-
- @Implementation
- public int getScrollY() {
- return scrollToCoordinates != null ? scrollToCoordinates.y : 0;
- }
-
- @Implementation
- public ViewTreeObserver getViewTreeObserver() {
- if (viewTreeObserver == null) {
- viewTreeObserver = newInstanceOf(ViewTreeObserver.class);
- }
- return viewTreeObserver;
- }
-
- @Implementation
- public void onAnimationEnd() {
- }
-
- /*
- * Non-Android accessor.
- */
- public void finishedAnimation() {
- try {
- Method onAnimationEnd = realView.getClass().getDeclaredMethod("onAnimationEnd", new Class[0]);
- onAnimationEnd.setAccessible(true);
- onAnimationEnd.invoke(realView);
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowViewAnimator.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowViewAnimator.java
deleted file mode 100644
index 52a56d3b8..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowViewAnimator.java
+++ /dev/null
@@ -1,42 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.view.View;
-import android.widget.ViewAnimator;
-
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-@Implements(ViewAnimator.class)
-public class ShadowViewAnimator extends ShadowFrameLayout {
- private int mWhichChild = 0;
-
- @Implementation
- public void showNext() {
- setDisplayedChild(mWhichChild + 1);
- }
-
- @Implementation
- public void showPrevious() {
- setDisplayedChild(mWhichChild - 1);
- }
-
- @Implementation
- public void setDisplayedChild(int whichChild) {
- mWhichChild = whichChild;
- if (whichChild >= getChildCount()) {
- mWhichChild = 0;
- } else if (whichChild < 0) {
- mWhichChild = getChildCount() - 1;
- }
- }
-
- @Implementation
- public int getDisplayedChild() {
- return mWhichChild;
- }
-
- @Implementation
- public View getCurrentView() {
- return getChildAt(mWhichChild);
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowViewConfiguration.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowViewConfiguration.java
deleted file mode 100644
index e2df35485..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowViewConfiguration.java
+++ /dev/null
@@ -1,230 +0,0 @@
-/*
- * Portions of this code came from frameworks/base/core/java/android/view/ViewConfiguration.java,
- * which contains the following license text:
- *
- * Copyright (C) 2006 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-package com.xtremelabs.robolectric.shadows;
-
-import android.content.Context;
-import android.util.DisplayMetrics;
-import android.view.ViewConfiguration;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.internal.RealObject;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-
-@SuppressWarnings({"UnusedDeclaration"})
-@Implements(ViewConfiguration.class)
-public class ShadowViewConfiguration {
-
- private static final int SCROLL_BAR_SIZE = 10;
- private static final int SCROLL_BAR_FADE_DURATION = 250;
- private static final int SCROLL_BAR_DEFAULT_DELAY = 300;
- private static final int FADING_EDGE_LENGTH = 12;
- private static final int PRESSED_STATE_DURATION = 125;
- private static final int LONG_PRESS_TIMEOUT = 500;
- private static final int GLOBAL_ACTIONS_KEY_TIMEOUT = 500;
- private static final int TAP_TIMEOUT = 115;
- private static final int JUMP_TAP_TIMEOUT = 500;
- private static final int DOUBLE_TAP_TIMEOUT = 300;
- private static final int ZOOM_CONTROLS_TIMEOUT = 3000;
- private static final int EDGE_SLOP = 12;
- private static final int TOUCH_SLOP = 16;
- private static final int PAGING_TOUCH_SLOP = TOUCH_SLOP * 2;
- private static final int DOUBLE_TAP_SLOP = 100;
- private static final int WINDOW_TOUCH_SLOP = 16;
- private static final int MINIMUM_FLING_VELOCITY = 50;
- private static final int MAXIMUM_FLING_VELOCITY = 4000;
- private static final int MAXIMUM_DRAWING_CACHE_SIZE = 320 * 480 * 4;
- private static float SCROLL_FRICTION = 0.015f;
- private static final int OVERSCROLL_DISTANCE = 0;
- private static final int OVERFLING_DISTANCE = 4;
-
- private int edgeSlop;
- private int fadingEdgeLength;
- private int minimumFlingVelocity;
- private int maximumFlingVelocity;
- private int scrollbarSize;
- private int touchSlop;
- private int pagingTouchSlop;
- private int doubleTapSlop;
- private int windowTouchSlop;
-
- @RealObject
- private ViewConfiguration realViewConfiguration;
-
- private void setup(Context context) {
- DisplayMetrics metrics = context.getResources().getDisplayMetrics();
- float density = metrics.density;
-
- edgeSlop = (int) (density * EDGE_SLOP + 0.5f);
- fadingEdgeLength = (int) (density * FADING_EDGE_LENGTH + 0.5f);
- minimumFlingVelocity = (int) (density * MINIMUM_FLING_VELOCITY + 0.5f);
- maximumFlingVelocity = (int) (density * MAXIMUM_FLING_VELOCITY + 0.5f);
- scrollbarSize = (int) (density * SCROLL_BAR_SIZE + 0.5f);
- touchSlop = (int) (density * TOUCH_SLOP + 0.5f);
- pagingTouchSlop = (int) (density * PAGING_TOUCH_SLOP + 0.5f);
- doubleTapSlop = (int) (density * DOUBLE_TAP_SLOP + 0.5f);
- windowTouchSlop = (int) (density * WINDOW_TOUCH_SLOP + 0.5f);
- }
-
- @Implementation
- public static ViewConfiguration get(Context context) {
- ViewConfiguration viewConfiguration = Robolectric.newInstanceOf(ViewConfiguration.class);
- shadowOf(viewConfiguration).setup(context);
- return viewConfiguration;
- }
-
- @Implementation
- public static int getScrollBarSize() {
- return SCROLL_BAR_SIZE;
- }
-
- @Implementation
- public int getScaledScrollBarSize() {
- return scrollbarSize;
- }
-
- @Implementation
- public static int getScrollBarFadeDuration() {
- return SCROLL_BAR_FADE_DURATION;
- }
-
- @Implementation
- public static int getScrollDefaultDelay() {
- return SCROLL_BAR_DEFAULT_DELAY;
- }
-
- @Implementation
- public static int getFadingEdgeLength() {
- return FADING_EDGE_LENGTH;
- }
-
- @Implementation
- public int getScaledFadingEdgeLength() {
- return fadingEdgeLength;
- }
-
- @Implementation
- public static int getPressedStateDuration() {
- return PRESSED_STATE_DURATION;
- }
-
- @Implementation
- public static int getLongPressTimeout() {
- return LONG_PRESS_TIMEOUT;
- }
-
- @Implementation
- public static int getTapTimeout() {
- return TAP_TIMEOUT;
- }
-
- @Implementation
- public static int getJumpTapTimeout() {
- return JUMP_TAP_TIMEOUT;
- }
-
- @Implementation
- public static int getDoubleTapTimeout() {
- return DOUBLE_TAP_TIMEOUT;
- }
-
- @Implementation
- public static int getEdgeSlop() {
- return EDGE_SLOP;
- }
-
- @Implementation
- public int getScaledEdgeSlop() {
- return edgeSlop;
- }
-
- @Implementation
- public static int getTouchSlop() {
- return TOUCH_SLOP;
- }
-
- @Implementation
- public int getScaledTouchSlop() {
- return touchSlop;
- }
-
- @Implementation
- public int getScaledPagingTouchSlop() {
- return pagingTouchSlop;
- }
-
- @Implementation
- public int getScaledDoubleTapSlop() {
- return doubleTapSlop;
- }
-
- @Implementation
- public static int getWindowTouchSlop() {
- return WINDOW_TOUCH_SLOP;
- }
-
- @Implementation
- public int getScaledWindowTouchSlop() {
- return windowTouchSlop;
- }
-
- @Implementation
- public static int getMinimumFlingVelocity() {
- return MINIMUM_FLING_VELOCITY;
- }
-
- @Implementation
- public int getScaledMinimumFlingVelocity() {
- return minimumFlingVelocity;
- }
-
- @Implementation
- public static int getMaximumFlingVelocity() {
- return MAXIMUM_FLING_VELOCITY;
- }
-
- @Implementation
- public int getScaledMaximumFlingVelocity() {
- return maximumFlingVelocity;
- }
-
- @Implementation
- public static int getMaximumDrawingCacheSize() {
- return MAXIMUM_DRAWING_CACHE_SIZE;
- }
-
- @Implementation
- public static long getZoomControlsTimeout() {
- return ZOOM_CONTROLS_TIMEOUT;
- }
-
- @Implementation
- public static long getGlobalActionKeyTimeout() {
- return GLOBAL_ACTIONS_KEY_TIMEOUT;
- }
-
- @Implementation
- public static float getScrollFriction() {
- return SCROLL_FRICTION;
- }
-
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowViewFlipper.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowViewFlipper.java
deleted file mode 100644
index 722ec4798..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowViewFlipper.java
+++ /dev/null
@@ -1,29 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.widget.ViewFlipper;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.internal.RealObject;
-
-@Implements(ViewFlipper.class)
-public class ShadowViewFlipper extends ShadowViewAnimator {
- @RealObject
- protected ViewFlipper realObject;
-
- protected boolean isFlipping;
-
- @Implementation
- public void startFlipping() {
- this.isFlipping = true;
- }
-
- @Implementation
- public void stopFlipping() {
- this.isFlipping = false;
- }
-
- @Implementation
- public boolean isFlipping() {
- return isFlipping;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowViewGroup.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowViewGroup.java
deleted file mode 100644
index bc998d960..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowViewGroup.java
+++ /dev/null
@@ -1,251 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.view.View;
-import android.view.ViewGroup;
-import android.view.animation.Animation.AnimationListener;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-import java.io.PrintStream;
-import java.util.ArrayList;
-import java.util.List;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-
-/**
- * Shadow for {@code ViewGroup} that simulates its implementation
- */
-@SuppressWarnings({"UnusedDeclaration"})
-@Implements(ViewGroup.class)
-public class ShadowViewGroup extends ShadowView {
- private List<View> children = new ArrayList<View>();
- private AnimationListener animListener;
- private boolean disallowInterceptTouchEvent = false;
-
- @Implementation
- @Override
- public View findViewById(int id) {
- if (id == getId()) {
- return realView;
- }
-
- for (View child : children) {
- View found = child.findViewById(id);
- if (found != null) {
- return found;
- }
- }
- return null;
- }
-
- @Implementation
- @Override
- public View findViewWithTag(Object obj) {
- if (obj.equals(realView.getTag())) {
- return realView;
- }
-
- for (View child : children) {
- View found = child.findViewWithTag(obj);
- if (found != null) {
- return found;
- }
- }
-
- return null;
- }
-
- @Implementation
- public void addView(View child) {
- ((ViewGroup) realView).addView(child, -1);
- }
-
- @Implementation
- public void addView(View child, int index) {
- if (index == -1) {
- children.add(child);
- } else {
- children.add(index, child);
- }
- shadowOf(child).parent = this;
- }
-
- @Implementation
- public void addView(View child, int width, int height) {
- ((ViewGroup) realView).addView(child, -1);
- }
-
- @Implementation
- public void addView(View child, ViewGroup.LayoutParams params) {
- ((ViewGroup) realView).addView(child, -1);
- }
-
- @Implementation
- public void addView(View child, int index, ViewGroup.LayoutParams params) {
- ((ViewGroup) realView).addView(child, index);
- }
-
- @Implementation
- public int indexOfChild(View child) {
- int count = getChildCount();
- for (int i = 0; i < count; i++) {
- if (children.get(i) == child) {
- return i;
- }
- }
- return -1;
- }
-
- @Implementation
- public int getChildCount() {
- return children.size();
- }
-
- @Implementation
- public View getChildAt(int index) {
- if( index >= children.size() ){ return null; }
- return children.get(index);
- }
-
- @Implementation
- public void removeAllViews() {
- for (View child : children) {
- shadowOf(child).parent = null;
- }
- children.clear();
- }
-
- @Implementation
- public void removeViewAt(int position) {
- shadowOf(children.remove(position)).parent = null;
- }
-
- @Implementation
- public void removeView(View view) {
- removeViewInLayout(view);
- }
-
- @Implementation
- public void removeViewInLayout(View view) {
- int index = indexOfChild(view);
- if (index >= 0) {
- removeViewAt(index);
- }
- }
-
- @Implementation
- public void removeViews(int start, int count) {
- removeViewsInLayout(start, count);
- }
-
- @Implementation
- public void removeViewsInLayout(int start, int count) {
- int lastIndex = start + count - 1;
- for (int i = lastIndex; i >= start; i--) {
- removeViewAt(i);
- }
- }
-
- @Override
- @Implementation
- public boolean hasFocus() {
- if (super.hasFocus()) return true;
-
- for (View child : children) {
- if (child.hasFocus()) return true;
- }
-
- return false;
- }
-
- @Implementation
- @Override
- public void clearFocus() {
- if (hasFocus()) {
- super.clearFocus();
-
- for (View child : children) {
- child.clearFocus();
- }
- }
- }
-
- @Implementation
- @Override
- public View findFocus() {
- if (super.hasFocus()) {
- return this.realView;
- }
-
- for (View child : children) {
- View focusedView = child.findFocus();
- if (focusedView != null) {
- return focusedView;
- }
- }
-
- return null;
- }
-
- /**
- * Returns a string representation of this {@code ViewGroup} by concatenating all of the strings contained in all
- * of the descendants of this {@code ViewGroup}.
- * <p/>
- * Robolectric extension.
- */
- @Override
- public String innerText() {
- String innerText = "";
- String delimiter = "";
-
- for (int i = 0; i < getChildCount(); i++) {
- View child = getChildAt(i);
- String childText = shadowOf(child).innerText();
- if (childText.length() > 0) {
- innerText += delimiter;
- delimiter = " ";
- }
- innerText += childText;
- }
- return innerText;
- }
-
- /**
- * Non-Android method that dumps the state of this {@code ViewGroup} to {@code System.out}
- */
- @Override
- public void dump(PrintStream out, int indent) {
- dumpFirstPart(out, indent);
- if (children.size() > 0) {
- out.println(">");
-
- for (View child : children) {
- shadowOf(child).dump(out, indent + 2);
- }
-
- dumpIndent(out, indent);
- out.println("</" + realView.getClass().getSimpleName() + ">");
- } else {
- out.println("/>");
- }
- }
-
- @Implementation
- public void setLayoutAnimationListener(AnimationListener listener) {
- animListener = listener;
- }
-
- @Implementation
- public AnimationListener getLayoutAnimationListener() {
- return animListener;
- }
-
- @Implementation
- public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
- disallowInterceptTouchEvent = disallowIntercept;
- }
-
- public boolean getDisallowInterceptTouchEvent() {
- return disallowInterceptTouchEvent;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowViewMeasureSpec.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowViewMeasureSpec.java
deleted file mode 100644
index ed225e71e..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowViewMeasureSpec.java
+++ /dev/null
@@ -1,54 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-import android.view.View;
-
-/**
- * Shadow for {@code View.MeasureSpec} inner class.
- *
- * As the implementation is very simple, it is taken from the AOSP source.
- */
-@Implements(View.MeasureSpec.class)
-public class ShadowViewMeasureSpec {
-
- private static final int MODE_SHIFT = 30;
- private static final int MODE_MASK = 0x3 << MODE_SHIFT;
-
- @Implementation
- public static int getMode (int measureSpec) {
- return (measureSpec & MODE_MASK);
- }
-
- @Implementation
- public static int getSize (int measureSpec) {
- return (measureSpec & ~MODE_MASK);
- }
-
- @Implementation
- public static int makeMeasureSpec (int size, int mode) {
- return size + mode;
- }
-
- @Implementation
- public static String toString (int measureSpec) {
- int mode = getMode(measureSpec);
- int size = getSize(measureSpec);
-
- StringBuilder sb = new StringBuilder("MeasureSpec: ");
-
- if (mode == View.MeasureSpec.UNSPECIFIED)
- sb.append("UNSPECIFIED ");
- else if (mode == View.MeasureSpec.EXACTLY)
- sb.append("EXACTLY ");
- else if (mode == View.MeasureSpec.AT_MOST)
- sb.append("AT_MOST ");
- else
- sb.append(mode).append(" ");
-
- sb.append(size);
- return sb.toString();
- }
-
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowViewPager.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowViewPager.java
deleted file mode 100644
index 87a54768c..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowViewPager.java
+++ /dev/null
@@ -1,50 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.support.v4.view.PagerAdapter;
-import android.support.v4.view.ViewPager;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.internal.RealObject;
-
-@Implements(ViewPager.class)
-public class ShadowViewPager extends ShadowViewGroup {
- @RealObject
- private ViewPager realViewPager;
-
- private PagerAdapter adapter;
- private int currentItem;
- private ViewPager.OnPageChangeListener onPageChangeListener;
-
- @Implementation
- public void setAdapter(PagerAdapter adapter) {
- this.adapter = adapter;
- }
-
- @Implementation
- public PagerAdapter getAdapter() {
- return adapter;
- }
-
- @Implementation
- public int getCurrentItem() {
- return currentItem;
- }
-
- @Implementation
- public void setOnPageChangeListener(ViewPager.OnPageChangeListener listener) {
- onPageChangeListener = listener;
- }
-
- @Implementation
- public void setCurrentItem(int position) {
- if (onPageChangeListener != null) {
- onPageChangeListener.onPageSelected(position);
- }
- currentItem = position;
- }
-
- @Implementation
- public void setCurrentItem(int position, boolean smoothScroll){
- setCurrentItem( position );
- }
-} \ No newline at end of file
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowViewStub.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowViewStub.java
deleted file mode 100644
index 49a836f00..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowViewStub.java
+++ /dev/null
@@ -1,104 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.view.LayoutInflater;
-import android.view.View;
-import android.view.ViewGroup;
-import android.view.ViewParent;
-import android.view.ViewStub;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.internal.RealObject;
-import com.xtremelabs.robolectric.res.ResourceExtractor;
-
-import java.lang.ref.WeakReference;
-
-@SuppressWarnings({"UnusedDeclaration"})
-@Implements(ViewStub.class)
-public class ShadowViewStub extends ShadowView {
- @RealObject ViewStub viewStub;
-
- private int mLayoutResource = 0;
- private int mInflatedId;
- private WeakReference<View> mInflatedViewRef;
- private ViewStub.OnInflateListener mInflateListener;
-
- @Override public void applyAttributes() {
- super.applyAttributes();
-
- String inflatedId = attributeSet.getAttributeValue("android", "inflatedId");
- if (inflatedId != null) {
- mInflatedId = getResourceId(inflatedId);
- }
-
- String layoutResId = attributeSet.getAttributeValue("android", "layout");
- if (layoutResId != null) {
- mLayoutResource = getResourceId(layoutResId);
- }
- }
-
- private Integer getResourceId(String inflatedId) {
- ResourceExtractor resourceExtractor = Robolectric.getShadowApplication().getResourceLoader().getResourceExtractor();
- return resourceExtractor.getResourceId(inflatedId, false);
- }
-
- @Implementation
- public int getInflatedId() {
- return mInflatedId;
- }
-
- @Implementation
- public void setInflatedId(int inflatedId) {
- mInflatedId = inflatedId;
- }
-
- @Implementation
- public int getLayoutResource() {
- return mLayoutResource;
- }
-
- @Implementation
- public void setLayoutResource(int layoutResource) {
- mLayoutResource = layoutResource;
- }
-
- @Implementation
- public View inflate() {
- ViewParent viewParent = viewStub.getParent();
-
- if (viewParent != null && viewParent instanceof ViewGroup) {
- if (mLayoutResource != 0) {
- ViewGroup parent = (ViewGroup) viewParent;
- LayoutInflater factory = LayoutInflater.from(viewStub.getContext());
- View view = factory.inflate(mLayoutResource, parent, false);
-
- if (mInflatedId != View.NO_ID) {
- view.setId(mInflatedId);
- }
-
- int index = parent.indexOfChild(viewStub);
- parent.removeViewAt(index);
-// parent.removeViewInLayout(viewStub);
-
- ViewGroup.LayoutParams layoutParams = getLayoutParams();
- if (layoutParams != null) {
- parent.addView(view, index, layoutParams);
- } else {
- parent.addView(view, index);
- }
-
- mInflatedViewRef = new WeakReference<View>(view);
-
- if (mInflateListener != null) {
- mInflateListener.onInflate(viewStub, view);
- }
-
- return view;
- } else {
- throw new IllegalArgumentException("ViewStub must have a valid layoutResource");
- }
- } else {
- throw new IllegalStateException("ViewStub must have a non-null ViewGroup viewParent");
- }
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowViewTreeObserver.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowViewTreeObserver.java
deleted file mode 100644
index f7c4fd5c4..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowViewTreeObserver.java
+++ /dev/null
@@ -1,35 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.view.ViewTreeObserver;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-import java.util.ArrayList;
-import java.util.List;
-
-@SuppressWarnings({"UnusedDeclaration"})
-@Implements(ViewTreeObserver.class)
-public class ShadowViewTreeObserver {
-
- private ArrayList<ViewTreeObserver.OnGlobalLayoutListener> globalLayoutListeners = new ArrayList<ViewTreeObserver.OnGlobalLayoutListener>();
-
- @Implementation
- public void addOnGlobalLayoutListener(ViewTreeObserver.OnGlobalLayoutListener listener) {
- this.globalLayoutListeners.add(listener);
- }
-
- @Implementation
- public void removeGlobalOnLayoutListener(ViewTreeObserver.OnGlobalLayoutListener listener) {
- this.globalLayoutListeners.remove(listener);
- }
-
- public void fireOnGlobalLayoutListeners() {
- for (ViewTreeObserver.OnGlobalLayoutListener listener : new ArrayList<ViewTreeObserver.OnGlobalLayoutListener>(globalLayoutListeners)) {
- listener.onGlobalLayout();
- }
- }
-
- public List<ViewTreeObserver.OnGlobalLayoutListener> getOnGlobalLayoutListeners() {
- return globalLayoutListeners;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowWebView.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowWebView.java
deleted file mode 100644
index d9b3caf9f..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowWebView.java
+++ /dev/null
@@ -1,245 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.content.Context;
-import android.util.AttributeSet;
-import android.webkit.WebChromeClient;
-import android.webkit.WebSettings;
-import android.webkit.TestWebSettings;
-import android.webkit.WebView;
-import android.webkit.WebViewClient;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-import java.util.HashMap;
-
-@SuppressWarnings({"UnusedDeclaration"})
-@Implements(WebView.class)
-public class ShadowWebView extends ShadowAbsoluteLayout {
-
- private String lastUrl;
- private HashMap<String, Object> javascriptInterfaces = new HashMap<String, Object>();
- private WebSettings webSettings = new TestWebSettings();
- private WebViewClient webViewClient = null;
- private boolean runFlag = false;
- private boolean clearCacheCalled = false;
- private boolean clearCacheIncludeDiskFiles = false;
- private boolean clearFormDataCalled = false;
- private boolean clearHistoryCalled = false;
- private boolean clearViewCalled = false;
- private boolean destroyCalled = false;
- private WebChromeClient webChromeClient;
- private boolean canGoBack;
- private int goBackInvocations = 0;
- private ShadowWebView.LoadData lastLoadData;
- private LoadDataWithBaseURL lastLoadDataWithBaseURL;
- private WebView.PictureListener pictureListener;
-
- @Override
- public void __constructor__(Context context, AttributeSet attributeSet) {
- super.__constructor__(context, attributeSet);
- }
-
- @Implementation
- public void loadUrl(String url) {
- lastUrl = url;
- }
-
- @Implementation
- public void loadDataWithBaseURL(String baseUrl, String data, String mimeType, String encoding, String historyUrl) {
- lastLoadDataWithBaseURL = new LoadDataWithBaseURL(baseUrl, data, mimeType, encoding, historyUrl);
- }
-
- @Implementation
- public void loadData(String data, String mimeType, String encoding) {
- lastLoadData = new LoadData(data, mimeType, encoding);
- }
-
- /**
- * Non-Android accessor.
- *
- * @return the last loaded url
- */
- public String getLastLoadedUrl() {
- return lastUrl;
- }
-
- public void clearLastLoadedUrl() {
- lastUrl = null;
- }
-
- @Implementation
- public WebSettings getSettings() {
- return webSettings;
- }
-
- @Implementation
- public void setWebViewClient(WebViewClient client) {
- webViewClient = client;
- }
-
- @Implementation
- public void setWebChromeClient(WebChromeClient client) {
- webChromeClient = client;
- }
-
- public WebViewClient getWebViewClient() {
- return webViewClient;
- }
-
- @Implementation
- public void setPictureListener(WebView.PictureListener listener) {
- pictureListener = listener;
- }
-
- public WebView.PictureListener getPictureListener() {
- return pictureListener;
- }
-
- @Implementation
- public void addJavascriptInterface(Object obj, String interfaceName) {
- javascriptInterfaces.put(interfaceName, obj);
- }
-
- public Object getJavascriptInterface(String interfaceName) {
- return javascriptInterfaces.get(interfaceName);
- }
-
- @Implementation
- public void clearCache(boolean includeDiskFiles) {
- clearCacheCalled = true;
- clearCacheIncludeDiskFiles = includeDiskFiles;
- }
-
- public boolean wasClearCacheCalled() {
- return clearCacheCalled;
- }
-
- public boolean didClearCacheIncludeDiskFiles() {
- return clearCacheIncludeDiskFiles;
- }
-
- @Implementation
- public void clearFormData() {
- clearFormDataCalled = true;
- }
-
- public boolean wasClearFormDataCalled() {
- return clearFormDataCalled;
- }
-
- @Implementation
- public void clearHistory() {
- clearHistoryCalled = true;
- }
-
- public boolean wasClearHistoryCalled() {
- return clearHistoryCalled;
- }
-
- @Implementation
- public void clearView() {
- clearViewCalled = true;
- }
-
- public boolean wasClearViewCalled() {
- return clearViewCalled;
- }
-
- @Implementation
- public void destroy() {
- destroyCalled = true;
- }
-
- public boolean wasDestroyCalled() {
- return destroyCalled;
- }
-
- @Implementation
- public void post(Runnable action) {
- action.run();
- runFlag = true;
- }
-
- public boolean getRunFlag() {
- return runFlag;
- }
-
-
- /**
- * Non-Android accessor.
- *
- * @return webChromeClient
- */
- public WebChromeClient getWebChromeClient() {
- return webChromeClient;
- }
-
- @Implementation
- public boolean canGoBack() {
- return canGoBack;
- }
-
- @Implementation
- public void goBack() {
- goBackInvocations++;
- }
-
-
- /**
- * Non-Android accessor.
- *
- * @return goBackInvocations the number of times {@code android.webkit.WebView#goBack()}
- * was invoked
- */
- public int getGoBackInvocations() {
- return goBackInvocations;
- }
-
- /**
- * Non-Android setter.
- *
- * Sets the value to return from {@code android.webkit.WebView#canGoBack()}
- *
- * @param canGoBack
- */
- public void setCanGoBack(boolean canGoBack) {
- this.canGoBack = canGoBack;
- }
-
- public LoadData getLastLoadData() {
- return lastLoadData;
- }
-
- public LoadDataWithBaseURL getLastLoadDataWithBaseURL() {
- return lastLoadDataWithBaseURL;
- }
-
- public class LoadDataWithBaseURL {
- public final String baseUrl;
- public final String data;
- public final String mimeType;
- public final String encoding;
- public final String historyUrl;
-
- public LoadDataWithBaseURL(String baseUrl, String data, String mimeType, String encoding, String historyUrl) {
- this.baseUrl = baseUrl;
- this.data = data;
- this.mimeType = mimeType;
- this.encoding = encoding;
- this.historyUrl = historyUrl;
- }
- }
-
- public class LoadData {
- public final String data;
- public final String mimeType;
- public final String encoding;
-
- public LoadData(String data, String mimeType, String encoding) {
- this.data = data;
- this.mimeType = mimeType;
- this.encoding = encoding;
- }
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowWifiConfiguration.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowWifiConfiguration.java
deleted file mode 100644
index 1258fd6c1..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowWifiConfiguration.java
+++ /dev/null
@@ -1,51 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.net.wifi.WifiConfiguration;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.internal.RealObject;
-
-import java.util.BitSet;
-
-@Implements(WifiConfiguration.class)
-public class ShadowWifiConfiguration {
- @RealObject WifiConfiguration realObject;
-
- public void __constructor__() {
- realObject.networkId = -1;
- realObject.SSID = null;
- realObject.BSSID = null;
- realObject.priority = 0;
- realObject.hiddenSSID = false;
- realObject.allowedKeyManagement = new BitSet();
- realObject.allowedProtocols = new BitSet();
- realObject.allowedAuthAlgorithms = new BitSet();
- realObject.allowedPairwiseCiphers = new BitSet();
- realObject.allowedGroupCiphers = new BitSet();
- realObject.wepKeys = new String[4];
- for (int i = 0; i < realObject.wepKeys.length; i++)
- realObject.wepKeys[i] = null;
-// for (EnterpriseField field : realObject.enterpriseFields) {
-// field.setValue(null);
-// }
- }
-
- public WifiConfiguration copy(){
- WifiConfiguration config = new WifiConfiguration();
- config.networkId = realObject.networkId;
- config.SSID = realObject.SSID;
- config.BSSID = realObject.BSSID;
- config.preSharedKey = realObject.preSharedKey;
- config.wepTxKeyIndex = realObject.wepTxKeyIndex;
- config.status = realObject.status;
- config.priority = realObject.priority;
- config.hiddenSSID = realObject.hiddenSSID;
- config.allowedKeyManagement = (BitSet) realObject.allowedKeyManagement.clone();
- config.allowedProtocols = (BitSet) realObject.allowedProtocols.clone();
- config.allowedAuthAlgorithms = (BitSet) realObject.allowedAuthAlgorithms.clone();
- config.allowedPairwiseCiphers = (BitSet) realObject.allowedPairwiseCiphers.clone();
- config.allowedGroupCiphers = (BitSet) realObject.allowedGroupCiphers.clone();
- config.wepKeys = new String[4];
- System.arraycopy(realObject.wepKeys, 0, config.wepKeys, 0, config.wepKeys.length);
- return config;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowWifiInfo.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowWifiInfo.java
deleted file mode 100644
index 943ab5831..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowWifiInfo.java
+++ /dev/null
@@ -1,20 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.net.wifi.WifiInfo;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-@Implements(WifiInfo.class)
-public class ShadowWifiInfo {
-
- private String macAddress;
-
- @Implementation
- public String getMacAddress() {
- return macAddress;
- }
-
- public void setMacAddress(String newMacAddress) {
- macAddress = newMacAddress;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowWifiManager.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowWifiManager.java
deleted file mode 100644
index 95fbdde53..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowWifiManager.java
+++ /dev/null
@@ -1,181 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.net.wifi.ScanResult;
-import android.net.wifi.WifiConfiguration;
-import android.net.wifi.WifiInfo;
-import android.net.wifi.WifiManager;
-import android.util.Pair;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-import java.util.ArrayList;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-
-@SuppressWarnings({"UnusedDeclaration"})
-@Implements(WifiManager.class)
-public class ShadowWifiManager {
- private static float sSignalLevelInPercent=1f;
- private boolean accessWifiStatePermission = true;
- private boolean wifiEnabled = true;
- private WifiInfo wifiInfo;
- private List<ScanResult> scanResults;
- private Map<Integer, WifiConfiguration> networkIdToConfiguredNetworks = new LinkedHashMap<Integer, WifiConfiguration>();
- public boolean wasSaved;
- private Pair<Integer, Boolean> lastEnabledNetwork;
-
- @Implementation
- public boolean setWifiEnabled(boolean wifiEnabled) {
- checkAccessWifiStatePermission();
- this.wifiEnabled = wifiEnabled;
- return true;
- }
-
- @Implementation
- public boolean isWifiEnabled() {
- checkAccessWifiStatePermission();
- return wifiEnabled;
- }
-
- @Implementation
- public WifiInfo getConnectionInfo() {
- checkAccessWifiStatePermission();
- if (wifiInfo == null) {
- wifiInfo = Robolectric.newInstanceOf(WifiInfo.class);
- }
- return wifiInfo;
- }
-
- @Implementation
- public List<ScanResult> getScanResults() {
- return scanResults;
- }
-
- @Implementation
- public List<WifiConfiguration> getConfiguredNetworks() {
- final ArrayList<WifiConfiguration> wifiConfigurations = new ArrayList<WifiConfiguration>();
- for (WifiConfiguration wifiConfiguration : networkIdToConfiguredNetworks.values()) {
- wifiConfigurations.add(wifiConfiguration);
- }
- return wifiConfigurations;
- }
-
- @Implementation
- public int addNetwork(WifiConfiguration config) {
- int networkId = networkIdToConfiguredNetworks.size();
- config.networkId = -1;
- networkIdToConfiguredNetworks.put(networkId, makeCopy(config, networkId));
- return networkId;
- }
-
- private WifiConfiguration makeCopy(WifiConfiguration config, int networkId) {
- WifiConfiguration copy = shadowOf(config).copy();
- copy.networkId = networkId;
- return copy;
- }
-
-
- @Implementation
- public int updateNetwork(WifiConfiguration config) {
- if (config == null || config.networkId < 0) {
- return -1;
- }
- networkIdToConfiguredNetworks.put(config.networkId, makeCopy(config, config.networkId));
- return config.networkId;
- }
-
- @Implementation
- public boolean saveConfiguration() {
- wasSaved = true;
- return true;
- }
-
- @Implementation
- public boolean enableNetwork(int netId, boolean disableOthers) {
- lastEnabledNetwork = new Pair<Integer, Boolean>(netId, disableOthers);
- return true;
- }
-
- @Implementation
- public WifiManager.WifiLock createWifiLock(int lockType, java.lang.String tag) {
- return Robolectric.newInstanceOf(WifiManager.WifiLock.class);
- }
-
- @Implementation
- public WifiManager.WifiLock createWifiLock(java.lang.String tag) {
- return createWifiLock(WifiManager.WIFI_MODE_FULL, tag);
- }
-
- @Implementation
- public static int calculateSignalLevel (int rssi, int numLevels)
- {
- return (int)(sSignalLevelInPercent*(numLevels-1));
- }
-
- public static void setSignalLevelInPercent(float level) {
- if (level < 0 || level > 1) {
- throw new IllegalArgumentException(
- "level needs to be between 0 and 1");
- }
- sSignalLevelInPercent = level;
- }
-
- public void setAccessWifiStatePermission(boolean accessWifiStatePermission) {
- this.accessWifiStatePermission = accessWifiStatePermission;
- }
-
- private void checkAccessWifiStatePermission() {
- if (!accessWifiStatePermission) {
- throw new SecurityException();
- }
- }
-
- public void setScanResults(List<ScanResult> scanResults) {
- this.scanResults = scanResults;
- }
-
- public Pair<Integer, Boolean> getLastEnabledNetwork() {
- return lastEnabledNetwork;
- }
-
-
- @Implements(WifiManager.WifiLock.class)
- public static class ShadowWifiLock {
- private int refCount;
- private boolean refCounted = true;
- private boolean locked;
- public static final int MAX_ACTIVE_LOCKS = 50;
-
- @Implementation
- public synchronized void acquire() {
- if (refCounted) {
- if (++refCount >= MAX_ACTIVE_LOCKS) throw new UnsupportedOperationException("Exceeded maximum number of wifi locks");
- } else {
- locked = true;
- }
- }
-
- @Implementation
- public synchronized void release() {
- if (refCounted) {
- if (--refCount < 0) throw new RuntimeException("WifiLock under-locked");
- } else {
- locked = false;
- }
- }
-
- @Implementation
- public synchronized boolean isHeld() {
- return refCounted ? refCount > 0 : locked;
- }
-
- @Implementation
- public void setReferenceCounted(boolean refCounted) {
- this.refCounted = refCounted;
- }
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowWindow.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowWindow.java
deleted file mode 100644
index 28f976e6a..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowWindow.java
+++ /dev/null
@@ -1,15 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.view.Window;
-import android.view.WindowManager;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-@SuppressWarnings({"UnusedDeclaration"})
-@Implements(Window.class)
-public class ShadowWindow {
- @Implementation
- public WindowManager.LayoutParams getAttributes() {
- return new WindowManager.LayoutParams();
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowZoomButtonsController.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowZoomButtonsController.java
deleted file mode 100644
index 44305d959..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/ShadowZoomButtonsController.java
+++ /dev/null
@@ -1,32 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.view.View;
-import android.widget.ZoomButtonsController;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-
-/**
- * Shadow of {@code ZoomButtonsController} that allows simulated clicking of the zoom button controls to trigger
- * events on the registered listener.
- */
-@SuppressWarnings({"UnusedDeclaration"})
-@Implements(ZoomButtonsController.class)
-public class ShadowZoomButtonsController {
- private ZoomButtonsController.OnZoomListener listener;
-
- public void __constructor__(View ownerView) {
- }
-
- @Implementation
- public void setOnZoomListener(ZoomButtonsController.OnZoomListener listener) {
- this.listener = listener;
- }
-
- public void simulateZoomInButtonClick() {
- listener.onZoom(true);
- }
-
- public void simulateZoomOutButtonClick() {
- listener.onZoom(false);
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/StatusLineStub.java b/v1/src/main/java/com/xtremelabs/robolectric/shadows/StatusLineStub.java
deleted file mode 100644
index bf329508a..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/StatusLineStub.java
+++ /dev/null
@@ -1,18 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import org.apache.http.ProtocolVersion;
-import org.apache.http.StatusLine;
-
-public class StatusLineStub implements StatusLine {
- @Override public ProtocolVersion getProtocolVersion() {
- throw new UnsupportedOperationException();
- }
-
- @Override public int getStatusCode() {
- throw new UnsupportedOperationException();
- }
-
- @Override public String getReasonPhrase() {
- throw new UnsupportedOperationException();
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/shadows/package.html b/v1/src/main/java/com/xtremelabs/robolectric/shadows/package.html
deleted file mode 100644
index 828a516f6..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/shadows/package.html
+++ /dev/null
@@ -1,29 +0,0 @@
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
-<html>
-<head>
-</head>
-<body bgcolor="white">
-
-Provides shadow implementations of classes in the Android SDK. All of the classes in this package ("Shadow" classes) are
-annotated with the {@link com.xtremelabs.robolectric.internal.Implements} annotation, which causes the implementations
-of the associated Android classes to be replaced, on a method by method basis, with their annotated counterparts on the
-Shadow class.
-
-<!--
-<h2>Package Specification</h2>
--->
-
-<!--
-<h2>Related Documentation</h2>
-
-For overviews, tutorials, examples, guides, and tool documentation, please see:
-<ul>
- <li><a href="">##### REFER TO NON-SPEC DOCUMENTATION HERE #####</a>
-</ul>
--->
-
-<!-- Put @see and @since tags down here. -->
-@see com.xtremelabs.robolectric.internal.Implements
-
-</body>
-</html> \ No newline at end of file
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/test/ConfigTestReceiver.java b/v1/src/main/java/com/xtremelabs/robolectric/test/ConfigTestReceiver.java
deleted file mode 100644
index 3ba8be575..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/test/ConfigTestReceiver.java
+++ /dev/null
@@ -1,13 +0,0 @@
-package com.xtremelabs.robolectric.test;
-
-import android.content.BroadcastReceiver;
-import android.content.Context;
-import android.content.Intent;
-
-public class ConfigTestReceiver extends BroadcastReceiver {
-
- @Override
- public void onReceive(Context context, Intent intent) {
- }
-
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/tester/android/content/TestSharedPreferences.java b/v1/src/main/java/com/xtremelabs/robolectric/tester/android/content/TestSharedPreferences.java
deleted file mode 100644
index 21f2e3ade..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/tester/android/content/TestSharedPreferences.java
+++ /dev/null
@@ -1,185 +0,0 @@
-package com.xtremelabs.robolectric.tester.android.content;
-
-import android.content.SharedPreferences;
-
-import java.util.*;
-
-public class TestSharedPreferences implements SharedPreferences {
-
- public Map<String, Map<String, Object>> content;
- protected String filename;
- public int mode;
-
- private ArrayList<OnSharedPreferenceChangeListener> listeners;
-
- public TestSharedPreferences(Map<String, Map<String, Object>> content,
- String name, int mode) {
- this.content = content;
- this.filename = name;
- this.mode = mode;
- if (!content.containsKey(name)) {
- content.put(name, new HashMap<String, Object>());
- }
-
- listeners = new ArrayList<OnSharedPreferenceChangeListener>();
- }
-
- @Override
- public Map<String, ?> getAll() {
- return new HashMap<String, Object>(content.get(filename));
- }
-
- @Override
- public String getString(String key, String defValue) {
- return (String) getValue(key, defValue);
- }
-
- private Object getValue(String key, Object defValue) {
- Map<String, Object> fileHash = content.get(filename);
- if (fileHash != null) {
- Object value = fileHash.get(key);
- if (value != null) {
- return value;
- }
- }
- return defValue;
- }
-
- @Override
- public int getInt(String key, int defValue) {
- return (Integer) getValue(key, defValue);
- }
-
- @Override
- public long getLong(String key, long defValue) {
- return (Long) getValue(key, defValue);
- }
-
- @Override
- public float getFloat(String key, float defValue) {
- return (Float) getValue(key, defValue);
- }
-
- @Override
- public boolean getBoolean(String key, boolean defValue) {
- return (Boolean) getValue(key, defValue);
- }
-
- @Override
- public boolean contains(String key) {
- return content.get(filename).containsKey(key);
- }
-
- @Override
- public Editor edit() {
- return new TestSharedPreferencesEditor();
- }
-
- @Override
- public void registerOnSharedPreferenceChangeListener(
- OnSharedPreferenceChangeListener listener) {
- if(!listeners.contains(listener))
- listeners.add(listener);
- }
-
- @Override
- public void unregisterOnSharedPreferenceChangeListener(
- OnSharedPreferenceChangeListener listener) {
- if(listeners.contains(listener))
- listeners.remove(listener);
- }
-
- public boolean hasListener(OnSharedPreferenceChangeListener listener) {
- return listeners.contains(listener);
- }
-
- private class TestSharedPreferencesEditor implements Editor {
-
- Map<String, Object> editsThatNeedCommit = new HashMap<String, Object>();
- Set<String> editsThatNeedRemove = new HashSet<String>();
- private boolean shouldClearOnCommit = false;
-
- @Override
- public Editor putString(String key, String value) {
- editsThatNeedCommit.put(key, value);
- editsThatNeedRemove.remove(key);
- return this;
- }
-
- @Override
- public Editor putInt(String key, int value) {
- editsThatNeedCommit.put(key, value);
- editsThatNeedRemove.remove(key);
- return this;
- }
-
- @Override
- public Editor putLong(String key, long value) {
- editsThatNeedCommit.put(key, value);
- editsThatNeedRemove.remove(key);
- return this;
- }
-
- @Override
- public Editor putFloat(String key, float value) {
- editsThatNeedCommit.put(key, value);
- editsThatNeedRemove.remove(key);
- return this;
- }
-
- @Override
- public Editor putBoolean(String key, boolean value) {
- editsThatNeedCommit.put(key, value);
- editsThatNeedRemove.remove(key);
- return this;
- }
-
- @Override
- public Editor remove(String key) {
- editsThatNeedRemove.add(key);
- return this;
- }
-
- @Override
- public Editor clear() {
- shouldClearOnCommit = true;
- return this;
- }
-
- @Override
- public boolean commit() {
- Map<String, Object> previousContent = content.get(filename);
- if (shouldClearOnCommit) {
- previousContent.clear();
- } else {
- for (String key : editsThatNeedCommit.keySet()) {
- previousContent.put(key, editsThatNeedCommit.get(key));
- }
- for (String key : editsThatNeedRemove) {
- previousContent.remove(key);
- }
- }
-
- for (String key : editsThatNeedCommit.keySet()) {
- previousContent.put(key, editsThatNeedCommit.get(key));
- }
-
- return true;
- }
-
- @Override
- public void apply() {
- commit();
- }
-
- @Override
- public Editor putStringSet(String key, Set<String> values) {
- return this;
- }
- }
-
- @Override
- public Set<String> getStringSet(String key, Set<String> defValues) {
- return null;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/tester/android/content/pm/StubPackageManager.java b/v1/src/main/java/com/xtremelabs/robolectric/tester/android/content/pm/StubPackageManager.java
deleted file mode 100644
index a4aca006d..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/tester/android/content/pm/StubPackageManager.java
+++ /dev/null
@@ -1,305 +0,0 @@
-package com.xtremelabs.robolectric.tester.android.content.pm;
-
-import android.content.ComponentName;
-import android.content.Intent;
-import android.content.IntentFilter;
-import android.content.pm.ActivityInfo;
-import android.content.pm.ApplicationInfo;
-import android.content.pm.FeatureInfo;
-import android.content.pm.InstrumentationInfo;
-import android.content.pm.PackageInfo;
-import android.content.pm.PackageManager;
-import android.content.pm.PermissionGroupInfo;
-import android.content.pm.PermissionInfo;
-import android.content.pm.ProviderInfo;
-import android.content.pm.ResolveInfo;
-import android.content.pm.ServiceInfo;
-import android.content.res.Resources;
-import android.content.res.XmlResourceParser;
-import android.graphics.drawable.Drawable;
-
-import java.util.List;
-
-public class StubPackageManager extends PackageManager {
- @Override
- public PackageInfo getPackageInfo(String packageName, int flags) throws NameNotFoundException {
- return null;
- }
-
- @Override public String[] currentToCanonicalPackageNames(String[] strings) {
- return new String[0];
- }
-
- @Override public String[] canonicalToCurrentPackageNames(String[] strings) {
- return new String[0];
- }
-
- @Override public Intent getLaunchIntentForPackage(String packageName) {
- return null;
- }
-
- @Override public int[] getPackageGids(String packageName) throws NameNotFoundException {
- return new int[0];
- }
-
- @Override
- public PermissionInfo getPermissionInfo(String name, int flags) throws NameNotFoundException {
- return null;
- }
-
- @Override
- public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) throws NameNotFoundException {
- return null;
- }
-
- @Override
- public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) throws NameNotFoundException {
- return null;
- }
-
- @Override public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
- return null;
- }
-
- @Override
- public ApplicationInfo getApplicationInfo(String packageName, int flags) throws NameNotFoundException {
- return null;
- }
-
- @Override
- public ActivityInfo getActivityInfo(ComponentName className, int flags) throws NameNotFoundException {
- return null;
- }
-
- @Override
- public ActivityInfo getReceiverInfo(ComponentName className, int flags) throws NameNotFoundException {
- return null;
- }
-
- @Override
- public ServiceInfo getServiceInfo(ComponentName className, int flags) throws NameNotFoundException {
- return null;
- }
-
- @Override
- public ProviderInfo getProviderInfo(ComponentName componentName, int i) throws NameNotFoundException {
- return null;
- }
-
- @Override public List<PackageInfo> getInstalledPackages(int flags) {
- return null;
- }
-
- @Override public int checkPermission(String permName, String pkgName) {
- return 0;
- }
-
- @Override public boolean addPermission(PermissionInfo info) {
- return false;
- }
-
- @Override public boolean addPermissionAsync(PermissionInfo permissionInfo) {
- return false;
- }
-
- @Override public void removePermission(String name) {
- }
-
- @Override public int checkSignatures(String pkg1, String pkg2) {
- return 0;
- }
-
- @Override public int checkSignatures(int uid1, int uid2) {
- return 0;
- }
-
- @Override public String[] getPackagesForUid(int uid) {
- return new String[0];
- }
-
- @Override public String getNameForUid(int uid) {
- return null;
- }
-
- @Override public List<ApplicationInfo> getInstalledApplications(int flags) {
- return null;
- }
-
- @Override public String[] getSystemSharedLibraryNames() {
- return new String[0];
- }
-
- @Override public FeatureInfo[] getSystemAvailableFeatures() {
- return new FeatureInfo[0];
- }
-
- @Override public boolean hasSystemFeature(String name) {
- return false;
- }
-
- @Override public ResolveInfo resolveActivity(Intent intent, int flags) {
- return null;
- }
-
- @Override public List<ResolveInfo> queryIntentActivities(Intent intent, int flags) {
- return null;
- }
-
- @Override
- public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, Intent[] specifics, Intent intent, int flags) {
- return null;
- }
-
- @Override public List<ResolveInfo> queryBroadcastReceivers(Intent intent, int flags) {
- return null;
- }
-
- @Override public ResolveInfo resolveService(Intent intent, int flags) {
- return null;
- }
-
- @Override public List<ResolveInfo> queryIntentServices(Intent intent, int flags) {
- return null;
- }
-
- @Override public ProviderInfo resolveContentProvider(String name, int flags) {
- return null;
- }
-
- @Override public List<ProviderInfo> queryContentProviders(String processName, int uid, int flags) {
- return null;
- }
-
- @Override
- public InstrumentationInfo getInstrumentationInfo(ComponentName className, int flags) throws NameNotFoundException {
- return null;
- }
-
- @Override public List<InstrumentationInfo> queryInstrumentation(String targetPackage, int flags) {
- return null;
- }
-
- @Override public Drawable getDrawable(String packageName, int resid, ApplicationInfo appInfo) {
- return null;
- }
-
- @Override public Drawable getActivityIcon(ComponentName activityName) throws NameNotFoundException {
- return null;
- }
-
- @Override public Drawable getActivityIcon(Intent intent) throws NameNotFoundException {
- return null;
- }
-
- @Override public Drawable getDefaultActivityIcon() {
- return null;
- }
-
- @Override public Drawable getApplicationIcon(ApplicationInfo info) {
- return null;
- }
-
- @Override public Drawable getApplicationIcon(String packageName) throws NameNotFoundException {
- return null;
- }
-
- @Override public Drawable getActivityLogo(ComponentName componentName) throws NameNotFoundException {
- return null;
- }
-
- @Override public Drawable getActivityLogo(Intent intent) throws NameNotFoundException {
- return null;
- }
-
- @Override public Drawable getApplicationLogo(ApplicationInfo applicationInfo) {
- return null;
- }
-
- @Override public Drawable getApplicationLogo(String s) throws NameNotFoundException {
- return null;
- }
-
- @Override public CharSequence getText(String packageName, int resid, ApplicationInfo appInfo) {
- return null;
- }
-
- @Override public XmlResourceParser getXml(String packageName, int resid, ApplicationInfo appInfo) {
- return null;
- }
-
- @Override public CharSequence getApplicationLabel(ApplicationInfo info) {
- return null;
- }
-
- @Override
- public Resources getResourcesForActivity(ComponentName activityName) throws NameNotFoundException {
- return null;
- }
-
- @Override
- public Resources getResourcesForApplication(ApplicationInfo app) throws NameNotFoundException {
- return null;
- }
-
- @Override
- public Resources getResourcesForApplication(String appPackageName) throws NameNotFoundException {
- return null;
- }
-
- @Override public String getInstallerPackageName(String packageName) {
- return null;
- }
-
- @Override public void addPackageToPreferred(String packageName) {
- }
-
- @Override public void removePackageFromPreferred(String packageName) {
- }
-
- @Override public List<PackageInfo> getPreferredPackages(int flags) {
- return null;
- }
-
- @Override
- public void addPreferredActivity(IntentFilter filter, int match, ComponentName[] set, ComponentName activity) {
- }
-
- @Override public void clearPackagePreferredActivities(String packageName) {
- }
-
- @Override
- public int getPreferredActivities(List<IntentFilter> outFilters, List<ComponentName> outActivities, String packageName) {
- return 0;
- }
-
- @Override public void setComponentEnabledSetting(ComponentName componentName, int newState, int flags) {
- }
-
- @Override public int getComponentEnabledSetting(ComponentName componentName) {
- return 0;
- }
-
- @Override public void setApplicationEnabledSetting(String packageName, int newState, int flags) {
- }
-
- @Override public int getApplicationEnabledSetting(String packageName) {
- return 0;
- }
-
- @Override public boolean isSafeMode() {
- return false;
- }
-
- @Override public void verifyPendingInstall(int id, int verificationCode) {
- }
-
- @Override public void setInstallerPackageName(String targetPackage, String installerPackageName) {
- }
-
- @Override public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, long millisecondsToDelay) {
- }
-
- @Override public List<PackageInfo> getPackagesHoldingPermissions(String[] permissions, int flags) {
- return null;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/tester/android/database/SimpleTestCursor.java b/v1/src/main/java/com/xtremelabs/robolectric/tester/android/database/SimpleTestCursor.java
deleted file mode 100644
index 9c72320ec..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/tester/android/database/SimpleTestCursor.java
+++ /dev/null
@@ -1,65 +0,0 @@
-package com.xtremelabs.robolectric.tester.android.database;
-
-import android.net.Uri;
-
-import java.util.ArrayList;
-import java.util.List;
-
-public class SimpleTestCursor extends TestCursor {
- public Uri uri;
- public String[] projection;
- public String selection;
- public String[] selectionArgs;
- public String sortOrder;
- Object[][] results = new Object[0][0];
- List<String> columnNames= new ArrayList<String>();
- int resultsIndex = -1;
- boolean closeWasCalled;
-
- @Override
- public void setQuery(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
- this.uri = uri;
- this.projection = projection;
- this.selection = selection;
- this.selectionArgs = selectionArgs;
- this.sortOrder = sortOrder;
- }
-
- @Override
- public int getColumnIndex(String columnName) {
- return columnNames.indexOf(columnName);
- }
-
- @Override
- public String getString(int columnIndex) {
- return (String) results[resultsIndex][columnIndex];
- }
-
- @Override
- public long getLong(int columnIndex) {
- return (Long) results[resultsIndex][columnIndex];
- }
-
- @Override
- public boolean moveToNext() {
- ++resultsIndex;
- return resultsIndex < results.length;
- }
-
- @Override
- public void close() {
- closeWasCalled = true;
- }
-
- public void setColumnNames(ArrayList<String> columnNames) {
- this.columnNames = columnNames;
- }
-
- public void setResults(Object[][] results) {
- this.results = results;
- }
-
- public boolean getCloseWasCalled() {
- return closeWasCalled;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/tester/android/database/TestCursor.java b/v1/src/main/java/com/xtremelabs/robolectric/tester/android/database/TestCursor.java
deleted file mode 100644
index 84a3d85b1..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/tester/android/database/TestCursor.java
+++ /dev/null
@@ -1,214 +0,0 @@
-package com.xtremelabs.robolectric.tester.android.database;
-
-import android.content.ContentResolver;
-import android.database.CharArrayBuffer;
-import android.database.ContentObserver;
-import android.database.Cursor;
-import android.database.DataSetObserver;
-import android.net.Uri;
-import android.os.Bundle;
-
-public class TestCursor implements Cursor {
- @Override
- public int getCount() {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public int getPosition() {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public boolean move(int offset) {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public boolean moveToPosition(int position) {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public boolean moveToFirst() {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public boolean moveToLast() {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public boolean moveToNext() {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public boolean moveToPrevious() {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public boolean isFirst() {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public boolean isLast() {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public boolean isBeforeFirst() {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public boolean isAfterLast() {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public int getColumnIndex(String columnName) {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public int getColumnIndexOrThrow(String columnName) throws IllegalArgumentException {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public String getColumnName(int columnIndex) {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public String[] getColumnNames() {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public int getColumnCount() {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public byte[] getBlob(int columnIndex) {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public String getString(int columnIndex) {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public void copyStringToBuffer(int columnIndex, CharArrayBuffer buffer) {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public short getShort(int columnIndex) {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public int getInt(int columnIndex) {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public long getLong(int columnIndex) {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public float getFloat(int columnIndex) {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public double getDouble(int columnIndex) {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public boolean isNull(int columnIndex) {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public void deactivate() {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public boolean requery() {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public void close() {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public boolean isClosed() {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public void registerContentObserver(ContentObserver observer) {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public void unregisterContentObserver(ContentObserver observer) {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public void registerDataSetObserver(DataSetObserver observer) {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public void unregisterDataSetObserver(DataSetObserver observer) {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public void setNotificationUri(ContentResolver cr, Uri uri) {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public boolean getWantsAllOnMoveCalls() {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public Bundle getExtras() {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public Bundle respond(Bundle extras) {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public int getType(int columnIndex) {
- throw new UnsupportedOperationException();
- }
-
- /**
- * Mimics ContentResolver.query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder)
- **/
- public void setQuery(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
- // Override this in your subclass if you care to implement any of the other methods
- // based on the query that was performed.
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/tester/android/text/TestClipboardManager.java b/v1/src/main/java/com/xtremelabs/robolectric/tester/android/text/TestClipboardManager.java
deleted file mode 100644
index 02c8948d2..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/tester/android/text/TestClipboardManager.java
+++ /dev/null
@@ -1,22 +0,0 @@
-package com.xtremelabs.robolectric.tester.android.text;
-
-import android.text.ClipboardManager;
-
-@SuppressWarnings("deprecation")
-public class TestClipboardManager extends ClipboardManager {
-
- private CharSequence text;
-
- public void setText(CharSequence text) {
- this.text = text;
- }
-
- public CharSequence getText() {
- return text;
- }
-
- public boolean hasText() {
- return text != null && text.length() > 0;
- }
-
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/tester/android/util/TestAttributeSet.java b/v1/src/main/java/com/xtremelabs/robolectric/tester/android/util/TestAttributeSet.java
deleted file mode 100644
index fd4562c3b..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/tester/android/util/TestAttributeSet.java
+++ /dev/null
@@ -1,216 +0,0 @@
-package com.xtremelabs.robolectric.tester.android.util;
-
-import android.util.AttributeSet;
-import android.view.View;
-import com.xtremelabs.robolectric.res.AttrResourceLoader;
-import com.xtremelabs.robolectric.res.ResourceExtractor;
-import com.xtremelabs.robolectric.util.I18nException;
-
-import java.util.*;
-
-public class TestAttributeSet implements AttributeSet {
- Map<String, String> attributes = new HashMap<String, String>();
- private ResourceExtractor resourceExtractor;
- private AttrResourceLoader attrResourceLoader;
- private Class<? extends View> viewClass;
- private boolean isSystem = false;
-
- /**
- * Names of attributes to be validated for i18n-safe values.
- */
- private static final String strictI18nAttrs[] = {
- "android:text",
- "android:title",
- "android:titleCondensed",
- "android:summary"
- };
-
- public TestAttributeSet() {
- this(new HashMap<String, String>());
- }
-
- public TestAttributeSet(Map<String, String> attributes, ResourceExtractor resourceExtractor,
- AttrResourceLoader attrResourceLoader, Class<? extends View> viewClass, boolean isSystem) {
- this.attributes = attributes;
- this.resourceExtractor = resourceExtractor;
- this.attrResourceLoader = attrResourceLoader;
- this.viewClass = viewClass;
- this.isSystem = isSystem;
- }
-
- public TestAttributeSet(Map<String, String> attributes) {
- this.attributes = attributes;
- this.resourceExtractor = new ResourceExtractor();
- this.attrResourceLoader = new AttrResourceLoader(this.resourceExtractor);
- this.viewClass = null;
- }
-
- public TestAttributeSet put(String name, String value) {
- attributes.put(name, value);
- return this;
- }
-
- @Override
- public boolean getAttributeBooleanValue(String namespace, String attribute, boolean defaultValue) {
- String value = getAttributeValueInMap(namespace, attribute);
- return (value != null) ? Boolean.valueOf(value) : defaultValue;
- }
-
- @Override
- public String getAttributeValue(String namespace, String attribute) {
- return getAttributeValueInMap(namespace, attribute);
- }
-
- @Override
- public int getAttributeIntValue(String namespace, String attribute, int defaultValue) {
- String value = getAttributeValueInMap(namespace, attribute);
-
- if (attrResourceLoader.hasAttributeFor(viewClass, "xxx", attribute)) {
- value = attrResourceLoader.convertValueToEnum(viewClass, "xxx", attribute, value);
- }
-
- return (value != null) ? Integer.valueOf(value) : defaultValue;
- }
-
- @Override
- public int getAttributeCount() {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public String getAttributeName(int index) {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public String getAttributeValue(int index) {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public String getPositionDescription() {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public int getAttributeNameResource(int index) {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public int getAttributeListValue(String namespace, String attribute, String[] options, int defaultValue) {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public int getAttributeUnsignedIntValue(String namespace, String attribute, int defaultValue) {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public float getAttributeFloatValue(String namespace, String attribute, float defaultValue) {
- String value = getAttributeValueInMap(namespace, attribute);
-
- if (attrResourceLoader.hasAttributeFor(viewClass, "xxx", attribute)) {
- value = attrResourceLoader.convertValueToEnum(viewClass, "xxx", attribute, value);
- }
-
- return (value != null) ? Float.valueOf(value) : defaultValue;
- }
-
- @Override
- public int getAttributeListValue(int index, String[] options, int defaultValue) {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public boolean getAttributeBooleanValue(int resourceId, boolean defaultValue) {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public int getAttributeResourceValue(String namespace, String attribute, int defaultValue) {
- String value = getAttributeValueInMap(namespace, attribute);
- Integer resourceId = defaultValue;
- if (value != null) {
- resourceId = resourceExtractor.getResourceId(value);
- }
- return resourceId == null ? defaultValue : resourceId;
- }
-
- @Override
- public int getAttributeResourceValue(int resourceId, int defaultValue) {
- String attrName = resourceExtractor.getResourceName(resourceId);
- String value = getAttributeValueInMap(null, attrName);
- return (value == null) ? defaultValue : resourceExtractor.getResourceId(value);
- }
-
- @Override
- public int getAttributeIntValue(int index, int defaultValue) {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public int getAttributeUnsignedIntValue(int index, int defaultValue) {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public float getAttributeFloatValue(int index, float defaultValue) {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public String getIdAttribute() {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public String getClassAttribute() {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public int getIdAttributeResourceValue(int defaultValue) {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public int getStyleAttribute() {
- throw new UnsupportedOperationException();
- }
-
- public void validateStrictI18n() {
- for (int i = 0; i < strictI18nAttrs.length; i++) {
- String key = strictI18nAttrs[i];
- if (attributes.containsKey(key)) {
- String value = attributes.get(key);
- if (!value.startsWith("@string/")) {
- throw new I18nException("View class: " + (viewClass != null ? viewClass.getName() : "") +
- " has attribute: " + key + " with hardcoded value: \"" + value + "\" and is not i18n-safe.");
- }
- }
- }
- }
-
- private String getAttributeValueInMap(String namespace, String attribute) {
- String value = null;
- for (String key : attributes.keySet()) {
- String[] mappedKeys = {null, key};
- if (key.contains(":")) {
- mappedKeys = key.split(":");
- }
-
- if (mappedKeys[1].equals(attribute) && (
- namespace == null || namespace != "android" ||
- (namespace.equals("android") && namespace.equals(mappedKeys[0])))) {
- value = attributes.get(key);
- break;
- }
- }
- if (value != null && isSystem && value.startsWith("@+id")) {
- value = value.replace("@+id", "@+android:id");
- }
- return value;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/tester/android/util/TestFragmentManager.java b/v1/src/main/java/com/xtremelabs/robolectric/tester/android/util/TestFragmentManager.java
deleted file mode 100644
index 115cde4a6..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/tester/android/util/TestFragmentManager.java
+++ /dev/null
@@ -1,238 +0,0 @@
-package com.xtremelabs.robolectric.tester.android.util;
-
-import android.os.Bundle;
-import android.os.Handler;
-import android.os.Looper;
-import android.support.v4.app.*;
-import android.view.View;
-import android.view.ViewGroup;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.shadows.SerializedFragmentState;
-import com.xtremelabs.robolectric.shadows.ShadowFragment;
-import com.xtremelabs.robolectric.shadows.ShadowFragmentActivity;
-
-import java.io.FileDescriptor;
-import java.io.PrintWriter;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-
-public class TestFragmentManager extends FragmentManager {
- private Map<Integer, Fragment> fragmentsById = new HashMap<Integer, Fragment>();
- private Map<String, Fragment> fragmentsByTag = new HashMap<String, Fragment>();
- private FragmentActivity activity;
- private List<TestFragmentTransaction> transactions = new ArrayList<TestFragmentTransaction>();
- private List<Runnable> transactionsToRunLater = new ArrayList<Runnable>();
-
- public TestFragmentManager(FragmentActivity activity) {
- this.activity = activity;
- }
-
- public FragmentActivity getActivity() {
- return activity;
- }
-
- @Override
- public FragmentTransaction beginTransaction() {
- return new TestFragmentTransaction(this);
- }
-
- @Override
- public boolean executePendingTransactions() {
- if (transactionsToRunLater.size() > 0) {
- for (Runnable runnable : new ArrayList<Runnable>(transactionsToRunLater)) {
- runnable.run();
- shadowOf(Looper.getMainLooper()).getScheduler().remove(runnable);
- }
- return true;
- }
- return false;
- }
-
- @Override
- public Fragment findFragmentById(int id) {
- return fragmentsById.get(id);
- }
-
- @Override
- public Fragment findFragmentByTag(String tag) {
- return fragmentsByTag.get(tag);
- }
-
- @Override
- public void popBackStack() {
- }
-
- @Override
- public boolean popBackStackImmediate() {
- return false;
- }
-
- @Override
- public void popBackStack(String name, int flags) {
- }
-
- @Override
- public boolean popBackStackImmediate(String name, int flags) {
- return false;
- }
-
- @Override
- public void popBackStack(int id, int flags) {
- }
-
- @Override
- public boolean popBackStackImmediate(int id, int flags) {
- return false;
- }
-
- @Override
- public int getBackStackEntryCount() {
- return 0;
- }
-
- @Override
- public BackStackEntry getBackStackEntryAt(int index) {
- return null;
- }
-
- @Override
- public void addOnBackStackChangedListener(OnBackStackChangedListener listener) {
- }
-
- @Override
- public void removeOnBackStackChangedListener(OnBackStackChangedListener listener) {
- }
-
- @Override
- public void putFragment(Bundle bundle, String key, Fragment fragment) {
- }
-
- @Override
- public Fragment getFragment(Bundle bundle, String key) {
- Object[] fragments = (Object[]) bundle.getSerializable(ShadowFragmentActivity.FRAGMENTS_TAG);
- for (Object object : fragments) {
- SerializedFragmentState fragment = (SerializedFragmentState) object;
- if (fragment.tag.equals(key)) {
- // TODO deserialize state
- return Robolectric.newInstanceOf(fragment.fragmentClass);
- }
- }
- return null;
- }
-
- @Override
- public Fragment.SavedState saveFragmentInstanceState(Fragment f) {
- return null;
- }
-
- @Override
- public void dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
- }
-
- public void addDialogFragment(String tag, DialogFragment fragment) {
- fragmentsByTag.put(tag, fragment);
- }
-
- public void addFragment(int containerViewId, String tag, Fragment fragment, boolean replace) {
- fragmentsById.put(containerViewId, fragment);
- fragmentsByTag.put(tag, fragment);
-
- ShadowFragment shadowFragment = shadowOf(fragment);
- shadowFragment.setTag(tag);
- shadowFragment.setContainerViewId(containerViewId);
- shadowFragment.setShouldReplace(replace);
- shadowFragment.setActivity(activity);
-
- fragment.onAttach(activity);
- fragment.onCreate(shadowFragment.getSavedInstanceState());
- }
-
- public void startFragment(Fragment fragment) {
- ViewGroup container = null;
- ShadowFragment shadowFragment = shadowOf(fragment);
- if (shadowOf(activity).getContentView() != null) {
- container = (ViewGroup) activity.findViewById(shadowFragment.getContainerViewId());
- }
-
- View view = fragment.onCreateView(activity.getLayoutInflater(), container, shadowFragment.getSavedInstanceState());
- shadowFragment.setView(view);
-
- fragment.onViewCreated(view, null);
- if (container != null) {
- if (shadowFragment.getShouldReplace()) {
- container.removeAllViews();
- }
- if (view != null) {
- container.addView(view);
- }
- }
-
- fragment.onActivityCreated(shadowFragment.getSavedInstanceState());
- fragment.onStart();
- }
-
- public HashMap<Integer, Fragment> getFragmentsById() {
- return new HashMap<Integer, Fragment>(fragmentsById);
- }
-
- public HashSet<Fragment> getFragments() {
- HashSet<Fragment> fragments = new HashSet<Fragment>();
- fragments.addAll(fragmentsById.values());
- fragments.addAll(fragmentsByTag.values());
- return fragments;
- }
-
- public List<TestFragmentTransaction> getCommittedTransactions() {
- return transactions;
- }
-
- public void commitTransaction(TestFragmentTransaction t) {
- transactions.add(t);
- if (t.isStarting()) {
- addFragment(t.getContainerViewId(), t.getTag(), t.getFragment(), t.isReplacing());
- shadowOf(t.getFragment()).setAdded(true);
- startFragment(t.getFragment());
- }
- if (t.isRemoving()) {
- Fragment fragment = t.getFragmentToRemove();
- shadowOf(fragment).setAdded(false);
- if (fragment instanceof DialogFragment) {
- ((DialogFragment)fragment).dismiss();
- }
- }
- if (t.isAttaching()) {
- shadowOf(t.getFragmentToAttach()).setAttached(true);
- }
- if (t.isHiding()) {
- Fragment fragment = t.getFragment();
- if (!fragment.isHidden()) {
- shadowOf(fragment).setHidden(true);
- fragment.onHiddenChanged(true);
- }
- }
- if (t.isShowing()) {
- Fragment fragment = t.getFragment();
- if (fragment.isHidden()) {
- shadowOf(fragment).setHidden(false);
- fragment.onHiddenChanged(false);
- }
- }
- }
-
- void commitLater(final TestFragmentTransaction testFragmentTransaction) {
- Runnable transactionCommit = new Runnable() {
- @Override
- public void run() {
- commitTransaction(testFragmentTransaction);
- transactionsToRunLater.remove(this);
- }
- };
- transactionsToRunLater.add(transactionCommit);
- new Handler().post(transactionCommit);
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/tester/android/util/TestFragmentTransaction.java b/v1/src/main/java/com/xtremelabs/robolectric/tester/android/util/TestFragmentTransaction.java
deleted file mode 100644
index 5c5a4948d..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/tester/android/util/TestFragmentTransaction.java
+++ /dev/null
@@ -1,241 +0,0 @@
-package com.xtremelabs.robolectric.tester.android.util;
-
-import android.support.v4.app.Fragment;
-import android.support.v4.app.FragmentTransaction;
-import android.view.View;
-
-public class TestFragmentTransaction extends FragmentTransaction {
-
- private TestFragmentManager fragmentManager;
- private int containerViewId;
- private String tag;
- private Fragment fragment;
- private boolean replacing;
- private boolean starting;
- private boolean removing;
- private boolean addedToBackStack;
- private boolean hiding;
- private boolean showing;
- private String backStackName;
- private int lastEnterAnimation;
- private int lastExitAnimation;
- private Fragment fragmentToRemove;
- private boolean committedAllowingStateLoss;
- private Fragment fragmentToAttach;
-
- public TestFragmentTransaction(TestFragmentManager fragmentManager) {
- this.fragmentManager = fragmentManager;
- }
-
- @Override
- public FragmentTransaction add(Fragment fragment, String tag) {
- return add(View.NO_ID, fragment, tag);
- }
-
- @Override
- public FragmentTransaction add(int containerViewId, Fragment fragment) {
- return add(containerViewId, fragment, null);
- }
-
- @Override
- public FragmentTransaction add(int containerViewId, Fragment fragment, String tag) {
- this.containerViewId = containerViewId;
- this.tag = tag;
- this.fragment = fragment;
- this.starting = true;
- return this;
- }
-
- @Override
- public FragmentTransaction replace(int containerViewId, Fragment fragment) {
- return replace(containerViewId, fragment, null);
- }
-
- @Override
- public FragmentTransaction replace(int containerViewId, Fragment fragment, String tag) {
- this.containerViewId = containerViewId;
- this.tag = tag;
- this.fragment = fragment;
- this.replacing = true;
- this.starting = true;
- return this;
- }
-
- @Override
- public FragmentTransaction remove(Fragment fragment) {
- this.fragmentToRemove = fragment;
- this.removing = true;
- return this;
- }
-
- @Override
- public FragmentTransaction hide(Fragment fragment) {
- this.fragment = fragment;
- this.hiding = true;
- this.showing = false;
- return this;
- }
-
- @Override
- public FragmentTransaction show(Fragment fragment) {
- this.fragment = fragment;
- this.showing = true;
- this.hiding = false;
- return this;
- }
-
- @Override
- public FragmentTransaction detach(Fragment fragment) {
- return null;
- }
-
- @Override
- public FragmentTransaction attach(Fragment fragment) {
- fragmentToAttach = fragment;
- return this;
- }
-
- @Override
- public boolean isEmpty() {
- return false;
- }
-
- @Override
- public FragmentTransaction setCustomAnimations(int enter, int exit) {
- this.lastEnterAnimation = enter;
- this.lastExitAnimation = exit;
- return this;
- }
-
- @Override
- public FragmentTransaction setCustomAnimations(int enter, int exit, int popEnter, int popExit) {
- return null;
- }
-
- @Override
- public FragmentTransaction setTransition(int transit) {
- return null;
- }
-
- @Override
- public FragmentTransaction setTransitionStyle(int styleRes) {
- return null;
- }
-
- @Override
- public FragmentTransaction addToBackStack(String name) {
- backStackName = name;
- addedToBackStack = true;
- return this;
- }
-
- @Override
- public boolean isAddToBackStackAllowed() {
- return false;
- }
-
- @Override
- public FragmentTransaction disallowAddToBackStack() {
- return null;
- }
-
- @Override
- public FragmentTransaction setBreadCrumbTitle(int res) {
- return null;
- }
-
- @Override
- public FragmentTransaction setBreadCrumbTitle(CharSequence text) {
- return null;
- }
-
- @Override
- public FragmentTransaction setBreadCrumbShortTitle(int res) {
- return null;
- }
-
- @Override
- public FragmentTransaction setBreadCrumbShortTitle(CharSequence text) {
- return null;
- }
-
- @Override
- public int commit() {
- fragmentManager.commitLater(this);
- return 0;
- }
-
- @Override
- public int commitAllowingStateLoss() {
- committedAllowingStateLoss = true;
- return commit();
- }
-
- public boolean isAddedToBackStack() {
- return addedToBackStack;
- }
-
- public int getContainerViewId() {
- return containerViewId;
- }
-
- public String getTag() {
- return tag;
- }
-
- public Fragment getFragment() {
- return fragment;
- }
-
- public boolean isReplacing() {
- return replacing;
- }
-
- public boolean isStarting() {
- return starting;
- }
-
- public boolean isRemoving() {
- return removing;
- }
-
- public boolean isHiding() {
- return hiding;
- }
-
- public boolean isShowing() {
- return showing;
- }
-
- public String getBackStackName() {
- return backStackName;
- }
-
- public int getLastEnterAnimation() {
- return lastEnterAnimation;
- }
-
- public int getLastExitAnimation() {
- return lastExitAnimation;
- }
-
- public TestFragmentManager getManager() {
- return fragmentManager;
- }
-
- public Fragment getFragmentToRemove() {
- return fragmentToRemove;
- }
-
- public boolean isCommittedAllowingStateLoss() {
- return committedAllowingStateLoss;
- }
-
- public boolean isAttaching() {
- return fragmentToAttach != null;
- }
-
- public Fragment getFragmentToAttach() {
- return fragmentToAttach;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/tester/android/view/TestMenu.java b/v1/src/main/java/com/xtremelabs/robolectric/tester/android/view/TestMenu.java
deleted file mode 100644
index 0ff86e16c..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/tester/android/view/TestMenu.java
+++ /dev/null
@@ -1,182 +0,0 @@
-package com.xtremelabs.robolectric.tester.android.view;
-
-import android.content.ComponentName;
-import android.content.Context;
-import android.content.Intent;
-import android.view.KeyEvent;
-import android.view.Menu;
-import android.view.MenuItem;
-import android.view.SubMenu;
-
-import java.util.ArrayList;
-import java.util.List;
-
-public class TestMenu implements Menu {
- private List<MenuItem> menuItems = new ArrayList<MenuItem>();
- private Context context;
-
- public TestMenu() {
- this(null);
- }
-
- public TestMenu(Context context) {
- this.context = context;
- }
-
- @Override
- public MenuItem add(CharSequence title) {
- return add(0, 0, 0, title);
- }
-
- @Override
- public MenuItem add(int titleRes) {
- return add(0, 0, 0, titleRes);
- }
-
- @Override
- public MenuItem add(int groupId, int itemId, int order, CharSequence title) {
- TestMenuItem menuItem = new TestMenuItem();
- menuItems.add(menuItem);
- menuItem.setItemId(itemId);
- menuItem.setTitle(title);
- return menuItem;
- }
-
- @Override
- public MenuItem add(int groupId, int itemId, int order, int titleRes) {
- return add(groupId, itemId, order, context.getResources().getString(titleRes));
- }
-
- @Override
- public SubMenu addSubMenu(CharSequence title) {
- TestSubMenu tsm = new TestSubMenu();
- TestMenuItem menuItem = new TestMenuItem();
- menuItems.add(menuItem);
- menuItem.setTitle(title);
- menuItem.setSubMenu(tsm);
- return tsm;
- }
-
- @Override
- public SubMenu addSubMenu(int titleRes) {
- TestSubMenu tsm = new TestSubMenu();
- TestMenuItem menuItem = new TestMenuItem();
- menuItems.add(menuItem);
- menuItem.setTitle(titleRes);
- menuItem.setSubMenu(tsm);
- return tsm;
- }
-
- @Override
- public SubMenu addSubMenu(int groupId, int itemId, int order, CharSequence title) {
- TestSubMenu tsm = new TestSubMenu();
- TestMenuItem menuItem = new TestMenuItem();
- menuItems.add(menuItem);
- menuItem.setItemId(itemId);
- menuItem.setTitle(title);
- menuItem.setSubMenu(tsm);
- return tsm;
- }
-
- @Override
- public SubMenu addSubMenu(int groupId, int itemId, int order, int titleRes) {
- TestSubMenu tsm = new TestSubMenu();
- TestMenuItem menuItem = new TestMenuItem();
- menuItems.add(menuItem);
- menuItem.setItemId(itemId);
- menuItem.setTitle(titleRes);
- menuItem.setSubMenu(tsm);
- return tsm;
- }
-
- @Override
- public int addIntentOptions(int groupId, int itemId, int order, ComponentName caller, Intent[] specifics,
- Intent intent, int flags, MenuItem[] outSpecificItems) {
- return 0;
- }
-
- @Override
- public void removeItem(int id) {
- MenuItem menuItem = findItem(id);
- menuItems.remove(menuItem);
- }
-
- @Override
- public void removeGroup(int groupId) {
- }
-
- @Override
- public void clear() {
- menuItems.clear();
- }
-
- @Override
- public void setGroupCheckable(int group, boolean checkable, boolean exclusive) {
- }
-
- @Override
- public void setGroupVisible(int group, boolean visible) {
- }
-
- @Override
- public void setGroupEnabled(int group, boolean enabled) {
- }
-
- @Override
- public boolean hasVisibleItems() {
- return false;
- }
-
- @Override
- public MenuItem findItem(int id) {
- for (MenuItem item : menuItems) {
- if (item.getItemId() == id) {
- return item;
- }
- }
- return null;
- }
-
- @Override
- public int size() {
- return menuItems.size();
- }
-
- @Override
- public MenuItem getItem(int index) {
- return menuItems.get(index);
- }
-
- @Override
- public void close() {
- }
-
- @Override
- public boolean performShortcut(int keyCode, KeyEvent event, int flags) {
- return false;
- }
-
- @Override
- public boolean isShortcutKey(int keyCode, KeyEvent event) {
- return false;
- }
-
- @Override
- public boolean performIdentifierAction(int id, int flags) {
- return false;
- }
-
- @Override
- public void setQwertyMode(boolean isQwerty) {
- }
-
- public TestMenuItem findMenuItem(CharSequence title) {
- for (int i = 0; i < size(); i++) {
- TestMenuItem menuItem = (TestMenuItem) getItem(i);
- if (menuItem.getTitle().equals(title)) {
- return menuItem;
- }
- }
- return null;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/tester/android/view/TestMenuItem.java b/v1/src/main/java/com/xtremelabs/robolectric/tester/android/view/TestMenuItem.java
deleted file mode 100644
index cea7467df..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/tester/android/view/TestMenuItem.java
+++ /dev/null
@@ -1,255 +0,0 @@
-package com.xtremelabs.robolectric.tester.android.view;
-
-import com.xtremelabs.robolectric.Robolectric;
-
-import android.app.Application;
-import android.content.Intent;
-import android.graphics.drawable.Drawable;
-import android.view.*;
-
-public class TestMenuItem implements MenuItem {
-
- private int itemId;
- private CharSequence title;
- private boolean enabled = true;
- private OnMenuItemClickListener menuItemClickListener;
- public int iconRes;
- private Intent intent;
- private boolean visible = true;
- private SubMenu subMenu;
-
- public TestMenuItem() {
- super();
- }
-
- public TestMenuItem(int itemId) {
- super();
- this.itemId = itemId;
- }
-
- public void setItemId(int itemId) {
- this.itemId = itemId;
- }
-
- @Override
- public int getItemId() {
- return itemId;
- }
-
- @Override
- public int getGroupId() {
- return 0;
- }
-
- @Override
- public int getOrder() {
- return 0;
- }
-
- @Override
- public MenuItem setTitle(CharSequence title) {
- this.title = title;
- return this;
- }
-
- @Override
- public MenuItem setTitle(int title) {
- return null;
- }
-
- @Override
- public CharSequence getTitle() {
- return title;
- }
-
- @Override
- public MenuItem setTitleCondensed(CharSequence title) {
- return null;
- }
-
- @Override
- public CharSequence getTitleCondensed() {
- return null;
- }
-
- @Override
- public MenuItem setIcon(Drawable icon) {
- return null;
- }
-
- @Override
- public MenuItem setIcon(int iconRes) {
- this.iconRes = iconRes;
- return this;
- }
-
- @Override
- public Drawable getIcon() {
- return null;
- }
-
- @Override
- public MenuItem setIntent(Intent intent) {
- this.intent = intent;
- return this;
- }
-
- @Override
- public Intent getIntent() {
- return this.intent;
- }
-
- @Override
- public MenuItem setShortcut(char numericChar, char alphaChar) {
- return null;
- }
-
- @Override
- public MenuItem setNumericShortcut(char numericChar) {
- return null;
- }
-
- @Override
- public char getNumericShortcut() {
- return 0;
- }
-
- @Override
- public MenuItem setAlphabeticShortcut(char alphaChar) {
- return null;
- }
-
- @Override
- public char getAlphabeticShortcut() {
- return 0;
- }
-
- @Override
- public MenuItem setCheckable(boolean checkable) {
- return null;
- }
-
- @Override
- public boolean isCheckable() {
- return false;
- }
-
- @Override
- public MenuItem setChecked(boolean checked) {
- return null;
- }
-
- @Override
- public boolean isChecked() {
- return false;
- }
-
- @Override
- public MenuItem setVisible(boolean visible) {
- this.visible = visible;
- return this;
- }
-
- @Override
- public boolean isVisible() {
- return visible;
- }
-
- @Override
- public MenuItem setEnabled(boolean enabled) {
- this.enabled = enabled;
- return this;
- }
-
- @Override
- public boolean isEnabled() {
- return enabled;
- }
-
- @Override
- public boolean hasSubMenu() {
- return subMenu != null;
- }
-
- @Override
- public SubMenu getSubMenu() {
- return subMenu;
- }
-
- public void setSubMenu(SubMenu subMenu) {
- this.subMenu = subMenu;
- }
-
- @Override
- public MenuItem setOnMenuItemClickListener(OnMenuItemClickListener menuItemClickListener) {
- this.menuItemClickListener = menuItemClickListener;
- return this;
- }
-
- @Override
- public ContextMenu.ContextMenuInfo getMenuInfo() {
- return null;
- }
-
- public void click() {
- if (enabled && menuItemClickListener != null) {
- menuItemClickListener.onMenuItemClick(this);
- } else if (enabled && intent != null) {
- Robolectric.application.startActivity(intent);
- }
- }
-
- @Override
- public void setShowAsAction(int actionEnum) {
- }
-
- @Override
- public MenuItem setShowAsActionFlags(int actionEnum) {
- return null;
- }
-
- @Override
- public MenuItem setActionView(View view) {
- return null;
- }
-
- @Override
- public MenuItem setActionView(int resId) {
- return null;
- }
-
- @Override
- public View getActionView() {
- return null;
- }
-
- @Override
- public MenuItem setActionProvider(ActionProvider actionProvider) {
- return null;
- }
-
- @Override
- public ActionProvider getActionProvider() {
- return null;
- }
-
- @Override
- public boolean expandActionView() {
- return false;
- }
-
- @Override
- public boolean collapseActionView() {
- return false;
- }
-
- @Override
- public boolean isActionViewExpanded() {
- return false;
- }
-
- @Override
- public MenuItem setOnActionExpandListener(OnActionExpandListener listener) {
- return null;
- }
-} \ No newline at end of file
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/tester/android/view/TestSubMenu.java b/v1/src/main/java/com/xtremelabs/robolectric/tester/android/view/TestSubMenu.java
deleted file mode 100644
index 6de52ecff..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/tester/android/view/TestSubMenu.java
+++ /dev/null
@@ -1,53 +0,0 @@
-package com.xtremelabs.robolectric.tester.android.view;
-
-import android.graphics.drawable.Drawable;
-import android.view.MenuItem;
-import android.view.SubMenu;
-import android.view.View;
-
-public class TestSubMenu extends TestMenu implements SubMenu {
-
- @Override
- public SubMenu setHeaderTitle(int titleRes) {
- return this;
- }
-
- @Override
- public SubMenu setHeaderTitle(CharSequence title) {
- return this;
- }
-
- @Override
- public SubMenu setHeaderIcon(int iconRes) {
- return this;
- }
-
- @Override
- public SubMenu setHeaderIcon(Drawable icon) {
- return this;
- }
-
- @Override
- public SubMenu setHeaderView(View view) {
- return this;
- }
-
- @Override
- public void clearHeader() {
- }
-
- @Override
- public SubMenu setIcon(int iconRes) {
- return this;
- }
-
- @Override
- public SubMenu setIcon(Drawable icon) {
- return this;
- }
-
- @Override
- public MenuItem getItem() {
- return null;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/tester/android/view/TestWindow.java b/v1/src/main/java/com/xtremelabs/robolectric/tester/android/view/TestWindow.java
deleted file mode 100644
index d222fe7e9..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/tester/android/view/TestWindow.java
+++ /dev/null
@@ -1,197 +0,0 @@
-package com.xtremelabs.robolectric.tester.android.view;
-
-import android.content.Context;
-import android.content.res.Configuration;
-import android.graphics.drawable.Drawable;
-import android.net.Uri;
-import android.os.Bundle;
-import android.view.InputQueue;
-import android.view.KeyEvent;
-import android.view.LayoutInflater;
-import android.view.MotionEvent;
-import android.view.SurfaceHolder;
-import android.view.View;
-import android.view.ViewGroup;
-import android.view.Window;
-import android.view.WindowManager;
-import com.xtremelabs.robolectric.Robolectric;
-
-public class TestWindow extends Window {
- public int flags;
- public int requestedFeatureId;
- public int featureDrawableResourceFeatureId;
- public int featureDrawableResourceResId;
- public int softInputMode;
- private TestWindowManager windowManager;
-
- public TestWindow(Context context) {
- super(context);
- windowManager = new TestWindowManager();
- }
-
- @Override public boolean requestFeature(int featureId) {
- this.requestedFeatureId = featureId;
- return true;
- }
-
- @Override public void setFlags(int flags, int mask) {
- this.flags = (flags & ~mask) | (flags & mask);
- }
-
- @Override public void addFlags(int flags) {
- setFlags(flags, flags);
- }
-
- @Override
- public WindowManager getWindowManager() {
- return windowManager;
- }
-
- @Override public boolean isFloating() {
- return false;
- }
-
- @Override public void takeSurface(SurfaceHolder.Callback2 callback2) {
- }
-
- @Override public void takeInputQueue(InputQueue.Callback callback) {
- }
-
- @Override public void setContentView(int layoutResID) {
- }
-
- @Override public void setContentView(View view) {
- }
-
- @Override public void setContentView(View view, ViewGroup.LayoutParams params) {
- }
-
- @Override public void addContentView(View view, ViewGroup.LayoutParams params) {
- }
-
- @Override public View getCurrentFocus() {
- return null;
- }
-
- @Override public LayoutInflater getLayoutInflater() {
- return null;
- }
-
- @Override public void setTitle(CharSequence title) {
- }
-
- @Override public void setTitleColor(int textColor) {
- }
-
- @Override public void openPanel(int featureId, KeyEvent event) {
- }
-
- @Override public void closePanel(int featureId) {
- }
-
- @Override public void togglePanel(int featureId, KeyEvent event) {
- }
-
- @Override public boolean performPanelShortcut(int featureId, int keyCode, KeyEvent event, int flags) {
- return false;
- }
-
- @Override public boolean performPanelIdentifierAction(int featureId, int id, int flags) {
- return false;
- }
-
- @Override public void closeAllPanels() {
- }
-
- @Override public boolean performContextMenuIdentifierAction(int id, int flags) {
- return false;
- }
-
- @Override public void onConfigurationChanged(Configuration newConfig) {
- }
-
- @Override public void setBackgroundDrawable(Drawable drawable) {
- }
-
- @Override public void setFeatureDrawableResource(int featureId, int resId) {
- featureDrawableResourceFeatureId = featureId;
- featureDrawableResourceResId = resId;
- }
-
- @Override public void setFeatureDrawableUri(int featureId, Uri uri) {
- }
-
- @Override public void setFeatureDrawable(int featureId, Drawable drawable) {
- }
-
- @Override public void setFeatureDrawableAlpha(int featureId, int alpha) {
- }
-
- @Override public void setFeatureInt(int featureId, int value) {
- }
-
- @Override public void takeKeyEvents(boolean get) {
- }
-
- @Override public boolean superDispatchKeyEvent(KeyEvent event) {
- return false;
- }
-
- @Override public boolean superDispatchTouchEvent(MotionEvent event) {
- return false;
- }
-
- @Override public boolean superDispatchTrackballEvent(MotionEvent event) {
- return false;
- }
-
- @Override public View getDecorView() {
- return new View(Robolectric.application);
- }
-
- @Override public View peekDecorView() {
- return null;
- }
-
- @Override public Bundle saveHierarchyState() {
- return null;
- }
-
- @Override public void restoreHierarchyState(Bundle savedInstanceState) {
- }
-
- @Override protected void onActive() {
- }
-
- @Override public void setChildDrawable(int featureId, Drawable drawable) {
- }
-
- @Override public void setChildInt(int featureId, int value) {
- }
-
- @Override public boolean isShortcutKey(int keyCode, KeyEvent event) {
- return false;
- }
-
- @Override public void setVolumeControlStream(int streamType) {
- }
-
- @Override public int getVolumeControlStream() {
- return 0;
- }
-
- @Override public void setSoftInputMode(int softInputMode) {
- this.softInputMode = softInputMode;
- }
-
- @Override public void invalidatePanelMenu(int featureId) {
- }
-
- @Override public boolean superDispatchKeyShortcutEvent(KeyEvent event) {
- return false;
- }
-
- @Override public boolean superDispatchGenericMotionEvent(MotionEvent event) {
- return false;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/tester/android/view/TestWindowManager.java b/v1/src/main/java/com/xtremelabs/robolectric/tester/android/view/TestWindowManager.java
deleted file mode 100644
index 370befca6..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/tester/android/view/TestWindowManager.java
+++ /dev/null
@@ -1,44 +0,0 @@
-package com.xtremelabs.robolectric.tester.android.view;
-
-import android.view.Display;
-import android.view.View;
-import android.view.WindowManager;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import static com.xtremelabs.robolectric.Robolectric.newInstanceOf;
-
-@SuppressWarnings({"UnusedDeclaration"})
-public class TestWindowManager implements WindowManager {
-
- private Display display;
- private List<View> views = new ArrayList<View>();
-
- @Override
- public void addView(View view, android.view.ViewGroup.LayoutParams layoutParams) {
- views.add(view);
- }
-
- @Override
- public void removeView(View view) {
- views.remove(view);
- }
-
- @Override
- public void updateViewLayout(View arg0, android.view.ViewGroup.LayoutParams arg1) {
- }
-
- @Override
- public Display getDefaultDisplay() {
- return display == null ? display = newInstanceOf(Display.class) : display;
- }
-
- @Override
- public void removeViewImmediate(View arg0) {
- }
-
- public List<View> getViews() {
- return views;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/tester/org/apache/http/FakeHttpLayer.java b/v1/src/main/java/com/xtremelabs/robolectric/tester/org/apache/http/FakeHttpLayer.java
deleted file mode 100644
index f5fa72e22..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/tester/org/apache/http/FakeHttpLayer.java
+++ /dev/null
@@ -1,404 +0,0 @@
-package com.xtremelabs.robolectric.tester.org.apache.http;
-
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.shadows.HttpResponseGenerator;
-import org.apache.http.*;
-import org.apache.http.client.RequestDirector;
-import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
-import org.apache.http.conn.ConnectTimeoutException;
-import org.apache.http.params.HttpConnectionParams;
-import org.apache.http.params.HttpParams;
-import org.apache.http.protocol.HttpContext;
-
-import java.io.IOException;
-import java.net.URI;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.regex.Pattern;
-
-public class FakeHttpLayer {
- List<HttpResponseGenerator> pendingHttpResponses = new ArrayList<HttpResponseGenerator>();
- List<HttpRequestInfo> httpRequestInfos = new ArrayList<HttpRequestInfo>();
- List<HttpEntityStub.ResponseRule> httpResponseRules = new ArrayList<HttpEntityStub.ResponseRule>();
- HttpResponse defaultHttpResponse;
- private HttpResponse defaultResponse;
- private boolean interceptHttpRequests = true;
-
- public HttpRequestInfo getLastSentHttpRequestInfo() {
- List<HttpRequestInfo> requestInfos = Robolectric.getFakeHttpLayer().getSentHttpRequestInfos();
- if (requestInfos.isEmpty()) {
- return null;
- }
- return requestInfos.get(requestInfos.size() - 1);
- }
-
- public void addPendingHttpResponse(int statusCode, String responseBody, Header... headers) {
- addPendingHttpResponse(new TestHttpResponse(statusCode, responseBody, headers));
- }
-
- public void addPendingHttpResponse(final HttpResponse httpResponse) {
- addPendingHttpResponse(new HttpResponseGenerator() {
- @Override
- public HttpResponse getResponse(HttpRequest request) {
- return httpResponse;
- }
- });
- }
-
- public void addPendingHttpResponse(HttpResponseGenerator httpResponseGenerator) {
- pendingHttpResponses.add(httpResponseGenerator);
- }
-
- public void addHttpResponseRule(String method, String uri, HttpResponse response) {
- addHttpResponseRule(new DefaultRequestMatcher(method, uri), response);
- }
-
- public void addHttpResponseRule(String uri, HttpResponse response) {
- addHttpResponseRule(new UriRequestMatcher(uri), response);
- }
-
- public void addHttpResponseRule(String uri, String response) {
- addHttpResponseRule(new UriRequestMatcher(uri), new TestHttpResponse(200, response));
- }
-
- public void addHttpResponseRule(RequestMatcher requestMatcher, HttpResponse response) {
- addHttpResponseRule(new RequestMatcherResponseRule(requestMatcher, response));
- }
-
- /**
- * Add a response rule.
- *
- * @param requestMatcher Request matcher
- * @param responses A list of responses that are returned to matching requests in order from first to last.
- */
- public void addHttpResponseRule(RequestMatcher requestMatcher, List<? extends HttpResponse> responses) {
- addHttpResponseRule(new RequestMatcherResponseRule(requestMatcher, responses));
- }
-
- public void addHttpResponseRule(HttpEntityStub.ResponseRule responseRule) {
- httpResponseRules.add(0, responseRule);
- }
-
- public void setDefaultHttpResponse(HttpResponse defaultHttpResponse) {
- this.defaultHttpResponse = defaultHttpResponse;
- }
-
- public void setDefaultHttpResponse(int statusCode, String responseBody) {
- setDefaultHttpResponse(new TestHttpResponse(statusCode, responseBody));
- }
-
- private HttpResponse findResponse(HttpRequest httpRequest) throws HttpException, IOException {
- if (!pendingHttpResponses.isEmpty()) {
- return pendingHttpResponses.remove(0).getResponse(httpRequest);
- }
-
- for (HttpEntityStub.ResponseRule httpResponseRule : httpResponseRules) {
- if (httpResponseRule.matches(httpRequest)) {
- return httpResponseRule.getResponse();
- }
- }
-
- return defaultHttpResponse;
- }
-
- public HttpResponse emulateRequest(HttpHost httpHost, HttpRequest httpRequest, HttpContext httpContext, RequestDirector requestDirector) throws HttpException, IOException {
- HttpResponse httpResponse = findResponse(httpRequest);
-
- if (httpResponse == null) {
- throw new RuntimeException("Unexpected call to execute, no pending responses are available. See Robolectric.addPendingResponse(). Request was: " +
- httpRequest.getRequestLine().getMethod() + " " + httpRequest.getRequestLine().getUri());
- } else {
- HttpParams params = httpResponse.getParams();
-
- if (HttpConnectionParams.getConnectionTimeout(params) < 0) {
- throw new ConnectTimeoutException("Socket is not connected");
- } else if (HttpConnectionParams.getSoTimeout(params) < 0) {
- throw new ConnectTimeoutException("The operation timed out");
- }
- }
-
- httpRequestInfos.add(new HttpRequestInfo(httpRequest, httpHost, httpContext, requestDirector));
-
- return httpResponse;
- }
-
- public boolean hasPendingResponses() {
- return !pendingHttpResponses.isEmpty();
- }
-
- public boolean hasRequestInfos() {
- return !httpRequestInfos.isEmpty();
- }
-
- public void clearRequestInfos() {
- httpRequestInfos.clear();
- }
-
- public boolean hasResponseRules() {
- return !httpResponseRules.isEmpty();
- }
-
- public boolean hasRequestMatchingRule(RequestMatcher rule) {
- for (HttpRequestInfo requestInfo : httpRequestInfos) {
- if (rule.matches(requestInfo.httpRequest)) {
- return true;
- }
- }
- return false;
- }
-
- public HttpResponse getDefaultResponse() {
- return defaultResponse;
- }
-
- public HttpRequestInfo getSentHttpRequestInfo(int index) {
- return httpRequestInfos.get(index);
- }
-
- public List<HttpRequestInfo> getSentHttpRequestInfos() {
- return new ArrayList<HttpRequestInfo>(httpRequestInfos);
- }
-
- public void clearHttpResponseRules() {
- httpResponseRules.clear();
- }
-
- public void clearPendingHttpResponses() {
- pendingHttpResponses.clear();
- }
-
- /**
- * You can disable Robolectric's fake HTTP layer temporarily
- * by calling this method.
- * @param interceptHttpRequests whether all HTTP requests should be
- * intercepted (true by default)
- */
- public void interceptHttpRequests(boolean interceptHttpRequests) {
- this.interceptHttpRequests = interceptHttpRequests;
- }
-
- public boolean isInterceptingHttpRequests() {
- return interceptHttpRequests;
- }
-
- public static class RequestMatcherResponseRule implements HttpEntityStub.ResponseRule {
- private RequestMatcher requestMatcher;
- private HttpResponse responseToGive;
- private IOException ioException;
- private HttpException httpException;
- private List<? extends HttpResponse> responses;
-
- public RequestMatcherResponseRule(RequestMatcher requestMatcher, HttpResponse responseToGive) {
- this.requestMatcher = requestMatcher;
- this.responseToGive = responseToGive;
- }
-
- public RequestMatcherResponseRule(RequestMatcher requestMatcher, IOException ioException) {
- this.requestMatcher = requestMatcher;
- this.ioException = ioException;
- }
-
- public RequestMatcherResponseRule(RequestMatcher requestMatcher, HttpException httpException) {
- this.requestMatcher = requestMatcher;
- this.httpException = httpException;
- }
-
- public RequestMatcherResponseRule(RequestMatcher requestMatcher, List<? extends HttpResponse> responses) {
- this.requestMatcher = requestMatcher;
- this.responses = responses;
- }
-
- @Override
- public boolean matches(HttpRequest request) {
- return requestMatcher.matches(request);
- }
-
- @Override
- public HttpResponse getResponse() throws HttpException, IOException {
- if (httpException != null) throw httpException;
- if (ioException != null) throw ioException;
- if (responseToGive != null) {
- return responseToGive;
- } else {
- if (responses.isEmpty()) {
- throw new RuntimeException("No more responses left to give");
- }
- return responses.remove(0);
- }
- }
- }
-
- public static class DefaultRequestMatcher implements RequestMatcher {
- private String method;
- private String uri;
-
- public DefaultRequestMatcher(String method, String uri) {
- this.method = method;
- this.uri = uri;
- }
-
- @Override
- public boolean matches(HttpRequest request) {
- return request.getRequestLine().getMethod().equals(method) &&
- request.getRequestLine().getUri().equals(uri);
- }
- }
-
- public static class UriRequestMatcher implements RequestMatcher {
- private String uri;
-
- public UriRequestMatcher(String uri) {
- this.uri = uri;
- }
-
- @Override
- public boolean matches(HttpRequest request) {
- return request.getRequestLine().getUri().equals(uri);
- }
- }
-
- public static class RequestMatcherBuilder implements RequestMatcher {
- private String method, hostname, path;
- private boolean noParams;
- private Map<String, String> params = new HashMap<String, String>();
- private Map<String, String> headers = new HashMap<String, String>();
- private PostBodyMatcher postBodyMatcher;
-
- public interface PostBodyMatcher {
- /**
- * Hint: you can use EntityUtils.toString(actualPostBody) to help you implement your matches method.
- *
- * @param actualPostBody The post body of the actual request that we are matching against.
- * @return true if you consider the body to match
- * @throws IOException Get turned into a RuntimeException to cause your test to fail.
- */
- boolean matches(HttpEntity actualPostBody) throws IOException;
- }
-
- public RequestMatcherBuilder method(String method) {
- this.method = method;
- return this;
- }
-
- public RequestMatcherBuilder host(String hostname) {
- this.hostname = hostname;
- return this;
- }
-
- public RequestMatcherBuilder path(String path) {
- if (path.startsWith("/")) {
- throw new RuntimeException("Path should not start with '/'");
- }
- this.path = "/" + path;
- return this;
- }
-
- public RequestMatcherBuilder param(String name, String value) {
- params.put(name, value);
- return this;
- }
-
- public RequestMatcherBuilder noParams() {
- noParams = true;
- return this;
- }
-
- public RequestMatcherBuilder postBody(PostBodyMatcher postBodyMatcher) {
- this.postBodyMatcher = postBodyMatcher;
- return this;
- }
-
- public RequestMatcherBuilder header(String name, String value) {
- headers.put(name, value);
- return this;
- }
-
- @Override
- public boolean matches(HttpRequest request) {
- URI uri = URI.create(request.getRequestLine().getUri());
- if (method != null && !method.equals(request.getRequestLine().getMethod())) {
- return false;
- }
- if (hostname != null && !hostname.equals(uri.getHost())) {
- return false;
- }
- if (path != null && !path.equals(uri.getRawPath())) {
- return false;
- }
- if (noParams && !uri.getRawQuery().equals(null)) {
- return false;
- }
- if (params.size() > 0) {
- Map<String, String> requestParams = ParamsParser.parseParams(request);
- if (!requestParams.equals(params)) {
- return false;
- }
- }
- if (headers.size() > 0) {
- Map<String, String> actualRequestHeaders = new HashMap<String, String>();
- for (Header header : request.getAllHeaders()) {
- actualRequestHeaders.put(header.getName(), header.getValue());
- }
- if (!headers.equals(actualRequestHeaders)) {
- return false;
- }
- }
- if (postBodyMatcher != null) {
- if (!(request instanceof HttpEntityEnclosingRequestBase)) {
- return false;
- }
- HttpEntityEnclosingRequestBase postOrPut = (HttpEntityEnclosingRequestBase) request;
- try {
- if (!postBodyMatcher.matches(postOrPut.getEntity())) {
- return false;
- }
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
- return true;
- }
-
- String getHostname() {
- return hostname;
- }
-
- String getPath() {
- return path;
- }
-
- String getParam(String key) {
- return params.get(key);
- }
-
- String getHeader(String key) {
- return headers.get(key);
- }
-
- boolean isNoParams() {
- return noParams;
- }
-
- String getMethod() {
- return method;
- }
- }
-
- public static class UriRegexMatcher implements RequestMatcher {
- private String method;
- private final Pattern uriRegex;
-
- public UriRegexMatcher(String method, String uriRegex) {
- this.method = method;
- this.uriRegex = Pattern.compile(uriRegex);
- }
-
- @Override
- public boolean matches(HttpRequest request) {
- return request.getRequestLine().getMethod().equals(method) &&
- uriRegex.matcher(request.getRequestLine().getUri()).matches();
- }
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/tester/org/apache/http/HttpEntityStub.java b/v1/src/main/java/com/xtremelabs/robolectric/tester/org/apache/http/HttpEntityStub.java
deleted file mode 100644
index 3d3c05c6d..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/tester/org/apache/http/HttpEntityStub.java
+++ /dev/null
@@ -1,55 +0,0 @@
-package com.xtremelabs.robolectric.tester.org.apache.http;
-
-import org.apache.http.Header;
-import org.apache.http.HttpEntity;
-import org.apache.http.HttpException;
-import org.apache.http.HttpRequest;
-import org.apache.http.HttpResponse;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-
-public class HttpEntityStub implements HttpEntity {
- @Override public boolean isRepeatable() {
- throw new UnsupportedOperationException();
- }
-
- @Override public boolean isChunked() {
- throw new UnsupportedOperationException();
- }
-
- @Override public long getContentLength() {
- throw new UnsupportedOperationException();
- }
-
- @Override public Header getContentType() {
- throw new UnsupportedOperationException();
- }
-
- @Override public Header getContentEncoding() {
- throw new UnsupportedOperationException();
- }
-
- @Override public InputStream getContent() throws IOException, IllegalStateException {
- throw new UnsupportedOperationException();
- }
-
- @Override public void writeTo(OutputStream outputStream) throws IOException {
- throw new UnsupportedOperationException();
- }
-
- @Override public boolean isStreaming() {
- throw new UnsupportedOperationException();
- }
-
- @Override public void consumeContent() throws IOException {
- throw new UnsupportedOperationException();
- }
-
- public static interface ResponseRule {
- boolean matches(HttpRequest request);
-
- HttpResponse getResponse() throws HttpException, IOException;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/tester/org/apache/http/HttpRequestInfo.java b/v1/src/main/java/com/xtremelabs/robolectric/tester/org/apache/http/HttpRequestInfo.java
deleted file mode 100644
index c174d8722..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/tester/org/apache/http/HttpRequestInfo.java
+++ /dev/null
@@ -1,36 +0,0 @@
-package com.xtremelabs.robolectric.tester.org.apache.http;
-
-import org.apache.http.HttpHost;
-import org.apache.http.HttpRequest;
-import org.apache.http.client.RequestDirector;
-import org.apache.http.protocol.HttpContext;
-
-public class HttpRequestInfo {
- HttpRequest httpRequest;
- HttpHost httpHost;
- HttpContext httpContext;
- RequestDirector requestDirector;
-
- public HttpRequestInfo(HttpRequest httpRequest, HttpHost httpHost, HttpContext httpContext, RequestDirector requestDirector) {
- this.httpRequest = httpRequest;
- this.httpHost = httpHost;
- this.httpContext = httpContext;
- this.requestDirector = requestDirector;
- }
-
- public HttpRequest getHttpRequest() {
- return httpRequest;
- }
-
- public HttpHost getHttpHost() {
- return httpHost;
- }
-
- public HttpContext getHttpContext() {
- return httpContext;
- }
-
- public RequestDirector getRequestDirector() {
- return requestDirector;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/tester/org/apache/http/HttpResponseStub.java b/v1/src/main/java/com/xtremelabs/robolectric/tester/org/apache/http/HttpResponseStub.java
deleted file mode 100644
index a325b7b0e..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/tester/org/apache/http/HttpResponseStub.java
+++ /dev/null
@@ -1,122 +0,0 @@
-package com.xtremelabs.robolectric.tester.org.apache.http;
-
-import org.apache.http.Header;
-import org.apache.http.HeaderIterator;
-import org.apache.http.HttpEntity;
-import org.apache.http.HttpResponse;
-import org.apache.http.ProtocolVersion;
-import org.apache.http.StatusLine;
-import org.apache.http.params.HttpParams;
-
-import java.util.Locale;
-
-public class HttpResponseStub implements HttpResponse {
- @Override public StatusLine getStatusLine() {
- throw new UnsupportedOperationException();
-
- }
-
- @Override public void setStatusLine(StatusLine statusLine) {
- throw new UnsupportedOperationException();
- }
-
- @Override public void setStatusLine(ProtocolVersion protocolVersion, int i) {
- throw new UnsupportedOperationException();
- }
-
- @Override public void setStatusLine(ProtocolVersion protocolVersion, int i, String s) {
- throw new UnsupportedOperationException();
- }
-
- @Override public void setStatusCode(int i) throws IllegalStateException {
- throw new UnsupportedOperationException();
- }
-
- @Override public void setReasonPhrase(String s) throws IllegalStateException {
- throw new UnsupportedOperationException();
- }
-
- @Override public HttpEntity getEntity() {
- throw new UnsupportedOperationException();
- }
-
- @Override public void setEntity(HttpEntity httpEntity) {
- throw new UnsupportedOperationException();
- }
-
- @Override public Locale getLocale() {
- throw new UnsupportedOperationException();
- }
-
- @Override public void setLocale(Locale locale) {
- throw new UnsupportedOperationException();
- }
-
- @Override public ProtocolVersion getProtocolVersion() {
- throw new UnsupportedOperationException();
- }
-
- @Override public boolean containsHeader(String s) {
- throw new UnsupportedOperationException();
- }
-
- @Override public Header[] getHeaders(String s) {
- throw new UnsupportedOperationException();
- }
-
- @Override public Header getFirstHeader(String s) {
- throw new UnsupportedOperationException();
- }
-
- @Override public Header getLastHeader(String s) {
- throw new UnsupportedOperationException();
- }
-
- @Override public Header[] getAllHeaders() {
- throw new UnsupportedOperationException();
- }
-
- @Override public void addHeader(Header header) {
- throw new UnsupportedOperationException();
- }
-
- @Override public void addHeader(String s, String s1) {
- throw new UnsupportedOperationException();
- }
-
- @Override public void setHeader(Header header) {
- throw new UnsupportedOperationException();
- }
-
- @Override public void setHeader(String s, String s1) {
- throw new UnsupportedOperationException();
- }
-
- @Override public void setHeaders(Header[] headers) {
- throw new UnsupportedOperationException();
- }
-
- @Override public void removeHeader(Header header) {
- throw new UnsupportedOperationException();
- }
-
- @Override public void removeHeaders(String s) {
- throw new UnsupportedOperationException();
- }
-
- @Override public HeaderIterator headerIterator() {
- throw new UnsupportedOperationException();
- }
-
- @Override public HeaderIterator headerIterator(String s) {
- throw new UnsupportedOperationException();
- }
-
- @Override public HttpParams getParams() {
- throw new UnsupportedOperationException();
- }
-
- @Override public void setParams(HttpParams httpParams) {
- throw new UnsupportedOperationException();
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/tester/org/apache/http/ParamsParser.java b/v1/src/main/java/com/xtremelabs/robolectric/tester/org/apache/http/ParamsParser.java
deleted file mode 100644
index 720317e1c..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/tester/org/apache/http/ParamsParser.java
+++ /dev/null
@@ -1,80 +0,0 @@
-package com.xtremelabs.robolectric.tester.org.apache.http;
-
-import org.apache.http.HttpRequest;
-import org.apache.http.client.methods.HttpPost;
-import org.apache.http.params.BasicHttpParams;
-import org.apache.http.params.HttpParams;
-import org.apache.http.util.EntityUtils;
-
-import java.io.IOException;
-import java.io.UnsupportedEncodingException;
-import java.lang.reflect.Field;
-import java.net.URI;
-import java.net.URLDecoder;
-import java.util.LinkedHashMap;
-import java.util.Map;
-import java.util.StringTokenizer;
-
-public class ParamsParser {
- public static Map<String, String> parseParams(HttpRequest request) {
- URI uri = URI.create(request.getRequestLine().getUri());
- String rawQuery = uri.getRawQuery();
- Map<String, String> params;
- if (rawQuery != null) {
- params = parseParamsFromQuery(rawQuery);
- } else if (request instanceof HttpPost && ((HttpPost) request).getEntity() != null) {
- try {
- params = parseParamsFromQuery(EntityUtils.toString(((HttpPost) request).getEntity()));
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- } else {
- HttpParams httpParams = request.getParams();
- if (httpParams instanceof BasicHttpParams) {
- Map<String, String> parameters = getPrivateMember(httpParams, "parameters");
- params = new LinkedHashMap<String, String>(parameters);
- }
- else {
- throw new RuntimeException("Was expecting a "+BasicHttpParams.class.getName());
- }
- return params;
- }
- return params;
- }
-
- private static Map<String, String> parseParamsFromQuery(String rawQuery) {
- Map<String, String> params = new LinkedHashMap<String, String>();
- StringTokenizer tok = new StringTokenizer(rawQuery, "&", false);
- while (tok.hasMoreTokens()) {
- String name, value;
- String nextParam = tok.nextToken();
- if (nextParam.contains("=")) {
- String[] nameAndValue = nextParam.split("=");
- name = nameAndValue[0];
- try {
- value = URLDecoder.decode(nameAndValue[1], "UTF-8");
- } catch (UnsupportedEncodingException e) {
- throw new RuntimeException(e);
- }
- } else {
- name = nextParam;
- value = "";
- }
- params.put(name, value);
- }
- return params;
- }
-
- private static <T> T getPrivateMember(Object obj, String name) {
- try {
- Field f = obj.getClass().getDeclaredField(name);
- f.setAccessible(true);
- //noinspection unchecked
- return (T) f.get(obj);
- } catch (NoSuchFieldException e) {
- throw new RuntimeException(e);
- } catch (IllegalAccessException e) {
- throw new RuntimeException(e);
- }
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/tester/org/apache/http/RequestMatcher.java b/v1/src/main/java/com/xtremelabs/robolectric/tester/org/apache/http/RequestMatcher.java
deleted file mode 100644
index 8cc1b6d0b..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/tester/org/apache/http/RequestMatcher.java
+++ /dev/null
@@ -1,7 +0,0 @@
-package com.xtremelabs.robolectric.tester.org.apache.http;
-
-import org.apache.http.HttpRequest;
-
-public interface RequestMatcher {
- public boolean matches(HttpRequest request);
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/tester/org/apache/http/TestHttpResponse.java b/v1/src/main/java/com/xtremelabs/robolectric/tester/org/apache/http/TestHttpResponse.java
deleted file mode 100644
index 13acd1577..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/tester/org/apache/http/TestHttpResponse.java
+++ /dev/null
@@ -1,249 +0,0 @@
-package com.xtremelabs.robolectric.tester.org.apache.http;
-
-import com.xtremelabs.robolectric.shadows.StatusLineStub;
-import org.apache.http.Header;
-import org.apache.http.HeaderIterator;
-import org.apache.http.HttpEntity;
-import org.apache.http.HttpVersion;
-import org.apache.http.ProtocolVersion;
-import org.apache.http.StatusLine;
-import org.apache.http.params.BasicHttpParams;
-import org.apache.http.params.HttpParams;
-
-import java.io.ByteArrayInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-import java.util.NoSuchElementException;
-
-public class TestHttpResponse extends HttpResponseStub {
-
- private int statusCode;
- private byte[] responseBody;
- private TestStatusLine statusLine = new TestStatusLine();
- private TestHttpEntity httpEntity = new TestHttpEntity();
- private int openEntityContentStreamCount = 0;
- private Header[] headers = new Header[0];
- private HttpParams params = new BasicHttpParams();
-
- public TestHttpResponse() {
- this.statusCode = 200;
- this.responseBody = new byte[0];
- }
-
- public TestHttpResponse(int statusCode, String responseBody) {
- this.statusCode = statusCode;
- this.responseBody = responseBody.getBytes();
- }
-
- public TestHttpResponse(int statusCode, String responseBody, Header... headers) {
- this(statusCode, responseBody.getBytes(), headers);
- }
-
- public TestHttpResponse(int statusCode, byte[] responseBody, Header... headers) {
- this.statusCode = statusCode;
- this.responseBody = responseBody.clone();
- this.headers = headers;
- }
-
- protected void setResponseBody(String responseBody) {
- this.responseBody = responseBody.getBytes();
- }
-
- @Override public StatusLine getStatusLine() {
- return statusLine;
- }
-
- @Override public HttpEntity getEntity() {
- return httpEntity;
- }
-
- @Override public Header[] getAllHeaders() {
- return headers;
- }
-
- @Override public Header getFirstHeader(String s) {
- for (Header h : headers) {
- if (s.equalsIgnoreCase(h.getName())) {
- return h;
- }
- }
- return null;
- }
-
- @Override public Header getLastHeader(String s) {
- for (int i = headers.length -1; i >= 0; i--) {
- if (headers[i].getName().equalsIgnoreCase(s)) {
- return headers[i];
- }
- }
- return null;
- }
-
- @Override public Header[] getHeaders(String s) {
- List<Header> found = new ArrayList<Header>();
- for (Header h : headers) {
- if (h.getName().equalsIgnoreCase(s)) found.add(h);
- }
- return found.toArray(new Header[found.size()]);
- }
-
- @Override
- public void addHeader(Header header) {
- List<Header> temp = new ArrayList<Header>();
- Collections.addAll(temp, headers);
- temp.add(header);
- headers = temp.toArray(new Header[temp.size()]);
- }
-
- @Override
- public void setHeader(Header newHeader) {
- for (int i = 0; i < headers.length; i++) {
- Header header = headers[i];
- if (header.getName().equals(newHeader.getName())) {
- headers[i] = newHeader;
- return;
- }
- }
- }
-
- @Override public HeaderIterator headerIterator() {
- return new HeaderIterator() {
- int index = 0;
-
- @Override public boolean hasNext() {
- return index < headers.length;
- }
-
- @Override public Header nextHeader() {
- if (index >= headers.length) throw new NoSuchElementException();
- return headers[index++];
- }
-
- @Override public Object next() {
- return nextHeader();
- }
-
- @Override public void remove() {
- throw new UnsupportedOperationException();
- }
- };
- }
-
-
- @Override public HeaderIterator headerIterator(final String s) {
- return new HeaderIterator() {
- int index = 0;
-
- @Override public boolean hasNext() {
- return nextIndex() != -1;
- }
-
- private int nextIndex() {
- for (int i = index; i<headers.length; i++) {
- if (headers[i].getName().equalsIgnoreCase(s)) {
- return i;
- }
- }
- return -1;
- }
-
- @Override public Header nextHeader() {
- index = nextIndex();
- if (index == -1) throw new NoSuchElementException();
- return headers[index++];
- }
-
- @Override public Object next() {
- return nextHeader();
- }
-
- @Override public void remove() {
- throw new UnsupportedOperationException();
- }
- };
- }
-
- @Override public boolean containsHeader(String s) {
- return getFirstHeader(s) != null;
-
- }
-
- @Override public HttpParams getParams() {
- return params;
- }
-
- @Override public void setParams(HttpParams httpParams) {
- this.params = httpParams;
- }
-
- public boolean entityContentStreamsHaveBeenClosed() {
- return openEntityContentStreamCount == 0;
- }
-
- public class TestHttpEntity extends HttpEntityStub {
-
- private ByteArrayInputStream inputStream;
-
- @Override public long getContentLength() {
- return responseBody.length;
- }
-
- @Override public Header getContentType() {
- for (Header header : headers) {
- if (header.getName().equals("Content-Type")) {
- return header;
- }
- }
- return null;
- }
-
- @Override public boolean isStreaming() {
- return true;
- }
-
- @Override public boolean isRepeatable() {
- return true;
- }
-
- @Override public InputStream getContent() throws IOException, IllegalStateException {
- openEntityContentStreamCount++;
- inputStream = new ByteArrayInputStream(responseBody) {
- @Override
- public void close() throws IOException {
- openEntityContentStreamCount--;
- super.close();
- }
- };
- return inputStream;
- }
-
- @Override public void writeTo(OutputStream outputStream) throws IOException {
- outputStream.write(responseBody);
- }
-
- @Override public void consumeContent() throws IOException {
- }
- }
-
- public class TestStatusLine extends StatusLineStub {
- @Override public ProtocolVersion getProtocolVersion() {
- return new HttpVersion(1, 0);
- }
-
- @Override public int getStatusCode() {
- return statusCode;
- }
-
- @Override public String getReasonPhrase() {
- return "HTTP status " + statusCode;
- }
-
- @Override public String toString() {
- return "TestStatusLine[" + getReasonPhrase() + "]";
- }
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/tester/org/apache/http/impl/client/DefaultRequestDirector.java b/v1/src/main/java/com/xtremelabs/robolectric/tester/org/apache/http/impl/client/DefaultRequestDirector.java
deleted file mode 100644
index 1b87c7dcf..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/tester/org/apache/http/impl/client/DefaultRequestDirector.java
+++ /dev/null
@@ -1,1163 +0,0 @@
-// copied verbatim (except for constructor access) from httpclient-4.0.3 sources
-
-/*
- * ====================================================================
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- * ====================================================================
- *
- * This software consists of voluntary contributions made by many
- * individuals on behalf of the Apache Software Foundation. For more
- * information on the Apache Software Foundation, please see
- * <http://www.apache.org/>.
- *
- */
-package com.xtremelabs.robolectric.tester.org.apache.http.impl.client;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.http.*;
-import org.apache.http.annotation.NotThreadSafe;
-import org.apache.http.auth.*;
-import org.apache.http.client.*;
-import org.apache.http.client.methods.AbortableHttpRequest;
-import org.apache.http.client.params.ClientPNames;
-import org.apache.http.client.params.HttpClientParams;
-import org.apache.http.client.protocol.ClientContext;
-import org.apache.http.client.utils.URIUtils;
-import org.apache.http.conn.*;
-import org.apache.http.conn.params.ConnManagerParams;
-import org.apache.http.conn.routing.BasicRouteDirector;
-import org.apache.http.conn.routing.HttpRoute;
-import org.apache.http.conn.routing.HttpRouteDirector;
-import org.apache.http.conn.routing.HttpRoutePlanner;
-import org.apache.http.conn.scheme.Scheme;
-import org.apache.http.entity.BufferedHttpEntity;
-import org.apache.http.impl.client.EntityEnclosingRequestWrapper;
-import org.apache.http.impl.client.RequestWrapper;
-import org.apache.http.impl.client.RoutedRequest;
-import org.apache.http.impl.client.TunnelRefusedException;
-import org.apache.http.message.BasicHttpRequest;
-import org.apache.http.params.HttpConnectionParams;
-import org.apache.http.params.HttpParams;
-import org.apache.http.params.HttpProtocolParams;
-import org.apache.http.protocol.ExecutionContext;
-import org.apache.http.protocol.HttpContext;
-import org.apache.http.protocol.HttpProcessor;
-import org.apache.http.protocol.HttpRequestExecutor;
-
-import java.io.IOException;
-import java.io.InterruptedIOException;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.util.Locale;
-import java.util.Map;
-import java.util.concurrent.TimeUnit;
-
-/**
- * Default implementation of {@link RequestDirector}.
- * <p>
- * The following parameters can be used to customize the behavior of this
- * class:
- * <ul>
- * <li>{@link org.apache.http.params.CoreProtocolPNames#PROTOCOL_VERSION}</li>
- * <li>{@link org.apache.http.params.CoreProtocolPNames#STRICT_TRANSFER_ENCODING}</li>
- * <li>{@link org.apache.http.params.CoreProtocolPNames#HTTP_ELEMENT_CHARSET}</li>
- * <li>{@link org.apache.http.params.CoreProtocolPNames#USE_EXPECT_CONTINUE}</li>
- * <li>{@link org.apache.http.params.CoreProtocolPNames#WAIT_FOR_CONTINUE}</li>
- * <li>{@link org.apache.http.params.CoreProtocolPNames#USER_AGENT}</li>
- * <li>{@link org.apache.http.params.CoreConnectionPNames#SOCKET_BUFFER_SIZE}</li>
- * <li>{@link org.apache.http.params.CoreConnectionPNames#MAX_LINE_LENGTH}</li>
- * <li>{@link org.apache.http.params.CoreConnectionPNames#MAX_HEADER_COUNT}</li>
- * <li>{@link org.apache.http.params.CoreConnectionPNames#SO_TIMEOUT}</li>
- * <li>{@link org.apache.http.params.CoreConnectionPNames#SO_LINGER}</li>
- * <li>{@link org.apache.http.params.CoreConnectionPNames#TCP_NODELAY}</li>
- * <li>{@link org.apache.http.params.CoreConnectionPNames#CONNECTION_TIMEOUT}</li>
- * <li>{@link org.apache.http.params.CoreConnectionPNames#STALE_CONNECTION_CHECK}</li>
- * <li>{@link org.apache.http.conn.params.ConnRoutePNames#FORCED_ROUTE}</li>
- * <li>{@link org.apache.http.conn.params.ConnRoutePNames#LOCAL_ADDRESS}</li>
- * <li>{@link org.apache.http.conn.params.ConnRoutePNames#DEFAULT_PROXY}</li>
- * <li>{@link org.apache.http.conn.params.ConnManagerPNames#TIMEOUT}</li>
- * <li>{@link org.apache.http.conn.params.ConnManagerPNames#MAX_CONNECTIONS_PER_ROUTE}</li>
- * <li>{@link org.apache.http.conn.params.ConnManagerPNames#MAX_TOTAL_CONNECTIONS}</li>
- * <li>{@link org.apache.http.cookie.params.CookieSpecPNames#DATE_PATTERNS}</li>
- * <li>{@link org.apache.http.cookie.params.CookieSpecPNames#SINGLE_COOKIE_HEADER}</li>
- * <li>{@link org.apache.http.auth.params.AuthPNames#CREDENTIAL_CHARSET}</li>
- * <li>{@link org.apache.http.client.params.ClientPNames#COOKIE_POLICY}</li>
- * <li>{@link org.apache.http.client.params.ClientPNames#HANDLE_AUTHENTICATION}</li>
- * <li>{@link org.apache.http.client.params.ClientPNames#HANDLE_REDIRECTS}</li>
- * <li>{@link org.apache.http.client.params.ClientPNames#MAX_REDIRECTS}</li>
- * <li>{@link org.apache.http.client.params.ClientPNames#ALLOW_CIRCULAR_REDIRECTS}</li>
- * <li>{@link org.apache.http.client.params.ClientPNames#VIRTUAL_HOST}</li>
- * <li>{@link org.apache.http.client.params.ClientPNames#DEFAULT_HOST}</li>
- * <li>{@link org.apache.http.client.params.ClientPNames#DEFAULT_HEADERS}</li>
- * </ul>
- *
- * @since 4.0
- */
-@NotThreadSafe // e.g. managedConn
-public class DefaultRequestDirector implements RequestDirector {
-
- private final Log log;
-
- /** The connection manager. */
- protected final ClientConnectionManager connManager;
-
- /** The route planner. */
- protected final HttpRoutePlanner routePlanner;
-
- /** The connection re-use strategy. */
- protected final ConnectionReuseStrategy reuseStrategy;
-
- /** The keep-alive duration strategy. */
- protected final ConnectionKeepAliveStrategy keepAliveStrategy;
-
- /** The request executor. */
- protected final HttpRequestExecutor requestExec;
-
- /** The HTTP protocol processor. */
- protected final HttpProcessor httpProcessor;
-
- /** The request retry handler. */
- protected final HttpRequestRetryHandler retryHandler;
-
- /** The redirect handler. */
- protected final RedirectHandler redirectHandler;
-
- /** The target authentication handler. */
- protected final AuthenticationHandler targetAuthHandler;
-
- /** The proxy authentication handler. */
- protected final AuthenticationHandler proxyAuthHandler;
-
- /** The user token handler. */
- protected final UserTokenHandler userTokenHandler;
-
- /** The HTTP parameters. */
- protected final HttpParams params;
-
- /** The currently allocated connection. */
- protected ManagedClientConnection managedConn;
-
- protected final AuthState targetAuthState;
-
- protected final AuthState proxyAuthState;
-
- private int redirectCount;
-
- private int maxRedirects;
-
- private HttpHost virtualHost;
-
- public DefaultRequestDirector(
- final Log log,
- final HttpRequestExecutor requestExec,
- final ClientConnectionManager conman,
- final ConnectionReuseStrategy reustrat,
- final ConnectionKeepAliveStrategy kastrat,
- final HttpRoutePlanner rouplan,
- final HttpProcessor httpProcessor,
- final HttpRequestRetryHandler retryHandler,
- final RedirectHandler redirectHandler,
- final AuthenticationHandler targetAuthHandler,
- final AuthenticationHandler proxyAuthHandler,
- final UserTokenHandler userTokenHandler,
- final HttpParams params) {
-
- if (log == null) {
- throw new IllegalArgumentException
- ("Log may not be null.");
- }
- if (requestExec == null) {
- throw new IllegalArgumentException
- ("Request executor may not be null.");
- }
- if (conman == null) {
- throw new IllegalArgumentException
- ("Client connection manager may not be null.");
- }
- if (reustrat == null) {
- throw new IllegalArgumentException
- ("Connection reuse strategy may not be null.");
- }
- if (kastrat == null) {
- throw new IllegalArgumentException
- ("Connection keep alive strategy may not be null.");
- }
- if (rouplan == null) {
- throw new IllegalArgumentException
- ("Route planner may not be null.");
- }
- if (httpProcessor == null) {
- throw new IllegalArgumentException
- ("HTTP protocol processor may not be null.");
- }
- if (retryHandler == null) {
- throw new IllegalArgumentException
- ("HTTP request retry handler may not be null.");
- }
- if (redirectHandler == null) {
- throw new IllegalArgumentException
- ("Redirect handler may not be null.");
- }
- if (targetAuthHandler == null) {
- throw new IllegalArgumentException
- ("Target authentication handler may not be null.");
- }
- if (proxyAuthHandler == null) {
- throw new IllegalArgumentException
- ("Proxy authentication handler may not be null.");
- }
- if (userTokenHandler == null) {
- throw new IllegalArgumentException
- ("User token handler may not be null.");
- }
- if (params == null) {
- throw new IllegalArgumentException
- ("HTTP parameters may not be null");
- }
- this.log = log;
- this.requestExec = requestExec;
- this.connManager = conman;
- this.reuseStrategy = reustrat;
- this.keepAliveStrategy = kastrat;
- this.routePlanner = rouplan;
- this.httpProcessor = httpProcessor;
- this.retryHandler = retryHandler;
- this.redirectHandler = redirectHandler;
- this.targetAuthHandler = targetAuthHandler;
- this.proxyAuthHandler = proxyAuthHandler;
- this.userTokenHandler = userTokenHandler;
- this.params = params;
-
- this.managedConn = null;
-
- this.redirectCount = 0;
- this.maxRedirects = this.params.getIntParameter(ClientPNames.MAX_REDIRECTS, 100);
- this.targetAuthState = new AuthState();
- this.proxyAuthState = new AuthState();
- } // constructor
-
- public DefaultRequestDirector(
- final HttpRequestExecutor requestExec,
- final ClientConnectionManager conman,
- final ConnectionReuseStrategy reustrat,
- final ConnectionKeepAliveStrategy kastrat,
- final HttpRoutePlanner rouplan,
- final HttpProcessor httpProcessor,
- final HttpRequestRetryHandler retryHandler,
- final RedirectHandler redirectHandler,
- final AuthenticationHandler targetAuthHandler,
- final AuthenticationHandler proxyAuthHandler,
- final UserTokenHandler userTokenHandler,
- final HttpParams params) {
- this(LogFactory.getLog(DefaultRequestDirector.class),
- requestExec,
- conman,
- reustrat,
- kastrat,
- rouplan,
- httpProcessor,
- retryHandler,
- redirectHandler,
- targetAuthHandler,
- proxyAuthHandler,
- userTokenHandler,
- params);
-
- }
-
- private RequestWrapper wrapRequest(
- final HttpRequest request) throws ProtocolException {
- if (request instanceof HttpEntityEnclosingRequest) {
- return new EntityEnclosingRequestWrapper(
- (HttpEntityEnclosingRequest) request);
- } else {
- return new RequestWrapper(
- request);
- }
- }
-
-
- protected void rewriteRequestURI(
- final RequestWrapper request,
- final HttpRoute route) throws ProtocolException {
- try {
-
- URI uri = request.getURI();
- if (route.getProxyHost() != null && !route.isTunnelled()) {
- // Make sure the request URI is absolute
- if (!uri.isAbsolute()) {
- HttpHost target = route.getTargetHost();
- uri = URIUtils.rewriteURI(uri, target);
- request.setURI(uri);
- }
- } else {
- // Make sure the request URI is relative
- if (uri.isAbsolute()) {
- uri = URIUtils.rewriteURI(uri, null);
- request.setURI(uri);
- }
- }
-
- } catch (URISyntaxException ex) {
- throw new ProtocolException("Invalid URI: " +
- request.getRequestLine().getUri(), ex);
- }
- }
-
-
- // non-javadoc, see interface ClientRequestDirector
- public HttpResponse execute(HttpHost target, HttpRequest request,
- HttpContext context)
- throws HttpException, IOException {
-
- HttpRequest orig = request;
- RequestWrapper origWrapper = wrapRequest(orig);
- origWrapper.setParams(params);
- HttpRoute origRoute = determineRoute(target, origWrapper, context);
-
- virtualHost = (HttpHost) orig.getParams().getParameter(
- ClientPNames.VIRTUAL_HOST);
-
- RoutedRequest roureq = new RoutedRequest(origWrapper, origRoute);
-
- long timeout = ConnManagerParams.getTimeout(params);
-
- int execCount = 0;
-
- boolean reuse = false;
- boolean done = false;
- try {
- HttpResponse response = null;
- while (!done) {
- // In this loop, the RoutedRequest may be replaced by a
- // followup request and route. The request and route passed
- // in the method arguments will be replaced. The original
- // request is still available in 'orig'.
-
- RequestWrapper wrapper = roureq.getRequest();
- HttpRoute route = roureq.getRoute();
- response = null;
-
- // See if we have a user token bound to the execution context
- Object userToken = context.getAttribute(ClientContext.USER_TOKEN);
-
- // Allocate connection if needed
- if (managedConn == null) {
- ClientConnectionRequest connRequest = connManager.requestConnection(
- route, userToken);
- if (orig instanceof AbortableHttpRequest) {
- ((AbortableHttpRequest) orig).setConnectionRequest(connRequest);
- }
-
- try {
- managedConn = connRequest.getConnection(timeout, TimeUnit.MILLISECONDS);
- } catch(InterruptedException interrupted) {
- InterruptedIOException iox = new InterruptedIOException();
- iox.initCause(interrupted);
- throw iox;
- }
-
- if (HttpConnectionParams.isStaleCheckingEnabled(params)) {
- // validate connection
- if (managedConn.isOpen()) {
- this.log.debug("Stale connection check");
- if (managedConn.isStale()) {
- this.log.debug("Stale connection detected");
- managedConn.close();
- }
- }
- }
- }
-
- if (orig instanceof AbortableHttpRequest) {
- ((AbortableHttpRequest) orig).setReleaseTrigger(managedConn);
- }
-
- // Reopen connection if needed
- if (!managedConn.isOpen()) {
- managedConn.open(route, context, params);
- } else {
- managedConn.setSocketTimeout(HttpConnectionParams.getSoTimeout(params));
- }
-
- try {
- establishRoute(route, context);
- } catch (TunnelRefusedException ex) {
- if (this.log.isDebugEnabled()) {
- this.log.debug(ex.getMessage());
- }
- response = ex.getResponse();
- break;
- }
-
- // Reset headers on the request wrapper
- wrapper.resetHeaders();
-
- // Re-write request URI if needed
- rewriteRequestURI(wrapper, route);
-
- // Use virtual host if set
- target = virtualHost;
-
- if (target == null) {
- target = route.getTargetHost();
- }
-
- HttpHost proxy = route.getProxyHost();
-
- // Populate the execution context
- context.setAttribute(ExecutionContext.HTTP_TARGET_HOST,
- target);
- context.setAttribute(ExecutionContext.HTTP_PROXY_HOST,
- proxy);
- context.setAttribute(ExecutionContext.HTTP_CONNECTION,
- managedConn);
- context.setAttribute(ClientContext.TARGET_AUTH_STATE,
- targetAuthState);
- context.setAttribute(ClientContext.PROXY_AUTH_STATE,
- proxyAuthState);
-
- // Run request protocol interceptors
- requestExec.preProcess(wrapper, httpProcessor, context);
-
- boolean retrying = true;
- Exception retryReason = null;
- while (retrying) {
- // Increment total exec count (with redirects)
- execCount++;
- // Increment exec count for this particular request
- wrapper.incrementExecCount();
- if (!wrapper.isRepeatable()) {
- this.log.debug("Cannot retry non-repeatable request");
- if (retryReason != null) {
- throw new NonRepeatableRequestException("Cannot retry request " +
- "with a non-repeatable request entity. The cause lists the " +
- "reason the original request failed: " + retryReason);
- } else {
- throw new NonRepeatableRequestException("Cannot retry request " +
- "with a non-repeatable request entity.");
- }
- }
-
- try {
- if (this.log.isDebugEnabled()) {
- this.log.debug("Attempt " + execCount + " to execute request");
- }
- response = requestExec.execute(wrapper, managedConn, context);
- retrying = false;
-
- } catch (IOException ex) {
- this.log.debug("Closing the connection.");
- managedConn.close();
- if (retryHandler.retryRequest(ex, wrapper.getExecCount(), context)) {
- if (this.log.isInfoEnabled()) {
- this.log.info("I/O exception ("+ ex.getClass().getName() +
- ") caught when processing request: "
- + ex.getMessage());
- }
- if (this.log.isDebugEnabled()) {
- this.log.debug(ex.getMessage(), ex);
- }
- this.log.info("Retrying request");
- retryReason = ex;
- } else {
- throw ex;
- }
-
- // If we have a direct route to the target host
- // just re-open connection and re-try the request
- if (!route.isTunnelled()) {
- this.log.debug("Reopening the direct connection.");
- managedConn.open(route, context, params);
- } else {
- // otherwise give up
- this.log.debug("Proxied connection. Need to start over.");
- retrying = false;
- }
-
- }
-
- }
-
- if (response == null) {
- // Need to start over
- continue;
- }
-
- // Run response protocol interceptors
- response.setParams(params);
- requestExec.postProcess(response, httpProcessor, context);
-
-
- // The connection is in or can be brought to a re-usable state.
- reuse = reuseStrategy.keepAlive(response, context);
- if (reuse) {
- // Set the idle duration of this connection
- long duration = keepAliveStrategy.getKeepAliveDuration(response, context);
- managedConn.setIdleDuration(duration, TimeUnit.MILLISECONDS);
-
- if (this.log.isDebugEnabled()) {
- if (duration >= 0) {
- this.log.debug("Connection can be kept alive for " + duration + " ms");
- } else {
- this.log.debug("Connection can be kept alive indefinitely");
- }
- }
- }
-
- RoutedRequest followup = handleResponse(roureq, response, context);
- if (followup == null) {
- done = true;
- } else {
- if (reuse) {
- // Make sure the response body is fully consumed, if present
- HttpEntity entity = response.getEntity();
- if (entity != null) {
- entity.consumeContent();
- }
- // entity consumed above is not an auto-release entity,
- // need to mark the connection re-usable explicitly
- managedConn.markReusable();
- } else {
- managedConn.close();
- }
- // check if we can use the same connection for the followup
- if (!followup.getRoute().equals(roureq.getRoute())) {
- releaseConnection();
- }
- roureq = followup;
- }
-
- if (managedConn != null && userToken == null) {
- userToken = userTokenHandler.getUserToken(context);
- context.setAttribute(ClientContext.USER_TOKEN, userToken);
- if (userToken != null) {
- managedConn.setState(userToken);
- }
- }
-
- } // while not done
-
-
- // check for entity, release connection if possible
- if ((response == null) || (response.getEntity() == null) ||
- !response.getEntity().isStreaming()) {
- // connection not needed and (assumed to be) in re-usable state
- if (reuse)
- managedConn.markReusable();
- releaseConnection();
- } else {
- // install an auto-release entity
- HttpEntity entity = response.getEntity();
- entity = new BasicManagedEntity(entity, managedConn, reuse);
- response.setEntity(entity);
- }
-
- return response;
-
- } catch (HttpException ex) {
- abortConnection();
- throw ex;
- } catch (IOException ex) {
- abortConnection();
- throw ex;
- } catch (RuntimeException ex) {
- abortConnection();
- throw ex;
- }
- } // execute
-
- /**
- * Returns the connection back to the connection manager
- * and prepares for retrieving a new connection during
- * the next request.
- */
- protected void releaseConnection() {
- // Release the connection through the ManagedConnection instead of the
- // ConnectionManager directly. This lets the connection control how
- // it is released.
- try {
- managedConn.releaseConnection();
- } catch(IOException ignored) {
- this.log.debug("IOException releasing connection", ignored);
- }
- managedConn = null;
- }
-
- /**
- * Determines the route for a request.
- * Called by {@link #execute}
- * to determine the route for either the original or a followup request.
- *
- * @param target the target host for the request.
- * Implementations may accept <code>null</code>
- * if they can still determine a route, for example
- * to a default target or by inspecting the request.
- * @param request the request to execute
- * @param context the context to use for the execution,
- * never <code>null</code>
- *
- * @return the route the request should take
- *
- * @throws HttpException in case of a problem
- */
- protected HttpRoute determineRoute(HttpHost target,
- HttpRequest request,
- HttpContext context)
- throws HttpException {
-
- if (target == null) {
- target = (HttpHost) request.getParams().getParameter(
- ClientPNames.DEFAULT_HOST);
- }
- if (target == null) {
- throw new IllegalStateException
- ("Target host must not be null, or set in parameters.");
- }
-
- return this.routePlanner.determineRoute(target, request, context);
- }
-
-
- /**
- * Establishes the target route.
- *
- * @param route the route to establish
- * @param context the context for the request execution
- *
- * @throws HttpException in case of a problem
- * @throws IOException in case of an IO problem
- */
- protected void establishRoute(HttpRoute route, HttpContext context)
- throws HttpException, IOException {
-
- HttpRouteDirector rowdy = new BasicRouteDirector();
- int step;
- do {
- HttpRoute fact = managedConn.getRoute();
- step = rowdy.nextStep(route, fact);
-
- switch (step) {
-
- case HttpRouteDirector.CONNECT_TARGET:
- case HttpRouteDirector.CONNECT_PROXY:
- managedConn.open(route, context, this.params);
- break;
-
- case HttpRouteDirector.TUNNEL_TARGET: {
- boolean secure = createTunnelToTarget(route, context);
- this.log.debug("Tunnel to target created.");
- managedConn.tunnelTarget(secure, this.params);
- } break;
-
- case HttpRouteDirector.TUNNEL_PROXY: {
- // The most simple example for this case is a proxy chain
- // of two proxies, where P1 must be tunnelled to P2.
- // route: Source -> P1 -> P2 -> Target (3 hops)
- // fact: Source -> P1 -> Target (2 hops)
- final int hop = fact.getHopCount()-1; // the hop to establish
- boolean secure = createTunnelToProxy(route, hop, context);
- this.log.debug("Tunnel to proxy created.");
- managedConn.tunnelProxy(route.getHopTarget(hop),
- secure, this.params);
- } break;
-
-
- case HttpRouteDirector.LAYER_PROTOCOL:
- managedConn.layerProtocol(context, this.params);
- break;
-
- case HttpRouteDirector.UNREACHABLE:
- throw new IllegalStateException
- ("Unable to establish route." +
- "\nplanned = " + route +
- "\ncurrent = " + fact);
-
- case HttpRouteDirector.COMPLETE:
- // do nothing
- break;
-
- default:
- throw new IllegalStateException
- ("Unknown step indicator "+step+" from RouteDirector.");
- } // switch
-
- } while (step > HttpRouteDirector.COMPLETE);
-
- } // establishConnection
-
-
- /**
- * Creates a tunnel to the target server.
- * The connection must be established to the (last) proxy.
- * A CONNECT request for tunnelling through the proxy will
- * be created and sent, the response received and checked.
- * This method does <i>not</i> update the connection with
- * information about the tunnel, that is left to the caller.
- *
- * @param route the route to establish
- * @param context the context for request execution
- *
- * @return <code>true</code> if the tunnelled route is secure,
- * <code>false</code> otherwise.
- * The implementation here always returns <code>false</code>,
- * but derived classes may override.
- *
- * @throws HttpException in case of a problem
- * @throws IOException in case of an IO problem
- */
- protected boolean createTunnelToTarget(HttpRoute route,
- HttpContext context)
- throws HttpException, IOException {
-
- HttpHost proxy = route.getProxyHost();
- HttpHost target = route.getTargetHost();
- HttpResponse response = null;
-
- boolean done = false;
- while (!done) {
-
- done = true;
-
- if (!this.managedConn.isOpen()) {
- this.managedConn.open(route, context, this.params);
- }
-
- HttpRequest connect = createConnectRequest(route, context);
- connect.setParams(this.params);
-
- // Populate the execution context
- context.setAttribute(ExecutionContext.HTTP_TARGET_HOST,
- target);
- context.setAttribute(ExecutionContext.HTTP_PROXY_HOST,
- proxy);
- context.setAttribute(ExecutionContext.HTTP_CONNECTION,
- managedConn);
- context.setAttribute(ClientContext.TARGET_AUTH_STATE,
- targetAuthState);
- context.setAttribute(ClientContext.PROXY_AUTH_STATE,
- proxyAuthState);
- context.setAttribute(ExecutionContext.HTTP_REQUEST,
- connect);
-
- this.requestExec.preProcess(connect, this.httpProcessor, context);
-
- response = this.requestExec.execute(connect, this.managedConn, context);
-
- response.setParams(this.params);
- this.requestExec.postProcess(response, this.httpProcessor, context);
-
- int status = response.getStatusLine().getStatusCode();
- if (status < 200) {
- throw new HttpException("Unexpected response to CONNECT request: " +
- response.getStatusLine());
- }
-
- CredentialsProvider credsProvider = (CredentialsProvider)
- context.getAttribute(ClientContext.CREDS_PROVIDER);
-
- if (credsProvider != null && HttpClientParams.isAuthenticating(params)) {
- if (this.proxyAuthHandler.isAuthenticationRequested(response, context)) {
-
- this.log.debug("Proxy requested authentication");
- Map<String, Header> challenges = this.proxyAuthHandler.getChallenges(
- response, context);
- try {
- processChallenges(
- challenges, this.proxyAuthState, this.proxyAuthHandler,
- response, context);
- } catch (AuthenticationException ex) {
- if (this.log.isWarnEnabled()) {
- this.log.warn("Authentication error: " + ex.getMessage());
- break;
- }
- }
- updateAuthState(this.proxyAuthState, proxy, credsProvider);
-
- if (this.proxyAuthState.getCredentials() != null) {
- done = false;
-
- // Retry request
- if (this.reuseStrategy.keepAlive(response, context)) {
- this.log.debug("Connection kept alive");
- // Consume response content
- HttpEntity entity = response.getEntity();
- if (entity != null) {
- entity.consumeContent();
- }
- } else {
- this.managedConn.close();
- }
-
- }
-
- } else {
- // Reset proxy auth scope
- this.proxyAuthState.setAuthScope(null);
- }
- }
- }
-
- int status = response.getStatusLine().getStatusCode(); // can't be null
-
- if (status > 299) {
-
- // Buffer response content
- HttpEntity entity = response.getEntity();
- if (entity != null) {
- response.setEntity(new BufferedHttpEntity(entity));
- }
-
- this.managedConn.close();
- throw new TunnelRefusedException("CONNECT refused by proxy: " +
- response.getStatusLine(), response);
- }
-
- this.managedConn.markReusable();
-
- // How to decide on security of the tunnelled connection?
- // The socket factory knows only about the segment to the proxy.
- // Even if that is secure, the hop to the target may be insecure.
- // Leave it to derived classes, consider insecure by default here.
- return false;
-
- } // createTunnelToTarget
-
-
-
- /**
- * Creates a tunnel to an intermediate proxy.
- * This method is <i>not</i> implemented in this class.
- * It just throws an exception here.
- *
- * @param route the route to establish
- * @param hop the hop in the route to establish now.
- * <code>route.getHopTarget(hop)</code>
- * will return the proxy to tunnel to.
- * @param context the context for request execution
- *
- * @return <code>true</code> if the partially tunnelled connection
- * is secure, <code>false</code> otherwise.
- *
- * @throws HttpException in case of a problem
- * @throws IOException in case of an IO problem
- */
- protected boolean createTunnelToProxy(HttpRoute route, int hop,
- HttpContext context)
- throws HttpException, IOException {
-
- // Have a look at createTunnelToTarget and replicate the parts
- // you need in a custom derived class. If your proxies don't require
- // authentication, it is not too hard. But for the stock version of
- // HttpClient, we cannot make such simplifying assumptions and would
- // have to include proxy authentication code. The HttpComponents team
- // is currently not in a position to support rarely used code of this
- // complexity. Feel free to submit patches that refactor the code in
- // createTunnelToTarget to facilitate re-use for proxy tunnelling.
-
- throw new UnsupportedOperationException
- ("Proxy chains are not supported.");
- }
-
-
-
- /**
- * Creates the CONNECT request for tunnelling.
- * Called by {@link #createTunnelToTarget createTunnelToTarget}.
- *
- * @param route the route to establish
- * @param context the context for request execution
- *
- * @return the CONNECT request for tunnelling
- */
- protected HttpRequest createConnectRequest(HttpRoute route,
- HttpContext context) {
- // see RFC 2817, section 5.2 and
- // INTERNET-DRAFT: Tunneling TCP based protocols through
- // Web proxy servers
-
- HttpHost target = route.getTargetHost();
-
- String host = target.getHostName();
- int port = target.getPort();
- if (port < 0) {
- Scheme scheme = connManager.getSchemeRegistry().
- getScheme(target.getSchemeName());
- port = scheme.getDefaultPort();
- }
-
- StringBuilder buffer = new StringBuilder(host.length() + 6);
- buffer.append(host);
- buffer.append(':');
- buffer.append(Integer.toString(port));
-
- String authority = buffer.toString();
- ProtocolVersion ver = HttpProtocolParams.getVersion(params);
- HttpRequest req = new BasicHttpRequest
- ("CONNECT", authority, ver);
-
- return req;
- }
-
-
- /**
- * Analyzes a response to check need for a followup.
- *
- * @param roureq the request and route.
- * @param response the response to analayze
- * @param context the context used for the current request execution
- *
- * @return the followup request and route if there is a followup, or
- * <code>null</code> if the response should be returned as is
- *
- * @throws HttpException in case of a problem
- * @throws IOException in case of an IO problem
- */
- protected RoutedRequest handleResponse(RoutedRequest roureq,
- HttpResponse response,
- HttpContext context)
- throws HttpException, IOException {
-
- HttpRoute route = roureq.getRoute();
- RequestWrapper request = roureq.getRequest();
-
- HttpParams params = request.getParams();
- if (HttpClientParams.isRedirecting(params) &&
- this.redirectHandler.isRedirectRequested(response, context)) {
-
- if (redirectCount >= maxRedirects) {
- throw new RedirectException("Maximum redirects ("
- + maxRedirects + ") exceeded");
- }
- redirectCount++;
-
- // Virtual host cannot be used any longer
- virtualHost = null;
-
- URI uri = this.redirectHandler.getLocationURI(response, context);
-
- HttpHost newTarget = new HttpHost(
- uri.getHost(),
- uri.getPort(),
- uri.getScheme());
-
- // Unset auth scope
- targetAuthState.setAuthScope(null);
- proxyAuthState.setAuthScope(null);
-
- // Invalidate auth states if redirecting to another host
- if (!route.getTargetHost().equals(newTarget)) {
- targetAuthState.invalidate();
- AuthScheme authScheme = proxyAuthState.getAuthScheme();
- if (authScheme != null && authScheme.isConnectionBased()) {
- proxyAuthState.invalidate();
- }
- }
-
- HttpRedirect redirect = new HttpRedirect(request.getMethod(), uri);
- HttpRequest orig = request.getOriginal();
- redirect.setHeaders(orig.getAllHeaders());
-
- RequestWrapper wrapper = new RequestWrapper(redirect);
- wrapper.setParams(params);
-
- HttpRoute newRoute = determineRoute(newTarget, wrapper, context);
- RoutedRequest newRequest = new RoutedRequest(wrapper, newRoute);
-
- if (this.log.isDebugEnabled()) {
- this.log.debug("Redirecting to '" + uri + "' via " + newRoute);
- }
-
- return newRequest;
- }
-
- CredentialsProvider credsProvider = (CredentialsProvider)
- context.getAttribute(ClientContext.CREDS_PROVIDER);
-
- if (credsProvider != null && HttpClientParams.isAuthenticating(params)) {
-
- if (this.targetAuthHandler.isAuthenticationRequested(response, context)) {
-
- HttpHost target = (HttpHost)
- context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
- if (target == null) {
- target = route.getTargetHost();
- }
-
- this.log.debug("Target requested authentication");
- Map<String, Header> challenges = this.targetAuthHandler.getChallenges(
- response, context);
- try {
- processChallenges(challenges,
- this.targetAuthState, this.targetAuthHandler,
- response, context);
- } catch (AuthenticationException ex) {
- if (this.log.isWarnEnabled()) {
- this.log.warn("Authentication error: " + ex.getMessage());
- return null;
- }
- }
- updateAuthState(this.targetAuthState, target, credsProvider);
-
- if (this.targetAuthState.getCredentials() != null) {
- // Re-try the same request via the same route
- return roureq;
- } else {
- return null;
- }
- } else {
- // Reset target auth scope
- this.targetAuthState.setAuthScope(null);
- }
-
- if (this.proxyAuthHandler.isAuthenticationRequested(response, context)) {
-
- HttpHost proxy = route.getProxyHost();
-
- this.log.debug("Proxy requested authentication");
- Map<String, Header> challenges = this.proxyAuthHandler.getChallenges(
- response, context);
- try {
- processChallenges(challenges,
- this.proxyAuthState, this.proxyAuthHandler,
- response, context);
- } catch (AuthenticationException ex) {
- if (this.log.isWarnEnabled()) {
- this.log.warn("Authentication error: " + ex.getMessage());
- return null;
- }
- }
- updateAuthState(this.proxyAuthState, proxy, credsProvider);
-
- if (this.proxyAuthState.getCredentials() != null) {
- // Re-try the same request via the same route
- return roureq;
- } else {
- return null;
- }
- } else {
- // Reset proxy auth scope
- this.proxyAuthState.setAuthScope(null);
- }
- }
- return null;
- } // handleResponse
-
-
- /**
- * Shuts down the connection.
- * This method is called from a <code>catch</code> block in
- * {@link #execute execute} during exception handling.
- */
- private void abortConnection() {
- ManagedClientConnection mcc = managedConn;
- if (mcc != null) {
- // we got here as the result of an exception
- // no response will be returned, release the connection
- managedConn = null;
- try {
- mcc.abortConnection();
- } catch (IOException ex) {
- if (this.log.isDebugEnabled()) {
- this.log.debug(ex.getMessage(), ex);
- }
- }
- // ensure the connection manager properly releases this connection
- try {
- mcc.releaseConnection();
- } catch(IOException ignored) {
- this.log.debug("Error releasing connection", ignored);
- }
- }
- } // abortConnection
-
-
- private void processChallenges(
- final Map<String, Header> challenges,
- final AuthState authState,
- final AuthenticationHandler authHandler,
- final HttpResponse response,
- final HttpContext context)
- throws MalformedChallengeException, AuthenticationException {
-
- AuthScheme authScheme = authState.getAuthScheme();
- if (authScheme == null) {
- // Authentication not attempted before
- authScheme = authHandler.selectScheme(challenges, response, context);
- authState.setAuthScheme(authScheme);
- }
- String id = authScheme.getSchemeName();
-
- Header challenge = challenges.get(id.toLowerCase(Locale.ENGLISH));
- if (challenge == null) {
- throw new AuthenticationException(id +
- " authorization challenge expected, but not found");
- }
- authScheme.processChallenge(challenge);
- this.log.debug("Authorization challenge processed");
- }
-
-
- private void updateAuthState(
- final AuthState authState,
- final HttpHost host,
- final CredentialsProvider credsProvider) {
-
- if (!authState.isValid()) {
- return;
- }
-
- String hostname = host.getHostName();
- int port = host.getPort();
- if (port < 0) {
- Scheme scheme = connManager.getSchemeRegistry().getScheme(host);
- port = scheme.getDefaultPort();
- }
-
- AuthScheme authScheme = authState.getAuthScheme();
- AuthScope authScope = new AuthScope(
- hostname,
- port,
- authScheme.getRealm(),
- authScheme.getSchemeName());
-
- if (this.log.isDebugEnabled()) {
- this.log.debug("Authentication scope: " + authScope);
- }
- Credentials creds = authState.getCredentials();
- if (creds == null) {
- creds = credsProvider.getCredentials(authScope);
- if (this.log.isDebugEnabled()) {
- if (creds != null) {
- this.log.debug("Found credentials");
- } else {
- this.log.debug("Credentials not found");
- }
- }
- } else {
- if (authScheme.isComplete()) {
- this.log.debug("Authentication failed");
- creds = null;
- }
- }
- authState.setAuthScope(authScope);
- authState.setCredentials(creds);
- }
-
-} // class DefaultClientRequestDirector
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/tester/org/apache/http/impl/client/HttpRedirect.java b/v1/src/main/java/com/xtremelabs/robolectric/tester/org/apache/http/impl/client/HttpRedirect.java
deleted file mode 100644
index fae9bfd1d..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/tester/org/apache/http/impl/client/HttpRedirect.java
+++ /dev/null
@@ -1,64 +0,0 @@
-// copied verbatim from httpclient-4.0.3 sources
-
-/*
- * ====================================================================
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- * ====================================================================
- *
- * This software consists of voluntary contributions made by many
- * individuals on behalf of the Apache Software Foundation. For more
- * information on the Apache Software Foundation, please see
- * <http://www.apache.org/>.
- *
- */
-package com.xtremelabs.robolectric.tester.org.apache.http.impl.client;
-
-import java.net.URI;
-
-import org.apache.http.client.methods.HttpGet;
-import org.apache.http.client.methods.HttpHead;
-import org.apache.http.client.methods.HttpRequestBase;
-
-import org.apache.http.annotation.NotThreadSafe;
-
-/**
- * Redirect request (can be either GET or HEAD).
- *
- * @since 4.0
- */
-@NotThreadSafe
-class HttpRedirect extends HttpRequestBase {
-
- private String method;
-
- public HttpRedirect(final String method, final URI uri) {
- super();
- if (method.equalsIgnoreCase(HttpHead.METHOD_NAME)) {
- this.method = HttpHead.METHOD_NAME;
- } else {
- this.method = HttpGet.METHOD_NAME;
- }
- setURI(uri);
- }
-
- @Override
- public String getMethod() {
- return this.method;
- }
-
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/util/DatabaseConfig.java b/v1/src/main/java/com/xtremelabs/robolectric/util/DatabaseConfig.java
deleted file mode 100644
index e14dcc507..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/util/DatabaseConfig.java
+++ /dev/null
@@ -1,133 +0,0 @@
-package com.xtremelabs.robolectric.util;
-
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Inherited;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
-import java.sql.Connection;
-import java.sql.DriverManager;
-import java.sql.SQLException;
-
-
-public class DatabaseConfig {
- private static DatabaseMap dbMap = null;
- private static boolean isLoaded = false;
-
- public static void setDatabaseMap(DatabaseMap map) {
- dbMap = map;
- isLoaded = false; //make sure to reset isLoaded or mixing databases in a test suite will fail.
- }
-
- public static DatabaseMap getDatabaseMap() {
- return dbMap;
- }
-
- /**
- * check if the map has been loaded
- *
- * @return
- */
- public static boolean isMapLoaded() {
- return isLoaded;
- }
-
- /**
- * Check if the map has been set at all.
- *
- * @return
- */
- public static boolean isMapNull() {
- return dbMap == null;
- }
-
- /**
- * Sets what database will be used and loads the database driver, based on what DBmap is provided.
- */
- private static void LoadSQLiteDriver() {
- if (isMapNull()) throw new NullDatabaseMapException("Error in DatabaseConfig: DatabaseMap has not been set.");
- try {
- Class.forName(dbMap.getDriverClassName()).newInstance();
- } catch (InstantiationException e) {
- throw new CannotLoadDatabaseMapDriverException("Error in DatabaseConfig: SQLite driver could not be instantiated;", e);
- } catch (IllegalAccessException e) {
- throw new CannotLoadDatabaseMapDriverException("Error in DatabaseConfig: SQLite driver could not be accessed;", e);
- } catch (ClassNotFoundException e) {
- throw new CannotLoadDatabaseMapDriverException("Error in DatabaseConfig: SQLite driver class could not be found;", e);
- }
- isLoaded = true;
- }
-
- /**
- * Gets an in memory DB connection. Will load DB Driver if not already loaded.
- *
- * @return Connection to In Memory Database.
- */
- public static Connection getMemoryConnection() {
- if (!isMapLoaded()) LoadSQLiteDriver();
- try {
- return DriverManager.getConnection(dbMap.getConnectionString());
- } catch (SQLException e) {
- throw new CannotLoadDatabaseMapDriverException("Error in DatabaseConfig, could not retrieve connection to in memory database.", e);
- }
- }
-
- /**
- * Makes any edits necessary in the SQL string for it to be compatible with the database in use.
- *
- * @return
- * @throws SQLException
- */
- public static String getScrubSQL(String sql) throws SQLException {
- if (isMapNull()) throw new NullDatabaseMapException("No database map set!");
- return dbMap.getScrubSQL(sql);
- }
-
- public static String getSelectLastInsertIdentity() {
- if (isMapNull()) throw new NullDatabaseMapException("No database map set!");
- return dbMap.getSelectLastInsertIdentity();
- }
-
- public static int getResultSetType() {
- if (isMapNull()) throw new NullDatabaseMapException("No database map set!");
- return dbMap.getResultSetType();
- }
-
- public interface DatabaseMap {
- String getDriverClassName();
-
- String getConnectionString();
-
- String getScrubSQL(String sql) throws SQLException;
-
- String getSelectLastInsertIdentity();
-
- int getResultSetType();
- }
-
- public static class NullDatabaseMapException extends RuntimeException {
- private static final long serialVersionUID = -4580960157495617424L;
-
- public NullDatabaseMapException(String message) {
- super(message);
- }
- }
-
- public static class CannotLoadDatabaseMapDriverException extends RuntimeException {
- private static final long serialVersionUID = 2614876121296128364L;
-
- public CannotLoadDatabaseMapDriverException(String message, Throwable cause) {
- super(message, cause);
- }
- }
-
- @Retention(RetentionPolicy.RUNTIME)
- @Target(ElementType.TYPE)
- @Inherited
- public @interface UsingDatabaseMap {
- /**
- * @return the classes to be run
- */
- public Class<? extends DatabaseMap> value();
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/util/H2Map.java b/v1/src/main/java/com/xtremelabs/robolectric/util/H2Map.java
deleted file mode 100644
index 4edc83380..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/util/H2Map.java
+++ /dev/null
@@ -1,75 +0,0 @@
-package com.xtremelabs.robolectric.util;
-
-import java.sql.Driver;
-import java.sql.DriverManager;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-
-
-public class H2Map implements DatabaseConfig.DatabaseMap {
-
- @Override
- public String getDriverClassName() {
- return "org.h2.Driver";
- }
-
- @Override
- public String getConnectionString() {
- return "jdbc:h2:mem:";
- }
-
- /**
- * Maps the SQL to the H2 Implementation
- *
- * @param sql the original SQL statement
- * @return the modified SQL statement.
- * @throws SQLException
- */
- @Override
- public String getScrubSQL(String sql) throws SQLException {
-
- if (sql.contains("PRIMARY KEY AUTOINCREMENT") && !sql.contains("INTEGER PRIMARY KEY AUTOINCREMENT")) {
- throw new SQLException("AUTOINCREMENT is only allowed on an INTEGER PRIMARY KEY");
- }
-
- // Map 'autoincrement' (sqlite) to 'auto_increment' (h2).
- String scrubbedSQL = sql.replaceAll("(?i:autoincrement)", "auto_increment");
- // Map 'integer' (sqlite) to 'bigint(19)' (h2).
- scrubbedSQL = scrubbedSQL.replaceAll("(?i:integer)", "bigint(19)");
- // h2 doesn't understand conflict algorithms
- scrubbedSQL = scrubbedSQL.replaceAll("INSERT OR ROLLBACK INTO", "INSERT INTO");
- scrubbedSQL = scrubbedSQL.replaceAll("INSERT OR ABORT INTO", "INSERT INTO");
- scrubbedSQL = scrubbedSQL.replaceAll("INSERT OR FAIL INTO", "INSERT INTO");
- scrubbedSQL = scrubbedSQL.replaceAll("INSERT OR IGNORE INTO", "INSERT INTO");
- scrubbedSQL = scrubbedSQL.replaceAll("INSERT OR REPLACE INTO", "INSERT INTO");
- return scrubbedSQL;
- }
-
- @Override
- public String getSelectLastInsertIdentity() {
- return "SELECT IDENTITY();";
- }
-
-
- public void DeregisterDriver() {
-
- try {
- Driver d = DriverManager.getDriver(getDriverClassName());
- DriverManager.deregisterDriver(d);
- } catch (SQLException e) {
- throw new RuntimeException(e);
- }
- }
-
- @Override
- protected void finalize() throws Throwable {
- super.finalize();
- DeregisterDriver();
- }
-
- @Override
- public int getResultSetType() {
- return ResultSet.TYPE_SCROLL_INSENSITIVE;
- }
-
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/util/H2Map_TypeForwardOnly.java b/v1/src/main/java/com/xtremelabs/robolectric/util/H2Map_TypeForwardOnly.java
deleted file mode 100644
index e9a9bfffe..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/util/H2Map_TypeForwardOnly.java
+++ /dev/null
@@ -1,13 +0,0 @@
-package com.xtremelabs.robolectric.util;
-
-import java.sql.ResultSet;
-
-
-public class H2Map_TypeForwardOnly extends H2Map implements DatabaseConfig.DatabaseMap {
-
- @Override
- public int getResultSetType() {
- return ResultSet.TYPE_FORWARD_ONLY;
- }
-
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/util/I18nException.java b/v1/src/main/java/com/xtremelabs/robolectric/util/I18nException.java
deleted file mode 100644
index 7ab86eae2..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/util/I18nException.java
+++ /dev/null
@@ -1,22 +0,0 @@
-package com.xtremelabs.robolectric.util;
-
-@SuppressWarnings("serial")
-public class I18nException extends RuntimeException {
-
- public I18nException() {
- super();
- }
-
- public I18nException(String arg0, Throwable arg1) {
- super(arg0, arg1);
- }
-
- public I18nException(String arg0) {
- super(arg0);
- }
-
- public I18nException(Throwable arg0) {
- super(arg0);
- }
-
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/util/Join.java b/v1/src/main/java/com/xtremelabs/robolectric/util/Join.java
deleted file mode 100644
index 8b3ec8a74..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/util/Join.java
+++ /dev/null
@@ -1,31 +0,0 @@
-package com.xtremelabs.robolectric.util;
-
-import java.util.Collection;
-
-public class Join {
- public static String join(String delimiter, Collection collection) {
- String del = "";
- StringBuilder sb = new StringBuilder();
- for (Object obj : collection) {
- String asString = obj == null ? null : obj.toString();
- if (obj != null && asString.length() > 0) {
- sb.append(del).append(obj);
- del = delimiter;
- }
- }
- return sb.toString();
- }
-
- public static String join(String delimiter, Object... collection) {
- String del = "";
- StringBuilder sb = new StringBuilder();
- for (Object obj : collection) {
- String asString = obj == null ? null : obj.toString();
- if (asString != null && asString.length() > 0) {
- sb.append(del).append(asString);
- del = delimiter;
- }
- }
- return sb.toString();
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/util/PropertiesHelper.java b/v1/src/main/java/com/xtremelabs/robolectric/util/PropertiesHelper.java
deleted file mode 100644
index 9d62bf573..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/util/PropertiesHelper.java
+++ /dev/null
@@ -1,50 +0,0 @@
-package com.xtremelabs.robolectric.util;
-
-import java.util.Enumeration;
-import java.util.Properties;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-public class PropertiesHelper {
-
- public static String doSingleSubstitution(String originalValue, Properties properties) {
- if (originalValue == null) {
- return null;
- }
-
- Pattern variablePattern = Pattern.compile("([^$]*)\\$\\{(.*?)\\}(.*)");
-
- String expandedValue = originalValue;
- Matcher variableMatcher = variablePattern.matcher(expandedValue);
- while (variableMatcher.matches()) {
- String propertyName = variableMatcher.group(2);
- String propertyValue = null;
- if (properties != null) {
- propertyValue = properties.getProperty(propertyName);
- }
- if (propertyValue == null) {
- propertyValue = System.getProperty(propertyName);
- }
- if (propertyValue == null) {
- return originalValue;
- }
-
- String sdkPathStart = variableMatcher.group(1);
- String sdkPathEnd = variableMatcher.group(3);
- expandedValue = sdkPathStart + propertyValue + sdkPathEnd;
- variableMatcher = variablePattern.matcher(expandedValue);
- }
-
- return expandedValue;
- }
-
- public static void doSubstitutions(Properties properties) {
- Enumeration<?> propertyNames = properties.propertyNames();
- while (propertyNames.hasMoreElements()) {
- String propertyName = (String) propertyNames.nextElement();
- String propertyValue = properties.getProperty(propertyName);
- String expandedPropertyValue = doSingleSubstitution(propertyValue, properties);
- properties.setProperty(propertyName, expandedPropertyValue);
- }
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/util/RobolectricBackgroundExecutorService.java b/v1/src/main/java/com/xtremelabs/robolectric/util/RobolectricBackgroundExecutorService.java
deleted file mode 100644
index b3529f19d..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/util/RobolectricBackgroundExecutorService.java
+++ /dev/null
@@ -1,92 +0,0 @@
-package com.xtremelabs.robolectric.util;
-
-import com.xtremelabs.robolectric.Robolectric;
-
-import java.util.Collection;
-import java.util.List;
-import java.util.concurrent.Callable;
-import java.util.concurrent.ExecutionException;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Future;
-import java.util.concurrent.FutureTask;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.TimeoutException;
-
-public class RobolectricBackgroundExecutorService implements ExecutorService {
- @Override
- public void shutdown() {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public List<Runnable> shutdownNow() {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public boolean isShutdown() {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public boolean isTerminated() {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public boolean awaitTermination(long l, TimeUnit timeUnit) throws InterruptedException {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public <T> Future<T> submit(Callable<T> tCallable) {
- return schedule(new FutureTask<T>(tCallable));
- }
-
- @Override
- public <T> Future<T> submit(Runnable runnable, T t) {
- return schedule(new FutureTask<T>(runnable, t));
- }
-
- @Override
- public Future<?> submit(Runnable runnable) {
- return submit(runnable, null);
- }
-
- private <T> Future<T> schedule(final FutureTask<T> futureTask) {
- Robolectric.getShadowApplication().getBackgroundScheduler().post(new Runnable() {
- @Override
- public void run() {
- futureTask.run();
- }
- });
-
- return futureTask;
- }
-
- @Override
- public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> callables) throws InterruptedException {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> callables, long l, TimeUnit timeUnit) throws InterruptedException {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public <T> T invokeAny(Collection<? extends Callable<T>> callables) throws InterruptedException, ExecutionException {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public <T> T invokeAny(Collection<? extends Callable<T>> callables, long l, TimeUnit timeUnit) throws InterruptedException, ExecutionException, TimeoutException {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public void execute(Runnable runnable) {
- submit(runnable);
- }
-}
-
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/util/SQLite.java b/v1/src/main/java/com/xtremelabs/robolectric/util/SQLite.java
deleted file mode 100644
index ebfd5ada0..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/util/SQLite.java
+++ /dev/null
@@ -1,206 +0,0 @@
-package com.xtremelabs.robolectric.util;
-
-import android.content.ContentValues;
-import android.database.sqlite.SQLiteException;
-
-import java.sql.SQLException;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map.Entry;
-
-/**
- * SQL utility methods to support the database-related shadows, such as
- * {@code ShadowSQLiteDatabase} and {@code ShadowSQLiteCursor}.
- */
-public class SQLite {
- private static final String[] CONFLICT_VALUES = {"", "OR ROLLBACK ", "OR ABORT ", "OR FAIL ", "OR IGNORE ", "OR REPLACE "};
-
- /**
- * Create a SQL INSERT string. Returned values are then bound via
- * JDBC to facilitate various data types.
- *
- * @param table table name
- * @param values column name/value pairs
- * @param conflictAlgorithm the conflict algorithm to use
- * @return insert string
- */
- public static SQLStringAndBindings buildInsertString(String table, ContentValues values, int conflictAlgorithm) throws SQLException {
- StringBuilder sb = new StringBuilder();
-
- sb.append("INSERT ");
- sb.append(CONFLICT_VALUES[conflictAlgorithm]);
- sb.append("INTO ");
-
- sb.append(table);
- sb.append(" ");
-
- SQLStringAndBindings columnsValueClause = buildColumnValuesClause(values);
- sb.append(columnsValueClause.sql);
- sb.append(";");
-
- String sql = DatabaseConfig.getScrubSQL(sb.toString());
- return new SQLStringAndBindings(sql, columnsValueClause.columnValues);
- }
-
- /**
- * Create a SQL UPDATE string. Returned values are then bound via
- * JDBC to facilitate various data types.
- *
- * @param table table name
- * @param values column name/value pairs
- * @param whereClause SQL where clause fragment
- * @param whereArgs Array of substitutions for args in whereClause
- * @return update string
- */
- public static SQLStringAndBindings buildUpdateString(String table, ContentValues values, String whereClause, String[] whereArgs) {
- StringBuilder sb = new StringBuilder();
-
- sb.append("UPDATE ");
- sb.append(table);
- sb.append(" SET ");
-
- SQLStringAndBindings columnAssignmentsClause = buildColumnAssignmentsClause(values);
- sb.append(columnAssignmentsClause.sql);
-
- if (whereClause != null) {
- String where = whereClause;
- if (whereArgs != null) {
- where = buildWhereClause(whereClause, whereArgs);
- }
- sb.append(" WHERE ");
- sb.append(where);
- }
- sb.append(";");
-
- return new SQLStringAndBindings(sb.toString(), columnAssignmentsClause.columnValues);
- }
-
- /**
- * Create a SQL DELETE string.
- *
- * @param table table name
- * @param whereClause SQL where clause fragment
- * @param whereArgs Array of substitutions for args in whereClause
- * @return delete string
- */
- public static String buildDeleteString(String table, String whereClause, String[] whereArgs) {
- StringBuilder sb = new StringBuilder();
-
- sb.append("DELETE FROM ");
- sb.append(table);
-
- if (whereClause != null) {
- String where = whereClause;
- if (whereArgs != null) {
- where = buildWhereClause(whereClause, whereArgs);
- }
- sb.append(" WHERE ");
- sb.append(where);
- }
- sb.append(";");
-
- return sb.toString();
- }
-
- /**
- * Build a WHERE clause used in SELECT, UPDATE and DELETE statements.
- *
- * @param selection SQL where clause fragment
- * @param selectionArgs Array of substitutions for args in selection
- * @return where clause
- */
- public static String buildWhereClause(String selection, String[] selectionArgs) throws SQLiteException {
- String whereClause = selection;
- int argsNeeded = 0;
- int args = 0;
-
- for (char c : selection.toCharArray()) {
- if (c == '?') argsNeeded++;
- }
- if (selectionArgs != null) {
- for (int x = 0; x < selectionArgs.length; x++) {
- if (selectionArgs[x] == null) {
- throw new IllegalArgumentException("the bind value at index " + x + " is null");
- } else {
- args++;
- }
- whereClause = whereClause.replaceFirst("\\?", "'" + selectionArgs[x] + "'");
- }
- }
- if (argsNeeded != args) {
- throw new SQLiteException("bind or column index out of range: count of selectionArgs does not match count of (?) placeholders for given sql statement!");
- }
-
- return whereClause;
- }
-
- /**
- * Build the '(columns...) VALUES (values...)' clause used in INSERT
- * statements.
- *
- * @param values column name/value pairs
- * @return SQLStringAndBindings
- */
- public static SQLStringAndBindings buildColumnValuesClause(ContentValues values) {
- StringBuilder clause = new StringBuilder("(");
- List<Object> columnValues = new ArrayList<Object>(values.size());
-
- Iterator<Entry<String, Object>> itemEntries = values.valueSet().iterator();
- while (itemEntries.hasNext()) {
- Entry<String, Object> entry = itemEntries.next();
- clause.append(entry.getKey());
- if (itemEntries.hasNext()) {
- clause.append(", ");
- }
- columnValues.add(entry.getValue());
- }
-
- clause.append(") VALUES (");
- for (int i = 0; i < values.size() - 1; i++) {
- clause.append("?, ");
- }
- clause.append("?)");
-
- return new SQLStringAndBindings(clause.toString(), columnValues);
- }
-
- /**
- * Build the '(col1=?, col2=? ... )' clause used in UPDATE statements.
- *
- * @param values column name/value pairs
- * @return SQLStringAndBindings
- */
- public static SQLStringAndBindings buildColumnAssignmentsClause(ContentValues values) {
- StringBuilder clause = new StringBuilder();
- List<Object> columnValues = new ArrayList<Object>(values.size());
-
- Iterator<Entry<String, Object>> itemsEntries = values.valueSet().iterator();
- while (itemsEntries.hasNext()) {
- Entry<String, Object> entry = itemsEntries.next();
- clause.append(entry.getKey());
- clause.append("=?");
- if (itemsEntries.hasNext()) {
- clause.append(", ");
- }
- columnValues.add(entry.getValue());
- }
-
- return new SQLStringAndBindings(clause.toString(), columnValues);
- }
-
- /**
- * Container for a SQL fragment and the objects which are to be
- * bound to the arguments in the fragment.
- */
- public static class SQLStringAndBindings {
- public String sql;
- public List<Object> columnValues;
-
- public SQLStringAndBindings(String sql, List<Object> columnValues) {
- this.sql = sql;
- this.columnValues = columnValues;
- }
- }
-
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/util/SQLiteMap.java b/v1/src/main/java/com/xtremelabs/robolectric/util/SQLiteMap.java
deleted file mode 100644
index 42a4401c1..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/util/SQLiteMap.java
+++ /dev/null
@@ -1,26 +0,0 @@
-package com.xtremelabs.robolectric.util;
-
-import java.sql.ResultSet;
-
-public class SQLiteMap implements DatabaseConfig.DatabaseMap {
-
- public String getDriverClassName() {
- return "org.sqlite.JDBC";
- }
-
- public String getConnectionString() {
- return "jdbc:sqlite::memory:";
- }
-
- public String getScrubSQL(String sql) {
- return sql;
- }
-
- public String getSelectLastInsertIdentity() {
- return "SELECT last_insert_rowid() AS id";
- }
-
- public int getResultSetType() {
- return ResultSet.TYPE_FORWARD_ONLY;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/util/Scheduler.java b/v1/src/main/java/com/xtremelabs/robolectric/util/Scheduler.java
deleted file mode 100644
index aa45f1b26..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/util/Scheduler.java
+++ /dev/null
@@ -1,161 +0,0 @@
-package com.xtremelabs.robolectric.util;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-import java.util.ListIterator;
-
-public class Scheduler {
- private List<PostedRunnable> postedRunnables = new ArrayList<PostedRunnable>();
- private long currentTime = 0;
- private boolean paused = false;
-
- public long getCurrentTime() {
- return currentTime;
- }
-
- public void pause() {
- paused = true;
- }
-
- public void unPause() {
- paused = false;
- advanceToLastPostedRunnable();
- }
-
- public boolean isPaused() {
- return paused;
- }
-
- public void postDelayed(Runnable runnable, long delayMillis) {
- if (paused || delayMillis > 0) {
- postedRunnables.add(new PostedRunnable(runnable, currentTime + delayMillis));
- Collections.sort(postedRunnables);
- } else {
- runnable.run();
- }
- }
-
- public void post(Runnable runnable) {
- postDelayed(runnable, 0);
- }
-
- public void postAtFrontOfQueue(Runnable runnable) {
- if (paused) {
- postedRunnables.add(0, new PostedRunnable(runnable, currentTime));
- } else {
- runnable.run();
- }
- }
-
- public void remove(Runnable runnable) {
- ListIterator<PostedRunnable> iterator = postedRunnables.listIterator();
- while (iterator.hasNext()) {
- PostedRunnable next = iterator.next();
- if (next.runnable == runnable) {
- iterator.remove();
- }
- }
- }
-
- public boolean advanceToLastPostedRunnable() {
- if (enqueuedTaskCount() < 1) {
- return false;
- }
-
- return advanceTo(postedRunnables.get(postedRunnables.size() - 1).scheduledTime);
- }
-
- public boolean advanceToNextPostedRunnable() {
- if (enqueuedTaskCount() < 1) {
- return false;
- }
-
- return advanceTo(postedRunnables.get(0).scheduledTime);
- }
-
- public boolean advanceBy(long intervalMs) {
- long endingTime = currentTime + intervalMs;
- return advanceTo(endingTime);
- }
-
- public boolean advanceTo(long endingTime) {
- if (endingTime - currentTime < 0 || enqueuedTaskCount() < 1) {
- return false;
- }
-
- int runCount = 0;
- while (nextTaskIsScheduledBefore(endingTime)) {
- runOneTask();
- ++runCount;
- }
- currentTime = endingTime;
-
- return runCount > 0;
- }
-
- public boolean runOneTask() {
- if (enqueuedTaskCount() < 1) {
- return false;
- }
-
- PostedRunnable postedRunnable = postedRunnables.remove(0);
- currentTime = postedRunnable.scheduledTime;
- postedRunnable.run();
- return true;
- }
-
- public boolean runTasks(int howMany) {
- if (enqueuedTaskCount() < howMany) {
- return false;
- }
-
- while (howMany > 0) {
- PostedRunnable postedRunnable = postedRunnables.remove(0);
- currentTime = postedRunnable.scheduledTime;
- postedRunnable.run();
- howMany--;
- }
- return true;
- }
-
- public int enqueuedTaskCount() {
- return postedRunnables.size();
- }
-
- public boolean areAnyRunnable() {
- return nextTaskIsScheduledBefore(currentTime);
- }
-
- public void reset() {
- postedRunnables.clear();
- paused = false;
- }
-
- public int size() {
- return postedRunnables.size();
- }
-
- class PostedRunnable implements Comparable<PostedRunnable> {
- Runnable runnable;
- long scheduledTime;
-
- PostedRunnable(Runnable runnable, long scheduledTime) {
- this.runnable = runnable;
- this.scheduledTime = scheduledTime;
- }
-
- @Override
- public int compareTo(PostedRunnable postedRunnable) {
- return (int) (scheduledTime - postedRunnable.scheduledTime);
- }
-
- public void run() {
- runnable.run();
- }
- }
-
- private boolean nextTaskIsScheduledBefore(long endingTime) {
- return enqueuedTaskCount() > 0 && postedRunnables.get(0).scheduledTime <= endingTime;
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/util/Strings.java b/v1/src/main/java/com/xtremelabs/robolectric/util/Strings.java
deleted file mode 100644
index 69e93ad62..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/util/Strings.java
+++ /dev/null
@@ -1,25 +0,0 @@
-package com.xtremelabs.robolectric.util;
-
-import java.io.IOException;
-import java.io.InputStream;
-
-public class Strings {
-
- public static String fromStream(InputStream inputStream) throws IOException {
- int bufSize = 1028;
- byte[] buffer = new byte[bufSize];
- int inSize;
- StringBuilder stringBuilder = new StringBuilder();
- while ((inSize = inputStream.read(buffer)) > 0) {
- stringBuilder.append(new String(buffer, 0, inSize));
- }
- return stringBuilder.toString();
- }
-
- public static boolean equals(String a, String b) {
- if (a == null) {
- return b == null;
- }
- return a.equals(b);
- }
-}
diff --git a/v1/src/main/java/com/xtremelabs/robolectric/util/Transcript.java b/v1/src/main/java/com/xtremelabs/robolectric/util/Transcript.java
deleted file mode 100644
index ef21ae551..000000000
--- a/v1/src/main/java/com/xtremelabs/robolectric/util/Transcript.java
+++ /dev/null
@@ -1,32 +0,0 @@
-package com.xtremelabs.robolectric.util;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-import static org.junit.Assert.assertEquals;
-
-public class Transcript {
- private List<String> events = new ArrayList<String>();
-
- public void add(String event) {
- events.add(event);
- }
-
- public void assertNoEventsSoFar() {
- assertEquals("Expected no events but got " + events + ".", 0, events.size());
- }
-
- public void assertEventsSoFar(String... expectedEvents) {
- assertEquals(Arrays.asList(expectedEvents), events);
- events.clear();
- }
-
- public void clear() {
- events.clear();
- }
-
- public List<String> getEvents() {
- return events;
- }
-}
diff --git a/v1/src/main/java/overview.html b/v1/src/main/java/overview.html
deleted file mode 100644
index 32dc92ab3..000000000
--- a/v1/src/main/java/overview.html
+++ /dev/null
@@ -1,42 +0,0 @@
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
-<html>
-<head>
-</head>
-<body bgcolor="white">
-
-<!-- THE TITLE FOR THIS PAGE is in the <doctitle> element of the "javadoc" task in robolectric/build.xml (where I would never have thought to look for it...) -->
-
-This document describes the elements of the Robolectric API, such as Shadow classes, Annotations, and TestRunners, that
-a developer is likely to use or extend. While the goal of Robolectric is to provide a complete solution for test
-driving Android applications, it is important to also acknowledge that every project is different and the needs of
-different applications may place conflicting demands upon the tools that support them. For this reason the components
-that make up Robolectric have been designed to be extended or replaced as needed. <p>
-
-If you have created extensions to Robolectric that you believe to be of use to a larger audience, please consider
-forking the main Robolectric repository at http://github.com/pivotal/robolectric and submitting your changes as pull
-requests.
-
-<!--
-<h2>Package Specification</h2>
--->
-
-<!--
-##### FILL IN ANY SPECS NEEDED BY JAVA COMPATIBILITY KIT #####
-<ul>
- <li><a href="">##### REFER TO ANY FRAMEMAKER SPECIFICATION HERE #####</a>
-</ul>
--->
-
-<!--
-<h2>Related Documentation</h2>
-
-For overviews, tutorials, examples, guides, and tool documentation, please see:
-<ul>
- <li><a href="">##### REFER TO NON-SPEC DOCUMENTATION HERE #####</a>
-</ul>
--->
-
-<!-- Put @see and @since tags down here. -->
-
-</body>
-</html> \ No newline at end of file
diff --git a/v1/src/test/java/android/webkit/TestWebSettingsTest.java b/v1/src/test/java/android/webkit/TestWebSettingsTest.java
deleted file mode 100644
index 12ae4c6bd..000000000
--- a/v1/src/test/java/android/webkit/TestWebSettingsTest.java
+++ /dev/null
@@ -1,181 +0,0 @@
-package android.webkit;
-
-import android.webkit.WebSettings;
-import android.webkit.TestWebSettings;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.junit.Assert.assertThat;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class TestWebSettingsTest {
-
- private TestWebSettings webSettings;
-
- private boolean[] trueAndFalse = {true, false};
-
- @Before
- public void setUp() throws Exception {
- webSettings = new TestWebSettings();
- }
-
- @Test
- public void testDefaults() {
- assertThat(webSettings.getAllowFileAccess(), equalTo(true));
- assertThat(webSettings.getBlockNetworkImage(), equalTo(false));
- assertThat(webSettings.getBlockNetworkLoads(), equalTo(false));
- assertThat(webSettings.getBuiltInZoomControls(), equalTo(true));
- assertThat(webSettings.getDatabaseEnabled(), equalTo(false));
- assertThat(webSettings.getDomStorageEnabled(), equalTo(false));
- assertThat(webSettings.getJavaScriptEnabled(), equalTo(false));
- assertThat(webSettings.getLightTouchEnabled(), equalTo(false));
- assertThat(webSettings.getLoadWithOverviewMode(), equalTo(false));
- assertThat(webSettings.getPluginState(), equalTo(WebSettings.PluginState.OFF));
-
- // deprecated methods
- assertThat(webSettings.getPluginsEnabled(), equalTo(false));
-
- // obsoleted methods
- assertThat(webSettings.getNeedInitialFocus(), equalTo(false));
- assertThat(webSettings.getSupportMultipleWindows(), equalTo(false));
- assertThat(webSettings.getSupportZoom(), equalTo(true));
- }
-
- @Test
- public void testAllowFileAccess() {
- for (boolean value : trueAndFalse) {
- webSettings.setAllowFileAccess(value);
- assertThat(webSettings.getAllowFileAccess(), equalTo(value));
- }
- }
-
- @Test
- public void testAllowFileAccessFromFileURLs() {
- for (boolean value : trueAndFalse) {
- webSettings.setAllowFileAccessFromFileURLs(value);
- assertThat(webSettings.getAllowFileAccessFromFileURLs(), equalTo(value));
- }
- }
-
- @Test
- public void testAllowUniversalAccessFromFileURLs() {
- for (boolean value : trueAndFalse) {
- webSettings.setAllowUniversalAccessFromFileURLs(value);
- assertThat(webSettings.getAllowUniversalAccessFromFileURLs(), equalTo(value));
- }
- }
-
- @Test
- public void testBlockNetworkImage() {
- for (boolean value : trueAndFalse) {
- webSettings.setBlockNetworkImage(value);
- assertThat(webSettings.getBlockNetworkImage(), equalTo(value));
- }
- }
-
- @Test
- public void testBlockNetworkLoads() {
- for (boolean value : trueAndFalse) {
- webSettings.setBlockNetworkLoads(value);
- assertThat(webSettings.getBlockNetworkLoads(), equalTo(value));
- }
- }
-
- @Test
- public void testBuiltInZoomControls() {
- for (boolean value : trueAndFalse) {
- webSettings.setBuiltInZoomControls(value);
- assertThat(webSettings.getBuiltInZoomControls(), equalTo(value));
- }
- }
-
- @Test
- public void testDatabaseEnabled() {
- for (boolean value : trueAndFalse) {
- webSettings.setDatabaseEnabled(value);
- assertThat(webSettings.getDatabaseEnabled(), equalTo(value));
- }
- }
-
- @Test
- public void testDomStorageEnabled() {
- for (boolean value : trueAndFalse) {
- webSettings.setDomStorageEnabled(value);
- assertThat(webSettings.getDomStorageEnabled(), equalTo(value));
- }
- }
-
- @Test
- public void testJavaScriptEnabled() {
- for (boolean value : trueAndFalse) {
- webSettings.setJavaScriptEnabled(value);
- assertThat(webSettings.getJavaScriptEnabled(), equalTo(value));
- }
- }
-
- @Test
- public void testLightTouchEnabled() {
- for (boolean value : trueAndFalse) {
- webSettings.setLightTouchEnabled(value);
- assertThat(webSettings.getLightTouchEnabled(), equalTo(value));
- }
- }
-
- @Test
- public void testLoadWithOverviewMode() {
- for (boolean value : trueAndFalse) {
- webSettings.setLoadWithOverviewMode(value);
- assertThat(webSettings.getLoadWithOverviewMode(), equalTo(value));
- }
- }
-
- @Test
- public void testNeedInitialFocus() {
- for (boolean value : trueAndFalse) {
- webSettings.setNeedInitialFocus(value);
- assertThat(webSettings.getNeedInitialFocus(), equalTo(value));
- }
- }
-
- @Test
- public void testPluginsEnabled() {
- for (boolean value : trueAndFalse) {
- webSettings.setPluginsEnabled(value);
- assertThat(webSettings.getPluginsEnabled(), equalTo(value));
- }
- }
-
- @Test
- public void testPluginState() {
- WebSettings.PluginState[] states = {
- WebSettings.PluginState.OFF,
- WebSettings.PluginState.ON,
- WebSettings.PluginState.ON_DEMAND
- };
-
- for (WebSettings.PluginState state : states) {
- webSettings.setPluginState(state);
- assertThat(webSettings.getPluginState(), equalTo(state));
- }
- }
-
- @Test
- public void testSupportMultipleWindows() {
- for (boolean value : trueAndFalse) {
- webSettings.setSupportMultipleWindows(value);
- assertThat(webSettings.getSupportMultipleWindows(), equalTo(value));
- }
- }
-
- @Test
- public void testSupportZoom() {
- for (boolean value : trueAndFalse) {
- webSettings.setSupportZoom(value);
- assertThat(webSettings.getSupportZoom(), equalTo(value));
- }
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/ApplicationResolverTest.java b/v1/src/test/java/com/xtremelabs/robolectric/ApplicationResolverTest.java
deleted file mode 100644
index e0469d464..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/ApplicationResolverTest.java
+++ /dev/null
@@ -1,54 +0,0 @@
-package com.xtremelabs.robolectric;
-
-import android.app.Application;
-import com.xtremelabs.robolectric.shadows.ShadowApplication;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import java.util.List;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-import static com.xtremelabs.robolectric.util.TestUtil.newConfig;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class ApplicationResolverTest {
-
- @Test(expected = RuntimeException.class)
- public void shouldThrowWhenManifestContainsBadApplicationClassName() throws Exception {
- new ApplicationResolver(newConfig("TestAndroidManifestWithBadAppName.xml")).resolveApplication();
- }
-
- @Test
- public void shouldReturnDefaultAndroidApplicationWhenManifestDeclaresNoAppName() throws Exception {
- assertEquals(Application.class,
- new ApplicationResolver(newConfig("TestAndroidManifest.xml")).resolveApplication().getClass());
- }
-
- @Test
- public void shouldReturnSpecifiedApplicationWhenManifestDeclaresAppName() throws Exception {
- assertEquals(TestApplication.class,
- new ApplicationResolver(newConfig("TestAndroidManifestWithAppName.xml")).resolveApplication().getClass());
- }
-
- @Test
- public void shouldAssignThePackageNameFromTheManifest() throws Exception {
- Application application = new ApplicationResolver(newConfig("TestAndroidManifestWithPackageName.xml")).resolveApplication();
- assertEquals("com.wacka.wa", application.getPackageName());
- }
-
- @Test
- public void shouldAssignTheApplicationNameFromTheManifest() throws Exception {
- Application application = new ApplicationResolver(newConfig("TestAndroidManifestWithAppName.xml")).resolveApplication();
- assertEquals("com.xtremelabs.robolectric.TestApplication", application.getApplicationInfo().name);
- }
-
- @Test
- public void shouldRegisterReceiversFromTheManifest() throws Exception {
- Application application = new ApplicationResolver(newConfig("TestAndroidManifestWithReceivers.xml")).resolveApplication();
- List<ShadowApplication.Wrapper> receivers = shadowOf(application).getRegisteredReceivers();
- assertEquals(7, receivers.size());
- assertTrue(receivers.get(0).intentFilter.matchAction("com.xtremelabs.robolectric.ACTION1"));
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/DotConfigTestReceiver.java b/v1/src/test/java/com/xtremelabs/robolectric/DotConfigTestReceiver.java
deleted file mode 100644
index 9afd46a85..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/DotConfigTestReceiver.java
+++ /dev/null
@@ -1,13 +0,0 @@
-package com.xtremelabs.robolectric;
-
-import android.content.BroadcastReceiver;
-import android.content.Context;
-import android.content.Intent;
-
-public class DotConfigTestReceiver extends BroadcastReceiver {
-
- @Override
- public void onReceive(Context context, Intent intent) {
- }
-
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/IncludedDependenciesTest.java b/v1/src/test/java/com/xtremelabs/robolectric/IncludedDependenciesTest.java
deleted file mode 100644
index 70d5bf077..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/IncludedDependenciesTest.java
+++ /dev/null
@@ -1,29 +0,0 @@
-package com.xtremelabs.robolectric;
-
-import org.json.JSONObject;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.xmlpull.v1.XmlPullParser;
-import org.xmlpull.v1.XmlPullParserFactory;
-
-import java.io.StringReader;
-
-import static org.junit.Assert.assertEquals;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class IncludedDependenciesTest {
- @Test
- public void jsonShouldWork() throws Exception {
- assertEquals("value", new JSONObject("{'name':'value'}").getString("name"));
- }
-
- @Test
- public void xppShouldWork() throws Exception {
- XmlPullParser xmlPullParser = XmlPullParserFactory.newInstance().newPullParser();
- xmlPullParser.setInput(new StringReader("<?xml version=\"1.0\" encoding=\"UTF-8\"?><test name=\"value\"/>"));
- assertEquals(XmlPullParser.START_TAG, xmlPullParser.nextTag());
- assertEquals(1, xmlPullParser.getAttributeCount());
- assertEquals("name", xmlPullParser.getAttributeName(0));
- assertEquals("value", xmlPullParser.getAttributeValue(0));
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/InstrumentDetectorTest.java b/v1/src/test/java/com/xtremelabs/robolectric/InstrumentDetectorTest.java
deleted file mode 100644
index 011278897..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/InstrumentDetectorTest.java
+++ /dev/null
@@ -1,174 +0,0 @@
-package com.xtremelabs.robolectric;
-
-import com.xtremelabs.robolectric.RobolectricTestRunner.InstrumentDetector;
-import com.xtremelabs.robolectric.bytecode.ClassHandler;
-import com.xtremelabs.robolectric.bytecode.RobolectricClassLoader;
-import com.xtremelabs.robolectric.bytecode.ShadowWrangler;
-import org.junit.Test;
-import org.junit.runner.JUnitCore;
-import org.junit.runner.Result;
-import org.junit.runner.RunWith;
-import org.junit.runners.model.InitializationError;
-
-import java.io.PrintWriter;
-import java.io.StringWriter;
-
-import static com.xtremelabs.robolectric.util.TestUtil.resourceFile;
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.junit.Assert.assertThat;
-import static org.junit.Assert.assertTrue;
-
-/**
- * Tests related to custom instrument detection strategy
- * that is used for introducing custom class loaders to test runners.
- */
-public class InstrumentDetectorTest {
-
- // ==================== CLASSLOADER ====================
-
- /** Custom class loader. It must be singleton. */
- public static class ClassLoaderForTesting extends RobolectricClassLoader {
-
- /** Instance. */
- private static ClassLoaderForTesting instance;
-
- /** Usage flag. */
- static boolean usageFlag = false;
-
- public static ClassLoaderForTesting getInstance() {
- if (instance == null) {
- instance = new ClassLoaderForTesting(ShadowWrangler.getInstance());
- }
- return instance;
- }
-
- protected ClassLoaderForTesting(final ClassHandler classHandler) {
- super(classHandler);
- }
-
- @Override
- public Class<?> loadClass(final String name) throws ClassNotFoundException {
- if (!usageFlag) {
- System.setProperty("robolectric.cusomClassLoader", "yes");
- }
- usageFlag = true;
- return super.loadClass(name);
- }
-
- }
-
- // ==================== RUNNERS ====================
-
- /** Custom runner that uses custom class loader but does not modify instrument detection. */
- public static class RunnerForTesting extends RobolectricTestRunner {
-
- public RunnerForTesting(final Class<?> testClass) throws InitializationError {
- super(
- testClass,
- isInstrumented() ? null : ShadowWrangler.getInstance(),
- isInstrumented() ? null : ClassLoaderForTesting.getInstance(),
- new RobolectricConfig(resourceFile("TestAndroidManifest.xml"), resourceFile("res"), resourceFile("assets"))
- );
- }
-
- }
-
- /** Custom runner that uses custom class loader. */
- public static class RunnerForTestingThatWillPass extends RobolectricTestRunner {
-
- static {
- RunnerForTestingThatWillPass.setInstrumentDetector(CUSTOM_DETECTOR);
- }
-
- public RunnerForTestingThatWillPass(final Class<?> testClass) throws InitializationError {
- super(
- testClass,
- isInstrumented() ? null : ShadowWrangler.getInstance(),
- isInstrumented() ? null : ClassLoaderForTesting.getInstance(),
- new RobolectricConfig(resourceFile("TestAndroidManifest.xml"), resourceFile("res"), resourceFile("assets"))
- );
- }
-
- }
-
- /** Custom instrument detector. */
- private static final InstrumentDetector CUSTOM_DETECTOR = new InstrumentDetector() {
- @Override
- public boolean isInstrumented() {
- final String currentLoader = RunnerForTestingThatWillPass.class.getClassLoader().getClass().getName();
- return currentLoader.contains(ClassLoaderForTesting.class.getName());
- }
- };
-
-
- // ==================== TEST CLASSES ====================
-
- /**
- * Default behavior test.
- */
- public static class DefaultBehaviorTest {
- @Test
- public void fakeTest() {
- assertThat(true, equalTo(true));
- }
- }
-
- /**
- * Test that is launched with a custom test runner and will fail.
- */
- @RunWith(RunnerForTesting.class)
- public static class TestWithCustomRunner {
- @Test
- public void loadedWithCustomClassLoader_usageFlagShoudBeTrue() {
- assertThat(System.getProperty("robolectric.cusomClassLoader"), equalTo("yes"));
- }
- }
-
- /**
- * Test that is launched with a custom test runner and will pass.
- */
- @RunWith(RunnerForTestingThatWillPass.class)
- public static class TestWithCustomRunnerThatWillPass extends TestWithCustomRunner {
- // nothing here, we just need another annotation
- }
-
-
- // ==================== RUN METHODS ====================
-
- /**
- * This is default behavior.
- */
- @Test
- public void withDefaultDetectorAndDefaultRunner_shouldPass() {
- final Result result = JUnitCore.runClasses(DefaultBehaviorTest.class);
- assertThat(result.getRunCount(), equalTo(1));
- assertThat(result.getFailureCount(), equalTo(0));
- }
-
- /**
- * This test simulates wrong instrument detection when custom class loader is used.
- */
- @Test
- public void wrongInstrumentDetection_shouldRaiseLinkageError() {
- final Result result = JUnitCore.runClasses(TestWithCustomRunner.class);
- assertThat(result.getRunCount(), equalTo(1));
- assertThat(result.getFailureCount(), equalTo(1));
-
- // check whether it's a linkage error
- final StringWriter buffer = new StringWriter();
- result.getFailures().get(0).getException().printStackTrace(new PrintWriter(buffer));
- final int linkageErrorNameIndex = buffer.toString().indexOf(LinkageError.class.getName());
- assertTrue(linkageErrorNameIndex >= 0);
- }
-
- /**
- * Propper behavior test.
- */
- @Test
- public void customizeInstumentDetection_shouldPass() {
- final Result result = JUnitCore.runClasses(TestWithCustomRunnerThatWillPass.class);
- assertThat(result.getRunCount(), equalTo(1));
- assertThat(result.getFailureCount(), equalTo(0));
- }
-
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/R.java b/v1/src/test/java/com/xtremelabs/robolectric/R.java
deleted file mode 100644
index bfc8dd163..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/R.java
+++ /dev/null
@@ -1,169 +0,0 @@
-/* AUTO-GENERATED FILE. DO NOT MODIFY.
- *
- * This class was automatically generated by the
- * aapt tool from the resource data it found. It
- * should not be modified by hand.
- */
-
-package com.xtremelabs.robolectric;
-
-public final class R {
- private static int nextId = 1234;
-
- public static final class id {
- public static final int time = nextId++;
- public static final int title = nextId++;
- public static final int subtitle = nextId++;
- public static final int snippet_text = nextId++;
- public static final int include_id = nextId++;
- public static final int inner_text = nextId++;
- public static final int map_view = nextId++;
- public static final int true_checkbox = nextId++;
- public static final int false_checkbox = nextId++;
- public static final int default_checkbox = nextId++;
- public static final int image = nextId++;
- public static final int icon = nextId++;
- public static final int text1 = nextId++;
- public static final int button = nextId++;
- public static final int invalid_onclick_button = nextId++;
- public static final int edit_text = nextId++;
- public static final int edit_text2 = nextId++;
- public static final int outer_merge = nextId++;
- public static final int web_view = nextId++;
-
- public static final int black_text_view = nextId++;
- public static final int white_text_view = nextId++;
- public static final int grey_text_view = nextId++;
-
- public static final int black_text_view_hint = nextId++;
- public static final int white_text_view_hint = nextId++;
- public static final int grey_text_view_hint = nextId++;
-
- public static final int textStyle = nextId++;
- public static final int textStyle2 = nextId++;
- public static final int textStyle3 = nextId++;
-
- public static final int test_menu_1 = nextId++;
- public static final int test_menu_2 = nextId++;
- public static final int test_menu_3 = nextId++;
-
- public static final int group_id_1 = nextId++;
-
- public static final int test_submenu_1 = nextId++;
-
- public static final int fragment = nextId++;
- public static final int dynamic_fragment_container = nextId++;
- public static final int content_view = nextId++;
-
- public static final int default_view = nextId++;
- public static final int filter_touches_false_view = nextId++;
- public static final int filter_touches_true_view = nextId++;
- public static final int clickable_false_view = nextId++;
- public static final int clickable_true_view = nextId++;
- public static final int focusable_false_view = nextId++;
- public static final int focusable_true_view = nextId++;
- }
-
- public static final class string {
- public static final int howdy = nextId++;
- public static final int hello = nextId++;
- public static final int some_html = nextId++;
- public static final int greeting = nextId++;
- public static final int copy = nextId++;
- }
-
- public static final class plurals {
- public static final int beer = nextId++;
- }
-
- public static final class array {
- public static final int items = nextId++;
- public static final int greetings = nextId++;
- public static final int alertDialogTestItems = nextId++;
- public static final int emailAddressTypes = nextId++;
- }
-
- public static final class color {
- public static final int background = nextId++;
- public static final int foreground = nextId++;
- public static final int grey42 = nextId++;
- public static final int black = nextId++;
- public static final int white = nextId++;
- public static final int clear = nextId++;
- public static final int color_with_alpha = nextId++;
- public static final int android_namespaced_black = nextId++;
- public static final int android_red = nextId++;
- }
-
- public static final class drawable {
- public static final int an_image = nextId++;
- public static final int an_other_image = nextId++;
- public static final int third_image = nextId++;
- public static final int fourth_image = nextId++;
- public static final int image_background = nextId++;
- public static final int l0_red = nextId++;
- public static final int l1_orange = nextId++;
- public static final int l2_yellow = nextId++;
- public static final int l3_green = nextId++;
- public static final int l4_blue = nextId++;
- public static final int l5_indigo = nextId++;
- public static final int l6_violet = nextId++;
- public static final int l7_white = nextId++;
- public static final int rainbow = nextId++;
- public static final int state_drawable = nextId++;
- public static final int animation_list = nextId++;
- public static final int nine_patch_drawable = nextId++;
- }
-
- public static final class layout {
- public static final int main = nextId++;
- public static final int media = nextId++;
- public static final int inner_merge = nextId++;
- public static final int included_linear_layout = nextId++;
- public static final int with_invalid_onclick = nextId++;
- public static final int text_views = nextId++;
- public static final int text_views_hints = nextId++;
- public static final int toplevel_merge = nextId++;
- public static final int tab_activity = nextId++;
- public static final int different_screen_sizes = nextId++;
- public static final int fragment_activity = nextId++;
- public static final int views = nextId++;
- }
-
- public static final class raw {
- public static final int raw_resource = nextId++;
- public static final int raw_no_ext = nextId++;
- }
-
- public static final class menu {
- public static final int test = nextId++;
- public static final int test_withchilds = nextId++;
- }
-
- public static final class xml {
- public static final int preferences = nextId++;
- }
-
- public static final class styleable {
- public static final int[] TitleBar = {id.textStyle};
- public static final int TitleBar_textStyle = 0;
-
- public static final int[] HeaderBar = {id.textStyle2, id.textStyle3};
- public static final int HeaderBar_textStyle2 = 0;
- public static final int HeaderBar_textStyle3 = 1;
- }
-
- public static final class dimen {
- public static final int test_dp_dimen = nextId++;
- public static final int test_dip_dimen = nextId++;
- public static final int test_px_dimen = nextId++;
- public static final int test_sp_dimen = nextId++;
- }
-
- public static final class integer {
- public static final int test_non_integer = nextId++;
- public static final int test_integer1 = nextId++;
- public static final int test_integer2 = nextId++;
- public static final int test_large_hex = nextId++;
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/RobolectricConfigTest.java b/v1/src/test/java/com/xtremelabs/robolectric/RobolectricConfigTest.java
deleted file mode 100644
index 0ad7a5b53..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/RobolectricConfigTest.java
+++ /dev/null
@@ -1,96 +0,0 @@
-package com.xtremelabs.robolectric;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import android.content.BroadcastReceiver;
-import android.content.Context;
-import android.content.Intent;
-
-import static android.content.pm.ApplicationInfo.*;
-import static com.xtremelabs.robolectric.util.TestUtil.newConfig;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class RobolectricConfigTest {
- @Test
- public void shouldReadBroadcastReceivers() throws Exception {
- RobolectricConfig config = newConfig("TestAndroidManifestWithReceivers.xml");
-
- assertEquals(7, config.getReceiverCount());
-
- assertEquals("com.xtremelabs.robolectric.RobolectricConfigTest.ConfigTestReceiver", config.getReceiverClassName(0));
- assertEquals("com.xtremelabs.robolectric.ACTION1", config.getReceiverIntentFilterActions(0).get(0));
-
- assertEquals("com.xtremelabs.robolectric.RobolectricConfigTest.ConfigTestReceiver", config.getReceiverClassName(1));
- assertEquals("com.xtremelabs.robolectric.ACTION2", config.getReceiverIntentFilterActions(1).get(0));
-
- assertEquals("com.xtremelabs.robolectric.test.ConfigTestReceiver", config.getReceiverClassName(2));
- assertEquals("com.xtremelabs.robolectric.ACTION_SUPERSET_PACKAGE", config.getReceiverIntentFilterActions(2).get(0));
-
- assertEquals("com.xtremelabs.ConfigTestReceiver", config.getReceiverClassName(3));
- assertEquals("com.xtremelabs.robolectric.ACTION_SUBSET_PACKAGE", config.getReceiverIntentFilterActions(3).get(0));
-
- assertEquals("com.xtremelabs.robolectric.DotConfigTestReceiver", config.getReceiverClassName(4));
- assertEquals("com.xtremelabs.robolectric.ACTION_DOT_PACKAGE", config.getReceiverIntentFilterActions(4).get(0));
-
- assertEquals("com.xtremelabs.robolectric.test.ConfigTestReceiver", config.getReceiverClassName(5));
- assertEquals("com.xtremelabs.robolectric.ACTION_DOT_SUBPACKAGE", config.getReceiverIntentFilterActions(5).get(0));
-
- assertEquals("com.foo.Receiver", config.getReceiverClassName(6));
- assertEquals("com.xtremelabs.robolectric.ACTION_DIFFERENT_PACKAGE", config.getReceiverIntentFilterActions(6).get(0));
- }
-
- @Test
- public void shouldReadSdkVersionFromAndroidManifest() throws Exception {
- assertEquals(42, newConfig("TestAndroidManifestWithSdkVersion.xml").getSdkVersion());
- assertEquals(3, newConfig("TestAndroidManifestWithSdkVersion.xml").getMinSdkVersion());
- }
-
- @Test
- public void shouldRessolveSdkVersionForResources() throws Exception {
- assertEquals(3, newConfig("TestAndroidManifestWithMinSdkVersionOnly.xml").getRealSdkVersion());
- assertEquals(42, newConfig("TestAndroidManifestWithSdkVersion.xml").getRealSdkVersion());
- }
-
- @Test
- public void shouldReadProcessFromAndroidManifest() throws Exception {
- assertEquals("robolectricprocess", newConfig("TestAndroidManifestWithProcess.xml").getProcessName());
- }
-
- @Test
- public void shouldReturnPackageNameWhenNoProcessIsSpecifiedInTheManifest() {
- assertEquals("com.xtremelabs.robolectric", newConfig("TestAndroidManifestWithNoProcess.xml").getProcessName());
- }
-
- @Test
- public void shouldReadFlagsFromAndroidManifest() throws Exception {
- RobolectricConfig config = newConfig("TestAndroidManifestWithFlags.xml");
- assertTrue(hasFlag(config.getApplicationFlags(), FLAG_ALLOW_BACKUP));
- assertTrue(hasFlag(config.getApplicationFlags(), FLAG_ALLOW_CLEAR_USER_DATA));
- assertTrue(hasFlag(config.getApplicationFlags(), FLAG_ALLOW_TASK_REPARENTING));
- assertTrue(hasFlag(config.getApplicationFlags(), FLAG_DEBUGGABLE));
- assertTrue(hasFlag(config.getApplicationFlags(), FLAG_HAS_CODE));
- assertTrue(hasFlag(config.getApplicationFlags(), FLAG_KILL_AFTER_RESTORE));
- assertTrue(hasFlag(config.getApplicationFlags(), FLAG_PERSISTENT));
- assertTrue(hasFlag(config.getApplicationFlags(), FLAG_RESIZEABLE_FOR_SCREENS));
- assertTrue(hasFlag(config.getApplicationFlags(), FLAG_RESTORE_ANY_VERSION));
- assertTrue(hasFlag(config.getApplicationFlags(), FLAG_SUPPORTS_LARGE_SCREENS));
- assertTrue(hasFlag(config.getApplicationFlags(), FLAG_SUPPORTS_NORMAL_SCREENS));
- assertTrue(hasFlag(config.getApplicationFlags(), FLAG_SUPPORTS_SCREEN_DENSITIES));
- assertTrue(hasFlag(config.getApplicationFlags(), FLAG_SUPPORTS_SMALL_SCREENS));
- assertTrue(hasFlag(config.getApplicationFlags(), FLAG_TEST_ONLY));
- assertTrue(hasFlag(config.getApplicationFlags(), FLAG_VM_SAFE_MODE));
- }
-
- private boolean hasFlag(final int flags, final int flag) {
- return (flags & flag) != 0;
- }
-
- public static class ConfigTestReceiver extends BroadcastReceiver {
- @Override
- public void onReceive(Context context, Intent intent) {
- }
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/RobolectricTest.java b/v1/src/test/java/com/xtremelabs/robolectric/RobolectricTest.java
deleted file mode 100644
index 9248ad15d..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/RobolectricTest.java
+++ /dev/null
@@ -1,196 +0,0 @@
-package com.xtremelabs.robolectric;
-
-import android.app.Activity;
-import android.content.Context;
-import android.os.Handler;
-import android.view.Display;
-import android.view.View;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.shadows.ShadowDisplay;
-import com.xtremelabs.robolectric.util.TestOnClickListener;
-import org.apache.http.HttpException;
-import org.apache.http.HttpResponse;
-import org.apache.http.client.methods.HttpGet;
-import org.apache.http.conn.ConnectionKeepAliveStrategy;
-import org.apache.http.impl.client.DefaultRequestDirector;
-import org.apache.http.protocol.HttpContext;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.PrintStream;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.junit.Assert.*;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class RobolectricTest {
-
- private PrintStream originalSystemOut;
- private ByteArrayOutputStream buff;
- private String defaultLineSeparator;
-
- @Before
- public void setUp() {
- originalSystemOut = System.out;
- defaultLineSeparator = System.getProperty("line.separator");
-
- System.setProperty("line.separator", "\n");
- buff = new ByteArrayOutputStream();
- PrintStream testOut = new PrintStream(buff);
- System.setOut(testOut);
- }
-
- @After
- public void tearDown() throws Exception {
- System.setProperty("line.separator", defaultLineSeparator);
- System.setOut(originalSystemOut);
- }
-
- @Test
- public void shouldLogMissingInvokedShadowMethodsWhenRequested() throws Exception {
- Robolectric.bindShadowClass(TestShadowView.class);
- Robolectric.logMissingInvokedShadowMethods();
-
-
- View aView = new View(null);
- // There's a shadow method for this
- aView.getContext();
- String output = buff.toString();
- assertEquals("No Shadow method found for View.<init>(android.content.Context)\n", output);
- buff.reset();
-
- aView.findViewById(27);
- // No shadow here... should be logged
- output = buff.toString();
- assertEquals("No Shadow method found for View.findViewById(int)\n", output);
- }
-
- @Test // This is nasty because it depends on the test above having run first in order to fail
- public void shouldNotLogMissingInvokedShadowMethodsByDefault() throws Exception {
- View aView = new View(null);
- aView.findViewById(27);
- String output = buff.toString();
-
- assertEquals("", output);
- }
-
- @Test(expected = RuntimeException.class)
- public void clickOn_shouldThrowIfViewIsDisabled() throws Exception {
- View view = new View(null);
- view.setEnabled(false);
- Robolectric.clickOn(view);
- }
-
- @Test
- public void shouldResetBackgroundSchedulerBeforeTests() throws Exception {
- assertThat(Robolectric.getBackgroundScheduler().isPaused(), equalTo(false));
- Robolectric.getBackgroundScheduler().pause();
- }
-
- @Test
- public void shouldResetBackgroundSchedulerAfterTests() throws Exception {
- assertThat(Robolectric.getBackgroundScheduler().isPaused(), equalTo(false));
- Robolectric.getBackgroundScheduler().pause();
- }
-
- @Test
- public void httpRequestWasSent_ReturnsTrueIfRequestWasSent() throws IOException, HttpException {
- makeRequest("http://example.com");
-
- assertTrue(Robolectric.httpRequestWasMade());
- }
-
- @Test
- public void httpRequestWasMade_ReturnsFalseIfNoRequestWasMade() {
- assertFalse(Robolectric.httpRequestWasMade());
- }
-
- @Test
- public void httpRequestWasMade_returnsTrueIfRequestMatchingGivenRuleWasMade() throws IOException, HttpException {
- makeRequest("http://example.com");
- assertTrue(Robolectric.httpRequestWasMade("http://example.com"));
- }
-
- @Test
- public void httpRequestWasMade_returnsFalseIfNoRequestMatchingGivenRuleWasMAde() throws IOException, HttpException {
- makeRequest("http://example.com");
- assertFalse(Robolectric.httpRequestWasMade("http://example.org"));
- }
-
- @Test
- public void idleMainLooper_executesScheduledTasks() {
- final boolean[] wasRun = new boolean[]{false};
- new Handler().postDelayed(new Runnable() {
- @Override
- public void run() {
- wasRun[0] = true;
- }
- }, 2000);
-
- assertFalse(wasRun[0]);
- Robolectric.idleMainLooper(1999);
- assertFalse(wasRun[0]);
- Robolectric.idleMainLooper(1);
- assertTrue(wasRun[0]);
- }
-
- @Test
- public void shouldUseSetDensityForContexts() throws Exception {
- assertThat(new Activity().getResources().getDisplayMetrics().density, equalTo(1.0f));
- Robolectric.setDisplayMetricsDensity(1.5f);
- assertThat(new Activity().getResources().getDisplayMetrics().density, equalTo(1.5f));
- }
-
- @Test
- public void shouldUseSetDisplayForContexts() throws Exception {
- assertThat(new Activity().getResources().getDisplayMetrics().widthPixels, equalTo(480));
- assertThat(new Activity().getResources().getDisplayMetrics().heightPixels, equalTo(800));
-
- Display display = Robolectric.newInstanceOf(Display.class);
- ShadowDisplay shadowDisplay = shadowOf(display);
- shadowDisplay.setWidth(100);
- shadowDisplay.setHeight(200);
- Robolectric.setDefaultDisplay(display);
-
- assertThat(new Activity().getResources().getDisplayMetrics().widthPixels, equalTo(100));
- assertThat(new Activity().getResources().getDisplayMetrics().heightPixels, equalTo(200));
- }
-
- public void clickOn_shouldCallClickListener() throws Exception {
- View view = new View(null);
- TestOnClickListener testOnClickListener = new TestOnClickListener();
- view.setOnClickListener(testOnClickListener);
- Robolectric.clickOn(view);
- assertTrue(testOnClickListener.clicked);
- }
-
- @Implements(View.class)
- public static class TestShadowView {
- @SuppressWarnings({"UnusedDeclaration"})
- @Implementation
- public Context getContext() {
- return null;
- }
- }
-
- private void makeRequest(String uri) throws HttpException, IOException {
- Robolectric.addPendingHttpResponse(200, "a happy response body");
-
- ConnectionKeepAliveStrategy connectionKeepAliveStrategy = new ConnectionKeepAliveStrategy() {
- @Override
- public long getKeepAliveDuration(HttpResponse httpResponse, HttpContext httpContext) {
- return 0;
- }
-
- };
- DefaultRequestDirector requestDirector = new DefaultRequestDirector(null, null, null, connectionKeepAliveStrategy, null, null, null, null, null, null, null, null);
-
- requestDirector.execute(null, new HttpGet(uri), null);
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/RobolectricTestRunnerClassLoaderSetup.java b/v1/src/test/java/com/xtremelabs/robolectric/RobolectricTestRunnerClassLoaderSetup.java
deleted file mode 100644
index f44f58f8a..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/RobolectricTestRunnerClassLoaderSetup.java
+++ /dev/null
@@ -1,18 +0,0 @@
-package com.xtremelabs.robolectric;
-
-import org.junit.Assert;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import com.xtremelabs.robolectric.bytecode.RobolectricClassLoader;
-
-
-@RunWith(WithTestDefaultsRunner.class)
-public class RobolectricTestRunnerClassLoaderSetup {
-
- @Test
- public void testUsingClassLoader() throws ClassNotFoundException {
- ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
- Assert.assertEquals(classLoader.getClass().getName(), RobolectricClassLoader.class.getName());
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/RobolectricTestRunnerTest.java b/v1/src/test/java/com/xtremelabs/robolectric/RobolectricTestRunnerTest.java
deleted file mode 100644
index a7859d95a..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/RobolectricTestRunnerTest.java
+++ /dev/null
@@ -1,112 +0,0 @@
-package com.xtremelabs.robolectric;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-import static org.junit.Assert.*;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.model.InitializationError;
-
-import android.app.Activity;
-import android.app.Application;
-import android.widget.TextView;
-
-import com.xtremelabs.robolectric.annotation.DisableStrictI18n;
-import com.xtremelabs.robolectric.annotation.EnableStrictI18n;
-import com.xtremelabs.robolectric.annotation.Values;
-import com.xtremelabs.robolectric.res.ResourceLoader;
-
-@RunWith(RobolectricTestRunnerTest.RunnerForTesting.class)
-public class RobolectricTestRunnerTest {
-
- @Test
- public void shouldInitializeAndBindApplicationButNotCallOnCreate() throws Exception {
- assertNotNull(Robolectric.application);
- assertEquals(MyTestApplication.class, Robolectric.application.getClass());
- assertFalse(((MyTestApplication) Robolectric.application).onCreateWasCalled);
- assertNotNull(shadowOf(Robolectric.application).getResourceLoader());
- }
-
- @Test
- public void setStaticValue_shouldIgnoreFinalModifier() {
- RobolectricTestRunner.setStaticValue(android.os.Build.class, "MODEL", "expected value");
-
- assertEquals("expected value", android.os.Build.MODEL);
- }
-
- @Test
- @EnableStrictI18n
- public void internalBeforeTest_setsI18nStrictModeFromProperty() {
- assertTrue(RunnerForTesting.instance.robolectricConfig.getStrictI18n());
- }
-
- @Test
- @DisableStrictI18n
- public void internalBeforeTest_clearsI18nStrictModeFromProperty() {
- assertFalse(RunnerForTesting.instance.robolectricConfig.getStrictI18n());
- }
-
- @Test
- @Values( locale="fr")
- public void internalBeforeTest_setLocale(){
- assertEquals( RunnerForTesting.instance.robolectricConfig.getLocale(), "fr" );
- }
-
- @Test
- public void internalBeforeTest_doesNotsetI18nStrictModeFromSystemIfPropertyAbsent() {
- assertFalse(RunnerForTesting.instance.robolectricConfig.getStrictI18n());
- }
-
- @Test
- @EnableStrictI18n
- public void methodBlock_setsI18nStrictModeForClassHandler() {
- TextView tv = new TextView(Robolectric.application);
- try {
- tv.setText("Foo");
- fail("TextView#setText(String) should produce an i18nException");
- } catch (Exception e) {
- // Compare exception name because it was loaded in the instrumented classloader
- assertEquals("com.xtremelabs.robolectric.util.I18nException", e.getClass().getName());
- }
- }
-
- @Test
- @EnableStrictI18n
- public void createResourceLoader_setsI18nStrictModeForResourceLoader() {
- ResourceLoader loader = Robolectric.shadowOf(Robolectric.application).getResourceLoader();
- assertTrue(RunnerForTesting.instance.robolectricConfig.getStrictI18n());
- assertTrue(loader.getStrictI18n());
- try {
- loader.inflateView(Robolectric.application, R.layout.text_views, null);
- fail("ResourceLoader#inflateView should produce an i18nException");
- } catch (Exception e) {
- assertEquals("com.xtremelabs.robolectric.util.I18nException", e.getClass().getName());
- }
- }
-
- public static class RunnerForTesting extends WithTestDefaultsRunner {
- public static RunnerForTesting instance;
-
- public RunnerForTesting(Class<?> testClass) throws InitializationError {
- super(testClass);
- instance = this;
- }
-
- @Override protected Application createApplication() {
- return new MyTestApplication();
- }
- }
-
- public static class MyTestApplication extends Application {
- private boolean onCreateWasCalled;
-
- @Override public void onCreate() {
- this.onCreateWasCalled = true;
- }
- }
-
- public static class MyTestActivity extends Activity {
-
- }
-
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/TemporaryBindingsTest.java b/v1/src/test/java/com/xtremelabs/robolectric/TemporaryBindingsTest.java
deleted file mode 100644
index 5c56ce867..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/TemporaryBindingsTest.java
+++ /dev/null
@@ -1,39 +0,0 @@
-package com.xtremelabs.robolectric;
-
-import android.view.View;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.shadows.ShadowView;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.junit.Assert.assertThat;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class TemporaryBindingsTest {
-
- @Test
- public void overridingShadowBindingsShouldNotAffectBindingsInLaterTests() throws Exception {
- assertThat(shadowOf(new View(null)).getClass().getSimpleName(), equalTo(ShadowView.class.getSimpleName()));
-
- Robolectric.bindShadowClass(TemporaryShadowView.class);
-
- assertThat(Robolectric.shadowOf_(new View(null)).getClass().getSimpleName(),
- equalTo(TemporaryShadowView.class.getSimpleName()));
- }
-
- @Test
- public void overridingShadowBindingsShouldNotAffectBindingsInLaterTestsAgain() throws Exception {
- assertThat(shadowOf(new View(null)).getClass().getSimpleName(), equalTo(ShadowView.class.getSimpleName()));
-
- Robolectric.bindShadowClass(TemporaryShadowView.class);
-
- assertThat(Robolectric.shadowOf_(new View(null)).getClass().getSimpleName(),
- equalTo(TemporaryShadowView.class.getSimpleName()));
- }
-
- @Implements(View.class)
- public static class TemporaryShadowView {
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/TestApplication.java b/v1/src/test/java/com/xtremelabs/robolectric/TestApplication.java
deleted file mode 100644
index e59941315..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/TestApplication.java
+++ /dev/null
@@ -1,6 +0,0 @@
-package com.xtremelabs.robolectric;
-
-import android.app.Application;
-
-public class TestApplication extends Application {
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/WithCustomClassListTestRunner.java b/v1/src/test/java/com/xtremelabs/robolectric/WithCustomClassListTestRunner.java
deleted file mode 100644
index 68ff154bd..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/WithCustomClassListTestRunner.java
+++ /dev/null
@@ -1,16 +0,0 @@
-package com.xtremelabs.robolectric;
-
-
-import org.junit.runners.model.InitializationError;
-
-import static com.xtremelabs.robolectric.util.TestUtil.resourceFile;
-
-public class WithCustomClassListTestRunner extends RobolectricTestRunner {
-
- public WithCustomClassListTestRunner(@SuppressWarnings("rawtypes") Class testClass) throws InitializationError {
- super(testClass, new RobolectricConfig(resourceFile("TestAndroidManifest.xml"), resourceFile("res"), resourceFile("assets")));
-
- addClassOrPackageToInstrument("com.xtremelabs.robolectric.bytecode.AndroidTranslatorClassIntrumentedTest$CustomPaint");
- addClassOrPackageToInstrument("com.xtremelabs.robolectric.bytecode.AndroidTranslatorClassIntrumentedTest$ClassWithPrivateConstructor");
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/WithTestDefaultsRunner.java b/v1/src/test/java/com/xtremelabs/robolectric/WithTestDefaultsRunner.java
deleted file mode 100644
index 57e2562e6..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/WithTestDefaultsRunner.java
+++ /dev/null
@@ -1,20 +0,0 @@
-package com.xtremelabs.robolectric;
-
-import static com.xtremelabs.robolectric.util.TestUtil.resourceFile;
-
-import org.junit.runners.model.InitializationError;
-
-import com.xtremelabs.robolectric.bytecode.ClassHandler;
-import com.xtremelabs.robolectric.bytecode.RobolectricClassLoader;
-import com.xtremelabs.robolectric.util.DatabaseConfig.DatabaseMap;
-
-public class WithTestDefaultsRunner extends RobolectricTestRunner {
-
- public WithTestDefaultsRunner(Class<?> testClass) throws InitializationError {
- super(testClass, new RobolectricConfig(resourceFile("TestAndroidManifest.xml"), resourceFile("res"), resourceFile("assets")));
- }
- public WithTestDefaultsRunner(Class<?> testClass,DatabaseMap databaseMap) throws InitializationError {
- super(testClass, new RobolectricConfig(resourceFile("TestAndroidManifest.xml"), resourceFile("res"), resourceFile("assets")), databaseMap);
- }
-
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/WithoutTestDefaultsRunner.java b/v1/src/test/java/com/xtremelabs/robolectric/WithoutTestDefaultsRunner.java
deleted file mode 100644
index 6d91ba160..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/WithoutTestDefaultsRunner.java
+++ /dev/null
@@ -1,15 +0,0 @@
-package com.xtremelabs.robolectric;
-
-import org.junit.runners.model.InitializationError;
-
-import java.lang.reflect.Method;
-
-public class WithoutTestDefaultsRunner extends RobolectricTestRunner {
- public WithoutTestDefaultsRunner(Class<?> testClass) throws InitializationError {
- super(testClass);
- }
-
- @Override public void internalBeforeTest(Method method) {
- // Don't do any resource loading or shadow class binding, because that's what we're trying to test here.
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/bytecode/AndroidTranslatorClassIntrumentedTest.java b/v1/src/test/java/com/xtremelabs/robolectric/bytecode/AndroidTranslatorClassIntrumentedTest.java
deleted file mode 100644
index 99d8280fb..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/bytecode/AndroidTranslatorClassIntrumentedTest.java
+++ /dev/null
@@ -1,156 +0,0 @@
-package com.xtremelabs.robolectric.bytecode;
-
-import android.graphics.Bitmap;
-import android.graphics.Paint;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithCustomClassListTestRunner;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.CoreMatchers.is;
-import static org.junit.Assert.assertThat;
-
-@RunWith(WithCustomClassListTestRunner.class)
-public class AndroidTranslatorClassIntrumentedTest {
-
- @Test
- public void testNativeMethodsAreDelegated() throws Exception {
- Robolectric.bindShadowClass(ShadowPaintForTests.class);
-
- Paint paint = new Paint();
- paint.setColor(1234);
-
- assertThat(paint.getColor(), is(1234));
- }
-
- @Test
- public void testClassesWithPrivateDefaultConstructorsCanBeShadowed() {
- Robolectric.bindShadowClass(ShadowClassWithPrivateConstructor.class);
-
- ClassWithPrivateConstructor inst = new ClassWithPrivateConstructor();
- assertThat(inst.getInt(), is(42));
- }
-
- @Test
- public void testEnumConstructorsAreNotRewritten() {
- // just referencing this enum value would blow up if we rewrite its constructor
- Bitmap.Config alpha8 = Bitmap.Config.ALPHA_8;
- assertThat(alpha8.toString(), equalTo("ALPHA_8"));
- }
-
- /*
- * Test "foreign class" getting its methods shadowed whe it's
- * in the RobolectricClassLoader CustomClassNames arrayList
- */
- @Test
- public void testCustomMethodShadowed() throws Exception {
- Robolectric.bindShadowClass(ShadowCustomPaint.class);
-
- CustomPaint customPaint = new CustomPaint();
- assertThat(customPaint.getColor(), equalTo(10));
- assertThat(customPaint.getColorName(), equalTo("rainbow"));
- }
-
- /*
- * Test "foreign class" not getting its methods shadowed when it's
- * not in the RobolectricClassLoader CustomClassNames arrayList
- */
- @Test
- public void testCustomMethodNotShadowed() throws Exception {
- Robolectric.bindShadowClass(ShadowCustomXmasPaint.class);
-
- CustomXmasPaint customXmasPaint = new CustomXmasPaint();
- assertThat(customXmasPaint.getColor(), equalTo(999));
- assertThat(customXmasPaint.getColorName(), equalTo("XMAS"));
- }
-
- public static class ClassWithPrivateConstructor {
- private ClassWithPrivateConstructor() {
- }
-
- public int getInt() {
- return 99;
- }
- }
-
- @Implements(ClassWithPrivateConstructor.class)
- public static class ShadowClassWithPrivateConstructor {
- @Implementation
- public int getInt() {
- return 42;
- }
- }
-
- @Implements(Paint.class)
- public static class ShadowPaintForTests {
- private int color;
-
- @Implementation
- public void setColor(int color) {
- this.color = color;
- }
-
- @Implementation
- public int getColor() {
- return color;
- }
- }
-
- @SuppressWarnings({"UnusedDeclaration"})
- public static class CustomPaint extends Paint {
- private int customColor;
-
- @Override
- public int getColor() {
- return customColor;
- }
-
- public String getColorName() {
- return Integer.toString(customColor);
- }
- }
-
- @Implements(CustomPaint.class)
- public static class ShadowCustomPaint {
-
- @Implementation
- public int getColor() {
- return 10;
- }
-
- @Implementation
- public String getColorName() {
- return "rainbow";
- }
- }
-
- @SuppressWarnings({"UnusedDeclaration"})
- public static class CustomXmasPaint extends Paint {
-
- @Override
- public int getColor() {
- return 999;
- }
-
- public String getColorName() {
- return "XMAS";
- }
- }
-
- @Implements(CustomXmasPaint.class)
- public static class ShadowCustomXmasPaint {
-
- @Implementation
- public int getColor() {
- return -999;
- }
-
- @Implementation
- public String getColorName() {
- return "XMAS Color Test";
- }
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/bytecode/AndroidTranslatorTest.java b/v1/src/test/java/com/xtremelabs/robolectric/bytecode/AndroidTranslatorTest.java
deleted file mode 100644
index 8d35ce65b..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/bytecode/AndroidTranslatorTest.java
+++ /dev/null
@@ -1,234 +0,0 @@
-package com.xtremelabs.robolectric.bytecode;
-
-import android.accounts.AccountManager;
-import android.content.Context;
-import android.graphics.Paint;
-import android.graphics.drawable.Drawable;
-import android.util.Log;
-import android.view.View;
-import android.widget.TextView;
-import com.google.android.maps.ItemizedOverlay;
-import com.google.android.maps.OverlayItem;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.internal.Instrument;
-import com.xtremelabs.robolectric.shadows.ShadowItemizedOverlay;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import java.lang.reflect.Constructor;
-
-import static com.xtremelabs.robolectric.Robolectric.directlyOn;
-import static com.xtremelabs.robolectric.RobolectricForMaps.shadowOf;
-import static org.hamcrest.CoreMatchers.*;
-import static org.hamcrest.core.StringContains.containsString;
-import static org.hamcrest.core.StringStartsWith.startsWith;
-import static org.junit.Assert.*;
-import static org.mockito.Mockito.mock;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class AndroidTranslatorTest {
-
- @Test
- public void testStaticMethodsAreDelegated() throws Exception {
- Robolectric.bindShadowClass(ShadowAccountManagerForTests.class);
-
- Context context = mock(Context.class);
- AccountManager.get(context);
- assertThat(ShadowAccountManagerForTests.wasCalled, is(true));
- assertThat(ShadowAccountManagerForTests.context, sameInstance(context));
- }
-
- @Test
- public void testProtectedMethodsAreDelegated() throws Exception {
- Robolectric.bindShadowClass(ShadowItemizedOverlay.class);
-
- ItemizedOverlayForTests overlay = new ItemizedOverlayForTests(null);
- overlay.triggerProtectedCall();
-
- assertThat(shadowOf(overlay).isPopulated(), is(true));
- }
-
- @Test
- public void testNativeMethodsAreDelegated() throws Exception {
- Robolectric.bindShadowClass(ShadowPaintForTests.class);
-
- Paint paint = new Paint();
- paint.setColor(1234);
-
- assertThat(paint.getColor(), is(1234));
- }
-
- @Test
- public void testPrintlnWorks() throws Exception {
- Log.println(1, "tag", "msg");
- }
-
- @Test
- public void testGeneratedDefaultConstructorIsWired() throws Exception {
- Robolectric.bindShadowClass(ShadowClassWithNoDefaultConstructor.class);
-
- Constructor<ClassWithNoDefaultConstructor> ctor = ClassWithNoDefaultConstructor.class.getDeclaredConstructor();
- ctor.setAccessible(true);
- ClassWithNoDefaultConstructor instance = ctor.newInstance();
- assertThat(Robolectric.shadowOf_(instance), not(nullValue()));
- assertThat(Robolectric.shadowOf_(instance), instanceOf(ShadowClassWithNoDefaultConstructor.class));
- }
-
- @Test
- public void testDirectlyOn() throws Exception {
- View view = new View(null);
- view.bringToFront();
-
- Exception e = null;
- try {
- directlyOn(view).bringToFront();
- } catch (RuntimeException e1) {
- e = e1;
- }
- assertNotNull(e);
- assertEquals("Stub!", e.getMessage());
-
- view.bringToFront();
- }
-
- @Test
- public void testDirectlyOn_Statics() throws Exception {
- View.resolveSize(0, 0);
-
- Exception e = null;
- try {
- directlyOn(View.class);
- View.resolveSize(0, 0);
- } catch (RuntimeException e1) {
- e = e1;
- }
- assertNotNull(e);
- assertEquals("Stub!", e.getMessage());
-
- View.resolveSize(0, 0);
- }
-
- @Test
- public void testDirectlyOn_InstanceChecking() throws Exception {
- View view1 = new View(null);
- View view2 = new View(null);
-
- Exception e = null;
- try {
- directlyOn(view1);
- view2.bringToFront();
- } catch (RuntimeException e1) {
- e = e1;
- }
- assertNotNull(e);
- assertThat(e.getMessage(), startsWith("expected to perform direct call on <android.view.View"));
- assertThat(e.getMessage(), containsString("> but got <android.view.View"));
- }
-
- @Test
- public void testDirectlyOn_Statics_InstanceChecking() throws Exception {
- TextView.getTextColors(null, null);
-
- Exception e = null;
- try {
- directlyOn(View.class);
- TextView.getTextColors(null, null);
- } catch (RuntimeException e1) {
- e = e1;
- }
- assertNotNull(e);
- assertThat(e.getMessage(), equalTo("expected to perform direct call on <class android.view.View> but got <class android.widget.TextView>"));
- }
-
- @Test
- public void testDirectlyOn_CallTwiceChecking() throws Exception {
- directlyOn(View.class);
-
- Exception e = null;
- try {
- directlyOn(View.class);
- } catch (RuntimeException e1) {
- e = e1;
- }
- assertNotNull(e);
- assertThat(e.getMessage(), equalTo("already expecting a direct call on <class android.view.View> but here's a new request for <class android.view.View>"));
- }
-
- @Test
- public void shouldDelegateToObjectToStringIfShadowHasNone() throws Exception {
- assertTrue(new View(null).toString().startsWith("android.view.View@"));
- }
-
- @Test
- public void shouldDelegateToObjectHashCodeIfShadowHasNone() throws Exception {
- assertFalse(new View(null).hashCode() == 0);
- }
-
- @Test
- public void shouldDelegateToObjectEqualsIfShadowHasNone() throws Exception {
- View view = new View(null);
- assertEquals(view, view);
- }
-
- @Implements(ItemizedOverlay.class)
- public static class ItemizedOverlayForTests extends ItemizedOverlay {
- public ItemizedOverlayForTests(Drawable drawable) {
- super(drawable);
- }
-
- @Override
- protected OverlayItem createItem(int i) {
- return null;
- }
-
- public void triggerProtectedCall() {
- populate();
- }
-
- @Override
- public int size() {
- return 0;
- }
- }
-
- @Implements(Paint.class)
- public static class ShadowPaintForTests {
- private int color;
-
- @Implementation
- public void setColor(int color) {
- this.color = color;
- }
-
- @Implementation
- public int getColor() {
- return color;
- }
- }
-
- @Implements(AccountManager.class)
- public static class ShadowAccountManagerForTests {
- public static boolean wasCalled = false;
- public static Context context;
-
- public static AccountManager get(Context context) {
- wasCalled = true;
- ShadowAccountManagerForTests.context = context;
- return mock(AccountManager.class);
- }
- }
-
- @Instrument
- @SuppressWarnings({"UnusedDeclaration"})
- public static class ClassWithNoDefaultConstructor {
- ClassWithNoDefaultConstructor(String string) {
- }
- }
-
- @Implements(ClassWithNoDefaultConstructor.class)
- public static class ShadowClassWithNoDefaultConstructor {
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/bytecode/AndroidTranslatorUnitTest.java b/v1/src/test/java/com/xtremelabs/robolectric/bytecode/AndroidTranslatorUnitTest.java
deleted file mode 100644
index b41f950d1..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/bytecode/AndroidTranslatorUnitTest.java
+++ /dev/null
@@ -1,151 +0,0 @@
-package com.xtremelabs.robolectric.bytecode;
-
-import javassist.ClassPool;
-import javassist.CtClass;
-import org.junit.Before;
-import org.junit.Test;
-
-import static org.junit.Assert.*;
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.anyObject;
-import static org.mockito.Matchers.eq;
-import static org.mockito.Mockito.*;
-
-public class AndroidTranslatorUnitTest {
- private ClassPool classPool;
- private AndroidTranslator androidTranslator;
-
- @Before public void setUp() throws Exception {
- classPool = new ClassPool(true);
- androidTranslator = new AndroidTranslator(null, null);
- }
-
- @Test
- public void whenMethodReturnsObject_shouldGenerateMethodBody() throws Exception {
- CtClass ctClass = classPool.get("java.lang.String");
- String methodBody = androidTranslator.generateMethodBody(
- ctClass, ctClass.getDeclaredMethod("substring", new CtClass[]{CtClass.intType}),
- ctClass, Type.OBJECT, false, false);
- assertEquals("if (!com.xtremelabs.robolectric.bytecode.RobolectricInternals.shouldCallDirectly(this)) {\n" +
- "Object x = com.xtremelabs.robolectric.bytecode.RobolectricInternals.methodInvoked(\n" +
- " java.lang.String.class, \"substring\", this, new String[] {\"int\"}, new Object[] {com.xtremelabs.robolectric.bytecode.RobolectricInternals.autobox($1)});\n" +
- "if (x != null) return ((java.lang.String) x);\n" +
- "return null;\n" +
- "}\n", methodBody);
- }
-
- @Test
- public void whenMethodReturnsPrimitive_shouldGenerateMethodBody() throws Exception {
- CtClass ctClass = classPool.get("java.lang.String");
- String methodBody = androidTranslator.generateMethodBody(
- ctClass, ctClass.getDeclaredMethod("length"),
- ctClass, Type.OBJECT, false, false);
- assertEquals("if (!com.xtremelabs.robolectric.bytecode.RobolectricInternals.shouldCallDirectly(this)) {\n" +
- "Object x = com.xtremelabs.robolectric.bytecode.RobolectricInternals.methodInvoked(\n" +
- " java.lang.String.class, \"length\", this, new String[0], new Object[0]);\n" +
- "if (x != null) return ((java.lang.String) x);\n" +
- "return null;\n" +
- "}\n", methodBody);
- }
-
- @Test
- public void whenMethodReturnsVoid_shouldGenerateMethodBody() throws Exception {
- CtClass ctClass = classPool.get("java.lang.Object");
- String methodBody = androidTranslator.generateMethodBody(
- ctClass, ctClass.getDeclaredMethod("wait"),
- ctClass, Type.VOID, false, false);
- assertEquals("if (!com.xtremelabs.robolectric.bytecode.RobolectricInternals.shouldCallDirectly(this)) {\n" +
- "com.xtremelabs.robolectric.bytecode.RobolectricInternals.methodInvoked(\n" +
- " java.lang.Object.class, \"wait\", this, new String[] {\"long\"}, new Object[] {com.xtremelabs.robolectric.bytecode.RobolectricInternals.autobox($1)});\n" +
- "return;\n" +
- "}\n", methodBody);
- }
-
- @Test
- public void whenMethodIsStatic_shouldGenerateMethodBody() throws Exception {
- CtClass ctClass = classPool.get("java.lang.String");
- String methodBody = androidTranslator.generateMethodBody(
- ctClass, ctClass.getDeclaredMethod("valueOf", new CtClass[]{CtClass.intType}),
- ctClass, Type.OBJECT, true, false);
- assertEquals("if (!com.xtremelabs.robolectric.bytecode.RobolectricInternals.shouldCallDirectly(java.lang.String.class)) {\n" +
- "Object x = com.xtremelabs.robolectric.bytecode.RobolectricInternals.methodInvoked(\n" +
- " java.lang.String.class, \"valueOf\", null, new String[] {\"int\"}, new Object[] {com.xtremelabs.robolectric.bytecode.RobolectricInternals.autobox($1)});\n" +
- "if (x != null) return ((java.lang.String) x);\n" +
- "return null;\n" +
- "}\n", methodBody);
- }
-
- @Test
- public void shouldGenerateParameterList() throws Exception {
- assertEquals(androidTranslator.makeParameterReplacementList(0), "");
- assertEquals(androidTranslator.makeParameterReplacementList(1), "$1");
- assertEquals(androidTranslator.makeParameterReplacementList(2), "$1, $2");
- }
-
- @Test
- public void shouldGenerateMethodBodyForEquals() throws Exception {
- CtClass ctClass = classPool.get("java.lang.Object");
- String methodBody = androidTranslator.generateMethodBody(
- ctClass, ctClass.getDeclaredMethod("equals", new CtClass[]{ctClass}),
- ctClass, Type.BOOLEAN, false, true);
- assertEquals("if (!com.xtremelabs.robolectric.bytecode.RobolectricInternals.shouldCallDirectly(this)) {\n" +
- "Object x = com.xtremelabs.robolectric.bytecode.RobolectricInternals.methodInvoked(\n" +
- " java.lang.Object.class, \"equals\", this, new String[] {\"java.lang.Object\"}, new Object[] {com.xtremelabs.robolectric.bytecode.RobolectricInternals.autobox($1)});\n" +
- "if (x != null) return ((java.lang.Boolean) x).booleanValue();\n" +
- "return super.equals($1);}\n", methodBody);
- }
-
- @Test
- public void shouldInstrumentDefaultRequestDirector() throws Exception {
- assertTrue(androidTranslator.shouldInstrument(classPool.makeClass("org.apache.http.impl.client.DefaultRequestDirector")));
- }
-
- @Test
- public void shouldInstrumentGoogleMapsClasses() throws Exception {
- assertTrue(androidTranslator.shouldInstrument(classPool.makeClass("com.google.android.maps.SomeMapsClass")));
- }
-
- @Test
- public void shouldNotInstrumentCoreJdkClasses() throws Exception {
- assertFalse(androidTranslator.shouldInstrument(classPool.get("java.lang.Object")));
- assertFalse(androidTranslator.shouldInstrument(classPool.get("java.lang.String")));
- }
-
- @Test
- public void shouldInstumentAndroidCoreClasses() throws Exception {
- assertTrue(androidTranslator.shouldInstrument(classPool.makeClass("android.content.Intent")));
- assertTrue(androidTranslator.shouldInstrument(classPool.makeClass("android.and.now.for.something.completely.different")));
-
- }
-
- @Test
- public void shouldNotInstrumentLocalBroadcastManager() throws Exception {
- assertFalse(androidTranslator.shouldInstrument(classPool.makeClass("android.support.v4.content.LocalBroadcastManager")));
- }
-
- @Test
- public void shouldAddCustomShadowClass() throws Exception {
- androidTranslator.addCustomShadowClass("my.custom.Klazz");
- assertTrue(androidTranslator.shouldInstrument(classPool.makeClass("my.custom.Klazz")));
- }
-
- @Test
- public void testOnLoadWithNonInstrumentedClass() throws Exception {
- ClassHandler handler = mock(ClassHandler.class);
- ClassCache cache = mock(ClassCache.class);
-
- AndroidTranslator translator = new AndroidTranslator(handler, cache);
-
- translator.onLoad(classPool, "java.lang.Object");
- verify(cache).isWriting();
- verifyNoMoreInteractions(cache);
- verifyZeroInteractions(handler);
- }
-
- @Test(expected = IllegalStateException.class)
- public void shouldThrowIllegalStateIfClassCacheIsWriting() throws Exception {
- ClassCache cache = mock(ClassCache.class);
- when(cache.isWriting()).thenReturn(true);
- new AndroidTranslator(null, cache).onLoad(classPool, "java.lang.Object");
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/bytecode/ClassCacheTest.java b/v1/src/test/java/com/xtremelabs/robolectric/bytecode/ClassCacheTest.java
deleted file mode 100644
index e14734dfd..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/bytecode/ClassCacheTest.java
+++ /dev/null
@@ -1,124 +0,0 @@
-package com.xtremelabs.robolectric.bytecode;
-
-import org.junit.Assert;
-import org.junit.Test;
-
-public class ClassCacheTest {
-
-
- @Test
- public void fixForCorberturaAndSonarCodeCoverage() throws InterruptedException {
- final ClassCache classCache = new ClassCache("target/test.txt", AndroidTranslator.CACHE_VERSION);
-
- // Substitute this LOCK with your monitor (could be you object you are
- // testing etc.)
- Thread locker = new Thread() {
- @Override
- public void run() {
- synchronized (classCache) {
- try {
- Thread.sleep(Long.MAX_VALUE);
- } catch (InterruptedException e) {
- return;
- }
- }
- }
- };
-
- locker.start();
-
- TestThreadIsWriting attempt = new TestThreadIsWriting(classCache);
-
- try {
- int timeToWait = 500;
- locker.join(timeToWait, 0);
-
- attempt.start();
- long before = System.currentTimeMillis();
- attempt.join(timeToWait, 0);
- long after = System.currentTimeMillis();
- Assert.assertEquals(false, attempt.ready);
- Assert.assertEquals(1, (after - before) / timeToWait);
- locker.interrupt();
- } finally {
-
- }
- }
-
- @Test
- public void fixForCorberturaAndSonarCodeCoverageTheOtherWayAround() throws InterruptedException {
- final ClassCache classCache = new ClassCache("target/test.txt", AndroidTranslator.CACHE_VERSION);
-
- // Substitute this LOCK with your monitor (could be you object you are
- // testing etc.)
- Thread locker = new Thread() {
- @Override
- public void run() {
- synchronized (classCache) {
- try {
- Thread.sleep(Long.MAX_VALUE);
- } catch (InterruptedException e) {
- return;
- }
- }
- }
- };
-
- locker.start();
-
- TestThreadSaveAllClassesToCache attempt = new TestThreadSaveAllClassesToCache(classCache);
-
- try {
- int timeToWait = 500;
- locker.join(timeToWait, 0);
-
- attempt.start();
- long before = System.currentTimeMillis();
- attempt.join(timeToWait, 0);
- long after = System.currentTimeMillis();
- Assert.assertEquals(false, attempt.ready);
- Assert.assertEquals(1, (after - before) / timeToWait);
- locker.interrupt();
-
- } finally {
-
- }
- }
-
- class TestThreadIsWriting extends Thread {
- public boolean ready = false;
- final ClassCache classCache;
-
-
- public TestThreadIsWriting(ClassCache classCache) {
- super();
- this.classCache = classCache;
- }
-
-
- @Override
- public void run() {
- classCache.isWriting();
- ready = true;
- }
- };
-
- class TestThreadSaveAllClassesToCache extends Thread {
- public boolean ready = false;
- final ClassCache classCache;
-
-
- public TestThreadSaveAllClassesToCache(ClassCache classCache) {
- super();
- this.classCache = classCache;
- }
-
-
- @Override
- public void run() {
- classCache.saveAllClassesToCache(null, null);
- ready = true;
- }
- };
-
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/bytecode/CustomRobolectricTestRunnerTest.java b/v1/src/test/java/com/xtremelabs/robolectric/bytecode/CustomRobolectricTestRunnerTest.java
deleted file mode 100644
index 5d2af05da..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/bytecode/CustomRobolectricTestRunnerTest.java
+++ /dev/null
@@ -1,77 +0,0 @@
-package com.xtremelabs.robolectric.bytecode;
-
-import android.app.Application;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.AfterClass;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.model.InitializationError;
-
-import java.lang.reflect.Method;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-
-@RunWith(CustomRobolectricTestRunnerTest.CustomRobolectricTestRunner.class)
-public class CustomRobolectricTestRunnerTest {
- Object preparedTest;
- static Method testMethod;
- static int beforeCallCount = 0;
- static int afterTestCallCount = 0;
-
- @Before
- public void setUp() throws Exception {
- beforeCallCount++;
- }
-
- @Test
- public void shouldInitializeApplication() throws Exception {
- assertNotNull(Robolectric.application);
- assertEquals(CustomApplication.class, Robolectric.application.getClass());
- }
-
- @Test
- public void shouldInvokePrepareTestWithAnInstanceOfTheTest() throws Exception {
- assertEquals(this, preparedTest);
- assertEquals(RobolectricClassLoader.class.getName(), preparedTest.getClass().getClassLoader().getClass().getName());
- }
-
- @Test
- public void shouldInvokeBeforeTestWithTheCorrectMethod() throws Exception {
- assertEquals("shouldInvokeBeforeTestWithTheCorrectMethod", testMethod.getName());
- }
-
- @AfterClass
- public static void shouldHaveCalledAfterTest() {
- assertTrue(beforeCallCount > 0);
- assertEquals(beforeCallCount, afterTestCallCount);
- }
-
- public static class CustomRobolectricTestRunner extends WithTestDefaultsRunner {
- public CustomRobolectricTestRunner(Class<?> testClass) throws InitializationError {
- super(testClass);
- }
-
- @Override public void prepareTest(Object test) {
- ((CustomRobolectricTestRunnerTest) test).preparedTest = test;
- }
-
- @Override public void beforeTest(Method method) {
- testMethod = method;
- }
-
- @Override public void afterTest(Method method) {
- afterTestCallCount++;
- }
-
- @Override protected Application createApplication() {
- return new CustomApplication();
- }
- }
-
- public static class CustomApplication extends Application {
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/bytecode/Foo.java b/v1/src/test/java/com/xtremelabs/robolectric/bytecode/Foo.java
deleted file mode 100644
index cd93b1bd8..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/bytecode/Foo.java
+++ /dev/null
@@ -1,18 +0,0 @@
-package com.xtremelabs.robolectric.bytecode;
-
-import com.xtremelabs.robolectric.internal.Instrument;
-
-@Instrument
-public class Foo {
- public Foo(String s) {
- throw new RuntimeException("stub!");
- }
-
- public String getName() {
- throw new RuntimeException("stub!");
- }
-
- public void findFooById(int i) {
- throw new RuntimeException("stub!");
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/bytecode/RobolectricWiringTest.java b/v1/src/test/java/com/xtremelabs/robolectric/bytecode/RobolectricWiringTest.java
deleted file mode 100644
index 60ea55160..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/bytecode/RobolectricWiringTest.java
+++ /dev/null
@@ -1,117 +0,0 @@
-package com.xtremelabs.robolectric.bytecode;
-
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.util.Join;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
-
-import java.lang.reflect.Member;
-import java.lang.reflect.Method;
-import java.lang.reflect.Modifier;
-import java.util.ArrayList;
-import java.util.List;
-
-public class RobolectricWiringTest {
- private List<String> mismatches;
-
- @Before public void setUp() throws Exception {
- mismatches = new ArrayList<String>();
- }
-
- @Test
- public void testAllImplementationMethodsHaveCorrectSignature() throws Exception {
- for (Class<?> shadowClass : Robolectric.getDefaultShadowClasses()) {
- verifyClass(shadowClass);
- }
-
- Assert.assertEquals("@Implementation method mismatch: " + Join.join("\n", mismatches), 0, mismatches.size());
- }
-
- private void verifyClass(final Class<?> shadowClass) {
- Implements annotation = shadowClass.getAnnotation(Implements.class);
- Class implementedClass = annotation.value();
-
- try {
- shadowClass.getConstructor(implementedClass);
- } catch (NoSuchMethodException e) {
- try {
- shadowClass.getConstructor();
- } catch (NoSuchMethodException e1) {
- mismatches.add("Missing constructor for " + shadowClass.getSimpleName());
- }
- }
-
- for (Method shadowMethod : shadowClass.getDeclaredMethods()) {
- verifyMethod(implementedClass, shadowMethod);
- }
- }
-
- private void verifyMethod(Class implementedClass, Method shadowMethod) {
- Member implementedMember;
-
- boolean isConstructor = shadowMethod.getName().equals("__constructor__");
- if (isAnnotatedImplementation(shadowMethod) || isConstructor) {
- if (isConstructor) {
- implementedMember = findConstructor(implementedClass, shadowMethod);
- } else {
- implementedMember = findMethod(implementedClass, shadowMethod);
- }
- if (implementedMember == null) {
- mismatches.add(shadowMethod.toGenericString() + " doesn't match a real method");
- } else if (staticMismatch(shadowMethod, implementedMember)) {
- mismatches.add(shadowMethod.toGenericString() + " doesn't match the staticness of the real method");
- }
- if (!Modifier.isPublic(shadowMethod.getModifiers())) {
- mismatches.add(shadowMethod.toGenericString() + " should be public");
- }
- } else {
- implementedMember = findMethod(implementedClass, shadowMethod);
- if (implementedMember != null) {
- mismatches.add(shadowMethod.toGenericString() + " should be annotated @Implementation");
- }
- }
- }
-
- private boolean isAnnotatedImplementation(Method shadowMethod) {
- // works around a weird bug causing overridden methods to show no annotations
- try {
- return shadowMethod.getDeclaringClass().getDeclaredMethod(shadowMethod.getName(), shadowMethod.getParameterTypes()).isAnnotationPresent(Implementation.class);
- } catch (NoSuchMethodException e) {
- throw new RuntimeException(e);
- }
- }
-
- private Member findConstructor(Class implementedClass, Method shadowMethod) {
- Class<?>[] parameterTypes = shadowMethod.getParameterTypes();
- try {
- return implementedClass.getConstructor(parameterTypes);
- } catch (NoSuchMethodException e1) {
- try {
- return implementedClass.getDeclaredConstructor(parameterTypes);
- } catch (NoSuchMethodException e2) {
- return null;
- }
- }
- }
-
- private Member findMethod(Class implementedClass, Method shadowMethod) {
- Class<?>[] parameterTypes = shadowMethod.getParameterTypes();
- String methodName = shadowMethod.getName();
- try {
- return implementedClass.getMethod(methodName, parameterTypes);
- } catch (NoSuchMethodException e1) {
- try {
- return implementedClass.getDeclaredMethod(methodName, parameterTypes);
- } catch (NoSuchMethodException e2) {
- return null;
- }
- }
- }
-
- private boolean staticMismatch(Member shadowMethod, Member implementedMethod) {
- return Modifier.isStatic(implementedMethod.getModifiers()) != Modifier.isStatic(shadowMethod.getModifiers());
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/bytecode/ShadowFoo.java b/v1/src/test/java/com/xtremelabs/robolectric/bytecode/ShadowFoo.java
deleted file mode 100644
index 06e3a6931..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/bytecode/ShadowFoo.java
+++ /dev/null
@@ -1,31 +0,0 @@
-package com.xtremelabs.robolectric.bytecode;
-
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.internal.RealObject;
-
-@Implements(Foo.class)
-public class ShadowFoo extends ShadowWranglerTest.ShadowFooParent {
- @RealObject Foo realFooField;
- Foo realFooInConstructor;
-
- Foo realFooCtor;
-
- String name;
-
- public ShadowFoo(Foo foo) {
- this.realFooCtor = foo;
- }
-
- @Override
- @SuppressWarnings({"UnusedDeclaration"})
- public void __constructor__(String name) {
- super.__constructor__(name);
- this.name = name;
- realFooInConstructor = realFooField;
- }
-
- @SuppressWarnings({"UnusedDeclaration"})
- public String getName() {
- return name;
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/bytecode/ShadowWranglerTest.java b/v1/src/test/java/com/xtremelabs/robolectric/bytecode/ShadowWranglerTest.java
deleted file mode 100644
index 45d4089ed..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/bytecode/ShadowWranglerTest.java
+++ /dev/null
@@ -1,239 +0,0 @@
-package com.xtremelabs.robolectric.bytecode;
-
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithoutTestDefaultsRunner;
-import com.xtremelabs.robolectric.annotation.EnableStrictI18n;
-import com.xtremelabs.robolectric.internal.Implementation;
-import com.xtremelabs.robolectric.internal.Implements;
-import com.xtremelabs.robolectric.internal.Instrument;
-import com.xtremelabs.robolectric.internal.RealObject;
-import org.junit.Before;
-import org.junit.Ignore;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import java.io.IOException;
-import java.io.PrintWriter;
-import java.io.StringWriter;
-
-import static org.hamcrest.CoreMatchers.instanceOf;
-import static org.hamcrest.CoreMatchers.not;
-import static org.hamcrest.core.StringContains.containsString;
-import static org.junit.Assert.*;
-
-@RunWith(WithoutTestDefaultsRunner.class)
-public class ShadowWranglerTest {
- private String name;
-
- @Before
- public void setUp() throws Exception {
- name = "context";
- }
-
- @Test
- public void testConstructorInvocation_WithDefaultConstructorAndNoConstructorDelegateOnShadowClass() throws Exception {
- Robolectric.bindShadowClass(ShadowFoo_WithDefaultConstructorAndNoConstructorDelegate.class);
-
- Foo foo = new Foo(name);
- assertEquals(ShadowFoo_WithDefaultConstructorAndNoConstructorDelegate.class, Robolectric.shadowOf_(foo).getClass());
- }
-
- @Test
- public void testConstructorInvocation() throws Exception {
- Robolectric.bindShadowClass(ShadowFoo.class);
-
- Foo foo = new Foo(name);
- assertSame(name, shadowOf(foo).name);
- assertSame(foo, shadowOf(foo).realFooCtor);
- }
-
- @Test
- public void testRealObjectAnnotatedFieldsAreSetBeforeConstructorIsCalled() throws Exception {
- Robolectric.bindShadowClass(ShadowFoo.class);
-
- Foo foo = new Foo(name);
- assertSame(name, shadowOf(foo).name);
- assertSame(foo, shadowOf(foo).realFooField);
-
- assertSame(foo, shadowOf(foo).realFooInConstructor);
- assertSame(foo, shadowOf(foo).realFooInParentConstructor);
- }
-
- @Test
- public void testMethodDelegation() throws Exception {
- Robolectric.bindShadowClass(ShadowFoo.class);
-
- Foo foo = new Foo(name);
- assertSame(name, foo.getName());
- }
-
- @Test
- public void testEqualsMethodDelegation() throws Exception {
- Robolectric.bindShadowClass(WithEquals.class);
-
- Foo foo1 = new Foo(name);
- Foo foo2 = new Foo(name);
- assertEquals(foo1, foo2);
- }
-
- @Test
- public void testHashCodeMethodDelegation() throws Exception {
- Robolectric.bindShadowClass(WithEquals.class);
-
- Foo foo = new Foo(name);
- assertEquals(42, foo.hashCode());
- }
-
- @Test
- public void testToStringMethodDelegation() throws Exception {
- Robolectric.bindShadowClass(WithToString.class);
-
- Foo foo = new Foo(name);
- assertEquals("the expected string", foo.toString());
- }
-
- @Test
- public void testShadowSelectionSearchesSuperclasses() throws Exception {
- Robolectric.bindShadowClass(ShadowFoo.class);
-
- TextFoo textFoo = new TextFoo(name);
- assertEquals(ShadowFoo.class, Robolectric.shadowOf_(textFoo).getClass());
- }
-
- @Test
- public void shouldUseMostSpecificShadow() throws Exception {
- Robolectric.bindShadowClass(ShadowFoo.class);
- Robolectric.bindShadowClass(ShadowTextFoo.class);
-
- TextFoo textFoo = new TextFoo(name);
- assertThat(shadowOf(textFoo), instanceOf(ShadowTextFoo.class));
- }
-
- @Test
- public void testPrimitiveArrays() throws Exception {
- Class<?> objArrayClass = ShadowWrangler.loadClass("java.lang.Object[]", getClass().getClassLoader());
- assertTrue(objArrayClass.isArray());
- assertEquals(Object.class, objArrayClass.getComponentType());
-
- Class<?> intArrayClass = ShadowWrangler.loadClass("int[]", getClass().getClassLoader());
- assertTrue(intArrayClass.isArray());
- assertEquals(Integer.TYPE, intArrayClass.getComponentType());
- }
-
- @Test
- public void shouldRemoveNoiseFromStackTraces() throws Exception {
- Robolectric.bindShadowClass(ExceptionThrowingShadowFoo.class);
- Foo foo = new Foo(null);
-
- Exception e = null;
- try {
- foo.getName();
- } catch (Exception e1) {
- e = e1;
- }
-
- assertNotNull(e);
- assertEquals(IOException.class, e.getClass());
- assertEquals("fake exception", e.getMessage());
- StringWriter stringWriter = new StringWriter();
- e.printStackTrace(new PrintWriter(stringWriter));
- String stackTrace = stringWriter.getBuffer().toString();
-
- assertThat(stackTrace, containsString("fake exception"));
- assertThat(stackTrace, containsString(ExceptionThrowingShadowFoo.class.getName() + ".getName("));
- assertThat(stackTrace, containsString(Foo.class.getName() + ".getName("));
- assertThat(stackTrace, containsString(ShadowWranglerTest.class.getName() + ".shouldRemoveNoiseFromStackTraces"));
-
- assertThat(stackTrace, not(containsString("sun.reflect")));
- assertThat(stackTrace, not(containsString("java.lang.reflect")));
- assertThat(stackTrace, not(containsString(ShadowWrangler.class.getName() + ".")));
- assertThat(stackTrace, not(containsString(RobolectricInternals.class.getName() + ".")));
- }
-
- @Test(expected=RuntimeException.class)
- @EnableStrictI18n
- public void shouldThrowExceptionOnI18nStrictMode() {
- Robolectric.bindShadowClass(ShadowFooI18n.class);
- Foo foo = new Foo(null);
- foo.getName();
- }
-
- private ShadowFoo shadowOf(Foo foo) {
- return (ShadowFoo) Robolectric.shadowOf_(foo);
- }
-
- private ShadowTextFoo shadowOf(TextFoo foo) {
- return (ShadowTextFoo) Robolectric.shadowOf_(foo);
- }
-
- @Implements(Foo.class)
- public static class WithEquals {
- @Override
- public boolean equals(Object o) {
- return true;
- }
-
-
- @Override
- public int hashCode() {
- return 42;
- }
-
- }
-
- @Implements(Foo.class)
- public static class WithToString {
- @Override
- public String toString() {
- return "the expected string";
- }
- }
-
- @Implements(TextFoo.class)
- public static class ShadowTextFoo {
- }
-
- @Instrument
- public static class TextFoo extends Foo {
- public TextFoo(String s) {
- super(s);
- }
- }
-
- @Implements(Foo.class)
- public static class ShadowFooI18n {
- String name;
-
- public void __constructor__(String name) {
- this.name = name;
- }
-
- @Implementation(i18nSafe=false)
- public String getName() {
- return name;
- }
- }
-
- @Implements(Foo.class)
- public static class ShadowFooParent {
- @RealObject
- private Foo realFoo;
- Foo realFooInParentConstructor;
-
- public void __constructor__(String name) {
- realFooInParentConstructor = realFoo;
- }
- }
-
- @Implements(Foo.class)
- public static class ShadowFoo_WithDefaultConstructorAndNoConstructorDelegate {
- }
-
- @Implements(Foo.class)
- public static class ExceptionThrowingShadowFoo {
- @SuppressWarnings({"UnusedDeclaration"})
- public String getName() throws IOException {
- throw new IOException("fake exception");
- }
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/internal/ClassNameResolverTest.java b/v1/src/test/java/com/xtremelabs/robolectric/internal/ClassNameResolverTest.java
deleted file mode 100644
index 161a5470e..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/internal/ClassNameResolverTest.java
+++ /dev/null
@@ -1,34 +0,0 @@
-package com.xtremelabs.robolectric.internal;
-
-import android.app.Application;
-import com.xtremelabs.robolectric.TestApplication;
-import org.junit.Test;
-
-import static org.junit.Assert.assertEquals;
-
-public class ClassNameResolverTest {
- @Test
- public void shouldResolveClassesBySimpleName() throws Exception {
- assertEquals(TestApplication.class, new ClassNameResolver<Application>("com.xtremelabs.robolectric", "TestApplication").resolve());
- }
-
- @Test
- public void shouldResolveClassesByDottedSimpleName() throws Exception {
- assertEquals(TestApplication.class, new ClassNameResolver<Application>("com.xtremelabs.robolectric", ".TestApplication").resolve());
- }
-
- @Test
- public void shouldResolveClassesByFullyQualifiedName() throws Exception {
- assertEquals(TestApplication.class, new ClassNameResolver<Application>("com.xtremelabs.robolectric", "com.xtremelabs.robolectric.TestApplication").resolve());
- }
-
- @Test
- public void shouldResolveClassesByPartiallyQualifiedName() throws Exception {
- assertEquals(TestApplication.class, new ClassNameResolver<Application>("com.xtremelabs", ".robolectric.TestApplication").resolve());
- }
-
- @Test(expected = RuntimeException.class)
- public void shouldNotResolveClassesByUndottedPartiallyQualifiedNameBecauseAndroidDoesnt() throws Exception {
- new ClassNameResolver<Application>("com.xtremelabs", "robolectric.TestApplication").resolve();
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/matchers/StartedMatcherTest.java b/v1/src/test/java/com/xtremelabs/robolectric/matchers/StartedMatcherTest.java
deleted file mode 100644
index 0b4f5ebd5..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/matchers/StartedMatcherTest.java
+++ /dev/null
@@ -1,93 +0,0 @@
-package com.xtremelabs.robolectric.matchers;
-
-import android.app.Activity;
-import android.app.ActivityGroup;
-import android.app.AliasActivity;
-import android.app.ListActivity;
-import android.content.Context;
-import android.content.Intent;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.hamcrest.Description;
-import org.hamcrest.Matcher;
-import org.hamcrest.StringDescription;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.internal.matchers.TypeSafeMatcher;
-import org.junit.runner.RunWith;
-
-import static com.xtremelabs.robolectric.matchers.StartedMatcher.createIntent;
-import static org.junit.Assert.assertThat;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class StartedMatcherTest {
- private Activity activity;
- private Intent intentWithExtra;
-
- @Before
- public void setUp() throws Exception {
- Robolectric.bindDefaultShadowClasses();
- Robolectric.resetStaticState();
-
- activity = new Activity();
- intentWithExtra = createIntent(AliasActivity.class, "someExtra", "value");
- }
-
- @Test
- public void shouldSayDidntStartAnythingIfNothingWasStarted() throws Exception {
- assertThat(new StartedMatcher(ActivityGroup.class),
- givesFailureMessage((Context) activity, "to start " + createIntent(ActivityGroup.class) + ", but didn't start anything"));
-
- assertThat(new StartedMatcher(ActivityGroup.class, "view"),
- givesFailureMessage((Context) activity, "to start " + createIntent(ActivityGroup.class, "view") + ", but didn't start anything"));
-
- assertThat(new StartedMatcher(intentWithExtra),
- givesFailureMessage((Context) activity, "to start " + intentWithExtra + ", but didn't start anything"));
- }
-
- @Test
- public void shouldSayStartedSomethingIfWrongThingWasStarted() throws Exception {
- Intent actualIntent = createIntent(ListActivity.class, "anotherExtra", "anotherValue");
-
- activity.startActivity(actualIntent);
- assertThat(new StartedMatcher(ActivityGroup.class),
- givesFailureMessage((Context) activity, "to start " + createIntent(ActivityGroup.class) + ", but started " + actualIntent));
-
- activity.startActivity(actualIntent);
- assertThat(new StartedMatcher(ActivityGroup.class, "view"),
- givesFailureMessage((Context) activity, "to start " + createIntent(ActivityGroup.class, "view") + ", but started " + actualIntent));
-
- activity.startActivity(actualIntent);
- assertThat(new StartedMatcher(intentWithExtra),
- givesFailureMessage((Context) activity, "to start " + intentWithExtra + ", but started " + actualIntent));
- }
-
- private <T> Matcher<Matcher<T>> givesFailureMessage(final T actual, final String expectedFailureMessage) {
- return new TypeSafeMatcher<Matcher<T>>() {
- public String message;
-
- @Override
- public boolean matchesSafely(Matcher<T> tMatcher) {
- if (tMatcher.matches(actual)) {
- message = "matcher to fail, but it passed";
- return false;
- }
- StringDescription description = new StringDescription();
- tMatcher.describeTo(description);
- String actualFailureMessage = description.toString();
- if (expectedFailureMessage.equals(actualFailureMessage)) {
- return true;
- } else {
- message = "failure message to be [" + expectedFailureMessage + "] but got [" + actualFailureMessage + "]";
- return false;
- }
- }
-
- @Override
- public void describeTo(Description description) {
- description.appendText(message);
- }
- };
- }
-
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/matchers/StartedServiceMatcherTest.java b/v1/src/test/java/com/xtremelabs/robolectric/matchers/StartedServiceMatcherTest.java
deleted file mode 100644
index 1af11533e..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/matchers/StartedServiceMatcherTest.java
+++ /dev/null
@@ -1,95 +0,0 @@
-package com.xtremelabs.robolectric.matchers;
-
-import android.app.IntentService;
-import android.content.Context;
-import android.content.Intent;
-import android.service.wallpaper.WallpaperService;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.hamcrest.Description;
-import org.hamcrest.Matcher;
-import org.hamcrest.StringDescription;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.internal.matchers.TypeSafeMatcher;
-import org.junit.runner.RunWith;
-import static com.xtremelabs.robolectric.matchers.StartedServiceMatcher.createIntent;
-import static org.junit.Assert.assertThat;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class StartedServiceMatcherTest {
- private WallpaperService service;
- private Intent intentWithExtra;
-
- @Before
- public void setUp() throws Exception {
- Robolectric.bindDefaultShadowClasses();
- Robolectric.resetStaticState();
-
- service = new WallpaperService() {
- @Override
- public Engine onCreateEngine() {
- return null;
- }
- };
- intentWithExtra = createIntent(WallpaperService.class, "someExtra", "value");
- }
-//
- @Test
- public void shouldSayDidntStartAnythingIfNothingWasStarted() throws Exception {
- assertThat(new StartedServiceMatcher(WallpaperService.class),
- givesFailureMessage((Context) service, "to start " + createIntent(WallpaperService.class) + ", but didn't start anything"));
-
- assertThat(new StartedServiceMatcher(WallpaperService.class, "view"),
- givesFailureMessage((Context) service, "to start " + createIntent(WallpaperService.class, "view") + ", but didn't start anything"));
-
- assertThat(new StartedServiceMatcher(intentWithExtra),
- givesFailureMessage((Context) service, "to start " + intentWithExtra + ", but didn't start anything"));
- }
-
- @Test
- public void shouldSayStartedSomethingIfWrongThingWasStarted() throws Exception {
- Intent actualIntent = createIntent(WallpaperService.class, "anotherExtra", "anotherValue");
-
- service.startService(actualIntent);
- assertThat(new StartedServiceMatcher(IntentService.class),
- givesFailureMessage((Context) service, "to start " + createIntent(IntentService.class) + ", but started " + actualIntent));
-
- service.startService(actualIntent);
- assertThat(new StartedServiceMatcher(IntentService.class, "view"),
- givesFailureMessage((Context) service, "to start " + createIntent(IntentService.class, "view") + ", but started " + actualIntent));
-
- service.startService(actualIntent);
- assertThat(new StartedServiceMatcher(intentWithExtra),
- givesFailureMessage((Context) service, "to start " + intentWithExtra + ", but did not get the same extras keys"));
- }
-
- private <T> Matcher<Matcher<T>> givesFailureMessage(final T actual, final String expectedFailureMessage) {
- return new TypeSafeMatcher<Matcher<T>>() {
- public String message;
-
- @Override
- public boolean matchesSafely(Matcher<T> tMatcher) {
- if (tMatcher.matches(actual)) {
- message = "matcher to fail, but it passed";
- return false;
- }
- StringDescription description = new StringDescription();
- tMatcher.describeTo(description);
- String actualFailureMessage = description.toString();
- if (expectedFailureMessage.equals(actualFailureMessage)) {
- return true;
- } else {
- message = "failure message to be [" + expectedFailureMessage + "] but got [" + actualFailureMessage + "]";
- return false;
- }
- }
-
- @Override
- public void describeTo(Description description) {
- description.appendText(message);
- }
- };
- }
-
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/res/AttrResourceLoaderTest.java b/v1/src/test/java/com/xtremelabs/robolectric/res/AttrResourceLoaderTest.java
deleted file mode 100644
index c1b91e75e..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/res/AttrResourceLoaderTest.java
+++ /dev/null
@@ -1,56 +0,0 @@
-package com.xtremelabs.robolectric.res;
-
-import android.content.Context;
-import android.util.AttributeSet;
-import android.widget.ImageView;
-import com.xtremelabs.robolectric.R;
-import com.xtremelabs.robolectric.util.CustomView;
-import org.junit.Before;
-import org.junit.Test;
-
-import static com.xtremelabs.robolectric.util.TestUtil.getSystemResourceDir;
-import static com.xtremelabs.robolectric.util.TestUtil.resourceFile;
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.junit.Assert.assertThat;
-
-public class AttrResourceLoaderTest {
- private AttrResourceLoader attrResourceLoader;
-
- @Before
- public void setUp() throws Exception {
- ResourceExtractor resourceExtractor = new ResourceExtractor();
- resourceExtractor.addLocalRClass(R.class);
- resourceExtractor.addSystemRClass(android.R.class);
- attrResourceLoader = new AttrResourceLoader(resourceExtractor);
- new DocumentLoader(attrResourceLoader).loadResourceXmlDir(resourceFile("res", "values"));
- new DocumentLoader(attrResourceLoader).loadSystemResourceXmlDir(getSystemResourceDir("values"));
- }
-
- @Test
- public void testAttributesAreResolved() throws Exception {
- assertThat(attrResourceLoader.convertValueToEnum(CustomView.class, "xxx", "itemType", "integer"), equalTo("0"));
- assertThat(attrResourceLoader.hasAttributeFor(CustomView.class, "xxx", "itemType"), equalTo(true));
-
- assertThat(attrResourceLoader.convertValueToEnum(CustomView.class, "xxx", "itemType", "string"), equalTo("1"));
- assertThat(attrResourceLoader.hasAttributeFor(CustomView.class, "xxx", "otherItemType"), equalTo(false));
- }
-
- @Test
- public void testAttributesAreResolvedForSystemAttrs() throws Exception {
- String expected = "" + ImageView.ScaleType.FIT_CENTER.ordinal();
- assertThat(attrResourceLoader.convertValueToEnum(ImageView.class, "android", "scaleType", "fitCenter"), equalTo(expected));
- assertThat(attrResourceLoader.hasAttributeFor(ImageView.class, "android", "scaleType"), equalTo(true));
- }
-
- @Test
- public void shouldResolveAttributesForSubClasses() throws Exception {
- assertThat(attrResourceLoader.convertValueToEnum(SubCustomView.class, "xxx", "itemType", "integer"), equalTo("0"));
- assertThat(attrResourceLoader.hasAttributeFor(SubCustomView.class, "xxx", "itemType"), equalTo(true));
- }
-
- private class SubCustomView extends CustomView {
- public SubCustomView(Context context, AttributeSet attrs) {
- super(context, attrs);
- }
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/res/ColorResourceLoaderTest.java b/v1/src/test/java/com/xtremelabs/robolectric/res/ColorResourceLoaderTest.java
deleted file mode 100644
index 60f183212..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/res/ColorResourceLoaderTest.java
+++ /dev/null
@@ -1,75 +0,0 @@
-package com.xtremelabs.robolectric.res;
-
-import android.graphics.Color;
-import com.xtremelabs.robolectric.R;
-import org.junit.Before;
-import org.junit.Test;
-
-import static com.xtremelabs.robolectric.util.TestUtil.getSystemResourceDir;
-import static com.xtremelabs.robolectric.util.TestUtil.resourceFile;
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.junit.Assert.assertThat;
-
-public class ColorResourceLoaderTest {
- private ColorResourceLoader colorResourceLoader;
-
- @Before public void setUp() throws Exception {
- ResourceExtractor resourceExtractor = new ResourceExtractor();
- resourceExtractor.addLocalRClass(R.class);
- resourceExtractor.addSystemRClass(android.R.class);
- colorResourceLoader = new ColorResourceLoader(resourceExtractor);
- new DocumentLoader(colorResourceLoader).loadResourceXmlDir(resourceFile("res", "values"));
- new DocumentLoader(colorResourceLoader).loadSystemResourceXmlDir(getSystemResourceDir("values"));
- }
-
- @Test
- public void shouldHandleNonColorResourcesWithoutCrashing() throws Exception {
- assertThat(colorResourceLoader.getValue(R.drawable.l0_red), equalTo(-0x000001));
- }
-
- @Test
- public void testStringsAreResolved() throws Exception {
- assertThat(colorResourceLoader.getValue(R.color.black), equalTo(0x000000));
- assertThat(colorResourceLoader.getValue(R.color.white), equalTo(0xffffff));
- }
-
- @Test
- public void shouldHandleColorsWithAlpha() throws Exception {
- assertThat(colorResourceLoader.getValue(R.color.clear), equalTo(0x000001));
- }
-
- @Test
- public void shouldHandleColorForwardReferences() throws Exception {
- assertThat(colorResourceLoader.getValue(R.color.foreground), equalTo(0xf5f5f5));
- }
-
- @Test
- public void shouldHandleColorBackwardReferences() throws Exception {
- assertThat(colorResourceLoader.getValue(R.color.background), equalTo(0xf5f5f5));
- }
-
- @Test
- public void shouldLoadColorsWithAlpha() throws Exception {
- assertThat(colorResourceLoader.getValue(R.color.color_with_alpha), equalTo(0x802C76AD));
- }
-
- @Test
- public void shouldReturnAndroidColors() throws Exception {
- assertThat(colorResourceLoader.getValue(android.R.color.black), equalTo(Color.BLACK));
- }
-
- @Test
- public void shouldSupportCarrierDefinedColors() throws Exception {
- assertThat(colorResourceLoader.getValue(android.R.color.background_dark), equalTo(0xFF000000));
- }
-
- @Test
- public void shouldParseAndroidColorReferences() throws Exception {
- assertThat(colorResourceLoader.getValue(R.color.android_namespaced_black), equalTo(Color.BLACK));
- }
-
- @Test
- public void shouldParseSimpleAndroidColorReferences() throws Exception {
- assertThat(colorResourceLoader.getValue(R.color.android_red), equalTo(Color.RED));
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/res/DimenResourceLoaderTest.java b/v1/src/test/java/com/xtremelabs/robolectric/res/DimenResourceLoaderTest.java
deleted file mode 100644
index 1ba3d60b2..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/res/DimenResourceLoaderTest.java
+++ /dev/null
@@ -1,37 +0,0 @@
-package com.xtremelabs.robolectric.res;
-
-import static com.xtremelabs.robolectric.util.TestUtil.resourceFile;
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.junit.Assert.assertThat;
-
-import org.junit.Before;
-import org.junit.Test;
-
-import com.xtremelabs.robolectric.R;
-
-public class DimenResourceLoaderTest {
-
- private DimenResourceLoader dimenResourceLoader;
-
- @Before
- public void setUp() throws Exception {
- ResourceExtractor resourceExtractor = new ResourceExtractor();
- resourceExtractor.addLocalRClass(R.class);
- dimenResourceLoader = new DimenResourceLoader(resourceExtractor);
- new DocumentLoader(dimenResourceLoader)
- .loadResourceXmlDir(resourceFile("res", "values"));
- }
-
- @Test
- public void testDimensionsAreResolved() throws Exception {
- assertThat(dimenResourceLoader.getValue(R.dimen.test_dp_dimen),
- equalTo(8.0f));
- assertThat(dimenResourceLoader.getValue(R.dimen.test_dip_dimen),
- equalTo(20.0f));
- assertThat(dimenResourceLoader.getValue(R.dimen.test_px_dimen),
- equalTo(15.0f));
- assertThat(dimenResourceLoader.getValue(R.dimen.test_sp_dimen),
- equalTo(5.0f));
- }
-
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/res/DrawableResourceLoaderTest.java b/v1/src/test/java/com/xtremelabs/robolectric/res/DrawableResourceLoaderTest.java
deleted file mode 100644
index 4357e55d4..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/res/DrawableResourceLoaderTest.java
+++ /dev/null
@@ -1,120 +0,0 @@
-package com.xtremelabs.robolectric.res;
-
-import android.graphics.drawable.Drawable;
-import android.graphics.drawable.LayerDrawable;
-import android.graphics.drawable.StateListDrawable;
-import com.xtremelabs.robolectric.R;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import com.xtremelabs.robolectric.shadows.ShadowStateListDrawable;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static com.xtremelabs.robolectric.util.TestUtil.getSystemResourceDir;
-import static com.xtremelabs.robolectric.util.TestUtil.resourceFile;
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.CoreMatchers.instanceOf;
-import static org.hamcrest.CoreMatchers.nullValue;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertThat;
-import static org.junit.Assert.assertTrue;
-
-/**
- * DrawableResourceLoaderTest
- */
-@RunWith(WithTestDefaultsRunner.class)
-public class DrawableResourceLoaderTest {
- protected DrawableResourceLoader resourceLoader;
-
- @Before
- public void setup() throws Exception {
- ResourceExtractor extractor = new ResourceExtractor();
- extractor.addLocalRClass(R.class);
- extractor.addSystemRClass(android.R.class);
-
- resourceLoader = new DrawableResourceLoader(extractor, resourceFile("res"));
- DocumentLoader documentLoader = new DocumentLoader(resourceLoader);
-
- documentLoader.loadResourceXmlDir(resourceFile("res", "drawable"));
- documentLoader.loadSystemResourceXmlDir(getSystemResourceDir("drawable"));
- }
-
- @Test
- public void testProcessResourceXml() throws Exception {
- assertTrue("drawable/rainbow", resourceLoader.documents.containsKey("drawable/rainbow"));
- assertEquals("documents.size", 116, resourceLoader.documents.size());
- }
-
- @Test
- public void testIsXml_rainbow() throws Exception {
- assertTrue(resourceLoader.isXml(R.drawable.rainbow));
- }
-
- @Test
- public void testIsXml_shouldWorkWithSystem() throws Exception {
- assertTrue(resourceLoader.isXml(android.R.drawable.ic_popup_sync));
- }
-
- @Test
- public void testIsXml_red() throws Exception {
- boolean result = resourceLoader.isXml(R.drawable.l0_red);
- assertFalse("result", result);
- }
-
- @Test
- public void testGetDrawableIds() {
- int[] expected = { R.drawable.l7_white, R.drawable.l0_red,
- R.drawable.l1_orange, R.drawable.l2_yellow,
- R.drawable.l3_green, R.drawable.l4_blue, R.drawable.l5_indigo,
- R.drawable.l6_violet };
-
- int[] result = resourceLoader.getDrawableIds(R.drawable.rainbow);
- for (int i = 0; i < expected.length; i++) {
- assertEquals("result[" + i + "]", expected[i], result[i]);
- }
- }
-
- @Test
- public void testGetDrawableIds_shouldWorkWithSystem() throws Exception {
- int[] result = resourceLoader.getDrawableIds(android.R.drawable.ic_popup_sync);
- for (int resultItem : result) {
- assertEquals(-1, resultItem);
- }
- }
-
- @Test
- public void testNotXmlDrawable() {
- int[] drawables = { R.drawable.l7_white, R.drawable.l0_red,
- R.drawable.l1_orange, R.drawable.l2_yellow,
- R.drawable.l3_green, R.drawable.l4_blue, R.drawable.l5_indigo,
- R.drawable.l6_violet };
-
- for (int i = 0; i < drawables.length; i++) {
- Drawable drawable = resourceLoader.getXmlDrawable( drawables[i] );
- assertThat( drawable, nullValue() );
- }
- }
-
- @Test
- public void testLayerDrawable() {
- Drawable drawable = resourceLoader.getXmlDrawable( R.drawable.rainbow );
- assertThat( drawable, instanceOf( LayerDrawable.class ) );
- }
-
- @Test
- public void testStateListDrawable() {
- Drawable drawable = resourceLoader.getXmlDrawable( R.drawable.state_drawable );
- assertThat( drawable, instanceOf( StateListDrawable.class ) );
- ShadowStateListDrawable shDrawable = Robolectric.shadowOf( ( StateListDrawable ) drawable );
- assertThat( shDrawable.getResourceIdForState( android.R.attr.state_selected ), equalTo( R.drawable.l0_red ) );
- assertThat( shDrawable.getResourceIdForState( android.R.attr.state_pressed ), equalTo( R.drawable.l1_orange ) );
- assertThat( shDrawable.getResourceIdForState( android.R.attr.state_focused ), equalTo( R.drawable.l2_yellow ) );
- assertThat( shDrawable.getResourceIdForState( android.R.attr.state_checkable ), equalTo( R.drawable.l3_green ) );
- assertThat( shDrawable.getResourceIdForState( android.R.attr.state_checked ), equalTo( R.drawable.l4_blue ) );
- assertThat( shDrawable.getResourceIdForState( android.R.attr.state_enabled ), equalTo( R.drawable.l5_indigo ) );
- assertThat( shDrawable.getResourceIdForState( android.R.attr.state_window_focused ), equalTo( R.drawable.l6_violet ) );
- assertThat( shDrawable.getResourceIdForState( android.R.attr.state_active ), equalTo( R.drawable.l7_white ) );
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/res/IntegerResourceLoaderTest.java b/v1/src/test/java/com/xtremelabs/robolectric/res/IntegerResourceLoaderTest.java
deleted file mode 100644
index 5c683e3d7..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/res/IntegerResourceLoaderTest.java
+++ /dev/null
@@ -1,35 +0,0 @@
-package com.xtremelabs.robolectric.res;
-
-import static com.xtremelabs.robolectric.util.TestUtil.resourceFile;
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.junit.Assert.assertThat;
-
-import org.junit.Before;
-import org.junit.Test;
-
-import com.xtremelabs.robolectric.R;
-
-public class IntegerResourceLoaderTest {
-
- protected IntegerResourceLoader resourceLoader;
-
- @Before
- public void setup() throws Exception {
- ResourceExtractor extractor = new ResourceExtractor();
- extractor.addLocalRClass( R.class );
- extractor.addSystemRClass( android.R.class );
-
- resourceLoader = new IntegerResourceLoader( extractor );
- DocumentLoader documentLoader = new DocumentLoader(resourceLoader);
-
- documentLoader.loadResourceXmlDir(resourceFile("res", "values"));
- }
-
- @Test
- public void testIntegersAreResolved() {
- assertThat( resourceLoader.getValue( R.integer.test_integer1 ), equalTo( 2000 ) );
- assertThat( resourceLoader.getValue( R.integer.test_integer2 ), equalTo( 9 ) );
- assertThat( resourceLoader.getValue( R.integer.test_large_hex), equalTo( 0xFFFF0000 ) );
- }
-
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/res/MenuLoaderTest.java b/v1/src/test/java/com/xtremelabs/robolectric/res/MenuLoaderTest.java
deleted file mode 100644
index 2a702035d..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/res/MenuLoaderTest.java
+++ /dev/null
@@ -1,194 +0,0 @@
-package com.xtremelabs.robolectric.res;
-
-
-import static com.xtremelabs.robolectric.util.TestUtil.getSystemResourceDir;
-import static com.xtremelabs.robolectric.util.TestUtil.resourceFile;
-
-import java.util.ArrayList;
-
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import android.content.ComponentName;
-import android.content.Intent;
-import android.graphics.drawable.Drawable;
-import android.view.KeyEvent;
-import android.view.Menu;
-import android.view.MenuItem;
-import android.view.SubMenu;
-import android.view.ContextMenu.ContextMenuInfo;
-import android.view.MenuItem.OnMenuItemClickListener;
-
-import com.xtremelabs.robolectric.R;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import com.xtremelabs.robolectric.tester.android.view.TestMenuItem;
-import com.xtremelabs.robolectric.util.I18nException;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class MenuLoaderTest {
-
- private MenuLoader menuLoader;
-
- @Before
- public void setUp() throws Exception {
- ResourceExtractor resourceExtractor = new ResourceExtractor();
- resourceExtractor.addLocalRClass(R.class);
- resourceExtractor.addSystemRClass(android.R.class);
-
- StringResourceLoader stringResourceLoader = new StringResourceLoader(resourceExtractor);
- new DocumentLoader(stringResourceLoader).loadResourceXmlDir(resourceFile("res", "values"));
- new DocumentLoader(stringResourceLoader).loadSystemResourceXmlDir(getSystemResourceDir("values"));
-
- menuLoader = new MenuLoader(resourceExtractor, new AttrResourceLoader(resourceExtractor));
- new DocumentLoader(menuLoader).loadResourceXmlDir(resourceFile("res", "menu"));
- }
-
- @After
- public void tearDown() throws Exception {
- }
-
- @Test(expected=I18nException.class)
- public void shouldThrowI18nExceptionOnMenuWithBareStrings() throws Exception {
- Menu testMenu = new TestMenu();
- menuLoader.setStrictI18n(true);
- menuLoader.inflateMenu(Robolectric.application, R.menu.test, testMenu);
- }
-
- public class TestMenu implements Menu {
- @Override
- public MenuItem add(CharSequence title) {
- return null;
- }
-
- @Override
- public MenuItem add(int titleRes) {
- return null;
- }
-
- @Override
- public MenuItem add(int groupId, int itemId, int order,
- CharSequence title) {
- return null;
- }
-
- @Override
- public MenuItem add(int groupId, int itemId, int order, int titleRes) {
- return null;
- }
-
- @Override
- public SubMenu addSubMenu(CharSequence title) {
- return null;
- }
-
- @Override
- public SubMenu addSubMenu(int titleRes) {
- return null;
- }
-
- @Override
- public SubMenu addSubMenu(int groupId, int itemId, int order,
- CharSequence title) {
- return null;
- }
-
- @Override
- public SubMenu addSubMenu(int groupId, int itemId, int order,
- int titleRes) {
- return null;
- }
-
- @Override
- public int addIntentOptions(int groupId, int itemId, int order,
- ComponentName caller, Intent[] specifics, Intent intent,
- int flags, MenuItem[] outSpecificItems) {
- return 0;
- }
-
- @Override
- public void removeItem(int id) {
-
- }
-
- @Override
- public void removeGroup(int groupId) {
-
- }
-
- @Override
- public void clear() {
-
- }
-
- @Override
- public void setGroupCheckable(int group, boolean checkable,
- boolean exclusive) {
-
- }
-
- @Override
- public void setGroupVisible(int group, boolean visible) {
-
- }
-
- @Override
- public void setGroupEnabled(int group, boolean enabled) {
-
- }
-
- @Override
- public boolean hasVisibleItems() {
- return false;
- }
-
- @Override
- public MenuItem findItem(int id) {
- return null;
- }
-
- @Override
- public int size() {
-
- return 0;
- }
-
- @Override
- public MenuItem getItem(int index) {
-
- return null;
- }
-
- @Override
- public void close() {
-
-
- }
-
- @Override
- public boolean performShortcut(int keyCode, KeyEvent event, int flags) {
-
- return false;
- }
-
- @Override
- public boolean isShortcutKey(int keyCode, KeyEvent event) {
-
- return false;
- }
-
- @Override
- public boolean performIdentifierAction(int id, int flags) {
-
- return false;
- }
-
- @Override
- public void setQwertyMode(boolean isQwerty) {
-
-
- }
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/res/MenuResourceLoaderTest.java b/v1/src/test/java/com/xtremelabs/robolectric/res/MenuResourceLoaderTest.java
deleted file mode 100644
index 95aafdb59..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/res/MenuResourceLoaderTest.java
+++ /dev/null
@@ -1,39 +0,0 @@
-package com.xtremelabs.robolectric.res;
-
-
-import static com.xtremelabs.robolectric.util.TestUtil.resourceFile;
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.junit.Assert.*;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import android.view.MenuItem;
-
-import com.xtremelabs.robolectric.R;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import com.xtremelabs.robolectric.tester.android.view.TestMenu;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class MenuResourceLoaderTest {
-
- @Test
- public void shouldInflateComplexMenu() throws Exception {
- ResourceLoader resourceLoader = new ResourceLoader(10, R.class, resourceFile("res"), resourceFile("menu"));
- TestMenu testMenu = new TestMenu();
- resourceLoader.inflateMenu(Robolectric.application, R.menu.test_withchilds, testMenu);
- assertThat(testMenu.size(), equalTo(4));
- }
-
- @Test
- public void shouldParseSubItemCorrectly() throws Exception {
- ResourceLoader resourceLoader = new ResourceLoader(10, R.class, resourceFile("res"), resourceFile("menu"));
- TestMenu testMenu = new TestMenu();
- resourceLoader.inflateMenu(Robolectric.application, R.menu.test_withchilds, testMenu);
- MenuItem mi = testMenu.findItem(R.id.test_submenu_1);
- assertTrue(mi.hasSubMenu());
- assertThat(mi.getSubMenu().size(), equalTo(2) );
- assertThat(mi.getSubMenu().getItem(1).getTitle() + "", equalTo("Test menu item 3") );
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/res/PluralResourceLoaderTest.java b/v1/src/test/java/com/xtremelabs/robolectric/res/PluralResourceLoaderTest.java
deleted file mode 100644
index 739e89074..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/res/PluralResourceLoaderTest.java
+++ /dev/null
@@ -1,33 +0,0 @@
-package com.xtremelabs.robolectric.res;
-
-import static com.xtremelabs.robolectric.util.TestUtil.resourceFile;
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.junit.Assert.assertThat;
-
-import com.xtremelabs.robolectric.R;
-import org.junit.Before;
-import org.junit.Test;
-
-public class PluralResourceLoaderTest {
- private PluralResourceLoader pluralResourceLoader;
-
- @Before
- public void setUp() throws Exception {
- ResourceExtractor resourceExtractor = new ResourceExtractor();
- resourceExtractor.addLocalRClass(R.class);
-
- StringResourceLoader stringResourceLoader = new StringResourceLoader(resourceExtractor);
- pluralResourceLoader = new PluralResourceLoader(resourceExtractor, stringResourceLoader);
-
- new DocumentLoader(stringResourceLoader).loadResourceXmlDir(resourceFile("res", "values"));
- new DocumentLoader(pluralResourceLoader).loadResourceXmlDir(resourceFile("res", "values"));
- }
-
- @Test
- public void testPluralsAreResolved() throws Exception {
- assertThat(pluralResourceLoader.getValue(R.plurals.beer, 0), equalTo("Howdy"));
- assertThat(pluralResourceLoader.getValue(R.plurals.beer, 1), equalTo("One beer"));
- assertThat(pluralResourceLoader.getValue(R.plurals.beer, 2), equalTo("Two beers"));
- assertThat(pluralResourceLoader.getValue(R.plurals.beer, 3), equalTo("%d beers, yay!"));
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/res/PreferenceLoaderTest.java b/v1/src/test/java/com/xtremelabs/robolectric/res/PreferenceLoaderTest.java
deleted file mode 100644
index e4da35902..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/res/PreferenceLoaderTest.java
+++ /dev/null
@@ -1,80 +0,0 @@
-package com.xtremelabs.robolectric.res;
-
-import static com.xtremelabs.robolectric.util.TestUtil.resourceFile;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import android.app.Activity;
-import android.preference.CheckBoxPreference;
-import android.preference.EditTextPreference;
-import android.preference.ListPreference;
-import android.preference.Preference;
-import android.preference.PreferenceCategory;
-import android.preference.PreferenceScreen;
-import android.preference.RingtonePreference;
-
-import com.xtremelabs.robolectric.R;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import com.xtremelabs.robolectric.util.I18nException;
-
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.CoreMatchers.instanceOf;
-import static org.junit.Assert.assertThat;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class PreferenceLoaderTest {
- private PreferenceLoader prefLoader;
-
- @Before
- public void setUp() throws Exception {
- Robolectric.bindDefaultShadowClasses();
-
- ResourceExtractor resourceExtractor = new ResourceExtractor();
- resourceExtractor.addLocalRClass(R.class);
- StringResourceLoader stringResourceLoader = new StringResourceLoader(resourceExtractor);
- new DocumentLoader(stringResourceLoader).loadResourceXmlDir(resourceFile("res", "values"));
- prefLoader = new PreferenceLoader(resourceExtractor);
- new DocumentLoader(prefLoader).loadResourceXmlDir(resourceFile("res", "xml"));
- }
-
- @Test
- public void shouldCreateCorrectClasses() {
- PreferenceScreen screen = prefLoader.inflatePreferences(new Activity(), "xml/preferences");
- assertThatScreenMatchesExpected(screen);
- }
-
- @Test
- public void shouldLoadByResourceId() {
- PreferenceScreen screen = prefLoader.inflatePreferences(new Activity(), R.xml.preferences);
- assertThatScreenMatchesExpected(screen);
- }
-
- @Test(expected=I18nException.class)
- public void shouldThrowI18nExceptionOnPrefsWithBareStrings() throws Exception {
- ResourceExtractor resourceExtractor = new ResourceExtractor();
- resourceExtractor.addLocalRClass(R.class);
- StringResourceLoader stringResourceLoader = new StringResourceLoader(resourceExtractor);
- new DocumentLoader(stringResourceLoader).loadResourceXmlDir(resourceFile("res", "values"));
- prefLoader = new PreferenceLoader(resourceExtractor);
- prefLoader.setStrictI18n(true);
- new DocumentLoader(prefLoader).loadResourceXmlDir(resourceFile("res", "xml"));
-
- prefLoader.inflatePreferences(Robolectric.application, R.xml.preferences);
- }
-
- protected void assertThatScreenMatchesExpected(PreferenceScreen screen) {
- assertThat(screen.getPreferenceCount(), equalTo(6));
-
- assertThat(screen.getPreference(0), instanceOf(PreferenceCategory.class));
- assertThat(((PreferenceCategory)screen.getPreference(0)).getPreference(0), instanceOf(Preference.class));
-
- assertThat(screen.getPreference(1), instanceOf(CheckBoxPreference.class));
- assertThat(screen.getPreference(2), instanceOf(EditTextPreference.class));
- assertThat(screen.getPreference(3), instanceOf(ListPreference.class));
- assertThat(screen.getPreference(4), instanceOf(Preference.class));
- assertThat(screen.getPreference(5), instanceOf(RingtonePreference.class));
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/res/RawResourceLoaderTest.java b/v1/src/test/java/com/xtremelabs/robolectric/res/RawResourceLoaderTest.java
deleted file mode 100644
index a0904074c..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/res/RawResourceLoaderTest.java
+++ /dev/null
@@ -1,57 +0,0 @@
-package com.xtremelabs.robolectric.res;
-
-import com.xtremelabs.robolectric.R;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.Reader;
-import java.io.StringWriter;
-import java.io.Writer;
-
-import static com.xtremelabs.robolectric.util.TestUtil.resourceFile;
-import static org.junit.Assert.assertEquals;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class RawResourceLoaderTest {
-
- private RawResourceLoader rawResourceLoader;
-
- @Before public void setUp() throws Exception {
- ResourceExtractor resourceExtractor = new ResourceExtractor();
- resourceExtractor.addLocalRClass(R.class);
- rawResourceLoader = new RawResourceLoader(resourceExtractor, resourceFile("res"));
- }
-
- @Test
- public void shouldReturnRawResourcesWithExtensions() throws Exception {
- InputStream is = rawResourceLoader.getValue(R.raw.raw_resource);
- assertEquals("raw txt file contents", readString(is));
- }
-
- @Test
- public void shouldReturnRawResourcesWithoutExtensions() throws Exception {
- InputStream is = rawResourceLoader.getValue(R.raw.raw_no_ext);
- assertEquals("no ext file contents", readString(is));
- }
-
- private static String readString(InputStream is) throws IOException {
- Writer writer = new StringWriter();
- char[] buffer = new char[1024];
- try {
- Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
- int n;
- while ((n = reader.read(buffer)) != -1) {
- writer.write(buffer, 0, n);
- }
- } finally {
- is.close();
- }
- return writer.toString();
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/res/ResourceExtractorTest.java b/v1/src/test/java/com/xtremelabs/robolectric/res/ResourceExtractorTest.java
deleted file mode 100644
index 7041efa5e..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/res/ResourceExtractorTest.java
+++ /dev/null
@@ -1,36 +0,0 @@
-package com.xtremelabs.robolectric.res;
-
-import com.xtremelabs.robolectric.R;
-import org.hamcrest.CoreMatchers;
-import org.junit.Before;
-import org.junit.Test;
-
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.junit.Assert.assertThat;
-
-public class ResourceExtractorTest {
- private ResourceExtractor resourceExtractor;
-
- @Before
- public void setUp() throws Exception {
- resourceExtractor = new ResourceExtractor();
- resourceExtractor.addLocalRClass(R.class);
- resourceExtractor.addSystemRClass(android.R.class);
- }
-
- @Test
- public void shouldHandleStyleable() throws Exception {
- assertThat(resourceExtractor.getLocalResourceId("id/textStyle"), equalTo(R.id.textStyle));
- assertThat(resourceExtractor.getLocalResourceId("styleable/TitleBar_textStyle"), CoreMatchers.<Object>nullValue());
- }
-
- @Test
- public void shouldPrefixAllSystemResourcesWithAndroid() throws Exception {
- assertThat(resourceExtractor.getResourceId("android:id/text1"), equalTo(android.R.id.text1));
- }
-
- @Test
- public void shouldHandleNull() throws Exception {
- assertThat(resourceExtractor.getLocalResourceId("@null"), equalTo(0));
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/res/ResourceLoaderTest.java b/v1/src/test/java/com/xtremelabs/robolectric/res/ResourceLoaderTest.java
deleted file mode 100644
index 917b2c228..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/res/ResourceLoaderTest.java
+++ /dev/null
@@ -1,106 +0,0 @@
-package com.xtremelabs.robolectric.res;
-
-
-import android.view.ViewGroup;
-import android.widget.FrameLayout;
-import android.widget.TextView;
-import com.xtremelabs.robolectric.R;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import com.xtremelabs.robolectric.util.I18nException;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import java.io.File;
-
-import static com.xtremelabs.robolectric.util.TestUtil.resourceFile;
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.junit.Assert.*;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class ResourceLoaderTest {
- @Test
- public void shouldUseFileSystemSeparatorWhenEvaluatingLayoutDirectories() throws Exception {
- assertTrue(ResourceLoader.isLayoutDirectory(File.separator + "layout"));
- }
-
- @Test
- public void shouldLoadSystemResources() throws Exception {
- ResourceLoader resourceLoader = new ResourceLoader(10, R.class, resourceFile("res"), resourceFile("assets"));
- String stringValue = resourceLoader.getStringValue(android.R.string.copy);
- assertEquals("Copy", stringValue);
-
- ViewLoader.ViewNode node = resourceLoader.getLayoutViewNode("android:layout/simple_spinner_item");
- assertNotNull(node);
- }
-
- @Test
- public void shouldLoadLocalResources() throws Exception {
- ResourceLoader resourceLoader = new ResourceLoader(10, R.class, resourceFile("res"), resourceFile("assets"));
- String stringValue = resourceLoader.getStringValue(R.string.copy);
- assertEquals("Local Copy", stringValue);
- }
-
- @Test(expected=I18nException.class)
- public void shouldThrowExceptionOnI18nStrictModeInflateView() throws Exception {
- ResourceLoader resourceLoader = new ResourceLoader(10, R.class, resourceFile("res"), resourceFile("layout"));
- resourceLoader.setStrictI18n(true);
- ViewGroup vg = new FrameLayout(Robolectric.application);
- resourceLoader.inflateView(Robolectric.application, R.layout.text_views, vg);
- }
-
- @Test(expected=I18nException.class)
- public void shouldThrowExceptionOnI18nStrictModeInflateMenu() throws Exception {
- ResourceLoader resourceLoader = new ResourceLoader(10, R.class, resourceFile("res"), resourceFile("menu"));
- resourceLoader.setStrictI18n(true);
- resourceLoader.inflateMenu(Robolectric.application, R.menu.test, null);
- }
-
- @Test(expected=I18nException.class)
- public void shouldThrowExceptionOnI18nStrictModeInflatePreferences() throws Exception {
- ResourceLoader resourceLoader = new ResourceLoader(10, R.class, resourceFile("res"), resourceFile("xml"));
- resourceLoader.setStrictI18n(true);
- resourceLoader.inflatePreferences(Robolectric.application, R.xml.preferences);
- }
-
- @Test
- public void testChoosesLayoutBasedOnSearchPath_respectsOrderOfPath() throws Exception {
- ResourceLoader resourceLoader = new ResourceLoader(10, R.class, resourceFile("res"), resourceFile("layout"));
- resourceLoader.setLayoutQualifierSearchPath("does-not-exist", "land", "xlarge");
- ViewGroup viewGroup = new FrameLayout(Robolectric.application);
- ViewGroup view = (ViewGroup) resourceLoader.inflateView(Robolectric.application, R.layout.different_screen_sizes, viewGroup);
- TextView textView = (TextView) view.findViewById(android.R.id.text1);
- assertThat(textView.getText().toString(), equalTo("land"));
- }
-
- @Test
- public void checkForPollution1() throws Exception {
- checkForPollutionHelper();
- }
-
- @Test
- public void checkForPollution2() throws Exception {
- checkForPollutionHelper();
- }
-
- private void checkForPollutionHelper() {
- ResourceLoader resourceLoader = Robolectric.getShadowApplication().getResourceLoader();
- ViewGroup viewGroup = new FrameLayout(Robolectric.application);
- ViewGroup view = (ViewGroup) resourceLoader.inflateView(Robolectric.application, R.layout.different_screen_sizes, viewGroup);
- TextView textView = (TextView) view.findViewById(android.R.id.text1);
- assertThat(textView.getText().toString(), equalTo("default"));
- resourceLoader.setLayoutQualifierSearchPath("land"); // testing if this pollutes the other test
- }
-
- @Test
- public void shouldIdentifyNinePatchDrawables() {
- ResourceLoader resourceLoader = Robolectric.getShadowApplication().getResourceLoader();
-
- assertThat(resourceLoader.isNinePatchDrawable(R.drawable.nine_patch_drawable), equalTo(true));
- assertThat(resourceLoader.isNinePatchDrawable(R.drawable.l2_yellow), equalTo(false));
- assertThat(resourceLoader.isNinePatchDrawable(R.drawable.state_drawable), equalTo(false));
- assertThat(resourceLoader.isNinePatchDrawable(R.drawable.animation_list), equalTo(false));
- assertThat(resourceLoader.isNinePatchDrawable(0), equalTo(false));
- assertThat(resourceLoader.isNinePatchDrawable(-1), equalTo(false));
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/res/RobolectricPackageManagerTest.java b/v1/src/test/java/com/xtremelabs/robolectric/res/RobolectricPackageManagerTest.java
deleted file mode 100644
index 1a7678309..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/res/RobolectricPackageManagerTest.java
+++ /dev/null
@@ -1,174 +0,0 @@
-package com.xtremelabs.robolectric.res;
-
-import static org.hamcrest.CoreMatchers.*;
-import static org.junit.Assert.assertThat;
-
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import android.content.ComponentName;
-import android.content.Intent;
-import android.content.pm.ApplicationInfo;
-import android.content.pm.PackageInfo;
-import android.content.pm.PackageManager;
-import android.content.pm.ResolveInfo;
-import android.graphics.drawable.BitmapDrawable;
-import android.graphics.drawable.Drawable;
-
-import java.util.List;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class RobolectricPackageManagerTest {
-
- private static final String TEST_PACKAGE_NAME = "com.some.other.package";
- private static final String TEST_PACKAGE_LABEL = "My Little App";
-
- RobolectricPackageManager rpm;
-
- @Before
- public void setUp() throws Exception {
- rpm = (RobolectricPackageManager) Robolectric.application.getPackageManager();
- }
-
- @After
- public void tearDown() throws Exception {
- }
-
- @Test
- public void getApplicationInfo__ThisApplication() throws Exception {
- ApplicationInfo info = rpm.getApplicationInfo(Robolectric.application.getPackageName(), 0);
- assertThat(info, notNullValue());
- assertThat(info.packageName, equalTo(Robolectric.application.getPackageName()));
- }
-
- @Test
- public void getApplicationInfo__OtherApplication() throws Exception {
- PackageInfo packageInfo = new PackageInfo();
- packageInfo.packageName = TEST_PACKAGE_NAME;
- packageInfo.applicationInfo = new ApplicationInfo();
- packageInfo.applicationInfo.packageName = TEST_PACKAGE_NAME;
- packageInfo.applicationInfo.name = TEST_PACKAGE_LABEL;
- rpm.addPackage(packageInfo);
-
- ApplicationInfo info = rpm.getApplicationInfo(TEST_PACKAGE_NAME, 0);
- assertThat(info, notNullValue());
- assertThat(info.packageName, equalTo(TEST_PACKAGE_NAME));
- assertThat(rpm.getApplicationLabel(info).toString(), equalTo(TEST_PACKAGE_LABEL));
- }
-
- @Test
- public void queryIntentActivities__EmptyResult() throws Exception {
- Intent i = new Intent(Intent.ACTION_MAIN, null);
- i.addCategory(Intent.CATEGORY_LAUNCHER);
-
- List<ResolveInfo> activities = rpm.queryIntentActivities(i, 0);
- assertThat(activities, notNullValue()); // empty list, not null
- assertThat(activities.size(), equalTo(0));
- }
-
- @Test
- public void queryIntentActivities__Match() throws Exception {
- Intent i = new Intent(Intent.ACTION_MAIN, null);
- i.addCategory(Intent.CATEGORY_LAUNCHER);
-
- ResolveInfo info = new ResolveInfo();
- info.nonLocalizedLabel = TEST_PACKAGE_LABEL;
-
- rpm.addResolveInfoForIntent(i, info);
-
- List<ResolveInfo> activities = rpm.queryIntentActivities(i, 0);
- assertThat(activities, notNullValue());
- assertThat(activities.size(), equalTo(1));
- assertThat(activities.get(0).nonLocalizedLabel.toString(), equalTo(TEST_PACKAGE_LABEL));
- }
-
- @Test
- public void queryBroadcastReceivers__EmptyResult() throws Exception {
- Intent i = new Intent(Intent.ACTION_MAIN, null);
- i.addCategory(Intent.CATEGORY_LAUNCHER);
-
- List<ResolveInfo> broadCastReceivers = rpm.queryBroadcastReceivers(i, 0);
- assertThat(broadCastReceivers.size(), equalTo(0));
- }
-
- @Test
- public void queryBroadcastReceivers__Match() throws Exception {
- Intent i = new Intent(Intent.ACTION_MAIN, null);
-
- ResolveInfo info = new ResolveInfo();
- info.nonLocalizedLabel = TEST_PACKAGE_LABEL;
-
- rpm.addResolveInfoForIntent(i, info);
-
- List<ResolveInfo> broadCastReceivers = rpm.queryBroadcastReceivers(i, 0);
- assertThat(broadCastReceivers.size(), equalTo(1));
- assertThat(broadCastReceivers.get(0).nonLocalizedLabel.toString(),
- equalTo(TEST_PACKAGE_LABEL));
- }
-
- @Test
- public void resolveActivity__Match() throws Exception {
- Intent i = new Intent(Intent.ACTION_MAIN, null).addCategory(Intent.CATEGORY_LAUNCHER);
- ResolveInfo info = new ResolveInfo();
- info.nonLocalizedLabel = TEST_PACKAGE_LABEL;
- rpm.addResolveInfoForIntent(i, info);
-
- assertThat(rpm.resolveActivity(i, 0), sameInstance(info));
- }
-
- @Test
- public void resolveActivity__NoMatch() throws Exception {
- Intent i = new Intent();
- i.setComponent(new ComponentName("foo.bar", "No Activity"));
- assertThat(rpm.resolveActivity(i, 0), nullValue());
- }
-
- @Test
- public void resolveService__Match() throws Exception {
- Intent i = new Intent(Intent.ACTION_MAIN, null);
- i.addCategory(Intent.CATEGORY_LAUNCHER);
-
- ResolveInfo info = new ResolveInfo();
- info.nonLocalizedLabel = TEST_PACKAGE_LABEL;
- rpm.addResolveInfoForIntent(i, info);
-
- assertThat(rpm.resolveService(i, 0), sameInstance(info));
- }
-
- @Test
- public void resolveService__NoMatch() throws Exception {
- Intent i = new Intent();
- i.setComponent(new ComponentName("foo.bar", "No Activity"));
- assertThat(rpm.resolveService(i, 0), nullValue());
- }
-
- @Test
- public void queryActivityIcons__Match() throws Exception {
- Intent i = rpm.getLaunchIntentForPackage(TEST_PACKAGE_NAME);
- Drawable d = new BitmapDrawable();
-
- rpm.addActivityIcon(i, d);
-
- assertThat(rpm.getActivityIcon(i), sameInstance(d));
- assertThat(rpm.getActivityIcon(i.getComponent()), sameInstance(d));
- }
-
- @Test
- public void hasSystemFeature() throws Exception {
- // uninitialized
- assertThat(rpm.hasSystemFeature(PackageManager.FEATURE_CAMERA), equalTo(false));
-
- // positive
- rpm.setSystemFeature(PackageManager.FEATURE_CAMERA, true);
- assertThat(rpm.hasSystemFeature(PackageManager.FEATURE_CAMERA), equalTo(true));
-
- // negative
- rpm.setSystemFeature(PackageManager.FEATURE_CAMERA, false);
- assertThat(rpm.hasSystemFeature(PackageManager.FEATURE_CAMERA), equalTo(false));
- }
-
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/res/StringArrayResourceLoaderTest.java b/v1/src/test/java/com/xtremelabs/robolectric/res/StringArrayResourceLoaderTest.java
deleted file mode 100644
index 065d7a334..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/res/StringArrayResourceLoaderTest.java
+++ /dev/null
@@ -1,50 +0,0 @@
-package com.xtremelabs.robolectric.res;
-
-import com.xtremelabs.robolectric.R;
-import org.junit.Before;
-import org.junit.Test;
-
-import java.io.File;
-import java.util.Arrays;
-
-import static com.xtremelabs.robolectric.util.TestUtil.getSystemResourceDir;
-import static com.xtremelabs.robolectric.util.TestUtil.resourceFile;
-import static org.hamcrest.core.IsCollectionContaining.hasItems;
-import static org.junit.Assert.assertThat;
-
-public class StringArrayResourceLoaderTest {
- private StringArrayResourceLoader stringArrayResourceLoader;
-
- @Before public void setUp() throws Exception {
- ResourceExtractor resourceExtractor = new ResourceExtractor();
- resourceExtractor.addLocalRClass(R.class);
- resourceExtractor.addSystemRClass(android.R.class);
-
- File resourceXmlDir = resourceFile("res", "values");
- File systemResourceXmlDir = getSystemResourceDir("values");
-
- StringResourceLoader stringResourceLoader = new StringResourceLoader(resourceExtractor);
- new DocumentLoader(stringResourceLoader).loadResourceXmlDir(resourceXmlDir);
- new DocumentLoader(stringResourceLoader).loadSystemResourceXmlDir(systemResourceXmlDir);
-
- stringArrayResourceLoader = new StringArrayResourceLoader(resourceExtractor, stringResourceLoader);
- new DocumentLoader(stringArrayResourceLoader).loadResourceXmlDir(resourceXmlDir);
- new DocumentLoader(stringArrayResourceLoader).loadSystemResourceXmlDir(systemResourceXmlDir);
- }
-
- @Test
- public void testStringsAreResolved() throws Exception {
- assertThat(Arrays.asList(stringArrayResourceLoader.getArrayValue(R.array.items)), hasItems("foo", "bar"));
- }
-
- @Test
- public void testStringsAreWithReferences() throws Exception {
- assertThat(Arrays.asList(stringArrayResourceLoader.getArrayValue(R.array.greetings)), hasItems("hola", "Hello"));
- }
-
- @Test
- public void shouldAddAndroidToSystemStringArrayName() throws Exception {
- assertThat(Arrays.asList(stringArrayResourceLoader.getArrayValue(android.R.array.emailAddressTypes)), hasItems("Home", "Work", "Other", "Custom"));
- assertThat(Arrays.asList(stringArrayResourceLoader.getArrayValue(R.array.emailAddressTypes)), hasItems("Doggy", "Catty"));
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/res/StringResourceLoaderTest.java b/v1/src/test/java/com/xtremelabs/robolectric/res/StringResourceLoaderTest.java
deleted file mode 100644
index ba86ad8ff..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/res/StringResourceLoaderTest.java
+++ /dev/null
@@ -1,36 +0,0 @@
-package com.xtremelabs.robolectric.res;
-
-import com.xtremelabs.robolectric.R;
-import org.junit.Before;
-import org.junit.Test;
-
-import static com.xtremelabs.robolectric.util.TestUtil.resourceFile;
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.junit.Assert.assertThat;
-
-public class StringResourceLoaderTest {
- private StringResourceLoader stringResourceLoader;
-
- @Before public void setUp() throws Exception {
- ResourceExtractor resourceExtractor = new ResourceExtractor();
- resourceExtractor.addLocalRClass(R.class);
- stringResourceLoader = new StringResourceLoader(resourceExtractor);
- new DocumentLoader(stringResourceLoader).loadResourceXmlDir(resourceFile("res", "values"));
- }
-
- @Test
- public void testStringsAreResolved() throws Exception {
- assertThat(stringResourceLoader.getValue(R.string.hello), equalTo("Hello"));
- assertThat(stringResourceLoader.getValue(R.string.howdy), equalTo("Howdy"));
- }
-
- @Test
- public void testHtmlTagsAreRemovedFromStrings() throws Exception {
- assertThat(stringResourceLoader.getValue(R.string.some_html), equalTo("Hello, world"));
- }
-
- @Test
- public void shouldResolveStringReferences() throws Exception {
- assertThat(stringResourceLoader.getValue(R.string.greeting), equalTo("Howdy"));
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/res/TestAttributeSetTest.java b/v1/src/test/java/com/xtremelabs/robolectric/res/TestAttributeSetTest.java
deleted file mode 100644
index 873acae53..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/res/TestAttributeSetTest.java
+++ /dev/null
@@ -1,148 +0,0 @@
-package com.xtremelabs.robolectric.res;
-
-import android.view.View;
-import com.xtremelabs.robolectric.R;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import com.xtremelabs.robolectric.tester.android.util.TestAttributeSet;
-import com.xtremelabs.robolectric.util.CustomView;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import java.util.HashMap;
-
-import static com.xtremelabs.robolectric.util.TestUtil.resourceFile;
-import static junit.framework.Assert.assertEquals;
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.MatcherAssert.assertThat;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class TestAttributeSetTest {
- private HashMap<String, String> attributes;
- private ResourceExtractor resourceExtractor;
-
- @Before
- public void setUp() throws Exception {
- attributes = new HashMap<String, String>();
-
- resourceExtractor = new ResourceExtractor();
- resourceExtractor.addLocalRClass(R.class);
- resourceExtractor.addSystemRClass(android.R.class);
- }
-
- @Test
- public void getSystemAttributeResourceValue_shouldReturnTheResourceValue() throws Exception {
- attributes.put("android:id", "@android:id/text1");
- TestAttributeSet testAttributeSet = new TestAttributeSet(attributes, resourceExtractor, null, null, false);
- assertThat(testAttributeSet.getAttributeResourceValue("android", "id", 0), equalTo(android.R.id.text1));
- }
-
- @Test
- public void getSystemAttributeResourceValue_shouldNotReturnTheResourceValueIfNameSpaceDoesNotMatch() throws Exception {
- attributes.put("id", "@id/text1");
- TestAttributeSet testAttributeSet = new TestAttributeSet(attributes, resourceExtractor, null, null, false);
- assertEquals(0, testAttributeSet.getAttributeResourceValue("android", "id", 0));
- }
-
- @Test
- public void getSystemAttributeResourceValue_shouldReturnDefaultValueForNullResourceId() throws Exception {
- attributes.put("id", "@null");
- TestAttributeSet testAttributeSet = new TestAttributeSet(attributes, resourceExtractor, null, null, false);
- assertEquals(0, testAttributeSet.getAttributeResourceValue("com.some.namespace", "id", 0));
- }
-
- @Test
- public void shouldCopeWithDefiningSystemIds() throws Exception {
- attributes.put("android:id", "@+id/text1");
-
- TestAttributeSet testAttributeSet = new TestAttributeSet(attributes, resourceExtractor, null, null, true);
- assertThat(testAttributeSet.getAttributeResourceValue("android", "id", 0), equalTo(android.R.id.text1));
- }
-
- @Test
- public void shouldCopeWithDefiningLocalIds() throws Exception {
- attributes.put("android:id", "@+id/text1");
-
- TestAttributeSet testAttributeSet = new TestAttributeSet(attributes, resourceExtractor, null, null, false);
- assertThat(testAttributeSet.getAttributeResourceValue("android", "id", 0), equalTo(R.id.text1));
- }
-
- @Test
- public void getAttributeResourceValue_shouldReturnTheResourceValue() throws Exception {
- attributes.put("message", "@string/howdy");
-
- TestAttributeSet testAttributeSet = new TestAttributeSet(attributes, resourceExtractor, null, null, false);
- assertThat(testAttributeSet.getAttributeResourceValue("com.some.namespace", "message", 0), equalTo(R.string.howdy));
- }
-
- @Test
- public void getAttributeResourceValue_withNamespace_shouldReturnTheResourceValue() throws Exception {
- attributes.put("message", "@string/howdy");
-
- TestAttributeSet testAttributeSet = new TestAttributeSet(attributes, resourceExtractor, null, null, false);
- assertThat(testAttributeSet.getAttributeResourceValue("com.some.namespace", "message", 0), equalTo(R.string.howdy));
- }
-
- @Test
- public void getAttributeResourceValue_shouldReturnDefaultValueWhenNotInAttributeSet() throws Exception {
- TestAttributeSet testAttributeSet = new TestAttributeSet(attributes, resourceExtractor, null, null, false);
- assertThat(testAttributeSet.getAttributeResourceValue("com.some.namespace", "message", -1), equalTo(-1));
- }
-
- @Test
- public void getAttributeBooleanValue_shouldGetBooleanValuesFromAttributes() throws Exception {
- attributes.put("isSugary", "true");
-
- TestAttributeSet testAttributeSet = new TestAttributeSet(attributes, null, null, null, false);
- assertThat(testAttributeSet.getAttributeBooleanValue("com.some.namespace", "isSugary", false), equalTo(true));
- }
-
- @Test
- public void getAttributeBooleanValue_withNamespace_shouldGetBooleanValuesFromAttributes() throws Exception {
- attributes.put("xxx:isSugary", "true");
-
- TestAttributeSet testAttributeSet = new TestAttributeSet(attributes, null, null, null, false);
- assertThat(testAttributeSet.getAttributeBooleanValue("com.some.namespace", "isSugary", false), equalTo(true));
- }
-
- @Test
- public void getAttributeBooleanValue_shouldReturnDefaultBooleanValueWhenNotInAttributeSet() throws Exception {
- TestAttributeSet testAttributeSet = new TestAttributeSet(attributes, null, null, null, false);
- assertThat(testAttributeSet.getAttributeBooleanValue("com.some.namespace", "isSugary", true), equalTo(true));
- }
-
- @Test
- public void getAttributeValue_shouldReturnValueFromAttribute() throws Exception {
- attributes.put("isSugary", "oh heck yeah");
-
- TestAttributeSet testAttributeSet = new TestAttributeSet(attributes, null, null, null, false);
- assertThat(testAttributeSet.getAttributeValue("com.some.namespace", "isSugary"), equalTo("oh heck yeah"));
- }
-
- @Test
- public void getAttributeIntValue_shouldReturnValueFromAttribute() throws Exception {
- attributes.put("sugarinessPercent", "100");
-
- AttrResourceLoader resourceLoader = new AttrResourceLoader(resourceExtractor);
- TestAttributeSet testAttributeSet = new TestAttributeSet(attributes, null, resourceLoader, View.class, false);
- assertThat(testAttributeSet.getAttributeIntValue("some namespace", "sugarinessPercent", 0), equalTo(100));
- }
-
- @Test
- public void getAttributeIntValue_shouldReturnEnumValuesForEnumAttributes() throws Exception {
- attributes.put("itemType", "string");
-
- AttrResourceLoader attrResourceLoader = new AttrResourceLoader(resourceExtractor);
- new DocumentLoader(attrResourceLoader).loadResourceXmlDir(resourceFile("res", "values"));
- TestAttributeSet testAttributeSet = new TestAttributeSet(attributes, null, attrResourceLoader, CustomView.class, false);
- assertThat(testAttributeSet.getAttributeIntValue("some namespace", "itemType", 0), equalTo(1));
- }
-
- @Test
- public void getAttributeIntValue_defaultConstructor() throws Exception {
- TestAttributeSet testAttributeSet = new TestAttributeSet();
- testAttributeSet.put("sugarinessPercent", "100");
-
- assertThat(testAttributeSet.getAttributeIntValue("some namespace", "sugarinessPercent", 0), equalTo(100));
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/res/ViewLoaderTest.java b/v1/src/test/java/com/xtremelabs/robolectric/res/ViewLoaderTest.java
deleted file mode 100644
index 139056a86..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/res/ViewLoaderTest.java
+++ /dev/null
@@ -1,392 +0,0 @@
-package com.xtremelabs.robolectric.res;
-
-import android.app.Activity;
-import android.content.Context;
-import android.os.Build;
-import android.os.Bundle;
-import android.view.View;
-import android.view.ViewGroup;
-import android.webkit.WebView;
-import android.widget.*;
-import com.google.android.maps.MapView;
-import com.xtremelabs.robolectric.R;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import com.xtremelabs.robolectric.shadows.ShadowImageView;
-import com.xtremelabs.robolectric.shadows.ShadowTextView;
-import com.xtremelabs.robolectric.util.CustomView;
-import com.xtremelabs.robolectric.util.CustomView2;
-import com.xtremelabs.robolectric.util.I18nException;
-import com.xtremelabs.robolectric.util.TestUtil;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-import static com.xtremelabs.robolectric.util.TestUtil.*;
-import static org.hamcrest.CoreMatchers.*;
-import static org.junit.Assert.*;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class ViewLoaderTest {
- private ViewLoader viewLoader;
- private Context context;
-
- @Before
- public void setUp() throws Exception {
- Robolectric.bindDefaultShadowClasses();
-
- ResourceExtractor resourceExtractor = new ResourceExtractor();
- resourceExtractor.addLocalRClass(R.class);
- resourceExtractor.addSystemRClass(android.R.class);
-
- StringResourceLoader stringResourceLoader = new StringResourceLoader(resourceExtractor);
- new DocumentLoader(stringResourceLoader).loadResourceXmlDir(resourceFile("res", "values"));
- new DocumentLoader(stringResourceLoader).loadSystemResourceXmlDir(getSystemResourceDir("values"));
-
- viewLoader = new ViewLoader(resourceExtractor, new AttrResourceLoader(resourceExtractor));
- new DocumentLoader(viewLoader).loadResourceXmlDir(resourceFile("res", "layout"));
- new DocumentLoader(viewLoader).loadResourceXmlDir(resourceFile("res", "layout-land"));
- new DocumentLoader(viewLoader).loadResourceXmlDir(resourceFile("res", "layout-large-v16"));
- new DocumentLoader(viewLoader).loadResourceXmlDir(resourceFile("res", "layout-v11"));
- new DocumentLoader(viewLoader).loadResourceXmlDir(resourceFile("res", "layout-xlarge"));
- new DocumentLoader(viewLoader).loadResourceXmlDir(resourceFile("res", "layout-xlarge-v11"));
- new DocumentLoader(viewLoader).loadSystemResourceXmlDir(getSystemResourceDir("layout"));
-
- context = new Activity();
- }
-
- @Test
- public void testCreatesCorrectClasses() throws Exception {
- ViewGroup view = (ViewGroup) viewLoader.inflateView(context, "layout/media");
- TestUtil.assertInstanceOf(LinearLayout.class, view);
-
- assertSame(context, view.getContext());
- }
-
- @Test
- public void testChoosesLayoutBasedOnDefaultScreenSize() throws Exception {
- ViewGroup view = (ViewGroup) viewLoader.inflateView(context, "layout/different_screen_sizes");
- TextView textView = (TextView) view.findViewById(android.R.id.text1);
- assertThat(textView.getText().toString(), equalTo("default"));
- }
-
- @Test
- public void testChoosesLayoutBasedOnSearchPath_choosesFirstFileFoundOnPath() throws Exception {
- viewLoader.setLayoutQualifierSearchPath("xlarge", "land");
- ViewGroup view = (ViewGroup) viewLoader.inflateView(context, "layout/different_screen_sizes");
- TextView textView = (TextView) view.findViewById(android.R.id.text1);
- assertThat(textView.getText().toString(), equalTo("xlarge"));
- }
-
- @Test
- public void testChoosesLayoutBasedOnSearchPath_respectsOrderOfPath() throws Exception {
- viewLoader.setLayoutQualifierSearchPath("does-not-exist", "land", "xlarge");
- ViewGroup view = (ViewGroup) viewLoader.inflateView(context, "layout/different_screen_sizes");
- TextView textView = (TextView) view.findViewById(android.R.id.text1);
- assertThat(textView.getText().toString(), equalTo("land"));
- }
-
- @Test
- public void testChoosesLayoutBasedOnDefaultVersion() throws Exception {
- Robolectric.Reflection.setFinalStaticField(Build.VERSION.class, "SDK_INT", Build.VERSION_CODES.FROYO);
- ViewGroup view = (ViewGroup) viewLoader.inflateView(context, "layout/different_screen_sizes");
- TextView textView = (TextView) view.findViewById(android.R.id.text1);
- assertThat(textView.getText().toString(), equalTo("default"));
- }
-
- @Test
- public void testChoosesLayoutBasedOnNewestVersion() throws Exception {
- Robolectric.Reflection.setFinalStaticField(Build.VERSION.class, "SDK_INT", Build.VERSION_CODES.JELLY_BEAN);
- ViewGroup view = (ViewGroup) viewLoader.inflateView(context, "layout/different_screen_sizes");
- TextView textView = (TextView) view.findViewById(android.R.id.text1);
- assertThat(textView.getText().toString(), equalTo("v11"));
- }
-
- @Test
- public void testChoosesLayoutBasedOnSearchPath_choosesFirstFileFoundOnPathWithVersionNumber() throws Exception {
- viewLoader.setLayoutQualifierSearchPath("xlarge", "large");
- Robolectric.Reflection.setFinalStaticField(Build.VERSION.class, "SDK_INT", Build.VERSION_CODES.HONEYCOMB);
- ViewGroup view = (ViewGroup) viewLoader.inflateView(context, "layout/different_screen_sizes");
- TextView textView = (TextView) view.findViewById(android.R.id.text1);
- assertThat(textView.getText().toString(), equalTo("xlarge-v11"));
- }
-
- @Test
- public void testChoosesLayoutBasedOnSearchPath_choosesBestFileFoundOnPathWithVersionNumber() throws Exception {
- viewLoader.setLayoutQualifierSearchPath("xlarge", "large");
- Robolectric.Reflection.setFinalStaticField(Build.VERSION.class, "SDK_INT", Build.VERSION_CODES.JELLY_BEAN);
- ViewGroup view = (ViewGroup) viewLoader.inflateView(context, "layout/different_screen_sizes");
- TextView textView = (TextView) view.findViewById(android.R.id.text1);
- assertThat(textView.getText().toString(), equalTo("xlarge-v11"));
- }
-
- @Test
- public void testWebView() throws Exception {
- ViewGroup view = (ViewGroup) viewLoader.inflateView(context, "layout/webview_holder");
- WebView webView = (WebView) view.findViewById(R.id.web_view);
-
- webView.loadUrl("www.example.com");
-
- assertThat(shadowOf(webView).getLastLoadedUrl(), equalTo("www.example.com"));
- }
-
- @Test
- public void testAddsChildren() throws Exception {
- ViewGroup view = (ViewGroup) viewLoader.inflateView(context, "layout/media");
- assertTrue(view.getChildCount() > 0);
-
- assertSame(context, view.getChildAt(0).getContext());
- }
-
- @Test
- public void testFindsChildrenById() throws Exception {
- ViewGroup mediaView = (ViewGroup) viewLoader.inflateView(context, "layout/media");
- TestUtil.assertInstanceOf(TextView.class, mediaView.findViewById(R.id.title));
-
- ViewGroup mainView = (ViewGroup) viewLoader.inflateView(context, "layout/main");
- assertInstanceOf(View.class, mainView.findViewById(R.id.title));
- }
-
- @Test
- public void testInflatingConflictingSystemAndLocalViewsWorks() throws Exception {
- ViewGroup view = (ViewGroup) viewLoader.inflateView(context, "layout/activity_list_item");
- assertInstanceOf(ImageView.class, view.findViewById(R.id.icon));
-
- view = (ViewGroup) viewLoader.inflateView(context, "android:layout/activity_list_item");
- assertInstanceOf(ImageView.class, view.findViewById(android.R.id.icon));
- }
-
- @Test
- public void testInclude() throws Exception {
- ViewGroup mediaView = (ViewGroup) viewLoader.inflateView(context, "layout/media");
- assertInstanceOf(TextView.class, mediaView.findViewById(R.id.include_id));
- }
-
- @Test
- public void testIncludeShouldRetainAttributes() throws Exception {
- ViewGroup mediaView = (ViewGroup) viewLoader.inflateView(context, "layout/media");
- assertThat(mediaView.findViewById(R.id.include_id).getVisibility(), is(View.GONE));
- }
-
- @Test
- public void shouldOverwriteIdOnIncludedNonMerge() throws Exception {
- ViewGroup mediaView = (ViewGroup) viewLoader.inflateView(context, "layout/media");
- assertNull(mediaView.findViewById(R.id.snippet_text));
- }
-
- @Test
- public void shouldRetainIdOnIncludedMergeWhenIncludeSpecifiesNoId() throws Exception {
- ViewGroup mediaView = (ViewGroup) viewLoader.inflateView(context, "layout/override_include");
- assertInstanceOf(TextView.class, mediaView.findViewById(R.id.inner_text));
- }
-
- @Test
- public void shouldRetainIdOnIncludedNonMergeWhenIncludeSpecifiesNoId() throws Exception {
- ViewGroup mediaView = (ViewGroup) viewLoader.inflateView(context, "layout/override_include");
- assertInstanceOf(TextView.class, mediaView.findViewById(R.id.snippet_text));
- }
-
- @Test
- public void testIncludedIdShouldNotBeFoundWhenIncludedIsMerge() throws Exception {
- ViewGroup overrideIncludeView = (ViewGroup) viewLoader.inflateView(context, "layout/outer");
- assertInstanceOf(LinearLayout.class, overrideIncludeView.findViewById(R.id.outer_merge));
- assertInstanceOf(TextView.class, overrideIncludeView.findViewById(R.id.inner_text));
- assertNull(overrideIncludeView.findViewById(R.id.include_id));
- assertEquals(1, overrideIncludeView.getChildCount());
- }
-
- @Test
- public void testIncludeShouldOverrideAttributesOfIncludedRootNode() throws Exception {
- ViewGroup overrideIncludeView = (ViewGroup) viewLoader.inflateView(context, "layout/override_include");
- assertThat(overrideIncludeView.findViewById(R.id.snippet_text).getVisibility(), is(View.INVISIBLE));
- }
-
- @Test
- public void shouldNotCountRequestFocusElementAsChild() throws Exception {
- ViewGroup viewGroup = (ViewGroup) viewLoader.inflateView(context, "layout/request_focus");
- ViewGroup frameLayout = (ViewGroup) viewGroup.getChildAt(1);
- assertEquals(0, frameLayout.getChildCount());
- }
-
- @Test
- public void shouldGiveFocusToElementContainingRequestFocusElement() throws Exception {
- ViewGroup viewGroup = (ViewGroup) viewLoader.inflateView(context, "layout/request_focus");
- EditText editText = (EditText) viewGroup.findViewById(R.id.edit_text);
- assertFalse(editText.isFocused());
- }
-
- @Test
- public void shouldGiveFocusToFirstFocusableElement_butThisMightBeTheWrongBehavior() throws Exception {
- ViewGroup viewGroup = (ViewGroup) viewLoader.inflateView(context, "layout/request_focus_with_two_edit_texts");
- assertTrue(viewGroup.findViewById(R.id.edit_text).isFocused());
- assertFalse(viewGroup.findViewById(R.id.edit_text2).isFocused());
- }
-
- @Test
- public void testMerge() throws Exception {
- ViewGroup mediaView = (ViewGroup) viewLoader.inflateView(context, "layout/outer");
- TestUtil.assertInstanceOf(TextView.class, mediaView.findViewById(R.id.inner_text));
- }
-
- @Test
- public void mergeIncludesShouldNotCreateAncestryLoops() throws Exception {
- ViewGroup mediaView = (ViewGroup) viewLoader.inflateView(context, "layout/outer");
- mediaView.hasFocus();
- }
-
- @Test
- public void testViewGroupsLooksAtItsOwnId() throws Exception {
- TextView mediaView = (TextView) viewLoader.inflateView(context, "layout/snippet");
- assertSame(mediaView, mediaView.findViewById(R.id.snippet_text));
- }
-
- @Test
- public void shouldConstructCustomViewsWithAttributesConstructor() throws Exception {
- CustomView view = (CustomView) viewLoader.inflateView(context, "layout/custom_layout");
- assertThat(view.attributeResourceValue, equalTo(R.string.hello));
- }
-
- @Test
- public void testViewVisibilityIsSet() throws Exception {
- View mediaView = viewLoader.inflateView(context, "layout/media");
- assertThat(mediaView.findViewById(R.id.title).getVisibility(), equalTo(View.VISIBLE));
- assertThat(mediaView.findViewById(R.id.subtitle).getVisibility(), equalTo(View.GONE));
- }
-
- @Test
- public void testTextViewTextIsSet() throws Exception {
- View mediaView = viewLoader.inflateView(context, "layout/main");
- assertThat(((TextView) mediaView.findViewById(R.id.title)).getText().toString(), equalTo("Main Layout"));
- assertThat(((TextView) mediaView.findViewById(R.id.subtitle)).getText().toString(), equalTo("Hello"));
- }
-
- @Test
- public void testTextViewCompoundDrawablesAreSet() throws Exception {
- View mediaView = viewLoader.inflateView(context, "layout/main");
- ShadowTextView shadowTextView = shadowOf((TextView) mediaView.findViewById(R.id.title));
-
- assertThat(shadowTextView.getCompoundDrawablesImpl().getTop(), equalTo(R.drawable.an_image));
- assertThat(shadowTextView.getCompoundDrawablesImpl().getRight(), equalTo(R.drawable.an_other_image));
- assertThat(shadowTextView.getCompoundDrawablesImpl().getBottom(), equalTo(R.drawable.third_image));
- assertThat(shadowTextView.getCompoundDrawablesImpl().getLeft(), equalTo(R.drawable.fourth_image));
- }
-
- @Test
- public void testCheckBoxCheckedIsSet() throws Exception {
- View mediaView = viewLoader.inflateView(context, "layout/main");
- assertThat(((CheckBox) mediaView.findViewById(R.id.true_checkbox)).isChecked(), equalTo(true));
- assertThat(((CheckBox) mediaView.findViewById(R.id.false_checkbox)).isChecked(), equalTo(false));
- assertThat(((CheckBox) mediaView.findViewById(R.id.default_checkbox)).isChecked(), equalTo(false));
- }
-
- @Test
- public void testImageViewSrcIsSet() throws Exception {
- View mediaView = viewLoader.inflateView(context, "layout/main");
- assertThat(((ShadowImageView) shadowOf(mediaView.findViewById(R.id.image))).getResourceId(), equalTo(R.drawable.an_image));
- }
-
- @Test
- public void shouldInflateMergeLayoutIntoParent() throws Exception {
- View innerMerge = viewLoader.inflateView(context, R.layout.inner_merge, new LinearLayout(null));
- assertNotNull(innerMerge);
- }
-
- @Test
- public void testMapView() throws Exception {
- RelativeLayout mainView = (RelativeLayout) viewLoader.inflateView(context, "layout/mapview");
- TestUtil.assertInstanceOf(MapView.class, mainView.findViewById(R.id.map_view));
- }
-
- @Test
- public void testViewEnabled() throws Exception {
- View mediaView = viewLoader.inflateView(context, "layout/main");
- assertThat(mediaView.findViewById(R.id.time).isEnabled(), equalTo(false));
- }
-
- @Test
- public void testContentDescriptionIsSet() throws Exception {
- View mediaView = viewLoader.inflateView(context, "layout/main");
- assertThat(mediaView.findViewById(R.id.time).getContentDescription().toString(), equalTo("Howdy"));
- }
-
- @Test
- public void testViewBackgroundIdIsSet() throws Exception {
- View mediaView = viewLoader.inflateView(context, "layout/main");
- ImageView imageView = (ImageView) mediaView.findViewById(R.id.image);
- ShadowImageView shadowImageView = Robolectric.shadowOf(imageView);
-
- assertThat(shadowImageView.getBackgroundResourceId(), equalTo(R.drawable.image_background));
- }
-
- @Test
- public void testOnClickAttribute() throws Exception {
- ClickActivity activity = new ClickActivity();
- activity.onCreate(null);
-
- assertThat(activity.clicked, equalTo(false));
-
- Button button = (Button)activity.findViewById(R.id.button);
- button.performClick();
-
- assertThat(activity.clicked, equalTo(true));
- }
-
- @Test
- public void testInvalidOnClickAttribute() throws Exception {
- Activity activity = new Activity();
- activity.setContentView(R.layout.with_invalid_onclick);
-
- Button button =
- (Button)activity.findViewById(R.id.invalid_onclick_button);
-
- IllegalStateException exception = null;
- try {
- button.performClick();
- } catch (IllegalStateException e) {
- exception = e;
- } finally {
- assertNotNull(exception);
- assertThat("The error message should contain the id name of the "
- + "faulty button",
- exception.getMessage(),
- containsString("invalid_onclick_button"));
- }
- }
-
- @Test
- public void shouldInvokeOnFinishInflate() throws Exception {
- CustomView2 outerCustomView = (CustomView2) viewLoader.inflateView(context, "layout/custom_layout2");
- CustomView2 innerCustomView = (CustomView2) outerCustomView.getChildAt(0);
- assertThat(outerCustomView.childCountAfterInflate, equalTo(1));
- assertThat(innerCustomView.childCountAfterInflate, equalTo(3));
- }
-
- @Test
- public void testIncludesLinearLayoutsOnlyOnce() throws Exception {
- ViewGroup parentView = (ViewGroup) viewLoader.inflateView(context, "layout/included_layout_parent");
- assertEquals(1, parentView.getChildCount());
- }
-
- @Test(expected=I18nException.class)
- public void shouldThrowI18nExceptionOnLayoutWithBareStrings() throws Exception {
- viewLoader.setStrictI18n(true);
- new DocumentLoader(viewLoader).loadResourceXmlDir(resourceFile("res", "layout"));
- new DocumentLoader(viewLoader).loadSystemResourceXmlDir(getSystemResourceDir("layout"));
-
- viewLoader.inflateView(context,"layout/text_views");
- }
-
- public static class ClickActivity extends Activity {
- public boolean clicked = false;
-
- @Override protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- }
-
- public void onButtonClick(View v) {
- clicked = true;
- }
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/AbsSeekBarTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/AbsSeekBarTest.java
deleted file mode 100644
index 4912fdb68..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/AbsSeekBarTest.java
+++ /dev/null
@@ -1,30 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.app.Activity;
-import android.content.Context;
-import android.widget.AbsSeekBar;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static org.hamcrest.CoreMatchers.instanceOf;
-import static org.junit.Assert.assertThat;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class AbsSeekBarTest {
-
- @Test
- public void testInheritance() {
- TestAbsSeekBar seekBar = new TestAbsSeekBar(new Activity());
- ShadowAbsSeekBar shadow = Robolectric.shadowOf(seekBar);
- assertThat(shadow, instanceOf(ShadowProgressBar.class));
- }
-
- private static class TestAbsSeekBar extends AbsSeekBar {
-
- public TestAbsSeekBar(Context context) {
- super(context);
- }
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/AbsSpinnerTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/AbsSpinnerTest.java
deleted file mode 100644
index 9dbecdbdc..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/AbsSpinnerTest.java
+++ /dev/null
@@ -1,129 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-
-import android.app.Activity;
-import android.content.Context;
-import android.view.View;
-import android.view.ViewGroup;
-import android.widget.AbsSpinner;
-import android.widget.AdapterView;
-import android.widget.ArrayAdapter;
-import android.widget.Gallery;
-import android.widget.Spinner;
-import android.widget.TextView;
-
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-
-import org.hamcrest.core.IsNull;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static org.hamcrest.CoreMatchers.*;
-import static org.junit.Assert.assertThat;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class AbsSpinnerTest {
- private Context context;
- private AdapterView adapterView;
- private Spinner spinner;
- private ShadowAbsSpinner shadowSpinner;
- private ArrayAdapter<String> arrayAdapter;
-
- @Before
- public void setUp() throws Exception {
- context = new Activity();
- adapterView = new Gallery(context);
- spinner = new Spinner(context);
- shadowSpinner = (ShadowAbsSpinner) Robolectric.shadowOf(spinner);
- String [] testItems = {"foo", "bar"};
- arrayAdapter = new MyArrayAdapter(this.context, testItems);
- }
-
- @Test
- public void shouldHaveAdapterViewCommonBehavior() throws Exception {
- AdapterViewBehavior.shouldActAsAdapterView(adapterView);
- }
-
- @Test
- public void checkSetAdapter() {
- spinner.setAdapter(arrayAdapter);
- }
-
- @Test
- public void getSelectedItemShouldReturnCorrectValue(){
- spinner.setAdapter(arrayAdapter);
- spinner.setSelection(0);
- assertThat((String) spinner.getSelectedItem(), equalTo("foo"));
- assertThat((String) spinner.getSelectedItem(), not(equalTo("bar")));
-
- spinner.setSelection(1);
- assertThat((String) spinner.getSelectedItem(), equalTo("bar"));
- assertThat((String) spinner.getSelectedItem(), not(equalTo("foo")));
- }
-
- @Test
- public void getSelectedItemShouldReturnNull_NoAdapterSet(){
- assertThat(spinner.getSelectedItem(), nullValue());
- }
-
- @Test (expected = IndexOutOfBoundsException.class)
- public void getSelectedItemShouldThrowException_EmptyArray(){
- spinner.setAdapter(new MyArrayAdapter(context, new String[]{}));
- spinner.getSelectedItem();
- }
-
- @Test
- public void setSelectionWithAnimatedTransition() {
- spinner.setAdapter(arrayAdapter);
- spinner.setSelection(0, true);
-
- assertThat((String) spinner.getSelectedItem(), equalTo("foo"));
- assertThat((String) spinner.getSelectedItem(), not(equalTo("bar")));
-
- assertThat(shadowSpinner.isAnimatedTransition(), equalTo(true));
- }
-
- @Test
- public void testGetSelectedView_noAdapter() {
- assertThat(spinner.getSelectedView(), nullValue());
- }
-
- @Test
- public void testGetSelectedView_noSelection() {
- spinner.setAdapter(arrayAdapter);
- spinner.setSelection(AdapterView.INVALID_POSITION);
-
- assertThat(spinner.getSelectedView(), nullValue());
- }
-
- @Test
- public void testGetSelectedView_default() {
- spinner.setAdapter(arrayAdapter);
-
- assertThat(((TextView) spinner.getSelectedView()).getText().toString(),
- equalTo("foo"));
- }
-
- @Test
- public void testGetSelectedView_changed() {
- spinner.setAdapter(arrayAdapter);
- spinner.setSelection(1);
-
- assertThat(((TextView) spinner.getSelectedView()).getText().toString(),
- equalTo("bar"));
- }
-
- private static class MyArrayAdapter extends ArrayAdapter<String> {
- public MyArrayAdapter(Context context, String[] testItems) {
- super(context, android.R.layout.simple_spinner_item, testItems);
- }
-
- @Override public View getView(int position, View convertView, ViewGroup parent) {
- TextView textView = new TextView(getContext());
- textView.setText(getItem(position));
- return textView;
- }
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/AbstractCursorTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/AbstractCursorTest.java
deleted file mode 100644
index 60815bfcc..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/AbstractCursorTest.java
+++ /dev/null
@@ -1,278 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.CoreMatchers.nullValue;
-import static org.junit.Assert.assertThat;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import android.database.AbstractCursor;
-import android.net.Uri;
-
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class AbstractCursorTest {
-
- private TestCursor cursor;
-
- @Before
- public void setUp() throws Exception {
- cursor = new TestCursor();
- }
-
- @Test
- public void testMoveToFirst() {
- cursor.theTable.add("Foobar");
- assertThat(cursor.moveToFirst(), equalTo(true));
- assertThat(cursor.getCount(), equalTo(1));
- }
-
- @Test
- public void testMoveToFirstEmptyList() {
- assertThat(cursor.moveToFirst(), equalTo(false));
- assertThat(cursor.getCount(), equalTo(0));
- }
-
- @Test
- public void testMoveToLast() {
- cursor.theTable.add("Foobar");
- cursor.theTable.add("Bletch");
-
- assertThat(cursor.moveToLast(), equalTo(true));
- assertThat(cursor.getCount(), equalTo(2));
- }
-
- @Test
- public void testMoveToLastEmptyList() {
- assertThat(cursor.moveToLast(), equalTo(false));
- assertThat(cursor.getCount(), equalTo(0));
- }
-
- @Test
- public void testGetPosition() {
- cursor.theTable.add("Foobar");
- cursor.theTable.add("Bletch");
-
- assertThat(cursor.moveToFirst(), equalTo(true));
- assertThat(cursor.getCount(), equalTo(2));
- assertThat(cursor.getPosition(), equalTo(0));
- }
-
- @Test
- public void testGetPositionSingleEntry() {
- cursor.theTable.add("Foobar");
-
- assertThat(cursor.moveToFirst(), equalTo(true));
- assertThat(cursor.getCount(), equalTo(1));
- assertThat(cursor.getPosition(), equalTo(0));
- }
-
- @Test
- public void testGetPositionEmptyList() {
- assertThat(cursor.moveToFirst(), equalTo(false));
- assertThat(cursor.getCount(), equalTo(0));
- assertThat(cursor.getPosition(), equalTo(0));
- }
-
- @Test
- public void testMoveToNext() {
- cursor.theTable.add("Foobar");
- cursor.theTable.add("Bletch");
-
- assertThat(cursor.moveToFirst(), equalTo(true));
- assertThat(cursor.getCount(), equalTo(2));
- assertThat(cursor.moveToNext(), equalTo(true));
- assertThat(cursor.getPosition(), equalTo(1));
- }
-
- @Test
- public void testAttemptToMovePastEnd() {
- cursor.theTable.add("Foobar");
- cursor.theTable.add("Bletch");
-
- assertThat(cursor.moveToFirst(), equalTo(true));
- assertThat(cursor.getCount(), equalTo(2));
- assertThat(cursor.moveToNext(), equalTo(true));
- assertThat(cursor.getPosition(), equalTo(1));
- assertThat(cursor.isLast(), equalTo(true));
- assertThat(cursor.moveToNext(), equalTo(false));
- assertThat(cursor.isAfterLast(), equalTo(true));
- assertThat(cursor.getPosition(), equalTo(2));
- }
-
- @Test
- public void testAttemptToMovePastSingleEntry() {
- cursor.theTable.add("Foobar");
-
- assertThat(cursor.moveToFirst(), equalTo(true));
- assertThat(cursor.getCount(), equalTo(1));
- assertThat(cursor.moveToNext(), equalTo(false));
- assertThat(cursor.getPosition(), equalTo(1));
- }
-
- @Test
- public void testAttemptToMovePastEmptyList() {
- assertThat(cursor.moveToFirst(), equalTo(false));
- assertThat(cursor.getCount(), equalTo(0));
- assertThat(cursor.moveToNext(), equalTo(false));
- assertThat(cursor.getPosition(), equalTo(0));
- }
-
- @Test
- public void testMoveToPrevious() {
- cursor.theTable.add("Foobar");
- cursor.theTable.add("Bletch");
- assertThat(cursor.moveToFirst(), equalTo(true));
- assertThat(cursor.moveToNext(), equalTo(true));
- assertThat(cursor.getPosition(), equalTo(1));
- assertThat(cursor.moveToPrevious(), equalTo(true));
- assertThat(cursor.getPosition(), equalTo(0));
- }
-
- @Test
- public void testAttemptToMovePastStart() {
- cursor.theTable.add("Foobar");
- cursor.theTable.add("Bletch");
- assertThat(cursor.moveToFirst(), equalTo(true));
- assertThat(cursor.moveToPrevious(), equalTo(true));
- assertThat(cursor.getPosition(), equalTo(-1));
- assertThat(cursor.moveToPrevious(), equalTo(false));
- assertThat(cursor.getPosition(), equalTo(-1));
- }
-
- @Test
- public void testIsFirst() {
- cursor.theTable.add("Foobar");
- cursor.theTable.add("Bletch");
- assertThat(cursor.moveToFirst(), equalTo(true));
- assertThat(cursor.isFirst(), equalTo(true));
- cursor.moveToNext();
- assertThat(cursor.isFirst(), equalTo(false));
- cursor.moveToFirst();
- cursor.moveToPrevious();
- assertThat(cursor.isFirst(), equalTo(false));
- }
-
- @Test
- public void testIsLast() {
- cursor.theTable.add("Foobar");
- cursor.theTable.add("Bletch");
- assertThat(cursor.moveToFirst(), equalTo(true));
- cursor.moveToNext();
- assertThat(cursor.isLast(), equalTo(true));
- cursor.moveToPrevious();
- assertThat(cursor.isLast(), equalTo(false));
- cursor.moveToFirst();
- cursor.moveToNext();
- assertThat(cursor.isLast(), equalTo(true));
- }
-
- @Test
- public void testIsBeforeFirst() {
- cursor.theTable.add("Foobar");
- cursor.theTable.add("Bletch");
- assertThat(cursor.moveToFirst(), equalTo(true));
- cursor.moveToNext();
- assertThat(cursor.isLast(), equalTo(true));
- cursor.moveToPrevious();
- assertThat(cursor.isLast(), equalTo(false));
- cursor.moveToPrevious();
- assertThat(cursor.isFirst(), equalTo(false));
- cursor.moveToPrevious();
- assertThat(cursor.isBeforeFirst(), equalTo(true));
- }
-
- @Test
- public void testIsAfterLast() {
- cursor.theTable.add("Foobar");
- cursor.theTable.add("Bletch");
- assertThat(cursor.moveToFirst(), equalTo(true));
- cursor.moveToNext();
- assertThat(cursor.isLast(), equalTo(true));
- cursor.moveToNext();
- assertThat(cursor.isAfterLast(), equalTo(true));
- cursor.moveToPrevious();
- assertThat(cursor.isLast(), equalTo(true));
- cursor.moveToPrevious();
- assertThat(cursor.isLast(), equalTo(false));
- cursor.moveToFirst();
- cursor.moveToNext();
- assertThat(cursor.isAfterLast(), equalTo(false));
- cursor.moveToNext();
- assertThat(cursor.isAfterLast(), equalTo(true));
- }
-
- @Test
- public void testGetNotificationUri() {
- Uri uri = Uri.parse("content://foo.com");
- ShadowAbstractCursor shadow = Robolectric.shadowOf_(cursor);
- assertThat(shadow.getNotificationUri_Compatibility(), is(nullValue()));
- cursor.setNotificationUri(null, uri);
- assertThat(shadow.getNotificationUri_Compatibility(), is(uri));
- }
-
- @Test
- public void testIsClosedWhenAfterCallingClose() {
- assertThat(cursor.isClosed(), equalTo(false));
- cursor.close();
- assertThat(cursor.isClosed(), equalTo(true));
- }
-
- private class TestCursor extends AbstractCursor {
-
- public List<Object> theTable = new ArrayList<Object>();
-
- @Override
- public int getCount() {
- return theTable.size();
- }
-
- @Override
- public String[] getColumnNames() {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public double getDouble(int columnIndex) {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public float getFloat(int columnIndex) {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public int getInt(int columnIndex) {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public long getLong(int columnIndex) {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public short getShort(int columnIndex) {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public String getString(int columnIndex) {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public boolean isNull(int columnIndex) {
- throw new UnsupportedOperationException();
- }
- }
-} \ No newline at end of file
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/AccountManagerTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/AccountManagerTest.java
deleted file mode 100644
index 6cdf29ff0..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/AccountManagerTest.java
+++ /dev/null
@@ -1,157 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.junit.Assert.assertArrayEquals;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertThat;
-import static org.junit.Assert.assertTrue;
-
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import android.accounts.Account;
-import android.accounts.AccountManager;
-import android.accounts.AccountManagerFuture;
-import android.app.Activity;
-import android.os.Bundle;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class AccountManagerTest {
-
- private static final Account ACCOUNT = new Account("name", "type");
-
- private AccountManager accountManager;
- private Activity activity;
- private String accountType;
- private String authTokenType;
- private String[] features;
-
- @Before
- public void setUp() {
- activity = new Activity();
- accountManager = AccountManager.get(activity);
- accountManager.invalidateAuthToken(null, null);
- accountType = "accountType";
- authTokenType = "authTokenType";
- features = new String[]{};
- }
-
- @Test
- public void testGetAuthTokenByFeatures_isCancelled() throws Exception {
- AccountManagerFuture<Bundle> future =
- accountManager.getAuthTokenByFeatures(accountType, authTokenType, features, activity, null, null, null, null);
-
- assertThat(future.isCancelled(), equalTo(false));
- future.cancel(true);
- assertThat(future.isCancelled(), equalTo(true));
- }
-
- @Test
- public void testGetAuthTokenByFeatures_isDoneWithCancel() throws Exception {
- AccountManagerFuture<Bundle> future =
- accountManager.getAuthTokenByFeatures(accountType, authTokenType, features, activity, null, null, null, null);
-
- assertThat(future.isDone(), equalTo(false));
- future.cancel(true);
- assertThat(future.isDone(), equalTo(true));
- }
-
- @Test
- public void testGetAuthTokenByFeatures_isDoneWithGetResult() throws Exception {
- AccountManagerFuture<Bundle> future =
- accountManager.getAuthTokenByFeatures(accountType, authTokenType, features, activity, null, null, null, null);
-
- assertThat(future.isDone(), equalTo(false));
- future.getResult();
- assertThat(future.isDone(), equalTo(true));
- }
-
- @Test
- public void testInvalidateAuthToken() throws Exception {
- // Check that it doesn't crash
- accountManager.invalidateAuthToken(accountType, null);
- }
-
- @Test
- public void testGetAuthTokenByFeatures_getResult() throws Exception {
- AccountManagerFuture<Bundle> future =
- accountManager.getAuthTokenByFeatures(accountType, authTokenType, features, activity, null, null, null, null);
-
- Bundle result = future.getResult();
- assertThat(result.containsKey(AccountManager.KEY_AUTHTOKEN), equalTo(true));
- assertThat(result.containsKey(AccountManager.KEY_ACCOUNT_NAME), equalTo(true));
- assertThat(result.containsKey(AccountManager.KEY_ACCOUNT_TYPE), equalTo(true));
- }
-
- @Test
- public void testGetAuthToken_getResult() throws Exception {
- AccountManagerFuture<Bundle> future =
- accountManager.getAuthToken(ACCOUNT, authTokenType, null, activity, null, null);
-
- Bundle result = future.getResult();
- assertThat(ACCOUNT.name, equalTo(result.getString(AccountManager.KEY_ACCOUNT_NAME)));
- assertThat(ACCOUNT.type, equalTo(result.getString(AccountManager.KEY_ACCOUNT_TYPE)));
- }
-
- @Test
- public void testAccountManagerIsSingleton() throws Exception {
- AccountManager ref = AccountManager.get(activity);
-
- assertTrue(ref == accountManager);
- assertThat(ref, equalTo(accountManager));
- }
-
- @Test
- public void testGetAccounts() throws Exception {
- Account[] origAccounts = new Account[] { ACCOUNT, ACCOUNT };
- shadowOf(accountManager).setAccounts(origAccounts);
-
- Account[] accounts = accountManager.getAccounts();
-
- assertArrayEquals(origAccounts, accounts);
- }
-
- @Test
- public void testGetAccountsByType() throws Exception {
- Account diffAccount = new Account("myName", "myType");
- Account[] origAccounts = new Account[] { ACCOUNT, diffAccount };
- shadowOf(accountManager).setAccounts(origAccounts);
-
- Account[] accounts = accountManager.getAccountsByType("myType");
-
- assertThat(accounts.length, equalTo(1));
- assertThat(accounts[0], equalTo(diffAccount));
- }
-
- @Test
- public void testPeek() throws Exception {
- shadowOf(accountManager).setCachedAuthToken(ACCOUNT, authTokenType, "myToken");
-
- String authToken = accountManager.peekAuthToken(ACCOUNT, authTokenType);
-
- assertThat(authToken, equalTo("myToken"));
- }
-
- @Test
- public void testPeek_differentAccount() throws Exception {
- shadowOf(accountManager).setCachedAuthToken(ACCOUNT, authTokenType, "myToken");
-
- String authToken =
- accountManager.peekAuthToken(new Account("other", "type"), authTokenType);
-
- assertNull(authToken);
- }
-
- @Test
- public void testPeek_differentAuthTokenType() throws Exception {
- shadowOf(accountManager).setCachedAuthToken(ACCOUNT, authTokenType, "myToken");
-
- String authToken = accountManager.peekAuthToken(ACCOUNT, "other");
-
- assertNull(authToken);
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/AccountTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/AccountTest.java
deleted file mode 100644
index abb69c84d..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/AccountTest.java
+++ /dev/null
@@ -1,72 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.accounts.Account;
-import android.os.Parcel;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.CoreMatchers.not;
-import static org.junit.Assert.assertThat;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class AccountTest {
-
- @Test
- public void shouldHaveStringsConstructor() throws Exception {
- Account account = new Account("name", "type");
-
- assertThat(account.name, equalTo("name"));
- assertThat(account.type, equalTo("type"));
- }
-
- @Test
- public void shouldHaveParcelConstructor() throws Exception {
- Parcel p = Parcel.obtain();
- p.writeString("name");
- p.writeString("type");
-
- p.setDataPosition(0);
-
- Account account = new Account(p);
- assertThat(account.name, equalTo("name"));
- assertThat(account.type, equalTo("type"));
- }
-
- @Test
- public void shouldHaveCreator() throws Exception {
- Account expected = new Account("name", "type");
- Parcel p = Parcel.obtain();
- expected.writeToParcel(p, 0);
-
- p.setDataPosition(0);
-
- Account actual = Account.CREATOR.createFromParcel(p);
- assertThat(expected, equalTo(actual));
- }
-
- @Test(expected = IllegalArgumentException.class)
- public void shouldThrowIfNameIsEmpty() throws Exception {
- new Account("", "type");
- }
-
- @Test(expected = IllegalArgumentException.class)
- public void shouldThrowIfTypeIsEmpty() throws Exception {
- new Account("name", "");
- }
-
- @Test
- public void shouldHaveToString() throws Exception {
- Account account = new Account("name", "type");
- assertThat(account.toString(), equalTo("Account {name=name, type=type}"));
- }
-
- @Test
- public void shouldProvideEqualAndHashCode() throws Exception {
- assertThat(new Account("a", "b"), equalTo(new Account("a", "b")));
- assertThat(new Account("a", "b"), not(equalTo(new Account("c", "b"))));
- assertThat(new Account("a", "b").hashCode(), equalTo(new Account("a", "b").hashCode()));
- assertThat(new Account("a", "b").hashCode(), not(equalTo(new Account("c", "b").hashCode())));
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ActivityGroupTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/ActivityGroupTest.java
deleted file mode 100644
index 27f35841a..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ActivityGroupTest.java
+++ /dev/null
@@ -1,24 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.app.Activity;
-import android.app.ActivityGroup;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-import static org.hamcrest.CoreMatchers.is;
-import static org.junit.Assert.assertThat;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class ActivityGroupTest {
-
- @Test
- public void getCurrentActivity_shouldReturnTheProvidedCurrentActivity() throws Exception {
- ActivityGroup activityGroup = new ActivityGroup();
- Activity activity = new Activity();
- shadowOf(activityGroup).setCurrentActivity(activity);
-
- assertThat(activityGroup.getCurrentActivity(), is(activity));
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ActivityManagerTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/ActivityManagerTest.java
deleted file mode 100644
index 9df19efd8..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ActivityManagerTest.java
+++ /dev/null
@@ -1,35 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.app.ActivityManager;
-import android.content.Context;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-import static junit.framework.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class ActivityManagerTest {
- @Test
- public void canGetMemoryInfoForOurProcess() {
- ActivityManager activityManager = (ActivityManager) Robolectric.application.getSystemService(Context.ACTIVITY_SERVICE);
- ShadowActivityManager shadowActivityManager = shadowOf(activityManager);
- ActivityManager.MemoryInfo memoryInfo = new ActivityManager.MemoryInfo();
- memoryInfo.lowMemory = true;
- shadowActivityManager.setMemoryInfo(memoryInfo);
- ActivityManager.MemoryInfo fetchedMemoryInfo = new ActivityManager.MemoryInfo();
- activityManager.getMemoryInfo(fetchedMemoryInfo);
- assertTrue(fetchedMemoryInfo.lowMemory);
- }
-
- @Test
- public void canGetMemoryInfoEvenWhenWeDidNotSetIt() {
- ActivityManager activityManager = (ActivityManager) Robolectric.application.getSystemService(Context.ACTIVITY_SERVICE);
- ActivityManager.MemoryInfo fetchedMemoryInfo = new ActivityManager.MemoryInfo();
- activityManager.getMemoryInfo(fetchedMemoryInfo);
- assertFalse(fetchedMemoryInfo.lowMemory);
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ActivityTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/ActivityTest.java
deleted file mode 100644
index 273cce959..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ActivityTest.java
+++ /dev/null
@@ -1,598 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.app.Activity;
-import android.app.Dialog;
-import android.appwidget.AppWidgetProvider;
-import android.content.*;
-import android.content.pm.ActivityInfo;
-import android.database.CharArrayBuffer;
-import android.database.ContentObserver;
-import android.database.Cursor;
-import android.database.DataSetObserver;
-import android.database.sqlite.SQLiteCursor;
-import android.net.Uri;
-import android.os.Bundle;
-import android.view.KeyEvent;
-import android.view.View;
-import android.widget.FrameLayout;
-import com.xtremelabs.robolectric.ApplicationResolver;
-import com.xtremelabs.robolectric.R;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import com.xtremelabs.robolectric.util.TestRunnable;
-import com.xtremelabs.robolectric.util.Transcript;
-import org.hamcrest.CoreMatchers;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import java.util.concurrent.atomic.AtomicBoolean;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-import static com.xtremelabs.robolectric.util.TestUtil.assertInstanceOf;
-import static com.xtremelabs.robolectric.util.TestUtil.newConfig;
-import static org.hamcrest.CoreMatchers.*;
-import static org.hamcrest.core.StringStartsWith.startsWith;
-import static org.junit.Assert.*;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class ActivityTest {
- @Test(expected = IllegalStateException.class)
- public void shouldComplainIfActivityIsDestroyedWithRegisteredBroadcastReceivers() throws Exception {
- DialogLifeCycleActivity activity = new DialogLifeCycleActivity();
- activity.registerReceiver(new AppWidgetProvider(), new IntentFilter());
- activity.onDestroy();
- }
-
- @Test
- public void shouldNotComplainIfActivityIsDestroyedWhileAnotherActivityHasRegisteredBroadcastReceivers() throws Exception {
- DialogLifeCycleActivity activity = new DialogLifeCycleActivity();
-
- DialogLifeCycleActivity activity2 = new DialogLifeCycleActivity();
- activity2.registerReceiver(new AppWidgetProvider(), new IntentFilter());
-
- activity.onDestroy(); // should not throw exception
- }
-
- @Test
- public void shouldNotRegisterNullBroadcastReceiver() {
- DialogLifeCycleActivity activity = new DialogLifeCycleActivity();
- activity.registerReceiver(null, new IntentFilter());
-
- activity.onDestroy();
- }
-
- @Test
- public void startActivityForResultAndReceiveResult_shouldSendResponsesBackToActivity() throws Exception {
- final Transcript transcript = new Transcript();
- Activity activity = new Activity() {
- @Override
- protected void onActivityResult(int requestCode, int resultCode, Intent data) {
- transcript.add("onActivityResult called with requestCode " + requestCode + ", resultCode " + resultCode + ", intent data " + data.getData());
- }
- };
- activity.startActivityForResult(new Intent().setType("audio/*"), 123);
- activity.startActivityForResult(new Intent().setType("image/*"), 456);
-
- shadowOf(activity).receiveResult(new Intent().setType("image/*"), Activity.RESULT_OK,
- new Intent().setData(Uri.parse("content:foo")));
- transcript.assertEventsSoFar("onActivityResult called with requestCode 456, resultCode -1, intent data content:foo");
- }
-
- @Test
- public void startActivityForResultAndReceiveResult_whenNoIntentMatches_shouldThrowException() throws Exception {
- Activity activity = new Activity() {
- @Override
- protected void onActivityResult(int requestCode, int resultCode, Intent data) {
- throw new IllegalStateException("should not be called");
- }
- };
- activity.startActivityForResult(new Intent().setType("audio/*"), 123);
- activity.startActivityForResult(new Intent().setType("image/*"), 456);
-
- Intent requestIntent = new Intent().setType("video/*");
- try {
- shadowOf(activity).receiveResult(requestIntent, Activity.RESULT_OK,
- new Intent().setData(Uri.parse("content:foo")));
- fail();
- } catch (Exception e) {
- assertThat(e.getMessage(), startsWith("No intent matches " + requestIntent));
- }
- }
-
- @Test
- public void shouldSupportStartActivityForResult() throws Exception {
- DialogLifeCycleActivity activity = new DialogLifeCycleActivity();
- ShadowActivity shadowActivity = Robolectric.shadowOf(activity);
- Intent intent = new Intent().setClass(activity, DialogLifeCycleActivity.class);
- assertThat(shadowActivity.getNextStartedActivity(), nullValue());
-
- activity.startActivityForResult(intent, 142);
-
- Intent startedIntent = shadowActivity.getNextStartedActivity();
- assertThat(startedIntent, notNullValue());
- assertThat(startedIntent, sameInstance(intent));
- }
-
- @Test
- public void shouldSupportGetStartedActitivitesForResult() throws Exception {
- DialogLifeCycleActivity activity = new DialogLifeCycleActivity();
- ShadowActivity shadowActivity = Robolectric.shadowOf(activity);
- Intent intent = new Intent().setClass(activity, DialogLifeCycleActivity.class);
-
- activity.startActivityForResult(intent, 142);
-
- ShadowActivity.IntentForResult intentForResult = shadowActivity.getNextStartedActivityForResult();
- assertThat(intentForResult, notNullValue());
- assertThat(shadowActivity.getNextStartedActivityForResult(), nullValue());
- assertThat(intentForResult.intent, notNullValue());
- assertThat(intentForResult.intent, sameInstance(intent));
- assertThat(intentForResult.requestCode, equalTo(142));
- }
-
- @Test
- public void shouldSupportPeekStartedActitivitesForResult() throws Exception {
- DialogLifeCycleActivity activity = new DialogLifeCycleActivity();
- ShadowActivity shadowActivity = Robolectric.shadowOf(activity);
- Intent intent = new Intent().setClass(activity, DialogLifeCycleActivity.class);
-
- activity.startActivityForResult(intent, 142);
-
- ShadowActivity.IntentForResult intentForResult = shadowActivity.peekNextStartedActivityForResult();
- assertThat(intentForResult, notNullValue());
- assertThat(shadowActivity.peekNextStartedActivityForResult(), sameInstance(intentForResult));
- assertThat(intentForResult.intent, notNullValue());
- assertThat(intentForResult.intent, sameInstance(intent));
- assertThat(intentForResult.requestCode, equalTo(142));
- }
-
- @Test
- public void onContentChangedShouldBeCalledAfterContentViewIsSet() throws RuntimeException {
- final Transcript transcript = new Transcript();
- Activity customActivity = new Activity() {
- @Override
- public void onContentChanged() {
- transcript.add("onContentChanged was called; title is \"" + shadowOf(findViewById(R.id.title)).innerText() + "\"");
- }
- };
- customActivity.setContentView(R.layout.main);
- transcript.assertEventsSoFar("onContentChanged was called; title is \"Main Layout\"");
- }
-
- @Test
- public void shouldRetrievePackageNameFromTheManifest() throws Exception {
- Robolectric.application = new ApplicationResolver(newConfig("TestAndroidManifestWithPackageName.xml")).resolveApplication();
- assertThat("com.wacka.wa", equalTo(new Activity().getPackageName()));
- }
-
- @Test
- public void shouldRunUiTasksImmediatelyByDefault() throws Exception {
- TestRunnable runnable = new TestRunnable();
- DialogLifeCycleActivity activity = new DialogLifeCycleActivity();
- activity.runOnUiThread(runnable);
- assertTrue(runnable.wasRun);
- }
-
- @Test
- public void shouldQueueUiTasksWhenUiThreadIsPaused() throws Exception {
- Robolectric.pauseMainLooper();
-
- DialogLifeCycleActivity activity = new DialogLifeCycleActivity();
- TestRunnable runnable = new TestRunnable();
- activity.runOnUiThread(runnable);
- assertFalse(runnable.wasRun);
-
- Robolectric.unPauseMainLooper();
- assertTrue(runnable.wasRun);
- }
-
- @Test
- public void showDialog_shouldCreatePrepareAndShowDialog() {
- final DialogLifeCycleActivity activity = new DialogLifeCycleActivity();
- final AtomicBoolean dialogWasShown = new AtomicBoolean(false);
-
- new Dialog(activity) {
- {
- activity.dialog = this;
- }
-
- @Override
- public void show() {
- dialogWasShown.set(true);
- }
- };
-
- activity.showDialog(1);
-
- assertTrue(activity.createdDialog);
- assertTrue(activity.preparedDialog);
- assertTrue(dialogWasShown.get());
- }
-
- @Test
- public void showDialog_shouldCreatePrepareAndShowDialogWithBundle() {
- final DialogLifeCycleActivity activity = new DialogLifeCycleActivity();
- final AtomicBoolean dialogWasShown = new AtomicBoolean(false);
-
- new Dialog(activity) {
- {
- activity.dialog = this;
- }
-
- @Override
- public void show() {
- dialogWasShown.set(true);
- }
- };
-
- activity.showDialog(1, new Bundle());
-
- assertTrue(activity.createdDialog);
- assertTrue(activity.preparedDialogWithBundle);
- assertTrue(dialogWasShown.get());
- }
-
- @Test
- public void showDialog_shouldReuseDialogs() {
- final DialogCreatingActivity activity = new DialogCreatingActivity();
-
- activity.showDialog(1);
-
- Dialog firstDialog = ShadowDialog.getLatestDialog();
-
- activity.showDialog(1);
-
- final Dialog secondDialog = ShadowDialog.getLatestDialog();
-
- assertSame("dialogs should be the same instance", firstDialog, secondDialog);
- }
-
- @Test
- public void showDialog_shouldShowDialog() throws Exception {
- final DialogCreatingActivity activity = new DialogCreatingActivity();
- activity.showDialog(1);
- Dialog dialog = ShadowDialog.getLatestDialog();
- assertTrue(dialog.isShowing());
- }
-
- @Test
- public void dismissDialog_shouldDismissPreviouslyShownDialog() throws Exception {
- final DialogCreatingActivity activity = new DialogCreatingActivity();
- activity.showDialog(1);
- activity.dismissDialog(1);
- Dialog dialog = ShadowDialog.getLatestDialog();
- assertFalse(dialog.isShowing());
- }
-
- @Test(expected = IllegalArgumentException.class)
- public void dismissDialog_shouldThrowExceptionIfDialogWasNotPreviouslyShown() throws Exception {
- final DialogCreatingActivity activity = new DialogCreatingActivity();
- activity.dismissDialog(1);
- }
-
- @Test
- public void removeDialog_shouldCreateDialogAgain() {
- final DialogCreatingActivity activity = new DialogCreatingActivity();
-
- activity.showDialog(1);
- Dialog firstDialog = ShadowDialog.getLatestDialog();
-
- activity.removeDialog(1);
- assertNull(Robolectric.shadowOf(activity).getDialogById(1));
-
- activity.showDialog(1);
- Dialog secondDialog = ShadowDialog.getLatestDialog();
-
- assertNotSame("dialogs should not be the same instance", firstDialog, secondDialog);
- }
-
- @Test
- public void shouldCallOnCreateDialogFromShowDialog() {
- ActivityWithOnCreateDialog activity = new ActivityWithOnCreateDialog();
- activity.showDialog(123);
- assertTrue(activity.onCreateDialogWasCalled);
- assertThat(ShadowDialog.getLatestDialog(), CoreMatchers.<Object>notNullValue());
- }
-
- @Test
- public void shouldCallFinishInOnBackPressed() {
- Activity activity = new Activity();
- activity.onBackPressed();
-
- ShadowActivity shadowActivity = shadowOf(activity);
- assertTrue(shadowActivity.isFinishing());
- }
-
- @Test
- public void shouldSupportCurrentFocus() {
- DialogLifeCycleActivity activity = new DialogLifeCycleActivity();
- ShadowActivity shadow = shadowOf(activity);
-
- assertNull(shadow.getCurrentFocus());
- View view = new View(activity);
- shadow.setCurrentFocus(view);
- assertEquals(view, shadow.getCurrentFocus());
- }
-
- @Test
- public void shouldSetOrientation() {
- DialogLifeCycleActivity activity = new DialogLifeCycleActivity();
- activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
- assertThat(activity.getRequestedOrientation(), equalTo(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT));
- }
-
- @Test
- public void retrieveIdOfResource() {
- Activity activity = new Activity();
-
- int id1 = R.string.hello;
- String string = activity.getString(id1);
- assertEquals("Hello", string);
-
- int id = activity.getResources().getIdentifier("hello", "string", "com.xtremelabs.robolectric");
- assertTrue(id > 0);
-
- String hello = activity.getResources().getString(id);
- assertEquals("Hello", hello);
- }
-
- @Test
- public void getCurrentFocus_shouldBeNullWhenNoFocusRequested() {
- Activity activity = new Activity();
- activity.setContentView(R.layout.main);
-
- View focusedView = shadowOf(activity).getCurrentFocus();
- assertNull(focusedView);
- }
-
- @Test
- public void getCurrentFocus_shouldReturnSubViewAfterFocusedRequest() {
- Activity activity = new Activity();
- activity.setContentView(R.layout.main);
-
- View view = activity.findViewById(R.id.button);
- view.requestFocus();
-
- View focusedView = shadowOf(activity).getCurrentFocus();
- assertEquals(R.id.button, focusedView.getId());
- }
-
- @Test
- public void retrieveIdOfNonExistingResource() {
- Activity activity = new Activity();
-
- int id = activity.getResources().getIdentifier("just_alot_of_crap", "string", "com.xtremelabs.robolectric");
- assertTrue(id == 0);
- }
-
- @Test
- public void shouldSetContentViewWithFrameLayoutAsParent() throws Exception {
- Activity activity = new Activity();
- activity.setContentView(R.layout.toplevel_merge);
-
- View contentView = shadowOf(activity).getContentView();
- assertInstanceOf(FrameLayout.class, contentView);
- assertThat(((FrameLayout) contentView).getChildCount(), equalTo(2));
- }
-
- @Test
- public void onKeyUp_recordsThatItWasCalled() throws Exception {
- Activity activity = new Activity();
- boolean consumed = activity.onKeyUp(KeyEvent.KEYCODE_0, new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_0));
-
- assertFalse(consumed);
- assertTrue(shadowOf(activity).onKeyUpWasCalled());
-
- shadowOf(activity).resetKeyUpWasCalled();
- assertFalse(shadowOf(activity).onKeyUpWasCalled());
- }
-
- @Test
- public void onKeyUp_callsOnBackPressedWhichFinishesTheActivity() throws Exception {
- Activity activity = new Activity();
- boolean consumed = activity.onKeyUp(KeyEvent.KEYCODE_BACK, new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_BACK));
-
- assertTrue(consumed);
- assertTrue(shadowOf(activity).onKeyUpWasCalled());
- assertTrue(activity.isFinishing());
- }
-
- @Test
- public void shouldGiveSharedPreferences() throws Exception {
- Activity activity = new Activity();
- SharedPreferences preferences = activity.getPreferences(Context.MODE_PRIVATE);
- assertNotNull(preferences);
- preferences.edit().putString("foo", "bar").commit();
- assertThat(activity.getPreferences(Context.MODE_PRIVATE).getString("foo", null), equalTo("bar"));
- }
-
- @Test
- public void shouldFindContentViewContainer() throws Exception {
- Activity activity = new Activity();
- View contentView = new View(activity);
- activity.setContentView(contentView);
-
- FrameLayout contentViewContainer = (FrameLayout) activity.findViewById(android.R.id.content);
- assertThat(contentViewContainer.getChildAt(0), is(contentView));
- }
-
- @Test
- public void createGoesThroughFullLifeCycle() throws Exception {
- TestActivity activity = new TestActivity();
-
- shadowOf(activity).create();
-
- activity.transcript.assertEventsSoFar(
- "onCreate",
- "onStart",
- "onPostCreate",
- "onResume"
- );
- }
-
-
- @Test
- public void recreateGoesThroughFullLifeCycle() throws Exception {
- TestActivity activity = new TestActivity();
-
- ShadowActivity shadow = shadowOf(activity);
- shadow.recreate();
-
- activity.transcript.assertEventsSoFar(
- "onSaveInstanceState",
- "onPause",
- "onStop",
- "onRetainNonConfigurationInstance",
- "onDestroy",
- "onCreate",
- "onStart",
- "onRestoreInstanceState",
- "onResume"
- );
-
- Integer storedValue = (Integer) activity.getLastNonConfigurationInstance();
- assertEquals(5, storedValue.intValue());
- }
-
- @Test
- public void startAndStopManagingCursorTracksCursors() throws Exception {
- TestActivity activity = new TestActivity();
-
- ShadowActivity shadow = shadowOf(activity);
-
- assertThat( shadow.getManagedCursors(), notNullValue() );
- assertThat( shadow.getManagedCursors().size(), equalTo(0) );
-
- Cursor c = Robolectric.newInstanceOf(SQLiteCursor.class);
- activity.startManagingCursor(c);
-
- assertThat( shadow.getManagedCursors(), notNullValue() );
- assertThat( shadow.getManagedCursors().size(), equalTo(1) );
- assertThat( shadow.getManagedCursors().get(0), sameInstance(c) );
-
- activity.stopManagingCursor(c);
-
- assertThat( shadow.getManagedCursors(), notNullValue() );
- assertThat( shadow.getManagedCursors().size(), equalTo(0) );
- }
-
- private static class TestActivity extends Activity {
- Transcript transcript = new Transcript();
-
- private boolean isRecreating = false;
-
- @Override
- public void onSaveInstanceState(Bundle outState) {
- isRecreating = true;
- transcript.add("onSaveInstanceState");
- outState.putString("TestActivityKey", "TestActivityValue");
- super.onSaveInstanceState(outState);
- }
-
- @Override
- public void onRestoreInstanceState(Bundle savedInstanceState) {
- transcript.add("onRestoreInstanceState");
- assertTrue(savedInstanceState.containsKey("TestActivityKey"));
- assertEquals("TestActivityValue", savedInstanceState.getString("TestActivityKey"));
- super.onRestoreInstanceState(savedInstanceState);
- }
-
- @Override
- public Object onRetainNonConfigurationInstance() {
- transcript.add("onRetainNonConfigurationInstance");
- return new Integer(5);
- }
-
- @Override
- public void onPause() {
- transcript.add("onPause");
- super.onPause();
- }
-
- @Override
- public void onDestroy() {
- transcript.add("onDestroy");
- super.onDestroy();
- }
-
- @Override
- public void onCreate(Bundle savedInstanceState) {
- transcript.add("onCreate");
-
- if( isRecreating ) {
- assertTrue(savedInstanceState.containsKey("TestActivityKey"));
- assertEquals("TestActivityValue", savedInstanceState.getString("TestActivityKey"));
- }
-
- super.onCreate(savedInstanceState);
- }
-
- @Override
- public void onStart() {
- transcript.add("onStart");
- super.onStart();
- }
-
- @Override
- public void onPostCreate(Bundle savedInstanceState) {
- transcript.add("onPostCreate");
- super.onPostCreate(savedInstanceState);
- }
-
- @Override
- public void onStop() {
- transcript.add("onStop");
- super.onStop();
- }
-
- @Override
- public void onResume() {
- transcript.add("onResume");
- super.onResume();
- }
- }
-
- private static class DialogCreatingActivity extends Activity {
- @Override
- protected Dialog onCreateDialog(int id) {
- return new Dialog(this);
- }
- }
-
- private static class DialogLifeCycleActivity extends Activity {
- public boolean createdDialog = false;
- public boolean preparedDialog = false;
- public boolean preparedDialogWithBundle = false;
- public Dialog dialog = null;
-
- @Override
- protected void onDestroy() {
- super.onDestroy();
- }
-
- @Override
- protected Dialog onCreateDialog(int id) {
- createdDialog = true;
- return dialog;
- }
-
- @Override
- protected void onPrepareDialog(int id, Dialog dialog) {
- preparedDialog = true;
- }
-
- @Override
- protected void onPrepareDialog(int id, Dialog dialog, Bundle bundle) {
- preparedDialogWithBundle = true;
- }
- }
-
- private static class ActivityWithOnCreateDialog extends Activity {
- boolean onCreateDialogWasCalled = false;
-
- @Override
- protected Dialog onCreateDialog(int id) {
- onCreateDialogWasCalled = true;
- return new Dialog(null);
- }
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/AdapterViewBehavior.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/AdapterViewBehavior.java
deleted file mode 100644
index 851c0bae2..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/AdapterViewBehavior.java
+++ /dev/null
@@ -1,201 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.os.Looper;
-import android.view.View;
-import android.view.ViewGroup;
-import android.widget.AdapterView;
-import android.widget.TextView;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.util.Transcript;
-
-import static com.xtremelabs.robolectric.Robolectric.*;
-import static com.xtremelabs.robolectric.matchers.TextViewHasTextMatcher.hasText;
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.CoreMatchers.not;
-import static org.hamcrest.CoreMatchers.nullValue;
-import static org.hamcrest.CoreMatchers.sameInstance;
-import static org.hamcrest.core.CombinableMatcher.both;
-import static org.junit.Assert.assertThat;
-
-public class AdapterViewBehavior {
- public static void shouldActAsAdapterView(AdapterView adapterView) throws Exception {
- Robolectric.shadowOf(Looper.getMainLooper()).pause();
-
- testSetAdapter_ShouldCauseViewsToBeRenderedAsynchronously(adapterView);
- testSetAdapter_ShouldSelectFirstItemAsynchronously(adapterView);
- testSetAdapter_ShouldFireOnNothingSelectedWhenAdapterCountIsReducedToZero(adapterView);
-
- shouldIgnoreSetSelectionCallsWithInvalidPosition(adapterView);
- shouldOnlyUpdateOnceIfInvalidatedMultipleTimes(adapterView);
-
- testSetEmptyView_ShouldHideAdapterViewIfAdapterIsNull(adapterView);
- testSetEmptyView_ShouldHideAdapterViewIfAdapterViewIsEmpty(adapterView);
- testSetEmptyView_ShouldHideEmptyViewIfAdapterViewIsNotEmpty(adapterView);
- testSetEmptyView_ShouldHideEmptyViewWhenAdapterGetsNewItem(adapterView);
- }
-
- private static void shouldIgnoreSetSelectionCallsWithInvalidPosition(AdapterView adapterView) {
- final Transcript transcript = new Transcript();
-
- adapterView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
- @Override
- public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
- transcript.add("onItemSelected fired");
- }
-
- @Override
- public void onNothingSelected(AdapterView<?> parent) {
- }
- });
-
- ShadowHandler.idleMainLooper();
- transcript.assertNoEventsSoFar();
- adapterView.setSelection(AdapterView.INVALID_POSITION);
- ShadowHandler.idleMainLooper();
- transcript.assertNoEventsSoFar();
- }
-
- private static void testSetAdapter_ShouldCauseViewsToBeRenderedAsynchronously(AdapterView adapterView) throws Exception {
- adapterView.setAdapter(new CountingAdapter(2));
-
- assertThat(adapterView.getCount(), equalTo(2));
- assertThat(adapterView.getChildCount(), equalTo(0));
-
- ShadowHandler.idleMainLooper();
- assertThat(adapterView.getChildCount(), equalTo(2));
- assertThat((TextView) adapterView.getChildAt(0), hasText("Item 0"));
- assertThat((TextView) adapterView.getChildAt(1), hasText("Item 1"));
- }
-
- private static void testSetAdapter_ShouldSelectFirstItemAsynchronously(final AdapterView adapterView) throws Exception {
- final Transcript transcript = new Transcript();
-
- adapterView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
- @Override
- public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
- assertThat(parent, sameInstance(adapterView));
- assertThat(view, both(sameInstance(adapterView.getChildAt(position))).and(not(nullValue())));
- assertThat(id, equalTo(adapterView.getAdapter().getItemId(position)));
- transcript.add("selected item " + position);
- }
-
- @Override
- public void onNothingSelected(AdapterView<?> parent) {
- }
- });
- adapterView.setAdapter(new CountingAdapter(2));
- transcript.assertNoEventsSoFar();
- ShadowHandler.idleMainLooper();
- transcript.assertEventsSoFar("selected item 0");
- }
-
- private static void testSetAdapter_ShouldFireOnNothingSelectedWhenAdapterCountIsReducedToZero(final AdapterView adapterView) throws Exception {
- final Transcript transcript = new Transcript();
-
- adapterView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
- @Override
- public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
- }
-
- @Override
- public void onNothingSelected(AdapterView<?> parent) {
- transcript.add("onNothingSelected fired");
- }
- });
- CountingAdapter adapter = new CountingAdapter(2);
- adapterView.setAdapter(adapter);
- ShadowHandler.idleMainLooper();
- transcript.assertNoEventsSoFar();
- adapter.setCount(0);
- ShadowHandler.idleMainLooper();
- transcript.assertEventsSoFar("onNothingSelected fired");
- }
-
- private static void testSetEmptyView_ShouldHideAdapterViewIfAdapterIsNull(final AdapterView adapterView) throws Exception {
- adapterView.setAdapter(null);
-
- View emptyView = new View(adapterView.getContext());
- adapterView.setEmptyView(emptyView);
-
- assertThat(adapterView.getVisibility(), is(View.GONE));
- assertThat(emptyView.getVisibility(), is(View.VISIBLE));
- }
-
- private static void testSetEmptyView_ShouldHideAdapterViewIfAdapterViewIsEmpty(final AdapterView adapterView) throws Exception {
- adapterView.setAdapter(new CountingAdapter(0));
-
- View emptyView = new View(adapterView.getContext());
- adapterView.setEmptyView(emptyView);
-
- assertThat(adapterView.getVisibility(), is(View.GONE));
- assertThat(emptyView.getVisibility(), is(View.VISIBLE));
- }
-
- private static void testSetEmptyView_ShouldHideEmptyViewIfAdapterViewIsNotEmpty(final AdapterView adapterView) throws Exception {
- adapterView.setAdapter(new CountingAdapter(1));
-
- View emptyView = new View(adapterView.getContext());
- adapterView.setEmptyView(emptyView);
-
- assertThat(adapterView.getVisibility(), is(View.VISIBLE));
- assertThat(emptyView.getVisibility(), is(View.GONE));
- }
-
- private static void testSetEmptyView_ShouldHideEmptyViewWhenAdapterGetsNewItem(final AdapterView adapterView) throws Exception {
- CountingAdapter adapter = new CountingAdapter(0);
- adapterView.setAdapter(adapter);
-
- View emptyView = new View(adapterView.getContext());
- adapterView.setEmptyView(emptyView);
-
- assertThat(adapterView.getVisibility(), is(View.GONE));
- assertThat(emptyView.getVisibility(), is(View.VISIBLE));
-
- adapter.setCount(1);
-
- ShadowHandler.idleMainLooper();
-
- assertThat(adapterView.getVisibility(), is(View.VISIBLE));
- assertThat(emptyView.getVisibility(), is(View.GONE));
- }
-
- private static void testSetEmptyView_ShouldHideAdapterViewWhenAdapterBecomesEmpty(final AdapterView adapterView) throws Exception {
- CountingAdapter adapter = new CountingAdapter(1);
- adapterView.setAdapter(adapter);
-
- View emptyView = new View(adapterView.getContext());
- adapterView.setEmptyView(emptyView);
-
- assertThat(adapterView.getVisibility(), is(View.GONE));
- assertThat(emptyView.getVisibility(), is(View.VISIBLE));
-
- adapter.setCount(0);
-
- ShadowHandler.idleMainLooper();
-
- assertThat(adapterView.getVisibility(), is(View.VISIBLE));
- assertThat(emptyView.getVisibility(), is(View.GONE));
- }
-
- private static void shouldOnlyUpdateOnceIfInvalidatedMultipleTimes(final AdapterView adapterView) {
- final Transcript transcript = new Transcript();
- CountingAdapter adapter = new CountingAdapter(2) {
- @Override
- public View getView(int position, View convertView, ViewGroup parent) {
- transcript.add("getView for " + position);
- return super.getView(position, convertView, parent);
- }
- };
- adapterView.setAdapter(adapter);
-
- transcript.assertNoEventsSoFar();
-
- adapter.notifyDataSetChanged();
- adapter.notifyDataSetChanged();
-
- ShadowHandler.idleMainLooper();
-
- transcript.assertEventsSoFar("getView for 0", "getView for 1");
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/AlarmManagerTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/AlarmManagerTest.java
deleted file mode 100644
index 5c75efec2..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/AlarmManagerTest.java
+++ /dev/null
@@ -1,162 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-
-import android.app.Activity;
-import android.app.AlarmManager;
-import android.app.PendingIntent;
-import android.content.Context;
-import android.content.Intent;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import java.util.Date;
-
-import static junit.framework.Assert.assertEquals;
-import static org.hamcrest.CoreMatchers.*;
-import static org.junit.Assert.assertThat;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class AlarmManagerTest {
-
- private MyActivity activity;
- private AlarmManager alarmManager;
- private ShadowAlarmManager shadowAlarmManager;
-
- @Before
- public void setUp() throws Exception {
- activity = new MyActivity();
- alarmManager = (AlarmManager) activity.getSystemService(Context.ALARM_SERVICE);
- shadowAlarmManager = Robolectric.shadowOf(alarmManager);
- }
-
- @After
- public void tearDown() throws Exception {
- }
-
- @Test
- public void shouldSupportSet() throws Exception {
- assertThat(shadowAlarmManager.getNextScheduledAlarm(), nullValue());
- alarmManager.set(AlarmManager.ELAPSED_REALTIME, 0, PendingIntent.getActivity(activity, 0, new Intent(activity, activity.getClass()), 0));
-
- ShadowAlarmManager.ScheduledAlarm scheduledAlarm = shadowAlarmManager.getNextScheduledAlarm();
- assertThat(scheduledAlarm, notNullValue());
- }
-
- @Test
- public void shouldSupportSetRepeating() throws Exception {
- assertThat(shadowAlarmManager.getNextScheduledAlarm(), nullValue());
- alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME, 0, AlarmManager.INTERVAL_HOUR,
- PendingIntent.getActivity(activity, 0, new Intent(activity, activity.getClass()), 0));
-
- ShadowAlarmManager.ScheduledAlarm scheduledAlarm = shadowAlarmManager.getNextScheduledAlarm();
- assertThat(scheduledAlarm, notNullValue());
- }
- @Test
- public void setShouldReplaceDuplicates() {
- alarmManager.set(AlarmManager.ELAPSED_REALTIME, 0, PendingIntent.getActivity(activity, 0, new Intent(activity, activity.getClass()), 0));
- alarmManager.set(AlarmManager.ELAPSED_REALTIME, 0, PendingIntent.getActivity(activity, 0, new Intent(activity, activity.getClass()), 0));
- assertEquals(1, shadowAlarmManager.getScheduledAlarms().size());
- }
- @Test
- public void setRepeatingShouldReplaceDuplicates() {
- alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME, 0, AlarmManager.INTERVAL_HOUR, PendingIntent.getActivity(activity, 0, new Intent(activity, activity.getClass()), 0));
- alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME, 0, AlarmManager.INTERVAL_HOUR, PendingIntent.getActivity(activity, 0, new Intent(activity, activity.getClass()), 0));
- assertEquals(1, shadowAlarmManager.getScheduledAlarms().size());
- }
-
- @Test
- public void shouldSupportGetNextScheduledAlarm() throws Exception {
- assertThat(shadowAlarmManager.getNextScheduledAlarm(), nullValue());
-
- long now = new Date().getTime();
- PendingIntent pendingIntent = PendingIntent.getActivity(activity, 0, new Intent(activity, activity.getClass()), 0);
- alarmManager.set(AlarmManager.ELAPSED_REALTIME, now, pendingIntent);
-
- ShadowAlarmManager.ScheduledAlarm scheduledAlarm = shadowAlarmManager.getNextScheduledAlarm();
- assertThat(shadowAlarmManager.getNextScheduledAlarm(), nullValue());
- assertScheduledAlarm(now, pendingIntent, scheduledAlarm);
- }
-
- @Test
- public void shouldSupportGetNextScheduledAlarmForRepeatingAlarms() throws Exception {
- assertThat(shadowAlarmManager.getNextScheduledAlarm(), nullValue());
-
- long now = new Date().getTime();
- PendingIntent pendingIntent = PendingIntent.getActivity(activity, 0, new Intent(activity, activity.getClass()), 0);
- alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME, now, AlarmManager.INTERVAL_HOUR, pendingIntent);
-
- ShadowAlarmManager.ScheduledAlarm scheduledAlarm = shadowAlarmManager.getNextScheduledAlarm();
- assertThat(shadowAlarmManager.getNextScheduledAlarm(), nullValue());
- assertRepeatingScheduledAlarm(now, AlarmManager.INTERVAL_HOUR, pendingIntent, scheduledAlarm);
- }
-
- @Test
- public void shouldSupportPeekScheduledAlarm() throws Exception {
- assertThat(shadowAlarmManager.getNextScheduledAlarm(), nullValue());
-
- long now = new Date().getTime();
- PendingIntent pendingIntent = PendingIntent.getActivity(activity, 0, new Intent(activity, activity.getClass()), 0);
- alarmManager.set(AlarmManager.ELAPSED_REALTIME, now, pendingIntent);
-
- ShadowAlarmManager.ScheduledAlarm scheduledAlarm = shadowAlarmManager.peekNextScheduledAlarm();
- assertThat(shadowAlarmManager.peekNextScheduledAlarm(), notNullValue());
- assertScheduledAlarm(now, pendingIntent, scheduledAlarm);
- }
-
- @Test
- public void cancel_removesMatchingPendingIntents() {
- Intent newIntent = new Intent(Robolectric.application.getApplicationContext(), String.class);
- PendingIntent pendingIntent = PendingIntent.getBroadcast(Robolectric.application.getApplicationContext(), 0, newIntent, PendingIntent.FLAG_UPDATE_CURRENT);
- alarmManager.set(AlarmManager.RTC, 1337, pendingIntent);
-
- Intent newIntent2 = new Intent(Robolectric.application.getApplicationContext(), Integer.class);
- PendingIntent pendingIntent2 = PendingIntent.getBroadcast(Robolectric.application.getApplicationContext(), 0, newIntent2, PendingIntent.FLAG_UPDATE_CURRENT);
- alarmManager.set(AlarmManager.RTC, 1337, pendingIntent2);
-
- assertEquals(2, shadowAlarmManager.getScheduledAlarms().size());
-
- Intent newIntent3 = new Intent(Robolectric.application.getApplicationContext(), String.class);
- PendingIntent newPendingIntent = PendingIntent.getBroadcast(Robolectric.application.getApplicationContext(), 0, newIntent3, PendingIntent.FLAG_UPDATE_CURRENT);
- alarmManager.cancel(newPendingIntent);
- assertEquals(1, shadowAlarmManager.getScheduledAlarms().size());
- }
-
- @Test
- public void cancel_removesMatchingPendingIntentsWithActions() {
- Intent newIntent = new Intent("someAction");
- PendingIntent pendingIntent = PendingIntent.getBroadcast(Robolectric.application.getApplicationContext(), 0, newIntent, 0);
- alarmManager.set(AlarmManager.RTC, 1337, pendingIntent);
- assertEquals(1, shadowAlarmManager.getScheduledAlarms().size());
- alarmManager.cancel(PendingIntent.getBroadcast(Robolectric.application, 0, new Intent("anotherAction"), 0));
- assertEquals(1, shadowAlarmManager.getScheduledAlarms().size());
- alarmManager.cancel(PendingIntent.getBroadcast(Robolectric.application, 0, new Intent("someAction"), 0));
- assertEquals(0, shadowAlarmManager.getScheduledAlarms().size());
- }
-
- private void assertScheduledAlarm(long now, PendingIntent pendingIntent,
- ShadowAlarmManager.ScheduledAlarm scheduledAlarm) {
- assertRepeatingScheduledAlarm(now, 0L, pendingIntent, scheduledAlarm);
- }
-
- private void assertRepeatingScheduledAlarm(long now, long interval, PendingIntent pendingIntent,
- ShadowAlarmManager.ScheduledAlarm scheduledAlarm) {
- assertThat(scheduledAlarm, notNullValue());
- assertThat(scheduledAlarm.operation, notNullValue());
- assertThat(scheduledAlarm.operation, sameInstance(pendingIntent));
- assertThat(scheduledAlarm.type, equalTo(AlarmManager.ELAPSED_REALTIME));
- assertThat(scheduledAlarm.triggerAtTime, equalTo(now));
- assertThat(scheduledAlarm.interval, equalTo(interval));
- }
-
- private static class MyActivity extends Activity {
- @Override
- protected void onDestroy() {
- super.onDestroy();
- }
- }
-
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/AlertDialogTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/AlertDialogTest.java
deleted file mode 100644
index d3c72fd06..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/AlertDialogTest.java
+++ /dev/null
@@ -1,384 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-import static junit.framework.Assert.assertFalse;
-import static junit.framework.Assert.assertNull;
-import static org.hamcrest.CoreMatchers.*;
-import static org.junit.Assert.*;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import android.app.Activity;
-import android.app.AlertDialog;
-import android.content.ContextWrapper;
-import android.content.DialogInterface;
-import android.view.View;
-import android.widget.ArrayAdapter;
-import android.widget.Button;
-import android.widget.EditText;
-
-import com.xtremelabs.robolectric.R;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class AlertDialogTest {
-
- @Test
- public void testBuilder() throws Exception {
- AlertDialog.Builder builder = new AlertDialog.Builder(new ContextWrapper(null));
- builder.setTitle("title").setMessage("message");
- builder.setCancelable(true);
- AlertDialog alert = builder.create();
- alert.show();
-
- assertThat(alert.isShowing(), equalTo(true));
-
- ShadowAlertDialog shadowAlertDialog = shadowOf(alert);
- assertEquals("title", shadowAlertDialog.getTitle());
- assertThat(shadowAlertDialog.getMessage(), equalTo("message"));
- assertThat(shadowAlertDialog.isCancelable(), equalTo(true));
- assertThat(shadowOf(ShadowAlertDialog.getLatestAlertDialog()), sameInstance(shadowAlertDialog));
- assertThat(ShadowAlertDialog.getLatestAlertDialog(), sameInstance(alert));
- }
-
- @Test
- public void getLatestAlertDialog_shouldReturnARealAlertDialog() throws Exception {
- assertThat(ShadowAlertDialog.getLatestAlertDialog(), nullValue());
-
- AlertDialog dialog = new AlertDialog.Builder(new ContextWrapper(null)).show();
- assertThat(ShadowAlertDialog.getLatestAlertDialog(), sameInstance(dialog));
- }
-
- @Test
- public void shouldOnlyCreateRequestedButtons() throws Exception {
- AlertDialog.Builder builder = new AlertDialog.Builder(new ContextWrapper(null));
- builder.setPositiveButton("OK", null);
- AlertDialog dialog = builder.create();
- dialog.show();
- assertThat(shadowOf(dialog).getButton(AlertDialog.BUTTON_POSITIVE), not(nullValue()));
- assertThat(shadowOf(dialog).getButton(AlertDialog.BUTTON_NEGATIVE), nullValue());
- }
-
- @Test
- public void shouldAllowNullButtonListeners() throws Exception {
- AlertDialog.Builder builder = new AlertDialog.Builder(new ContextWrapper(null));
- builder.setPositiveButton("OK", null);
- AlertDialog dialog = builder.create();
- dialog.show();
- Robolectric.clickOn(dialog.getButton(AlertDialog.BUTTON_POSITIVE));
- }
-
- @Test
- public void testSetMessageAfterCreation() {
- AlertDialog.Builder builder = new AlertDialog.Builder(new ContextWrapper(null));
- builder.setTitle("title").setMessage("message");
- AlertDialog alert = builder.create();
-
- ShadowAlertDialog shadowAlertDialog = shadowOf(alert);
- assertThat(shadowAlertDialog.getMessage(), equalTo("message"));
-
- shadowAlertDialog.setMessage("new message");
- assertThat(shadowAlertDialog.getMessage(), equalTo("new message"));
-
- shadowAlertDialog.setMessage(null);
- assertThat(shadowAlertDialog.getMessage(), nullValue());
- }
-
- @Test
- public void shouldSetMessageFromResourceId() throws Exception {
- AlertDialog.Builder builder = new AlertDialog.Builder(new Activity());
- builder.setTitle("title").setMessage(R.string.hello);
-
- AlertDialog alert = builder.create();
- ShadowAlertDialog shadowAlertDialog = shadowOf(alert);
- assertThat(shadowAlertDialog.getMessage(), equalTo("Hello"));
- }
-
- @Test
- public void shouldSetView() throws Exception {
- ContextWrapper context = new ContextWrapper(null);
- AlertDialog.Builder builder = new AlertDialog.Builder(context);
- EditText view = new EditText(context);
- builder.setView(view);
-
- AlertDialog alert = builder.create();
- assertThat(shadowOf(alert).getView(), equalTo((View) view));
- }
-
- @Test
- public void shouldSetCustomTitleView() throws Exception {
- ContextWrapper context = new ContextWrapper(null);
- AlertDialog.Builder builder = new AlertDialog.Builder(context);
- View view = new View(context);
- assertThat(builder.setCustomTitle(view), sameInstance(builder));
-
- AlertDialog alert = builder.create();
- assertThat(shadowOf(alert).getCustomTitleView(), equalTo((View) view));
- }
-
- @Test
- public void shouldSetThePositiveButtonAfterCreation() throws Exception {
- final AlertDialog alertDialog = new AlertDialog.Builder(new ContextWrapper(null))
- .setPositiveButton("Positive", null).create();
-
- TestDialogOnClickListener listener = new TestDialogOnClickListener();
- alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "More Positive", listener);
-
- final Button positiveButton = shadowOf(alertDialog).getButton(AlertDialog.BUTTON_POSITIVE);
- positiveButton.performClick();
-
- assertThat(positiveButton.getText().toString(), equalTo("More Positive"));
- assertThat(listener.clickedItem, equalTo(AlertDialog.BUTTON_POSITIVE));
- }
-
- @Test
- public void shouldSetTheNegativeButtonAfterCreation() throws Exception {
- final AlertDialog alertDialog = new AlertDialog.Builder(new ContextWrapper(null))
- .setNegativeButton("Negative", null).create();
-
- TestDialogOnClickListener listener = new TestDialogOnClickListener();
- alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "More Negative", listener);
-
- final Button negativeButton = shadowOf(alertDialog).getButton(AlertDialog.BUTTON_NEGATIVE);
- negativeButton.performClick();
-
- assertThat(negativeButton.getText().toString(), equalTo("More Negative"));
- assertThat(listener.clickedItem, equalTo(AlertDialog.BUTTON_NEGATIVE));
- }
-
- @Test
- public void shouldSetTheNeutralButtonAfterCreation() throws Exception {
- final AlertDialog alertDialog = new AlertDialog.Builder(new ContextWrapper(null))
- .setNegativeButton("Neutral", null).create();
-
- TestDialogOnClickListener listener = new TestDialogOnClickListener();
- alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "Still Neutral", listener);
-
- final Button neutralButton = shadowOf(alertDialog).getButton(AlertDialog.BUTTON_NEUTRAL);
- neutralButton.performClick();
-
- assertThat(neutralButton.getText().toString(), equalTo("Still Neutral"));
- assertThat(listener.clickedItem, equalTo(AlertDialog.BUTTON_NEUTRAL));
- }
-
- @Test
- public void clickingPositiveButtonDismissesDialog() throws Exception {
- AlertDialog alertDialog = new AlertDialog.Builder(new ContextWrapper(null))
- .setPositiveButton("Positive", null).create();
- alertDialog.show();
-
- assertTrue(alertDialog.isShowing());
- alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).performClick();
- assertFalse(alertDialog.isShowing());
- }
-
- @Test
- public void clickingNeutralButtonDismissesDialog() throws Exception {
- AlertDialog alertDialog = new AlertDialog.Builder(new ContextWrapper(null))
- .setNeutralButton("Neutral", new DialogInterface.OnClickListener() {
- @Override
- public void onClick(DialogInterface dialog, int which) {
- }
- }).create();
- alertDialog.show();
-
- assertTrue(alertDialog.isShowing());
- alertDialog.getButton(AlertDialog.BUTTON_NEUTRAL).performClick();
- assertFalse(alertDialog.isShowing());
- }
-
- @Test
- public void clickingNegativeButtonDismissesDialog() throws Exception {
- AlertDialog alertDialog = new AlertDialog.Builder(new ContextWrapper(null))
- .setNegativeButton("Negative", new DialogInterface.OnClickListener() {
- @Override
- public void onClick(DialogInterface dialog, int which) {
- }
- }).create();
- alertDialog.show();
-
- assertTrue(alertDialog.isShowing());
- alertDialog.getButton(AlertDialog.BUTTON_NEGATIVE).performClick();
- assertFalse(alertDialog.isShowing());
- }
-
- @Test
- public void testBuilderWithItemArrayViaResourceId() throws Exception {
- AlertDialog.Builder builder = new AlertDialog.Builder(new ContextWrapper(Robolectric.application));
-
- builder.setTitle("title");
- builder.setItems(R.array.alertDialogTestItems, new TestDialogOnClickListener());
- AlertDialog alert = builder.create();
- alert.show();
-
- assertThat(alert.isShowing(), equalTo(true));
-
- ShadowAlertDialog shadowAlertDialog = shadowOf(alert);
- assertThat(shadowAlertDialog.getTitle().toString(), equalTo("title"));
- assertThat(shadowAlertDialog.getItems().length, equalTo(2));
- assertEquals(shadowAlertDialog.getItems()[0], "Aloha");
- assertThat(shadowOf(ShadowAlertDialog.getLatestAlertDialog()), sameInstance(shadowAlertDialog));
- assertThat(ShadowAlertDialog.getLatestAlertDialog(), sameInstance(alert));
- }
-
-
-// @Test
-// public void testBuilderWithItemArrayCanPerformClickOnItem() throws Exception {
-// TestDialogOnClickListener listener = new TestDialogOnClickListener();
-// AlertDialog alert = new AlertDialog.Builder(new ContextWrapper(Robolectric.application))
-// .setItems(R.array.alertDialogTestItems, listener)
-// .create();
-//
-// alert.show();
-// ShadowAlertDialog shadowAlertDialog = shadowOf(alert);
-// shadowAlertDialog.clickOnItem(1);
-//
-//
-// }
-
- @Test
- public void testBuilderWithAdapter() throws Exception {
- List<Integer> list = new ArrayList<Integer>();
- list.add(99);
- list.add(88);
- list.add(77);
- ArrayAdapter<Integer> adapter = new ArrayAdapter<Integer>(Robolectric.application, R.layout.main, R.id.title, list);
-
- AlertDialog.Builder builder = new AlertDialog.Builder(new ContextWrapper(null));
- builder.setSingleChoiceItems(adapter, -1, new DialogInterface.OnClickListener() {
- @Override
- public void onClick(DialogInterface dialog, int item) {
- dialog.dismiss();
- }
- });
- AlertDialog alert = builder.create();
- alert.show();
-
- assertTrue(alert.isShowing());
- ShadowAlertDialog shadowAlertDialog = shadowOf(alert);
- assertEquals(shadowAlertDialog.getAdapter().getCount(), 3);
- assertEquals(shadowAlertDialog.getAdapter().getItem(0), 99);
- }
-
- @Test
- public void show_setsLatestAlertDialogAndLatestDialog() {
- AlertDialog alertDialog = new AlertDialog.Builder(Robolectric.application).create();
- assertNull(ShadowDialog.getLatestDialog());
- assertNull(ShadowAlertDialog.getLatestAlertDialog());
-
- alertDialog.show();
-
- assertEquals(alertDialog, ShadowDialog.getLatestDialog());
- assertEquals(alertDialog, ShadowAlertDialog.getLatestAlertDialog());
- }
-
- @Test
- public void shouldReturnTheIndexOfTheCheckedItemInASingleChoiceDialog() throws Exception {
- AlertDialog.Builder builder = new AlertDialog.Builder(new ContextWrapper(Robolectric.application));
-
- builder.setSingleChoiceItems(new String[]{"foo", "bar"}, 1, new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog, int item) {
-
- }
- });
- AlertDialog alert = builder.create();
- alert.show();
-
- assertThat(alert.isShowing(), equalTo(true));
-
- ShadowAlertDialog shadowAlertDialog = shadowOf(alert);
- assertEquals(shadowAlertDialog.getCheckedItemIndex(), 1);
- assertEquals(shadowAlertDialog.getItems()[0], "foo");
- assertThat(shadowAlertDialog.getItems().length, equalTo(2));
- assertThat(ShadowAlertDialog.getLatestAlertDialog(), sameInstance(alert));
- }
-
- @Test
- public void shouldCallTheClickListenerOfTheCheckedItemInASingleChoiceDialog() throws Exception {
- AlertDialog.Builder builder = new AlertDialog.Builder(new ContextWrapper(Robolectric.application));
-
- TestDialogOnClickListener listener = new TestDialogOnClickListener();
- builder.setSingleChoiceItems(new String[]{"foo", "bar"}, 1, listener);
-
- AlertDialog alert = builder.create();
- alert.show();
-
- ShadowAlertDialog shadowAlertDialog = shadowOf(alert);
- shadowAlertDialog.clickOnItem(0);
- assertThat(listener.clickedItem, equalTo(0));
- assertThat(shadowAlertDialog.getCheckedItemIndex(), equalTo(0));
-
- shadowAlertDialog.clickOnItem(1);
- assertThat(listener.clickedItem, equalTo(1));
- assertThat(shadowAlertDialog.getCheckedItemIndex(), equalTo(1));
-
- }
-
- @Test
- public void shouldCallTheClickListenerOfTheCheckedAdapterInASingleChoiceDialog() throws Exception {
- AlertDialog.Builder builder = new AlertDialog.Builder(new ContextWrapper(Robolectric.application));
-
- TestDialogOnClickListener listener = new TestDialogOnClickListener();
- List<Integer> list = new ArrayList<Integer>();
- list.add(1);
- list.add(2);
- list.add(3);
- ArrayAdapter<Integer> arrayAdapter = new ArrayAdapter<Integer>(Robolectric.application, R.layout.main, R.id.title, list);
- builder.setSingleChoiceItems(arrayAdapter, 1, listener);
-
- AlertDialog alert = builder.create();
- alert.show();
-
- ShadowAlertDialog shadowAlertDialog = shadowOf(alert);
- shadowAlertDialog.clickOnItem(0);
- assertThat(listener.clickedItem, equalTo(0));
- assertThat(shadowAlertDialog.getCheckedItemIndex(), equalTo(0));
-
- shadowAlertDialog.clickOnItem(1);
- assertThat(listener.clickedItem, equalTo(1));
- assertThat(shadowAlertDialog.getCheckedItemIndex(), equalTo(1));
-
- }
-
- @Test
- public void shouldFindViewsByIdIfAViewIsSet() throws Exception {
- ContextWrapper context = new ContextWrapper(null);
- AlertDialog dialog = new AlertDialog.Builder(context).create();
-
- assertThat(dialog.findViewById(99), nullValue());
-
- View view = new View(context);
- view.setId(99);
- dialog.setView(view);
- assertThat(dialog.findViewById(99), sameInstance(view));
-
- assertThat(dialog.findViewById(66), nullValue());
- }
-
- @Test
- public void shouldDelegateToDialogFindViewByIdIfViewIsNull() {
- AlertDialog dialog = new AlertDialog(Robolectric.application) {
- };
-
- assertThat(dialog.findViewById(99), nullValue());
-
- dialog.setContentView(R.layout.main);
- assertNotNull(dialog.findViewById(R.id.title));
- }
-
-
- private static class TestDialogOnClickListener implements DialogInterface.OnClickListener {
- private DialogInterface dialog;
- private int clickedItem;
-
- public void onClick(DialogInterface dialog, int item) {
- this.dialog = dialog;
- this.clickedItem = item;
- }
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/AlphaAnimationTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/AlphaAnimationTest.java
deleted file mode 100644
index ff6c50806..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/AlphaAnimationTest.java
+++ /dev/null
@@ -1,24 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.view.animation.AlphaAnimation;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-import static junit.framework.Assert.assertEquals;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class AlphaAnimationTest {
- @Test
- public void getFromAlpha_shouldReturnTheFromAlphaThatWasPassedToTheConstructor() throws Exception {
- assertEquals(99.0f, shadowOf(new AlphaAnimation(99, 88)).getFromAlpha());
- assertEquals(66.7f, shadowOf(new AlphaAnimation(66.7f, 88)).getFromAlpha());
- }
-
- @Test
- public void getToAlpha_shouldReturnTheToAlphaThatWasPassedToTheConstructor() throws Exception {
- assertEquals(88.0f, shadowOf(new AlphaAnimation(99, 88)).getToAlpha());
- assertEquals(98f, shadowOf(new AlphaAnimation(66.7f, 98)).getToAlpha());
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/AndroidHttpClientTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/AndroidHttpClientTest.java
deleted file mode 100644
index efb9ffffc..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/AndroidHttpClientTest.java
+++ /dev/null
@@ -1,42 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import static org.hamcrest.CoreMatchers.*;
-import static org.junit.Assert.assertThat;
-
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import com.xtremelabs.robolectric.util.Strings;
-import org.apache.http.HttpResponse;
-import org.apache.http.client.methods.HttpGet;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import android.net.http.AndroidHttpClient;
-
-import java.io.IOException;
-import java.io.InputStream;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class AndroidHttpClientTest {
-
- @Test
- public void testNewInstance() throws Exception {
- AndroidHttpClient client = AndroidHttpClient.newInstance("foo");
- assertThat(client, not(nullValue()));
- }
-
- @Test
- public void testNewInstanceWithContext() throws Exception {
- AndroidHttpClient client = AndroidHttpClient.newInstance("foo", Robolectric.application);
- assertThat(client, not(nullValue()));
- }
-
- @Test
- public void testExecute() throws IOException {
- AndroidHttpClient client = AndroidHttpClient.newInstance("foo");
- Robolectric.addPendingHttpResponse(200, "foo");
- HttpResponse resp = client.execute(new HttpGet("/foo"));
- assertThat(resp.getStatusLine().getStatusCode(), is(200));
- assertThat(Strings.fromStream(resp.getEntity().getContent()), equalTo("foo"));
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/AnimationSetTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/AnimationSetTest.java
deleted file mode 100644
index ef968a896..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/AnimationSetTest.java
+++ /dev/null
@@ -1,45 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import java.util.List;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import android.view.animation.*;
-
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-import static org.hamcrest.CoreMatchers.*;
-import static org.junit.Assert.assertThat;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class AnimationSetTest {
- private AnimationSet set;
- private ShadowAnimationSet shadow;
-
- @Before
- public void setUp() {
- set = new AnimationSet(true);
- shadow = shadowOf(set);
- }
-
-
- @Test
- public void testAnimationList() {
- Animation alpha = new AlphaAnimation(1f, 2f);
- Animation translate = new TranslateAnimation(1f, 2f, 3f, 4f);
- Animation rotate = new RotateAnimation(1f, 2f);
- set.addAnimation(alpha);
- set.addAnimation(translate);
- set.addAnimation(rotate);
-
- List<Animation> list = shadow.getAnimations();
- assertThat(list.size(), equalTo(3));
- assertThat(list.get(0), sameInstance(alpha));
- assertThat(list.get(1), sameInstance(translate));
- assertThat(list.get(2), sameInstance(rotate));
- }
-
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/AnimationTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/AnimationTest.java
deleted file mode 100644
index fc80eca3a..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/AnimationTest.java
+++ /dev/null
@@ -1,140 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.R;
-import android.view.animation.Animation;
-import android.view.animation.LinearInterpolator;
-import android.view.animation.Transformation;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import com.xtremelabs.robolectric.util.TestAnimationListener;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-import static org.hamcrest.CoreMatchers.*;
-import static org.junit.Assert.assertThat;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class AnimationTest {
-
- private TestAnimation animation;
- private ShadowAnimation shadow;
- private TestAnimationListener listener;
-
- @Before
- public void setUp() throws Exception {
- animation = new TestAnimation();
- shadow = shadowOf(animation);
- listener = new TestAnimationListener();
- animation.setAnimationListener(listener);
- }
-
- @Test
- public void startShouldInvokeStartCallback() throws Exception {
- assertThat(listener.wasStartCalled, equalTo(false));
- animation.start();
- assertThat(listener.wasStartCalled, equalTo(true));
- assertThat(listener.wasEndCalled, equalTo(false));
- assertThat(listener.wasRepeatCalled, equalTo(false));
- }
-
- @Test
- public void cancelShouldInvokeEndCallback() throws Exception {
- assertThat(listener.wasEndCalled, equalTo(false));
- animation.cancel();
- assertThat(listener.wasStartCalled, equalTo(false));
- assertThat(listener.wasEndCalled, equalTo(true));
- assertThat(listener.wasRepeatCalled, equalTo(false));
- }
-
- @Test
- public void invokeRepeatShouldInvokeRepeatCallback() throws Exception {
- assertThat(listener.wasRepeatCalled, equalTo(false));
- shadow.invokeRepeat();
- assertThat(listener.wasStartCalled, equalTo(false));
- assertThat(listener.wasEndCalled, equalTo(false));
- assertThat(listener.wasRepeatCalled, equalTo(true));
- }
-
- @Test
- public void invokeEndShouldInvokeEndCallback() throws Exception {
- assertThat(listener.wasEndCalled, equalTo(false));
- shadow.invokeEnd();
- assertThat(listener.wasStartCalled, equalTo(false));
- assertThat(listener.wasEndCalled, equalTo(true));
- assertThat(listener.wasRepeatCalled, equalTo(false));
- }
-
- @Test
- public void simulateAnimationEndShouldInvokeApplyTransformationWith1() throws Exception {
- assertThat(animation.interpolatedTime, equalTo(0f));
- shadow.invokeEnd();
- assertThat(animation.interpolatedTime, equalTo(1f));
- }
-
- @Test
- public void testHasStarted() throws Exception {
- assertThat(animation.hasStarted(), equalTo(false));
- animation.start();
- assertThat(animation.hasStarted(), equalTo(true));
- animation.cancel();
- assertThat(animation.hasStarted(), equalTo(false));
- }
-
- @Test
- public void testDuration() throws Exception {
- assertThat(animation.getDuration(), not(equalTo(1000l)));
- animation.setDuration(1000);
- assertThat(animation.getDuration(), equalTo(1000l));
- }
-
- @Test
- public void testInterpolation() throws Exception {
- assertThat(animation.getInterpolator(), nullValue());
- LinearInterpolator i = new LinearInterpolator();
- animation.setInterpolator(i);
- assertThat((LinearInterpolator)animation.getInterpolator(), sameInstance(i));
- }
-
- @Test
- public void testRepeatCount() throws Exception {
- assertThat(animation.getRepeatCount(), not(equalTo(5)));
- animation.setRepeatCount(5);
- assertThat(animation.getRepeatCount(), equalTo(5));
- }
-
- @Test
- public void testRepeatMode() throws Exception {
- assertThat(animation.getRepeatMode(), not(equalTo(Animation.REVERSE)));
- animation.setRepeatMode(Animation.REVERSE);
- assertThat(animation.getRepeatMode(), equalTo(Animation.REVERSE));
- }
-
- @Test
- public void testStartOffset() throws Exception {
- assertThat(animation.getStartOffset(), not(equalTo(500l)));
- animation.setStartOffset(500l);
- assertThat(animation.getStartOffset(), equalTo(500l));
- }
-
- @Test(expected=IllegalStateException.class)
- public void testNotLoadedFromResourceId() throws Exception {
- shadow.getLoadedFromResourceId();
- }
-
- @Test
- public void testLoadedFromResourceId() throws Exception {
- shadow.setLoadedFromResourceId(R.anim.fade_in);
- assertThat(shadow.getLoadedFromResourceId(), equalTo(R.anim.fade_in));
- }
-
- private class TestAnimation extends Animation {
- float interpolatedTime;
- Transformation t;
-
- @Override protected void applyTransformation(float interpolatedTime, Transformation t) {
- this.interpolatedTime = interpolatedTime;
- this.t = t;
- }
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/AnimationUtilsTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/AnimationUtilsTest.java
deleted file mode 100644
index 8aace65e3..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/AnimationUtilsTest.java
+++ /dev/null
@@ -1,30 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.R;
-import android.app.Activity;
-import android.view.animation.Animation;
-import android.view.animation.AnimationUtils;
-
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.CoreMatchers.notNullValue;
-import static org.junit.Assert.assertThat;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class AnimationUtilsTest {
-
- @Test
- public void testLoadAnimation() {
- assertThat(AnimationUtils.loadAnimation(new Activity(), 1), notNullValue());
- }
-
- @Test
- public void testLoadAnimationResourceId() {
- Animation anim = AnimationUtils.loadAnimation(new Activity(), R.anim.fade_in);
- assertThat(Robolectric.shadowOf(anim).getLoadedFromResourceId(), equalTo(R.anim.fade_in));
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/AppWidgetManagerTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/AppWidgetManagerTest.java
deleted file mode 100644
index c77b51edf..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/AppWidgetManagerTest.java
+++ /dev/null
@@ -1,108 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.appwidget.AppWidgetManager;
-import android.appwidget.AppWidgetProvider;
-import android.content.ComponentName;
-import android.content.Context;
-import android.content.ContextWrapper;
-import android.view.View;
-import android.widget.RemoteViews;
-import android.widget.TextView;
-import com.xtremelabs.robolectric.R;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-import static org.junit.Assert.*;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class AppWidgetManagerTest {
- private AppWidgetManager appWidgetManager;
- private ShadowAppWidgetManager shadowAppWidgetManager;
-
- @Before
- public void setUp() throws Exception {
- appWidgetManager = AppWidgetManager.getInstance(Robolectric.application);
- shadowAppWidgetManager = shadowOf(appWidgetManager);
- }
-
- @Test
- public void getInstance_shouldReturnSameInstance() throws Exception {
- assertNotNull(appWidgetManager);
- assertSame(AppWidgetManager.getInstance(Robolectric.application), appWidgetManager);
- assertSame(AppWidgetManager.getInstance(new ContextWrapper(Robolectric.application)), appWidgetManager);
- }
-
- @Test
- public void createWidget_shouldInflateViewAndAssignId() throws Exception {
- int widgetId = shadowAppWidgetManager.createWidget(SpanishTestAppWidgetProvider.class, R.layout.main);
- View widgetView = shadowAppWidgetManager.getViewFor(widgetId);
-
- assertEquals("Hola", ((TextView) widgetView.findViewById(R.id.subtitle)).getText());
- }
-
- @Test
- public void getViewFor_shouldReturnSameViewEveryTimeForGivenWidgetId() throws Exception {
- int widgetId = shadowAppWidgetManager.createWidget(SpanishTestAppWidgetProvider.class, R.layout.main);
- View widgetView = shadowAppWidgetManager.getViewFor(widgetId);
-
- assertNotNull(widgetView);
- assertSame(widgetView, shadowAppWidgetManager.getViewFor(widgetId));
- }
-
- @Test
- public void createWidget_shouldAllowForMultipleInstancesOfWidgets() throws Exception {
- int widgetId = shadowAppWidgetManager.createWidget(SpanishTestAppWidgetProvider.class, R.layout.main);
- View widgetView = shadowAppWidgetManager.getViewFor(widgetId);
-
- assertNotSame(widgetId,
- shadowAppWidgetManager.createWidget(SpanishTestAppWidgetProvider.class, R.layout.main));
- assertNotSame(widgetView,
- shadowAppWidgetManager.getViewFor(shadowAppWidgetManager.createWidget(SpanishTestAppWidgetProvider.class, R.layout.main)));
- }
-
- @Test
- public void shouldReplaceLayoutIfAndOnlyIfLayoutIdIsDifferent() throws Exception {
- int widgetId = shadowAppWidgetManager.createWidget(SpanishTestAppWidgetProvider.class, R.layout.main);
- View originalWidgetView = shadowAppWidgetManager.getViewFor(widgetId);
- assertContains("Main Layout", originalWidgetView);
-
- appWidgetManager.updateAppWidget(widgetId, new RemoteViews("whatevs", R.layout.main));
- assertSame(originalWidgetView, shadowAppWidgetManager.getViewFor(widgetId));
-
- appWidgetManager.updateAppWidget(widgetId, new RemoteViews("whatevs", R.layout.media));
- assertNotSame(originalWidgetView, shadowAppWidgetManager.getViewFor(widgetId));
-
- View mediaWidgetView = shadowAppWidgetManager.getViewFor(widgetId);
- assertContains("Media Layout", mediaWidgetView);
- }
-
- @Test
- public void getAppWidgetIds() {
- int expectedWidgetId = shadowAppWidgetManager.createWidget(SpanishTestAppWidgetProvider.class, R.layout.main);
-
- int[] appWidgetIds = appWidgetManager.getAppWidgetIds(
- new ComponentName(
- SpanishTestAppWidgetProvider.class.getPackage().getName(),
- SpanishTestAppWidgetProvider.class.getName()));
-
- assertEquals(1, appWidgetIds.length);
- assertEquals(expectedWidgetId, appWidgetIds[0]);
- }
-
- private void assertContains(String expectedText, View view) {
- String actualText = shadowOf(view).innerText();
- assertTrue("Expected <" + actualText + "> to contain <" + expectedText + ">", actualText.contains(expectedText));
- }
-
- public static class SpanishTestAppWidgetProvider extends AppWidgetProvider {
- @Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
- RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.main);
- remoteViews.setTextViewText(R.id.subtitle, "Hola");
- appWidgetManager.updateAppWidget(appWidgetIds, remoteViews);
- }
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ApplicationTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/ApplicationTest.java
deleted file mode 100644
index c65a381c6..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ApplicationTest.java
+++ /dev/null
@@ -1,311 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.app.Activity;
-import android.app.Application;
-import android.content.BroadcastReceiver;
-import android.content.ComponentName;
-import android.content.Context;
-import android.content.ContextWrapper;
-import android.content.Intent;
-import android.content.IntentFilter;
-import android.os.IBinder;
-import android.os.IInterface;
-import android.os.Parcel;
-import android.os.RemoteException;
-import com.xtremelabs.robolectric.ApplicationResolver;
-import com.xtremelabs.robolectric.R;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import com.xtremelabs.robolectric.res.ResourceLoader;
-import com.xtremelabs.robolectric.res.StringResourceLoader;
-import com.xtremelabs.robolectric.util.TestBroadcastReceiver;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import java.io.FileDescriptor;
-import java.util.List;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-import static com.xtremelabs.robolectric.util.TestUtil.newConfig;
-import static junit.framework.Assert.assertEquals;
-import static junit.framework.Assert.assertTrue;
-import static org.hamcrest.CoreMatchers.sameInstance;
-import static org.hamcrest.core.IsInstanceOf.instanceOf;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertThat;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class ApplicationTest {
- @Before
- public void setUp() throws Exception {
- Robolectric.application = new Application();
- }
-
- @Test
- public void shouldBeAContext() throws Exception {
- assertThat(new Activity().getApplication(), sameInstance(Robolectric.application));
- assertThat(new Activity().getApplication().getApplicationContext(), sameInstance((Context) Robolectric.application));
- }
-
- @Test
- public void shouldBeBindableToAResourceLoader() throws Exception {
- ResourceLoader resourceLoader1 = new ResourceLoader(mock(StringResourceLoader.class)) {
- };
- when(resourceLoader1.getStringValue(R.id.title)).thenReturn("title from resourceLoader1");
- Application app1 = ShadowApplication.bind(new Application(), resourceLoader1);
-
- ResourceLoader resourceLoader2 = new ResourceLoader(mock(StringResourceLoader.class)) {
- };
- when(resourceLoader2.getStringValue(R.id.title)).thenReturn("title from resourceLoader2");
- Application app2 = ShadowApplication.bind(new Application(), resourceLoader2);
-
- assertEquals("title from resourceLoader1", new ContextWrapper(app1).getResources().getString(R.id.title));
- assertEquals("title from resourceLoader2", new ContextWrapper(app2).getResources().getString(R.id.title));
- }
-
- @Test
- public void shouldProvideServices() throws Exception {
- checkSystemService(Context.LAYOUT_INFLATER_SERVICE, android.view.LayoutInflater.class);
- checkSystemService(Context.ACTIVITY_SERVICE, android.app.ActivityManager.class);
- checkSystemService(Context.POWER_SERVICE, android.os.PowerManager.class);
- checkSystemService(Context.ALARM_SERVICE, android.app.AlarmManager.class);
- checkSystemService(Context.NOTIFICATION_SERVICE, android.app.NotificationManager.class);
- checkSystemService(Context.KEYGUARD_SERVICE, android.app.KeyguardManager.class);
- checkSystemService(Context.LOCATION_SERVICE, android.location.LocationManager.class);
- checkSystemService(Context.SEARCH_SERVICE, android.app.SearchManager.class);
- checkSystemService(Context.SENSOR_SERVICE, android.hardware.TestSensorManager.class);
- checkSystemService(Context.STORAGE_SERVICE, android.os.storage.StorageManager.class);
- checkSystemService(Context.VIBRATOR_SERVICE, android.os.TestVibrator.class);
-// checkSystemService(Context.CONNECTIVITY_SERVICE, android.net.ConnectivityManager.class);
-// checkSystemService(Context.WIFI_SERVICE, android.net.wifi.WifiManager.class);
-// checkSystemService(Context.AUDIO_SERVICE, android.media.AudioManager.class);
-// checkSystemService(Context.TELEPHONY_SERVICE, android.telephony.TelephonyManager.class);
-// checkSystemService(Context.INPUT_METHOD_SERVICE, android.view.inputmethod.InputMethodManager.class);
-// checkSystemService(Context.UI_MODE_SERVICE, android.app.UiModeManager.class);
-// checkSystemService(Context.DOWNLOAD_SERVICE, android.app.DownloadManager.class);
- }
-
- private void checkSystemService(String name, Class expectedClass) {
- Object systemService = Robolectric.application.getSystemService(name);
- assertThat(systemService, instanceOf(expectedClass));
- assertThat(systemService, sameInstance(Robolectric.application.getSystemService(name)));
- }
-
- @Test
- public void packageManager_shouldKnowPackageName() throws Exception {
- Application application = new ApplicationResolver(newConfig("TestAndroidManifestWithPackageName.xml")).resolveApplication();
- assertEquals("com.wacka.wa", application.getPackageManager().getPackageInfo("com.wacka.wa", 0).packageName);
- }
-
- @Test
- public void packageManager_shouldKnowApplicationName() throws Exception {
- Application application = new ApplicationResolver(newConfig("TestAndroidManifestWithAppName.xml")).resolveApplication();
- assertEquals("com.xtremelabs.robolectric.TestApplication",
- application.getPackageManager().getApplicationInfo("com.xtremelabs.robolectric", 0).name);
- }
-
- @Test
- public void bindServiceShouldCallOnServiceConnectedWhenNotPaused() {
- Robolectric.pauseMainLooper();
- ComponentName expectedComponentName = new ComponentName("", "");
- NullBinder expectedBinder = new NullBinder();
- Robolectric.shadowOf(Robolectric.application).setComponentNameAndServiceForBindService(expectedComponentName, expectedBinder);
-
- TestService service = new TestService();
- assertTrue(Robolectric.application.bindService(new Intent(""), service, Context.BIND_AUTO_CREATE));
-
- assertNull(service.name);
- assertNull(service.service);
-
- Robolectric.unPauseMainLooper();
-
- assertEquals(expectedComponentName, service.name);
- assertEquals(expectedBinder, service.service);
- }
-
- @Test
- public void unbindServiceShouldCallOnServiceDisconnectedWhenNotPaused() {
- TestService service = new TestService();
- ComponentName expectedComponentName = new ComponentName("", "");
- NullBinder expectedBinder = new NullBinder();
- Robolectric.shadowOf(Robolectric.application).setComponentNameAndServiceForBindService(expectedComponentName, expectedBinder);
- Robolectric.application.bindService(new Intent(""), service, Context.BIND_AUTO_CREATE);
- Robolectric.pauseMainLooper();
-
- Robolectric.application.unbindService(service);
- assertNull(service.nameUnbound);
- Robolectric.unPauseMainLooper();
- assertEquals(expectedComponentName, service.nameUnbound);
- }
-
- @Test
- public void unbindServiceAddsEntryToUnboundServicesCollection() {
- TestService service = new TestService();
- ComponentName expectedComponentName = new ComponentName("", "");
- NullBinder expectedBinder = new NullBinder();
- final ShadowApplication shadowApplication = Robolectric.shadowOf(Robolectric.application);
- shadowApplication.setComponentNameAndServiceForBindService(expectedComponentName, expectedBinder);
- Robolectric.application.bindService(new Intent(""), service, Context.BIND_AUTO_CREATE);
- Robolectric.application.unbindService(service);
- assertEquals(1, shadowApplication.getUnboundServiceConnections().size());
- assertEquals(service, shadowApplication.getUnboundServiceConnections().get(0));
- }
-
- @Test
- public void declaringServiceUnbindableMakesBindServiceReturnFalse() {
- Robolectric.pauseMainLooper();
- TestService service = new TestService();
- ComponentName expectedComponentName = new ComponentName("", "");
- NullBinder expectedBinder = new NullBinder();
- final ShadowApplication shadowApplication = Robolectric.shadowOf(Robolectric.application);
- shadowApplication.setComponentNameAndServiceForBindService(expectedComponentName, expectedBinder);
- shadowApplication.declareActionUnbindable("refuseToBind");
- assertFalse(Robolectric.application.bindService(new Intent("refuseToBind"), service, Context.BIND_AUTO_CREATE));
- Robolectric.unPauseMainLooper();
- assertNull(service.name);
- assertNull(service.service);
- assertNull(shadowApplication.peekNextStartedService());
- }
-
- @Test
- public void shouldHaveStoppedServiceIntentAndIndicateServiceWasntRunning() {
- ShadowApplication shadowApplication = Robolectric.shadowOf(Robolectric.application);
-
- Activity activity = new Activity();
-
- Intent intent = getSomeActionIntent("some.action");
-
- boolean wasRunning = activity.stopService(intent);
-
- assertFalse(wasRunning);
- assertEquals(intent, shadowApplication.getNextStoppedService());
- }
-
- private Intent getSomeActionIntent(String action) {
- Intent intent = new Intent();
- intent.setAction(action);
- return intent;
- }
-
- @Test
- public void shouldHaveStoppedServiceIntentAndIndicateServiceWasRunning() {
- ShadowApplication shadowApplication = shadowOf(Robolectric.application);
-
- Activity activity = new Activity();
-
- Intent intent = getSomeActionIntent("some.action");
-
- activity.startService(intent);
-
- boolean wasRunning = activity.stopService(intent);
-
- assertTrue(wasRunning);
- assertEquals(intent, shadowApplication.getNextStoppedService());
- }
-
- @Test
- public void shouldClearStartedServiceIntents() {
- ShadowApplication shadowApplication = shadowOf(Robolectric.application);
- shadowApplication.startService(getSomeActionIntent("some.action"));
- shadowApplication.startService(getSomeActionIntent("another.action"));
-
- shadowApplication.clearStartedServices();
-
- assertNull(shadowApplication.getNextStartedService());
- }
-
- @Test(expected = IllegalStateException.class)
- public void shouldThrowIfContainsRegisteredReceiverOfAction() {
- Activity activity = new Activity();
- activity.registerReceiver(new TestBroadcastReceiver(), new IntentFilter("Foo"));
-
- shadowOf(Robolectric.application).assertNoBroadcastListenersOfActionRegistered(activity, "Foo");
- }
-
- @Test
- public void shouldNotThrowIfDoesNotContainsRegisteredReceiverOfAction() {
- Activity activity = new Activity();
- activity.registerReceiver(new TestBroadcastReceiver(), new IntentFilter("Foo"));
-
- shadowOf(Robolectric.application).assertNoBroadcastListenersOfActionRegistered(activity, "Bar");
- }
-
- @Test
- public void canAnswerIfReceiverIsRegisteredForIntent() throws Exception {
- BroadcastReceiver expectedReceiver = new TestBroadcastReceiver();
- ShadowApplication shadowApplication = shadowOf(Robolectric.application);
- assertFalse(shadowApplication.hasReceiverForIntent(new Intent("Foo")));
- Robolectric.application.registerReceiver(expectedReceiver, new IntentFilter("Foo"));
-
- assertTrue(shadowApplication.hasReceiverForIntent(new Intent("Foo")));
- }
-
- @Test
- public void canFindAllReceiversForAnIntent() throws Exception {
- BroadcastReceiver expectedReceiver = new TestBroadcastReceiver();
- ShadowApplication shadowApplication = shadowOf(Robolectric.application);
- assertFalse(shadowApplication.hasReceiverForIntent(new Intent("Foo")));
- Robolectric.application.registerReceiver(expectedReceiver, new IntentFilter("Foo"));
- Robolectric.application.registerReceiver(expectedReceiver, new IntentFilter("Foo"));
-
- assertTrue(shadowApplication.getReceiversForIntent(new Intent("Foo")).size() == 2);
- }
-
- @Test
- public void broadcasts_shouldBeLogged() {
- Intent broadcastIntent = new Intent("foo");
- Robolectric.application.sendBroadcast(broadcastIntent);
-
- List<Intent> broadcastIntents = shadowOf(Robolectric.application).getBroadcastIntents();
- assertTrue(broadcastIntents.size() == 1);
- assertEquals(broadcastIntent, broadcastIntents.get(0));
- }
-
- private static class NullBinder implements IBinder {
- @Override
- public String getInterfaceDescriptor() throws RemoteException {
- return null;
- }
-
- @Override
- public boolean pingBinder() {
- return false;
- }
-
- @Override
- public boolean isBinderAlive() {
- return false;
- }
-
- @Override
- public IInterface queryLocalInterface(String descriptor) {
- return null;
- }
-
- @Override
- public void dump(FileDescriptor fd, String[] args) throws RemoteException {
- }
-
- @Override
- public boolean transact(int code, Parcel data, Parcel reply, int flags) throws RemoteException {
- return false;
- }
-
- @Override
- public void linkToDeath(DeathRecipient recipient, int flags) throws RemoteException {
- }
-
- @Override
- public boolean unlinkToDeath(DeathRecipient recipient, int flags) {
- return false;
- }
-
- @Override
- public void dumpAsync(FileDescriptor fd, String[] args) throws RemoteException {
- }
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ArrayAdapterTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/ArrayAdapterTest.java
deleted file mode 100644
index 7597c538f..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ArrayAdapterTest.java
+++ /dev/null
@@ -1,161 +0,0 @@
-// Copyright 2010 Google Inc. All Rights Reserved.
-
-package com.xtremelabs.robolectric.shadows;
-
-import static org.junit.Assert.assertEquals;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.verifyNoMoreInteractions;
-
-import android.database.DataSetObserver;
-import android.view.View;
-import android.widget.ArrayAdapter;
-import android.widget.ListView;
-import android.widget.TextView;
-
-import com.xtremelabs.robolectric.R;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class ArrayAdapterTest {
- private ArrayAdapter<Integer> arrayAdapter;
-
- @Before public void setUp() throws Exception {
- List<Integer> list = new ArrayList<Integer>();
- list.add(1);
- list.add(2);
- list.add(3);
-
- arrayAdapter = new ArrayAdapter<Integer>(Robolectric.application, 0, list);
- }
-
- @Test
- public void verifyContext() {
- assertEquals(Robolectric.application, arrayAdapter.getContext());
- }
-
- @Test
- public void verifyListContent() {
- assertEquals(3, arrayAdapter.getCount());
- assertEquals(new Integer(1), arrayAdapter.getItem(0));
- assertEquals(new Integer(2), arrayAdapter.getItem(1));
- assertEquals(new Integer(3), arrayAdapter.getItem(2));
- }
-
- @Test
- public void usesTextViewResourceIdToSetTextWithinListItemView() throws Exception {
- ListView parent = new ListView(Robolectric.application);
- ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(Robolectric.application, R.layout.main, R.id.title, new String[] { "first value" });
- View listItemView = arrayAdapter.getView(0, null, parent);
- TextView titleTextView = (TextView) listItemView.findViewById(R.id.title);
- assertEquals("first value", titleTextView.getText().toString());
- }
-
- @Test
- public void hasTheCorrectConstructorResourceIDs() {
- ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(Robolectric.application, R.id.title, new String[] { "first value" });
-
- //this assertion may look a little backwards since R.id.title is labeled
- //textViewResourceId in the constructor parameter list, but the output is correct.
- Assert.assertTrue(Robolectric.shadowOf(arrayAdapter).getResourceId()==R.id.title);
- Assert.assertTrue(Robolectric.shadowOf(arrayAdapter).getTextViewResourceId()!=R.id.title);
- Assert.assertTrue(Robolectric.shadowOf(arrayAdapter).getTextViewResourceId()==0);
-
- ArrayAdapter<String> arrayAdapter2 = new ArrayAdapter<String>(Robolectric.application, R.id.title);
-
- //this assertion may look a little backwards since R.id.title is labeled
- //textViewResourceId in the constructor parameter list, but the output is correct.
- Assert.assertTrue(Robolectric.shadowOf(arrayAdapter2).getResourceId()==R.id.title);
- Assert.assertTrue(Robolectric.shadowOf(arrayAdapter2).getTextViewResourceId()!=R.id.title);
- Assert.assertTrue(Robolectric.shadowOf(arrayAdapter2).getTextViewResourceId()==0);
-
- ArrayAdapter<String> arrayAdapter3 = new ArrayAdapter<String>(Robolectric.application, R.id.title, Arrays.asList(new String[] { "first value" }));
-
- //this assertion may look a little backwards since R.id.title is labeled
- //textViewResourceId in the constructor parameter list, but the output is correct.
- Assert.assertTrue(Robolectric.shadowOf(arrayAdapter3).getResourceId()==R.id.title);
- Assert.assertTrue(Robolectric.shadowOf(arrayAdapter3).getTextViewResourceId()!=R.id.title);
- Assert.assertTrue(Robolectric.shadowOf(arrayAdapter3).getTextViewResourceId()==0);
- }
-
- @Test
- public void shouldClear() throws Exception {
- arrayAdapter.clear();
- assertEquals(0, arrayAdapter.getCount());
- }
-
- @Test
- public void test_remove() throws Exception {
- Integer firstItem = arrayAdapter.getItem(0);
- assertEquals(3, arrayAdapter.getCount());
- assertEquals(new Integer(1), firstItem);
-
- arrayAdapter.remove(firstItem);
-
- assertEquals(2, arrayAdapter.getCount());
- assertEquals(new Integer(2), arrayAdapter.getItem(0));
- assertEquals(new Integer(3), arrayAdapter.getItem(1));
- }
-
- @Test
- public void testRemoveNotifiesDataSetObservers() {
- DataSetObserver observer = mock(DataSetObserver.class);
- arrayAdapter.registerDataSetObserver(observer);
- Integer firstItem = arrayAdapter.getItem(0);
-
- arrayAdapter.remove(firstItem);
-
- verify(observer).onChanged();
- }
-
- @Test
- public void testClearNotifiesDataSetObservers() {
- DataSetObserver observer = mock(DataSetObserver.class);
- arrayAdapter.registerDataSetObserver(observer);
-
- arrayAdapter.clear();
-
- verify(observer).onChanged();
- }
-
- @Test
- public void testAddNotifiesDataSetObservers() {
- DataSetObserver observer = mock(DataSetObserver.class);
- arrayAdapter.registerDataSetObserver(observer);
-
- arrayAdapter.add(27);
-
- verify(observer).onChanged();
- }
-
- @Test
- public void testInsertNotifiesDataSetObservers() {
- DataSetObserver observer = mock(DataSetObserver.class);
- arrayAdapter.registerDataSetObserver(observer);
-
- arrayAdapter.insert(27, 1);
-
- verify(observer).onChanged();
- }
-
- @Test
- public void testInsertDoesNotNotifyDataSetObserversWhenDisabled() {
- DataSetObserver observer = mock(DataSetObserver.class);
- arrayAdapter.registerDataSetObserver(observer);
-
- arrayAdapter.setNotifyOnChange(false);
- arrayAdapter.insert(27, 1);
-
- verifyNoMoreInteractions(observer);
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/AssetManagerTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/AssetManagerTest.java
deleted file mode 100644
index f8b69886b..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/AssetManagerTest.java
+++ /dev/null
@@ -1,87 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.app.Activity;
-import android.content.res.AssetManager;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import com.xtremelabs.robolectric.util.Strings;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.Arrays;
-import java.util.List;
-
-import static org.junit.Assert.*;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class AssetManagerTest {
- AssetManager assetManager;
- String sp = System.getProperty("file.separator");
-
- @Before
- public void setUp() throws Exception {
- assetManager = new Activity().getAssets();
- }
-
- @Test
- public void assertGetAssetsNotNull() {
- assertNotNull(assetManager);
-
- assetManager = Robolectric.application.getAssets();
- assertNotNull(assetManager);
-
- assetManager = Robolectric.application.getResources().getAssets();
- assertNotNull(assetManager);
- }
-
- @Test
- public void assetsPathListing() throws IOException {
- List<String> files;
- String testPath;
-
- testPath = "";
- files = Arrays.asList(assetManager.list(testPath));
- assertTrue(files.contains("docs"));
- assertTrue(files.contains("assetsHome.txt"));
-
- testPath = "docs";
- files = Arrays.asList(assetManager.list(testPath));
- assertTrue(files.contains("extra"));
-
- testPath = "docs" + sp + "extra";
- files = Arrays.asList(assetManager.list(testPath));
- assertTrue(files.contains("testing"));
-
- testPath = "docs" + sp + "extra" + sp + "testing";
- files = Arrays.asList(assetManager.list(testPath));
- assertTrue(files.contains("hello.txt"));
-
- testPath = "assetsHome.txt";
- files = Arrays.asList(assetManager.list(testPath));
- assertFalse(files.contains(testPath));
-
- testPath = "bogus.file";
- files = Arrays.asList(assetManager.list(testPath));
- assertEquals(0, files.size());
- }
-
- @Test
- public void assetsInputStreams() throws IOException {
- String testPath;
- String fileContents;
- InputStream inputStream;
-
- testPath = "assetsHome.txt";
- inputStream = assetManager.open(testPath);
- fileContents = Strings.fromStream(inputStream);
- assertEquals("assetsHome!", fileContents);
-
- testPath = "docs" + sp + "extra" + sp + "testing" + sp + "hello.txt";
- inputStream = assetManager.open(testPath);
- fileContents = Strings.fromStream(inputStream);
- assertEquals("hello!", fileContents);
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/AsyncTaskTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/AsyncTaskTest.java
deleted file mode 100644
index 54d832d25..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/AsyncTaskTest.java
+++ /dev/null
@@ -1,145 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import java.util.concurrent.TimeUnit;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import android.os.AsyncTask;
-
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import com.xtremelabs.robolectric.util.Join;
-import com.xtremelabs.robolectric.util.Transcript;
-
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.CoreMatchers.is;
-import static org.junit.Assert.*;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class AsyncTaskTest {
- private Transcript transcript;
-
- @Before public void setUp() throws Exception {
- transcript = new Transcript();
- Robolectric.getBackgroundScheduler().pause();
- Robolectric.getUiThreadScheduler().pause();
- }
-
- @Test
- public void testNormalFlow() throws Exception {
- AsyncTask<String, String, String> asyncTask = new MyAsyncTask();
-
- asyncTask.execute("a", "b");
- transcript.assertEventsSoFar("onPreExecute");
-
- Robolectric.runBackgroundTasks();
- transcript.assertEventsSoFar("doInBackground a, b");
- assertEquals("Result should get stored in the AsyncTask", "c", asyncTask.get(100, TimeUnit.MILLISECONDS));
-
- Robolectric.runUiThreadTasks();
- transcript.assertEventsSoFar("onPostExecute c");
- }
-
- @Test
- public void testCancelBeforeBackground() throws Exception {
- AsyncTask<String, String, String> asyncTask = new MyAsyncTask();
-
- asyncTask.execute("a", "b");
- transcript.assertEventsSoFar("onPreExecute");
-
- assertTrue(asyncTask.cancel(true));
- assertTrue(asyncTask.isCancelled());
-
- Robolectric.runBackgroundTasks();
- transcript.assertNoEventsSoFar();
-
- Robolectric.runUiThreadTasks();
- transcript.assertEventsSoFar("onCancelled");
- }
-
- @Test
- public void testCancelBeforePostExecute() throws Exception {
- AsyncTask<String, String, String> asyncTask = new MyAsyncTask();
-
- asyncTask.execute("a", "b");
- transcript.assertEventsSoFar("onPreExecute");
-
- Robolectric.runBackgroundTasks();
- transcript.assertEventsSoFar("doInBackground a, b");
- assertEquals("Result should get stored in the AsyncTask", "c", asyncTask.get(100, TimeUnit.MILLISECONDS));
-
- assertFalse(asyncTask.cancel(true));
- assertFalse(asyncTask.isCancelled());
-
- Robolectric.runUiThreadTasks();
- transcript.assertEventsSoFar("onPostExecute c");
- }
-
- @Test
- public void progressUpdatesAreQueuedUntilBackgroundThreadFinishes() throws Exception {
- AsyncTask<String, String, String> asyncTask = new MyAsyncTask() {
- @Override protected String doInBackground(String... strings) {
- publishProgress("33%");
- publishProgress("66%");
- publishProgress("99%");
- return "done";
- }
- };
-
- asyncTask.execute("a", "b");
- transcript.assertEventsSoFar("onPreExecute");
-
- Robolectric.runBackgroundTasks();
- transcript.assertNoEventsSoFar();
- assertEquals("Result should get stored in the AsyncTask", "done", asyncTask.get(100, TimeUnit.MILLISECONDS));
-
- Robolectric.runUiThreadTasks();
- transcript.assertEventsSoFar(
- "onProgressUpdate 33%",
- "onProgressUpdate 66%",
- "onProgressUpdate 99%",
- "onPostExecute done");
- }
-
- @Test
- public void executeReturnsAsyncTask() throws Exception {
- Robolectric.getBackgroundScheduler().unPause();
- AsyncTask<String, String, String> asyncTask = new MyAsyncTask();
- assertThat(asyncTask.execute("a", "b").get(), equalTo("c"));
- }
-
- @Test
- public void shouldGetStatusForAsyncTask() throws Exception {
- AsyncTask<String, String, String> asyncTask = new MyAsyncTask();
- assertThat(asyncTask.getStatus(), is(AsyncTask.Status.PENDING));
- asyncTask.execute("a");
- assertThat(asyncTask.getStatus(), is(AsyncTask.Status.RUNNING));
- Robolectric.getBackgroundScheduler().unPause();
- assertThat(asyncTask.getStatus(), is(AsyncTask.Status.FINISHED));
- }
-
- private class MyAsyncTask extends AsyncTask<String, String, String> {
- @Override protected void onPreExecute() {
- transcript.add("onPreExecute");
- }
-
- @Override protected String doInBackground(String... strings) {
- transcript.add("doInBackground " + Join.join(", ", (Object[]) strings));
- return "c";
- }
-
- @Override protected void onProgressUpdate(String... values) {
- transcript.add("onProgressUpdate " + Join.join(", ", (Object[]) values));
- }
-
- @Override protected void onPostExecute(String s) {
- transcript.add("onPostExecute " + s);
- }
-
- @Override protected void onCancelled() {
- transcript.add("onCancelled");
- }
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/AudioManagerTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/AudioManagerTest.java
deleted file mode 100644
index 267344eb3..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/AudioManagerTest.java
+++ /dev/null
@@ -1,81 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-
-import android.media.AudioManager;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static org.junit.Assert.*;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class AudioManagerTest {
- private AudioManager audioManager;
- private ShadowAudioManager shadowAudioManager;
- private AudioManager.OnAudioFocusChangeListener listener;
-
- @Before
- public void setUp() throws Exception {
- audioManager = Robolectric.newInstanceOf(AudioManager.class);
- shadowAudioManager = Robolectric.shadowOf(audioManager);
- listener = new AudioManager.OnAudioFocusChangeListener() {
- @Override
- public void onAudioFocusChange(int focusChange) {
- }
- };
- }
-
- @Test
- public void requestAudioFocus_shouldRecordArgumentsOfMostRecentCall() {
- assertNull(shadowAudioManager.getLastAudioFocusRequest());
- audioManager.requestAudioFocus(listener, 999, 888);
- assertSame(listener, shadowAudioManager.getLastAudioFocusRequest().listener);
- assertEquals(999, shadowAudioManager.getLastAudioFocusRequest().streamType);
- assertEquals(888, shadowAudioManager.getLastAudioFocusRequest().durationHint);
- }
-
- @Test
- public void requestAudioFocus_shouldReturnTheSpecifiedValue() {
- int value = audioManager.requestAudioFocus(listener, 999, 888);
- assertEquals(AudioManager.AUDIOFOCUS_REQUEST_GRANTED, value);
-
- shadowAudioManager.setNextFocusRequestResponse(AudioManager.AUDIOFOCUS_REQUEST_FAILED);
-
- value = audioManager.requestAudioFocus(listener, 999, 888);
- assertEquals(AudioManager.AUDIOFOCUS_REQUEST_FAILED, value);
- }
-
- @Test
- public void abandonAudioFocus_shouldRecordTheListenerOfTheMostRecentCall() {
- audioManager.abandonAudioFocus(null);
- assertNull(shadowAudioManager.getLastAbandonedAudioFocusListener());
-
- audioManager.abandonAudioFocus(listener);
- assertSame(listener, shadowAudioManager.getLastAbandonedAudioFocusListener());
- }
-
- @Test
- public void shouldGetStreamMaxVolume() throws Exception {
- shadowAudioManager.setStreamMaxVolume(45);
-
- assertEquals(45, audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC));
- }
-
- @Test
- public void shouldGetVolume() throws Exception {
- shadowAudioManager.setStreamVolume(5);
-
- assertEquals(5, audioManager.getStreamVolume(AudioManager.STREAM_MUSIC));
- }
-
- @Test
- public void shouldSetVolume() throws Exception {
- audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 8, 0);
-
- assertEquals(8, audioManager.getStreamVolume(AudioManager.STREAM_MUSIC));
- assertEquals(8, shadowAudioManager.getStreamVolume());
- }
-
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/Base64Test.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/Base64Test.java
deleted file mode 100644
index dcd91d4ee..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/Base64Test.java
+++ /dev/null
@@ -1,32 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.util.Base64;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.CoreMatchers.not;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertArrayEquals;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class Base64Test {
-
- private static final String base64Encoded = "YmFzZTY0IGVuY29kZWQgc3RyaW5n";
- private static final String base64Decoded = "base64 encoded string";
-
- @Test
- public void testEncodeToString() {
- String result = Base64.encodeToString(base64Decoded.getBytes(), Base64.DEFAULT);
-
- assertEquals(result, base64Encoded);
- }
-
- @Test
- public void testDecode() {
- byte[] result = Base64.decode(base64Encoded, Base64.DEFAULT);
-
- assertArrayEquals(result, base64Decoded.getBytes());
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/BaseAdapterTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/BaseAdapterTest.java
deleted file mode 100644
index d4cebd6bf..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/BaseAdapterTest.java
+++ /dev/null
@@ -1,52 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.view.View;
-import android.view.ViewGroup;
-import android.widget.BaseAdapter;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-import static junit.framework.Assert.assertFalse;
-import static junit.framework.Assert.assertTrue;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class BaseAdapterTest {
- @Test
- public void shouldRecordNotifyDataSetChanged() throws Exception {
- BaseAdapter adapter = new TestBaseAdapter();
- adapter.notifyDataSetChanged();
- assertTrue(shadowOf(adapter).wasNotifyDataSetChangedCalled());
- }
-
- @Test
- public void canResetNotifyDataSetChangedFlag() throws Exception {
- BaseAdapter adapter = new TestBaseAdapter();
- adapter.notifyDataSetChanged();
- shadowOf(adapter).clearWasDataSetChangedCalledFlag();
- assertFalse(shadowOf(adapter).wasNotifyDataSetChangedCalled());
- }
-
- private static class TestBaseAdapter extends BaseAdapter {
- @Override
- public int getCount() {
- return 0;
- }
-
- @Override
- public Object getItem(int position) {
- return null;
- }
-
- @Override
- public long getItemId(int position) {
- return 0;
- }
-
- @Override
- public View getView(int position, View convertView, ViewGroup parent) {
- return null;
- }
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/BinderTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/BinderTest.java
deleted file mode 100644
index 2b5ba9a9d..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/BinderTest.java
+++ /dev/null
@@ -1,30 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import static org.junit.Assert.assertThat;
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.CoreMatchers.not;
-
-import android.os.Binder;
-
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class BinderTest {
-
- @Test
- public void testSetCallingPid() {
- ShadowBinder.setCallingPid(47);
-
- assertThat(Binder.getCallingPid(), equalTo(47));
- }
-
- @Test
- public void testCallingProcessIsJvmProcessId() {
- int pid = Binder.getCallingPid();
-
- assertThat(pid, not(equalTo(0)));
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/BitmapDrawableTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/BitmapDrawableTest.java
deleted file mode 100644
index 56d69a59b..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/BitmapDrawableTest.java
+++ /dev/null
@@ -1,103 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.content.res.Resources;
-import android.graphics.Canvas;
-import android.graphics.ColorMatrix;
-import android.graphics.ColorMatrixColorFilter;
-import android.graphics.Shader;
-import android.graphics.drawable.BitmapDrawable;
-import android.graphics.drawable.Drawable;
-import com.xtremelabs.robolectric.R;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import java.io.ByteArrayInputStream;
-import java.io.InputStream;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class BitmapDrawableTest {
- private Resources resources;
-
- @Before
- public void setUp() throws Exception {
- resources = Robolectric.application.getResources();
- }
-
- @Test
- public void getBitmap_shouldReturnBitmapUsedToDraw() throws Exception {
- BitmapDrawable drawable = (BitmapDrawable) resources.getDrawable(R.drawable.an_image);
- assertEquals("Bitmap for resource:drawable/an_image", shadowOf(drawable.getBitmap()).getDescription());
- }
-
- @Test
- public void draw_shouldCopyDescriptionToCanvas() throws Exception {
- BitmapDrawable drawable = (BitmapDrawable) resources.getDrawable(R.drawable.an_image);
- Canvas canvas = new Canvas();
- drawable.draw(canvas);
-
- assertEquals("Bitmap for resource:drawable/an_image", shadowOf(canvas).getDescription());
- }
-
- @Test
- public void shouldInheritSourceStringFromDrawableDotCreateFromStream() throws Exception {
- InputStream emptyInputStream = new ByteArrayInputStream("".getBytes());
- BitmapDrawable drawable = (BitmapDrawable) Drawable.createFromStream(emptyInputStream, "source string value");
- assertEquals("source string value", shadowOf(drawable).getSource());
- }
-
- @Test
- public void withColorFilterSet_draw_shouldCopyDescriptionToCanvas() throws Exception {
- BitmapDrawable drawable = (BitmapDrawable) resources.getDrawable(R.drawable.an_image);
- drawable.setColorFilter(new ColorMatrixColorFilter(new ColorMatrix()));
- Canvas canvas = new Canvas();
- drawable.draw(canvas);
-
- assertEquals("Bitmap for resource:drawable/an_image with ColorMatrixColorFilter<1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0>",
- shadowOf(canvas).getDescription());
- }
-
- @Test
- public void equals_shouldTestResourceId() throws Exception {
- Drawable drawable1a = resources.getDrawable(R.drawable.an_image);
- Drawable drawable1b = resources.getDrawable(R.drawable.an_image);
- Drawable drawable2 = resources.getDrawable(R.drawable.an_other_image);
-
- assertEquals(drawable1a, drawable1b);
- assertFalse(drawable1a.equals(drawable2));
- }
-
- @Test
- public void equals_shouldTestBounds() throws Exception {
- Drawable drawable1a = resources.getDrawable(R.drawable.an_image);
- Drawable drawable1b = resources.getDrawable(R.drawable.an_image);
-
- drawable1a.setBounds(1, 2, 3, 4);
- drawable1b.setBounds(1, 2, 3, 4);
-
- assertEquals(drawable1a, drawable1b);
-
- drawable1b.setBounds(1, 2, 3, 5);
- assertFalse(drawable1a.equals(drawable1b));
- }
-
- @Test
- public void shouldStillHaveShadow() throws Exception {
- Drawable drawable = resources.getDrawable(R.drawable.an_image);
- assertEquals(R.drawable.an_image, ((ShadowBitmapDrawable) Robolectric.shadowOf(drawable)).getLoadedFromResourceId());
- }
-
- @Test
- public void shouldSetTileModeXY() throws Exception {
- BitmapDrawable drawable = (BitmapDrawable) resources.getDrawable(R.drawable.an_image);
- drawable.setTileModeXY(Shader.TileMode.REPEAT, Shader.TileMode.MIRROR);
- assertEquals(Shader.TileMode.REPEAT, drawable.getTileModeX());
- assertEquals(Shader.TileMode.MIRROR, drawable.getTileModeY());
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/BitmapFactoryTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/BitmapFactoryTest.java
deleted file mode 100644
index 54d081250..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/BitmapFactoryTest.java
+++ /dev/null
@@ -1,127 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.graphics.Bitmap;
-import android.graphics.BitmapFactory;
-import android.net.Uri;
-import android.provider.MediaStore;
-import com.xtremelabs.robolectric.R;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import java.io.InputStream;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-import static org.junit.Assert.assertEquals;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class BitmapFactoryTest {
- @Test
- public void decodeResource_shouldSetDescription() throws Exception {
- Bitmap bitmap = BitmapFactory.decodeResource(Robolectric.application.getResources(), R.drawable.an_image);
- assertEquals("Bitmap for resource:drawable/an_image", shadowOf(bitmap).getDescription());
- assertEquals(100, bitmap.getWidth());
- assertEquals(100, bitmap.getHeight());
- }
-
- @Test
- public void decodeResourceWithOpts_shouldSetDescription() throws Exception {
- BitmapFactory.Options opts = new BitmapFactory.Options();
- Bitmap bitmap = BitmapFactory.decodeResource(Robolectric.application.getResources(), R.drawable.an_image, opts);
- assertEquals("Bitmap for resource:drawable/an_image", shadowOf(bitmap).getDescription());
- assertEquals(100, bitmap.getWidth());
- assertEquals(100, bitmap.getHeight());
- assertEquals(100, opts.outWidth);
- assertEquals(100, opts.outHeight);
- }
-
- @Test
- public void decodeFile_shouldSetDescription() throws Exception {
- Bitmap bitmap = BitmapFactory.decodeFile("/some/file.jpg");
- assertEquals("Bitmap for file:/some/file.jpg", shadowOf(bitmap).getDescription());
- assertEquals(100, bitmap.getWidth());
- assertEquals(100, bitmap.getHeight());
- }
-
- @Test
- public void decodeStream_shouldSetDescription() throws Exception {
- InputStream inputStream = Robolectric.application.getContentResolver().openInputStream(Uri.parse("content:/path"));
- Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
- assertEquals("Bitmap for content:/path", shadowOf(bitmap).getDescription());
- assertEquals(100, bitmap.getWidth());
- assertEquals(100, bitmap.getHeight());
- }
-
- @Test
- public void decodeResource_shouldGetWidthAndHeightFromHints() throws Exception {
- ShadowBitmapFactory.provideWidthAndHeightHints(R.drawable.an_image, 123, 456);
-
- Bitmap bitmap = BitmapFactory.decodeResource(Robolectric.application.getResources(), R.drawable.an_image);
- assertEquals("Bitmap for resource:drawable/an_image", shadowOf(bitmap).getDescription());
- assertEquals(123, bitmap.getWidth());
- assertEquals(456, bitmap.getHeight());
- }
-
- @Test
- public void decodeResourceWithOpts_shouldGetWidthAndHeightFromHints() throws Exception {
- ShadowBitmapFactory.provideWidthAndHeightHints(R.drawable.an_image, 123, 456);
-
- BitmapFactory.Options opts = new BitmapFactory.Options();
- Bitmap bitmap = BitmapFactory.decodeResource(Robolectric.application.getResources(), R.drawable.an_image, opts);
- assertEquals("Bitmap for resource:drawable/an_image", shadowOf(bitmap).getDescription());
- assertEquals(123, bitmap.getWidth());
- assertEquals(456, bitmap.getHeight());
- assertEquals(123, opts.outWidth);
- assertEquals(456, opts.outHeight);
- }
-
- @Test
- public void decodeResource_canTakeOptions() throws Exception {
- BitmapFactory.Options options = new BitmapFactory.Options();
- options.inSampleSize = 100;
- Bitmap bitmap = BitmapFactory.decodeResource(Robolectric.application.getResources(), R.drawable.an_image, options);
- assertEquals(true, shadowOf(bitmap).getDescription().contains("inSampleSize=100"));
- }
-
- @Test
- public void decodeFile_shouldGetWidthAndHeightFromHints() throws Exception {
- ShadowBitmapFactory.provideWidthAndHeightHints("/some/file.jpg", 123, 456);
-
- Bitmap bitmap = BitmapFactory.decodeFile("/some/file.jpg");
- assertEquals("Bitmap for file:/some/file.jpg", shadowOf(bitmap).getDescription());
- assertEquals(123, bitmap.getWidth());
- assertEquals(456, bitmap.getHeight());
- }
-
- @Test
- public void decodeFileEtc_shouldSetOptionsOutWidthAndOutHeightFromHints() throws Exception {
- ShadowBitmapFactory.provideWidthAndHeightHints("/some/file.jpg", 123, 456);
-
- BitmapFactory.Options options = new BitmapFactory.Options();
- BitmapFactory.decodeFile("/some/file.jpg", options);
- assertEquals(123, options.outWidth);
- assertEquals(456, options.outHeight);
- }
-
- @Test
- public void decodeUri_shouldGetWidthAndHeightFromHints() throws Exception {
- ShadowBitmapFactory.provideWidthAndHeightHints(Uri.parse("content:/path"), 123, 456);
-
- Bitmap bitmap = MediaStore.Images.Media.getBitmap(Robolectric.application.getContentResolver(), Uri.parse("content:/path"));
- assertEquals("Bitmap for content:/path", shadowOf(bitmap).getDescription());
- assertEquals(123, bitmap.getWidth());
- assertEquals(456, bitmap.getHeight());
- }
-
- @Test
- public void decodeStream_shouldGetWidthAndHeightFromHints() throws Exception {
- ShadowBitmapFactory.provideWidthAndHeightHints(Uri.parse("content:/path"), 123, 456);
-
- InputStream inputStream = Robolectric.application.getContentResolver().openInputStream(Uri.parse("content:/path"));
- Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
- assertEquals("Bitmap for content:/path", shadowOf(bitmap).getDescription());
- assertEquals(123, bitmap.getWidth());
- assertEquals(456, bitmap.getHeight());
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/BitmapTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/BitmapTest.java
deleted file mode 100644
index 55c695bdd..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/BitmapTest.java
+++ /dev/null
@@ -1,140 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.graphics.Bitmap;
-import android.graphics.Bitmap.Config;
-import android.graphics.Canvas;
-import android.graphics.ColorMatrix;
-import android.graphics.ColorMatrixColorFilter;
-import android.graphics.Matrix;
-import android.graphics.Paint;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class BitmapTest {
- @Test
- public void shouldCreateScaledBitmap() throws Exception {
- Bitmap originalBitmap = Robolectric.newInstanceOf(Bitmap.class);
- shadowOf(originalBitmap).appendDescription("Original bitmap");
- Bitmap scaledBitmap = Bitmap.createScaledBitmap(originalBitmap, 100, 200, false);
- assertEquals("Original bitmap scaled to 100 x 200", shadowOf(scaledBitmap).getDescription());
- assertEquals(100, scaledBitmap.getWidth());
- assertEquals(200, scaledBitmap.getHeight());
- }
-
- @Test
- public void shouldCreateActiveBitmap() throws Exception {
- Bitmap bitmap = Bitmap.createBitmap(100, 200, Config.ARGB_8888);
- assertFalse(bitmap.isRecycled());
- }
-
- @Test
- public void shouldCreateBitmapWithCorrectConfig() throws Exception {
- Bitmap bitmap = Bitmap.createBitmap(100, 200, Config.ARGB_8888);
- assertEquals(bitmap.getConfig(), Config.ARGB_8888);
- }
-
- @Test
- public void shouldCreateBitmapFromAnotherBitmap() {
- Bitmap originalBitmap = Robolectric.newInstanceOf(Bitmap.class);
- shadowOf(originalBitmap).appendDescription("Original bitmap");
- Bitmap newBitmap = Bitmap.createBitmap(originalBitmap);
- assertEquals("Original bitmap created from Bitmap object", shadowOf(newBitmap).getDescription());
- }
-
-
- @Test
- public void shouldRecycleBitmap() throws Exception {
- Bitmap bitmap = Bitmap.createBitmap(100, 200, Config.ARGB_8888);
- bitmap.recycle();
- assertTrue( bitmap.isRecycled() );
- }
-
- @Test
- public void equals_shouldCompareDescriptions() throws Exception {
- assertFalse(ShadowBitmap.create("bitmap A").equals(ShadowBitmap.create("bitmap B")));
-
- assertTrue(ShadowBitmap.create("bitmap A").equals(ShadowBitmap.create("bitmap A")));
- }
-
- @Test
- public void equals_shouldCompareWidthAndHeight() throws Exception {
- Bitmap bitmapA1 = ShadowBitmap.create("bitmap A");
- shadowOf(bitmapA1).setWidth(100);
- shadowOf(bitmapA1).setHeight(100);
-
- Bitmap bitmapA2 = ShadowBitmap.create("bitmap A");
- shadowOf(bitmapA2).setWidth(101);
- shadowOf(bitmapA2).setHeight(101);
-
- assertFalse(bitmapA1.equals(bitmapA2));
- }
-
- @Test
- public void shouldReceiveDescriptionWhenDrawingToCanvas() throws Exception {
- Bitmap bitmap1 = Robolectric.newInstanceOf(Bitmap.class);
- shadowOf(bitmap1).appendDescription("Bitmap One");
-
- Bitmap bitmap2 = Robolectric.newInstanceOf(Bitmap.class);
- shadowOf(bitmap2).appendDescription("Bitmap Two");
-
- Canvas canvas = new Canvas(bitmap1);
- canvas.drawBitmap(bitmap2, 0, 0, null);
-
- assertEquals("Bitmap One\nBitmap Two", shadowOf(bitmap1).getDescription());
- }
-
- @Test
- public void shouldReceiveDescriptionWhenDrawingToCanvasWithBitmapAndMatrixAndPaint() throws Exception {
- Bitmap bitmap1 = Robolectric.newInstanceOf(Bitmap.class);
- shadowOf(bitmap1).appendDescription("Bitmap One");
-
- Bitmap bitmap2 = Robolectric.newInstanceOf(Bitmap.class);
- shadowOf(bitmap2).appendDescription("Bitmap Two");
-
- Canvas canvas = new Canvas(bitmap1);
- canvas.drawBitmap(bitmap2, new Matrix(), null);
-
- assertEquals("Bitmap One\nBitmap Two transformed by matrix", shadowOf(bitmap1).getDescription());
- }
-
- @Test
- public void shouldReceiveDescriptionWhenDrawABitmapToCanvasWithAPaintEffect() throws Exception {
- Bitmap bitmap1 = Robolectric.newInstanceOf(Bitmap.class);
- shadowOf(bitmap1).appendDescription("Bitmap One");
-
- Bitmap bitmap2 = Robolectric.newInstanceOf(Bitmap.class);
- shadowOf(bitmap2).appendDescription("Bitmap Two");
-
- Canvas canvas = new Canvas(bitmap1);
- Paint paint = new Paint();
- paint.setColorFilter(new ColorMatrixColorFilter(new ColorMatrix()));
- canvas.drawBitmap(bitmap2, new Matrix(), paint);
-
- assertEquals("Bitmap One\nBitmap Two with ColorMatrixColorFilter<1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0> transformed by matrix", shadowOf(bitmap1).getDescription());
- }
-
- @Test
- public void visualize_shouldReturnDescription() throws Exception {
- Bitmap bitmap = Robolectric.newInstanceOf(Bitmap.class);
- shadowOf(bitmap).appendDescription("Bitmap One");
-
- assertEquals("Bitmap One", Robolectric.visualize(bitmap));
-
- }
-
- @Test
- public void shouldCopyBitmap() {
- Bitmap bitmap = Robolectric.newInstanceOf(Bitmap.class);
- Bitmap bitmapCopy = bitmap.copy(Config.ARGB_8888, true);
- assertEquals(shadowOf(bitmapCopy).getConfig(), Config.ARGB_8888);
- assertTrue(shadowOf(bitmapCopy).isMutable());
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/BundleTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/BundleTest.java
deleted file mode 100644
index 88c080aae..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/BundleTest.java
+++ /dev/null
@@ -1,406 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.os.Build;
-import android.os.Bundle;
-import android.os.Parcelable;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import junit.framework.AssertionFailedError;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import java.util.ArrayList;
-
-import static org.junit.Assert.*;
-
-
-@RunWith(WithTestDefaultsRunner.class)
-public class BundleTest {
-
- private Bundle bundle;
-
- @Before public void setUp() throws Exception {
- bundle = new Bundle();
- }
-
- @Test
- public void testContainsKey() throws Exception {
- assertFalse(bundle.containsKey("foo"));
- bundle.putString("foo", "bar");
- assertTrue(bundle.containsKey("foo"));
- }
-
- @Test
- public void testInt() {
- bundle.putInt("foo", 5);
- assertEquals(5,bundle.getInt("foo"));
- assertEquals(0,bundle.getInt("bar"));
- assertEquals(7, bundle.getInt("bar", 7));
- }
-
- @Test
- public void testSize() {
- assertEquals(0, bundle.size());
- bundle.putInt("foo", 5);
- assertEquals(1, bundle.size());
- bundle.putInt("bar", 5);
- assertEquals(2, bundle.size());
- }
-
- @Test
- public void testLong() {
- bundle.putLong("foo", 5);
- assertEquals(5, bundle.getLong("foo"));
- assertEquals(0,bundle.getLong("bar"));
- assertEquals(7, bundle.getLong("bar", 7));
- }
-
- @Test
- public void testDouble() {
- bundle.putDouble("foo", 5);
- assertEquals(Double.valueOf(5), Double.valueOf(bundle.getDouble("foo")));
- assertEquals(Double.valueOf(0),Double.valueOf(bundle.getDouble("bar")));
- assertEquals(Double.valueOf(7), Double.valueOf(bundle.getDouble("bar", 7)));
- }
-
- @Test
- public void testByte() {
- bundle.putByte("foo", (byte) 0xA);
- assertEquals((byte) 0xA, bundle.getByte("foo"));
- assertEquals((byte) 0x0, bundle.getByte("bar"));
- assertEquals((byte) 0x37, bundle.getByte("bar", (byte) 0x37).byteValue());
- }
-
- @Test
- public void testBoolean() {
- bundle.putBoolean("foo", true);
- assertEquals(true, bundle.getBoolean("foo"));
- assertEquals(false, bundle.getBoolean("bar"));
- assertEquals(true, bundle.getBoolean("bar", true));
- }
-
- @Test
- public void testShort() {
- bundle.putShort("foo", (short) 0xA);
- assertEquals((short) 0xA, bundle.getShort("foo"));
- assertEquals((short) 0x0, bundle.getShort("bar"));
- assertEquals((short) 0x37, bundle.getShort("bar", (short) 0x37));
- }
-
- @Test
- public void testFloat() {
- bundle.putFloat("foo", 5f);
- assertEquals(Float.valueOf(5), Float.valueOf(bundle.getFloat("foo")));
- assertEquals(Float.valueOf(0),Float.valueOf(bundle.getFloat("bar")));
- assertEquals(Float.valueOf(7), Float.valueOf(bundle.getFloat("bar", 7)));
- }
-
- @Test
- public void testStringHasValue() {
- bundle.putString("key", "value");
- assertEquals("value", bundle.getString("key"));
- }
-
- @Test
- public void testStringDoesNotHaveValue() {
- assertNull(bundle.getString("key"));
- }
-
- @Test
- public void testStringNullKey() {
- bundle.putString(null, "value");
- assertEquals("value", bundle.getString(null));
- }
-
- @Test
- public void testStringNullValue() {
- bundle.putString("key", null);
- assertNull(bundle.getString("key"));
- }
-
- @Test
- public void testStringApi1() {
- int previousApiLevel = Build.VERSION.SDK_INT;
- Robolectric.Reflection.setFinalStaticField(Build.VERSION.class, "SDK_INT",
- Build.VERSION_CODES.BASE);
-
- try {
- bundle.getString("value", "defaultValue");
- fail();
- } catch (RuntimeException e) {
- // Expected
- } finally {
- Robolectric.Reflection.setFinalStaticField(Build.VERSION.class, "SDK_INT",
- previousApiLevel);
- }
- }
-
- @Test
- public void testStringApi12HasKey() {
- int previousApiLevel = Build.VERSION.SDK_INT;
- Robolectric.Reflection.setFinalStaticField(Build.VERSION.class, "SDK_INT",
- Build.VERSION_CODES.HONEYCOMB_MR1);
-
- try {
- bundle.putString("key", "value");
- assertEquals("value", bundle.getString("key", "defaultValue"));
- } finally {
- Robolectric.Reflection.setFinalStaticField(Build.VERSION.class, "SDK_INT",
- previousApiLevel);
- }
- }
-
- @Test
- public void testStringApi12DoesNotHaveKey() {
- int previousApiLevel = Build.VERSION.SDK_INT;
- Robolectric.Reflection.setFinalStaticField(Build.VERSION.class, "SDK_INT",
- Build.VERSION_CODES.HONEYCOMB_MR1);
-
- try {
- bundle.putString("key", "value");
- assertEquals("defaultValue", bundle.getString("foo", "defaultValue"));
- } finally {
- Robolectric.Reflection.setFinalStaticField(Build.VERSION.class, "SDK_INT",
- previousApiLevel);
- }
- }
-
- @Test
- public void testStringApi12NullKey() {
- int previousApiLevel = Build.VERSION.SDK_INT;
- Robolectric.Reflection.setFinalStaticField(Build.VERSION.class, "SDK_INT",
- Build.VERSION_CODES.HONEYCOMB_MR1);
-
- try {
- bundle.putString(null, "value");
- assertEquals("value", bundle.getString(null, "defaultValue"));
- } finally {
- Robolectric.Reflection.setFinalStaticField(Build.VERSION.class, "SDK_INT",
- previousApiLevel);
- }
- }
-
- @Test
- public void testStringApi12NullValue() {
- int previousApiLevel = Build.VERSION.SDK_INT;
- Robolectric.Reflection.setFinalStaticField(Build.VERSION.class, "SDK_INT",
- Build.VERSION_CODES.HONEYCOMB_MR1);
-
- try {
- bundle.putString("key", null);
- assertEquals("defaultValue", bundle.getString("key", "defaultValue"));
- } finally {
- Robolectric.Reflection.setFinalStaticField(Build.VERSION.class, "SDK_INT",
- previousApiLevel);
- }
- }
-
- @Test
- public void testGetOfWrongType() {
- bundle.putFloat("foo", 5f);
- assertEquals(0, bundle.getChar("foo"));
- assertEquals(null, bundle.getCharArray("foo"));
- assertEquals(0, bundle.getInt("foo"));
- assertEquals(null, bundle.getIntArray("foo"));
- assertEquals(null, bundle.getIntegerArrayList("foo"));
- assertEquals(0, bundle.getShort("foo"));
- assertEquals(null, bundle.getShortArray("foo"));
- assertEquals(false, bundle.getBoolean("foo"));
- assertEquals(null, bundle.getBooleanArray("foo"));
- assertEquals(0, bundle.getLong("foo"));
- assertEquals(null, bundle.getLongArray("foo"));
- assertEquals(null, bundle.getFloatArray("foo"));
- assertEquals(0, bundle.getDouble("foo"), 0.005);
- assertEquals(null, bundle.getDoubleArray("foo"));
- assertEquals(null, bundle.getString("foo"));
- assertEquals(null, bundle.getStringArray("foo"));
- assertEquals(null, bundle.getStringArrayList("foo"));
- assertEquals(null, bundle.getBundle("foo"));
- assertEquals(null, bundle.getParcelable("foo"));
- assertEquals(null, bundle.getParcelableArray("foo"));
- assertEquals(null, bundle.getParcelableArrayList("foo"));
-
- bundle.putInt("foo", 1);
- assertEquals(0, bundle.getFloat("foo"), 0.005f);
- }
-
- @Test
- public void testRemove() {
- bundle.putFloat("foo", 5f);
- bundle.putFloat("foo2", 5f);
-
- bundle.remove("foo");
-
- assertFalse(bundle.containsKey("foo"));
- assertTrue(bundle.containsKey("foo2"));
- }
-
- @Test
- public void testClear() {
- bundle.putFloat("foo", 5f);
-
- bundle.clear();
-
- assertEquals(0, bundle.size());
- }
-
- @Test
- public void testIsEmpty() {
- assertTrue(bundle.isEmpty());
- bundle.putBoolean("foo", true);
- assertFalse(bundle.isEmpty());
- }
-
- @Test
- public void testStringArray() {
- bundle.putStringArray("foo", new String[] { "a" });
- Assert.assertArrayEquals(new String[] { "a" }, bundle.getStringArray("foo"));
- assertNull(bundle.getStringArray("bar"));
- }
-
- @Test
- public void testStringArrayList() {
- ArrayList<String> list = new ArrayList<String>();
- list.add("a");
-
- bundle.putStringArrayList("foo", new ArrayList<String>(list));
- Assert.assertEquals(list, bundle.getStringArrayList("foo"));
- assertNull(bundle.getStringArrayList("bar"));
- }
-
- @Test
- public void testIntegerArrayList() {
- ArrayList<Integer> list = new ArrayList<Integer>();
- list.add(100);
-
- bundle.putIntegerArrayList("foo", new ArrayList<Integer>(list));
- Assert.assertEquals(list, bundle.getIntegerArrayList("foo"));
- assertNull(bundle.getIntegerArrayList("bar"));
- }
-
- @Test
- public void testBundle() {
- Bundle innerBundle = new Bundle();
- innerBundle.putInt("int", 7);
- bundle.putBundle("bundle", innerBundle);
-
- assertEquals(innerBundle, bundle.getBundle("bundle"));
- assertNull(bundle.getBundle("bar"));
- }
-
- @Test
- public void testBooleanArray() {
- boolean [] arr = new boolean[] { false, true };
- bundle.putBooleanArray("foo", arr);
-
- assertArrayEquals(arr, bundle.getBooleanArray("foo"));
- assertNull(bundle.getBooleanArray("bar"));
- }
-
- @Test
- public void testByteArray() {
- byte [] arr = new byte[] { 12, 24 };
- bundle.putByteArray("foo", arr);
-
- Assert.assertArrayEquals(arr, bundle.getByteArray("foo"));
- assertNull(bundle.getByteArray("bar"));
- }
-
- @Test
- public void testCharArray() {
- char [] arr = new char[] { 'c', 'j' };
- bundle.putCharArray("foo", arr);
-
- Assert.assertArrayEquals(arr, bundle.getCharArray("foo"));
- assertNull(bundle.getCharArray("bar"));
- }
-
- @Test
- public void testDoubleArray() {
- double [] arr = new double[] { 1.2, 3.4 };
- bundle.putDoubleArray("foo", arr);
-
- assertArrayEquals(arr, bundle.getDoubleArray("foo"));
- assertNull(bundle.getDoubleArray("bar"));
- }
-
- @Test
- public void testIntArray() {
- int [] arr = new int[] { 87, 65 };
- bundle.putIntArray("foo", arr);
-
- Assert.assertArrayEquals(arr, bundle.getIntArray("foo"));
- assertNull(bundle.getIntArray("bar"));
- }
-
- @Test
- public void testLongArray() {
- long [] arr = new long[] { 23, 11 };
- bundle.putLongArray("foo", arr);
-
- Assert.assertArrayEquals(arr, bundle.getLongArray("foo"));
- assertNull(bundle.getLongArray("bar"));
- }
-
- @Test
- public void testShortArray() {
- short [] arr = new short[] { 89, 37 };
- bundle.putShortArray("foo", arr);
-
- Assert.assertArrayEquals(arr, bundle.getShortArray("foo"));
- assertNull(bundle.getShortArray("bar"));
- }
-
- @Test
- public void testParcelableArray() {
- Bundle innerBundle = new Bundle();
- innerBundle.putInt("value", 1);
- Parcelable[] arr = new Parcelable[] { innerBundle };
- bundle.putParcelableArray("foo", arr);
-
- Assert.assertArrayEquals(arr, bundle.getParcelableArray("foo"));
- assertNull(bundle.getParcelableArray("bar"));
- }
-
- @Test
- public void testCopyConstructor() {
- bundle.putInt("value", 1);
- Bundle copiedBundle = new Bundle(bundle);
-
- Assert.assertEquals(copiedBundle, bundle);
- }
-
- private void assertArrayEquals(double[] expected, double[] actual) {
- if (expected != null && actual == null) {
- throw new AssertionFailedError();
- } else if (expected == null && actual != null) {
- throw new AssertionFailedError();
- } else {
- for (int i = 0; i < expected.length; i++) {
- if (expected[i] != actual[i])
- throw new AssertionFailedError();
- }
-
- if (expected.length != actual.length)
- throw new AssertionFailedError();
- }
- }
-
- private void assertArrayEquals(boolean[] expected, boolean[] actual) {
- if (expected != null && actual == null) {
- throw new AssertionFailedError();
- } else if (expected == null && actual != null) {
- throw new AssertionFailedError();
- } else {
- for (int i = 0; i < expected.length; i++) {
- if (expected[i] != actual[i])
- throw new AssertionFailedError();
- }
-
- if (expected.length != actual.length)
- throw new AssertionFailedError();
- }
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/CameraParametersTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/CameraParametersTest.java
deleted file mode 100644
index e220be340..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/CameraParametersTest.java
+++ /dev/null
@@ -1,135 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-
-import android.graphics.ImageFormat;
-import android.hardware.Camera;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import java.util.List;
-
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.CoreMatchers.not;
-import static org.hamcrest.CoreMatchers.notNullValue;
-import static org.hamcrest.core.IsCollectionContaining.hasItem;
-import static org.junit.Assert.assertThat;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class CameraParametersTest {
-
- private Camera.Parameters parameters;
- private ShadowCameraParameters shadowParameters;
-
- @Before
- public void setUp() throws Exception {
- parameters = Robolectric.newInstanceOf(Camera.Parameters.class);
- shadowParameters = Robolectric.shadowOf(parameters);
- }
-
- @Test
- public void testPictureSize() throws Exception {
- assertThat(shadowParameters.getPictureHeight(), not(equalTo(600)));
- assertThat(shadowParameters.getPictureWidth(), not(equalTo(800)));
- parameters.setPictureSize(800, 600);
- Camera.Size pictureSize = parameters.getPictureSize();
- assertThat(pictureSize.width, equalTo(800));
- assertThat(pictureSize.height, equalTo(600));
- assertThat(shadowParameters.getPictureHeight(), equalTo(600));
- assertThat(shadowParameters.getPictureWidth(), equalTo(800));
- }
-
- @Test
- public void testPreviewFpsRange() throws Exception {
- int[] fpsRange = new int[2];
- parameters.getPreviewFpsRange(fpsRange);
- assertThat(fpsRange[1], not(equalTo(15)));
- assertThat(fpsRange[0], not(equalTo(25)));
- parameters.setPreviewFpsRange(15, 25);
- parameters.getPreviewFpsRange(fpsRange);
- assertThat(fpsRange[1], equalTo(25));
- assertThat(fpsRange[0], equalTo(15));
- }
-
- @Test
- public void testPreviewFrameRate() throws Exception {
- assertThat(parameters.getPreviewFrameRate(), not(equalTo(15)));
- parameters.setPreviewFrameRate(15);
- assertThat(parameters.getPreviewFrameRate(), equalTo(15));
- }
-
- @Test
- public void testPreviewSize() throws Exception {
- assertThat(shadowParameters.getPreviewWidth(), not(equalTo(320)));
- assertThat(shadowParameters.getPreviewHeight(), not(equalTo(240)));
- parameters.setPreviewSize(320, 240);
- Camera.Size size = parameters.getPreviewSize();
- assertThat(size.width, equalTo(320));
- assertThat(size.height, equalTo(240));
- assertThat(shadowParameters.getPreviewWidth(), equalTo(320));
- assertThat(shadowParameters.getPreviewHeight(), equalTo(240));
- }
-
- @Test
- public void testPreviewFormat() throws Exception {
- assertThat(shadowParameters.getPreviewFormat(), equalTo(ImageFormat.NV21));
- parameters.setPreviewFormat(ImageFormat.JPEG);
- assertThat(shadowParameters.getPreviewFormat(), equalTo(ImageFormat.JPEG));
- }
-
- @Test
- public void testGetSupportedPreviewFormats() throws Exception {
- List<Integer> supportedFormats = parameters.getSupportedPreviewFormats();
- assertThat(supportedFormats, notNullValue());
- assertThat(supportedFormats.size(), not(equalTo(0)));
- assertThat(supportedFormats, hasItem(ImageFormat.NV21));
- }
-
- @Test
- public void testGetSupportedPictureFormats() throws Exception {
- List<Integer> supportedFormats = parameters.getSupportedPictureFormats();
- assertThat(supportedFormats, notNullValue());
- assertThat(supportedFormats.size(), equalTo(2));
- assertThat(supportedFormats, hasItem(new Integer(ImageFormat.NV21)));
- }
-
- @Test
- public void testGetSupportedPictureSizes() throws Exception {
- List<Camera.Size> supportedSizes = parameters.getSupportedPictureSizes();
- assertThat(supportedSizes, notNullValue());
- assertThat(supportedSizes.size(), equalTo(3));
- assertThat(supportedSizes.get(0).width, equalTo(320));
- assertThat(supportedSizes.get(0).height, equalTo(240));
- }
-
- @Test
- public void testGetSupportedPreviewSizes() throws Exception {
- List<Camera.Size> supportedSizes = parameters.getSupportedPreviewSizes();
- assertThat(supportedSizes, notNullValue());
- assertThat(supportedSizes.size(), equalTo(2));
- assertThat(supportedSizes.get(0).width, equalTo(320));
- assertThat(supportedSizes.get(0).height, equalTo(240));
- }
-
- @Test
- public void testGetSupportedPreviewFpsRange() throws Exception {
- List<int[]> supportedRanges = parameters.getSupportedPreviewFpsRange();
- assertThat(supportedRanges, notNullValue());
- assertThat(supportedRanges.size(), equalTo(2));
- assertThat(supportedRanges.get(0)[0], equalTo(15000));
- assertThat(supportedRanges.get(0)[1], equalTo(15000));
- assertThat(supportedRanges.get(1)[0], equalTo(10000));
- assertThat(supportedRanges.get(1)[1], equalTo(30000));
- }
-
- @Test
- public void testGetSupportedPreviewFrameRates() throws Exception {
- List<Integer> supportedRates = parameters.getSupportedPreviewFrameRates();
- assertThat(supportedRates, notNullValue());
- assertThat(supportedRates.size(), equalTo(3));
- assertThat(supportedRates.get(0), equalTo(10));
- }
-
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/CameraSizeTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/CameraSizeTest.java
deleted file mode 100644
index ad443b8fc..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/CameraSizeTest.java
+++ /dev/null
@@ -1,45 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-
-import android.hardware.Camera;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.CoreMatchers.not;
-import static org.junit.Assert.assertThat;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class CameraSizeTest {
-
- private Camera.Size cameraSize;
-
- @Before
- public void setUp() throws Exception {
- cameraSize = Robolectric.newInstanceOf(Camera.class).new Size(480, 320);
- }
-
- @Test
- public void testConstructor() throws Exception {
- assertThat(cameraSize.width, equalTo(480));
- assertThat(cameraSize.height, equalTo(320));
- }
-
- @Test
- public void testSetWidth() throws Exception {
- assertThat(cameraSize.width, not(equalTo(640)));
- cameraSize.width = 640;
- assertThat(cameraSize.width, equalTo(640));
- }
-
- @Test
- public void testSetHeight() throws Exception {
- assertThat(cameraSize.height, not(equalTo(480)));
- cameraSize.height = 480;
- assertThat(cameraSize.height, equalTo(480));
- }
-
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/CameraTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/CameraTest.java
deleted file mode 100644
index 9975c2df8..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/CameraTest.java
+++ /dev/null
@@ -1,291 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-
-import android.graphics.Canvas;
-import android.graphics.ImageFormat;
-import android.graphics.Rect;
-import android.hardware.Camera;
-import android.view.Surface;
-import android.view.SurfaceHolder;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.CoreMatchers.not;
-import static org.hamcrest.CoreMatchers.notNullValue;
-import static org.hamcrest.CoreMatchers.nullValue;
-import static org.hamcrest.CoreMatchers.sameInstance;
-import static org.junit.Assert.assertThat;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class CameraTest {
-
- private Camera camera;
- private ShadowCamera shadowCamera;
-
- @Before
- public void setUp() throws Exception {
- camera = Camera.open();
- shadowCamera = Robolectric.shadowOf(camera);
- }
-
- @After
- public void tearDown() throws Exception {
- ShadowCamera.clearCameraInfo();
- }
-
- @Test
- public void testOpen() throws Exception {
- assertThat(camera, notNullValue());
- }
-
- @Test
- public void testUnlock() throws Exception {
- assertThat(shadowCamera.isLocked(), equalTo(true));
- camera.unlock();
- assertThat(shadowCamera.isLocked(), equalTo(false));
- }
-
- @Test
- public void testReconnect() throws Exception {
- camera.unlock();
- assertThat(shadowCamera.isLocked(), equalTo(false));
- camera.reconnect();
- assertThat(shadowCamera.isLocked(), equalTo(true));
- }
-
- @Test
- public void testGetParameters() throws Exception {
- Camera.Parameters parameters = camera.getParameters();
- assertThat(parameters, notNullValue());
- assertThat(parameters.getSupportedPreviewFormats(), notNullValue());
- assertThat(parameters.getSupportedPreviewFormats().size(), not(equalTo(0)));
- }
-
- @Test
- public void testSetParameters() throws Exception {
- Camera.Parameters parameters = camera.getParameters();
- assertThat(parameters.getPreviewFormat(), equalTo(ImageFormat.NV21));
- parameters.setPreviewFormat(ImageFormat.JPEG);
- camera.setParameters(parameters);
- assertThat(camera.getParameters().getPreviewFormat(), equalTo(ImageFormat.JPEG));
- }
-
- @Test
- public void testSetPreviewDisplay() throws Exception {
- SurfaceHolder previewSurfaceHolder = new TestSurfaceHolder();
- camera.setPreviewDisplay(previewSurfaceHolder);
- assertThat(shadowCamera.getPreviewDisplay(), sameInstance(previewSurfaceHolder));
- }
-
- @Test
- public void testStartPreview() throws Exception {
- assertThat(shadowCamera.isPreviewing(), equalTo(false));
- camera.startPreview();
- assertThat(shadowCamera.isPreviewing(), equalTo(true));
- }
-
- @Test
- public void testStopPreview() throws Exception {
- camera.startPreview();
- assertThat(shadowCamera.isPreviewing(), equalTo(true));
- camera.stopPreview();
- assertThat(shadowCamera.isPreviewing(), equalTo(false));
- }
-
- @Test
- public void testRelease() throws Exception {
- assertThat(shadowCamera.isReleased(), equalTo(false));
- camera.release();
- assertThat(shadowCamera.isReleased(), equalTo(true));
- }
-
- @Test
- public void testSetPreviewCallbacks() throws Exception {
- TestPreviewCallback callback = new TestPreviewCallback();
- assertThat(callback.camera, nullValue());
- assertThat(callback.data, nullValue());
-
- camera.setPreviewCallback(callback);
- shadowCamera.invokePreviewCallback("foobar".getBytes());
-
- assertThat(callback.camera, sameInstance(camera));
- assertThat(callback.data, equalTo("foobar".getBytes()));
- }
-
- @Test
- public void testSetOneShotPreviewCallbacks() throws Exception {
- TestPreviewCallback callback = new TestPreviewCallback();
- assertThat(callback.camera, nullValue());
- assertThat(callback.data, nullValue());
-
- camera.setOneShotPreviewCallback(callback);
- shadowCamera.invokePreviewCallback("foobar".getBytes());
-
- assertThat(callback.camera, sameInstance(camera));
- assertThat(callback.data, equalTo("foobar".getBytes()));
- }
-
- @Test
- public void testPreviewCallbacksWithBuffers() throws Exception {
- TestPreviewCallback callback = new TestPreviewCallback();
- assertThat(callback.camera, nullValue());
- assertThat(callback.data, nullValue());
-
- camera.setPreviewCallbackWithBuffer(callback);
- shadowCamera.invokePreviewCallback("foobar".getBytes());
-
- assertThat(callback.camera, sameInstance(camera));
- assertThat(callback.data, equalTo("foobar".getBytes()));
- }
-
- @Test
- public void testClearPreviewCallback() throws Exception {
- TestPreviewCallback callback = new TestPreviewCallback();
- assertThat(callback.camera, nullValue());
- assertThat(callback.data, nullValue());
-
- camera.setPreviewCallback(callback);
- camera.setPreviewCallback(null);
-
- shadowCamera.invokePreviewCallback("foobar".getBytes());
- assertThat(callback.camera, nullValue());
- assertThat(callback.data, nullValue());
-
- camera.setOneShotPreviewCallback(callback);
- camera.setOneShotPreviewCallback(null);
-
- shadowCamera.invokePreviewCallback("foobar".getBytes());
- assertThat(callback.camera, nullValue());
- assertThat(callback.data, nullValue());
-
- camera.setPreviewCallbackWithBuffer(callback);
- camera.setPreviewCallbackWithBuffer(null);
-
- shadowCamera.invokePreviewCallback("foobar".getBytes());
- assertThat(callback.camera, nullValue());
- assertThat(callback.data, nullValue());
- }
-
- @Test
- public void testCameraInfoNoCameras() throws Exception {
- assertThat(Camera.getNumberOfCameras(), equalTo(0));
- }
-
- @Test
- public void testCameraInfoBackOnly() throws Exception {
- Camera.CameraInfo cameraQuery = new Camera.CameraInfo();
-
- addBackCamera();
- Camera.getCameraInfo(0, cameraQuery);
-
- assertThat(Camera.getNumberOfCameras(), equalTo(1));
- assertThat(cameraQuery.facing, equalTo(Camera.CameraInfo.CAMERA_FACING_BACK));
- assertThat(cameraQuery.orientation, equalTo(0));
- }
-
- @Test
- public void testCameraInfoBackAndFront() throws Exception {
- Camera.CameraInfo cameraQuery = new Camera.CameraInfo();
- addBackCamera();
- addFrontCamera();
-
- assertThat( Camera.getNumberOfCameras(), equalTo(2) );
- Camera.getCameraInfo(0, cameraQuery);
- assertThat( cameraQuery.facing, equalTo(Camera.CameraInfo.CAMERA_FACING_BACK) );
- assertThat( cameraQuery.orientation, equalTo(0) );
- Camera.getCameraInfo(1, cameraQuery);
- assertThat( cameraQuery.facing, equalTo(Camera.CameraInfo.CAMERA_FACING_FRONT) );
- assertThat( cameraQuery.orientation, equalTo(90) );
- }
-
- private void addBackCamera() {
- Camera.CameraInfo frontCamera = new Camera.CameraInfo();
- frontCamera.facing = Camera.CameraInfo.CAMERA_FACING_BACK;
- frontCamera.orientation = 0;
- ShadowCamera.addCameraInfo(0, frontCamera);
- }
-
- private void addFrontCamera() {
- Camera.CameraInfo backCamera = new Camera.CameraInfo();
- backCamera.facing = Camera.CameraInfo.CAMERA_FACING_FRONT;
- backCamera.orientation = 90;
- ShadowCamera.addCameraInfo(1, backCamera);
- }
-
- private class TestPreviewCallback implements Camera.PreviewCallback {
- public Camera camera = null;
- public byte[] data = null;
-
- @Override
- public void onPreviewFrame(byte[] data, Camera camera) {
- this.data = data;
- this.camera = camera;
- }
- }
-
- private class TestSurfaceHolder implements SurfaceHolder {
-
- @Override
- public void addCallback(Callback callback) {
- }
-
- @Override
- public Surface getSurface() {
- return null;
- }
-
- @Override
- public Rect getSurfaceFrame() {
- return null;
- }
-
- @Override
- public boolean isCreating() {
- return false;
- }
-
- @Override
- public Canvas lockCanvas() {
- return null;
- }
-
- @Override
- public Canvas lockCanvas(Rect dirty) {
- return null;
- }
-
- @Override
- public void removeCallback(Callback callback) {
- }
-
- @Override
- public void setFixedSize(int width, int height) {
- }
-
- @Override
- public void setFormat(int format) {
- }
-
- @Override
- public void setKeepScreenOn(boolean screenOn) {
- }
-
- @Override
- public void setSizeFromLayout() {
- }
-
- @Override
- public void setType(int type) {
- }
-
- @Override
- public void unlockCanvasAndPost(Canvas canvas) {
- }
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/CanvasTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/CanvasTest.java
deleted file mode 100644
index e9c14fd0c..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/CanvasTest.java
+++ /dev/null
@@ -1,109 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.graphics.*;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertThat;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class CanvasTest {
- private Bitmap targetBitmap;
- private Bitmap imageBitmap;
-
- @Before
- public void setUp() throws Exception {
- targetBitmap = Robolectric.newInstanceOf(Bitmap.class);
- imageBitmap = BitmapFactory.decodeFile("/an/image.jpg");
- }
-
- @Test
- public void shouldDescribeBitmapDrawing() throws Exception {
- Canvas canvas = new Canvas(targetBitmap);
- canvas.drawBitmap(imageBitmap, 1, 2, new Paint());
- canvas.drawBitmap(imageBitmap, 100, 200, new Paint());
-
- assertEquals("Bitmap for file:/an/image.jpg at (1,2)\n" +
- "Bitmap for file:/an/image.jpg at (100,200)", shadowOf(canvas).getDescription());
-
- assertEquals("Bitmap for file:/an/image.jpg at (1,2)\n" +
- "Bitmap for file:/an/image.jpg at (100,200)", shadowOf(targetBitmap).getDescription());
- }
-
- @Test
- public void shouldDescribeBitmapDrawing_WithMatrix() throws Exception {
- Canvas canvas = new Canvas(targetBitmap);
- canvas.drawBitmap(imageBitmap, new Matrix(), new Paint());
- canvas.drawBitmap(imageBitmap, new Matrix(), new Paint());
-
- assertEquals("Bitmap for file:/an/image.jpg transformed by matrix\n" +
- "Bitmap for file:/an/image.jpg transformed by matrix", shadowOf(canvas).getDescription());
-
- assertEquals("Bitmap for file:/an/image.jpg transformed by matrix\n" +
- "Bitmap for file:/an/image.jpg transformed by matrix", shadowOf(targetBitmap).getDescription());
- }
-
- @Test
- public void visualize_shouldReturnDescription() throws Exception {
- Canvas canvas = new Canvas(targetBitmap);
- canvas.drawBitmap(imageBitmap, new Matrix(), new Paint());
- canvas.drawBitmap(imageBitmap, new Matrix(), new Paint());
-
- assertEquals("Bitmap for file:/an/image.jpg transformed by matrix\n" +
- "Bitmap for file:/an/image.jpg transformed by matrix", Robolectric.visualize(canvas));
-
- }
-
- @Test
- public void drawColor_shouldReturnDescription() throws Exception {
- Canvas canvas = new Canvas(targetBitmap);
- canvas.drawColor(Color.WHITE);
- canvas.drawColor(Color.GREEN);
- canvas.drawColor(Color.TRANSPARENT);
- assertEquals("draw color -1draw color -16711936draw color 0",
- shadowOf(canvas).getDescription());
- }
-
- @Test
- public void drawPath_shouldRecordThePathAndThePaint() throws Exception {
- Canvas canvas = new Canvas(targetBitmap);
- Path path = new Path();
- path.lineTo(10, 10);
-
- Paint paint = new Paint();
- paint.setAlpha(7);
- canvas.drawPath(path, paint);
-
- ShadowCanvas shadow = shadowOf(canvas);
- assertThat(shadow.getPathPaintHistoryCount(), equalTo(1));
- assertThat(shadow.getDrawnPath(0), equalTo(path));
- assertThat(shadow.getDrawnPathPaint(0), equalTo(paint));
- }
-
- @Test
- public void drawPath_shouldAppendDescriptionToBitmap() throws Exception {
- Canvas canvas = new Canvas(targetBitmap);
- Path path1 = new Path();
- path1.lineTo(10, 10);
- path1.moveTo(20, 15);
- Path path2 = new Path();
- path2.moveTo(100, 100);
- path2.lineTo(150, 140);
-
- Paint paint = new Paint();
- canvas.drawPath(path1, paint);
- canvas.drawPath(path2, paint);
-
- assertEquals("Path " + shadowOf(path1).getPoints().toString() + "\n"
- + "Path " + shadowOf(path2).getPoints().toString(), shadowOf(canvas).getDescription());
-
- assertEquals("Path " + shadowOf(path1).getPoints().toString() + "\n"
- + "Path " + shadowOf(path2).getPoints().toString(), shadowOf(targetBitmap).getDescription());
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/CheckBoxTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/CheckBoxTest.java
deleted file mode 100644
index 9fb89f476..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/CheckBoxTest.java
+++ /dev/null
@@ -1,27 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.widget.CheckBox;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.junit.Assert.assertThat;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class CheckBoxTest {
- @Test
- public void testWorks() throws Exception {
- CheckBox checkBox = new CheckBox(null);
- assertThat(checkBox.isChecked(), equalTo(false));
-
- checkBox.setChecked(true);
- assertThat(checkBox.isChecked(), equalTo(true));
-
- checkBox.performClick();
- assertThat(checkBox.isChecked(), equalTo(false));
-
- checkBox.toggle();
- assertThat(checkBox.isChecked(), equalTo(true));
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/CheckedTextViewTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/CheckedTextViewTest.java
deleted file mode 100644
index d7eee2a88..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/CheckedTextViewTest.java
+++ /dev/null
@@ -1,41 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.app.Activity;
-import android.widget.CheckedTextView;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class CheckedTextViewTest {
-
- private CheckedTextView checkedTextView;
-
- @Before
- public void beforeTests() {
- checkedTextView = new CheckedTextView(new Activity());
- }
-
- @Test
- public void testToggle() {
- assertFalse(checkedTextView.isChecked());
-
- checkedTextView.toggle();
-
- assertTrue(checkedTextView.isChecked());
- }
-
- @Test
- public void testSetChecked() {
- assertFalse(checkedTextView.isChecked());
-
- checkedTextView.setChecked(true);
-
- assertTrue(checkedTextView.isChecked());
- }
-
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ClipboardManagerTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/ClipboardManagerTest.java
deleted file mode 100644
index 194ea613f..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ClipboardManagerTest.java
+++ /dev/null
@@ -1,54 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.content.Context;
-import android.text.ClipboardManager;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static org.hamcrest.core.IsEqual.equalTo;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertThat;
-import static org.junit.Assert.assertTrue;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class ClipboardManagerTest {
-
- private ClipboardManager clipboardManager;
-
- @Before public void setUp() throws Exception {
- clipboardManager = (ClipboardManager) Robolectric.application.getSystemService(Context.CLIPBOARD_SERVICE);
- }
-
- @Test
- public void shouldStoreText() throws Exception {
- clipboardManager.setText("BLARG!!!");
- assertThat(clipboardManager.getText().toString(), equalTo("BLARG!!!"));
- }
-
- @Test
- public void shouldNotHaveTextIfTextIsNull() throws Exception {
- clipboardManager.setText(null);
- assertFalse(clipboardManager.hasText());
- }
-
- @Test
- public void shouldNotHaveTextIfTextIsEmpty() throws Exception {
- clipboardManager.setText("");
- assertFalse(clipboardManager.hasText());
- }
-
- @Test
- public void shouldHaveTextIfEmptyString() throws Exception {
- clipboardManager.setText(" ");
- assertTrue(clipboardManager.hasText());
- }
-
- @Test
- public void shouldHaveTextIfString() throws Exception {
- clipboardManager.setText("BLARG");
- assertTrue(clipboardManager.hasText());
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ColorTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/ColorTest.java
deleted file mode 100644
index ca6c14a21..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ColorTest.java
+++ /dev/null
@@ -1,26 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import static org.hamcrest.CoreMatchers.is;
-import static org.junit.Assert.assertThat;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import android.graphics.Color;
-
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class ColorTest {
- @Test
- public void testRgb() {
- int color = Color.rgb(160, 160, 160);
- assertThat(color, is(-6250336));
- }
-
- @Test
- public void testArgb() {
- int color = Color.argb(100, 160, 160, 160);
- assertThat(color, is(1688248480));
- }
-} \ No newline at end of file
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ConfigurationTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/ConfigurationTest.java
deleted file mode 100644
index 4db940728..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ConfigurationTest.java
+++ /dev/null
@@ -1,44 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-
-import java.util.Locale;
-
-import android.content.res.Configuration;
-
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.junit.Assert.assertThat;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class ConfigurationTest {
-
- private Configuration configuration;
- private ShadowConfiguration shConfiguration;
-
- @Before
- public void setUp() throws Exception {
- configuration = new Configuration();
- shConfiguration = Robolectric.shadowOf( configuration );
- }
-
- @Test
- public void testSetToDefaults() throws Exception {
- configuration.setToDefaults();
- assertThat(configuration.screenLayout, equalTo(Configuration.SCREENLAYOUT_LONG_NO | Configuration.SCREENLAYOUT_SIZE_NORMAL));
- }
-
- @Test
- public void testSetLocale() {
- shConfiguration.setLocale( Locale.US );
- assertThat( configuration.locale, equalTo( Locale.US ) );
-
- shConfiguration.setLocale( Locale.FRANCE);
- assertThat( configuration.locale, equalTo( Locale.FRANCE ) );
-}
-
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ConnectivityManagerTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/ConnectivityManagerTest.java
deleted file mode 100644
index 7355d4a50..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ConnectivityManagerTest.java
+++ /dev/null
@@ -1,105 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.content.Context;
-import android.net.ConnectivityManager;
-import android.net.NetworkInfo;
-import android.telephony.TelephonyManager;
-
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.CoreMatchers.sameInstance;
-import static org.junit.Assert.*;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class ConnectivityManagerTest {
- private ConnectivityManager connectivityManager;
- private ShadowNetworkInfo shadowOfActiveNetworkInfo;
- private ShadowConnectivityManager shadowConnectivityManager;
-
- @Before
- public void setUp() throws Exception {
- connectivityManager = (ConnectivityManager) Robolectric.application.getSystemService(Context.CONNECTIVITY_SERVICE);
- shadowConnectivityManager = shadowOf(connectivityManager);
- shadowOfActiveNetworkInfo = shadowOf(connectivityManager.getActiveNetworkInfo());
- }
-
- @Test
- public void getConnectivityManagerShouldNotBeNull() {
- assertNotNull(connectivityManager);
- assertNotNull(connectivityManager.getActiveNetworkInfo());
- }
-
- @Test
- public void networkInfoShouldReturnTrueCorrectly() {
- shadowOfActiveNetworkInfo.setConnectionStatus(true);
-
- assertTrue(connectivityManager.getActiveNetworkInfo().isConnectedOrConnecting());
- assertTrue(connectivityManager.getActiveNetworkInfo().isConnected());
- }
-
- @Test
- public void getNetworkInfoShouldReturnAssignedValue() throws Exception {
- NetworkInfo networkInfo = ShadowNetworkInfo.newInstance(NetworkInfo.DetailedState.CONNECTING);
- shadowConnectivityManager.setNetworkInfo(ConnectivityManager.TYPE_WIFI, networkInfo);
- NetworkInfo actual = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
- assertThat(actual, sameInstance(networkInfo));
- assertThat(actual.getDetailedState(), is(NetworkInfo.DetailedState.CONNECTING));
- }
-
- @Test
- public void networkInfoShouldReturnFalseCorrectly() {
- shadowOfActiveNetworkInfo.setConnectionStatus(false);
-
- assertFalse(connectivityManager.getActiveNetworkInfo().isConnectedOrConnecting());
- assertFalse(connectivityManager.getActiveNetworkInfo().isConnected());
- }
-
- @Test
- public void networkInfoShouldReturnTypeCorrectly(){
- shadowOfActiveNetworkInfo.setConnectionType(ConnectivityManager.TYPE_MOBILE);
- assertEquals(ConnectivityManager.TYPE_MOBILE, shadowOfActiveNetworkInfo.getType());
-
- shadowOfActiveNetworkInfo.setConnectionType(ConnectivityManager.TYPE_WIFI);
- assertEquals(ConnectivityManager.TYPE_WIFI, shadowOfActiveNetworkInfo.getType());
- }
-
- @Test
- public void shouldGetAndSetBackgroundDataSetting() throws Exception {
- assertFalse(connectivityManager.getBackgroundDataSetting());
- shadowConnectivityManager.setBackgroundDataSetting(true);
- assertTrue(connectivityManager.getBackgroundDataSetting());
- }
-
- @Test
- public void shouldSetActiveNetworkInfo() throws Exception {
- shadowConnectivityManager.setActiveNetworkInfo(null);
- assertNull(connectivityManager.getActiveNetworkInfo());
- shadowConnectivityManager.setActiveNetworkInfo(ShadowNetworkInfo.newInstance(null,
- ConnectivityManager.TYPE_MOBILE_HIPRI,
- TelephonyManager.NETWORK_TYPE_EDGE, true, false));
-
- NetworkInfo info = connectivityManager.getActiveNetworkInfo();
-
- assertEquals(ConnectivityManager.TYPE_MOBILE_HIPRI, info.getType());
- assertEquals(TelephonyManager.NETWORK_TYPE_EDGE, info.getSubtype());
- assertTrue(info.isAvailable());
- assertFalse(info.isConnected());
- }
-
- @Test
- public void shouldGetAllNetworkInfo() throws Exception {
- NetworkInfo[] infos = connectivityManager.getAllNetworkInfo();
- assertNotNull(infos);
- assertEquals(1, infos.length);
- assertSame(connectivityManager.getActiveNetworkInfo(), infos[0]);
-
- shadowConnectivityManager.setActiveNetworkInfo(null);
- assertEquals(0, connectivityManager.getAllNetworkInfo().length);
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ContentProviderOperationBuilderTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/ContentProviderOperationBuilderTest.java
deleted file mode 100644
index 1e1f81121..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ContentProviderOperationBuilderTest.java
+++ /dev/null
@@ -1,70 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.CoreMatchers.notNullValue;
-import static org.junit.Assert.assertThat;
-
-import java.util.Map;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import android.content.ContentProviderOperation;
-import android.content.ContentProviderOperation.Builder;
-
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class ContentProviderOperationBuilderTest {
- private Builder builder;
- private ShadowContentProviderOperationBuilder shadowBuilder;
-
- @Before
- public void before() {
- builder = Robolectric.newInstanceOf(Builder.class);
- shadowBuilder = Robolectric.shadowOf(builder);
- }
-
- @Test
- public void withValue() {
- builder
- .withValue("stringTest", "bar")
- .withValue("intTest", 5)
- .withValue("longTest", 10L);
-
- Map<String, Object> values = shadowBuilder.getValues();
- assertThat(values.size(), is(3));
- assertThat(values.get("stringTest").toString(), equalTo("bar"));
- assertThat(Integer.parseInt(values.get("intTest").toString()), equalTo(5));
- assertThat(Long.parseLong(values.get("longTest").toString()), equalTo(10L));
- }
-
- @Test
- public void withSelection() {
- builder
- .withSelection("first", new String[] { "a", "b" })
- .withSelection("second", new String[] { "c", "d" });
-
- Map<String, String[]> selections = shadowBuilder.getSelections();
- assertThat(selections.size(), is(2));
- assertThat(selections.get("first"), equalTo(new String[] { "a", "b" }));
- assertThat(selections.get("second"), equalTo(new String[] { "c", "d" }));
- }
-
- @Test
- public void withValueBackReference() {
- builder.withValueBackReference("foo", 5);
-
- int backReference = shadowBuilder.getWithValueBackReference("foo");
- assertThat(backReference, is(5));
- }
-
- @Test
- public void build() {
- ContentProviderOperation operation = builder.build();
- assertThat(operation, notNullValue());
- }
-} \ No newline at end of file
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ContentProviderOperationTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/ContentProviderOperationTest.java
deleted file mode 100644
index 75854fd9d..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ContentProviderOperationTest.java
+++ /dev/null
@@ -1,76 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.CoreMatchers.is;
-import static org.junit.Assert.assertThat;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import android.content.ContentProviderOperation;
-import android.content.ContentProviderOperation.Builder;
-import android.net.Uri;
-
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class ContentProviderOperationTest {
-
- @Test
- public void newInsert() {
- final Uri URI = Uri.parse("content://com.xtremelabs.robolectric");
- Builder builder = ContentProviderOperation.newInsert(URI);
- builder.withValue("stringValue", "bar");
- builder.withValue("intValue", 5);
- ContentProviderOperation operation = builder.build();
- ShadowContentProviderOperation shadowOperation = Robolectric.shadowOf(operation);
- assertThat(operation.getUri(), equalTo(URI));
- assertThat(shadowOperation.isInsert(), is(true));
- assertThat(shadowOperation.isUpdate(), is(false));
- assertThat(shadowOperation.isDelete(), is(false));
- assertThat(shadowOperation.getValues().size(), is(2));
- assertThat(shadowOperation.getValues().get("stringValue").toString(), equalTo("bar"));
- assertThat(Integer.parseInt(shadowOperation.getValues().get("intValue").toString()), is(5));
- }
-
- @Test
- public void newInsertWithValueBackReference() {
- final Uri URI = Uri.parse("content://com.xtremelabs.robolectric");
- Builder builder = ContentProviderOperation.newInsert(URI);
- builder.withValueBackReference("my_id", 0);
- ContentProviderOperation operation = builder.build();
- ShadowContentProviderOperationBuilder shadowBuilder = Robolectric.shadowOf(builder);
- ShadowContentProviderOperation shadowOperation = Robolectric.shadowOf(operation);
- assertThat(shadowBuilder.getWithValueBackReference("my_id"), is(0));
- assertThat(shadowOperation.getWithValueBackReference("my_id"), is(0));
- }
-
- @Test
- public void newUpdate() {
- final Uri URI = Uri.parse("content://com.xtremelabs.robolectric");
- Builder builder = ContentProviderOperation.newUpdate(URI);
- builder.withSelection("id_column", new String[] { "5" });
- ContentProviderOperation operation = builder.build();
- ShadowContentProviderOperation shadowOperation = Robolectric.shadowOf(operation);
- assertThat(operation.getUri(), equalTo(URI));
- assertThat(shadowOperation.isInsert(), is(false));
- assertThat(shadowOperation.isUpdate(), is(true));
- assertThat(shadowOperation.isDelete(), is(false));
- assertThat(shadowOperation.getSelections().get("id_column"), equalTo(new String[] { "5" }));
- }
-
- @Test
- public void newDelete() {
- final Uri URI = Uri.parse("content://com.xtremelabs.robolectric");
- Builder builder = ContentProviderOperation.newDelete(URI);
- builder.withSelection("id_column", new String[] { "5" });
- ContentProviderOperation operation = builder.build();
- ShadowContentProviderOperation shadowOperation = Robolectric.shadowOf(operation);
- assertThat(operation.getUri(), equalTo(URI));
- assertThat(shadowOperation.isInsert(), is(false));
- assertThat(shadowOperation.isUpdate(), is(false));
- assertThat(shadowOperation.isDelete(), is(true));
- assertThat(shadowOperation.getSelections().get("id_column"), equalTo(new String[] { "5" }));
- }
-} \ No newline at end of file
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ContentProviderResultTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/ContentProviderResultTest.java
deleted file mode 100644
index 680e8c012..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ContentProviderResultTest.java
+++ /dev/null
@@ -1,29 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.CoreMatchers.is;
-import static org.junit.Assert.assertThat;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import android.content.ContentProviderResult;
-import android.net.Uri;
-
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class ContentProviderResultTest {
- @Test
- public void count() {
- ContentProviderResult result = new ContentProviderResult(5);
- assertThat(result.count, is(5));
- }
-
- @Test
- public void uri() {
- Uri uri = Uri.parse("content://com.xtremelabs.robolectric");
- ContentProviderResult result = new ContentProviderResult(uri);
- assertThat(result.uri, equalTo(uri));
- }
-} \ No newline at end of file
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ContentProviderTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/ContentProviderTest.java
deleted file mode 100644
index 8634f0d52..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ContentProviderTest.java
+++ /dev/null
@@ -1,71 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.CoreMatchers.notNullValue;
-import static org.junit.Assert.assertThat;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import android.content.ContentProvider;
-import android.content.ContentValues;
-import android.database.Cursor;
-import android.net.Uri;
-
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class ContentProviderTest {
-
- class TestContentProvider extends ContentProvider {
-
- @Override
- public int delete(Uri arg0, String arg1, String[] arg2) {
- return 0;
- }
-
- @Override
- public String getType(Uri arg0) {
- return null;
- }
-
- @Override
- public Uri insert(Uri arg0, ContentValues arg1) {
- return null;
- }
-
- @Override
- public boolean onCreate() {
- return false;
- }
-
- @Override
- public Cursor query(Uri arg0, String[] arg1, String arg2,
- String[] arg3, String arg4) {
- return null;
- }
-
- @Override
- public int update(Uri arg0, ContentValues arg1, String arg2,
- String[] arg3) {
- return 0;
- }
-
- }
-
- TestContentProvider provider;
-
- @Before public void instantiateProvider() {
- provider = new TestContentProvider();
- }
-
- @Test public void hasAContext() {
- assertThat(provider.getContext(), is(notNullValue()));
- }
-
- @Test public void canGetAResolver() {
- assertThat(provider.getContext().getContentResolver(), is(notNullValue()));
- }
-
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ContentResolverTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/ContentResolverTest.java
deleted file mode 100644
index a29aaa4ce..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ContentResolverTest.java
+++ /dev/null
@@ -1,371 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import static android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.CoreMatchers.hasItem;
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.CoreMatchers.notNullValue;
-import static org.hamcrest.CoreMatchers.nullValue;
-import static org.hamcrest.CoreMatchers.sameInstance;
-import static org.junit.Assert.*;
-
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.util.ArrayList;
-import java.util.List;
-
-import android.accounts.Account;
-import android.content.*;
-import android.os.Bundle;
-import org.hamcrest.CoreMatchers;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import android.app.Activity;
-import android.database.Cursor;
-import android.net.Uri;
-import android.os.RemoteException;
-
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import com.xtremelabs.robolectric.tester.android.database.TestCursor;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class ContentResolverTest {
- static final String AUTHORITY = "com.xtremelabs.robolectric";
-
- private ContentResolver contentResolver;
- private ShadowContentResolver shadowContentResolver;
- private Uri uri21;
- private Uri uri22;
- private Account a, b;
-
- @Before
- public void setUp() throws Exception {
- contentResolver = new Activity().getContentResolver();
- shadowContentResolver = shadowOf(contentResolver);
- uri21 = Uri.parse(EXTERNAL_CONTENT_URI.toString() + "/21");
- uri22 = Uri.parse(EXTERNAL_CONTENT_URI.toString() + "/22");
-
- a = new Account("a", "type");
- b = new Account("b", "type");
- }
-
- @Test
- public void insert_shouldReturnIncreasingUris() throws Exception {
- shadowContentResolver.setNextDatabaseIdForInserts(21);
-
- assertThat(contentResolver.insert(EXTERNAL_CONTENT_URI, new ContentValues()), equalTo(uri21));
- assertThat(contentResolver.insert(EXTERNAL_CONTENT_URI, new ContentValues()), equalTo(uri22));
- }
-
- @Test
- public void insert_shouldTrackInsertStatements() throws Exception {
- ContentValues contentValues = new ContentValues();
- contentValues.put("foo", "bar");
- contentResolver.insert(EXTERNAL_CONTENT_URI, contentValues);
- assertThat(shadowContentResolver.getInsertStatements().size(), is(1));
- assertThat(shadowContentResolver.getInsertStatements().get(0).getUri(), equalTo(EXTERNAL_CONTENT_URI));
- assertThat(shadowContentResolver.getInsertStatements().get(0).getContentValues().getAsString("foo"), equalTo("bar"));
-
- contentValues = new ContentValues();
- contentValues.put("hello", "world");
- contentResolver.insert(EXTERNAL_CONTENT_URI, contentValues);
- assertThat(shadowContentResolver.getInsertStatements().size(), is(2));
- assertThat(shadowContentResolver.getInsertStatements().get(1).getContentValues().getAsString("hello"), equalTo("world"));
- }
-
- @Test
- public void insert_shouldTrackUpdateStatements() throws Exception {
- ContentValues contentValues = new ContentValues();
- contentValues.put("foo", "bar");
- contentResolver.update(EXTERNAL_CONTENT_URI, contentValues, "robolectric", new String[] { "awesome" });
- assertThat(shadowContentResolver.getUpdateStatements().size(), is(1));
- assertThat(shadowContentResolver.getUpdateStatements().get(0).getUri(), equalTo(EXTERNAL_CONTENT_URI));
- assertThat(shadowContentResolver.getUpdateStatements().get(0).getContentValues().getAsString("foo"), equalTo("bar"));
- assertThat(shadowContentResolver.getUpdateStatements().get(0).getWhere(), equalTo("robolectric"));
- assertThat(shadowContentResolver.getUpdateStatements().get(0).getSelectionArgs(), equalTo(new String[] { "awesome" }));
-
- contentValues = new ContentValues();
- contentValues.put("hello", "world");
- contentResolver.update(EXTERNAL_CONTENT_URI, contentValues, null, null);
- assertThat(shadowContentResolver.getUpdateStatements().size(), is(2));
- assertThat(shadowContentResolver.getUpdateStatements().get(1).getUri(), equalTo(EXTERNAL_CONTENT_URI));
- assertThat(shadowContentResolver.getUpdateStatements().get(1).getContentValues().getAsString("hello"), equalTo("world"));
- assertThat(shadowContentResolver.getUpdateStatements().get(1).getWhere(), nullValue());
- assertThat(shadowContentResolver.getUpdateStatements().get(1).getSelectionArgs(), nullValue());
- }
-
- @Test
- public void delete_shouldTrackDeletedUris() throws Exception {
- assertThat(shadowContentResolver.getDeletedUris().size(), equalTo(0));
-
- assertThat(contentResolver.delete(uri21, null, null), equalTo(1));
- assertThat(shadowContentResolver.getDeletedUris(), hasItem(uri21));
- assertThat(shadowContentResolver.getDeletedUris().size(), equalTo(1));
-
- assertThat(contentResolver.delete(uri22, null, null), equalTo(1));
- assertThat(shadowContentResolver.getDeletedUris(), hasItem(uri22));
- assertThat(shadowContentResolver.getDeletedUris().size(), equalTo(2));
- }
-
- @Test
- public void delete_shouldTrackDeletedStatements() {
- assertThat(shadowContentResolver.getDeleteStatements().size(), equalTo(0));
-
- assertThat(contentResolver.delete(uri21, "id", new String[] { "5" }), equalTo(1));
- assertThat(shadowContentResolver.getDeleteStatements().size(), equalTo(1));
- assertThat(shadowContentResolver.getDeleteStatements().get(0).getUri(), equalTo(uri21));
- assertThat(shadowContentResolver.getDeleteStatements().get(0).getWhere(), equalTo("id"));
- assertThat(shadowContentResolver.getDeleteStatements().get(0).getSelectionArgs()[0], equalTo("5"));
-
- assertThat(contentResolver.delete(uri21, "foo", new String[] { "bar" }), equalTo(1));
- assertThat(shadowContentResolver.getDeleteStatements().size(), equalTo(2));
- assertThat(shadowContentResolver.getDeleteStatements().get(1).getUri(), equalTo(uri21));
- assertThat(shadowContentResolver.getDeleteStatements().get(1).getWhere(), equalTo("foo"));
- assertThat(shadowContentResolver.getDeleteStatements().get(1).getSelectionArgs()[0], equalTo("bar"));
- }
-
- @Test
- public void query_shouldReturnTheCursorThatWasSet() throws Exception {
- assertNull(shadowContentResolver.query(null, null, null, null, null));
- TestCursor cursor = new TestCursor();
- shadowContentResolver.setCursor(cursor);
- assertThat((TestCursor) shadowContentResolver.query(null, null, null, null, null),
- sameInstance(cursor));
- }
-
- @Test
- public void query__shouldReturnSpecificCursorsForSpecificUris() throws Exception {
- assertNull(shadowContentResolver.query(uri21, null, null, null, null));
- assertNull(shadowContentResolver.query(uri22, null, null, null, null));
-
- TestCursor cursor21 = new TestCursor();
- TestCursor cursor22 = new TestCursor();
- shadowContentResolver.setCursor(uri21, cursor21);
- shadowContentResolver.setCursor(uri22, cursor22);
-
- assertThat((TestCursor) shadowContentResolver.query(uri21, null, null, null, null),
- sameInstance(cursor21));
- assertThat((TestCursor) shadowContentResolver.query(uri22, null, null, null, null),
- sameInstance(cursor22));
- }
-
- @Test
- public void query__shouldKnowWhatItsParamsWere() throws Exception {
- String[] projection = {};
- String selection = "select";
- String[] selectionArgs = {};
- String sortOrder = "order";
-
- QueryParamTrackingTestCursor testCursor = new QueryParamTrackingTestCursor();
-
- shadowContentResolver.setCursor(testCursor);
- Cursor cursor = shadowContentResolver.query(uri21, projection, selection, selectionArgs, sortOrder);
- assertThat((QueryParamTrackingTestCursor)cursor, equalTo(testCursor));
- assertThat(testCursor.uri, equalTo(uri21));
- assertThat(testCursor.projection, equalTo(projection));
- assertThat(testCursor.selection, equalTo(selection));
- assertThat(testCursor.selectionArgs, equalTo(selectionArgs));
- assertThat(testCursor.sortOrder, equalTo(sortOrder));
- }
-
- @Test
- public void openInputStream_shouldReturnAnInputStream() throws Exception {
- assertThat(contentResolver.openInputStream(uri21), CoreMatchers.instanceOf(InputStream.class));
- }
-
- @Test
- public void openOutputStream_shouldReturnAnOutputStream() throws Exception {
- assertThat(contentResolver.openOutputStream(uri21), CoreMatchers.instanceOf(OutputStream.class));
- }
-
- @Test
- public void shouldTrackNotifiedUris() throws Exception {
- contentResolver.notifyChange(Uri.parse("foo"), null, true);
- contentResolver.notifyChange(Uri.parse("bar"), null);
-
- assertThat(shadowContentResolver.getNotifiedUris().size(), equalTo(2));
- ShadowContentResolver.NotifiedUri uri = shadowContentResolver.getNotifiedUris().get(0);
-
- assertThat(uri.uri.toString(), equalTo("foo"));
- assertTrue(uri.syncToNetwork);
- assertNull(uri.observer);
-
- uri = shadowContentResolver.getNotifiedUris().get(1);
-
- assertThat(uri.uri.toString(), equalTo("bar"));
- assertFalse(uri.syncToNetwork);
- assertNull(uri.observer);
- }
-
- @Test
- public void applyBatch() throws RemoteException, OperationApplicationException {
- ArrayList<ContentProviderOperation> resultOperations = shadowContentResolver.getContentProviderOperations(AUTHORITY);
- assertThat(resultOperations, notNullValue());
- assertThat(resultOperations.size(), is(0));
-
- ContentProviderResult[] contentProviderResults = new ContentProviderResult[] {
- new ContentProviderResult(1),
- new ContentProviderResult(1),
- };
- shadowContentResolver.setContentProviderResult(contentProviderResults);
- Uri uri = Uri.parse("content://com.xtremelabs.robolectric");
- ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>();
- operations.add(ContentProviderOperation.newInsert(uri)
- .withValue("column1", "foo")
- .withValue("column2", 5)
- .build());
- operations.add(ContentProviderOperation.newUpdate(uri)
- .withSelection("id_column", new String[] { "99" })
- .withValue("column1", "bar")
- .build());
- operations.add(ContentProviderOperation.newDelete(uri)
- .withSelection("id_column", new String[] { "11" })
- .build());
- ContentProviderResult[] result = contentResolver.applyBatch(AUTHORITY, operations);
-
- resultOperations = shadowContentResolver.getContentProviderOperations(AUTHORITY);
- assertThat(resultOperations, equalTo(operations));
- assertThat(result, equalTo(contentProviderResults));
- }
-
- @Test
- public void shouldKeepTrackOfSyncRequests() throws Exception {
- ShadowContentResolver.Status status = ShadowContentResolver.getStatus(a, AUTHORITY, true);
- assertNotNull(status);
- assertThat(status.syncRequests, equalTo(0));
- ContentResolver.requestSync(a, AUTHORITY, new Bundle());
- assertThat(status.syncRequests, equalTo(1));
- assertNotNull(status.syncExtras);
- }
-
- @Test
- public void shouldSetIsSyncable() throws Exception {
- assertThat(ContentResolver.getIsSyncable(a, AUTHORITY), equalTo(-1));
- assertThat(ContentResolver.getIsSyncable(b, AUTHORITY), equalTo(-1));
- ContentResolver.setIsSyncable(a, AUTHORITY, 1);
- ContentResolver.setIsSyncable(b, AUTHORITY, 2);
- assertThat(ContentResolver.getIsSyncable(a, AUTHORITY), equalTo(1));
- assertThat(ContentResolver.getIsSyncable(b, AUTHORITY), equalTo(2));
- }
-
- @Test
- public void shouldSetSyncAutomatically() throws Exception {
- assertFalse(ContentResolver.getSyncAutomatically(a, AUTHORITY));
- ContentResolver.setSyncAutomatically(a, AUTHORITY, true);
- assertTrue(ContentResolver.getSyncAutomatically(a, AUTHORITY));
- }
-
- @Test
- public void shouldAddPeriodicSync() throws Exception {
- ContentResolver.addPeriodicSync(a, AUTHORITY, new Bundle(), 6000l);
- ShadowContentResolver.Status status = ShadowContentResolver.getStatus(a, AUTHORITY);
- assertNotNull(status);
- assertThat(status.syncs.size(), is(1));
- assertThat(status.syncs.get(0).period, is(6000l));
- assertNotNull(status.syncs.get(0).extras);
- }
-
- @Test
- public void shouldRemovePeriodSync() throws Exception {
- ContentResolver.addPeriodicSync(a, AUTHORITY, new Bundle(), 6000l);
- ContentResolver.removePeriodicSync(a, AUTHORITY, new Bundle());
- assertThat(ShadowContentResolver.getStatus(a, AUTHORITY).syncs.size(), is(0));
- }
-
- @Test
- public void shouldGetPeriodSyncs() throws Exception {
- assertThat(ContentResolver.getPeriodicSyncs(a, AUTHORITY).size(), is(0));
- ContentResolver.addPeriodicSync(a, AUTHORITY, new Bundle(), 6000l);
-
- List<PeriodicSync> syncs = ContentResolver.getPeriodicSyncs(a, AUTHORITY);
- assertThat(syncs.size(), is(1));
-
- PeriodicSync first = syncs.get(0);
- assertThat(first.account, equalTo(a));
- assertThat(first.authority, equalTo(AUTHORITY));
- assertThat(first.period, equalTo(6000l));
- assertNotNull(first.extras);
- }
-
- @Test
- public void shouldValidateSyncExtras() throws Exception {
- Bundle bundle = new Bundle();
- bundle.putString("foo", "strings");
- bundle.putLong("long", 10l);
- bundle.putDouble("double", 10.0d);
- bundle.putFloat("float", 10.0f);
- bundle.putInt("int", 10);
- bundle.putParcelable("account", a);
- ContentResolver.validateSyncExtrasBundle(bundle);
- }
-
- @Test(expected = IllegalArgumentException.class)
- public void shouldValidateSyncExtrasAndThrow() throws Exception {
- Bundle bundle = new Bundle();
- bundle.putParcelable("intent", new Intent());
- ContentResolver.validateSyncExtrasBundle(bundle);
- }
-
- @Test
- public void shouldSetMasterSyncAutomatically() throws Exception {
- assertFalse(ContentResolver.getMasterSyncAutomatically());
- ContentResolver.setMasterSyncAutomatically(true);
- assertTrue(ContentResolver.getMasterSyncAutomatically());
- }
-
- @Test
- public void shouldDelegateCallsToRegisteredProvider() throws Exception {
- ShadowContentResolver.registerProvider(AUTHORITY, new ContentProvider() {
- @Override public boolean onCreate() {
- return false;
- }
- @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
- return new TestCursor();
- }
- @Override public Uri insert(Uri uri, ContentValues values) {
- return null;
- }
- @Override public int delete(Uri uri, String selection, String[] selectionArgs) {
- return -1;
- }
- @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
- return -1;
- }
- @Override public String getType(Uri uri) {
- return null;
- }
- });
- final Uri uri = Uri.parse("content://"+AUTHORITY+"/some/path");
- final Uri unrelated = Uri.parse("content://unrelated/some/path");
-
- assertNotNull(contentResolver.query(uri, null, null, null, null));
- assertNull(contentResolver.insert(uri, new ContentValues()));
- assertThat(contentResolver.delete(uri, null, null), is(-1));
- assertThat(contentResolver.update(uri, new ContentValues(), null, null), is(-1));
-
- assertNull(contentResolver.query(unrelated, null, null, null, null));
- assertNotNull(contentResolver.insert(unrelated, new ContentValues()));
- assertThat(contentResolver.delete(unrelated, null, null), is(1));
- assertThat(contentResolver.update(unrelated, new ContentValues(), null, null), is(0));
- }
-
- static class QueryParamTrackingTestCursor extends TestCursor {
- public Uri uri;
- public String[] projection;
- public String selection;
- public String[] selectionArgs;
- public String sortOrder;
-
- @Override
- public void setQuery(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
- this.uri = uri;
- this.projection = projection;
- this.selection = selection;
- this.selectionArgs = selectionArgs;
- this.sortOrder = sortOrder;
- }
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ContentUrisTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/ContentUrisTest.java
deleted file mode 100644
index 13fdd9eb9..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ContentUrisTest.java
+++ /dev/null
@@ -1,47 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.content.ContentUris;
-import android.net.Uri;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static org.hamcrest.CoreMatchers.is;
-import static org.junit.Assert.assertThat;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class ContentUrisTest {
- Uri URI;
-
- @Before
- public void setUp() throws Exception {
- URI = Uri.parse("content://foo.com");
- }
-
- @Test public void canAppendId() {
- assertThat(ContentUris.withAppendedId(URI, 1),
- is(Uri.parse("content://foo.com/1")));
- }
-
- @Test(expected=NullPointerException.class)
- public void appendIdThrowsNullPointerException() {
- ContentUris.withAppendedId(null, 1);
- }
-
- @Test public void canParseId() {
- assertThat(ContentUris.parseId(Uri.withAppendedPath(URI, "1")), is(1L));
- assertThat(ContentUris.parseId(URI), is(-1L));
- }
-
- @Test(expected=NumberFormatException.class)
- public void parseIdThrowsNumberFormatException() {
- ContentUris.parseId(Uri.withAppendedPath(URI, "bar"));
- }
-
- @Test(expected=UnsupportedOperationException.class)
- public void parseIdThrowsUnsupportedException() {
- ContentUris.parseId(Uri.parse("mailto:bar@foo.com"));
- }
-
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ContextTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/ContextTest.java
deleted file mode 100644
index 5978ce20b..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ContextTest.java
+++ /dev/null
@@ -1,240 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.app.Activity;
-import android.content.Context;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-
-import org.hamcrest.CoreMatchers;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.FileWriter;
-import java.io.IOException;
-
-import static org.hamcrest.CoreMatchers.*;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertThat;
-import static org.junit.Assert.assertTrue;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class ContextTest {
- private Context context;
-
- @Before
- public void setUp() throws Exception {
- context = new Activity();
- deleteDir(context.getFilesDir());
- deleteDir(context.getCacheDir());
-
- File[] files = context.getFilesDir().listFiles();
- assertNotNull(files);
- assertThat(files.length, is(0));
-
- File[] cachedFiles = context.getFilesDir().listFiles();
- assertNotNull(cachedFiles);
- assertThat(cachedFiles.length, is(0));
- }
-
- @After
- public void after() {
- deleteDir(context.getFilesDir());
- deleteDir(context.getCacheDir());
- deleteDir(context.getExternalCacheDir());
- deleteDir(context.getExternalFilesDir(null));
- }
-
- public void deleteDir(File path) {
- if (path.isDirectory()) {
- File[] files = path.listFiles();
- assertNotNull(files);
- for (File f : files) {
- deleteDir(f);
- }
- }
- path.delete();
- }
-
- @Test
- public void shouldGetApplicationDataDirectory() throws IOException {
- File dataDir = new File(ShadowContext.FILES_DIR, "data");
- assertThat(dataDir.mkdir(), is(true));
-
- dataDir = context.getDir("data", Context.MODE_PRIVATE);
- assertThat(dataDir, not(nullValue()));
- assertThat(dataDir.exists(), is(true));
- }
-
-
- @Test
- public void shouldCreateIfDoesNotExistAndGetApplicationDataDirectory() {
- File dataDir = new File(ShadowContext.FILES_DIR, "data");
- assertThat(dataDir.exists(), is(false));
-
- dataDir = context.getDir("data", Context.MODE_PRIVATE);
- assertThat(dataDir, not(nullValue()));
- assertThat(dataDir.exists(), is(true));
- }
-
- @Test
- public void shouldStubThemeStuff() throws Exception {
- assertThat(context.obtainStyledAttributes(null), not(nullValue()));
- assertThat(context.obtainStyledAttributes(0, null), not(nullValue()));
- assertThat(context.obtainStyledAttributes(null, null), not(nullValue()));
- assertThat(context.obtainStyledAttributes(null, null, 0, 0), not(nullValue()));
- }
-
- @Test
- public void getCacheDir_shouldCreateDirectory() throws Exception {
- assertTrue(context.getCacheDir().exists());
- }
-
- @Test
- public void getExternalCacheDir_shouldCreateDirectory() throws Exception {
- assertTrue(context.getExternalCacheDir().exists());
- }
-
- @Test
- public void shouldWriteToCacheDir() throws Exception {
- assertNotNull(context.getCacheDir());
- File cacheTest = new File(context.getCacheDir(), "__test__");
-
- assertThat(cacheTest.getPath(), CoreMatchers.containsString("android-cache"));
-
- FileOutputStream fos = null;
- try {
- fos = new FileOutputStream(cacheTest);
- fos.write("test".getBytes());
- } finally {
- if (fos != null)
- fos.close();
- }
- assertTrue(cacheTest.exists());
- }
-
- @Test
- public void shouldWriteToExternalCacheDir() throws Exception {
- assertNotNull(context.getExternalCacheDir());
- File cacheTest = new File(context.getExternalCacheDir(), "__test__");
-
- assertThat(cacheTest.getPath(), containsString("android-external-cache"));
-
- FileOutputStream fos = null;
- try {
- fos = new FileOutputStream(cacheTest);
- fos.write("test".getBytes());
- } finally {
- if (fos != null)
- fos.close();
- }
-
- assertTrue(cacheTest.exists());
- }
-
- @Test
- public void getFilesDir_shouldCreateDirectory() throws Exception {
- assertTrue(context.getFilesDir().exists());
- }
-
- @Test
- public void getExternalFilesDir_shouldCreateDirectory() throws Exception {
- assertTrue(context.getExternalFilesDir(null).exists());
- }
-
- @Test
- public void getExternalFilesDir_shouldCreateNamedDirectory() throws Exception {
- File f = context.getExternalFilesDir("__test__");
- assertTrue(f.exists());
- assertTrue(f.getAbsolutePath().endsWith("__test__"));
- }
-
- @Test
- public void openFileInput_shouldReturnAFileInputStream() throws Exception {
- String fileContents = "blah";
-
- File file = new File(context.getFilesDir(), "__test__");
- FileWriter fileWriter = new FileWriter(file);
- fileWriter.write(fileContents);
- fileWriter.close();
-
- FileInputStream fileInputStream = null;
- try {
- fileInputStream = context.openFileInput("__test__");
-
- byte[] bytes = new byte[fileContents.length()];
- fileInputStream.read(bytes);
- assertThat(bytes, equalTo(fileContents.getBytes()));
- } finally {
- if (fileInputStream != null)
- fileInputStream.close();
- }
- }
-
- @Test(expected = IllegalArgumentException.class)
- public void openFileInput_shouldNotAcceptPathsWithSeparatorCharacters() throws Exception {
- FileInputStream fileInputStream = null;
- try {
- fileInputStream = context.openFileInput("data" + File.separator + "test");
- } finally {
- if (fileInputStream != null)
- fileInputStream.close();
- }
- }
-
- @Test
- public void openFileOutput_shouldReturnAFileOutputStream() throws Exception {
- File file = new File("__test__");
- String fileContents = "blah";
- FileOutputStream fileOutputStream = null;
- try {
- fileOutputStream = context.openFileOutput("__test__", -1);
- fileOutputStream.write(fileContents.getBytes());
- } finally {
- if (fileOutputStream != null)
- fileOutputStream.close();
- }
- FileInputStream fileInputStream = null;
- try {
- fileInputStream = new FileInputStream(new File(context.getFilesDir(), file.getName()));
- byte[] readBuffer = new byte[fileContents.length()];
- fileInputStream.read(readBuffer);
- assertThat(new String(readBuffer), equalTo(fileContents));
- } finally {
- if (fileInputStream != null)
- fileInputStream.close();
- }
- }
-
- @Test(expected = IllegalArgumentException.class)
- public void openFileOutput_shouldNotAcceptPathsWithSeparatorCharacters() throws Exception {
- FileOutputStream fos = null;
- try {
- fos = context.openFileOutput(File.separator + "data" + File.separator + "test" + File.separator + "hi", 0);
- } finally {
- if (fos != null)
- fos.close();
- }
- }
-
- @Test
- public void deleteFile_shouldReturnTrue() throws IOException {
- File filesDir = context.getFilesDir();
- File file = new File(filesDir, "test.txt");
- boolean successfully = file.createNewFile();
- assertThat(successfully, is(true));
- successfully = context.deleteFile(file.getName());
- assertThat(successfully, is(true));
- }
-
- @Test
- public void deleteFile_shouldReturnFalse() throws IOException {
- File filesDir = context.getFilesDir();
- File file = new File(filesDir, "test.txt");
- boolean successfully = context.deleteFile(file.getName());
- assertThat(successfully, is(false));
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ContextWrapperTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/ContextWrapperTest.java
deleted file mode 100644
index eaf075582..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ContextWrapperTest.java
+++ /dev/null
@@ -1,199 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.app.Activity;
-import android.appwidget.AppWidgetProvider;
-import android.content.BroadcastReceiver;
-import android.content.Context;
-import android.content.ContextWrapper;
-import android.content.Intent;
-import android.content.IntentFilter;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import com.xtremelabs.robolectric.util.Transcript;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import java.util.List;
-
-import static android.content.pm.PackageManager.PERMISSION_DENIED;
-import static android.content.pm.PackageManager.PERMISSION_GRANTED;
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-import static junit.framework.Assert.assertEquals;
-import static org.hamcrest.CoreMatchers.notNullValue;
-import static org.hamcrest.CoreMatchers.nullValue;
-import static org.hamcrest.CoreMatchers.sameInstance;
-import static org.hamcrest.core.IsEqual.equalTo;
-import static org.junit.Assert.assertThat;
-import static org.junit.Assert.assertTrue;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class ContextWrapperTest {
- public Transcript transcript;
- private ContextWrapper contextWrapper;
-
- @Before public void setUp() throws Exception {
- transcript = new Transcript();
- contextWrapper = new ContextWrapper(new Activity());
- }
-
- @Test
- public void registerReceiver_shouldRegisterForAllIntentFilterActions() throws Exception {
- BroadcastReceiver receiver = broadcastReceiver("Larry");
- contextWrapper.registerReceiver(receiver, intentFilter("foo", "baz"));
-
- contextWrapper.sendBroadcast(new Intent("foo"));
- transcript.assertEventsSoFar("Larry notified of foo");
-
- contextWrapper.sendBroadcast(new Intent("womp"));
- transcript.assertNoEventsSoFar();
-
- contextWrapper.sendBroadcast(new Intent("baz"));
- transcript.assertEventsSoFar("Larry notified of baz");
- }
-
- @Test
- public void sendBroadcast_shouldSendIntentToEveryInterestedReceiver() throws Exception {
- BroadcastReceiver larryReceiver = broadcastReceiver("Larry");
- contextWrapper.registerReceiver(larryReceiver, intentFilter("foo", "baz"));
-
- BroadcastReceiver bobReceiver = broadcastReceiver("Bob");
- contextWrapper.registerReceiver(bobReceiver, intentFilter("foo"));
-
- contextWrapper.sendBroadcast(new Intent("foo"));
- transcript.assertEventsSoFar("Larry notified of foo", "Bob notified of foo");
-
- contextWrapper.sendBroadcast(new Intent("womp"));
- transcript.assertNoEventsSoFar();
-
- contextWrapper.sendBroadcast(new Intent("baz"));
- transcript.assertEventsSoFar("Larry notified of baz");
- }
-
- @Test
- public void unregisterReceiver_shouldUnregisterReceiver() throws Exception {
- BroadcastReceiver receiver = broadcastReceiver("Larry");
-
- contextWrapper.registerReceiver(receiver, intentFilter("foo", "baz"));
- contextWrapper.unregisterReceiver(receiver);
-
- contextWrapper.sendBroadcast(new Intent("foo"));
- transcript.assertNoEventsSoFar();
- }
-
- @Test(expected = IllegalArgumentException.class)
- public void unregisterReceiver_shouldThrowExceptionWhenReceiverIsNotRegistered() throws Exception {
- contextWrapper.unregisterReceiver(new AppWidgetProvider());
- }
-
- @Test
- public void broadcastReceivers_shouldBeSharedAcrossContextsPerApplicationContext() throws Exception {
- BroadcastReceiver receiver = broadcastReceiver("Larry");
-
- new ContextWrapper(Robolectric.application).registerReceiver(receiver, intentFilter("foo", "baz"));
- new ContextWrapper(Robolectric.application).sendBroadcast(new Intent("foo"));
- Robolectric.application.sendBroadcast(new Intent("baz"));
- transcript.assertEventsSoFar("Larry notified of foo", "Larry notified of baz");
-
- new ContextWrapper(Robolectric.application).unregisterReceiver(receiver);
- }
-
- @Test
- public void broadcasts_shouldBeLogged() {
- Intent broadcastIntent = new Intent("foo");
- contextWrapper.sendBroadcast(broadcastIntent);
-
- List<Intent> broadcastIntents = shadowOf(contextWrapper).getBroadcastIntents();
- assertTrue(broadcastIntents.size() == 1);
- assertEquals(broadcastIntent, broadcastIntents.get(0));
- }
-
-
- @Test
- public void shouldReturnSameApplicationEveryTime() throws Exception {
- Activity activity = new Activity();
- assertThat(activity.getApplication(), sameInstance(activity.getApplication()));
-
- assertThat(activity.getApplication(), sameInstance(new Activity().getApplication()));
- }
-
- @Test
- public void shouldReturnSameApplicationContextEveryTime() throws Exception {
- Activity activity = new Activity();
- assertThat(activity.getApplicationContext(), sameInstance(activity.getApplicationContext()));
-
- assertThat(activity.getApplicationContext(), sameInstance(new Activity().getApplicationContext()));
- }
-
- @Test
- public void shouldReturnSameContentResolverEveryTime() throws Exception {
- Activity activity = new Activity();
- assertThat(activity.getContentResolver(), sameInstance(activity.getContentResolver()));
-
- assertThat(activity.getContentResolver(), sameInstance(new Activity().getContentResolver()));
- }
-
- @Test
- public void shouldReturnSameLocationManagerEveryTime() throws Exception {
- assertSameInstanceEveryTime(Context.LOCATION_SERVICE);
- }
-
- @Test
- public void shouldReturnSameWifiManagerEveryTime() throws Exception {
- assertSameInstanceEveryTime(Context.WIFI_SERVICE);
- }
-
- @Test
- public void shouldReturnSameAlarmServiceEveryTime() throws Exception {
- assertSameInstanceEveryTime(Context.ALARM_SERVICE);
- }
-
- @Test
- public void checkPermissionsShouldReturnPermissionGrantedToAddedPermissions() throws Exception {
- shadowOf(contextWrapper).grantPermissions("foo", "bar");
- assertThat(contextWrapper.checkPermission("foo", 0, 0), equalTo(PERMISSION_GRANTED));
- assertThat(contextWrapper.checkPermission("bar", 0, 0), equalTo(PERMISSION_GRANTED));
- assertThat(contextWrapper.checkPermission("baz", 0, 0), equalTo(PERMISSION_DENIED));
- }
-
- @Test
- public void shouldReturnAContext() {
- assertThat(contextWrapper.getBaseContext(), notNullValue());
- ShadowContextWrapper shContextWrapper = Robolectric.shadowOf(contextWrapper);
- shContextWrapper.attachBaseContext(null);
- assertThat(contextWrapper.getBaseContext(), nullValue());
-
- Activity baseContext = new Activity();
- shContextWrapper.attachBaseContext(baseContext);
- assertThat(contextWrapper.getBaseContext(), sameInstance((Context) baseContext));
- }
-
- private void assertSameInstanceEveryTime(String serviceName) {
- Activity activity = new Activity();
- assertThat(activity.getSystemService(serviceName), sameInstance(activity.getSystemService(serviceName)));
-
- assertThat(activity.getSystemService(serviceName), sameInstance(new Activity().getSystemService(serviceName)));
- }
-
- @Test
- public void bindServiceDelegatesToShadowApplication() {
- contextWrapper.bindService(new Intent("foo"), new TestService(), Context.BIND_AUTO_CREATE);
- assertEquals("foo", shadowOf(Robolectric.application).getNextStartedService().getAction());
- }
-
- private BroadcastReceiver broadcastReceiver(final String name) {
- return new BroadcastReceiver() {
- @Override public void onReceive(Context context, Intent intent) {
- transcript.add(name + " notified of " + intent.getAction());
- }
- };
- }
-
- private IntentFilter intentFilter(String... actions) {
- IntentFilter larryIntentFilter = new IntentFilter();
- for (String action : actions) {
- larryIntentFilter.addAction(action);
- }
- return larryIntentFilter;
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/CookieManagerTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/CookieManagerTest.java
deleted file mode 100644
index fc3bba897..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/CookieManagerTest.java
+++ /dev/null
@@ -1,55 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.webkit.CookieManager;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static org.hamcrest.CoreMatchers.is;
-import static org.junit.Assert.*;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class CookieManagerTest {
-
- @Test
- public void shouldGetASingletonInstance() {
- assertNotNull(CookieManager.getInstance());
- assertThat( CookieManager.getInstance(), is(CookieManager.getInstance()));
- }
-
- @Test
- public void shouldSetAndGetACookie() {
- CookieManager cookieManager = CookieManager.getInstance();
- String url = "http://www.google.com";
- String value = "my cookie";
- cookieManager.setCookie(url, value);
- assertThat(cookieManager.getCookie(url), is(value));
- }
-
- @Test
- public void shouldGetCookieForUrl() {
- CookieManager cookieManager = CookieManager.getInstance();
- String url1 = "http://www.google.com";
- String value1 = "my cookie";
- cookieManager.setCookie(url1, value1);
-
- String url2 = "http://www.hotbot.com";
- String value2 = "some special value: thing";
- cookieManager.setCookie(url2, value2);
-
- assertThat(cookieManager.getCookie("http://www.google.com"), is(value1));
- assertThat(cookieManager.getCookie(url2), is(value2));
- }
-
- @Test
- public void shouldRecordAcceptCookie() {
- CookieManager cookieManager = CookieManager.getInstance();
- cookieManager.setCookie("foo", "bar");
- cookieManager.setCookie("baz", "qux");
- assertNotNull(cookieManager.getCookie("foo"));
- cookieManager.removeAllCookie();
- assertNull(cookieManager.getCookie("foo"));
- assertNull(cookieManager.getCookie("baz"));
- }
-}
-
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/CookieSyncManagerTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/CookieSyncManagerTest.java
deleted file mode 100644
index 7c1247a6e..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/CookieSyncManagerTest.java
+++ /dev/null
@@ -1,43 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import static org.hamcrest.CoreMatchers.notNullValue;
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.junit.Assert.assertThat;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import android.app.Activity;
-import android.webkit.CookieSyncManager;
-
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class CookieSyncManagerTest {
-
- @Test
- public void testCreateInstance() {
- assertThat( CookieSyncManager.createInstance( new Activity() ) , notNullValue() );
- }
-
- @Test
- public void testGetInstance() {
- CookieSyncManager.createInstance( new Activity() );
- assertThat( CookieSyncManager.getInstance(), notNullValue() );
- }
-
- @Test
- public void testSyncAndReset() {
- CookieSyncManager.createInstance( new Activity() );
- CookieSyncManager mgr = CookieSyncManager.getInstance();
-
- ShadowCookieSyncManager shadowMgr = Robolectric.shadowOf( mgr );
- assertThat( shadowMgr.synced(), equalTo( false ) );
- mgr.sync();
- assertThat( shadowMgr.synced(), equalTo( true ) );
- shadowMgr.reset();
- assertThat( shadowMgr.synced(), equalTo( false ) );
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/CountDownTimerTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/CountDownTimerTest.java
deleted file mode 100644
index 8e2551bbf..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/CountDownTimerTest.java
+++ /dev/null
@@ -1,82 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import android.os.CountDownTimer;
-
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.CoreMatchers.not;
-import static org.hamcrest.CoreMatchers.notNullValue;
-
-import static org.junit.Assert.assertThat;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class CountDownTimerTest {
-
- private ShadowCountDownTimer shadowCountDownTimer;
- private CountDownTimer countDownTimer;
- private long millisInFuture = 2000;
- private long countDownInterval = 1000;
- private String msg = null;
-
- @Before
- public void setUp() throws Exception {
-
- countDownTimer = new CountDownTimer(millisInFuture, countDownInterval) {
-
- @Override
- public void onFinish() {
- msg = "onFinish() is called";
- }
-
- @Override
- public void onTick(long millisUnitilFinished) {
- msg = "onTick() is called";
- }
- };
- shadowCountDownTimer = Robolectric.shadowOf(countDownTimer);
- }
-
-
- @Test
- public void testInvokeOnTick() {
- assertThat(msg, not(equalTo("onTick() is called")));
- shadowCountDownTimer.invokeTick(countDownInterval);
- assertThat(msg, equalTo("onTick() is called"));
- }
-
- @Test
- public void testInvokeOnFinish() {
- assertThat(msg, not(equalTo("onFinish() is called")));
- shadowCountDownTimer.invokeFinish();
- assertThat(msg, equalTo("onFinish() is called"));
- }
-
- @Test
- public void testStart() {
- assertThat(shadowCountDownTimer.hasStarted(), equalTo(false));
- CountDownTimer timer = shadowCountDownTimer.start();
- assertThat(timer, notNullValue());
- assertThat(shadowCountDownTimer.hasStarted(), equalTo(true));
- }
-
- @Test
- public void testCancel() {
- CountDownTimer timer = shadowCountDownTimer.start();
- assertThat(timer, notNullValue());
- assertThat(shadowCountDownTimer.hasStarted(), equalTo(true));
- shadowCountDownTimer.cancel();
- assertThat(shadowCountDownTimer.hasStarted(), equalTo(false));
- }
-
- @Test
- public void testAccessors() {
- assertThat(shadowCountDownTimer.getCountDownInterval(), equalTo(countDownInterval));
- assertThat(shadowCountDownTimer.getMillisInFuture(), equalTo(millisInFuture));
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/CountingAdapter.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/CountingAdapter.java
deleted file mode 100644
index fe491da08..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/CountingAdapter.java
+++ /dev/null
@@ -1,41 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.view.View;
-import android.view.ViewGroup;
-import android.widget.BaseAdapter;
-import android.widget.TextView;
-
-class CountingAdapter extends BaseAdapter {
- private int itemCount;
-
- public CountingAdapter(int itemCount) {
- this.itemCount = itemCount;
- }
-
- public void setCount(int itemCount) {
- this.itemCount = itemCount;
- notifyDataSetChanged();
- }
-
- @Override
- public int getCount() {
- return itemCount;
- }
-
- @Override
- public Object getItem(int position) {
- return null;
- }
-
- @Override
- public long getItemId(int position) {
- return 0;
- }
-
- @Override
- public View getView(int position, View convertView, ViewGroup parent) {
- TextView textView = new TextView(null);
- textView.setText("Item " + position);
- return textView;
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/CriteriaTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/CriteriaTest.java
deleted file mode 100644
index 99f3dacce..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/CriteriaTest.java
+++ /dev/null
@@ -1,50 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import static org.hamcrest.MatcherAssert.assertThat;
-import junit.framework.Assert;
-
-import org.hamcrest.core.IsEqual;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import android.location.Criteria;
-
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class CriteriaTest {
- private Criteria criteria;
-
- @Before
- public void setUp() {
- criteria = new Criteria();
- }
-
- @Test
- public void shouldReturnAccuracy() {
- criteria.setAccuracy(Criteria.ACCURACY_COARSE);
- assertThat(Criteria.ACCURACY_COARSE, IsEqual.equalTo(criteria.getAccuracy()));
- }
-
- @Test
- public void shouldReturnPowerRequirement() {
- criteria.setPowerRequirement(Criteria.POWER_HIGH);
- assertThat(Criteria.POWER_HIGH, IsEqual.equalTo(criteria.getPowerRequirement()));
- }
-
- @Test
- public void shouldBeEqual() {
- criteria.setPowerRequirement(Criteria.POWER_HIGH);
- criteria.setAccuracy(Criteria.ACCURACY_COARSE);
-
- Criteria criteria1 = new Criteria(criteria);
- Assert.assertTrue(criteria1.equals(criteria));
-
- Criteria criteria2 = new Criteria();
- criteria2.setPowerRequirement(Criteria.POWER_HIGH);
- criteria2.setAccuracy(Criteria.ACCURACY_COARSE);
- Assert.assertTrue(criteria2.equals(criteria));
- }
-
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/CursorAdapterTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/CursorAdapterTest.java
deleted file mode 100644
index 4f31e6794..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/CursorAdapterTest.java
+++ /dev/null
@@ -1,116 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.CoreMatchers.notNullValue;
-import static org.hamcrest.CoreMatchers.nullValue;
-import static org.hamcrest.CoreMatchers.sameInstance;
-import static org.junit.Assert.assertThat;
-
-import java.sql.Connection;
-import java.sql.ResultSet;
-import java.sql.Statement;
-import java.util.ArrayList;
-import java.util.List;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import android.content.Context;
-import android.database.Cursor;
-import android.database.sqlite.SQLiteCursor;
-import android.view.View;
-import android.view.ViewGroup;
-import android.widget.CursorAdapter;
-
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import com.xtremelabs.robolectric.util.DatabaseConfig;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class CursorAdapterTest {
-
- private Cursor curs;
- private CursorAdapter adapter;
-
- @Before
- public void setUp() throws Exception {
- Connection connection = DatabaseConfig.getMemoryConnection();
-
- Statement statement = connection.createStatement();
- statement.execute("CREATE TABLE table_name(_id INT PRIMARY KEY, name VARCHAR(255));" );
- String[] inserts = {
- "INSERT INTO table_name (_id, name) VALUES(1234, 'Chuck');",
- "INSERT INTO table_name (_id, name) VALUES(1235, 'Julie');",
- "INSERT INTO table_name (_id, name) VALUES(1236, 'Chris');",
- "INSERT INTO table_name (_id, name) VALUES(1237, 'Brenda');",
- "INSERT INTO table_name (_id, name) VALUES(1238, 'Jane');"
- };
-
- for (String insert : inserts) {
- connection.createStatement().executeUpdate(insert);
- }
-
- statement = connection.createStatement(DatabaseConfig.getResultSetType(), ResultSet.CONCUR_READ_ONLY);
- String sql = "SELECT * FROM table_name;";
- ResultSet resultSet = statement.executeQuery(sql);
- curs = new SQLiteCursor(null, null, null, null);
- Robolectric.shadowOf((SQLiteCursor)curs).setResultSet(resultSet,sql);
-
- adapter = new TestAdapter(curs);
- }
-
- @Test
- public void testChangeCursor() {
- assertThat(adapter.getCursor(), notNullValue());
- assertThat(adapter.getCursor(), sameInstance(curs));
-
- adapter.changeCursor( null );
-
- assertThat(curs.isClosed(), equalTo( true ) );
- assertThat(adapter.getCursor(), nullValue() );
- }
-
- @Test
- public void testCount() {
- assertThat(adapter.getCount(), equalTo(curs.getCount()));
- adapter.changeCursor( null );
- assertThat(adapter.getCount(), equalTo(0) );
- }
-
- @Test
- public void testGetItemId() {
- for ( int i = 0; i < 5; i++ ) {
- assertThat(adapter.getItemId(i), equalTo((long) 1234 + i));
- }
- }
-
- @Test
- public void testGetView() {
- List<View> views = new ArrayList<View>();
- for (int i = 0; i < 5; i++) {
- views.add(new View(Robolectric.application));
- }
-
- Robolectric.shadowOf(adapter).setViews( views );
-
- for (int i = 0; i < 5; i++) {
- assertThat(adapter.getView(i, null, null), sameInstance(views.get(i)));
- }
- }
-
- private class TestAdapter extends CursorAdapter {
-
- public TestAdapter( Cursor curs ) {
- super( Robolectric.application, curs, false );
- }
-
- @Override
- public void bindView(View view, Context context, Cursor cursor) { }
-
- @Override
- public View newView(Context context, Cursor cursor, ViewGroup parent) {
- return null;
- }
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/CursorLoaderTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/CursorLoaderTest.java
deleted file mode 100644
index 31bf7348a..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/CursorLoaderTest.java
+++ /dev/null
@@ -1,56 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.app.Activity;
-import android.net.Uri;
-import android.support.v4.content.CursorLoader;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.junit.Assert.assertThat;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class CursorLoaderTest {
- @Test
- public void testGetters() {
- Uri uri = Uri.parse("http://robolectric.org");
- String[] projection = new String[] { "_id", "TestColumn" };
- String selection = "_id = ?";
- String[] selectionArgs = new String[] { "5" };
- String sortOrder = "_id";
- CursorLoader cursorLoader = new CursorLoader(new Activity(),
- uri,
- projection,
- selection,
- selectionArgs,
- sortOrder);
-
- assertThat(cursorLoader.getUri(), equalTo(uri));
- assertThat(cursorLoader.getProjection(), equalTo(projection));
- assertThat(cursorLoader.getSelection(), equalTo(selection));
- assertThat(cursorLoader.getSelectionArgs(), equalTo(selectionArgs));
- assertThat(cursorLoader.getSortOrder(), equalTo(sortOrder));
- }
-
- @Test
- public void testSetters() {
- Uri uri = Uri.parse("http://robolectric.org");
- String[] projection = new String[] { "_id", "TestColumn" };
- String selection = "_id = ?";
- String[] selectionArgs = new String[] { "5" };
- String sortOrder = "_id";
- CursorLoader cursorLoader = new CursorLoader(new Activity());
- cursorLoader.setUri(uri);
- cursorLoader.setProjection(projection);
- cursorLoader.setSelection(selection);
- cursorLoader.setSelectionArgs(selectionArgs);
- cursorLoader.setSortOrder(sortOrder);
-
- assertThat(cursorLoader.getUri(), equalTo(uri));
- assertThat(cursorLoader.getProjection(), equalTo(projection));
- assertThat(cursorLoader.getSelection(), equalTo(selection));
- assertThat(cursorLoader.getSelectionArgs(), equalTo(selectionArgs));
- assertThat(cursorLoader.getSortOrder(), equalTo(sortOrder));
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/CursorWrapperTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/CursorWrapperTest.java
deleted file mode 100644
index 6d47c14ce..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/CursorWrapperTest.java
+++ /dev/null
@@ -1,105 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.content.ContentResolver;
-import android.database.*;
-import android.net.Uri;
-import android.os.Bundle;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.Mockito;
-
-import java.lang.reflect.Method;
-import java.util.HashMap;
-
-import static org.hamcrest.CoreMatchers.*;
-import static org.junit.Assert.assertThat;
-import static org.mockito.Mockito.*;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class CursorWrapperTest {
-
- private class ForwardVerifier {
-
- final Cursor mockCursor;
- final CursorWrapper cursorWrapper;
- final HashMap<String, Method> cursorMethod;
-
- public ForwardVerifier() {
- mockCursor = mock(Cursor.class);
- cursorWrapper = new CursorWrapper(mockCursor);
- cursorMethod = new HashMap<String, Method>();
-
- // This works because no two methods in the Cursor interface have the same name
- for (Method m : Cursor.class.getMethods()) {
- cursorMethod.put(m.getName(), m);
- }
- }
-
- public void verifyForward(String methodName, Object... params) throws Exception {
- assertThat(cursorMethod.keySet(), hasItem(methodName));
-
- Method method = cursorMethod.get(methodName);
- method.invoke(cursorWrapper, params);
- method.invoke(verify(mockCursor, times(1)), params);
- Mockito.verifyNoMoreInteractions(mockCursor);
- }
-
- }
-
- @Test
- public void testCursorMethodsAreForwarded() throws Exception {
- ForwardVerifier v = new ForwardVerifier();
-
- v.verifyForward("close");
- v.verifyForward("copyStringToBuffer", 1, mock(CharArrayBuffer.class));
- v.verifyForward("deactivate");
- v.verifyForward("getBlob", 2);
- v.verifyForward("getColumnCount");
- v.verifyForward("getColumnIndex", "foo");
- v.verifyForward("getColumnIndexOrThrow", "foo");
- v.verifyForward("getColumnName", 3);
- v.verifyForward("getColumnNames");
- v.verifyForward("getCount");
- v.verifyForward("getDouble", 12);
- v.verifyForward("getExtras");
- v.verifyForward("getFloat", 4);
- v.verifyForward("getInt", 5);
- v.verifyForward("getLong", 6);
- v.verifyForward("getPosition");
- v.verifyForward("getShort", 7);
- v.verifyForward("getString", 8);
- v.verifyForward("getWantsAllOnMoveCalls");
- v.verifyForward("isAfterLast");
- v.verifyForward("isBeforeFirst");
- v.verifyForward("isClosed");
- v.verifyForward("isFirst");
- v.verifyForward("isLast");
- v.verifyForward("isNull", 10);
- v.verifyForward("move", 11);
- v.verifyForward("moveToFirst");
- v.verifyForward("moveToLast");
- v.verifyForward("moveToNext");
- v.verifyForward("moveToPosition", 13);
- v.verifyForward("moveToPrevious");
- v.verifyForward("registerContentObserver", mock(ContentObserver.class));
- v.verifyForward("registerDataSetObserver", mock(DataSetObserver.class));
- v.verifyForward("requery");
- v.verifyForward("respond", mock(Bundle.class));
- v.verifyForward("setNotificationUri", mock(ContentResolver.class), mock(Uri.class));
- v.verifyForward("unregisterContentObserver", mock(ContentObserver.class));
- v.verifyForward("unregisterDataSetObserver", mock(DataSetObserver.class));
-
- }
-
- @Test
- public void getWrappedCursor() {
- Cursor mockCursor = mock(Cursor.class);
- CursorWrapper cursorWrapper = new CursorWrapper(mockCursor);
- ShadowCursorWrapper shadow = Robolectric.shadowOf(cursorWrapper);
-
- assertThat(shadow.getWrappedCursor(), is(sameInstance(mockCursor)));
- }
-
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/DatabaseTestBase.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/DatabaseTestBase.java
deleted file mode 100644
index a951774f1..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/DatabaseTestBase.java
+++ /dev/null
@@ -1,606 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.content.ContentValues;
-import android.database.Cursor;
-import android.database.sqlite.SQLiteDatabase;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.sql.Statement;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.CoreMatchers.not;
-import static org.junit.Assert.*;
-
-
-public abstract class DatabaseTestBase {
- protected SQLiteDatabase database;
- protected ShadowSQLiteDatabase shDatabase;
-
- @Before
- public void setUp() throws Exception {
- database = SQLiteDatabase.openDatabase("path", null, 0);
- shDatabase = Robolectric.shadowOf(database);
- database.execSQL("CREATE TABLE table_name (\n" +
- " id INTEGER PRIMARY KEY AUTOINCREMENT,\n" +
- " first_column VARCHAR(255),\n" +
- " second_column BINARY,\n" +
- " name VARCHAR(255),\n" +
- " big_int INTEGER\n" +
- ");");
-
- database.execSQL("CREATE TABLE rawtable (\n" +
- " id INTEGER PRIMARY KEY AUTOINCREMENT,\n" +
- " first_column VARCHAR(255),\n" +
- " second_column BINARY,\n" +
- " name VARCHAR(255),\n" +
- " big_int INTEGER\n" +
- ");");
-
- database.execSQL("CREATE TABLE exectable (\n" +
- " id INTEGER PRIMARY KEY AUTOINCREMENT,\n" +
- " first_column VARCHAR(255),\n" +
- " second_column BINARY,\n" +
- " name VARCHAR(255),\n" +
- " big_int INTEGER\n" +
- ");");
-
- String stringColumnValue = "column_value";
- byte[] byteColumnValue = new byte[]{1, 2, 3};
-
- ContentValues values = new ContentValues();
-
- values.put("first_column", stringColumnValue);
- values.put("second_column", byteColumnValue);
-
- database.insert("rawtable", null, values);
- ////////////////////////////////////////////////
- String stringColumnValue2 = "column_value2";
- byte[] byteColumnValue2 = new byte[]{4, 5, 6};
- ContentValues values2 = new ContentValues();
-
- values2.put("first_column", stringColumnValue2);
- values2.put("second_column", byteColumnValue2);
-
- database.insert("rawtable", null, values2);
- }
-
-
- @After
- public void tearDown() throws Exception {
- database.close();
- }
-
- @Test()
- public void testInsertAndQuery() throws Exception {
- String stringColumnValue = "column_value";
- byte[] byteColumnValue = new byte[]{1, 2, 3};
-
- ContentValues values = new ContentValues();
-
- values.put("first_column", stringColumnValue);
- values.put("second_column", byteColumnValue);
-
- database.insert("table_name", null, values);
-
- Cursor cursor = database.query("table_name", new String[]{"second_column", "first_column"}, null, null, null, null, null);
-
- assertThat(cursor.moveToFirst(), equalTo(true));
-
- byte[] byteValueFromDatabase = cursor.getBlob(0);
- String stringValueFromDatabase = cursor.getString(1);
-
- assertThat(stringValueFromDatabase, equalTo(stringColumnValue));
- assertThat(byteValueFromDatabase, equalTo(byteColumnValue));
- }
-
- @Test
- public void testInsertAndRawQuery() throws Exception {
- String stringColumnValue = "column_value";
- byte[] byteColumnValue = new byte[]{1, 2, 3};
-
- ContentValues values = new ContentValues();
-
- values.put("first_column", stringColumnValue);
- values.put("second_column", byteColumnValue);
-
- database.insert("table_name", null, values);
-
- Cursor cursor = database.rawQuery("select second_column, first_column from table_name", null);
-
- assertThat(cursor.moveToFirst(), equalTo(true));
-
- byte[] byteValueFromDatabase = cursor.getBlob(0);
- String stringValueFromDatabase = cursor.getString(1);
-
- assertThat(stringValueFromDatabase, equalTo(stringColumnValue));
- assertThat(byteValueFromDatabase, equalTo(byteColumnValue));
- }
-
- @Test(expected = android.database.SQLException.class)
- public void testInsertOrThrowWithSQLException() {
- shDatabase.setThrowOnInsert(true);
- database.insertOrThrow("table_name", null, new ContentValues());
- }
-
- @Test
- public void testInsertOrThrow() {
- String stringColumnValue = "column_value";
- byte[] byteColumnValue = new byte[]{1, 2, 3};
- ContentValues values = new ContentValues();
- values.put("first_column", stringColumnValue);
- values.put("second_column", byteColumnValue);
- database.insertOrThrow("table_name", null, values);
-
- Cursor cursor = database.rawQuery("select second_column, first_column from table_name", null);
- assertThat(cursor.moveToFirst(), equalTo(true));
- byte[] byteValueFromDatabase = cursor.getBlob(0);
- String stringValueFromDatabase = cursor.getString(1);
- assertThat(stringValueFromDatabase, equalTo(stringColumnValue));
- assertThat(byteValueFromDatabase, equalTo(byteColumnValue));
- }
-
- @Test(expected = IllegalArgumentException.class)
- public void testRawQueryThrowsIndex0NullException() throws Exception {
- database.rawQuery("select second_column, first_column from rawtable WHERE `id` = ?", new String[]{null});
- }
-
- @Test(expected = IllegalArgumentException.class)
- public void testRawQueryThrowsIndex0NullException2() throws Exception {
- database.rawQuery("select second_column, first_column from rawtable", new String[]{null});
- }
-
- @Test
- public void testRawQueryCount() throws Exception {
- Cursor cursor = database.rawQuery("select second_column, first_column from rawtable WHERE `id` = ?", new String[]{"1"});
- assertThat(cursor.getCount(), equalTo(1));
- }
-
- @Test
- public void testRawQueryCount2() throws Exception {
- Cursor cursor = database.rawQuery("select second_column, first_column from rawtable", null);
- assertThat(cursor.getCount(), equalTo(2));
- }
-
- @Test
- public void testRawQueryCount3() throws Exception {
- Cursor cursor = database.rawQuery("select second_column, first_column from rawtable", new String[]{});
- assertThat(cursor.getCount(), equalTo(2));
- }
- /*
- * Reason why testRawQueryCount4() and testRawQueryCount5() expects exceptions even though exceptions are not found in Android.
- *
- * The code in Android acts inconsistently under API version 2.1_r1 (and perhaps other APIs)..
- * What happens is that rawQuery() remembers the selectionArgs of previous queries,
- * and uses them if no selectionArgs are given in subsequent queries.
- * If they were never given selectionArgs THEN they return empty cursors.
- *
- *
- * if you run {
- * db.rawQuery("select * from exercise WHERE name = ?",null); //this returns an empty cursor
- * db.rawQuery("select * from exercise WHERE name = ?",new String[]{}); //this returns an empty cursor
- * }
- *
- * but if you run {
- * db.rawQuery("select * from exercise WHERE name = ?",new String[]{"Leg Press"}); //this returns 1 exercise named "Leg Press"
- * db.rawQuery("select * from exercise WHERE name = ?",null); //this too returns 1 exercise named "Leg Press"
- * db.rawQuery("select * from exercise WHERE name = ?",new String[]{}); //this too returns 1 exercise named "Leg Press"
- * }
- *
- * so SQLite + Android work inconsistently (it maintains state that it should not)
- * whereas H2 just throws an exception for not supplying the selectionArgs
- *
- * So the question is should Robolectric:
- * 1) throw an exception, the way H2 does.
- * 2) return an empty Cursor.
- * 3) mimic Android\SQLite precisely and return inconsistent results based on previous state
- *
- * Returning an empty cursor all the time would be bad
- * because Android doesn't always return an empty cursor.
- * But just mimicing Android would not be helpful,
- * since it would be less than obvious where the problem is coming from.
- * One should just avoid ever calling a statement without selectionArgs (when one has a ? placeholder),
- * so it is best to throw an Exception to let the programmer know that this isn't going to turn out well if they try to run it under Android.
- * Because we are running in the context of a test we do not have to mimic Android precisely (if it is more helpful not to!), we just need to help
- * the testing programmer figure out what is going on.
- */
-
- @Test(expected = Exception.class)
- public void testRawQueryCount4() throws Exception {
- //Android and SQLite don't normally throw an exception here. See above explanation as to why Robolectric should.
- Cursor cursor = database.rawQuery("select second_column, first_column from rawtable WHERE `id` = ?", null);
- }
-
- @Test(expected = Exception.class)
- public void testRawQueryCount5() throws Exception {
- //Android and SQLite don't normally throw an exception here. See above explanation as to why Robolectric should.
- Cursor cursor = database.rawQuery("select second_column, first_column from rawtable WHERE `id` = ?", new String[]{});
- }
-
- @Test(expected = android.database.sqlite.SQLiteException.class)
- public void testRawQueryCount8() throws Exception {
- Cursor cursor = database.rawQuery("select second_column, first_column from rawtable", new String[]{"1"});
- }
-
- @Test
- public void testInsertWithException() {
- ContentValues values = new ContentValues();
-
- assertEquals(-1, database.insert("table_that_doesnt_exist", null, values));
- }
-
-
- @Test
- public void testEmptyTable() throws Exception {
- Cursor cursor = database.query("table_name", new String[]{"second_column", "first_column"}, null, null, null, null, null);
-
- assertThat(cursor.moveToFirst(), equalTo(false));
- }
-
- @Test
- public void testInsertRowIdGeneration() throws Exception {
- ContentValues values = new ContentValues();
- values.put("name", "Chuck");
-
- long id = database.insert("table_name", null, values);
-
- assertThat(id, not(equalTo(0L)));
- }
-
- @Test
- public void testInsertKeyGeneration() throws Exception {
- ContentValues values = new ContentValues();
- values.put("name", "Chuck");
-
- long key = database.insertWithOnConflict("table_name", null, values, SQLiteDatabase.CONFLICT_IGNORE);
-
- assertThat(key, not(equalTo(0L)));
- }
-
- @Test
- public void testUpdate() throws Exception {
- addChuck();
-
- assertThat(updateName(1234L, "Buster"), equalTo(1));
-
- Cursor cursor = database.query("table_name", new String[]{"id", "name"}, null, null, null, null, null);
- assertThat(cursor.moveToFirst(), equalTo(true));
- assertThat(cursor.getCount(), equalTo(1));
-
- assertIdAndName(cursor, 1234L, "Buster");
- }
-
- @Test
- public void testUpdateNoMatch() throws Exception {
- addChuck();
-
- assertThat(updateName(5678L, "Buster"), equalTo(0));
-
- Cursor cursor = database.query("table_name", new String[]{"id", "name"}, null, null, null, null, null);
- assertThat(cursor.moveToFirst(), equalTo(true));
- assertThat(cursor.getCount(), equalTo(1));
-
- assertIdAndName(cursor, 1234L, "Chuck");
- }
-
- @Test
- public void testUpdateAll() throws Exception {
- addChuck();
- addJulie();
-
- assertThat(updateName("Belvedere"), equalTo(2));
-
- Cursor cursor = database.query("table_name", new String[]{"id", "name"}, null, null, null, null, null);
- assertThat(cursor.moveToFirst(), equalTo(true));
- assertThat(cursor.getCount(), equalTo(2));
-
- assertIdAndName(cursor, 1234L, "Belvedere");
- assertThat(cursor.moveToNext(), equalTo(true));
-
- assertIdAndName(cursor, 1235L, "Belvedere");
- assertThat(cursor.isLast(), equalTo(true));
- assertThat(cursor.moveToNext(), equalTo(false));
- assertThat(cursor.isAfterLast(), equalTo(true));
- assertThat(cursor.moveToNext(), equalTo(false));
- }
-
- @Test
- public void testDelete() throws Exception {
- addChuck();
-
- int deleted = database.delete("table_name", "id=1234", null);
- assertThat(deleted, equalTo(1));
-
- assertEmptyDatabase();
- }
-
- @Test
- public void testDeleteNoMatch() throws Exception {
- addChuck();
-
- int deleted = database.delete("table_name", "id=5678", null);
- assertThat(deleted, equalTo(0));
-
- assertNonEmptyDatabase();
- }
-
- @Test
- public void testDeleteAll() throws Exception {
- addChuck();
- addJulie();
-
- int deleted = database.delete("table_name", "1", null);
- assertThat(deleted, equalTo(2));
-
- assertEmptyDatabase();
- }
-
-
- @Test
- public void testExecSQL() throws Exception {
- Statement statement;
- ResultSet resultSet;
-
- database.execSQL("INSERT INTO table_name (id, name) VALUES(1234, 'Chuck');");
-
- statement = shadowOf(database).getConnection().createStatement();
- resultSet = statement.executeQuery("SELECT COUNT(*) FROM table_name");
- assertThat(resultSet.next(), equalTo(true));
- assertThat(resultSet.getInt(1), equalTo(1));
-
- statement = shadowOf(database).getConnection().createStatement();
- resultSet = statement.executeQuery("SELECT * FROM table_name");
- assertThat(resultSet.next(), equalTo(true));
- assertThat(resultSet.getInt(1), equalTo(1234));
- assertThat(resultSet.getString(4), equalTo("Chuck"));
- }
-
- @Test
- public void testExecSQLParams() throws Exception {
- Statement statement;
- ResultSet resultSet;
-
- database.execSQL("CREATE TABLE `routine` (`id` INTEGER PRIMARY KEY AUTOINCREMENT , `name` VARCHAR , `lastUsed` INTEGER DEFAULT 0 , UNIQUE (`name`)) ", new Object[]{});
- database.execSQL("INSERT INTO `routine` (`name` ,`lastUsed` ) VALUES (?,?)", new Object[]{"Leg Press", 0});
- database.execSQL("INSERT INTO `routine` (`name` ,`lastUsed` ) VALUES (?,?)", new Object[]{"Bench Press", 1});
-
- statement = shadowOf(database).getConnection().createStatement();
- resultSet = statement.executeQuery("SELECT COUNT(*) FROM `routine`");
- assertThat(resultSet.next(), equalTo(true));
- assertThat(resultSet.getInt(1), equalTo(2));
-
- statement = shadowOf(database).getConnection().createStatement();
- resultSet = statement.executeQuery("SELECT `id`, `name` ,`lastUsed` FROM `routine`");
- assertThat(resultSet.next(), equalTo(true));
- assertThat(resultSet.getInt(1), equalTo(1));
- assertThat(resultSet.getString(2), equalTo("Leg Press"));
- assertThat(resultSet.getInt(3), equalTo(0));
- assertThat(resultSet.next(), equalTo(true));
- assertThat(resultSet.getLong(1), equalTo(2L));
- assertThat(resultSet.getString(2), equalTo("Bench Press"));
- assertThat(resultSet.getInt(3), equalTo(1));
- }
-
- @Test(expected = android.database.SQLException.class)
- public void testExecSQLException() throws Exception {
- database.execSQL("INSERT INTO table_name;"); // invalid SQL
- }
-
- @Test(expected = IllegalArgumentException.class)
- public void testExecSQLException2() throws Exception {
- database.execSQL("insert into exectable (first_column) values (?);", null);
- }
-
- @Test(expected = IllegalArgumentException.class)
- public void testExecSQLException4() throws Exception {
- database.execSQL("insert into exectable (first_column) values ('sdfsfs');", null);
- }
-
- @Test(expected = Exception.class)
- public void testExecSQLException5() throws Exception {
- //TODO: make this throw android.database.SQLException.class
- database.execSQL("insert into exectable (first_column) values ('kjhk');", new String[]{"xxxx"});
- }
-
- @Test(expected = Exception.class)
- public void testExecSQLException6() throws Exception {
- //TODO: make this throw android.database.SQLException.class
- database.execSQL("insert into exectable (first_column) values ('kdfd');", new String[]{null});
- }
-
- @Test
- public void testExecSQL2() throws Exception {
- database.execSQL("insert into exectable (first_column) values ('eff');", new String[]{});
- }
-
- @Test
- public void testExecSQLInsertNull() throws Exception {
- String name = "nullone";
-
- database.execSQL("insert into exectable (first_column, name) values (?,?);", new String[]{null, name});
-
- Cursor cursor = database.rawQuery("select * from exectable WHERE `name` = ?", new String[]{name});
- cursor.moveToFirst();
- int firstIndex = cursor.getColumnIndex("first_column");
- int nameIndex = cursor.getColumnIndex("name");
- assertThat(cursor.getString(nameIndex), equalTo(name));
- assertThat(cursor.getString(firstIndex), equalTo(null));
-
- }
-
- @Test(expected = Exception.class)
- public void testExecSQLInsertNullShouldBeException() throws Exception {
- //this inserts null in android, but it when it happens it is likely an error. H2 throws an exception. So we'll make Robolectric expect an Exception so that the error can be found.
-
- database.delete("exectable", null, null);
-
- Cursor cursor = database.rawQuery("select * from exectable", null);
- cursor.moveToFirst();
- assertThat(cursor.getCount(), equalTo(0));
-
- database.execSQL("insert into exectable (first_column) values (?);", new String[]{});
- Cursor cursor2 = database.rawQuery("select * from exectable", new String[]{null});
- cursor.moveToFirst();
- assertThat(cursor2.getCount(), equalTo(1));
-
- }
-
- @Test
- public void testExecSQLAutoIncrementSQLite() throws Exception {
- database.execSQL("CREATE TABLE auto_table (id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR(255));");
-
- ContentValues values = new ContentValues();
- values.put("name", "Chuck");
-
- long key = database.insert("auto_table", null, values);
- assertThat(key, not(equalTo(0L)));
-
- long key2 = database.insert("auto_table", null, values);
- assertThat(key2, not(equalTo(key)));
- }
-
- @Test(expected = IllegalStateException.class)
- public void testClose() throws Exception {
- database.close();
-
- database.execSQL("INSERT INTO table_name (id, name) VALUES(1234, 'Chuck');");
- }
-
- @Test
- public void testIsOpen() throws Exception {
- assertThat(database.isOpen(), equalTo(true));
- database.close();
- assertThat(database.isOpen(), equalTo(false));
- }
-
- @Test
- public void shouldStoreGreatBigHonkinIntegersCorrectly() throws Exception {
- database.execSQL("INSERT INTO table_name(big_int) VALUES(1234567890123456789);");
- Cursor cursor = database.query("table_name", new String[]{"big_int"}, null, null, null, null, null);
- cursor.moveToFirst();
- assertEquals(1234567890123456789L, cursor.getLong(0));
- }
-
- @Test
- public void testSuccessTransaction() throws SQLException {
- assertThat(shDatabase.isTransactionSuccess(), equalTo(false));
- database.beginTransaction();
- assertThat(shDatabase.isTransactionSuccess(), equalTo(false));
- database.execSQL("INSERT INTO table_name (id, name) VALUES(1234, 'Chuck');");
- assertThat(shDatabase.isTransactionSuccess(), equalTo(false));
- database.setTransactionSuccessful();
- assertThat(shDatabase.isTransactionSuccess(), equalTo(true));
- database.endTransaction();
- assertThat(shDatabase.isTransactionSuccess(), equalTo(false));
-
- Statement statement = shadowOf(database).getConnection().createStatement();
- ResultSet resultSet = statement.executeQuery("SELECT COUNT(*) FROM table_name");
- assertThat(resultSet.next(), equalTo(true));
- assertThat(resultSet.getInt(1), equalTo(1));
- }
-
- @Test
- public void testFailureTransaction() throws Exception {
- assertThat(shDatabase.isTransactionSuccess(), equalTo(false));
- database.beginTransaction();
- assertThat(shDatabase.isTransactionSuccess(), equalTo(false));
-
- database.execSQL("INSERT INTO table_name (id, name) VALUES(1234, 'Chuck');");
-
- Statement statement = shadowOf(database).getConnection().createStatement();
- final String select = "SELECT COUNT(*) FROM table_name";
-
- ResultSet rs = statement.executeQuery(select);
- assertThat(rs.next(), equalTo(true));
- assertThat(rs.getInt(1), equalTo(1));
- rs.close();
-
- assertThat(shDatabase.isTransactionSuccess(), equalTo(false));
- database.endTransaction();
-
- statement = shadowOf(database).getConnection().createStatement();
- rs = statement.executeQuery(select);
- assertThat(rs.next(), equalTo(true));
- assertThat(rs.getInt(1), equalTo(0));
-
- assertThat(shDatabase.isTransactionSuccess(), equalTo(false));
- }
-
- @Test
- public void testTransactionAlreadySuccessful() {
- database.beginTransaction();
- database.setTransactionSuccessful();
- try {
- database.setTransactionSuccessful();
- fail("didn't receive the expected IllegalStateException");
- } catch (IllegalStateException e) {
- assertThat(e.getMessage(), equalTo("transaction already successfully"));
- }
- }
-
- @Test
- public void testInTransaction() throws Exception {
- assertThat( database.inTransaction(), equalTo(false) );
- database.beginTransaction();
- assertThat( database.inTransaction(), equalTo(true) );
- database.endTransaction();
- assertThat( database.inTransaction(), equalTo(false) );
- }
-
- protected long addChuck() {
- return addPerson(1234L, "Chuck");
- }
-
- protected long addJulie() {
- return addPerson(1235L, "Julie");
- }
-
- protected long addPerson(long id, String name) {
- ContentValues values = new ContentValues();
- values.put("id", id);
- values.put("name", name);
- return database.insert("table_name", null, values);
- }
-
- protected int updateName(long id, String name) {
- ContentValues values = new ContentValues();
- values.put("name", name);
- return database.update("table_name", values, "id=" + id, null);
- }
-
- protected int updateName(String name) {
- ContentValues values = new ContentValues();
- values.put("name", name);
- return database.update("table_name", values, null, null);
- }
-
- protected void assertIdAndName(Cursor cursor, long id, String name) {
- long idValueFromDatabase;
- String stringValueFromDatabase;
-
- idValueFromDatabase = cursor.getLong(0);
- stringValueFromDatabase = cursor.getString(1);
- assertThat(idValueFromDatabase, equalTo(id));
- assertThat(stringValueFromDatabase, equalTo(name));
- }
-
- protected void assertEmptyDatabase() {
- Cursor cursor = database.query("table_name", new String[]{"id", "name"}, null, null, null, null, null);
- assertThat(cursor.moveToFirst(), equalTo(false));
- assertThat(cursor.isClosed(), equalTo(false));
- assertThat(cursor.getCount(), equalTo(0));
- }
-
- protected void assertNonEmptyDatabase() {
- Cursor cursor = database.query("table_name", new String[]{"id", "name"}, null, null, null, null, null);
- assertThat(cursor.moveToFirst(), equalTo(true));
- assertThat(cursor.getCount(), not(equalTo(0)));
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/DatabaseUtilsTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/DatabaseUtilsTest.java
deleted file mode 100644
index c1bdebec1..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/DatabaseUtilsTest.java
+++ /dev/null
@@ -1,19 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.junit.Assert.assertThat;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class DatabaseUtilsTest {
-
- @Test
- public void testQuote() {
- assertThat( ShadowDatabaseUtils.sqlEscapeString( "foobar" ), equalTo( "'foobar'" ) );
- assertThat( ShadowDatabaseUtils.sqlEscapeString( "Rich's" ), equalTo( "'Rich''s'" ) );
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/DefaultRequestDirectorTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/DefaultRequestDirectorTest.java
deleted file mode 100644
index 2c4178c95..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/DefaultRequestDirectorTest.java
+++ /dev/null
@@ -1,365 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import com.xtremelabs.robolectric.tester.org.apache.http.FakeHttpLayer;
-import com.xtremelabs.robolectric.tester.org.apache.http.RequestMatcher;
-import com.xtremelabs.robolectric.tester.org.apache.http.TestHttpResponse;
-import com.xtremelabs.robolectric.util.Strings;
-import junit.framework.Assert;
-import org.apache.http.HttpRequest;
-import org.apache.http.HttpResponse;
-import org.apache.http.client.methods.HttpGet;
-import org.apache.http.client.methods.HttpPost;
-import org.apache.http.client.methods.HttpUriRequest;
-import org.apache.http.conn.ConnectTimeoutException;
-import org.apache.http.conn.ConnectionKeepAliveStrategy;
-import org.apache.http.impl.client.BasicResponseHandler;
-import org.apache.http.impl.client.DefaultHttpClient;
-import org.apache.http.impl.client.DefaultRequestDirector;
-import org.apache.http.message.BasicHeader;
-import org.apache.http.params.HttpConnectionParams;
-import org.apache.http.params.HttpParams;
-import org.apache.http.protocol.HttpContext;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.URI;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-import static org.hamcrest.core.IsEqual.equalTo;
-import static org.junit.Assert.*;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class DefaultRequestDirectorTest {
- private DefaultRequestDirector requestDirector;
- private ConnectionKeepAliveStrategy connectionKeepAliveStrategy;
-
- @Before
- public void setUp_EnsureStaticStateIsReset() {
- FakeHttpLayer fakeHttpLayer = Robolectric.getFakeHttpLayer();
- assertFalse(fakeHttpLayer.hasPendingResponses());
- assertFalse(fakeHttpLayer.hasRequestInfos());
- assertFalse(fakeHttpLayer.hasResponseRules());
- assertNull(fakeHttpLayer.getDefaultResponse());
-
- connectionKeepAliveStrategy = new ConnectionKeepAliveStrategy() {
- @Override public long getKeepAliveDuration(HttpResponse httpResponse, HttpContext httpContext) {
- return 0;
- }
- };
- requestDirector = new DefaultRequestDirector(null, null, null, connectionKeepAliveStrategy, null, null, null, null, null, null, null, null);
- }
-
- @After
- public void tearDown_EnsureStaticStateIsReset() throws Exception {
- Robolectric.addPendingHttpResponse(200, "a happy response body");
- }
-
- @Test
- public void shouldGetHttpResponseFromExecute() throws Exception {
- Robolectric.addPendingHttpResponse(new TestHttpResponse(200, "a happy response body"));
- HttpResponse response = requestDirector.execute(null, new HttpGet("http://example.com"), null);
-
- assertNotNull(response);
- assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
- assertThat(Strings.fromStream(response.getEntity().getContent()), equalTo("a happy response body"));
- }
-
- @Test
- public void shouldPreferPendingResponses() throws Exception {
- Robolectric.addPendingHttpResponse(new TestHttpResponse(200, "a happy response body"));
-
- Robolectric.addHttpResponseRule(HttpGet.METHOD_NAME, "http://some.uri",
- new TestHttpResponse(200, "a cheery response body"));
-
- HttpResponse response = requestDirector.execute(null, new HttpGet("http://some.uri"), null);
-
- assertNotNull(response);
- assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
- assertThat(Strings.fromStream(response.getEntity().getContent()), equalTo("a happy response body"));
- }
-
- @Test
- public void shouldReturnRequestsByRule() throws Exception {
- Robolectric.addHttpResponseRule(HttpGet.METHOD_NAME, "http://some.uri",
- new TestHttpResponse(200, "a cheery response body"));
-
- HttpResponse response = requestDirector.execute(null, new HttpGet("http://some.uri"), null);
-
- assertNotNull(response);
- assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
- assertThat(Strings.fromStream(response.getEntity().getContent()), equalTo("a cheery response body"));
- }
-
- @Test
- public void shouldReturnRequestsByRule_MatchingMethod() throws Exception {
- Robolectric.setDefaultHttpResponse(404, "no such page");
- Robolectric.addHttpResponseRule(HttpPost.METHOD_NAME, "http://some.uri",
- new TestHttpResponse(200, "a cheery response body"));
-
- HttpResponse response = requestDirector.execute(null, new HttpGet("http://some.uri"), null);
-
- assertNotNull(response);
- assertThat(response.getStatusLine().getStatusCode(), equalTo(404));
- }
-
- @Test
- public void shouldReturnRequestsByRule_AnyMethod() throws Exception {
- Robolectric.addHttpResponseRule("http://some.uri", new TestHttpResponse(200, "a cheery response body"));
-
- HttpResponse getResponse = requestDirector.execute(null, new HttpGet("http://some.uri"), null);
- assertNotNull(getResponse);
- assertThat(getResponse.getStatusLine().getStatusCode(), equalTo(200));
- assertThat(Strings.fromStream(getResponse.getEntity().getContent()), equalTo("a cheery response body"));
-
- HttpResponse postResponse = requestDirector.execute(null, new HttpPost("http://some.uri"), null);
- assertNotNull(postResponse);
- assertThat(postResponse.getStatusLine().getStatusCode(), equalTo(200));
- assertThat(Strings.fromStream(postResponse.getEntity().getContent()), equalTo("a cheery response body"));
- }
-
- @Test
- public void shouldReturnRequestsByRule_KeepsTrackOfOpenContentStreams() throws Exception {
- TestHttpResponse testHttpResponse = new TestHttpResponse(200, "a cheery response body");
- Robolectric.addHttpResponseRule("http://some.uri", testHttpResponse);
-
- assertThat(testHttpResponse.entityContentStreamsHaveBeenClosed(), equalTo(true));
-
- HttpResponse getResponse = requestDirector.execute(null, new HttpGet("http://some.uri"), null);
- InputStream getResponseStream = getResponse.getEntity().getContent();
- assertThat(Strings.fromStream(getResponseStream), equalTo("a cheery response body"));
- assertThat(testHttpResponse.entityContentStreamsHaveBeenClosed(), equalTo(false));
-
- HttpResponse postResponse = requestDirector.execute(null, new HttpPost("http://some.uri"), null);
- InputStream postResponseStream = postResponse.getEntity().getContent();
- assertThat(Strings.fromStream(postResponseStream), equalTo("a cheery response body"));
- assertThat(testHttpResponse.entityContentStreamsHaveBeenClosed(), equalTo(false));
-
- getResponseStream.close();
- assertThat(testHttpResponse.entityContentStreamsHaveBeenClosed(), equalTo(false));
-
- postResponseStream.close();
- assertThat(testHttpResponse.entityContentStreamsHaveBeenClosed(), equalTo(true));
- }
-
- @Test
- public void shouldReturnRequestsByRule_WithTextResponse() throws Exception {
- Robolectric.addHttpResponseRule("http://some.uri", "a cheery response body");
-
- HttpResponse response = requestDirector.execute(null, new HttpGet("http://some.uri"), null);
-
- assertNotNull(response);
- assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
- assertThat(Strings.fromStream(response.getEntity().getContent()), equalTo("a cheery response body"));
- }
-
- @Test
- public void clearHttpResponseRules_shouldRemoveAllRules() throws Exception {
- Robolectric.addHttpResponseRule("http://some.uri", "a cheery response body");
- Robolectric.clearHttpResponseRules();
- Robolectric.addHttpResponseRule("http://some.uri", "a gloomy response body");
-
- HttpResponse response = requestDirector.execute(null, new HttpGet("http://some.uri"), null);
-
- assertNotNull(response);
- assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
- assertThat(Strings.fromStream(response.getEntity().getContent()), equalTo("a gloomy response body"));
- }
-
- @Test
- public void clearPendingHttpResponses() throws Exception {
- Robolectric.addPendingHttpResponse(200, "earlier");
- Robolectric.clearPendingHttpResponses();
- Robolectric.addPendingHttpResponse(500, "later");
-
- HttpResponse response = requestDirector.execute(null, new HttpGet("http://some.uri"), null);
-
- assertNotNull(response);
- assertThat(response.getStatusLine().getStatusCode(), equalTo(500));
- assertThat(Strings.fromStream(response.getEntity().getContent()), equalTo("later"));
- }
-
- @Test
- public void shouldReturnRequestsByRule_WithCustomRequestMatcher() throws Exception {
- Robolectric.setDefaultHttpResponse(404, "no such page");
-
- Robolectric.addHttpResponseRule(new RequestMatcher() {
- @Override public boolean matches(HttpRequest request) {
- return request.getRequestLine().getUri().equals("http://matching.uri");
- }
- }, new TestHttpResponse(200, "a cheery response body"));
-
- HttpResponse response = requestDirector.execute(null, new HttpGet("http://matching.uri"), null);
- assertNotNull(response);
- assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
- assertThat(Strings.fromStream(response.getEntity().getContent()), equalTo("a cheery response body"));
-
- response = requestDirector.execute(null, new HttpGet("http://non-matching.uri"), null);
- assertNotNull(response);
- assertThat(response.getStatusLine().getStatusCode(), equalTo(404));
- assertThat(Strings.fromStream(response.getEntity().getContent()), equalTo("no such page"));
- }
-
- @Test
- public void shouldGetHttpResponseFromExecuteSimpleApi() throws Exception {
- Robolectric.addPendingHttpResponse(200, "a happy response body");
- HttpResponse response = requestDirector.execute(null, new HttpGet("http://example.com"), null);
-
- assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
- assertThat(Strings.fromStream(response.getEntity().getContent()), equalTo("a happy response body"));
- }
-
- @Test
- public void shouldHandleMultipleInvocations() throws Exception {
- Robolectric.addPendingHttpResponse(200, "a happy response body");
- Robolectric.addPendingHttpResponse(201, "another happy response body");
-
- HttpResponse response1 = requestDirector.execute(null, new HttpGet("http://example.com"), null);
- HttpResponse response2 = requestDirector.execute(null, new HttpGet("www.example.com"), null);
-
- assertThat(response1.getStatusLine().getStatusCode(), equalTo(200));
- assertThat(Strings.fromStream(response1.getEntity().getContent()), equalTo("a happy response body"));
-
- assertThat(response2.getStatusLine().getStatusCode(), equalTo(201));
- assertThat(Strings.fromStream(response2.getEntity().getContent()), equalTo("another happy response body"));
- }
-
- @Test
- public void shouldHandleMultipleInvocationsOfExecute() throws Exception {
- Robolectric.addPendingHttpResponse(200, "a happy response body");
- Robolectric.addPendingHttpResponse(201, "another happy response body");
-
- requestDirector.execute(null, new HttpGet("http://example.com"), null);
- requestDirector.execute(null, new HttpGet("www.example.com"), null);
-
- HttpUriRequest request1 = (HttpUriRequest) Robolectric.getSentHttpRequest(0);
- assertThat(request1.getMethod(), equalTo(HttpGet.METHOD_NAME));
- assertThat(request1.getURI(), equalTo(URI.create("http://example.com")));
-
- HttpUriRequest request2 = (HttpUriRequest) Robolectric.getSentHttpRequest(1);
- assertThat(request2.getMethod(), equalTo(HttpGet.METHOD_NAME));
- assertThat(request2.getURI(), equalTo(URI.create("www.example.com")));
- }
-
- @Test
- public void shouldRejectUnexpectedCallsToExecute() throws Exception {
- try {
- requestDirector.execute(null, new HttpGet("http://example.com"), null);
- fail();
- } catch (RuntimeException expected) {
- assertThat(expected.getMessage(), equalTo("Unexpected call to execute, no pending responses are available. See Robolectric.addPendingResponse(). Request was: GET http://example.com"));
- }
- }
-
- @Test
- public void shouldRecordExtendedRequestData() throws Exception {
- Robolectric.addPendingHttpResponse(200, "a happy response body");
- HttpGet httpGet = new HttpGet("http://example.com");
- requestDirector.execute(null, httpGet, null);
-
- assertSame(Robolectric.getSentHttpRequestInfo(0).getHttpRequest(), httpGet);
- ConnectionKeepAliveStrategy strategy = shadowOf((DefaultRequestDirector) Robolectric.getSentHttpRequestInfo(0).getRequestDirector()).getConnectionKeepAliveStrategy();
- assertSame(strategy, connectionKeepAliveStrategy);
- }
-
- @Test
- public void shouldSupportBasicResponseHandlerHandleResponse() throws Exception {
- Robolectric.addPendingHttpResponse(200, "OK", new BasicHeader("Content-Type", "text/plain"));
-
- DefaultHttpClient client = new DefaultHttpClient();
- HttpResponse response = client.execute(new HttpGet("http://www.nowhere.org"));
-
- assertThat(((HttpUriRequest) Robolectric.getSentHttpRequest(0)).getURI(),
- equalTo(URI.create("http://www.nowhere.org")));
-
- Assert.assertNotNull(response);
- String responseStr = new BasicResponseHandler().handleResponse(response);
- Assert.assertEquals("OK", responseStr);
- }
-
- @Test
- public void shouldFindLastRequestMade() throws Exception {
- Robolectric.addPendingHttpResponse(200, "a happy response body");
- Robolectric.addPendingHttpResponse(200, "a happy response body");
- Robolectric.addPendingHttpResponse(200, "a happy response body");
-
- DefaultHttpClient client = new DefaultHttpClient();
- client.execute(new HttpGet("http://www.first.org"));
- client.execute(new HttpGet("http://www.second.org"));
- client.execute(new HttpGet("http://www.third.org"));
-
- assertThat(((HttpUriRequest) Robolectric.getLatestSentHttpRequest()).getURI(),
- equalTo(URI.create("http://www.third.org")));
- }
-
-
- @Test
- public void shouldSupportConnectionTimeoutWithExceptions() throws Exception {
- Robolectric.setDefaultHttpResponse(new TestHttpResponse() {
- @Override
- public HttpParams getParams() {
- HttpParams httpParams = super.getParams();
- HttpConnectionParams.setConnectionTimeout(httpParams, -1);
- return httpParams;
- }
- });
-
- DefaultHttpClient client = new DefaultHttpClient();
- try {
- client.execute(new HttpGet("http://www.nowhere.org"));
- } catch (ConnectTimeoutException x) {
- return;
- }
-
- fail("Exception should have been thrown");
- }
-
- @Test
- public void shouldSupportSocketTimeoutWithExceptions() throws Exception {
- Robolectric.setDefaultHttpResponse(new TestHttpResponse() {
- @Override
- public HttpParams getParams() {
- HttpParams httpParams = super.getParams();
- HttpConnectionParams.setSoTimeout(httpParams, -1);
- return httpParams;
- }
- });
-
- DefaultHttpClient client = new DefaultHttpClient();
- try {
- client.execute(new HttpGet("http://www.nowhere.org"));
- } catch (ConnectTimeoutException x) {
- return;
- }
-
- fail("Exception should have been thrown");
- }
-
- @Test(expected = IOException.class)
- public void shouldSupportRealHttpRequests() throws Exception {
- Robolectric.getFakeHttpLayer().interceptHttpRequests(false);
- DefaultHttpClient client = new DefaultHttpClient();
- client.execute(new HttpGet("http://www.this-host-should-not-exist-123456790.org:999"));
- }
-
- @Test
- public void shouldReturnResponseFromHttpResponseGenerator() throws Exception {
- Robolectric.addPendingHttpResponse(new HttpResponseGenerator() {
- @Override
- public HttpResponse getResponse(HttpRequest request) {
- return new TestHttpResponse(200, "a happy response body");
- }
- });
- HttpResponse response = requestDirector.execute(null, new HttpGet("http://example.com"), null);
-
- assertNotNull(response);
- assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
- assertThat(Strings.fromStream(response.getEntity().getContent()), equalTo("a happy response body"));
- }
-
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/DialogFragmentTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/DialogFragmentTest.java
deleted file mode 100644
index dbfd139b0..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/DialogFragmentTest.java
+++ /dev/null
@@ -1,227 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.app.Activity;
-import android.app.Dialog;
-import android.os.Bundle;
-import android.support.v4.app.DialogFragment;
-import android.support.v4.app.FragmentActivity;
-import android.support.v4.app.FragmentTransaction;
-import android.view.LayoutInflater;
-import android.view.View;
-import android.view.ViewGroup;
-import com.xtremelabs.robolectric.R;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import com.xtremelabs.robolectric.tester.android.util.TestFragmentManager;
-import com.xtremelabs.robolectric.util.Transcript;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-import static org.junit.Assert.*;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class DialogFragmentTest {
-
- private FragmentActivity activity;
- private TestDialogFragment dialogFragment;
- private TestFragmentManager fragmentManager;
-
- @Before
- public void setUp() throws Exception {
- activity = new FragmentActivity();
- dialogFragment = new TestDialogFragment();
- fragmentManager = new TestFragmentManager(activity);
- }
-
- @Test
- public void show_shouldCallLifecycleMethods() throws Exception {
- dialogFragment.show(fragmentManager, "this is a tag");
-
- dialogFragment.transcript.assertEventsSoFar(
- "onAttach",
- "onCreate",
- "onCreateDialog",
- "onCreateView",
- "onViewCreated",
- "onActivityCreated",
- "onStart",
- "onResume"
- );
-
- assertNotNull(dialogFragment.getActivity());
- assertSame(activity, dialogFragment.onAttachActivity);
- }
-
- @Test
- public void show_whenPassedATransaction_shouldCallShowWithManager() throws Exception {
- dialogFragment.show(fragmentManager.beginTransaction(), "this is a tag");
-
- dialogFragment.transcript.assertEventsSoFar(
- "onAttach",
- "onCreate",
- "onCreateDialog",
- "onCreateView",
- "onViewCreated",
- "onActivityCreated",
- "onStart",
- "onResume"
- );
-
- assertNotNull(dialogFragment.getActivity());
- assertSame(activity, dialogFragment.onAttachActivity);
- }
-
- @Test
- public void show_shouldShowDialogThatWasReturnedFromOnCreateDialog_whenOnCreateDialogReturnsADialog() throws Exception {
- Dialog dialogFromOnCreateDialog = new Dialog(activity);
- dialogFragment.returnThisDialogFromOnCreateDialog(dialogFromOnCreateDialog);
- dialogFragment.show(fragmentManager, "this is a tag");
-
- Dialog dialog = ShadowDialog.getLatestDialog();
- assertSame(dialogFromOnCreateDialog, dialog);
- assertSame(dialogFromOnCreateDialog, dialogFragment.getDialog());
- assertSame(dialogFragment, fragmentManager.findFragmentByTag("this is a tag"));
- }
-
- @Test
- public void show_shouldShowDialogThatWasAutomaticallyCreated_whenOnCreateDialogReturnsNull() throws Exception {
- dialogFragment.show(fragmentManager, "this is a tag");
-
- Dialog dialog = ShadowDialog.getLatestDialog();
- assertNotNull(dialog);
- assertSame(dialog, dialogFragment.getDialog());
- assertNotNull(dialog.findViewById(R.id.title));
- assertSame(dialogFragment, fragmentManager.findFragmentByTag("this is a tag"));
- }
-
- @Test
- public void dismiss_shouldDismissTheDialog() throws Exception {
- dialogFragment.show(fragmentManager, "tag");
-
- dialogFragment.dismiss();
-
- Dialog dialog = ShadowDialog.getLatestDialog();
- assertFalse(dialog.isShowing());
- assertTrue(shadowOf(dialog).hasBeenDismissed());
- }
-
- @Test
- public void removeUsingTransaction_shouldDismissTheDialog() throws Exception {
- dialogFragment.show(fragmentManager, null);
-
- FragmentTransaction t = fragmentManager.beginTransaction();
- t.remove(dialogFragment);
- t.commit();
-
- Dialog dialog = ShadowDialog.getLatestDialog();
- assertFalse(dialog.isShowing());
- assertTrue(shadowOf(dialog).hasBeenDismissed());
- }
-
- @Test
- public void shouldDefaultToCancelable() throws Exception {
- DialogFragment dialogFragment = new DialogFragment();
-
- assertTrue(dialogFragment.isCancelable());
- }
-
- @Test
- public void shouldStoreCancelable() throws Exception {
- DialogFragment dialogFragment = new DialogFragment();
-
- dialogFragment.setCancelable(false);
-
- assertFalse(dialogFragment.isCancelable());
- }
-
- @Test
- public void shouldSetCancelableOnDialog() throws Exception {
- DialogFragment dialogFragment = new DialogFragment();
- dialogFragment.show(fragmentManager, "TAG");
-
- Dialog dialog = dialogFragment.getDialog();
-
- assertTrue(shadowOf(dialog).isCancelable());
- }
-
- @Test
- public void shouldSetNotCancelableOnDialogBeforeShow() throws Exception {
- DialogFragment dialogFragment = new DialogFragment();
- dialogFragment.setCancelable(false);
- dialogFragment.show(fragmentManager, "TAG");
-
- Dialog dialog = dialogFragment.getDialog();
-
- assertFalse(shadowOf(dialog).isCancelable());
- }
-
- @Test
- public void shouldSetNotCancelableOnDialogAfterShow() throws Exception {
- DialogFragment dialogFragment = new DialogFragment();
- dialogFragment.show(fragmentManager, "TAG");
- dialogFragment.setCancelable(false);
-
- Dialog dialog = dialogFragment.getDialog();
-
- assertFalse(shadowOf(dialog).isCancelable());
- }
-
- private class TestDialogFragment extends DialogFragment {
- final Transcript transcript = new Transcript();
- Activity onAttachActivity;
- private Dialog returnThisDialogFromOnCreateDialog;
-
- @Override
- public void onAttach(Activity activity) {
- transcript.add("onAttach");
- onAttachActivity = activity;
- super.onAttach(activity);
- }
-
- @Override
- public void onCreate(Bundle savedInstanceState) {
- transcript.add("onCreate");
- }
-
- @Override
- public Dialog onCreateDialog(Bundle savedInstanceState) {
- transcript.add("onCreateDialog");
- return returnThisDialogFromOnCreateDialog;
- }
-
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
- transcript.add("onCreateView");
- return inflater.inflate(R.layout.main, null);
- }
-
- @Override
- public void onViewCreated(View view, Bundle savedInstanceState) {
- transcript.add("onViewCreated");
- super.onViewCreated(view, savedInstanceState);
- }
-
- @Override
- public void onActivityCreated(Bundle savedInstanceState) {
- transcript.add("onActivityCreated");
- super.onActivityCreated(savedInstanceState);
- }
-
- @Override
- public void onStart() {
- transcript.add("onStart");
- super.onStart();
- }
-
- @Override
- public void onResume() {
- transcript.add("onResume");
- super.onResume();
- }
-
- public void returnThisDialogFromOnCreateDialog(Dialog dialog) {
- returnThisDialogFromOnCreateDialog = dialog;
- }
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/DialogPreferenceTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/DialogPreferenceTest.java
deleted file mode 100644
index 7374a3cdf..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/DialogPreferenceTest.java
+++ /dev/null
@@ -1,73 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.app.Activity;
-import android.content.Context;
-import android.preference.DialogPreference;
-import android.util.AttributeSet;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import com.xtremelabs.robolectric.tester.android.util.TestAttributeSet;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import java.util.HashMap;
-
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.CoreMatchers.sameInstance;
-import static org.junit.Assert.assertThat;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class DialogPreferenceTest {
-
- private static final String TEST_DIALOG_MESSAGE = "This is only a test";
-
- private DialogPreference preference;
- private ShadowDialogPreference shadow;
-
- private Context context;
- private TestAttributeSet attrs;
-
- @Before
- public void setup() {
- HashMap<String, String> hash = new HashMap<String, String>();
- hash.put("dialogMessage", TEST_DIALOG_MESSAGE);
- context = new Activity();
- attrs = new TestAttributeSet(hash);
- preference = new TestDialogPreference(context, attrs);
- shadow = Robolectric.shadowOf(preference);
- }
-
- @Test
- public void testConstructors() {
- int defStyle = 7;
-
- preference = new TestDialogPreference(context, attrs, defStyle);
- shadow = Robolectric.shadowOf(preference);
- assertThat(shadow.getContext(), sameInstance(context));
- assertThat(shadow.getAttrs(), sameInstance((AttributeSet) attrs));
- assertThat(shadow.getDefStyle(), equalTo(defStyle));
-
- preference = new TestDialogPreference(context, attrs);
- shadow = Robolectric.shadowOf(preference);
- assertThat(shadow.getContext(), sameInstance(context));
- assertThat(shadow.getAttrs(), sameInstance((AttributeSet) attrs));
- assertThat(shadow.getDefStyle(), equalTo(0));
- }
-
- @Test
- public void testGetDialogMessage() {
- assertThat((String) preference.getDialogMessage(), equalTo(TEST_DIALOG_MESSAGE));
- }
-
- protected static class TestDialogPreference extends DialogPreference {
-
- public TestDialogPreference(Context context, AttributeSet attrs, int defStyle) {
- super(context, attrs, defStyle);
- }
-
- public TestDialogPreference(Context context, AttributeSet attrs) {
- super(context, attrs);
- }
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/DialogTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/DialogTest.java
deleted file mode 100644
index 6b7886ce4..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/DialogTest.java
+++ /dev/null
@@ -1,189 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.app.Dialog;
-import android.content.DialogInterface;
-import android.os.Bundle;
-import android.widget.TextView;
-import com.xtremelabs.robolectric.R;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import com.xtremelabs.robolectric.util.Transcript;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static com.xtremelabs.robolectric.util.TestUtil.assertInstanceOf;
-import static junit.framework.Assert.*;
-import static org.hamcrest.CoreMatchers.nullValue;
-import static org.hamcrest.CoreMatchers.sameInstance;
-import static org.hamcrest.core.IsEqual.equalTo;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertThat;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class DialogTest {
- @Test
- public void shouldCallOnDismissListener() throws Exception {
- final Transcript transcript = new Transcript();
-
- final Dialog dialog = new Dialog(null);
- dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
- @Override
- public void onDismiss(DialogInterface dialogInListener) {
- assertThat((Dialog) dialogInListener, sameInstance(dialog));
- transcript.add("onDismiss called!");
- }
- });
-
- dialog.dismiss();
-
- transcript.assertEventsSoFar("onDismiss called!");
- }
-
- @Test
- public void shouldGetLayoutInflater() {
- Dialog dialog = new Dialog(Robolectric.application);
- assertNotNull(dialog.getLayoutInflater());
- }
-
- @Test
- public void shouldCallOnStartFromShow() {
- TestDialog dialog = new TestDialog();
- dialog.show();
-
- assertTrue(dialog.onStartCalled);
- }
-
- @Test
- public void shouldSetCancelable() {
- Dialog dialog = new Dialog(null);
- ShadowDialog shadow = Robolectric.shadowOf(dialog);
-
- dialog.setCancelable(false);
- assertThat(shadow.isCancelable(), equalTo(false));
- }
-
- @Test
- public void shouldDismissTheRealDialogWhenCancelled() throws Exception {
- TestDialog dialog = new TestDialog();
- dialog.cancel();
- assertThat(dialog.wasDismissed, equalTo(true));
- }
-
- @Test
- public void shouldDefaultCancelableToTrueAsTheSDKDoes() throws Exception {
- Dialog dialog = new Dialog(null);
- ShadowDialog shadow = Robolectric.shadowOf(dialog);
-
- assertThat(shadow.isCancelable(), equalTo(true));
- }
-
- @Test
- public void shouldOnlyCallOnCreateOnce() {
- final Transcript transcript = new Transcript();
-
- Dialog dialog = new Dialog(Robolectric.application) {
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- transcript.add("onCreate called");
- }
- };
-
- dialog.show();
- transcript.assertEventsSoFar("onCreate called");
-
- dialog.dismiss();
- dialog.show();
- transcript.assertNoEventsSoFar();
- }
-
- @Test
- public void show_setsLatestDialog() {
- Dialog dialog = new Dialog(Robolectric.application);
- assertNull(ShadowDialog.getLatestDialog());
-
- dialog.show();
-
- assertEquals(dialog, ShadowDialog.getLatestDialog());
- assertNull(ShadowAlertDialog.getLatestAlertDialog());
- }
-
- @Test
- public void getLatestDialog_shouldReturnARealDialog() throws Exception {
- assertThat(ShadowDialog.getLatestDialog(), nullValue());
-
- Dialog dialog = new Dialog(null);
- dialog.show();
- assertThat(ShadowDialog.getLatestDialog(), sameInstance(dialog));
- }
-
- @Test
- public void shouldKeepListOfOpenedDialogs() throws Exception {
- assertEquals(0, ShadowDialog.getShownDialogs().size());
-
- TestDialog dialog = new TestDialog();
- dialog.show();
-
- assertEquals(1, ShadowDialog.getShownDialogs().size());
- assertEquals(dialog, ShadowDialog.getShownDialogs().get(0));
-
- TestDialog dialog2 = new TestDialog();
- dialog2.show();
-
- assertEquals(2, ShadowDialog.getShownDialogs().size());
- assertEquals(dialog2, ShadowDialog.getShownDialogs().get(1));
-
- dialog.dismiss();
-
- assertEquals(2, ShadowDialog.getShownDialogs().size());
-
- ShadowDialog.reset();
-
- assertEquals(0, ShadowDialog.getShownDialogs().size());
- }
-
- @Test
- public void shouldPopulateListOfRecentDialogsInCorrectOrder() throws Exception {
- new NestingTestDialog().show();
-
- assertEquals(TestDialog.class, ShadowDialog.getLatestDialog().getClass());
- }
-
- @Test
- public void shouldFindViewsWithinAContentViewThatWasPreviouslySet() throws Exception {
- Dialog dialog = new Dialog(Robolectric.application);
- dialog.setContentView(dialog.getLayoutInflater().inflate(R.layout.main, null));
- assertInstanceOf(TextView.class, dialog.findViewById(R.id.title));
- }
-
- private static class TestDialog extends Dialog {
- boolean onStartCalled = false;
- boolean wasDismissed = false;
-
- public TestDialog() {
- super(null);
- }
-
- @Override
- protected void onStart() {
- onStartCalled = true;
- }
-
- @Override public void dismiss() {
- super.dismiss();
- wasDismissed = true;
- }
- }
-
- private static class NestingTestDialog extends Dialog {
- public NestingTestDialog() {
- super(null);
- };
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- new TestDialog().show();
- }
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/DisplayTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/DisplayTest.java
deleted file mode 100644
index 0f20caa3e..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/DisplayTest.java
+++ /dev/null
@@ -1,41 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.util.DisplayMetrics;
-import android.view.Display;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static org.junit.Assert.assertEquals;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class DisplayTest {
- @Test
- public void shouldProvideDisplayMetrics() throws Exception {
-
- Display display = Robolectric.newInstanceOf(Display.class);
- ShadowDisplay shadow = Robolectric.shadowOf(display);
-
- shadow.setDensity(1.5f);
- shadow.setDensityDpi(DisplayMetrics.DENSITY_MEDIUM);
- shadow.setScaledDensity(1.6f);
- shadow.setWidth(1024);
- shadow.setHeight(600);
- shadow.setXdpi(183.0f);
- shadow.setYdpi(184.0f);
-
- DisplayMetrics metrics = new DisplayMetrics();
-
- display.getMetrics(metrics);
-
- assertEquals(1.5f, metrics.density, 0.05);
- assertEquals(DisplayMetrics.DENSITY_MEDIUM, metrics.densityDpi);
- assertEquals(1.6f, metrics.scaledDensity, 0.05);
- assertEquals(1024, metrics.widthPixels);
- assertEquals(600, metrics.heightPixels);
- assertEquals(183.0f, metrics.xdpi, 0.05);
- assertEquals(184.0f, metrics.ydpi, 0.05);
- }
-
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/DrawableTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/DrawableTest.java
deleted file mode 100644
index dd4940a9b..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/DrawableTest.java
+++ /dev/null
@@ -1,175 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.graphics.BitmapFactory;
-import android.graphics.Canvas;
-import android.graphics.ColorFilter;
-import android.graphics.Rect;
-import android.graphics.drawable.Drawable;
-
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import java.io.ByteArrayInputStream;
-import java.io.InputStream;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-import static junit.framework.Assert.assertFalse;
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.CoreMatchers.is;
-import static org.junit.Assert.*;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class DrawableTest {
- @Test
- public void createFromStream__shouldReturnNullWhenAskedToCreateADrawableFromACorruptedSourceStream() throws Exception {
- String corruptedStreamSource = "http://foo.com/image.jpg";
- ShadowDrawable.addCorruptStreamSource(corruptedStreamSource);
- assertNull(ShadowDrawable.createFromStream(new ByteArrayInputStream(new byte[0]), corruptedStreamSource));
- }
-
- @Test
- public void createFromStream__shouldReturnDrawableWithSpecificSource() throws Exception {
- Drawable drawable = ShadowDrawable.createFromStream(new ByteArrayInputStream(new byte[0]), "my_source");
- assertNotNull(drawable);
- assertEquals("my_source", ((ShadowBitmapDrawable) shadowOf(drawable)).getSource());
- }
-
- @Test
- public void reset__shouldClearStaticState() throws Exception {
- String src = "source1";
- ShadowDrawable.addCorruptStreamSource(src);
- assertTrue(ShadowDrawable.corruptStreamSources.contains(src));
- ShadowDrawable.reset();
- assertFalse(ShadowDrawable.corruptStreamSources.contains(src));
- }
-
- @Test
- public void testCreateFromStream_shouldSetTheInputStreamOnTheReturnedDrawable() throws Exception {
- ByteArrayInputStream byteInputStream = new ByteArrayInputStream(new byte[0]);
- Drawable drawable = Drawable.createFromStream(byteInputStream, "src name");
- assertThat(shadowOf(drawable).getInputStream(), equalTo((InputStream) byteInputStream));
- }
-
- @Test
- public void copyBoundsWithPassedRect() {
- Drawable drawable = ShadowDrawable.createFromStream(new ByteArrayInputStream(new byte[0]), "my_source");
- drawable.setBounds(1, 2, 3, 4);
- Rect r = new Rect();
- drawable.copyBounds(r);
- assertThat(r.left, is(1));
- assertThat(r.top, is(2));
- assertThat(r.right, is(3));
- assertThat(r.bottom, is(4));
- }
-
- @Test
- public void copyBoundsToReturnedRect() {
- Drawable drawable = ShadowDrawable.createFromStream(new ByteArrayInputStream(new byte[0]), "my_source");
- drawable.setBounds(1, 2, 3, 4);
- Rect r = drawable.copyBounds();
- assertThat(r.left, is(1));
- assertThat(r.top, is(2));
- assertThat(r.right, is(3));
- assertThat(r.bottom, is(4));
- }
-
- @Test
- public void createFromPath__shouldReturnDrawableWithSpecificPath() throws Exception {
- Drawable drawable = ShadowDrawable.createFromPath("/foo");
- assertNotNull(drawable);
- assertEquals("/foo", ((ShadowBitmapDrawable) shadowOf(drawable)).getPath());
- }
-
- @Test
- public void testGetLoadedFromResourceId_shouldDefaultToNegativeOne() throws Exception {
- Drawable drawable = new TestDrawable();
- assertThat(shadowOf(drawable).getLoadedFromResourceId(), is(-1));
- }
-
- @Test
- public void testSetLoadedFromResourceId() throws Exception {
- Drawable drawable = new TestDrawable();
- ShadowDrawable shadowDrawable = shadowOf(drawable);
- shadowDrawable.setLoadedFromResourceId(99);
- assertThat(shadowDrawable.getLoadedFromResourceId(), is(99));
- }
-
- @Test
- public void testCreateFromResourceId_shouldSetTheId() throws Exception {
- Drawable drawable = ShadowDrawable.createFromResourceId(34758);
- ShadowDrawable shadowDrawable = shadowOf(drawable);
- assertThat(shadowDrawable.getLoadedFromResourceId(), is(34758));
- }
-
- @Test
- public void testWasSelfInvalidated() throws Exception {
- Drawable drawable = ShadowDrawable.createFromResourceId(34758);
- ShadowDrawable shadowDrawable = shadowOf(drawable);
- assertFalse(shadowDrawable.wasInvalidated());
- drawable.invalidateSelf();
- assertTrue(shadowDrawable.wasInvalidated());
- }
-
- @Test
- public void createFromResourceStream__shouldReturnNullWhenAskedToCreateADrawableFromACorruptedSourceStream() throws Exception {
- String corruptedStreamSource = "http://foo.com/image.jpg";
- ShadowDrawable.addCorruptStreamSource(corruptedStreamSource);
- assertNull(ShadowDrawable.createFromResourceStream(null, null, new ByteArrayInputStream(new byte[0]), corruptedStreamSource));
- }
-
- @Test
- public void createFromResourceStream__shouldReturnDrawableWithSpecificSource() throws Exception {
- Drawable drawable = ShadowDrawable.createFromResourceStream(null, null, new ByteArrayInputStream(new byte[0]), "my_source");
- assertNotNull(drawable);
- assertEquals("my_source", ((ShadowBitmapDrawable) shadowOf(drawable)).getSource());
- }
-
- @Test
- public void testCreateFromResourceStream_shouldSetTheInputStreamOnTheReturnedDrawable() throws Exception {
- ByteArrayInputStream byteInputStream = new ByteArrayInputStream(new byte[0]);
- Drawable drawable = Drawable.createFromResourceStream(null, null, byteInputStream, "src name");
- assertThat(shadowOf(drawable).getInputStream(), equalTo((InputStream) byteInputStream));
- }
-
- @Test
- public void createFromResourceStreamWithOptions__shouldReturnNullWhenAskedToCreateADrawableFromACorruptedSourceStream() throws Exception {
- String corruptedStreamSource = "http://foo.com/image.jpg";
- ShadowDrawable.addCorruptStreamSource(corruptedStreamSource);
- assertNull(ShadowDrawable.createFromResourceStream(null, null, new ByteArrayInputStream(new byte[0]), corruptedStreamSource, new BitmapFactory.Options()));
- }
-
- @Test
- public void createFromResourceStreamWithOptions__shouldReturnDrawableWithSpecificSource() throws Exception {
- Drawable drawable = ShadowDrawable.createFromResourceStream(null, null, new ByteArrayInputStream(new byte[0]), "my_source", new BitmapFactory.Options());
- assertNotNull(drawable);
- assertEquals("my_source", ((ShadowBitmapDrawable) shadowOf(drawable)).getSource());
- }
-
- @Test
- public void testCreateFromResourceStreamWithOptions_shouldSetTheInputStreamOnTheReturnedDrawable() throws Exception {
- ByteArrayInputStream byteInputStream = new ByteArrayInputStream(new byte[0]);
- Drawable drawable = Drawable.createFromResourceStream(null, null, byteInputStream, "src name", new BitmapFactory.Options());
- assertThat(shadowOf(drawable).getInputStream(), equalTo((InputStream) byteInputStream));
- }
-
- private static class TestDrawable extends Drawable {
- @Override
- public void draw(Canvas canvas) {
- }
-
- @Override
- public void setAlpha(int alpha) {
- }
-
- @Override
- public void setColorFilter(ColorFilter cf) {
- }
-
- @Override
- public int getOpacity() {
- return 0;
- }
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/EditTextTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/EditTextTest.java
deleted file mode 100644
index 9fa8d8dbb..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/EditTextTest.java
+++ /dev/null
@@ -1,91 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.junit.Assert.assertThat;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.Matchers.anyInt;
-import static org.mockito.Matchers.eq;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-
-import java.util.Random;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import android.util.AttributeSet;
-import android.widget.EditText;
-
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class EditTextTest {
-
- @Test
- public void shouldBeFocusableByDefault() throws Exception {
- assertTrue(new EditText(null).isFocusable());
- assertTrue(new EditText(null).isFocusableInTouchMode());
- }
-
- @Test
- public void givenInitializingWithAttributeSet_whenMaxLengthDefined_thenRestrictTextLengthToMaxLength() {
- int maxLength = anyInteger();
- AttributeSet attrs = attributeSetWithMaxLength(maxLength);
- EditText editText = new EditText(null, attrs);
- String excessiveInput = stringOfLength(maxLength * 2);
-
- editText.setText(excessiveInput);
-
- assertThat(editText.getText().toString(), equalTo(excessiveInput.subSequence(0, maxLength)));
- }
-
- @Test
- public void givenInitializingWithAttributeSet_whenMaxLengthNotDefined_thenTextLengthShouldHaveNoRestrictions() {
- AttributeSet attrs = attributeSetWithoutMaxLength();
- EditText editText = new EditText(null, attrs);
- String input = anyString();
-
- editText.setText(input);
-
- assertThat(editText.getText().toString(), equalTo(input));
- }
-
- @Test
- public void whenInitializingWithoutAttributeSet_thenTextLengthShouldHaveNoRestrictions() {
- EditText editText = new EditText(null);
- String input = anyString();
-
- editText.setText(input);
-
- assertThat(editText.getText().toString(), equalTo(input));
- }
-
- private String anyString() {
- return stringOfLength(anyInteger());
- }
-
- private String stringOfLength(int length) {
- StringBuilder stringBuilder = new StringBuilder();
-
- for (int i = 0; i < length; i++)
- stringBuilder.append('x');
-
- return stringBuilder.toString();
- }
-
- private int anyInteger() {
- return new Random().nextInt(1000) + 1;
- }
-
- private AttributeSet attributeSetWithMaxLength(int maxLength) {
- AttributeSet attrs = mock(AttributeSet.class);
- when(attrs.getAttributeIntValue(eq("android"), eq("maxLength"), anyInt())).thenReturn(maxLength);
- return attrs;
- }
-
- private AttributeSet attributeSetWithoutMaxLength() {
- AttributeSet attrs = mock(AttributeSet.class);
- when(attrs.getAttributeIntValue("android", "maxLength", Integer.MAX_VALUE)).thenReturn(Integer.MAX_VALUE);
- return attrs;
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/EnvironmentTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/EnvironmentTest.java
deleted file mode 100644
index fa5376a57..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/EnvironmentTest.java
+++ /dev/null
@@ -1,56 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import static org.junit.Assert.*;
-
-import java.io.File;
-
-import org.junit.After;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import android.os.Environment;
-
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-
-import static org.hamcrest.CoreMatchers.equalTo;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class EnvironmentTest {
-
- @After
- public void tearDown() throws Exception {
- deleteDir(ShadowContext.EXTERNAL_CACHE_DIR);
- deleteDir(ShadowContext.EXTERNAL_FILES_DIR);
- ShadowEnvironment.setExternalStorageState("removed");
- }
-
- @Test
- public void testExternalStorageState() {
- assertThat( Environment.getExternalStorageState(), equalTo("removed") );
- ShadowEnvironment.setExternalStorageState("mounted");
- assertThat( Environment.getExternalStorageState(), equalTo("mounted") );
- }
-
- @Test
- public void testGetExternalStorageDirectory() {
- assertTrue(Environment.getExternalStorageDirectory().exists());
- }
-
- @Test
- public void testGetExternalStoragePublicDirectory() {
- File extStoragePublic = Environment.getExternalStoragePublicDirectory("Movies");
- assertTrue(extStoragePublic.exists());
- assertThat(extStoragePublic, equalTo( new File(ShadowContext.EXTERNAL_FILES_DIR, "Movies" ) ) );
- }
-
- public void deleteDir(File path) {
- if (path.isDirectory()) {
- File[] files = path.listFiles();
- for (File f : files) {
- deleteDir(f);
- }
- }
- path.delete();
- }
-
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ExpandableListViewTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/ExpandableListViewTest.java
deleted file mode 100644
index f20c8d482..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ExpandableListViewTest.java
+++ /dev/null
@@ -1,57 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.view.View;
-import android.widget.ExpandableListView;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import com.xtremelabs.robolectric.util.Transcript;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static org.hamcrest.CoreMatchers.sameInstance;
-import static org.junit.Assert.assertThat;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class ExpandableListViewTest {
-
- private Transcript transcript;
- private ExpandableListView expandableListView;
- private MyOnChildClickListener myOnChildClickListener;
-
- @Before
- public void setUp() {
- expandableListView = new ExpandableListView(null);
- transcript = new Transcript();
- myOnChildClickListener = new MyOnChildClickListener();
- }
-
- @Test
- public void testPerformItemClick_ShouldFireOnItemClickListener() throws Exception {
- expandableListView.setOnChildClickListener(myOnChildClickListener);
- expandableListView.performItemClick(null, 6, -1);
- transcript.assertEventsSoFar("item was clicked: 6");
- }
-
- @Test
- public void shouldTolerateNullChildClickListener() throws Exception {
- expandableListView.performItemClick(null, 6, -1);
- }
-
- @Test
- public void shouldPassTheViewToTheClickListener() throws Exception {
- expandableListView.setOnChildClickListener(myOnChildClickListener);
- expandableListView.performItemClick(null, 6, -1);
- assertThat(myOnChildClickListener.expandableListView, sameInstance(expandableListView));
- }
-
- private class MyOnChildClickListener implements ExpandableListView.OnChildClickListener {
- ExpandableListView expandableListView;
-
- @Override
- public boolean onChildClick(ExpandableListView expandableListView, View view, int i, int position, long l) {
- this.expandableListView = expandableListView;
- transcript.add("item was clicked: " + position);
- return true;
- }
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/FragmentActivityTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/FragmentActivityTest.java
deleted file mode 100644
index 557757877..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/FragmentActivityTest.java
+++ /dev/null
@@ -1,185 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.os.Bundle;
-import android.support.v4.app.Fragment;
-import android.support.v4.app.FragmentActivity;
-import android.view.View;
-import android.view.ViewGroup;
-import android.widget.Button;
-
-import com.xtremelabs.robolectric.R;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import com.xtremelabs.robolectric.tester.android.util.TestFragmentManager;
-import org.junit.Before;
-import org.junit.Ignore;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-import static junit.framework.Assert.assertNull;
-import static junit.framework.Assert.assertTrue;
-import static org.junit.Assert.*;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class FragmentActivityTest {
-
- private TestFragmentActivity activity;
- private TestFragment fragment;
-
- @Before
- public void setUp() throws Exception {
- activity = new TestFragmentActivity();
- activity.onCreate(null);
- fragment = (TestFragment) activity.getSupportFragmentManager().findFragmentByTag("fragment_tag");
- }
-
- @Test
- public void shouldHaveAFragmentManager() throws Exception {
- assertNotNull(activity.getSupportFragmentManager());
- }
-
- @Test
- public void viewLoader_shouldInflateFragment() throws Exception {
- assertEquals(TestFragment.class, fragment.getClass());
- }
-
- @Test
- public void viewLoader_shouldSetFragmentId() throws Exception {
- Fragment fragmentById = activity.getSupportFragmentManager().findFragmentById(R.id.fragment);
- assertSame(fragment, fragmentById);
- }
-
- @Test
- public void viewLoader_shouldInsertFragmentViewIntoLayout() throws Exception {
- assertSame(fragment.onCreateViewReturnValue, activity.findViewById(TestFragment.FRAGMENT_VIEW_ID));
- }
-
- @Test
- public void viewLoader_shouldSetFragmentsActivity() throws Exception {
- assertSame(activity, fragment.getActivity());
- }
-
- @Test
- public void viewLoader_shouldCreateContainerView() throws Exception {
- ViewGroup container = (ViewGroup) activity.findViewById(R.id.fragment);
- assertNotNull(container);
- }
-
- @Test
- public void viewLoader_shouldInsertFragmentViewIntoContainer() throws Exception {
- ViewGroup container = (ViewGroup) activity.findViewById(R.id.fragment);
- View fragmentView = container.findViewById(TestFragment.FRAGMENT_VIEW_ID);
- assertSame(fragment.onCreateViewReturnValue, fragmentView);
- }
-
- @Test
- @Ignore("Seems to be broken by 'Android Support' rev 8")
- public void onSaveInstanceState_shouldStoreListOfFragments() throws Exception {
- Fragment fragment = new TestFragment();
- int fragment_container = R.id.dynamic_fragment_container;
- activity.getSupportFragmentManager().beginTransaction().add(fragment_container, fragment).commit();
- Bundle outState = new Bundle();
- activity.onSaveInstanceState(outState);
-
- assertTrue(outState.containsKey(ShadowFragmentActivity.FRAGMENTS_TAG));
-
- Object[] states = (Object[]) outState.getSerializable(ShadowFragmentActivity.FRAGMENTS_TAG);
- SerializedFragmentState fragmentState = (SerializedFragmentState) states[1];
-
- assertEquals(fragmentState.id, fragment.getId());
- assertEquals(fragmentState.tag, fragment.getTag());
- assertEquals(fragmentState.fragmentClass, fragment.getClass());
- assertEquals(fragmentState.containerId, fragment_container);
- }
-
- @Test
- public void onSaveInstanceState_shouldCallOnSaveInstanceStateOnFragments() throws Exception {
- TestFragment fragment = new TestFragment();
- int fragment_container = R.id.dynamic_fragment_container;
- activity.getSupportFragmentManager().beginTransaction().add(fragment_container, fragment).commit();
- Bundle outState = new Bundle();
- activity.onSaveInstanceState(outState);
-
- assertTrue(fragment.onSaveInstanceStateWasCalled);
- }
-
- @Test
- public void onCreate_shouldRecreateFragments() throws Exception {
- Bundle bundle = new Bundle();
- TestFragment dynamicFrag = new TestFragment();
- int containerId = 123;
- SerializedFragmentState fragmentState = new SerializedFragmentState(containerId, dynamicFrag);
- bundle.putSerializable(ShadowFragmentActivity.FRAGMENTS_TAG, new Object[]{fragmentState});
-
- activity = new TestFragmentActivity();
- activity.onCreate(bundle);
- TestFragmentManager fragmentManager = (TestFragmentManager) activity.getSupportFragmentManager();
- assertEquals(2, fragmentManager.getFragments().size());
-
- TestFragment restoredFrag = (TestFragment) fragmentManager.getFragmentsById().get(containerId);
- assertEquals(restoredFrag.getId(), dynamicFrag.getId());
- assertEquals(restoredFrag.getTag(), dynamicFrag.getTag());
- assertEquals(bundle, shadowOf(restoredFrag).getSavedInstanceState());
- assertSame(activity, restoredFrag.onAttachActivity);
- assertSame(activity, restoredFrag.getActivity());
- assertNull(restoredFrag.getView());
- }
-
- @Test
- public void onStart_shouldStartFragments() throws Exception {
- Bundle bundle = new Bundle();
- TestFragment dynamicFrag = new TestFragment();
- int containerId = 123;
- SerializedFragmentState fragmentState = new SerializedFragmentState(containerId, dynamicFrag);
- bundle.putSerializable(ShadowFragmentActivity.FRAGMENTS_TAG, new Object[]{fragmentState});
-
- activity = new TestFragmentActivity();
- activity.onCreate(bundle);
- shadowOf(activity).onStart();
- TestFragmentManager fragmentManager = (TestFragmentManager) activity.getSupportFragmentManager();
- assertEquals(2, fragmentManager.getFragments().size());
- TestFragment restoredFrag = (TestFragment) fragmentManager.getFragmentsById().get(containerId);
-
- assertEquals(restoredFrag.onCreateViewInflater, activity.getLayoutInflater());
- assertNotNull(restoredFrag.getView());
- }
-
- @Test
- public void onPause_shouldPauseTheFragment() throws Exception {
- activity.onPause();
- assertTrue(fragment.onPauseWasCalled);
- }
-
- @Test
- public void getCurrentFocus_shouldGetFocusFromFragment() {
- activity = new TestFragmentActivity();
- activity.onCreate(null);
- shadowOf(activity).onStart();
-
- Fragment fragment = activity.getSupportFragmentManager().findFragmentById(
- TestFragment.FRAGMENT_VIEW_ID);
- View button = activity.findViewById(R.id.button);
- button.requestFocus();
-
- View focusedView = activity.getCurrentFocus();
- assertSame(button, focusedView);
- }
-
- private static class TestFragmentActivity extends FragmentActivity {
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.fragment_activity);
- }
-
- @Override
- public void onSaveInstanceState(Bundle outState) {
- super.onSaveInstanceState(outState);
- }
-
- @Override
- public void onPause() {
- super.onPause();
- }
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/FragmentManagerTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/FragmentManagerTest.java
deleted file mode 100644
index c3bf61664..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/FragmentManagerTest.java
+++ /dev/null
@@ -1,249 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.os.Bundle;
-import android.os.Handler;
-import android.os.Looper;
-import android.support.v4.app.Fragment;
-import android.support.v4.app.FragmentActivity;
-import android.support.v4.app.FragmentTransaction;
-import android.view.LayoutInflater;
-import android.view.View;
-import android.view.ViewGroup;
-import android.widget.Button;
-import android.widget.FrameLayout;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import com.xtremelabs.robolectric.tester.android.util.TestFragmentManager;
-import com.xtremelabs.robolectric.util.Scheduler;
-import com.xtremelabs.robolectric.util.TestRunnable;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.CoreMatchers.sameInstance;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.junit.Assert.*;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class FragmentManagerTest {
-
- public static final int CONTAINER_VIEW_ID = 888;
- private TestFragmentManager manager;
- private TestFragment fragment;
- private TestFragmentActivity activity;
- private ViewGroup containerView;
-
- @Before
- public void setUp() throws Exception {
- activity = new TestFragmentActivity();
- activity.onCreate(null);
- manager = (TestFragmentManager) activity.getSupportFragmentManager();
- fragment = new TestFragment();
- containerView = (ViewGroup) activity.findViewById(CONTAINER_VIEW_ID);
- }
-
- @Test
- public void shouldFindFragmentById() throws Exception {
- manager.addFragment(CONTAINER_VIEW_ID, "tag1", fragment, false);
-
- assertThat(manager.findFragmentById(CONTAINER_VIEW_ID), sameInstance((Fragment) fragment));
- }
-
- @Test
- public void shouldFindFragmentByTag() throws Exception {
- manager.addFragment(CONTAINER_VIEW_ID, "tag1", fragment, false);
-
- assertThat(manager.findFragmentByTag("tag1"), sameInstance((Fragment) fragment));
- }
-
- @Test
- public void addFragment_shouldCallLifecycleMethods() throws Exception {
- manager.addFragment(View.NO_ID, null, fragment, false);
-
- fragment.transcript.assertEventsSoFar(
- "onAttach",
- "onCreate"
- );
-
- assertSame(activity, fragment.onAttachActivity);
- assertSame(activity, fragment.getActivity());
- }
-
- @Test
- public void startFragment_shouldCallLifecycleMethods() throws Exception {
- manager.addFragment(View.NO_ID, null, fragment, false);
- fragment.transcript.clear();
- manager.startFragment(fragment);
-
- fragment.transcript.assertEventsSoFar(
- "onCreateView",
- "onViewCreated",
- "onActivityCreated",
- "onStart"
- );
-
- assertEquals(fragment.onCreateViewInflater, activity.getLayoutInflater());
- assertNotNull(fragment.getView());
- }
-
- @Test
- public void addFragment_shouldSetTheFragmentsView() throws Exception {
- manager.addFragment(View.NO_ID, null, fragment, false);
-
- assertThat(fragment.getView(), sameInstance(fragment.onCreateViewReturnValue));
- }
-
- @Test
- public void addFragment_shouldSetTheFragmentsTag() throws Exception {
- manager.addFragment(View.NO_ID, "expected tag", fragment, false);
-
- assertThat(fragment.getTag(), equalTo("expected tag"));
- }
-
- @Test
- public void startFragment_shouldInsertTheFragmentViewIntoTheContainerView() throws Exception {
- manager.addFragment(CONTAINER_VIEW_ID, null, fragment, false);
- manager.startFragment(fragment);
-
- View fragmentViewParent = (View) activity.findViewById(TestFragment.FRAGMENT_VIEW_ID).getParent();
- assertThat(activity.findViewById(TestFragment.FRAGMENT_VIEW_ID), sameInstance(fragment.onCreateViewReturnValue));
- assertThat(fragmentViewParent, sameInstance((View) containerView));
- }
-
- @Test
- public void addFragmentWithReplace_shouldEmptyTheContainer() throws Exception {
- containerView.addView(new Button(activity));
- assertEquals(1, containerView.getChildCount());
-
- manager.addFragment(CONTAINER_VIEW_ID, null, fragment, true);
-
- assertEquals(1, containerView.getChildCount());
- }
-
- @Test
- public void addFragmentWithReplace_withNoContainer_shouldNotThrow() throws Exception {
- manager.addFragment(0, null, fragment, true);
- // pass
- }
-
- @Test
- public void addFragment_shouldSetFragmentsActivity() throws Exception {
- manager.addFragment(0, null, fragment, false);
-
- assertSame(activity, fragment.getActivity());
- }
-
- @Test
- public void addFragment_shouldPassTheSavedInstanceStateToOnCreate() throws Exception {
- Bundle bundle = new Bundle();
- shadowOf(fragment).setSavedInstanceState(bundle);
- manager.addFragment(0, null, fragment, false);
- assertSame(bundle, fragment.onCreateSavedInstanceState);
- }
-
- @Test
- public void getFragment_whenBundleSavedByShadowFragmentActivity_shouldGetFragmentByTagFromBundle() throws Exception {
- manager.addFragment(CONTAINER_VIEW_ID, "fragment tag", fragment, true);
-
- Bundle outState = new Bundle();
- shadowOf(activity).onSaveInstanceState(outState);
-
- Fragment retrievedFragment = manager.getFragment(outState, "fragment tag");
- assertEquals(TestFragment.class, retrievedFragment.getClass());
- }
-
- @Test
- public void startFragment_shouldPassSavedInstanceStateToOnCreateMethodOfFragment() throws Exception {
- shadowOf(fragment).setSavedInstanceState(new Bundle());
- manager.addFragment(CONTAINER_VIEW_ID, null, fragment, true);
- manager.startFragment(fragment);
-
- assertTrue(fragment.onActivityCreated_savedInstanceState != null);
- }
-
- @Test
- public void getCommittedTransactions_shouldReturnListOfOnlyCommittedTransactions() throws Exception {
- assertTrue(manager.getCommittedTransactions().isEmpty());
-
- FragmentTransaction transaction = manager.beginTransaction();
- assertTrue(manager.getCommittedTransactions().isEmpty());
-
- transaction.add(new Fragment(), "tag");
- transaction.commit();
- assertEquals(1, manager.getCommittedTransactions().size());
- assertSame(transaction, manager.getCommittedTransactions().get(0));
-
- FragmentTransaction anotherTransaction = manager.beginTransaction();
- anotherTransaction.add(new Fragment(), "tag");
- anotherTransaction.commit();
- assertEquals(2, manager.getCommittedTransactions().size());
- assertSame(anotherTransaction, manager.getCommittedTransactions().get(1));
- }
-
- @Test
- public void shouldBeAbleToCommitTransactions_whenTheFragmentHasNoView() throws Exception {
- TestFragment fragment = new TestFragment() {
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
- return null;
- }
- };
-
- activity.getSupportFragmentManager().beginTransaction().add(CONTAINER_VIEW_ID, fragment).commit();
-
- assertSame(fragment, activity.getSupportFragmentManager().findFragmentById(CONTAINER_VIEW_ID));
- }
-
- @Test
- public void executePendingTransactions_shouldRunPendingCommitsAsIfTheMainLooperWereNotPaused() throws Exception {
- Robolectric.pauseMainLooper();
- Scheduler scheduler = shadowOf(Looper.getMainLooper()).getScheduler();
- Fragment fragment2 = new Fragment();
-
- TestRunnable otherEnqueuedTask = new TestRunnable();
- new Handler(Looper.getMainLooper()).post(otherEnqueuedTask);
-
- manager.beginTransaction().add(fragment, "fragment1").commit();
- manager.beginTransaction().add(fragment2, "fragment2").commit();
-
- assertEquals(3, scheduler.enqueuedTaskCount());
- assertNull(manager.findFragmentByTag("fragment1"));
- assertNull(manager.findFragmentByTag("fragment2"));
-
- boolean ranSomeTransactions = manager.executePendingTransactions();
- assertTrue(ranSomeTransactions);
- assertSame(fragment, manager.findFragmentByTag("fragment1"));
- assertSame(fragment2, manager.findFragmentByTag("fragment2"));
- assertEquals(1, scheduler.enqueuedTaskCount());
-
- assertFalse(otherEnqueuedTask.wasRun);
- Robolectric.unPauseMainLooper();
- assertTrue(otherEnqueuedTask.wasRun);
-
- ranSomeTransactions = manager.executePendingTransactions();
- assertFalse(ranSomeTransactions);
- }
-
- @Test
- public void executePendingTransactions_shouldAvoidRunningTransactionsThatWereAlreadyRun() throws Exception {
- manager.beginTransaction().add(fragment, "tag").commit();
- assertEquals(1, manager.getCommittedTransactions().size());
-
- boolean ranSomeTransactions = manager.executePendingTransactions();
- assertFalse(ranSomeTransactions);
- assertEquals(1, manager.getCommittedTransactions().size());
- }
-
- private static class TestFragmentActivity extends FragmentActivity {
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- View view = new FrameLayout(this);
- view.setId(CONTAINER_VIEW_ID);
- setContentView(view);
- }
- }
-
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/FragmentTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/FragmentTest.java
deleted file mode 100644
index fcc92acab..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/FragmentTest.java
+++ /dev/null
@@ -1,41 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.support.v4.app.Fragment;
-import android.support.v4.app.FragmentActivity;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class FragmentTest {
- private Fragment fragment;
- private FragmentActivity fragmentActivity;
-
- @Before
- public void setUp() throws Exception {
- fragmentActivity = new FragmentActivity();
- fragment = new TestFragment();
- fragmentActivity.getSupportFragmentManager().beginTransaction().add(fragment, null).commit();
- }
-
- @Test
- public void retrieveIdOfResource() {
- int id = fragment.getResources().getIdentifier("hello", "string", "com.xtremelabs.robolectric");
- assertTrue(id > 0);
-
- String hello = fragment.getResources().getString(id);
- assertEquals("Hello", hello);
-
- hello = fragment.getString(id);
- assertEquals("Hello", hello);
- }
-
- @Test(expected = IllegalStateException.class)
- public void unattachedFragmentsCannotGetResources() throws Exception {
- new TestFragment().getResources();
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/FragmentTransactionTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/FragmentTransactionTest.java
deleted file mode 100644
index a6a0e7a31..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/FragmentTransactionTest.java
+++ /dev/null
@@ -1,298 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.Matchers.anyBoolean;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.never;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-
-import android.content.Intent;
-import android.support.v4.app.Fragment;
-import android.support.v4.app.FragmentActivity;
-import android.support.v4.app.FragmentTransaction;
-import android.view.View;
-
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import com.xtremelabs.robolectric.tester.android.util.TestFragmentManager;
-import com.xtremelabs.robolectric.tester.android.util.TestFragmentTransaction;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Map;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class FragmentTransactionTest {
- private MockTestFragmentManager manager;
- private Fragment fragment;
- private TestFragmentTransaction txn;
- private String tag;
- private int id;
-
- @Before
- public void setUp() throws Exception {
- manager = new MockTestFragmentManager();
- txn = new TestFragmentTransaction(manager);
- fragment = new TestFragment();
- tag = "tag";
- id = 111;
- }
-
- @Test
- public void testGetters() throws Exception {
- txn.add(fragment, tag);
- assertSame(fragment, txn.getFragment());
- assertSame(tag, txn.getTag());
- assertEquals(View.NO_ID, txn.getContainerViewId());
-
- txn.add(id, fragment);
- assertEquals(id, txn.getContainerViewId());
- assertSame(fragment, txn.getFragment());
-
- txn.add(id, fragment, tag);
- assertEquals(id, txn.getContainerViewId());
- assertSame(fragment, txn.getFragment());
- assertSame(tag, txn.getTag());
- assertFalse(txn.isReplacing());
-
- txn.replace(id, fragment);
- assertEquals(id, txn.getContainerViewId());
- assertSame(fragment, txn.getFragment());
- assertTrue(txn.isReplacing());
-
- txn.replace(id, fragment, tag);
- assertEquals(id, txn.getContainerViewId());
- assertSame(fragment, txn.getFragment());
- assertSame(tag, txn.getTag());
- assertTrue(txn.isReplacing());
- }
-
- @Test
- public void testAddToBackStack() throws Exception {
- assertFalse(txn.isAddedToBackStack());
- FragmentTransaction returnedTransaction = txn.addToBackStack("name");
- assertSame(txn, returnedTransaction);
- assertTrue(txn.isAddedToBackStack());
- assertEquals("name", txn.getBackStackName());
- }
-
- @Test
- public void addWithId_commit_shouldCallFragmentManager() throws Exception {
- txn.add(111, fragment).commit();
-
- assertTrue(manager.addFragmentWasCalled);
- assertEquals(manager.addFragmentContainerViewId, 111);
- assertEquals(manager.addFragmentTag, null);
- assertSame(manager.addFragmentFragment, fragment);
- assertFalse(manager.addFragmentReplace);
- }
-
- @Test
- public void addWithIdAndTag_commit_shouldCallFragmentManager() throws Exception {
- txn.add(111, fragment, "tag1").commit();
-
- assertTrue(manager.addFragmentWasCalled);
- assertEquals(manager.addFragmentContainerViewId, 111);
- assertEquals(manager.addFragmentTag, "tag1");
- assertSame(manager.addFragmentFragment, fragment);
- assertFalse(manager.addFragmentReplace);
- }
-
- @Test
- public void addWithTag_commit_shouldCallFragmentManager() throws Exception {
- txn.add(fragment, "tag1").commit();
-
- assertTrue(manager.addFragmentWasCalled);
- assertEquals(manager.addFragmentContainerViewId, View.NO_ID);
- assertEquals(manager.addFragmentTag, "tag1");
- assertSame(manager.addFragmentFragment, fragment);
- assertFalse(manager.addFragmentReplace);
- }
-
- @Test
- public void replaceWithId_commit_shouldCallFragmentManager() throws Exception {
- txn.replace(111, fragment).commit();
-
- assertTrue(manager.addFragmentWasCalled);
- assertEquals(manager.addFragmentContainerViewId, 111);
- assertEquals(manager.addFragmentTag, null);
- assertSame(manager.addFragmentFragment, fragment);
- assertTrue(manager.addFragmentReplace);
- }
-
- @Test
- public void replaceWithIdAndTag_commit_shouldCallFragmentManager() throws Exception {
- txn.replace(111, fragment, "tag1").commit();
-
- assertTrue(manager.addFragmentWasCalled);
- assertEquals(manager.addFragmentContainerViewId, 111);
- assertEquals(manager.addFragmentTag, "tag1");
- assertSame(manager.addFragmentFragment, fragment);
- assertTrue(manager.addFragmentReplace);
- }
-
- @Test
- public void startActivity_shouldNotDelegateToParentActivity() throws Exception {
- // because for some reason that's not what Android does in real life
- StartActivityTrackingActivity trackingActivity = new StartActivityTrackingActivity();
- shadowOf(fragment).setActivity(trackingActivity);
- fragment.startActivity(null);
- assertFalse(trackingActivity.startActivityWasCalled);
- }
-
- @Test
- public void commit_shouldNotActLikeCommitAllowingStateLoss() throws Exception {
- txn.add(fragment, "tag1").commit();
- assertFalse(txn.isCommittedAllowingStateLoss());
- }
-
- @Test
- public void commitAllowingStateLoss_shouldCommitAndSetAFlag() throws Exception {
- txn.add(fragment, "tag1").commitAllowingStateLoss();
-
- assertTrue(manager.addFragmentWasCalled);
- assertEquals(manager.addFragmentContainerViewId, View.NO_ID);
- assertEquals(manager.addFragmentTag, "tag1");
- assertSame(manager.addFragmentFragment, fragment);
-
- assertTrue(txn.isCommittedAllowingStateLoss());
- }
-
- @Test
- public void attach_shouldCauseFragmentToBecomeAttached() throws Exception {
- shadowOf(fragment).setAttached(false);
- txn.attach(fragment).commit();
- assertTrue(shadowOf(fragment).isAttached());
- }
-
- @Test
- public void hide_shouldCauseFragmentToBecomeHidden() {
- shadowOf(fragment).setHidden(false);
- txn.hide(fragment).commit();
- assertTrue(shadowOf(fragment).isHidden());
- }
-
- @Test
- public void show_shouldCauseFragmentToBecomeNotHidden() {
- shadowOf(fragment).setHidden(true);
- txn.show(fragment).commit();
- assertFalse(shadowOf(fragment).isHidden());
- }
-
- @Test
- public void hide_shouldCallOnHiddenChangedOnFragment() {
- final String key = "onHiddenChanged";
- final Map<String, Boolean> calls = new HashMap<String, Boolean>();
- Fragment fragment = new TestFragment() {
- @Override
- public void onHiddenChanged(boolean hidden) {
- super.onHiddenChanged(hidden);
- calls.put(key, hidden);
- }
- };
- shadowOf(fragment).setHidden(false);
- txn.hide(fragment).commit();
- assertEquals(true, calls.get(key));
- }
-
- @Test
- public void show_shouldCallOnHiddenChangedOnFragment() {
- final String key = "onHiddenChanged";
- final Map<String, Boolean> calls = new HashMap<String, Boolean>();
- Fragment fragment = new TestFragment() {
- @Override
- public void onHiddenChanged(boolean hidden) {
- super.onHiddenChanged(hidden);
- calls.put(key, hidden);
- }
- };
- shadowOf(fragment).setHidden(true);
- txn.show(fragment).commit();
- assertEquals(false, calls.get(key));
- }
-
- @Test
- public void hide_shouldNotCallOnHiddenChangedOnFragmentIfAlreadyHidden() {
- final String key = "onHiddenChanged";
- final Map<String, Boolean> calls = new HashMap<String, Boolean>();
- Fragment fragment = new TestFragment() {
- @Override
- public void onHiddenChanged(boolean hidden) {
- super.onHiddenChanged(hidden);
- calls.put(key, hidden);
- }
- };
- shadowOf(fragment).setHidden(true);
- txn.hide(fragment).commit();
- assertFalse(calls.containsKey(key));
- }
-
- @Test
- public void show_shouldNotCallOnHiddenChangedOnFragmentIfAlreadyNotHidden() {
- final String key = "onHiddenChanged";
- final Map<String, Boolean> calls = new HashMap<String, Boolean>();
- Fragment fragment = new TestFragment() {
- @Override
- public void onHiddenChanged(boolean hidden) {
- super.onHiddenChanged(hidden);
- calls.put(key, hidden);
- }
- };
- shadowOf(fragment).setHidden(false);
- txn.show(fragment).commit();
- assertFalse(calls.containsKey(key));
- }
-
- @Test
- public void showHide_shouldHideFragment() {
- shadowOf(fragment).setHidden(false);
- txn.show(fragment).hide(fragment).commit();
- assertTrue(shadowOf(fragment).isHidden());
- }
-
- @Test
- public void hideShow_shouldShowFragment() {
- shadowOf(fragment).setHidden(false);
- txn.hide(fragment).show(fragment).commit();
- assertFalse(shadowOf(fragment).isHidden());
- }
-
- private static class MockTestFragmentManager extends TestFragmentManager {
- private boolean addFragmentWasCalled;
- private int addFragmentContainerViewId;
- private String addFragmentTag;
- private Fragment addFragmentFragment;
- private boolean addFragmentReplace;
-
- public MockTestFragmentManager() {
- super(new FragmentActivity());
- }
-
- @Override
- public void addFragment(int containerViewId, String tag, Fragment fragment, boolean replace) {
- addFragmentWasCalled = true;
- addFragmentContainerViewId = containerViewId;
- addFragmentTag = tag;
- addFragmentFragment = fragment;
- addFragmentReplace = replace;
- }
- }
-
- private static class StartActivityTrackingActivity extends FragmentActivity {
- boolean startActivityWasCalled;
-
- @Override
- public void startActivity(Intent intent) {
- super.startActivity(intent);
- startActivityWasCalled = true;
- }
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/FrameLayoutTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/FrameLayoutTest.java
deleted file mode 100644
index 74db0aa3e..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/FrameLayoutTest.java
+++ /dev/null
@@ -1,33 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-
-import android.view.ViewGroup;
-import android.widget.FrameLayout;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static org.hamcrest.CoreMatchers.instanceOf;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertThat;
-
-/**
- * {@link ShadowFrameLayout} test suite.
- */
-@RunWith(WithTestDefaultsRunner.class)
-public class FrameLayoutTest {
-
- @Test
- public void testNotNull() {
- FrameLayout frameLayout = new FrameLayout(null);
- assertNotNull(frameLayout);
- }
-
- @Test
- public void getLayoutParamsShouldReturnInstanceOfMarginLayoutParams() {
- FrameLayout frameLayout = new FrameLayout(null);
- ViewGroup.LayoutParams layoutParams = frameLayout.getLayoutParams();
- assertThat(layoutParams, instanceOf(ViewGroup.MarginLayoutParams.class));
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/GalleryTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/GalleryTest.java
deleted file mode 100644
index 97de42fcb..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/GalleryTest.java
+++ /dev/null
@@ -1,59 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.view.KeyEvent;
-import android.view.View;
-import android.widget.Gallery;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.CoreMatchers.sameInstance;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.junit.Assert.assertTrue;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class GalleryTest {
- private Gallery gallery;
- private TestOnKeyListener listener;
- private KeyEvent event;
-
- @Before
- public void setUp() throws Exception {
- gallery = new Gallery(null);
- listener = new TestOnKeyListener();
- gallery.setOnKeyListener(listener);
- event = new KeyEvent(1, 2);
- }
-
- @Test
- public void onKeyDown_dPadRightShouldTriggerKeyEventDPadRight() throws Exception {
- assertTrue(gallery.onKeyDown(KeyEvent.KEYCODE_DPAD_RIGHT, event));
- assertThat(listener.keyCode, equalTo(KeyEvent.KEYCODE_DPAD_RIGHT));
- assertThat((Gallery) listener.view, sameInstance(gallery));
- assertThat(listener.event, sameInstance(event));
- }
-
- @Test
- public void onKeyDown_dPadLeftShouldTriggerKeyEventListener() throws Exception {
- assertTrue(gallery.onKeyDown(KeyEvent.KEYCODE_DPAD_RIGHT, event));
- assertThat(listener.keyCode, equalTo(KeyEvent.KEYCODE_DPAD_RIGHT));
- assertThat((Gallery)listener.view, sameInstance(gallery));
- assertThat(listener.event, sameInstance(event));
- }
-
- private static class TestOnKeyListener implements View.OnKeyListener {
- View view;
- int keyCode;
- KeyEvent event;
-
- @Override
- public boolean onKey(View view, int keyCode, KeyEvent event) {
- this.view = view;
- this.keyCode = keyCode;
- this.event = event;
- return false;
- }
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/GeocoderTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/GeocoderTest.java
deleted file mode 100644
index b2fc75f26..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/GeocoderTest.java
+++ /dev/null
@@ -1,63 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.app.Activity;
-import android.location.Address;
-import android.location.Geocoder;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import java.util.List;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-import static junit.framework.Assert.assertFalse;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class GeocoderTest {
-
- private Geocoder geocoder;
-
- @Before
- public void setUp() throws Exception {
- geocoder = new Geocoder(new Activity());
- }
-
- @Test
- public void shouldRecordLastLocationName() throws Exception {
- geocoder.getFromLocationName("731 Market St, San Francisco, CA 94103", 1);
- String lastLocationName = shadowOf(geocoder).getLastLocationName();
-
- assertEquals("731 Market St, San Francisco, CA 94103", lastLocationName);
- }
-
- @Test
- public void setsUpHasLocationInAddressFromLocationName() throws Exception {
- shadowOf(geocoder).setSimulatedHasLatLong(true, true);
- Address address = geocoder.getFromLocationName("731 Market St, San Francisco, CA 94103", 1).get(0);
- assertTrue(address.hasLatitude());
- assertTrue(address.hasLongitude());
- shadowOf(geocoder).setSimulatedHasLatLong(false, false);
- address = geocoder.getFromLocationName("731 Market St, San Francisco, CA 94103", 1).get(0);
- assertFalse(address.hasLatitude());
- assertFalse(address.hasLongitude());
- }
-
- @Test
- public void canReturnNoAddressesOnRequest() throws Exception {
- shadowOf(geocoder).setReturnNoResults(true);
- List<Address> result = geocoder.getFromLocationName("731 Market St, San Francisco, CA 94103", 1);
- assertEquals(0, result.size());
- }
-
-
- @Test
- public void answersWhetherResolutionHappened() throws Exception {
- assertFalse(shadowOf(geocoder).didResolution());
- shadowOf(geocoder).setReturnNoResults(true);
- geocoder.getFromLocationName("731 Market St, San Francisco, CA 94103", 1);
- assertTrue(shadowOf(geocoder).didResolution());
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/H2DatabaseTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/H2DatabaseTest.java
deleted file mode 100644
index da91972c9..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/H2DatabaseTest.java
+++ /dev/null
@@ -1,20 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import com.xtremelabs.robolectric.util.DatabaseConfig;
-import com.xtremelabs.robolectric.util.H2Map;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.junit.Assert.assertThat;
-
-@DatabaseConfig.UsingDatabaseMap(H2Map.class)
-@RunWith(WithTestDefaultsRunner.class)
-public class H2DatabaseTest extends DatabaseTestBase {
- @Test
- public void shouldUseH2DatabaseMap() throws Exception {
- assertThat(DatabaseConfig.getDatabaseMap().getClass().getName(),
- equalTo(H2Map.class.getName()));
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/HandlerTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/HandlerTest.java
deleted file mode 100644
index 3d11fb388..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/HandlerTest.java
+++ /dev/null
@@ -1,398 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.os.Handler;
-import android.os.Looper;
-import android.os.Message;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import com.xtremelabs.robolectric.util.TestRunnable;
-import com.xtremelabs.robolectric.util.Transcript;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static com.xtremelabs.robolectric.Robolectric.newInstanceOf;
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.CoreMatchers.nullValue;
-import static org.junit.Assert.assertThat;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.assertFalse;
-
-import java.util.ArrayList;
-import java.util.List;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class HandlerTest {
- private Transcript transcript;
- TestRunnable scratchRunnable = new TestRunnable();
-
- private Handler.Callback callback = new Handler.Callback() {
- @Override
- public boolean handleMessage(Message msg) {
- hasHandlerCallbackHandledMessage = true;
- return false;
- }
- };
-
- private Boolean hasHandlerCallbackHandledMessage = false;
-
- @Before
- public void setUp() throws Exception {
- transcript = new Transcript();
- }
-
- @Test
- public void testInsertsRunnablesBasedOnLooper() throws Exception {
- Looper looper = newInstanceOf(Looper.class);
-
- Handler handler1 = new Handler(looper);
- handler1.post(new Say("first thing"));
-
- Handler handler2 = new Handler(looper);
- handler2.post(new Say("second thing"));
-
- shadowOf(looper).idle();
-
- transcript.assertEventsSoFar("first thing", "second thing");
- }
-
- @Test
- public void testDefaultConstructorUsesDefaultLooper() throws Exception {
- Handler handler1 = new Handler();
- handler1.post(new Say("first thing"));
-
- Handler handler2 = new Handler(Looper.myLooper());
- handler2.post(new Say("second thing"));
-
- shadowOf(Looper.myLooper()).idle();
-
- transcript.assertEventsSoFar("first thing", "second thing");
- }
-
- @Test
- public void testDifferentLoopersGetDifferentQueues() throws Exception {
- Looper looper1 = Robolectric.newInstanceOf(Looper.class);
- Robolectric.pauseLooper(looper1);
-
- Looper looper2 = Robolectric.newInstanceOf(Looper.class);
- Robolectric.pauseLooper(looper2);
-
- Handler handler1 = new Handler(looper1);
- handler1.post(new Say("first thing"));
-
- Handler handler2 = new Handler(looper2);
- handler2.post(new Say("second thing"));
-
- shadowOf(looper2).idle();
-
- transcript.assertEventsSoFar("second thing");
- }
-
- @Test
- public void shouldCallProvidedHandlerCallback() {
- Handler handler = new Handler(callback);
- handler.sendMessage(new Message());
- assertTrue(hasHandlerCallbackHandledMessage);
- }
-
- @Test
- public void testPostAndIdleMainLooper() throws Exception {
- new Handler().post(scratchRunnable);
- ShadowHandler.idleMainLooper();
- assertThat(scratchRunnable.wasRun, equalTo(true));
- }
-
- @Test
- public void postDelayedThenIdleMainLooper_shouldNotRunRunnable() throws Exception {
- new Handler().postDelayed(scratchRunnable, 1);
- ShadowHandler.idleMainLooper();
- assertThat(scratchRunnable.wasRun, equalTo(false));
- }
-
- @Test
- public void testPostDelayedThenRunMainLooperOneTask() throws Exception {
- new Handler().postDelayed(scratchRunnable, 1);
- ShadowHandler.runMainLooperOneTask();
- assertThat(scratchRunnable.wasRun, equalTo(true));
- }
-
- @Test
- public void testRemoveCallbacks() throws Exception {
- Handler handler = new Handler();
- ShadowLooper shadowLooper = shadowOf(handler.getLooper());
- shadowLooper.pause();
- handler.post(scratchRunnable);
- handler.removeCallbacks(scratchRunnable);
-
- shadowLooper.unPause();
-
- assertThat(scratchRunnable.wasRun, equalTo(false));
- }
-
- @Test
- public void testPostDelayedThenRunMainLooperToNextTask_shouldRunOneTask() throws Exception {
- new Handler().postDelayed(scratchRunnable, 1);
- ShadowHandler.runMainLooperToNextTask();
- assertThat(scratchRunnable.wasRun, equalTo(true));
- }
-
- @Test
- public void testPostDelayedTwiceThenRunMainLooperToNextTask_shouldRunMultipleTasks() throws Exception {
- TestRunnable task1 = new TestRunnable();
- TestRunnable task2 = new TestRunnable();
-
- new Handler().postDelayed(task1, 1);
- new Handler().postDelayed(task2, 1);
-
- ShadowHandler.runMainLooperToNextTask();
- assertThat(task1.wasRun, equalTo(true));
- assertThat(task2.wasRun, equalTo(true));
- }
-
- @Test
- public void testPostDelayedTwiceThenRunMainLooperOneTask_shouldRunOnlyOneTask() throws Exception {
- TestRunnable task1 = new TestRunnable();
- TestRunnable task2 = new TestRunnable();
-
- new Handler().postDelayed(task1, 1);
- new Handler().postDelayed(task2, 1);
-
- ShadowHandler.runMainLooperOneTask();
- assertThat(task1.wasRun, equalTo(true));
- assertThat(task2.wasRun, equalTo(false));
- }
-
- @Test
- public void testPostDelayedMultipleThenRunMainLooperOneTask_shouldRunMultipleTask() throws Exception {
- TestRunnable task1 = new TestRunnable();
- TestRunnable task2 = new TestRunnable();
- TestRunnable task3 = new TestRunnable();
-
- new Handler().postDelayed(task1, 1);
- new Handler().postDelayed(task2, 10);
- new Handler().postDelayed(task3, 100);
-
- ShadowHandler.runMainLooperToEndOfTasks();
- assertThat(task1.wasRun, equalTo(true));
- assertThat(task2.wasRun, equalTo(true));
- assertThat(task3.wasRun, equalTo(true));
- }
-
- @Test
- public void testPostAtFrontOfQueueThenRunMainLooperOneTaskAtATime_shouldRunFrontOfQueueTaskFirst() throws Exception {
- TestRunnable task1 = new TestRunnable();
- TestRunnable task2 = new TestRunnable();
-
- ShadowLooper.pauseMainLooper();
- new Handler().post(task1);
- boolean result = new Handler().postAtFrontOfQueue(task2);
-
- assertTrue(result);
-
- ShadowHandler.runMainLooperOneTask();
- assertThat(task2.wasRun, equalTo(true));
- assertThat(task1.wasRun, equalTo(false));
- ShadowHandler.runMainLooperOneTask();
- assertThat(task1.wasRun, equalTo(true));
- }
-
- @Test
- public void testSendMessageAtFrontOfQueueThenRunMainLooperOneMsgAtATime_shouldRunFrontOfQueueMsgFirst() throws Exception {
- Handler handler = new Handler();
-
- ShadowLooper.pauseMainLooper();
- // Post two messages to handler. Handle first message and confirm that msg posted
- // to front is removed.
- handler.obtainMessage(123).sendToTarget();
- Message frontMsg = handler.obtainMessage(345);
- boolean result = handler.sendMessageAtFrontOfQueue(frontMsg);
-
- assertTrue(result);
-
- assertTrue(handler.hasMessages(123));
- assertTrue(handler.hasMessages(345));
- ShadowHandler.runMainLooperOneTask();
- assertTrue(handler.hasMessages(123));
- assertFalse(handler.hasMessages(345));
- ShadowHandler.runMainLooperOneTask();
- assertFalse(handler.hasMessages(123));
- assertFalse(handler.hasMessages(345));
- }
-
- @Test
- public void sendEmptyMessage_addMessageToQueue() {
- Robolectric.pauseMainLooper();
- Handler handler = new Handler();
- assertThat(handler.hasMessages(123), equalTo(false));
- handler.sendEmptyMessage(123);
- assertThat(handler.hasMessages(456), equalTo(false));
- assertThat(handler.hasMessages(123), equalTo(true));
- Robolectric.idleMainLooper(0);
- assertThat(handler.hasMessages(123), equalTo(false));
- }
-
- @Test
- public void sendEmptyMessageDelayed_sendsMessageAtCorrectTime() {
- Robolectric.pauseMainLooper();
- Handler handler = new Handler();
- handler.sendEmptyMessageDelayed(123, 500);
- assertThat(handler.hasMessages(123), equalTo(true));
- Robolectric.idleMainLooper(100);
- assertThat(handler.hasMessages(123), equalTo(true));
- Robolectric.idleMainLooper(400);
- assertThat(handler.hasMessages(123), equalTo(false));
- }
-
- @Test
- public void removeMessages_takesMessageOutOfQueue() {
- Robolectric.pauseMainLooper();
- Handler handler = new Handler();
- handler.sendEmptyMessageDelayed(123, 500);
- handler.removeMessages(123);
- assertThat(handler.hasMessages(123), equalTo(false));
- }
-
- @Test
- public void removeMessage_withSpecifiedObject() throws Exception {
- Robolectric.pauseMainLooper();
- Handler handler = new Handler();
- Message.obtain(handler, 123, "foo").sendToTarget();
- Message.obtain(handler, 123, "bar").sendToTarget();
-
- assertThat(handler.hasMessages(123), equalTo(true));
- assertThat(handler.hasMessages(123, "foo"), equalTo(true));
- assertThat(handler.hasMessages(123, "bar"), equalTo(true));
- assertThat(handler.hasMessages(123, "baz"), equalTo(false));
-
- handler.removeMessages(123, "foo");
- assertThat(handler.hasMessages(123), equalTo(true));
-
- handler.removeMessages(123, "bar");
- assertThat(handler.hasMessages(123), equalTo(false));
- }
-
- @Test
- public void testHasMessagesWithWhatAndObject() {
- Robolectric.pauseMainLooper();
- Object testObject = new Object();
- Handler handler = new Handler();
- Message message = handler.obtainMessage(123, testObject);
-
- assertFalse(handler.hasMessages(123, testObject));
-
- handler.sendMessage(message);
-
- assertTrue(handler.hasMessages(123, testObject));
- }
-
- @Test
- public void testSendToTarget() {
- Robolectric.pauseMainLooper();
- Object testObject = new Object();
- Handler handler = new Handler();
- Message message = handler.obtainMessage(123, testObject);
-
- assertThat(handler, equalTo(message.getTarget()));
-
- message.sendToTarget();
-
- assertTrue(handler.hasMessages(123, testObject));
- }
-
- @Test
- public void removeMessages_removesFromLooperQueueAsWell() {
- final boolean[] wasRun = new boolean[1];
- Robolectric.pauseMainLooper();
- Handler handler = new Handler() {
- @Override
- public void handleMessage(Message msg) {
- wasRun[0] = true;
- }
- };
- handler.sendEmptyMessageDelayed(123, 500);
- handler.removeMessages(123);
- Robolectric.unPauseMainLooper();
- assertThat(wasRun[0], equalTo(false));
- }
-
- @Test
- public void shouldObtainMessage() throws Exception {
- Message m0 = new Handler().obtainMessage();
- assertThat(m0.what, equalTo(0));
- assertThat(m0.obj, nullValue());
-
- Message m1 = new Handler().obtainMessage(1);
- assertThat(m1.what, equalTo(1));
- assertThat(m1.obj, nullValue());
-
- Message m2 = new Handler().obtainMessage(1, "foo");
- assertThat(m2.what, equalTo(1));
- assertThat(m2.obj, equalTo((Object)"foo"));
-
- Message m3 = new Handler().obtainMessage(1, 2, 3);
- assertThat(m3.what, equalTo(1));
- assertThat(m3.arg1, equalTo(2));
- assertThat(m3.arg2, equalTo(3));
- assertThat(m3.obj, nullValue());
-
- Message m4 = new Handler().obtainMessage(1, 2, 3, "foo");
- assertThat(m4.what, equalTo(1));
- assertThat(m4.arg1, equalTo(2));
- assertThat(m4.arg2, equalTo(3));
- assertThat(m4.obj, equalTo((Object)"foo"));
- }
-
- @Test
- public void shouldSetWhenOnMessage() throws Exception {
- final List<Message> msgs = new ArrayList<Message>();
- Handler h = new Handler(new Handler.Callback() {
- @Override
- public boolean handleMessage(Message msg) {
- msgs.add(msg);
- return false;
- }
- });
-
- h.sendEmptyMessage(0);
- h.sendEmptyMessageDelayed(0, 4000l);
- Robolectric.getUiThreadScheduler().advanceToLastPostedRunnable();
- h.sendEmptyMessageDelayed(0, 12000l);
- Robolectric.getUiThreadScheduler().advanceToLastPostedRunnable();
- assertThat(msgs.size(), equalTo(3));
-
- Message m0 = msgs.get(0);
- Message m1 = msgs.get(1);
- Message m2 = msgs.get(2);
-
- assertThat(m0.getWhen(), equalTo(0l));
- assertThat(m1.getWhen(), equalTo(4000l));
- assertThat(m2.getWhen(), equalTo(16000l));
- }
-
- @Test
- public void shouldRemoveMessageFromQueueBeforeDispatching() throws Exception {
- Handler h = new Handler(Looper.myLooper()) {
- @Override
- public void handleMessage(Message msg) {
- assertFalse(hasMessages(0));
- }
- };
- h.sendEmptyMessage(0);
- h.sendMessageAtFrontOfQueue(h.obtainMessage());
- }
-
-
- private class Say implements Runnable {
- private String event;
-
- public Say(String event) {
- this.event = event;
- }
-
- @Override
- public void run() {
- transcript.add(event);
- }
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/HandlerThreadTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/HandlerThreadTest.java
deleted file mode 100644
index 8e2340d5a..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/HandlerThreadTest.java
+++ /dev/null
@@ -1,81 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-import static org.junit.Assert.*;
-
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-
-import org.junit.After;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import android.os.HandlerThread;
-import android.os.Looper;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class HandlerThreadTest {
-
- private HandlerThread handlerThread;
-
- @After
- public void tearDown() throws Exception {
- // Try to ensure we've exited the thread at the end of each test
- if ( handlerThread != null ) {
- handlerThread.quit();
- handlerThread.join();
- }
- }
-
- @Test
- public void shouldReturnLooper() throws Exception {
- handlerThread = new HandlerThread("test");
- handlerThread.start();
- assertNotNull(handlerThread.getLooper());
- assertNotSame(handlerThread.getLooper(), Robolectric.application.getMainLooper());
- }
-
- @Test
- public void shouldReturnNullIfThreadHasNotBeenStarted() throws Exception {
- handlerThread = new HandlerThread("test");
- assertNull(handlerThread.getLooper());
- }
-
- @Test
- public void shouldQuitLooperAndThread() throws Exception {
- handlerThread = new HandlerThread("test");
- handlerThread.start();
- assertTrue(handlerThread.isAlive());
- assertTrue(handlerThread.quit());
- handlerThread.join();
- assertFalse(handlerThread.isAlive());
- handlerThread = null;
- }
-
- @Test
- public void shouldStopThreadIfLooperIsQuit() throws Exception {
- handlerThread = new HandlerThread("test1");
- handlerThread.start();
- Looper looper = handlerThread.getLooper();
- assertFalse(shadowOf(looper).quit);
- looper.quit();
- handlerThread.join();
- assertFalse(handlerThread.isAlive());
- assertTrue(shadowOf(looper).quit);
- handlerThread = null;
- }
-
- @Test
- public void shouldCallOnLooperPrepared() throws Exception {
- final Boolean[] wasCalled = new Boolean[] { false };
- handlerThread = new HandlerThread("test") {
- @Override
- protected void onLooperPrepared() {
- wasCalled[0] = true;
- }
- };
- handlerThread.start();
- assertNotNull(handlerThread.getLooper());
- assertTrue(wasCalled[0]);
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/HtmlTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/HtmlTest.java
deleted file mode 100644
index 47c68b537..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/HtmlTest.java
+++ /dev/null
@@ -1,44 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-
-import android.app.Activity;
-import android.content.Context;
-import android.text.Html;
-import android.widget.EditText;
-import android.widget.TextView;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.junit.Assert.assertThat;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class HtmlTest {
- private Context context;
-
- @Before
- public void setUp() throws Exception {
- context = new Activity();
- }
-
- @Test
- public void shouldBeAbleToGetTextFromTextViewAfterUsingSetTextWithHtmlDotFromHtml() throws Exception {
- TextView textView = new TextView(context);
- textView.setText(Html.fromHtml("<b>some</b> html text"));
- assertThat(textView.getText().toString(), equalTo("<b>some</b> html text"));
- }
-
- @Test
- public void shouldBeAbleToGetTextFromEditTextAfterUsingSetTextWithHtmlDotFromHtml() throws Exception {
- EditText editText = new EditText(context);
- editText.setText(Html.fromHtml("<b>some</b> html text"));
- assertThat(editText.getText().toString(), equalTo("<b>some</b> html text"));
- }
-
- @Test(expected = NullPointerException.class)
- public void shouldThrowNullPointerExceptionWhenNullStringEncountered() throws Exception {
- Html.fromHtml(null);
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ImageViewTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/ImageViewTest.java
deleted file mode 100644
index 151929154..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ImageViewTest.java
+++ /dev/null
@@ -1,107 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.content.res.Resources;
-import android.graphics.Bitmap;
-import android.graphics.BitmapFactory;
-import android.graphics.Matrix;
-import android.graphics.drawable.AnimationDrawable;
-import android.graphics.drawable.Drawable;
-import android.graphics.drawable.LayerDrawable;
-import android.widget.ImageView;
-import com.xtremelabs.robolectric.R;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-import static com.xtremelabs.robolectric.Robolectric.visualize;
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class ImageViewTest {
- private ImageView imageView;
-
- @Before
- public void setUp() throws Exception {
- Resources resources = Robolectric.application.getResources();
- Bitmap bitmap = BitmapFactory.decodeResource(resources,
- R.drawable.an_image);
- imageView = new ImageView(Robolectric.application);
- imageView.setImageBitmap(bitmap);
- }
-
- @Test
- public void shouldDrawWithImageMatrix() throws Exception {
- imageView.setImageMatrix(new Matrix());
- assertEquals("Bitmap for resource:drawable/an_image",
- visualize(imageView));
-
- Matrix matrix = new Matrix();
- matrix.setTranslate(15, 20);
- imageView.setImageMatrix(matrix);
- assertEquals("Bitmap for resource:drawable/an_image at (15,20)",
- visualize(imageView));
- }
-
- @Test
- public void shouldCopyMatrixSetup() throws Exception {
- Matrix matrix = new Matrix();
- matrix.setTranslate(15, 20);
- imageView.setImageMatrix(matrix);
- assertEquals("Bitmap for resource:drawable/an_image at (15,20)",
- visualize(imageView));
-
- matrix.setTranslate(30, 40);
- assertEquals("Bitmap for resource:drawable/an_image at (15,20)",
- visualize(imageView));
-
- imageView.setImageMatrix(matrix);
- assertEquals("Bitmap for resource:drawable/an_image at (30,40)",
- visualize(imageView));
- }
-
- @Test
- public void testSetImageResource_drawable() {
- imageView.setImageResource(R.drawable.l0_red);
- assertTrue("Drawable", imageView.getDrawable() instanceof Drawable);
- assertFalse("LayerDrawable",
- imageView.getDrawable() instanceof LayerDrawable);
- }
-
- @Test
- public void testSetAnimatedImage_drawable() {
- imageView.setImageResource(R.drawable.animation_list);
- Drawable animation = imageView.getDrawable();
- assertTrue(animation instanceof Drawable);
- assertTrue(animation instanceof AnimationDrawable);
- }
-
- @Test
- public void testSetAnimationItem() throws Exception {
- imageView.setImageResource(R.drawable.animation_list);
- AnimationDrawable animation = (AnimationDrawable) imageView.getDrawable();
- assertEquals(3, animation.getNumberOfFrames());
- }
-
- @Test
- public void testSetImageResource_layerDrawable() {
- imageView.setImageResource(R.drawable.rainbow);
- assertTrue("Drawable", imageView.getDrawable() instanceof Drawable);
- assertTrue("LayerDrawable",
- imageView.getDrawable() instanceof LayerDrawable);
- assertThat(shadowOf(imageView.getDrawable()).getLoadedFromResourceId(), is(R.drawable.rainbow));
- }
-
- @Test
- public void testSetImageLevel() throws Exception {
- imageView.setImageLevel(2);
- assertThat(shadowOf(imageView).getImageLevel(), equalTo(2));
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/InputMethodManagerTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/InputMethodManagerTest.java
deleted file mode 100644
index 5fedbfdff..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/InputMethodManagerTest.java
+++ /dev/null
@@ -1,38 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import android.app.Activity;
-import android.view.inputmethod.InputMethodManager;
-
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.junit.Assert.assertThat;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class InputMethodManagerTest {
-
- private InputMethodManager manager;
- private ShadowInputMethodManager shadow;
-
- @Before
- public void setUp() throws Exception {
- manager = (InputMethodManager) Robolectric.application.getSystemService(Activity.INPUT_METHOD_SERVICE);
- shadow = Robolectric.shadowOf(manager);
- }
-
- @Test
- public void shouldRecordSoftInputVisibility() {
- assertThat(shadow.isSoftInputVisible(), equalTo(false));
-
- manager.showSoftInput(null, 0);
- assertThat(shadow.isSoftInputVisible(), equalTo(true));
-
- manager.hideSoftInputFromWindow(null, 0);
- assertThat(shadow.isSoftInputVisible(), equalTo(false));
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/IntentFilterAuthorityEntryTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/IntentFilterAuthorityEntryTest.java
deleted file mode 100644
index 4017c621e..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/IntentFilterAuthorityEntryTest.java
+++ /dev/null
@@ -1,23 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.content.IntentFilter;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.junit.Assert.assertThat;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class IntentFilterAuthorityEntryTest {
- @Test(expected = NumberFormatException.class)
- public void constructor_shouldThrowAnExceptionIfPortIsNotAValidNumber() throws Exception {
- new IntentFilter.AuthorityEntry("", "not a number");
- }
-
- @Test
- public void constructor_shouldAllowNullPortAndSetToNegativeOne() throws Exception {
- IntentFilter.AuthorityEntry authorityEntry = new IntentFilter.AuthorityEntry("host", null);
- assertThat(authorityEntry.getPort(), equalTo(-1));
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/IntentFilterTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/IntentFilterTest.java
deleted file mode 100644
index 088138fee..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/IntentFilterTest.java
+++ /dev/null
@@ -1,34 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.content.IntentFilter;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.junit.Assert.assertThat;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class IntentFilterTest {
- @Test
- public void addDataScheme_shouldAddTheDataScheme() throws Exception {
- IntentFilter intentFilter = new IntentFilter();
- intentFilter.addDataScheme("http");
- intentFilter.addDataScheme("ftp");
-
- assertThat(intentFilter.getDataScheme(0), equalTo("http"));
- assertThat(intentFilter.getDataScheme(1), equalTo("ftp"));
- }
-
- @Test
- public void addDataAuthority_shouldAddTheDataAuthority() throws Exception {
- IntentFilter intentFilter = new IntentFilter();
- intentFilter.addDataAuthority("test.com", "8080");
- intentFilter.addDataAuthority("example.com", "42");
-
- assertThat(intentFilter.getDataAuthority(0).getHost(), equalTo("test.com"));
- assertThat(intentFilter.getDataAuthority(0).getPort(), equalTo(8080));
- assertThat(intentFilter.getDataAuthority(1).getHost(), equalTo("example.com"));
- assertThat(intentFilter.getDataAuthority(1).getPort(), equalTo(42));
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/IntentTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/IntentTest.java
deleted file mode 100644
index d491606c6..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/IntentTest.java
+++ /dev/null
@@ -1,488 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-import static junit.framework.Assert.assertEquals;
-import static junit.framework.Assert.assertTrue;
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.CoreMatchers.not;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotSame;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertThat;
-
-import android.app.Activity;
-import android.content.ComponentName;
-import android.content.Intent;
-import android.net.Uri;
-import android.os.Bundle;
-import android.os.Parcel;
-import android.os.Parcelable;
-
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Set;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class IntentTest {
- @Test
- public void testStringExtra() throws Exception {
- Intent intent = new Intent();
- assertSame(intent, intent.putExtra("foo", "bar"));
- assertEquals("bar", intent.getExtras().get("foo"));
- }
-
- @Test
- public void testCharSequenceExtra() throws Exception {
- Intent intent = new Intent();
- CharSequence cs = new TestCharSequence("bar");
- assertSame(intent, intent.putExtra("foo", cs));
- assertSame(cs, intent.getExtras().get("foo"));
- }
-
- @Test
- public void testIntExtra() throws Exception {
- Intent intent = new Intent();
- assertSame(intent, intent.putExtra("foo", 2));
- assertEquals(2, intent.getExtras().get("foo"));
- assertEquals(2, intent.getIntExtra("foo", -1));
- }
-
- @Test
- public void testDoubleExtra() throws Exception {
- Intent intent = new Intent();
- assertSame(intent, intent.putExtra("foo", 2d));
- assertEquals(2d, intent.getExtras().get("foo"));
- assertEquals(2d, intent.getDoubleExtra("foo", -1));
- }
-
- @Test
- public void testFloatExtra() throws Exception {
- Intent intent = new Intent();
- assertSame(intent, intent.putExtra("foo", 2f));
- assertEquals(2f, intent.getExtras().get("foo"));
- assertEquals(2f, intent.getFloatExtra("foo", -1));
- }
-
- @Test
- public void testIntArrayExtra() throws Exception {
- Intent intent = new Intent();
- int[] array = new int[2];
- array[0] = 1;
- array[1] = 2;
- assertSame(intent, intent.putExtra("foo", array));
- assertEquals(1, intent.getIntArrayExtra("foo")[0]);
- assertEquals(2, intent.getIntArrayExtra("foo")[1]);
- }
-
- @Test
- public void testLongArrayExtra() throws Exception {
- Intent intent = new Intent();
- long[] array = new long[2];
- array[0] = 1L;
- array[1] = 2L;
- assertSame(intent, intent.putExtra("foo", array));
- assertEquals(1L, intent.getLongArrayExtra("foo")[0]);
- assertEquals(2L, intent.getLongArrayExtra("foo")[1]);
- }
-
- @Test
- public void testSerializableExtra() throws Exception {
- Intent intent = new Intent();
- TestSerializable serializable = new TestSerializable("some string");
- assertSame(intent, intent.putExtra("foo", serializable));
- assertEquals(serializable, intent.getExtras().get("foo"));
- assertNotSame(serializable, intent.getExtras().get("foo"));
- assertEquals(serializable, intent.getSerializableExtra("foo"));
- assertNotSame(serializable, intent.getSerializableExtra("foo"));
- }
-
- @Test
- public void testParcelableExtra() throws Exception {
- Intent intent = new Intent();
- Parcelable parcelable = new TestParcelable(44);
- assertSame(intent, intent.putExtra("foo", parcelable));
- assertSame(parcelable, intent.getExtras().get("foo"));
- assertSame(parcelable, intent.getParcelableExtra("foo"));
- }
-
- @Test
- public void testParcelableArrayExtra() throws Exception {
- Intent intent = new Intent();
- Parcelable parcelable = new TestParcelable(11);
- intent.putExtra("foo", parcelable);
- assertSame(null, intent.getParcelableArrayExtra("foo"));
- Parcelable[] parcelables = {new TestParcelable(12), new TestParcelable(13)};
- assertSame(intent, intent.putExtra("bar", parcelables));
- assertSame(parcelables, intent.getParcelableArrayExtra("bar"));
- }
-
- @Test
- public void testParcelableArrayListExtra() {
- Intent intent = new Intent();
- Parcelable parcel1 = new TestParcelable(22);
- Parcelable parcel2 = new TestParcelable(23);
- ArrayList<Parcelable> parcels = new ArrayList<Parcelable>();
- parcels.add(parcel1);
- parcels.add(parcel2);
-
- assertSame(intent, intent.putParcelableArrayListExtra("foo", parcels));
- assertSame(parcels, intent.getParcelableArrayListExtra("foo"));
- assertSame(parcel1, intent.getParcelableArrayListExtra("foo").get(0));
- assertSame(parcel2, intent.getParcelableArrayListExtra("foo").get(1));
- assertSame(parcels, intent.getExtras().getParcelableArrayList("foo"));
- }
-
- @Test
- public void testLongExtra() throws Exception {
- Intent intent = new Intent();
- assertSame(intent, intent.putExtra("foo", 2L));
- assertEquals(2L, shadowOf(intent).getExtras().get("foo"));
- assertEquals(2L, intent.getLongExtra("foo", -1));
- assertEquals(-1L, intent.getLongExtra("bar", -1));
- }
-
- @Test
- public void testBundleExtra() throws Exception {
- Intent intent = new Intent();
- Bundle bundle = new Bundle();
- bundle.putInt("bar", 5);
- assertSame(intent, intent.putExtra("foo", bundle));
- assertEquals(5, intent.getBundleExtra("foo").getInt("bar"));
- }
-
- @Test
- public void testHasExtra() throws Exception {
- Intent intent = new Intent();
- assertSame(intent, intent.putExtra("foo", ""));
- assertTrue(intent.hasExtra("foo"));
- assertFalse(intent.hasExtra("bar"));
- }
-
- @Test
- public void testGetActionReturnsWhatWasSet() throws Exception {
- Intent intent = new Intent();
- assertSame(intent, intent.setAction("foo"));
- assertEquals("foo", intent.getAction());
- }
-
- @Test
- public void testSetData() throws Exception {
- Intent intent = new Intent();
- Uri uri = Uri.parse("content://this/and/that");
- intent.setType("abc");
- assertSame(intent, intent.setData(uri));
- assertSame(uri, intent.getData());
- assertNull(intent.getType());
- }
-
- @Test
- public void testSetType() throws Exception {
- Intent intent = new Intent();
- intent.setData(Uri.parse("content://this/and/that"));
- assertSame(intent, intent.setType("def"));
- assertNull(intent.getData());
- assertEquals("def", intent.getType());
- }
-
- @Test
- public void testSetDataAndType() throws Exception {
- Intent intent = new Intent();
- Uri uri = Uri.parse("content://this/and/that");
- assertSame(intent, intent.setDataAndType(uri, "ghi"));
- assertSame(uri, intent.getData());
- assertEquals("ghi", intent.getType());
- }
-
- @Test
- public void testSetClass() throws Exception {
- Intent intent = new Intent();
- Class<? extends IntentTest> thisClass = getClass();
- Intent output = intent.setClass(new Activity(), thisClass);
-
- assertSame(output, intent);
- ShadowIntent si = shadowOf(intent);
- assertSame(si.getIntentClass(), thisClass);
- }
-
- @Test
- public void testSetClassName() throws Exception {
- Intent intent = new Intent();
- Class<? extends IntentTest> thisClass = getClass();
- intent.setClassName("package.name", thisClass.getName());
- assertSame(thisClass.getName(), intent.getComponent().getClassName());
- assertEquals("package.name", intent.getComponent().getPackageName());
- ShadowIntent si = shadowOf(intent);
- assertSame(si.getIntentClass(), thisClass);
- }
-
- @Test
- public void testSetClassThroughConstructor() throws Exception {
- Intent intent = new Intent(new Activity(), getClass());
- assertEquals(shadowOf(intent).getIntentClass(), getClass());
- }
-
- @Test
- public void shouldSetFlags() throws Exception {
- Intent intent = new Intent();
- Intent self = intent.setFlags(1234);
- assertEquals(1234, intent.getFlags());
- assertSame(self, intent);
- }
-
- @Test
- public void shouldAddFlags() throws Exception {
- Intent intent = new Intent();
- Intent self = intent.addFlags(4);
- self.addFlags(8);
- assertEquals(12, intent.getFlags());
- assertSame(self, intent);
- }
-
- @Test
- public void shouldSupportCategories() throws Exception {
- Intent intent = new Intent();
- Intent self = intent.addCategory("category.name.1");
- intent.addCategory("category.name.2");
-
- assertTrue(intent.hasCategory("category.name.1"));
- assertTrue(intent.hasCategory("category.name.2"));
-
- Set<String> categories = intent.getCategories();
- assertTrue(categories.contains("category.name.1"));
- assertTrue(categories.contains("category.name.2"));
-
- intent.removeCategory("category.name.1");
- assertFalse(intent.hasCategory("category.name.1"));
- assertTrue(intent.hasCategory("category.name.2"));
-
- intent.removeCategory("category.name.2");
- assertFalse(intent.hasCategory("category.name.2"));
-
- assertEquals(0, intent.getCategories().size());
-
- assertSame(self, intent);
- }
-
- @Test
- public void shouldAddCategories() throws Exception {
- Intent intent = new Intent();
- Intent self = intent.addCategory("foo");
- assertTrue(intent.getCategories().contains("foo"));
- assertSame(self, intent);
- }
-
- @Test
- public void shouldFillIn() throws Exception {
- Intent intentA = new Intent();
- Intent intentB = new Intent();
-
- intentB.setAction("foo");
- Uri uri = Uri.parse("http://www.foo.com");
- intentB.setDataAndType(uri, "text/html");
- String category = "category";
- intentB.addCategory(category);
- intentB.setPackage("com.foobar.app");
- ComponentName cn = new ComponentName("com.foobar.app", "activity");
- intentB.setComponent(cn);
- intentB.putExtra("FOO", 23);
-
- int flags = Intent.FILL_IN_ACTION |
- Intent.FILL_IN_DATA |
- Intent.FILL_IN_CATEGORIES |
- Intent.FILL_IN_PACKAGE |
- Intent.FILL_IN_COMPONENT;
-
- int result = intentA.fillIn(intentB, flags);
- assertEquals("foo", intentA.getAction());
- assertSame(uri, intentA.getData());
- assertEquals("text/html", intentA.getType());
- assertTrue(intentA.getCategories().contains(category));
- assertEquals("com.foobar.app", intentA.getPackage());
- assertSame(cn, intentA.getComponent());
- assertEquals(23, intentA.getIntExtra("FOO", -1));
- assertEquals(result, flags);
- }
-
- @Test
- public void equals_shouldTestActionComponentNameDataAndExtras() throws Exception {
- Intent intentA = new Intent()
- .setAction("action")
- .setData(Uri.parse("content:1"))
- .setComponent(new ComponentName("pkg", "cls"))
- .putExtra("extra", "blah")
- .setType("image/*")
- .addCategory("category.name");
-
- Intent intentB = new Intent()
- .setAction("action")
- .setData(Uri.parse("content:1"))
- .setComponent(new ComponentName("pkg", "cls"))
- .putExtra("extra", "blah")
- .setType("image/*")
- .addCategory("category.name");
-
- assertThat(intentA, equalTo(intentB));
-
- intentB.setAction("other action");
- assertThat(intentA, not(equalTo(intentB)));
-
- intentB.setAction("action");
- intentB.setData(Uri.parse("content:other"));
- assertThat(intentA, not(equalTo(intentB)));
-
- intentB.setData(Uri.parse("content:1"));
- intentB.setComponent(new ComponentName("other-pkg", "other-cls"));
- assertThat(intentA, not(equalTo(intentB)));
-
- intentB.setComponent(new ComponentName("pkg", "cls"));
- intentB.putExtra("extra", "foo");
- assertThat(intentA, not(equalTo(intentB)));
-
- intentB.putExtra("extra", "blah");
- intentB.setType("other/*");
- assertThat(intentA, not(equalTo(intentB)));
-
- intentB.setType("image/*");
- assertThat(intentA, equalTo(intentB));
-
- intentB.removeCategory("category.name");
- assertThat(intentA, not(equalTo(intentB)));
- }
-
- @Test
- public void equals_whenOtherObjectIsNotAnIntent_shouldReturnFalse() throws Exception {
- assertThat(new Intent(), not(equalTo(new Object())));
- }
-
- @Test
- public void createChooser_shouldWrapIntent() throws Exception {
- Intent originalIntent = new Intent(Intent.ACTION_BATTERY_CHANGED, Uri.parse("foo://blah"));
- Intent chooserIntent = Intent.createChooser(originalIntent, "The title");
- Intent expectedIntent = new Intent(Intent.ACTION_CHOOSER);
- expectedIntent.putExtra(Intent.EXTRA_INTENT, originalIntent);
- expectedIntent.putExtra(Intent.EXTRA_TITLE, "The title");
- assertEquals(expectedIntent, chooserIntent);
- }
-
- @Test
- public void putStringArrayListExtra_addsListToExtras() {
- Intent intent = new Intent();
- final ArrayList<String> strings = new ArrayList<String>(Arrays.asList("hi", "there"));
-
- intent.putStringArrayListExtra("KEY", strings);
- assertThat(intent.getStringArrayListExtra("KEY"), equalTo(strings));
- assertThat(Robolectric.shadowOf(intent.getExtras()).getStringArrayList("KEY"), equalTo(strings));
- }
-
- @Test
- public void putIntegerArrayListExtra_addsListToExtras() {
- Intent intent = new Intent();
- final ArrayList<Integer> integers = new ArrayList<Integer>(Arrays.asList(100, 200, 300));
-
- intent.putIntegerArrayListExtra("KEY", integers);
- assertThat(intent.getIntegerArrayListExtra("KEY"), equalTo(integers));
- assertThat(Robolectric.shadowOf(intent.getExtras()).getIntegerArrayList("KEY"), equalTo(integers));
- }
-
- @Test
- public void testParcelIo_explicitIntent() {
- Intent intent = new Intent(new Activity(), getClass());
- intent.putExtra("boolean", true);
- intent.putExtra("string", "string value");
- Bundle bundle = new Bundle();
- bundle.putDouble("bundle double", 3.14);
- intent.putExtra("bundle", bundle);
- intent.putExtra("long", 893);
-
- verifyIntentReadIsWhatWasWrittenToParcel(intent);
- }
-
- @Test
- public void testParcelIo_actionTypeCategory() {
- Intent intent = new Intent("action");
- intent.setType("type");
- intent.addCategory("category");
- verifyIntentReadIsWhatWasWrittenToParcel(intent);
- }
-
- @Test
- public void shouldHaveCreator() throws Exception {
- Intent expected = new Intent("action");
- expected.setType("type");
- expected.addCategory("category");
- Parcel p = Parcel.obtain();
- expected.writeToParcel(p, 0);
-
- p.setDataPosition(0);
-
- Intent actual = Intent.CREATOR.createFromParcel(p);
- assertThat(expected, equalTo(actual));
- }
-
- private void verifyIntentReadIsWhatWasWrittenToParcel(Intent expected) {
- Parcel parcel = Parcel.obtain();
- expected.writeToParcel(parcel, 0);
- parcel.setDataPosition(0);
- Intent actual = new Intent();
- actual.readFromParcel(parcel);
-
- assertThat(expected, equalTo(actual));
- }
-
- private static class TestSerializable implements Serializable {
- private final String someValue;
-
- public TestSerializable(String someValue) {
- this.someValue = someValue;
- }
-
- @Override
- public boolean equals(Object o) {
- if (this == o) return true;
- if (o == null || getClass() != o.getClass()) return false;
-
- TestSerializable that = (TestSerializable) o;
-
- if (someValue != null ? !someValue.equals(that.someValue) : that.someValue != null) return false;
-
- return true;
- }
-
- @Override
- public int hashCode() {
- return someValue != null ? someValue.hashCode() : 0;
- }
- }
-
- private class TestCharSequence implements CharSequence {
- String s;
-
- public TestCharSequence(String s) {
- this.s = s;
- }
-
- @Override
- public char charAt(int index) {
- return s.charAt(index);
- }
-
- @Override
- public int length() {
- return s.length();
- }
-
- @Override
- public CharSequence subSequence(int start, int end) {
- return s.subSequence(start, end);
- }
-
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ItemizedOverlayTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/ItemizedOverlayTest.java
deleted file mode 100644
index 381942947..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ItemizedOverlayTest.java
+++ /dev/null
@@ -1,78 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import com.google.android.maps.GeoPoint;
-import com.google.android.maps.ItemizedOverlay;
-import com.google.android.maps.OverlayItem;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class ItemizedOverlayTest {
-
- class TestItemizedOverlay extends ItemizedOverlay<OverlayItem> {
- public OverlayItem firstOverlayItem = new OverlayItem(new GeoPoint(0, 0), "title1", "snippet1");
- public OverlayItem secondOverlayItem = new OverlayItem(new GeoPoint(5, 5), "title2", "snippet2");
-
- public TestItemizedOverlay() {
- super(null);
- }
-
- @Override
- protected OverlayItem createItem(int index) {
- if (index == 0) {
- return firstOverlayItem;
- } else if (index == 1) {
- return secondOverlayItem;
- }
- return null;
- }
-
- @Override
- public int size() {
- return 2;
- }
-
- public void callPopulate() {
- populate();
- }
- }
-
- @Test
- public void populateShouldCreateItems() {
- TestItemizedOverlay itemizedOverlay = new TestItemizedOverlay();
- itemizedOverlay.callPopulate();
-
- assertEquals(itemizedOverlay.firstOverlayItem, itemizedOverlay.getItem(0));
- assertEquals(itemizedOverlay.secondOverlayItem, itemizedOverlay.getItem(1));
- }
-
- @Test
- public void callingPopulateTwoTimesShouldNotAddAdditionalItems() {
- TestItemizedOverlay itemizedOverlay = new TestItemizedOverlay();
- itemizedOverlay.callPopulate();
- itemizedOverlay.callPopulate();
-
- assertEquals(itemizedOverlay.firstOverlayItem, itemizedOverlay.getItem(0));
- assertEquals(itemizedOverlay.secondOverlayItem, itemizedOverlay.getItem(1));
-
- boolean indexOutOfBoundsExceptionCatched = false;
- try {
- itemizedOverlay.getItem(2);
- } catch (IndexOutOfBoundsException e) {
- indexOutOfBoundsExceptionCatched = true;
- }
- assertTrue(indexOutOfBoundsExceptionCatched);
- }
-
- @Test(expected = IndexOutOfBoundsException.class)
- public void getItemWithoutPopulateShouldThrowIndexOutOfBoundException() {
- TestItemizedOverlay itemizedOverlay = new TestItemizedOverlay();
-
- assertNull(itemizedOverlay.getItem(0));
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/JsPromptResultTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/JsPromptResultTest.java
deleted file mode 100644
index e0d8fbc6c..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/JsPromptResultTest.java
+++ /dev/null
@@ -1,18 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.webkit.JsPromptResult;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static org.junit.Assert.assertNotNull;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class JsPromptResultTest {
-
- @Test
- public void shouldConstruct() throws Exception {
- JsPromptResult result = ShadowJsPromptResult.newInstance();
- assertNotNull(result);
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/JsResultTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/JsResultTest.java
deleted file mode 100644
index 561a18184..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/JsResultTest.java
+++ /dev/null
@@ -1,27 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.webkit.JsResult;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-import static junit.framework.Assert.assertTrue;
-import static org.junit.Assert.assertFalse;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class JsResultTest {
-
- @Test
- public void shouldRecordCanceled() throws Exception {
- JsResult jsResult = Robolectric.newInstanceOf(JsResult.class);
-
- assertFalse(shadowOf(jsResult).wasCancelled());
-
- jsResult.cancel();
- assertTrue(shadowOf(jsResult).wasCancelled());
-
- }
-
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/KeyguardManagerTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/KeyguardManagerTest.java
deleted file mode 100644
index 12a1ad12b..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/KeyguardManagerTest.java
+++ /dev/null
@@ -1,42 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.app.Activity;
-import android.app.KeyguardManager;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static android.content.Context.KEYGUARD_SERVICE;
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertThat;
-import static org.junit.Assert.assertTrue;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class KeyguardManagerTest {
-
- @Test
- public void testIsInRestrcitedInputMode() {
- Activity activity = new Activity();
- KeyguardManager mgr = ( KeyguardManager ) activity.getSystemService( KEYGUARD_SERVICE );
- assertThat( mgr.inKeyguardRestrictedInputMode(), equalTo( false ) );
- ShadowKeyguardManager shadowMgr = shadowOf(mgr);
- shadowMgr.setinRestrictedInputMode( true );
- assertThat( mgr.inKeyguardRestrictedInputMode(), equalTo( true ) );
- }
-
- @Test
- public void testShouldBeAbleToDisableTheKeyguardLock() throws Exception {
- Activity activity = new Activity();
- KeyguardManager mgr = ( KeyguardManager ) activity.getSystemService( KEYGUARD_SERVICE );
- KeyguardManager.KeyguardLock lock = mgr.newKeyguardLock(KEYGUARD_SERVICE);
- assertTrue(shadowOf(lock).isEnabled());
-
- lock.disableKeyguard();
- assertFalse(shadowOf(lock).isEnabled());
-
- lock.reenableKeyguard();
- assertTrue(shadowOf(lock).isEnabled());
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/LayerDrawableTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/LayerDrawableTest.java
deleted file mode 100644
index 38bb9ee04..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/LayerDrawableTest.java
+++ /dev/null
@@ -1,103 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.graphics.BitmapFactory;
-import android.graphics.drawable.BitmapDrawable;
-import android.graphics.drawable.Drawable;
-import android.graphics.drawable.LayerDrawable;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-import static org.junit.Assert.*;
-
-/**
- * ShadowLayerDrawableTest
- */
-@RunWith(WithTestDefaultsRunner.class)
-public class LayerDrawableTest {
- /**
- * drawables
- */
- protected Drawable drawable1000;
- protected Drawable drawable2000;
- protected Drawable drawable3000;
- protected Drawable drawable4000;
-
- /**
- * drawables
- */
- protected Drawable[] drawables;
-
- @Before
- public void setUp() {
- drawable1000 = new BitmapDrawable(BitmapFactory.decodeResource(
- Robolectric.application.getResources(), 0x00001000));
- drawable2000 = new BitmapDrawable(BitmapFactory.decodeResource(
- Robolectric.application.getResources(), 0x00002000));
- drawable3000 = new BitmapDrawable(BitmapFactory.decodeResource(
- Robolectric.application.getResources(), 0x00003000));
- drawable4000 = new BitmapDrawable(BitmapFactory.decodeResource(
- Robolectric.application.getResources(), 0x00004000));
-
- drawables = new Drawable[]{drawable1000, drawable2000, drawable3000};
- }
-
- @Test
- public void testConstruction() {
- LayerDrawable layerDrawable = new LayerDrawable(drawables);
- assertSame("drawables", drawables, shadowOf(layerDrawable).drawables);
- }
-
- @Test
- public void testGetNumberOfLayers() {
- LayerDrawable layerDrawable = new LayerDrawable(drawables);
- assertEquals("count", 3, layerDrawable.getNumberOfLayers());
- }
-
- @Test
- public void testSetDrawableByLayerId1() throws Exception {
- LayerDrawable layerDrawable = new LayerDrawable(drawables);
- int index = 1;
- int layerId = 345;
- layerDrawable.setId(index, layerId);
-
- layerDrawable.setDrawableByLayerId(layerId, drawable4000);
-
- assertEquals(shadowOf(drawable4000).getLoadedFromResourceId(),
- shadowOf(layerDrawable.getDrawable(index)).getLoadedFromResourceId());
- }
-
- @Test
- public void testSetDrawableByLayerId2() throws Exception {
- LayerDrawable layerDrawable = new LayerDrawable(drawables);
- int index = 0;
- int layerId = 345;
- layerDrawable.setId(index, layerId);
-
- layerDrawable.setDrawableByLayerId(layerId, drawable4000);
-
- assertEquals(shadowOf(drawable4000).getLoadedFromResourceId(),
- shadowOf(layerDrawable.getDrawable(index)).getLoadedFromResourceId());
- }
-
- @Test
- public void setDrawableByLayerId_shouldReturnFalseIfIdNotFound() throws Exception {
- LayerDrawable layerDrawable = new LayerDrawable(drawables);
- boolean ret = layerDrawable.setDrawableByLayerId(123, drawable4000);
- assertFalse(ret);
- }
-
- @Test
- public void setDrawableByLayerId_shouldReturnTrueIfIdWasFound() throws Exception {
- LayerDrawable layerDrawable = new LayerDrawable(drawables);
- int index = 0;
- int layerId = 345;
- layerDrawable.setId(index, layerId);
-
- boolean ret = layerDrawable.setDrawableByLayerId(layerId, drawable4000);
- assertTrue(ret);
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/LayoutInflaterTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/LayoutInflaterTest.java
deleted file mode 100644
index e870efa3c..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/LayoutInflaterTest.java
+++ /dev/null
@@ -1,29 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.content.ContextWrapper;
-import android.view.LayoutInflater;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertSame;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class LayoutInflaterTest {
- private LayoutInflater layoutInflater;
-
- @Before
- public void setUp() throws Exception {
- layoutInflater = LayoutInflater.from(Robolectric.application);
- }
-
- @Test
- public void getInstance_shouldReturnSameInstance() throws Exception {
- assertNotNull(layoutInflater);
- assertSame(LayoutInflater.from(Robolectric.application), layoutInflater);
- assertSame(LayoutInflater.from(new ContextWrapper(Robolectric.application)), layoutInflater);
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/LayoutParamsTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/LayoutParamsTest.java
deleted file mode 100644
index b78ecb89e..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/LayoutParamsTest.java
+++ /dev/null
@@ -1,19 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.widget.Gallery;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.junit.Assert.assertThat;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class LayoutParamsTest {
- @Test
- public void testConstructor() throws Exception {
- Gallery.LayoutParams layoutParams = new Gallery.LayoutParams(123, 456);
- assertThat(layoutParams.width, equalTo(123));
- assertThat(layoutParams.height, equalTo(456));
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/LinearLayoutTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/LinearLayoutTest.java
deleted file mode 100644
index ac4227eeb..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/LinearLayoutTest.java
+++ /dev/null
@@ -1,31 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.view.ViewGroup;
-import android.widget.LinearLayout;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static org.hamcrest.CoreMatchers.instanceOf;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.junit.Assert.assertTrue;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class LinearLayoutTest {
- @Test
- public void getLayoutParams_shouldReturnLinearLayoutParams() throws Exception {
- ViewGroup.LayoutParams layoutParams = new LinearLayout(null).getLayoutParams();
-
- assertThat(layoutParams, instanceOf(LinearLayout.LayoutParams.class));
- }
-
- @Test
- public void getLayoutParams_shouldReturnTheSameLinearLayoutParamsFromTheSetter() throws Exception {
- LinearLayout linearLayout = new LinearLayout(null);
- LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(1, 2);
-
- linearLayout.setLayoutParams(params);
-
- assertTrue(linearLayout.getLayoutParams() == params);
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/LinkMovementMethodTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/LinkMovementMethodTest.java
deleted file mode 100644
index 07dbeb3ca..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/LinkMovementMethodTest.java
+++ /dev/null
@@ -1,19 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.text.method.LinkMovementMethod;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static org.hamcrest.CoreMatchers.instanceOf;
-import static org.junit.Assert.assertThat;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class LinkMovementMethodTest {
-
- @Test
- public void getInstance_shouldReturnAnInstanceOf_LinkedMovementMethod() throws Exception {
- assertThat(LinkMovementMethod.getInstance(), instanceOf(LinkMovementMethod.class));
- }
-
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ListActivityTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/ListActivityTest.java
deleted file mode 100644
index fa0b28690..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ListActivityTest.java
+++ /dev/null
@@ -1,54 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.app.ListActivity;
-import android.view.View;
-import android.widget.ListAdapter;
-import android.widget.ListView;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static junit.framework.Assert.assertTrue;
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.CoreMatchers.notNullValue;
-import static org.hamcrest.CoreMatchers.sameInstance;
-import static org.hamcrest.MatcherAssert.assertThat;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class ListActivityTest {
-
- @Test
- public void shouldSupportSettingAndGettingListAdapter(){
- ListActivity listActivity = new ListActivity();
- ListAdapter adapter = new CountingAdapter(5);
- listActivity.setListAdapter(adapter);
-
- assertThat(listActivity.getListAdapter(), is(notNullValue()));
- }
-
- @Test
- public void shouldSupportOnItemClick() throws Exception {
- final boolean[] clicked = new boolean[1];
- ListActivity listActivity = new ListActivity() {
- @Override
- protected void onListItemClick(ListView l, View v, int position, long id) {
- clicked[0] = true;
- }
- };
- listActivity.setContentView(new ListView(null));
- listActivity.setListAdapter(new CountingAdapter(5));
- Robolectric.shadowOf(listActivity.getListView()).performItemClick(0);
- assertTrue(clicked[0]);
- }
-
- @Test
- public void shouldSetAdapterOnListView() throws Exception {
- ListActivity listActivity = new ListActivity();
- ListAdapter adapter = new CountingAdapter(5);
- final ListView listView = new ListView(null);
- listActivity.setContentView(listView);
- listActivity.setListAdapter(adapter);
- assertThat(listView.getAdapter(), sameInstance(adapter));
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ListFragmentTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/ListFragmentTest.java
deleted file mode 100644
index 1295654b7..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ListFragmentTest.java
+++ /dev/null
@@ -1,30 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.support.v4.app.ListFragment;
-import android.view.View;
-import android.widget.ListAdapter;
-import android.widget.ListView;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static junit.framework.Assert.assertTrue;
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.CoreMatchers.notNullValue;
-import static org.hamcrest.CoreMatchers.sameInstance;
-import static org.hamcrest.MatcherAssert.assertThat;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class ListFragmentTest {
-
- @Test
- public void shouldSupportSettingAndGettingListAdapter(){
- ListFragment listFragment = new ListFragment();
- Robolectric.shadowOf(listFragment).setView(new ListView(null));
- ListAdapter adapter = new CountingAdapter(5);
- listFragment.setListAdapter(adapter);
-
- assertThat(listFragment.getListAdapter(), is(notNullValue()));
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ListPreferenceTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/ListPreferenceTest.java
deleted file mode 100644
index 1b9212b75..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ListPreferenceTest.java
+++ /dev/null
@@ -1,74 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.app.Activity;
-import android.preference.ListPreference;
-import com.xtremelabs.robolectric.R;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.CoreMatchers.instanceOf;
-import static org.hamcrest.CoreMatchers.notNullValue;
-import static org.hamcrest.CoreMatchers.nullValue;
-import static org.hamcrest.CoreMatchers.sameInstance;
-import static org.junit.Assert.assertThat;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class ListPreferenceTest {
-
- private ListPreference listPreference;
- private ShadowListPreference shadow;
-
- @Before
- public void setUp() throws Exception {
- listPreference = new ListPreference(new Activity());
- shadow = Robolectric.shadowOf(listPreference);
- }
-
- @Test
- public void shouldInheritFromDialogPreference() {
- assertThat(shadow, instanceOf(ShadowDialogPreference.class));
- }
-
- @Test
- public void shouldHaveEntries() {
- CharSequence[] entries = { "this", "is", "only", "a", "test" };
-
- assertThat(listPreference.getEntries(), nullValue());
- listPreference.setEntries(entries);
- assertThat(listPreference.getEntries(), sameInstance(entries));
- }
-
- @Test
- public void shouldSetEntriesByResourceId() {
- assertThat(listPreference.getEntries(), nullValue());
- listPreference.setEntries(R.array.greetings);
- assertThat(listPreference.getEntries(), notNullValue());
- }
-
- @Test
- public void shouldHaveEntryValues() {
- CharSequence[] entryValues = { "this", "is", "only", "a", "test" };
-
- assertThat(listPreference.getEntryValues(), nullValue());
- listPreference.setEntryValues(entryValues);
- assertThat(listPreference.getEntryValues(), sameInstance(entryValues));
- }
-
- @Test
- public void shouldSetEntryValuesByResourceId() {
- assertThat(listPreference.getEntryValues(), nullValue());
- listPreference.setEntryValues(R.array.greetings);
- assertThat(listPreference.getEntryValues(), notNullValue());
- }
-
- @Test
- public void shouldSetValue() {
- assertThat(listPreference.getValue(), nullValue());
- listPreference.setValue("testing");
- assertThat(listPreference.getValue(), equalTo("testing"));
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ListViewTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/ListViewTest.java
deleted file mode 100644
index e743a34b1..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ListViewTest.java
+++ /dev/null
@@ -1,576 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-import static java.util.Arrays.asList;
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.CoreMatchers.notNullValue;
-import static org.hamcrest.CoreMatchers.nullValue;
-import static org.hamcrest.CoreMatchers.sameInstance;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertThat;
-import static org.junit.Assert.fail;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-import java.util.Random;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import android.util.SparseBooleanArray;
-import android.view.View;
-import android.view.ViewGroup;
-import android.widget.AdapterView;
-import android.widget.ArrayAdapter;
-import android.widget.BaseAdapter;
-import android.widget.LinearLayout;
-import android.widget.ListView;
-
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import com.xtremelabs.robolectric.util.Transcript;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class ListViewTest {
-
- private Transcript transcript;
- private ListView listView;
- private int checkedItemPosition;
- private SparseBooleanArray checkedItemPositions;
- private int lastCheckedPosition;
-
- @Before
- public void setUp() throws Exception {
- transcript = new Transcript();
- listView = new ListView(null);
- }
-
- @Test
- public void testSetSelection_ShouldFireOnItemSelectedListener() throws Exception {
- listView.setAdapter(new CountingAdapter(1));
- ShadowHandler.idleMainLooper();
-
- listView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
- @Override
- public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
- transcript.add("item was selected: " + position);
- }
-
- @Override
- public void onNothingSelected(AdapterView<?> parent) {
- }
- });
-
- listView.setSelection(0);
- ShadowHandler.idleMainLooper();
- transcript.assertEventsSoFar("item was selected: 0");
- }
-
- @Test
- public void addHeaderView_ShouldThrowIfAdapterIsAlreadySet() throws Exception {
- listView.setAdapter(new CountingAdapter(1));
- try {
- listView.addHeaderView(new View(null));
- fail();
- } catch (java.lang.IllegalStateException exception) {
- assertThat(exception.getMessage(), equalTo("Cannot add header view to list -- setAdapter has already been called"));
- }
-
- try {
- listView.addHeaderView(new View(null), null, false);
- fail();
- } catch (java.lang.IllegalStateException exception) {
- assertThat(exception.getMessage(), equalTo("Cannot add header view to list -- setAdapter has already been called"));
- }
- }
-
- @Test
- public void addHeaderView_ShouldRecordHeaders() throws Exception {
- View view0 = new View(null);
- view0.setId(0);
- View view1 = new View(null);
- view1.setId(1);
- View view2 = new View(null);
- view2.setId(2);
- View view3 = new View(null);
- view3.setId(3);
- listView.addHeaderView(view0);
- listView.addHeaderView(view1);
- listView.addHeaderView(view2, null, false);
- listView.addHeaderView(view3, null, false);
- assertThat(listView.getHeaderViewsCount(), equalTo(4));
- assertThat(shadowOf(listView).getHeaderViews().get(0), sameInstance(view0));
- assertThat(shadowOf(listView).getHeaderViews().get(1), sameInstance(view1));
- assertThat(shadowOf(listView).getHeaderViews().get(2), sameInstance(view2));
- assertThat(shadowOf(listView).getHeaderViews().get(3), sameInstance(view3));
-
- assertThat(listView.findViewById(0), notNullValue());
- assertThat(listView.findViewById(1), notNullValue());
- assertThat(listView.findViewById(2), notNullValue());
- assertThat(listView.findViewById(3), notNullValue());
- }
-
- @Test
- public void addHeaderView_shouldAttachTheViewToTheList() throws Exception {
- View view = new View(null);
- view.setId(42);
-
- listView.addHeaderView(view);
-
- assertThat(listView.findViewById(42), is(view));
- }
-
- @Test
- public void addFooterView_ShouldThrowIfAdapterIsAlreadySet() throws Exception {
- listView.setAdapter(new CountingAdapter(1));
- try {
- listView.addFooterView(new View(null));
- fail();
- } catch (java.lang.IllegalStateException exception) {
- assertThat(exception.getMessage(), equalTo("Cannot add footer view to list -- setAdapter has already been called"));
-
- }
- }
-
- @Test
- public void addFooterView_ShouldRecordFooters() throws Exception {
- View view0 = new View(null);
- View view1 = new View(null);
- listView.addFooterView(view0);
- listView.addFooterView(view1);
- assertThat(shadowOf(listView).getFooterViews().get(0), sameInstance(view0));
- assertThat(shadowOf(listView).getFooterViews().get(1), sameInstance(view1));
- }
-
- @Test
- public void addFooterView_shouldAttachTheViewToTheList() throws Exception {
- View view = new View(null);
- view.setId(42);
-
- listView.addFooterView(view);
-
- assertThat(listView.findViewById(42), is(view));
- }
-
- @Test
- public void setAdapter_shouldNotClearHeaderOrFooterViews() throws Exception {
- View header = new View(null);
- listView.addHeaderView(header);
- View footer = new View(null);
- listView.addFooterView(footer);
-
- prepareListWithThreeItems();
-
- assertThat(listView.getChildCount(), equalTo(5));
- assertThat(listView.getChildAt(0), is(header));
- assertThat(listView.getChildAt(4), is(footer));
- }
-
- @Test
- public void testGetFooterViewsCount() throws Exception {
- listView.addHeaderView(new View(null));
- listView.addFooterView(new View(null));
- listView.addFooterView(new View(null));
-
- prepareListWithThreeItems();
-
- assertThat(listView.getFooterViewsCount(), equalTo(2));
- }
-
- @Test
- public void smoothScrollBy_shouldBeRecorded() throws Exception {
- listView.smoothScrollBy(42, 420);
- assertThat(shadowOf(listView).getLastSmoothScrollByDistance(), equalTo(42));
- assertThat(shadowOf(listView).getLastSmoothScrollByDuration(), equalTo(420));
- }
-
- @Test
- public void testPerformItemClick_ShouldFireOnItemClickListener() throws Exception {
- listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
- @Override
- public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
- transcript.add("item was clicked: " + position);
- }
- });
-
- listView.performItemClick(null, 0, -1);
- transcript.assertEventsSoFar("item was clicked: 0");
- }
-
- @Test
- public void testSetSelection_WhenNoItemSelectedListenerIsSet_ShouldDoNothing() throws Exception {
- listView.setSelection(0);
- }
-
- @Test
- public void shouldHaveAdapterViewCommonBehavior() throws Exception {
- AdapterViewBehavior.shouldActAsAdapterView(listView);
- }
-
- @Test
- public void findItemContainingText_shouldFindChildByString() throws Exception {
- ShadowListView shadowListView = prepareListWithThreeItems();
- View item1 = shadowListView.findItemContainingText("Item 1");
- assertThat(item1, sameInstance(listView.getChildAt(1)));
- }
-
- @Test
- public void findItemContainingText_shouldReturnNullIfNotFound() throws Exception {
- ShadowListView shadowListView = prepareListWithThreeItems();
- assertThat(shadowListView.findItemContainingText("Non-existant item"), nullValue());
- }
-
- @Test
- public void clickItemContainingText_shouldPerformItemClickOnList() throws Exception {
- ShadowListView shadowListView = prepareListWithThreeItems();
- listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
- @Override
- public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
- transcript.add("clicked on item " + position);
- }
- });
- shadowListView.clickFirstItemContainingText("Item 1");
- transcript.assertEventsSoFar("clicked on item 1");
- }
-
- @Test
- public void clickItemContainingText_shouldPerformItemClickOnList_arrayAdapter() throws Exception {
- ArrayList<String> adapterFileList = new ArrayList<String>();
- adapterFileList.add("Item 1");
- adapterFileList.add("Item 2");
- adapterFileList.add("Item 3");
- final ArrayAdapter<String> adapter = new ArrayAdapter<String>(null, android.R.layout.simple_list_item_1, adapterFileList);
- listView.setAdapter(adapter);
- ShadowHandler.idleMainLooper();
- ShadowListView shadowListView = shadowOf(listView);
- listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
- @Override
- public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
- transcript.add("clicked on item " + adapter.getItem(position));
- }
- });
- shadowListView.clickFirstItemContainingText("Item 3");
- transcript.assertEventsSoFar("clicked on item Item 3");
- }
-
- @Test(expected = IllegalArgumentException.class)
- public void clickItemContainingText_shouldThrowExceptionIfNotFound() throws Exception {
- ShadowListView shadowListView = prepareListWithThreeItems();
- shadowListView.clickFirstItemContainingText("Non-existant item");
- }
-
- @Test
- public void revalidate_whenItemsHaveNotChanged_shouldWork() throws Exception {
- prepareWithListAdapter();
- shadowOf(listView).checkValidity();
- }
-
- @Test(expected = ArrayIndexOutOfBoundsException.class)
- public void revalidate_removingAnItemWithoutInvalidating_shouldExplode() throws Exception {
- ListAdapter adapter = prepareWithListAdapter();
- adapter.items.remove(0);
- shadowOf(listView).checkValidity(); // should 'splode!
- }
-
- @Test(expected = ArrayIndexOutOfBoundsException.class)
- public void revalidate_addingAnItemWithoutInvalidating_shouldExplode() throws Exception {
- ListAdapter adapter = prepareWithListAdapter();
- adapter.items.add("x");
- shadowOf(listView).checkValidity(); // should 'splode!
- }
-
- @Test(expected = RuntimeException.class)
- public void revalidate_changingAnItemWithoutInvalidating_shouldExplode() throws Exception {
- ListAdapter adapter = prepareWithListAdapter();
- adapter.items.remove(2);
- adapter.items.add("x");
- shadowOf(listView).checkValidity(); // should 'splode!
- }
-
- @Test
- public void testShouldBeAbleToTurnOffAutomaticRowUpdates() throws Exception {
- try {
- TranscriptAdapter adapter1 = new TranscriptAdapter();
- assertThat(adapter1.getCount(), equalTo(1));
- listView.setAdapter(adapter1);
- transcript.assertEventsSoFar("called getView");
- transcript.clear();
- adapter1.notifyDataSetChanged();
- transcript.assertEventsSoFar("called getView");
-
- transcript.clear();
- ShadowAdapterView.automaticallyUpdateRowViews(false);
-
- TranscriptAdapter adapter2 = new TranscriptAdapter();
- assertThat(adapter2.getCount(), equalTo(1));
- listView.setAdapter(adapter2);
- adapter2.notifyDataSetChanged();
- transcript.assertNoEventsSoFar();
-
- } finally {
- ShadowAdapterView.automaticallyUpdateRowViews(true);
- }
- }
-
- @Test(expected = UnsupportedOperationException.class)
- public void removeAllViews_shouldThrowAnException() throws Exception {
- listView.removeAllViews();
- }
-
- @Test(expected = UnsupportedOperationException.class)
- public void removeView_shouldThrowAnException() throws Exception {
- listView.removeView(new View(null));
- }
-
- @Test(expected = UnsupportedOperationException.class)
- public void removeViewAt_shouldThrowAnException() throws Exception {
- listView.removeViewAt(0);
- }
-
- @Test
- public void getPositionForView_shouldReturnThePositionInTheListForTheView() throws Exception {
- prepareWithListAdapter();
- View childViewOfListItem = ((ViewGroup) listView.getChildAt(1)).getChildAt(0);
- assertThat(listView.getPositionForView(childViewOfListItem), equalTo(1));
- }
-
- @Test
- public void getPositionForView_shouldReturnInvalidPostionForViewThatIsNotFound() throws Exception {
- prepareWithListAdapter();
- assertThat(listView.getPositionForView(new View(null)), equalTo(AdapterView.INVALID_POSITION));
- }
-
- @Test
- public void revalidate_withALazyAdapterShouldWork() {
- ListAdapter lazyAdapter = new ListAdapter() {
- List<String> lazyItems = Arrays.asList("a", "b", "c");
-
- @Override
- public View getView(int position, View convertView, ViewGroup parent) {
- if (items.isEmpty()) items.addAll(lazyItems);
- return super.getView(position, convertView, parent);
- }
-
- @Override
- public int getCount() {
- return lazyItems.size();
- }
- };
- listView.setAdapter(lazyAdapter);
- ShadowHandler.idleMainLooper();
- shadowOf(listView).checkValidity();
- }
-
- @Test
- public void shouldRecordLatestCallToSmoothScrollToPostion() throws Exception {
- listView.smoothScrollToPosition(10);
- assertThat(shadowOf(listView).getSmoothScrolledPosition(), equalTo(10));
- }
-
- @Test
- public void givenChoiceModeIsSingle_whenGettingCheckedItemPosition_thenReturnPosition() {
- prepareListAdapter().withChoiceMode(ListView.CHOICE_MODE_SINGLE).withAnyItemChecked();
-
- assertThat(listView.getCheckedItemPosition(), is(checkedItemPosition));
- }
-
- @Test
- public void givenChoiceModeIsMultiple_whenGettingCheckedItemPosition_thenReturnInvalidPosition() {
- prepareListAdapter().withChoiceMode(ListView.CHOICE_MODE_MULTIPLE).withAnyItemChecked();
-
- assertThat(listView.getCheckedItemPosition(), is(ListView.INVALID_POSITION));
- }
-
- @Test
- public void givenChoiceModeIsNone_whenGettingCheckedItemPosition_thenReturnInvalidPosition() {
- prepareListAdapter().withChoiceMode(ListView.CHOICE_MODE_NONE);
-
- assertThat(listView.getCheckedItemPosition(), is(ListView.INVALID_POSITION));
- }
-
- @Test
- public void givenNoItemsChecked_whenGettingCheckedItemOisition_thenReturnInvalidPosition() {
- prepareListAdapter().withChoiceMode(ListView.CHOICE_MODE_SINGLE);
-
- assertThat(listView.getCheckedItemPosition(), is(ListView.INVALID_POSITION));
- }
-
- @Test
- public void givenChoiceModeIsSingleAndAnItemIsChecked_whenSettingChoiceModeToNone_thenGetCheckedItemPositionShouldReturnInvalidPosition() {
- prepareListAdapter().withChoiceMode(ListView.CHOICE_MODE_SINGLE).withAnyItemChecked();
-
- listView.setChoiceMode(ListView.CHOICE_MODE_NONE);
-
- assertThat(listView.getCheckedItemPosition(), is(ListView.INVALID_POSITION));
- }
-
- @Test
- public void givenChoiceModeIsMultipleAndMultipleItemsAreChecked_whenGettingCheckedItemPositions_thenReturnCheckedPositions() {
- prepareListAdapter().withChoiceMode(ListView.CHOICE_MODE_MULTIPLE).withAnyItemsChecked();
-
- assertThat(listView.getCheckedItemPositions(), equalTo(checkedItemPositions));
- }
-
- @Test
- public void givenChoiceModeIsSingleAndMultipleItemsAreChecked_whenGettingCheckedItemPositions_thenReturnOnlyTheLastCheckedPosition() {
- prepareListAdapter().withChoiceMode(ListView.CHOICE_MODE_SINGLE).withAnyItemsChecked();
- SparseBooleanArray expectedCheckedItemPositions = new SparseBooleanArray();
- expectedCheckedItemPositions.put(lastCheckedPosition, true);
-
- assertThat(listView.getCheckedItemPositions(), equalTo(expectedCheckedItemPositions));
- }
-
- @Test
- public void givenChoiceModeIsNoneAndMultipleItemsAreChecked_whenGettingCheckedItemPositions_thenReturnNull() {
- prepareListAdapter().withChoiceMode(ListView.CHOICE_MODE_NONE).withAnyItemsChecked();
-
- assertNull(listView.getCheckedItemPositions());
- }
-
- @Test
- public void givenItemIsNotCheckedAndChoiceModeIsSingle_whenPerformingItemClick_thenItemShouldBeChecked() {
- prepareListAdapter().withChoiceMode(ListView.CHOICE_MODE_SINGLE);
- int positionToClick = anyListIndex();
-
- listView.performItemClick(null, positionToClick, 0);
-
- assertThat(listView.getCheckedItemPosition(), equalTo(positionToClick));
- }
-
- @Test
- public void givenItemIsCheckedAndChoiceModeIsSingle_whenPerformingItemClick_thenItemShouldBeChecked() {
- prepareListAdapter().withChoiceMode(ListView.CHOICE_MODE_SINGLE).withAnyItemChecked();
-
- listView.performItemClick(null, checkedItemPosition, 0);
-
- assertThat(listView.getCheckedItemPosition(), equalTo(checkedItemPosition));
- }
-
- @Test
- public void givenItemIsNotCheckedAndChoiceModeIsMultiple_whenPerformingItemClick_thenItemShouldBeChecked() {
- prepareListAdapter().withChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
- int positionToClick = anyListIndex();
- SparseBooleanArray expectedCheckedItemPositions = new SparseBooleanArray();
- expectedCheckedItemPositions.put(positionToClick, true);
-
- listView.performItemClick(null, positionToClick, 0);
-
- assertThat(listView.getCheckedItemPositions(), equalTo(expectedCheckedItemPositions));
- }
-
- @Test
- public void givenItemIsCheckedAndChoiceModeIsMultiple_whenPerformingItemClick_thenItemShouldNotBeChecked() {
- prepareListAdapter().withChoiceMode(ListView.CHOICE_MODE_MULTIPLE).withAnyItemChecked();
-
- listView.performItemClick(null, checkedItemPosition, 0);
-
- assertFalse(listView.getCheckedItemPositions().get(checkedItemPosition));
- }
-
- private ListAdapterBuilder prepareListAdapter() {
- return new ListAdapterBuilder();
- }
-
- private ListAdapter prepareWithListAdapter() {
- ListAdapter adapter = new ListAdapter("a", "b", "c");
- listView.setAdapter(adapter);
- ShadowHandler.idleMainLooper();
- return adapter;
- }
-
- private ShadowListView prepareListWithThreeItems() {
- listView.setAdapter(new CountingAdapter(3));
- ShadowHandler.idleMainLooper();
-
- return shadowOf(listView);
- }
-
- private int anyListIndex() {
- return new Random().nextInt(3);
- }
-
- private static class ListAdapter extends BaseAdapter {
- public List<String> items = new ArrayList<String>();
-
- public ListAdapter(String... items) {
- this.items.addAll(asList(items));
- }
-
- @Override
- public int getCount() {
- return items.size();
- }
-
- @Override
- public Object getItem(int position) {
- return items.get(position);
- }
-
- @Override
- public long getItemId(int position) {
- return 0;
- }
-
- @Override
- public View getView(int position, View convertView, ViewGroup parent) {
- LinearLayout linearLayout = new LinearLayout(null);
- linearLayout.addView(new View(null));
- return linearLayout;
- }
- }
-
- public class ListAdapterBuilder {
-
- public ListAdapterBuilder() {
- prepareListWithThreeItems();
- }
-
- public ListAdapterBuilder withChoiceMode(int choiceMode) {
- listView.setChoiceMode(choiceMode);
- return this;
- }
-
- public ListAdapterBuilder withAnyItemChecked() {
- checkedItemPosition = anyListIndex();
- listView.setItemChecked(checkedItemPosition, true);
- return this;
- }
-
- public void withAnyItemsChecked() {
- checkedItemPositions = new SparseBooleanArray();
- int numberOfSelections = anyListIndex() + 1;
- for (int i = 0; i < numberOfSelections; i++) {
- checkedItemPositions.put(i, true);
- listView.setItemChecked(i, true);
- lastCheckedPosition = i;
- }
-
- }
- }
-
- private class TranscriptAdapter extends BaseAdapter {
- @Override
- public int getCount() {
- return 1;
- }
-
- @Override
- public Object getItem(int position) {
- return null;
- }
-
- @Override
- public long getItemId(int position) {
- return position;
- }
-
- @Override
- public View getView(int position, View convertView, ViewGroup parent) {
- transcript.add("called getView");
- return new View(parent.getContext());
- }
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/LocalBroadcastManagerTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/LocalBroadcastManagerTest.java
deleted file mode 100644
index 730b2fa1f..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/LocalBroadcastManagerTest.java
+++ /dev/null
@@ -1,75 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.content.BroadcastReceiver;
-import android.content.Context;
-import android.content.Intent;
-import android.content.IntentFilter;
-import android.support.v4.content.LocalBroadcastManager;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static junit.framework.Assert.*;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class LocalBroadcastManagerTest {
- private static LocalBroadcastManager lastInstance;
-
- @Test
- public void shouldGetInstance() throws Exception {
- LocalBroadcastManager instance = LocalBroadcastManager.getInstance(Robolectric.application);
- assertNotNull(instance);
- assertSame(instance, LocalBroadcastManager.getInstance(Robolectric.application));
- }
-
- @Test
- public void shouldSendBroadcasts() throws Exception {
- LocalBroadcastManager instance = LocalBroadcastManager.getInstance(Robolectric.application);
- final boolean[] called = new boolean[1];
- final BroadcastReceiver receiver = new BroadcastReceiver() {
- @Override
- public void onReceive(Context context, Intent intent) {
- called[0] = true;
-
- }
- };
- instance.registerReceiver(receiver, new IntentFilter("com.foo"));
-
- instance.sendBroadcast(new Intent("com.bar"));
- assertFalse(called[0]);
- instance.sendBroadcast(new Intent("com.foo"));
- assertTrue(called[0]);
- }
-
- @Test
- public void shouldUnregisterReceiver() throws Exception {
-
- LocalBroadcastManager instance = LocalBroadcastManager.getInstance(Robolectric.application);
- final boolean[] called = new boolean[1];
- final BroadcastReceiver receiver = new BroadcastReceiver() {
- @Override
- public void onReceive(Context context, Intent intent) {
- called[0] = true;
-
- }
- };
- instance.registerReceiver(receiver, new IntentFilter("com.foo"));
- instance.unregisterReceiver(receiver);
- instance.sendBroadcast(new Intent("com.foo"));
- assertFalse(called[0]);
- }
-
- @Test
- public void shouldResetStateBetweenTests1() throws Exception {
- lastInstance = LocalBroadcastManager.getInstance(Robolectric.application);
- assertNotNull(lastInstance);
- }
-
- @Test
- public void shouldResetStateBetweenTests2() throws Exception {
- assertNotNull(lastInstance);
- assertNotSame(lastInstance, LocalBroadcastManager.getInstance(Robolectric.application));
- lastInstance = null;
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/LocationManagerTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/LocationManagerTest.java
deleted file mode 100644
index fd96f140c..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/LocationManagerTest.java
+++ /dev/null
@@ -1,423 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.app.PendingIntent;
-import android.content.Context;
-import android.content.Intent;
-import android.location.Criteria;
-import android.location.GpsStatus.Listener;
-import android.location.Location;
-import android.location.LocationListener;
-import android.location.LocationManager;
-import android.os.Bundle;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import junit.framework.Assert;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import java.util.*;
-
-import static android.location.LocationManager.GPS_PROVIDER;
-import static android.location.LocationManager.NETWORK_PROVIDER;
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-import static junit.framework.Assert.*;
-import static org.hamcrest.core.IsEqual.equalTo;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertThat;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class LocationManagerTest {
- private LocationManager locationManager;
- private ShadowLocationManager shadowLocationManager;
-
- @Before
- public void setUp() {
- locationManager = (LocationManager) Robolectric.application.getSystemService(Context.LOCATION_SERVICE);
- shadowLocationManager = shadowOf(locationManager);
- }
-
- @Test
- public void shouldReturnNoProviderEnabledByDefault() {
- Boolean enabled = locationManager.isProviderEnabled(GPS_PROVIDER);
- assertFalse(enabled);
- enabled = locationManager.isProviderEnabled(NETWORK_PROVIDER);
- assertFalse(enabled);
- enabled = locationManager.isProviderEnabled("RANDOM_PROVIDER");
- assertFalse(enabled);
- }
-
- @Test
- public void shouldDisableProvider() {
- // No provider is enabled by default, so it must be manually enabled
- shadowLocationManager.setProviderEnabled(GPS_PROVIDER, true);
- shadowLocationManager.setProviderEnabled(GPS_PROVIDER, false);
- assertFalse(locationManager.isProviderEnabled(GPS_PROVIDER));
- }
-
- @Test
- public void shouldHaveListenerOnceAdded() {
- Listener listener = addGpsListenerToLocationManager();
- assertTrue(shadowLocationManager.hasGpsStatusListener(listener));
- }
-
- @Test
- public void shouldNotHaveListenerOnceRemoved() {
- Listener listener = addGpsListenerToLocationManager();
-
- locationManager.removeGpsStatusListener(listener);
-
- assertFalse(shadowLocationManager.hasGpsStatusListener(listener));
- }
-
- @Test
- public void shouldReturnEnabledProviders() throws Exception {
- shadowLocationManager.setProviderEnabled(NETWORK_PROVIDER, false);
- shadowLocationManager.setProviderEnabled(GPS_PROVIDER, false);
- shadowLocationManager.setProviderEnabled(LocationManager.PASSIVE_PROVIDER, false);
-
- assertTrue(locationManager.getProviders(true).isEmpty());
- assertThat(locationManager.getProviders(false).size(), equalTo(3));
-
- shadowLocationManager.setProviderEnabled(NETWORK_PROVIDER, true);
-
- List<String> providers = locationManager.getProviders(true);
- assertTrue(providers.contains(NETWORK_PROVIDER));
- assertThat(providers.size(), equalTo(1));
-
- shadowLocationManager.setProviderEnabled(GPS_PROVIDER, true);
- providers = locationManager.getProviders(true);
- assertTrue(providers.contains(NETWORK_PROVIDER));
- assertTrue(providers.contains(GPS_PROVIDER));
- assertThat(providers.size(), equalTo(2));
-
- shadowLocationManager.setProviderEnabled(LocationManager.PASSIVE_PROVIDER, true);
- providers = locationManager.getProviders(true);
- assertTrue(providers.contains(NETWORK_PROVIDER));
- assertTrue(providers.contains(GPS_PROVIDER));
- assertTrue(providers.contains(LocationManager.PASSIVE_PROVIDER));
- assertThat(providers.size(), equalTo(3));
- }
-
- @Test
- public void shouldReturnAllProviders() throws Exception {
- assertThat(locationManager.getAllProviders().size(), equalTo(3));
-
- shadowLocationManager.setProviderEnabled("MY_PROVIDER", false);
- assertThat(locationManager.getAllProviders().size(), equalTo(4));
- }
-
- @Test
- public void shouldReturnLastKnownLocationForAProvider() throws Exception {
- assertNull(locationManager.getLastKnownLocation(NETWORK_PROVIDER));
-
- Location networkLocation = new Location(NETWORK_PROVIDER);
- Location gpsLocation = new Location(GPS_PROVIDER);
-
- shadowLocationManager.setLastKnownLocation(NETWORK_PROVIDER, networkLocation);
- shadowLocationManager.setLastKnownLocation(GPS_PROVIDER, gpsLocation);
-
- assertSame(locationManager.getLastKnownLocation(NETWORK_PROVIDER), networkLocation);
- assertSame(locationManager.getLastKnownLocation(GPS_PROVIDER), gpsLocation);
- }
-
- @Test
- public void shouldStoreRequestLocationUpdateListeners() throws Exception {
- TestLocationListener listener = new TestLocationListener();
- locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1, 2.0f, listener);
- assertSame(shadowLocationManager.getRequestLocationUpdateListeners().get(0), listener);
- }
-
- @Test
- public void shouldKeepTrackOfWhichProvidersAListenerIsBoundTo_withoutDuplicates_inAnyOrder() throws Exception {
- TestLocationListener listener1 = new TestLocationListener();
- TestLocationListener listener2 = new TestLocationListener();
-
- locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1, 1, listener1);
- locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1, 1, listener1);
-
- Set<String> listOfExpectedProvidersForListener1 = new HashSet<String>();
- listOfExpectedProvidersForListener1.add(LocationManager.NETWORK_PROVIDER);
- listOfExpectedProvidersForListener1.add(LocationManager.GPS_PROVIDER);
-
- locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1, 1, listener2);
- locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1, 1, listener2);
-
- Set<String> listOfExpectedProvidersForListener2 = new HashSet<String>();
- listOfExpectedProvidersForListener2.add(LocationManager.NETWORK_PROVIDER);
-
- assertEquals(listOfExpectedProvidersForListener1, new HashSet<String>(shadowLocationManager.getProvidersForListener(listener1)));
- assertEquals(listOfExpectedProvidersForListener2, new HashSet<String>(shadowLocationManager.getProvidersForListener(listener2)));
-
- locationManager.removeUpdates(listener1);
- assertEquals(0, shadowLocationManager.getProvidersForListener(listener1).size());
- }
-
- @Test
- public void shouldRemoveLocationListeners() throws Exception {
- TestLocationListener listener = new TestLocationListener();
- locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1, 2.0f, listener);
- locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1, 2.0f, listener);
-
- TestLocationListener otherListener = new TestLocationListener();
- locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1, 2.0f, otherListener);
-
- locationManager.removeUpdates(listener);
-
- List<LocationListener> expected = new ArrayList<LocationListener>();
- expected.add(otherListener);
- assertThat(shadowLocationManager.getRequestLocationUpdateListeners(), equalTo(expected));
- }
-
- @Test
- public void shouldRemovePendingIntentsWhenRequestingLocationUpdatesUsingCriteria() throws Exception {
- Intent someIntent = new Intent("some_action");
- PendingIntent someLocationListenerPendingIntent = PendingIntent.getBroadcast(Robolectric
- .getShadowApplication().getApplicationContext(), 0, someIntent,
- PendingIntent.FLAG_UPDATE_CURRENT);
- Intent someOtherIntent = new Intent("some_other_action");
- PendingIntent someOtherLocationListenerPendingIntent = PendingIntent.getBroadcast(
- Robolectric.getShadowApplication().getApplicationContext(), 0, someOtherIntent,
- PendingIntent.FLAG_UPDATE_CURRENT);
-
- shadowLocationManager.setProviderEnabled(GPS_PROVIDER, true);
- shadowLocationManager.setBestProvider(LocationManager.GPS_PROVIDER, true);
- Criteria criteria = new Criteria();
- criteria.setAccuracy(Criteria.ACCURACY_FINE);
-
- locationManager.requestLocationUpdates(0, 0, criteria, someLocationListenerPendingIntent);
- locationManager.requestLocationUpdates(0, 0, criteria, someOtherLocationListenerPendingIntent);
-
- locationManager.removeUpdates(someLocationListenerPendingIntent);
-
- Map<PendingIntent, Criteria> expectedCriteria = new HashMap<PendingIntent, Criteria>();
- expectedCriteria.put(someOtherLocationListenerPendingIntent, criteria);
- assertThat(shadowLocationManager.getRequestLocationUdpateCriteriaPendingIntents(), equalTo(expectedCriteria));
- }
-
- @Test
- public void shouldNotSetBestEnabledProviderIfProviderIsDisabled() throws Exception {
- shadowLocationManager.setProviderEnabled(GPS_PROVIDER, true);
- assertTrue(shadowLocationManager.setBestProvider(LocationManager.GPS_PROVIDER, true));
- }
-
- @Test
- public void shouldNotSetBestDisabledProviderIfProviderIsEnabled() throws Exception {
- shadowLocationManager.setProviderEnabled(GPS_PROVIDER, true);
- assertFalse(shadowLocationManager.setBestProvider(LocationManager.GPS_PROVIDER, false));
- }
-
- @Test
- public void shouldRemovePendingIntentsWhenRequestingLocationUpdatesUsingLocationListeners() throws Exception {
- Intent someIntent = new Intent("some_action");
- PendingIntent someLocationListenerPendingIntent = PendingIntent.getBroadcast(Robolectric.getShadowApplication().getApplicationContext(), 0,
- someIntent, PendingIntent.FLAG_UPDATE_CURRENT);
- Intent someOtherIntent = new Intent("some_other_action");
- PendingIntent someOtherLocationListenerPendingIntent = PendingIntent.getBroadcast(Robolectric.getShadowApplication().getApplicationContext(),
- 0, someOtherIntent, PendingIntent.FLAG_UPDATE_CURRENT);
-
- shadowLocationManager.setProviderEnabled(GPS_PROVIDER, true);
- shadowLocationManager.setBestProvider(LocationManager.GPS_PROVIDER, true);
- shadowLocationManager.setProviderEnabled(NETWORK_PROVIDER, true);
-
- locationManager.requestLocationUpdates(GPS_PROVIDER, 0, 0, someLocationListenerPendingIntent);
- locationManager.requestLocationUpdates(NETWORK_PROVIDER, 0, 0, someOtherLocationListenerPendingIntent);
-
- locationManager.removeUpdates(someLocationListenerPendingIntent);
-
- Map<PendingIntent, String> expectedProviders = new HashMap<PendingIntent, String>();
- expectedProviders.put(someOtherLocationListenerPendingIntent, NETWORK_PROVIDER);
- assertThat(shadowLocationManager.getRequestLocationUdpateProviderPendingIntents(),
- equalTo(expectedProviders));
- }
-
- @Test
- public void shouldStoreBestProviderCriteriaAndEnabledOnlyFlag() throws Exception {
- Criteria criteria = new Criteria();
- assertNull(locationManager.getBestProvider(criteria, true));
- assertSame(criteria, shadowLocationManager.getLastBestProviderCriteria());
- assertTrue(shadowLocationManager.getLastBestProviderEnabledOnly());
- }
-
- @Test
- public void shouldReturnNullIfBestProviderNotExplicitlySet() throws Exception {
- Criteria criteria = new Criteria();
- assertNull(locationManager.getBestProvider(null, false));
- assertNull(locationManager.getBestProvider(null, true));
- assertNull(locationManager.getBestProvider(criteria, false));
- assertNull(locationManager.getBestProvider(criteria, true));
- }
-
- @Test
- public void shouldThrowExceptionWhenRequestingLocationUpdatesWithANullIntent() throws Exception {
- try {
- shadowLocationManager.requestLocationUpdates(0, 0, new Criteria(), null);
- Assert.fail("When requesting location updates the intent must not be null!");
- } catch (Exception e) {
- // No worries, everything is fine...
- }
- }
-
- @Test
- public void shouldThrowExceptionWhenRequestingLocationUpdatesAndNoProviderIsFound() throws Exception {
- Intent someIntent = new Intent("some_action");
- PendingIntent someLocationListenerPendingIntent = PendingIntent.getBroadcast(Robolectric.getShadowApplication().getApplicationContext(), 0,
- someIntent, PendingIntent.FLAG_UPDATE_CURRENT);
- Criteria criteria = new Criteria();
- criteria.setAccuracy(Criteria.ACCURACY_FINE);
- try {
- shadowLocationManager.requestLocationUpdates(0, 0, criteria, someLocationListenerPendingIntent);
- Assert.fail("When requesting location updates the intent must not be null!");
- } catch (Exception e) {
- // No worries, everything is fine...
- }
- }
-
- @Test
- public void shouldThrowExceptionIfTheBestProviderIsUnknown() throws Exception {
- Criteria criteria = new Criteria();
- criteria.setAccuracy(Criteria.ACCURACY_FINE);
- try {
- shadowLocationManager.setBestProvider("BEST_ENABLED_PROVIDER", true);
- Assert.fail("The best provider is unknown!");
- } catch (Exception e) {
- // No worries, everything is fine...
- }
- }
-
- @Test
- public void shouldReturnBestCustomProviderUsingCriteria() throws Exception {
- Criteria criteria = new Criteria();
- Criteria customProviderCriteria = new Criteria();
-
- // Manually set best provider should be returned
- ArrayList<Criteria> criteriaList = new ArrayList<Criteria>();
- customProviderCriteria.setAccuracy(Criteria.ACCURACY_COARSE);
- criteriaList.add(customProviderCriteria);
- shadowLocationManager.setProviderEnabled("BEST_ENABLED_PROVIDER_WITH_CRITERIA", true, criteriaList);
- assertTrue(shadowLocationManager.setBestProvider("BEST_ENABLED_PROVIDER_WITH_CRITERIA", true));
- criteria.setAccuracy(Criteria.ACCURACY_COARSE);
- criteria.setPowerRequirement(Criteria.NO_REQUIREMENT);
- assertThat("BEST_ENABLED_PROVIDER_WITH_CRITERIA", equalTo(locationManager.getBestProvider(criteria, true)));
- assertTrue(shadowLocationManager.setBestProvider("BEST_ENABLED_PROVIDER_WITH_CRITERIA", true));
- assertThat("BEST_ENABLED_PROVIDER_WITH_CRITERIA", equalTo(locationManager.getBestProvider(criteria, false)));
- assertThat("BEST_ENABLED_PROVIDER_WITH_CRITERIA", equalTo(locationManager.getBestProvider(criteria, true)));
- }
-
- @Test
- public void shouldReturnBestProviderUsingCriteria() {
- Criteria criteria = new Criteria();
-
- shadowLocationManager.setProviderEnabled(LocationManager.GPS_PROVIDER, false);
- criteria.setAccuracy(Criteria.ACCURACY_FINE);
- assertThat(LocationManager.GPS_PROVIDER, equalTo(locationManager.getBestProvider(criteria, false)));
-
- shadowLocationManager.setProviderEnabled(LocationManager.NETWORK_PROVIDER, false);
- criteria.setAccuracy(Criteria.ACCURACY_COARSE);
- assertThat(LocationManager.NETWORK_PROVIDER, equalTo(locationManager.getBestProvider(criteria, false)));
-
- criteria.setPowerRequirement(Criteria.POWER_LOW);
- criteria.setAccuracy(Criteria.ACCURACY_FINE);
- assertThat(LocationManager.NETWORK_PROVIDER, equalTo(locationManager.getBestProvider(criteria, false)));
- }
-
- @Test
- public void shouldReturnBestDisabledProvider() throws Exception {
- shadowLocationManager.setProviderEnabled("BEST_DISABLED_PROVIDER", false);
- shadowLocationManager.setBestProvider("BEST_DISABLED_PROVIDER", false);
- shadowLocationManager.setProviderEnabled("BEST_ENABLED_PROVIDER", true);
- shadowLocationManager.setBestProvider("BEST_ENABLED_PROVIDER", true);
-
- assertTrue(shadowLocationManager.setBestProvider("BEST_DISABLED_PROVIDER", false));
- assertThat("BEST_DISABLED_PROVIDER", equalTo(locationManager.getBestProvider(null, false)));
- assertThat("BEST_ENABLED_PROVIDER", equalTo(locationManager.getBestProvider(null, true)));
- }
-
- @Test
- public void shouldReturnBestEnabledProvider() throws Exception {
- shadowLocationManager.setProviderEnabled("BEST_ENABLED_PROVIDER", true);
-
- assertTrue(shadowLocationManager.setBestProvider("BEST_ENABLED_PROVIDER", true));
- assertFalse(shadowLocationManager.setBestProvider("BEST_ENABLED_PROVIDER", false));
- assertThat("BEST_ENABLED_PROVIDER", equalTo(locationManager.getBestProvider(null, true)));
- assertNull(locationManager.getBestProvider(null, false));
- }
-
- @Test
- public void shouldNotifyAllListenersIfProviderStateChanges() {
- TestLocationListener listener = new TestLocationListener();
- locationManager.requestLocationUpdates("TEST_PROVIDER", 0, 0, listener);
- shadowLocationManager.setProviderEnabled("TEST_PROVIDER", true);
- assertTrue(listener.providerEnabled);
- shadowLocationManager.setProviderEnabled("TEST_PROVIDER", false);
- assertFalse(listener.providerEnabled);
- }
-
- @Test
- public void shouldRegisterLocationUpdatesWhenProviderGiven() throws Exception {
- shadowLocationManager.setProviderEnabled(GPS_PROVIDER, true);
- shadowLocationManager.setBestProvider(LocationManager.GPS_PROVIDER, true);
-
- Intent someIntent = new Intent("some_action");
- PendingIntent someLocationListenerPendingIntent = PendingIntent.getBroadcast(Robolectric.getShadowApplication().getApplicationContext(), 0,
- someIntent, PendingIntent.FLAG_UPDATE_CURRENT);
- locationManager.requestLocationUpdates(GPS_PROVIDER, 0, 0, someLocationListenerPendingIntent);
-
- assertThat(shadowLocationManager.getRequestLocationUdpateProviderPendingIntents().get(someLocationListenerPendingIntent),
- equalTo(GPS_PROVIDER));
- }
-
- @Test
- public void shouldRegisterLocationUpdatesWhenCriteriaGiven() throws Exception {
- shadowLocationManager.setProviderEnabled(NETWORK_PROVIDER, true);
- shadowLocationManager.setBestProvider(LocationManager.NETWORK_PROVIDER, true);
- Criteria criteria = new Criteria();
- criteria.setAccuracy(Criteria.ACCURACY_COARSE);
-
- Intent someIntent = new Intent("some_action");
- PendingIntent someLocationListenerPendingIntent = PendingIntent.getBroadcast(Robolectric.getShadowApplication().getApplicationContext(), 0,
- someIntent, PendingIntent.FLAG_UPDATE_CURRENT);
- Criteria someCriteria = new Criteria();
- someCriteria.setAccuracy(Criteria.ACCURACY_COARSE);
- locationManager.requestLocationUpdates(0, 0, someCriteria, someLocationListenerPendingIntent);
-
- assertThat(shadowLocationManager.getRequestLocationUdpateCriteriaPendingIntents().get(someLocationListenerPendingIntent),
- equalTo(someCriteria));
- }
-
- private Listener addGpsListenerToLocationManager() {
- Listener listener = new TestGpsListener();
- locationManager.addGpsStatusListener(listener);
- return listener;
- }
-
- private static class TestLocationListener implements LocationListener {
- public boolean providerEnabled;
-
- @Override
- public void onLocationChanged(Location location) {
- }
-
- @Override
- public void onStatusChanged(String s, int i, Bundle bundle) {
- }
-
- @Override
- public void onProviderEnabled(String s) {
- providerEnabled = true;
- }
-
- @Override
- public void onProviderDisabled(String s) {
- providerEnabled = false;
- }
- }
-
- private class TestGpsListener implements Listener {
-
- @Override
- public void onGpsStatusChanged(int event) {
-
- }
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/LocationTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/LocationTest.java
deleted file mode 100644
index fd0da5b13..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/LocationTest.java
+++ /dev/null
@@ -1,121 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.location.Location;
-import android.location.LocationManager;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static junit.framework.Assert.assertEquals;
-import static junit.framework.Assert.assertTrue;
-import static junit.framework.Assert.assertFalse;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class LocationTest {
-
- private Location location;
-
- @Before
- public void setUp() throws Exception {
- location = new Location(LocationManager.GPS_PROVIDER);
- location.setTime(1);
- location.setLatitude(2);
- location.setLongitude(3);
- location.setAccuracy(4);
- location.setBearing(0.5f);
- location.setSpeed(5.5f);
- location.setAltitude(3.0d);
- }
-
- @Test
- public void test_copyConstructor() throws Exception {
- Location copiedLocation = new Location(location);
-
- assertLocationFieldsFromTestSetup(copiedLocation);
- }
-
- @Test
- public void test_set() throws Exception {
- Location newLocation = new Location(LocationManager.NETWORK_PROVIDER);
- newLocation.set(location);
-
- assertLocationFieldsFromTestSetup(newLocation);
- }
-
- @Test
- public void removeFieldShouldReportHasFieldAsFalse()
- {
- assertTrue(location.hasAccuracy());
- location.removeAccuracy();
- assertFalse(location.hasAccuracy());
-
- assertTrue(location.hasBearing());
- location.removeBearing();
- assertFalse(location.hasBearing());
-
- assertTrue(location.hasAltitude());
- location.removeAltitude();
- assertFalse(location.hasAltitude());
-
- assertTrue(location.hasSpeed());
- location.removeSpeed();
- assertFalse(location.hasSpeed());
- }
-
- @Test
- public void defaultLocationShouldNotReportFieldsAsAvailable()
- {
- Location defaultLocation = new Location(LocationManager.GPS_PROVIDER);
- assertFalse(defaultLocation.hasAccuracy());
- assertFalse(defaultLocation.hasBearing());
- assertFalse(defaultLocation.hasAltitude());
- assertFalse(defaultLocation.hasSpeed());
-
- assertEquals(0.0d, defaultLocation.getLatitude());
- assertEquals(0.0d, defaultLocation.getLongitude());
- assertEquals(0.0f, defaultLocation.getAccuracy());
- assertEquals(0.0f, defaultLocation.getBearing());
- assertEquals(0.0f, defaultLocation.getSpeed());
- assertEquals(0.0d, defaultLocation.getAltitude());
- }
-
- @Test
- public void settingFieldShouldMakeHasFieldReturnTrue()
- {
- Location l = new Location(LocationManager.GPS_PROVIDER);
- assertFalse(l.hasAccuracy());
- l.setAccuracy(0.5f);
- assertTrue(l.hasAccuracy());
-
- assertFalse(l.hasBearing());
- l.setBearing(1);
- assertTrue(l.hasBearing());
-
- assertFalse(l.hasAltitude());
- l.setAltitude(1);
- assertTrue(l.hasAltitude());
-
- assertFalse(l.hasSpeed());
- l.setSpeed(5);
- assertTrue(l.hasSpeed());
- }
-
- private void assertLocationFieldsFromTestSetup(Location l) {
- assertEquals(1, l.getTime());
- assertEquals(2.0, l.getLatitude());
- assertEquals(3.0, l.getLongitude());
- assertEquals(4f, l.getAccuracy());
- assertEquals(0.5f, l.getBearing());
- assertEquals(5.5f, l.getSpeed());
- assertEquals(3.0d, l.getAltitude());
- assertEquals(LocationManager.GPS_PROVIDER, l.getProvider());
-
- assertTrue(l.hasAltitude());
- assertTrue(l.hasAccuracy());
- assertTrue(l.hasBearing());
- assertTrue(l.hasSpeed());
-
- assertEquals(location, l);
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/LogTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/LogTest.java
deleted file mode 100644
index b64fad3e8..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/LogTest.java
+++ /dev/null
@@ -1,173 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.util.Log;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import junit.framework.Assert;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import java.io.ByteArrayOutputStream;
-import java.io.PrintStream;
-
-import static junit.framework.Assert.assertEquals;
-import static org.hamcrest.CoreMatchers.*;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertThat;
-import static org.junit.Assert.assertTrue;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class LogTest {
- @Test
- public void d_shouldLogAppropriately() {
- Log.d("tag", "msg");
-
- assertLogged(Log.DEBUG, "tag", "msg", null);
- }
-
- @Test
- public void d_shouldLogAppropriately_withThrowable() {
- Throwable throwable = new Throwable();
-
- Log.d("tag", "msg", throwable);
-
- assertLogged(Log.DEBUG, "tag", "msg", throwable);
- }
-
- @Test
- public void e_shouldLogAppropriately() {
- Log.e("tag", "msg");
-
- assertLogged(Log.ERROR, "tag", "msg", null);
- }
-
- @Test
- public void e_shouldLogAppropriately_withThrowable() {
- Throwable throwable = new Throwable();
-
- Log.e("tag", "msg", throwable);
-
- assertLogged(Log.ERROR, "tag", "msg", throwable);
- }
-
- @Test
- public void i_shouldLogAppropriately() {
- Log.i("tag", "msg");
-
- assertLogged(Log.INFO, "tag", "msg", null);
- }
-
- @Test
- public void i_shouldLogAppropriately_withThrowable() {
- Throwable throwable = new Throwable();
-
- Log.i("tag", "msg", throwable);
-
- assertLogged(Log.INFO, "tag", "msg", throwable);
- }
-
- @Test
- public void v_shouldLogAppropriately() {
- Log.v("tag", "msg");
-
- assertLogged(Log.VERBOSE, "tag", "msg", null);
- }
-
- @Test
- public void v_shouldLogAppropriately_withThrowable() {
- Throwable throwable = new Throwable();
-
- Log.v("tag", "msg", throwable);
-
- assertLogged(Log.VERBOSE, "tag", "msg", throwable);
- }
-
- @Test
- public void w_shouldLogAppropriately() {
- Log.w("tag", "msg");
-
- assertLogged(Log.WARN, "tag", "msg", null);
- }
-
- @Test
- public void w_shouldLogAppropriately_withThrowable() {
- Throwable throwable = new Throwable();
-
- Log.w("tag", "msg", throwable);
-
- assertLogged(Log.WARN, "tag", "msg", throwable);
- }
-
- @Test
- public void w_shouldLogAppropriately_withJustThrowable() {
- Throwable throwable = new Throwable();
- Log.w("tag", throwable);
- assertLogged(Log.WARN, "tag", null, throwable);
- }
-
- @Test
- public void wtf_shouldLogAppropriately() {
- Log.wtf("tag", "msg");
-
- assertLogged(Log.ASSERT, "tag", "msg", null);
- }
-
- @Test
- public void wtf_shouldLogAppropriately_withThrowable() {
- Throwable throwable = new Throwable();
-
- Log.wtf("tag", "msg", throwable);
-
- assertLogged(Log.ASSERT, "tag", "msg", throwable);
- }
-
- @Test
- public void shouldLogToProvidedStream() throws Exception {
- final ByteArrayOutputStream bos = new ByteArrayOutputStream();
- PrintStream old = ShadowLog.stream;
- try {
- ShadowLog.stream = new PrintStream(bos);
- Log.d("tag", "msg");
- assertThat(new String(bos.toByteArray()), equalTo("D/tag: msg\n"));
-
- Log.w("tag", new RuntimeException());
- assertTrue(new String(bos.toByteArray()).contains("RuntimeException"));
- } finally {
- ShadowLog.stream = old;
- }
- }
-
- @Test
- public void infoIsDefaultLoggableLevel() throws Exception {
- PrintStream old = ShadowLog.stream;
- ShadowLog.stream = null;
- assertFalse(Log.isLoggable("FOO", Log.VERBOSE));
- assertFalse(Log.isLoggable("FOO", Log.DEBUG));
-
- assertTrue(Log.isLoggable("FOO", Log.INFO));
- assertTrue(Log.isLoggable("FOO", Log.WARN));
- assertTrue(Log.isLoggable("FOO", Log.ERROR));
- assertTrue(Log.isLoggable("FOO", Log.ASSERT));
- ShadowLog.stream = old;
- }
-
- @Test
- public void shouldAlwaysBeLoggableIfStreamIsSpecified() throws Exception {
- PrintStream old = ShadowLog.stream;
- ShadowLog.stream = new PrintStream(new ByteArrayOutputStream());
- assertTrue(Log.isLoggable("FOO", Log.VERBOSE));
- assertTrue(Log.isLoggable("FOO", Log.DEBUG));
- assertTrue(Log.isLoggable("FOO", Log.INFO));
- assertTrue(Log.isLoggable("FOO", Log.WARN));
- assertTrue(Log.isLoggable("FOO", Log.ERROR));
- assertTrue(Log.isLoggable("FOO", Log.ASSERT));
- ShadowLog.stream = old;
- }
-
- private void assertLogged(int type, String tag, String msg, Throwable throwable) {
- ShadowLog.LogItem lastLog = ShadowLog.getLogs().get(0);
- assertEquals(type, lastLog.type);
- assertEquals(msg, lastLog.msg);
- assertEquals(tag, lastLog.tag);
- assertEquals(throwable, lastLog.throwable);
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/LooperTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/LooperTest.java
deleted file mode 100644
index b2f0c5e10..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/LooperTest.java
+++ /dev/null
@@ -1,106 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.os.Handler;
-import android.os.HandlerThread;
-import android.os.Looper;
-
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-import static org.junit.Assert.*;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class LooperTest {
-
- @Test
- public void testMainLooperAndMyLooperAreTheSameInstanceOnMainThread() throws Exception {
- assertSame(Looper.myLooper(), Looper.getMainLooper());
- }
-
- @Test
- public void idleMainLooper_executesScheduledTasks() {
- final boolean[] wasRun = new boolean[]{false};
- new Handler().postDelayed(new Runnable() {
- @Override
- public void run() {
- wasRun[0] = true;
- }
- }, 2000);
-
- assertFalse(wasRun[0]);
- ShadowLooper.idleMainLooper(1999);
- assertFalse(wasRun[0]);
- ShadowLooper.idleMainLooper(1);
- assertTrue(wasRun[0]);
- }
-
- @Test
- public void differentThreadsGetDifferentLoopers() {
- Looper mainLooper = Looper.getMainLooper();
- Looper thisThreadsLooper = Looper.myLooper();
-
- assertSame("junit test's thread should use the main looper", mainLooper, thisThreadsLooper);
-
- final Looper[] thread1Looper = new Looper[1];
- new Thread() {
- @Override
- public void run() {
- Looper.prepare();
- thread1Looper[0] = Looper.myLooper();
- }
- }.start();
-
- while(thread1Looper[0] == null) {
- Thread.yield();
- }
-
- assertNotSame(mainLooper, thread1Looper[0]);
- }
-
- @Test(expected = RuntimeException.class)
- public void shouldThrowRuntimeExceptionIfTryingToQuitMainLooper() throws Exception {
- Looper.getMainLooper().quit();
- }
-
- @Test
- public void shouldNotQueueMessagesIfLooperIsQuit() throws Exception {
- HandlerThread ht = new HandlerThread("test1");
- ht.start();
- Looper looper = ht.getLooper();
- looper.quit();
- assertTrue(shadowOf(looper).hasQuit());
- assertFalse(shadowOf(looper).post(new Runnable() {
- @Override public void run() { }
- }, 0));
-
- assertFalse(shadowOf(looper).postAtFrontOfQueue(new Runnable() {
- @Override
- public void run() {
- }
- }));
- assertFalse(shadowOf(looper).getScheduler().areAnyRunnable());
- }
-
- @Test
- public void shouldThrowawayRunnableQueueIfLooperQuits() throws Exception {
- HandlerThread ht = new HandlerThread("test1");
- ht.start();
- Looper looper = ht.getLooper();
- shadowOf(looper).pause();
- shadowOf(looper).post(new Runnable() {
- @Override
- public void run() {
- }
- }, 0);
- looper.quit();
- assertTrue(shadowOf(looper).hasQuit());
- assertFalse(shadowOf(looper).getScheduler().areAnyRunnable());
- }
-
- @Test
- public void testLoopThread() {
- assertTrue(shadowOf(Looper.getMainLooper()).getThread() == Thread.currentThread());
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/MapActivityTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/MapActivityTest.java
deleted file mode 100644
index 6ccc41733..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/MapActivityTest.java
+++ /dev/null
@@ -1,49 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.os.Bundle;
-import com.google.android.maps.MapActivity;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class MapActivityTest {
- @Test
- public void onDestroy_shouldNotComplainIfLifecycleIsCorrect() throws Exception {
- MyMapActivity mapActivity = new MyMapActivity();
- mapActivity.onCreate(null);
- mapActivity.onResume();
- mapActivity.onPause();
- mapActivity.onDestroy();
- }
-
- @Test(expected = IllegalStateException.class)
- public void onDestroy_shouldComplainIfPauseIsNotCalled() throws Exception {
- MyMapActivity mapActivity = new MyMapActivity();
- mapActivity.onCreate(null);
- mapActivity.onResume();
- mapActivity.onDestroy();
- }
-
- private static class MyMapActivity extends MapActivity {
- @Override protected void onCreate(Bundle bundle) {
- super.onCreate(bundle);
- }
-
- @Override protected void onDestroy() {
- super.onDestroy();
- }
-
- @Override protected void onPause() {
- super.onPause();
- }
-
- @Override protected void onResume() {
- super.onResume();
- }
-
- @Override protected boolean isRouteDisplayed() {
- return false;
- }
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/MapViewTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/MapViewTest.java
deleted file mode 100644
index f44f01b4d..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/MapViewTest.java
+++ /dev/null
@@ -1,179 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.app.Activity;
-import android.graphics.Point;
-import android.view.MotionEvent;
-import android.view.View;
-import com.google.android.maps.GeoPoint;
-import com.google.android.maps.MapView;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import com.xtremelabs.robolectric.bytecode.AndroidTranslatorTest;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static com.xtremelabs.robolectric.shadows.ShadowMapView.toE6;
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.CoreMatchers.nullValue;
-import static org.hamcrest.CoreMatchers.sameInstance;
-import static org.junit.Assert.assertThat;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class MapViewTest {
- private MapView mapView;
- private MyOverlay overlay1;
- private MyOverlay overlay2;
- private MotionEvent sourceEvent;
- private MyOnTouchListener mapTouchListener;
-
-
- @Before public void setUp() throws Exception {
- mapView = new MapView(new Activity(), "foo");
-
- overlay1 = new MyOverlay();
- overlay2 = new MyOverlay();
- mapTouchListener = new MyOnTouchListener();
-
- mapView.getOverlays().add(overlay1);
- mapView.getOverlays().add(overlay2);
- mapView.setOnTouchListener(mapTouchListener);
-
- sourceEvent = MotionEvent.obtain(0, 0, 0, 0, 0, 0);
- }
-
- @Test
- public void shouldDispatchTouchEventsToOverlays() throws Exception {
- mapView.dispatchTouchEvent(sourceEvent);
-
- assertThat(overlay1.lastMotionEvent, sameInstance(sourceEvent));
- assertThat(overlay2.lastMotionEvent, nullValue());
- assertThat(mapTouchListener.lastMotionEvent, nullValue());
- }
-
- @Test
- public void shouldDispatchTouchEventsToOverlaysUntilEventIsConsumed() throws Exception {
- overlay1.shouldConsumeEvent = false;
- overlay2.shouldConsumeEvent = true;
-
- mapView.dispatchTouchEvent(sourceEvent);
-
- assertThat(overlay1.lastMotionEvent, sameInstance(sourceEvent));
- assertThat(overlay2.lastMotionEvent, sameInstance(sourceEvent));
- assertThat(mapTouchListener.lastMotionEvent, nullValue());
- }
-
- @Test
- public void shouldDispatchTouchEventsToMapViewIfNoOverlayConsumesEvent() throws Exception {
- overlay1.shouldConsumeEvent = false;
- overlay2.shouldConsumeEvent = false;
-
- mapView.dispatchTouchEvent(sourceEvent);
-
- assertThat(overlay1.lastMotionEvent, sameInstance(sourceEvent));
- assertThat(overlay2.lastMotionEvent, sameInstance(sourceEvent));
- assertThat(mapTouchListener.lastMotionEvent, sameInstance(sourceEvent));
- }
-
- @Test
- public void dispatchTouchEvents_shouldDragMapByCorrectAmount() throws Exception {
- initMapForDrag();
-
- dispatchTouchEvent(MotionEvent.ACTION_DOWN, 10, 10);
- dispatchTouchEvent(MotionEvent.ACTION_UP, 11, 11);
- assertThat(mapView.getMapCenter(), equalTo(new GeoPoint(toE6(26), toE6(24))));
- }
-
- @Test
- public void dispatchTouchEvents_shouldDragMapByCorrectAmountInMultipleSteps() throws Exception {
- initMapForDrag();
-
- dispatchTouchEvent(MotionEvent.ACTION_DOWN, 10, 10);
- dispatchTouchEvent(MotionEvent.ACTION_MOVE, 11, 11);
- dispatchTouchEvent(MotionEvent.ACTION_MOVE, 12, 12);
- dispatchTouchEvent(MotionEvent.ACTION_UP, 11, 11);
- assertThat(mapView.getMapCenter(), equalTo(new GeoPoint(toE6(26), toE6(24))));
- }
-
- @Test
- public void dispatchTouchEvents_shouldMoveBackToCenterOnCancel() throws Exception {
- initMapForDrag();
-
- dispatchTouchEvent(MotionEvent.ACTION_DOWN, 10, 10);
- dispatchTouchEvent(MotionEvent.ACTION_MOVE, 11, 11);
- dispatchTouchEvent(MotionEvent.ACTION_MOVE, 12, 12);
- dispatchTouchEvent(MotionEvent.ACTION_CANCEL, 11, 11);
- assertThat(mapView.getMapCenter(), equalTo(new GeoPoint(toE6(25), toE6(25))));
- }
-
- private void initMapForDrag() {
- mapView = new MapView(null, "");
- mapView.layout(0, 0, 50, 50);
- mapView.getController().setCenter(new GeoPoint(toE6(25), toE6(25)));
- mapView.getController().zoomToSpan(toE6(50), toE6(50));
- }
-
- @Test
- public void getProjection_fromPixels_shouldPerformCorrectTranslations() throws Exception {
- int centerLat = 11;
- int centerLng = 16;
- int spanLat = 20;
- int spanLng = 30;
-
- mapView.getController().setCenter(new GeoPoint(toE6(centerLat), toE6(centerLng)));
- mapView.getController().zoomToSpan(toE6(spanLat), toE6(spanLng));
- mapView.layout(50, 60, 650, 460);
-
- assertThat(mapView.getProjection().fromPixels(50, 60),
- equalTo(new GeoPoint(toE6(21), toE6(1))));
- assertThat(mapView.getProjection().fromPixels(350, 260),
- equalTo(new GeoPoint(toE6(11), toE6(16))));
- assertThat(mapView.getProjection().fromPixels(650, 460),
- equalTo(new GeoPoint(toE6(1), toE6(31))));
- }
-
- @Test
- public void getProjection_toPixels_shouldPerformCorrectTranslations() throws Exception {
- int centerLat = 11;
- int centerLng = 16;
- int spanLat = 20;
- int spanLng = 30;
-
- mapView.getController().setCenter(new GeoPoint(toE6(centerLat), toE6(centerLng)));
- mapView.getController().zoomToSpan(toE6(spanLat), toE6(spanLng));
- mapView.layout(50, 60, 650, 460);
-
- assertThat(mapView.getProjection().toPixels(new GeoPoint(toE6(21), toE6(1)), null),
- equalTo(new Point(50, 60)));
- assertThat(mapView.getProjection().toPixels(new GeoPoint(toE6(11), toE6(16)), null),
- equalTo(new Point(350, 260)));
- assertThat(mapView.getProjection().toPixels(new GeoPoint(toE6(1), toE6(31)), null),
- equalTo(new Point(650, 460)));
- }
-
- private void dispatchTouchEvent(int action, int x, int y) {
- mapView.dispatchTouchEvent(MotionEvent.obtain(0, 0, action, x, y, 0));
- }
-
- private static class MyOnTouchListener implements View.OnTouchListener {
- private MotionEvent lastMotionEvent;
-
- @Override public boolean onTouch(View v, MotionEvent event) {
- lastMotionEvent = event;
- return false;
- }
- }
-
- private class MyOverlay extends AndroidTranslatorTest.ItemizedOverlayForTests {
- private MotionEvent lastMotionEvent;
- private boolean shouldConsumeEvent = true;
-
- public MyOverlay() {
- super(null);
- }
-
- @Override public boolean onTouchEvent(MotionEvent motionEvent, MapView mapView) {
- lastMotionEvent = motionEvent;
- return shouldConsumeEvent;
- }
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/MarginLayoutParamsTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/MarginLayoutParamsTest.java
deleted file mode 100644
index 290125e9d..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/MarginLayoutParamsTest.java
+++ /dev/null
@@ -1,28 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-
-import android.view.ViewGroup;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.junit.Assert.assertThat;
-
-/**
- * {@link ShadowMarginLayoutParams} test suite.
- */
-@RunWith(WithTestDefaultsRunner.class)
-public class MarginLayoutParamsTest {
-
- @Test
- public void testSetMargins() {
- ViewGroup.MarginLayoutParams marginLayoutParams = new ViewGroup.MarginLayoutParams(0, 0);
- marginLayoutParams.setMargins(1, 2, 3, 4);
- assertThat(marginLayoutParams.leftMargin, equalTo(1));
- assertThat(marginLayoutParams.topMargin, equalTo(2));
- assertThat(marginLayoutParams.rightMargin, equalTo(3));
- assertThat(marginLayoutParams.bottomMargin, equalTo(4));
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/MatrixCursorTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/MatrixCursorTest.java
deleted file mode 100644
index ab40385af..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/MatrixCursorTest.java
+++ /dev/null
@@ -1,157 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.CoreMatchers.nullValue;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertThat;
-import static org.junit.Assert.assertTrue;
-
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import android.database.CursorIndexOutOfBoundsException;
-import android.database.MatrixCursor;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class MatrixCursorTest {
-
- private MatrixCursor singleColumnSingleNullValueMatrixCursor;
-
- @Before
- public void setUp() throws Exception {
- singleColumnSingleNullValueMatrixCursor = new MatrixCursor(new String[]{"a"});
- singleColumnSingleNullValueMatrixCursor.addRow(new Object[]{null});
- singleColumnSingleNullValueMatrixCursor.moveToFirst();
- }
-
- @Test
- public void shouldAddRows() throws Exception {
- MatrixCursor cursor = new MatrixCursor(new String[]{"a", "b", "c"});
- cursor.addRow(new Object[]{"foo", 10L, 0.1f});
- cursor.addRow(new Object[]{"baz", 20L, null});
- assertThat(cursor.getCount(), equalTo(2));
-
- assertTrue(cursor.moveToFirst());
-
- assertThat(cursor.getString(0), equalTo("foo"));
- assertThat(cursor.getLong(1), equalTo(10L));
- assertThat(cursor.getFloat(2), equalTo(0.1f));
-
- assertTrue(cursor.moveToNext());
-
- assertThat(cursor.getString(0), equalTo("baz"));
- assertThat(cursor.getLong(1), equalTo(20L));
- assertTrue(cursor.isNull(2));
-
- assertFalse(cursor.moveToNext());
- }
-
- @Test
- public void shouldDefineColumnNames() throws Exception {
- MatrixCursor cursor = new MatrixCursor(new String[]{"a", "b", "c"});
-
- assertThat(cursor.getColumnCount(), equalTo(3));
-
- assertThat(cursor.getColumnName(0), equalTo("a"));
- assertThat(cursor.getColumnName(1), equalTo("b"));
- assertThat(cursor.getColumnName(2), equalTo("c"));
-
- assertThat(cursor.getColumnNames(), equalTo(new String[]{"a", "b", "c"}));
-
- assertThat(cursor.getColumnIndex("b"), equalTo(1));
- assertThat(cursor.getColumnIndex("z"), equalTo(-1));
- }
-
- @Test
- public void shouldDefineGetBlob() throws Exception {
- byte[] blob = {1, 2, 3, 4};
-
- MatrixCursor cursor = new MatrixCursor(new String[]{"a"});
- cursor.addRow(new Object[]{blob});
- assertTrue(cursor.moveToFirst());
-
- assertThat(cursor.getBlob(0), equalTo(blob));
- }
-
- @Test
- public void shouldAllowTypeFlexibility() throws Exception {
- MatrixCursor cursor = new MatrixCursor(new String[]{"a", "b", "c"});
- cursor.addRow(new Object[]{42, 3.3});
- assertTrue(cursor.moveToFirst());
-
- assertThat(cursor.getString(0), equalTo("42"));
- assertThat(cursor.getShort(0), equalTo((short) 42));
- assertThat(cursor.getInt(0), equalTo(42));
- assertThat(cursor.getLong(0), equalTo(42L));
- assertThat(cursor.getFloat(0), equalTo(42.0F));
- assertThat(cursor.getDouble(0), equalTo(42.0));
-
- assertThat(cursor.getString(1), equalTo("3.3"));
- assertThat(cursor.getShort(1), equalTo((short) 3));
- assertThat(cursor.getInt(1), equalTo(3));
- assertThat(cursor.getLong(1), equalTo(3L));
- assertThat(cursor.getFloat(1), equalTo(3.3F));
- assertThat(cursor.getDouble(1), equalTo(3.3));
- }
-
- @Test(expected = IllegalArgumentException.class)
- public void shouldDefineGetColumnNameOrThrow() throws Exception {
- MatrixCursor cursor = new MatrixCursor(new String[]{"a", "b", "c"});
- cursor.getColumnIndexOrThrow("z");
- }
-
- @Test(expected = CursorIndexOutOfBoundsException.class)
- public void shouldThrowIndexOutOfBoundsExceptionWithoutData() throws Exception {
- MatrixCursor cursor = new MatrixCursor(new String[]{"a", "b", "c"});
- cursor.getString(0);
- }
-
- @Test(expected = CursorIndexOutOfBoundsException.class)
- public void shouldThrowIndexOutOfBoundsExceptionForInvalidColumn() throws Exception {
- MatrixCursor cursor = new MatrixCursor(new String[]{"a", "b", "c"});
- cursor.addRow(new Object[]{"foo", 10L, 0.1f});
- cursor.getString(3);
- }
-
- @Test(expected = CursorIndexOutOfBoundsException.class)
- public void shouldThrowIndexOutOfBoundsExceptionForInvalidColumnLastRow() throws Exception {
- MatrixCursor cursor = new MatrixCursor(new String[]{"a", "b", "c"});
- cursor.addRow(new Object[]{"foo", 10L, 0.1f});
- cursor.moveToFirst();
- cursor.moveToNext();
- cursor.getString(0);
- }
-
- @Test
- public void returnsNullWhenGettingStringFromNullColumn() {
- assertThat(singleColumnSingleNullValueMatrixCursor.getString(0), is(nullValue()));
- }
-
- @Test
- public void returnsZeroWhenGettingIntFromNullColumn() {
- assertThat(singleColumnSingleNullValueMatrixCursor.getInt(0), is(equalTo(0)));
- }
-
- @Test
- public void returnsZeroWhenGettingLongFromNullColumn() {
- assertThat(singleColumnSingleNullValueMatrixCursor.getLong(0), is(equalTo(0L)));
- }
-
- @Test
- public void returnsZeroWhenGettingShortFromNullColumn() {
- assertThat(singleColumnSingleNullValueMatrixCursor.getShort(0), is(equalTo((short) 0)));
- }
-
- @Test
- public void returnsZeroWhenGettingFloatFromNullColumn() {
- assertThat(singleColumnSingleNullValueMatrixCursor.getFloat(0), is(equalTo(0.0f)));
- }
-
- @Test
- public void returnsZeroWhenGettingDoubleFromNullColumn() {
- assertThat(singleColumnSingleNullValueMatrixCursor.getDouble(0), is(equalTo(0.0)));
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/MediaPlayerTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/MediaPlayerTest.java
deleted file mode 100644
index 31c72bad8..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/MediaPlayerTest.java
+++ /dev/null
@@ -1,34 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.media.MediaPlayer;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.junit.Assert.assertThat;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class MediaPlayerTest {
-
- private MediaPlayer mediaPlayer;
- private ShadowMediaPlayer shadowMediaPlayer;
-
- @Before
- public void setUp() throws Exception {
- mediaPlayer = Robolectric.newInstanceOf(MediaPlayer.class);
- shadowMediaPlayer = Robolectric.shadowOf(mediaPlayer);
- }
-
- @Test
- public void testCurrentPosition() {
- int[] positions = {0, 1, 2, 1024};
-
- for (int position : positions) {
- shadowMediaPlayer.setCurrentPosition(position);
- assertThat(mediaPlayer.getCurrentPosition(), equalTo(position));
- }
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/MediaRecorderTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/MediaRecorderTest.java
deleted file mode 100644
index 71efe6e77..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/MediaRecorderTest.java
+++ /dev/null
@@ -1,234 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-
-import android.hardware.Camera;
-import android.media.MediaRecorder;
-import android.view.Surface;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static org.hamcrest.CoreMatchers.*;
-import static org.junit.Assert.assertThat;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class MediaRecorderTest {
-
- private MediaRecorder mediaRecorder;
- private ShadowMediaRecorder shadowMediaRecorder;
-
- @Before
- public void setUp() throws Exception {
- mediaRecorder = new MediaRecorder();
- shadowMediaRecorder = Robolectric.shadowOf(mediaRecorder);
- }
-
- @Test
- public void testAudioChannels() throws Exception {
- assertThat(shadowMediaRecorder.getAudioChannels(), not(equalTo(2)));
- mediaRecorder.setAudioChannels(2);
- assertThat(shadowMediaRecorder.getAudioChannels(), equalTo(2));
- }
-
- @Test
- public void testAudioEncoder() throws Exception {
- assertThat(shadowMediaRecorder.getAudioEncoder(), not(equalTo(MediaRecorder.AudioEncoder.AMR_NB)));
- assertThat(shadowMediaRecorder.getState(), not(equalTo(ShadowMediaRecorder.STATE_DATA_SOURCE_CONFIGURED)));
- mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
- assertThat(shadowMediaRecorder.getAudioEncoder(), equalTo(MediaRecorder.AudioEncoder.AMR_NB));
- assertThat(shadowMediaRecorder.getState(), equalTo(ShadowMediaRecorder.STATE_DATA_SOURCE_CONFIGURED));
- }
-
- @Test
- public void testAudioEncodingBitRate() throws Exception {
- assertThat(shadowMediaRecorder.getAudioEncodingBitRate(), not(equalTo(128000)));
- mediaRecorder.setAudioEncodingBitRate(128000);
- assertThat(shadowMediaRecorder.getAudioEncodingBitRate(), equalTo(128000));
- }
-
- @Test
- public void testAudioSamplingRate() throws Exception {
- assertThat(shadowMediaRecorder.getAudioSamplingRate(), not(equalTo(22050)));
- mediaRecorder.setAudioSamplingRate(22050);
- assertThat(shadowMediaRecorder.getAudioSamplingRate(), equalTo(22050));
- }
-
- @Test
- public void testAudioSource() throws Exception {
- assertThat(shadowMediaRecorder.getAudioSource(), not(equalTo(MediaRecorder.AudioSource.CAMCORDER)));
- assertThat(shadowMediaRecorder.getState(), not(equalTo(ShadowMediaRecorder.STATE_INITIALIZED)));
- mediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
- assertThat(shadowMediaRecorder.getAudioSource(), equalTo(MediaRecorder.AudioSource.CAMCORDER));
- assertThat(shadowMediaRecorder.getState(), equalTo(ShadowMediaRecorder.STATE_INITIALIZED));
- }
-
- @Test
- public void testCamera() throws Exception {
- assertThat(shadowMediaRecorder.getCamera(), nullValue());
- Camera c = Robolectric.newInstanceOf(Camera.class);
- mediaRecorder.setCamera(c);
- assertThat(shadowMediaRecorder.getCamera(), notNullValue());
- assertThat(shadowMediaRecorder.getCamera(), sameInstance(c));
- }
-
- @Test
- public void testMaxDuration() throws Exception {
- assertThat(shadowMediaRecorder.getMaxDuration(), not(equalTo(30000)));
- mediaRecorder.setMaxDuration(30000);
- assertThat(shadowMediaRecorder.getMaxDuration(), equalTo(30000));
- }
-
- @Test
- public void testMaxFileSize() throws Exception {
- assertThat(shadowMediaRecorder.getMaxFileSize(), not(equalTo(512000L)));
- mediaRecorder.setMaxFileSize(512000);
- assertThat(shadowMediaRecorder.getMaxFileSize(), equalTo(512000L));
- }
-
- @Test
- public void testOnErrorListener() throws Exception {
- assertThat(shadowMediaRecorder.getErrorListener(), nullValue());
- TestErrorListener listener = new TestErrorListener();
- mediaRecorder.setOnErrorListener(listener);
- assertThat(shadowMediaRecorder.getErrorListener(), notNullValue());
- assertThat(shadowMediaRecorder.getErrorListener(), sameInstance((MediaRecorder.OnErrorListener) listener));
- }
-
- @Test
- public void testOnInfoListener() throws Exception {
- assertThat(shadowMediaRecorder.getInfoListener(), nullValue());
- TestInfoListener listener = new TestInfoListener();
- mediaRecorder.setOnInfoListener(listener);
- assertThat(shadowMediaRecorder.getInfoListener(), notNullValue());
- assertThat(shadowMediaRecorder.getInfoListener(), sameInstance((MediaRecorder.OnInfoListener) listener));
- }
-
- @Test
- public void testOutputFile() throws Exception {
- assertThat(shadowMediaRecorder.getState(), not(equalTo(ShadowMediaRecorder.STATE_DATA_SOURCE_CONFIGURED)));
- assertThat(shadowMediaRecorder.getOutputPath(), nullValue());
- mediaRecorder.setOutputFile("/dev/null");
- assertThat(shadowMediaRecorder.getOutputPath(), equalTo("/dev/null"));
- assertThat(shadowMediaRecorder.getState(), equalTo(ShadowMediaRecorder.STATE_DATA_SOURCE_CONFIGURED));
- }
-
- @Test
- public void testOutputFormat() throws Exception {
- assertThat(shadowMediaRecorder.getState(), not(equalTo(ShadowMediaRecorder.STATE_DATA_SOURCE_CONFIGURED)));
- assertThat(shadowMediaRecorder.getOutputFormat(), not(equalTo(MediaRecorder.OutputFormat.MPEG_4)));
- mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
- assertThat(shadowMediaRecorder.getOutputFormat(), equalTo(MediaRecorder.OutputFormat.MPEG_4));
- assertThat(shadowMediaRecorder.getState(), equalTo(ShadowMediaRecorder.STATE_DATA_SOURCE_CONFIGURED));
- }
-
- @Test
- public void testPreviewDisplay() throws Exception {
- assertThat(shadowMediaRecorder.getState(), not(equalTo(ShadowMediaRecorder.STATE_DATA_SOURCE_CONFIGURED)));
- assertThat(shadowMediaRecorder.getPreviewDisplay(), nullValue());
- Surface surface = Robolectric.newInstanceOf(Surface.class);
- mediaRecorder.setPreviewDisplay(surface);
- assertThat(shadowMediaRecorder.getPreviewDisplay(), notNullValue());
- assertThat(shadowMediaRecorder.getPreviewDisplay(), sameInstance(surface));
- assertThat(shadowMediaRecorder.getState(), equalTo(ShadowMediaRecorder.STATE_DATA_SOURCE_CONFIGURED));
- }
-
- @Test
- public void testVideoEncoder() throws Exception {
- assertThat(shadowMediaRecorder.getState(), not(equalTo(ShadowMediaRecorder.STATE_DATA_SOURCE_CONFIGURED)));
- assertThat(shadowMediaRecorder.getVideoEncoder(), not(equalTo(MediaRecorder.VideoEncoder.H264)));
- mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
- assertThat(shadowMediaRecorder.getVideoEncoder(), equalTo(MediaRecorder.VideoEncoder.H264));
- assertThat(shadowMediaRecorder.getState(), equalTo(ShadowMediaRecorder.STATE_DATA_SOURCE_CONFIGURED));
- }
-
- @Test
- public void testVideoEncodingBitRate() throws Exception {
- assertThat(shadowMediaRecorder.getVideoEncodingBitRate(), not(equalTo(320000)));
- mediaRecorder.setVideoEncodingBitRate(320000);
- assertThat(shadowMediaRecorder.getVideoEncodingBitRate(), equalTo(320000));
- }
-
- @Test
- public void testVideoFrameRate() throws Exception {
- assertThat(shadowMediaRecorder.getState(), not(equalTo(ShadowMediaRecorder.STATE_DATA_SOURCE_CONFIGURED)));
- assertThat(shadowMediaRecorder.getVideoFrameRate(), not(equalTo(30)));
- mediaRecorder.setVideoFrameRate(30);
- assertThat(shadowMediaRecorder.getVideoFrameRate(), equalTo(30));
- assertThat(shadowMediaRecorder.getState(), equalTo(ShadowMediaRecorder.STATE_DATA_SOURCE_CONFIGURED));
- }
-
- @Test
- public void testVideoSize() throws Exception {
- assertThat(shadowMediaRecorder.getState(), not(equalTo(ShadowMediaRecorder.STATE_DATA_SOURCE_CONFIGURED)));
- assertThat(shadowMediaRecorder.getVideoWidth(), not(equalTo(640)));
- assertThat(shadowMediaRecorder.getVideoHeight(), not(equalTo(480)));
- mediaRecorder.setVideoSize(640, 480);
- assertThat(shadowMediaRecorder.getVideoWidth(), equalTo(640));
- assertThat(shadowMediaRecorder.getVideoHeight(), equalTo(480));
- assertThat(shadowMediaRecorder.getState(), equalTo(ShadowMediaRecorder.STATE_DATA_SOURCE_CONFIGURED));
- }
-
- @Test
- public void testVideoSource() throws Exception {
- assertThat(shadowMediaRecorder.getVideoSource(), not(equalTo(MediaRecorder.VideoSource.CAMERA)));
- assertThat(shadowMediaRecorder.getState(), not(equalTo(ShadowMediaRecorder.STATE_INITIALIZED)));
- mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
- assertThat(shadowMediaRecorder.getVideoSource(), equalTo(MediaRecorder.VideoSource.CAMERA));
- assertThat(shadowMediaRecorder.getState(), equalTo(ShadowMediaRecorder.STATE_INITIALIZED));
- }
-
- @Test
- public void testPrepare() throws Exception {
- assertThat(shadowMediaRecorder.getState(), not(equalTo(ShadowMediaRecorder.STATE_PREPARED)));
- mediaRecorder.prepare();
- assertThat(shadowMediaRecorder.getState(), equalTo(ShadowMediaRecorder.STATE_PREPARED));
- }
-
- @Test
- public void testStart() throws Exception {
- mediaRecorder.prepare();
- assertThat(shadowMediaRecorder.getState(), not(equalTo(ShadowMediaRecorder.STATE_RECORDING)));
- mediaRecorder.start();
- assertThat(shadowMediaRecorder.getState(), equalTo(ShadowMediaRecorder.STATE_RECORDING));
- }
-
- @Test
- public void testStop() throws Exception {
- mediaRecorder.start();
- assertThat(shadowMediaRecorder.getState(), equalTo(ShadowMediaRecorder.STATE_RECORDING));
- mediaRecorder.stop();
- assertThat(shadowMediaRecorder.getState(), equalTo(ShadowMediaRecorder.STATE_INITIAL));
- }
-
- @Test
- public void testReset() throws Exception {
- mediaRecorder.start();
- assertThat(shadowMediaRecorder.getState(), equalTo(ShadowMediaRecorder.STATE_RECORDING));
- mediaRecorder.reset();
- assertThat(shadowMediaRecorder.getState(), equalTo(ShadowMediaRecorder.STATE_INITIAL));
- }
-
- @Test
- public void testRelease() throws Exception {
- mediaRecorder.start();
- mediaRecorder.reset();
- assertThat(shadowMediaRecorder.getState(), equalTo(ShadowMediaRecorder.STATE_INITIAL));
- mediaRecorder.release();
- assertThat(shadowMediaRecorder.getState(), equalTo(ShadowMediaRecorder.STATE_RELEASED));
- }
-
- private class TestErrorListener implements MediaRecorder.OnErrorListener {
- @Override
- public void onError(MediaRecorder arg0, int arg1, int arg2) {
- }
- }
-
- private class TestInfoListener implements MediaRecorder.OnInfoListener {
- @Override
- public void onInfo(MediaRecorder mr, int what, int extra) {
- }
- }
-
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/MediaStoreTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/MediaStoreTest.java
deleted file mode 100644
index e073427af..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/MediaStoreTest.java
+++ /dev/null
@@ -1,21 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static android.provider.MediaStore.Images;
-import static android.provider.MediaStore.Video;
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.junit.Assert.assertThat;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class MediaStoreTest {
- @Test
- public void shouldInitializeFields() throws Exception {
- assertThat(Images.Media.EXTERNAL_CONTENT_URI.toString(), equalTo("content://media/external/images/media"));
- assertThat(Images.Media.INTERNAL_CONTENT_URI.toString(), equalTo("content://media/internal/images/media"));
- assertThat(Video.Media.EXTERNAL_CONTENT_URI.toString(), equalTo("content://media/external/video/media"));
- assertThat(Video.Media.INTERNAL_CONTENT_URI.toString(), equalTo("content://media/internal/video/media"));
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/MenuInflaterTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/MenuInflaterTest.java
deleted file mode 100644
index d75ae9a95..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/MenuInflaterTest.java
+++ /dev/null
@@ -1,34 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.view.MenuInflater;
-import com.xtremelabs.robolectric.R;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import com.xtremelabs.robolectric.tester.android.view.TestMenu;
-import com.xtremelabs.robolectric.tester.android.view.TestMenuItem;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class MenuInflaterTest {
- @Test
- public void canRetrieveMenuListAndFindMenuItemById() {
- TestMenu menu = new TestMenu(Robolectric.application);
- new MenuInflater(Robolectric.application).inflate(R.menu.test, menu);
-
- TestMenuItem testMenuItem = (TestMenuItem) menu.getItem(0);
- assertEquals("Test menu item 1", testMenuItem.getTitle().toString());
- testMenuItem.click();
-
- testMenuItem = (TestMenuItem) menu.getItem(1);
- assertEquals("Test menu item 2", testMenuItem.getTitle().toString());
- testMenuItem.click();
-
- assertNotNull(menu.findItem(R.id.test_menu_1));
- }
-
-} \ No newline at end of file
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/MessageTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/MessageTest.java
deleted file mode 100644
index 15d966a5a..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/MessageTest.java
+++ /dev/null
@@ -1,164 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.junit.Assert.*;
-
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import android.os.Bundle;
-import android.os.Handler;
-import android.os.Message;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class MessageTest {
-
- @Test
- public void testGetDataShouldLazilyCreateBundle() throws Exception {
- assertNotNull(new Message().getData());
- assertTrue(new Message().getData().isEmpty());
- }
-
- @Test
- public void testGetData() throws Exception {
- Message m = new Message();
- Bundle b = new Bundle();
- m.setData(b);
- assertThat(m.getData(), equalTo(b));
- }
-
- @Test
- public void testPeekData() throws Exception {
- assertNull(new Message().peekData());
-
- Message m = new Message();
- Bundle b = new Bundle();
- m.setData(b);
- assertThat(m.peekData(), equalTo(b));
- }
-
- @Test
- public void testGetTarget() throws Exception {
- Message m = new Message();
- Handler h = new Handler();
- m.setTarget(h);
- assertThat(m.getTarget(), equalTo(h));
- }
-
- @Test
- public void testCopyFrom() throws Exception {
- Bundle b = new Bundle();
- Message m = new Message();
- m.arg1 = 10;
- m.arg2 = 42;
- m.obj = "obj";
- m.what = 24;
- m.setData(b);
- m.setTarget(new Handler());
- Message m2 = new Message();
- m2.copyFrom(m);
-
- assertThat(m2.arg1, equalTo(m.arg1));
- assertThat(m2.arg2, equalTo(m.arg2));
- assertThat(m2.obj, equalTo(m.obj));
- assertThat(m2.what, equalTo(m.what));
- assertThat(m2.getData(), equalTo(m.getData()));
- assertNull(m2.getTarget());
- }
-
- @Test
- public void testObtain() throws Exception {
- Message m = Message.obtain();
- assertNotNull(m);
- }
-
- @Test
- public void testObtainWithHandler() throws Exception {
- Handler h = new Handler();
- Message m = Message.obtain(h);
- assertThat(m.getTarget(), equalTo(h));
- }
-
- @Test
- public void testObtainWithHandlerAndWhat() throws Exception {
- Handler h = new Handler();
- int what = 10;
- Message m = Message.obtain(h, what);
-
- assertThat(m.getTarget(), equalTo(h));
- assertThat(m.what, equalTo(what));
- assertThat(m.getTarget(), equalTo(h));
- }
-
- @Test
- public void testObtainWithHandlerWhatAndObject() throws Exception {
- Handler h = new Handler();
- int what = 10;
- Object obj = "test";
- Message m = Message.obtain(h, what, obj);
-
- assertThat(m.getTarget(), equalTo(h));
- assertThat(m.what, equalTo(what));
- assertThat(m.getTarget(), equalTo(h));
- assertThat(m.obj, equalTo(obj));
- }
-
- @Test
- public void testObtainWithHandlerWhatAndTwoArgs() throws Exception {
- Handler h = new Handler();
- int what = 2;
- int arg1 = 3;
- int arg2 = 5;
- Message m = Message.obtain(h, what, arg1, arg2);
-
- assertThat(m.getTarget(), equalTo(h));
- assertThat(m.what, equalTo(what));
- assertThat(m.arg1, equalTo(arg1));
- assertThat(m.arg2, equalTo(arg2));
- }
-
- @Test
- public void testObtainWithHandlerWhatTwoArgsAndObj() throws Exception {
- Handler h = new Handler();
- int what = 2;
- int arg1 = 3;
- int arg2 = 5;
- Object obj = "test";
- Message m = Message.obtain(h, what, arg1, arg2, obj);
-
- assertThat(m.getTarget(), equalTo(h));
- assertThat(m.what, equalTo(what));
- assertThat(m.arg1, equalTo(arg1));
- assertThat(m.arg2, equalTo(arg2));
- assertThat(m.obj, equalTo(obj));
- }
-
- @Test
- public void testObtainWithMessage() throws Exception {
- Bundle b = new Bundle();
- Message m = new Message();
- m.arg1 = 10;
- m.arg2 = 42;
- m.obj = "obj";
- m.what = 24;
- m.setData(b);
- m.setTarget(new Handler());
- Message m2 = Message.obtain(m);
-
- assertThat(m2.arg1, equalTo(m.arg1));
- assertThat(m2.arg2, equalTo(m.arg2));
- assertThat(m2.obj, equalTo(m.obj));
- assertThat(m2.what, equalTo(m.what));
- assertThat(m2.getData(), equalTo(m.getData()));
- assertThat(m2.getTarget(), equalTo(m.getTarget()));
- }
-
- @Test
- public void testSendToTarget() throws Exception {
- ShadowLooper.pauseMainLooper();
- Handler h = new Handler();
- Message.obtain(h, 123).sendToTarget();
- assertTrue(h.hasMessages(123));
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/MessengerTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/MessengerTest.java
deleted file mode 100644
index f89b44e5f..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/MessengerTest.java
+++ /dev/null
@@ -1,33 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import static org.junit.Assert.*;
-
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import android.os.Bundle;
-import android.os.Handler;
-import android.os.Message;
-import android.os.Messenger;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class MessengerTest {
-
- @Test
- public void testMessengerSend() throws Exception {
- Handler handler = new Handler();
- Messenger messenger = new Messenger(handler);
-
- ShadowLooper.pauseMainLooper();
- Message msg = Message.obtain(null, 123);
- messenger.send(msg);
-
- assertTrue(handler.hasMessages(123));
- ShadowHandler.runMainLooperOneTask();
- assertFalse(handler.hasMessages(123));
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/MimeTypeMapTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/MimeTypeMapTest.java
deleted file mode 100644
index 154fd45bf..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/MimeTypeMapTest.java
+++ /dev/null
@@ -1,97 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.webkit.MimeTypeMap;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-import static org.junit.Assert.*;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class MimeTypeMapTest {
-
- private static final String IMAGE_EXTENSION = "jpg";
- private static final String VIDEO_EXTENSION = "mp4";
- private static final String VIDEO_MIMETYPE = "video/mp4";
- private static final String IMAGE_MIMETYPE = "image/jpeg";
-
- @Test
- public void shouldResetStaticStateBetweenTests() throws Exception {
- assertFalse(MimeTypeMap.getSingleton().hasExtension(VIDEO_EXTENSION));
- shadowOf(MimeTypeMap.getSingleton()).addExtensionMimeTypMapping(VIDEO_EXTENSION, VIDEO_MIMETYPE);
- }
-
- @Test
- public void shouldResetStaticStateBetweenTests_anotherTime() throws Exception {
- assertFalse(MimeTypeMap.getSingleton().hasExtension(VIDEO_EXTENSION));
- shadowOf(MimeTypeMap.getSingleton()).addExtensionMimeTypMapping(VIDEO_EXTENSION, VIDEO_MIMETYPE);
- }
-
- @Test
- public void getSingletonShouldAlwaysReturnSameInstance() {
- MimeTypeMap firstInstance = MimeTypeMap.getSingleton();
- MimeTypeMap secondInstance = MimeTypeMap.getSingleton();
-
- assertSame(firstInstance, secondInstance);
- }
-
- @Test
- public void byDefaultThereShouldBeNoMapping() {
- assertFalse(MimeTypeMap.getSingleton().hasExtension(VIDEO_EXTENSION));
- assertFalse(MimeTypeMap.getSingleton().hasExtension(IMAGE_EXTENSION));
- }
-
- @Test
- public void addingMappingShouldWorkCorrectly() {
- ShadowMimeTypeMap shadowMimeTypeMap = Robolectric.shadowOf(MimeTypeMap.getSingleton());
- shadowMimeTypeMap.addExtensionMimeTypMapping(VIDEO_EXTENSION, VIDEO_MIMETYPE);
- shadowMimeTypeMap.addExtensionMimeTypMapping(IMAGE_EXTENSION, IMAGE_MIMETYPE);
-
- assertTrue(MimeTypeMap.getSingleton().hasExtension(VIDEO_EXTENSION));
- assertTrue(MimeTypeMap.getSingleton().hasExtension(IMAGE_EXTENSION));
- assertTrue(MimeTypeMap.getSingleton().hasMimeType(VIDEO_MIMETYPE));
- assertTrue(MimeTypeMap.getSingleton().hasMimeType(IMAGE_MIMETYPE));
-
- assertEquals(IMAGE_EXTENSION, MimeTypeMap.getSingleton().getExtensionFromMimeType(IMAGE_MIMETYPE));
- assertEquals(VIDEO_EXTENSION, MimeTypeMap.getSingleton().getExtensionFromMimeType(VIDEO_MIMETYPE));
-
- assertEquals(IMAGE_MIMETYPE, MimeTypeMap.getSingleton().getMimeTypeFromExtension(IMAGE_EXTENSION));
- assertEquals(VIDEO_MIMETYPE, MimeTypeMap.getSingleton().getMimeTypeFromExtension(VIDEO_EXTENSION));
- }
-
- @Test
- public void clearMappingsShouldRemoveAllMappings() {
- ShadowMimeTypeMap shadowMimeTypeMap = Robolectric.shadowOf(MimeTypeMap.getSingleton());
- shadowMimeTypeMap.addExtensionMimeTypMapping(VIDEO_EXTENSION, VIDEO_MIMETYPE);
- shadowMimeTypeMap.addExtensionMimeTypMapping(IMAGE_EXTENSION, IMAGE_MIMETYPE);
-
- shadowMimeTypeMap.clearMappings();
-
- assertFalse(MimeTypeMap.getSingleton().hasExtension(VIDEO_EXTENSION));
- assertFalse(MimeTypeMap.getSingleton().hasExtension(IMAGE_EXTENSION));
- assertFalse(MimeTypeMap.getSingleton().hasMimeType(VIDEO_MIMETYPE));
- assertFalse(MimeTypeMap.getSingleton().hasExtension(IMAGE_MIMETYPE));
- }
-
- @Test
- public void unknownExtensionShouldProvideNothing() {
- ShadowMimeTypeMap shadowMimeTypeMap = Robolectric.shadowOf(MimeTypeMap.getSingleton());
- shadowMimeTypeMap.addExtensionMimeTypMapping(VIDEO_EXTENSION, VIDEO_MIMETYPE);
- shadowMimeTypeMap.addExtensionMimeTypMapping(IMAGE_EXTENSION, IMAGE_MIMETYPE);
-
- assertFalse(MimeTypeMap.getSingleton().hasExtension("foo"));
- assertNull(MimeTypeMap.getSingleton().getMimeTypeFromExtension("foo"));
- }
-
- @Test
- public void unknownMimeTypeShouldProvideNothing() {
- ShadowMimeTypeMap shadowMimeTypeMap = Robolectric.shadowOf(MimeTypeMap.getSingleton());
- shadowMimeTypeMap.addExtensionMimeTypMapping(VIDEO_EXTENSION, VIDEO_MIMETYPE);
- shadowMimeTypeMap.addExtensionMimeTypMapping(IMAGE_EXTENSION, IMAGE_MIMETYPE);
-
- assertFalse(MimeTypeMap.getSingleton().hasMimeType("foo/bar"));
- assertNull(MimeTypeMap.getSingleton().getExtensionFromMimeType("foo/bar"));
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/MotionEventTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/MotionEventTest.java
deleted file mode 100644
index f9704734b..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/MotionEventTest.java
+++ /dev/null
@@ -1,83 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.view.MotionEvent;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertThat;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class MotionEventTest {
- private MotionEvent event;
- private ShadowMotionEvent shadowMotionEvent;
-
- @Before
- public void setUp() throws Exception {
- event = MotionEvent.obtain(100, 200, MotionEvent.ACTION_MOVE, 5.0f, 10.0f, 0);
- shadowMotionEvent = shadowOf(event);
- }
-
- @Test
- public void addingSecondPointerSetsCount() {
- assertThat(event.getX(0), equalTo(5.0f));
- assertThat(event.getY(0), equalTo(10.0f));
- assertThat(event.getPointerCount(), equalTo(1));
-
- shadowOf(event).setPointer2( 20.0f, 30.0f );
-
- assertThat(event.getX(1), equalTo(20.0f));
- assertThat(event.getY(1), equalTo(30.0f));
- assertThat(event.getPointerCount(), equalTo(2));
- }
-
- @Test
- public void canSetPointerIdsByIndex() {
- shadowMotionEvent.setPointer2(20.0f, 30.0f);
- shadowMotionEvent.setPointerIds(2, 5);
- assertEquals(2, event.getPointerId(0));
- assertEquals(5, event.getPointerId(1));
- }
-
- @Test
- public void indexShowsUpInAction() {
- shadowMotionEvent.setPointerIndex(1);
- assertEquals(1 << MotionEvent.ACTION_POINTER_ID_SHIFT | MotionEvent.ACTION_MOVE, event.getAction());
- }
-
- @Test
- public void canGetActionIndex() {
- assertEquals(0, event.getActionIndex());
- shadowMotionEvent.setPointerIndex(1);
- assertEquals(1, event.getActionIndex());
- }
-
- @Test
- public void getActionMaskedStripsPointerIndexFromAction() {
- assertEquals(MotionEvent.ACTION_MOVE, event.getActionMasked());
- shadowMotionEvent.setPointerIndex(1);
- assertEquals(MotionEvent.ACTION_MOVE, event.getActionMasked());
- }
-
- @Test
- public void canFindPointerIndexFromId() {
- shadowMotionEvent.setPointer2(20.0f, 30.0f);
- shadowMotionEvent.setPointerIds(2, 1);
- assertEquals(0, event.findPointerIndex(2));
- assertEquals(1, event.findPointerIndex(1));
- assertEquals(-1, event.findPointerIndex(3));
- }
-
- @Test
- public void canSetMotionEventLocation() throws Exception {
- assertEquals(5.0f, event.getX(), 0.0f);
- assertEquals(10.0f, event.getY(), 0.0f);
- shadowMotionEvent.setLocation(10.0f, 20.0f);
- assertEquals(10.0f, event.getX(), 0.0f);
- assertEquals(20.0f, event.getY(), 0.0f);
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/NdefMessageTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/NdefMessageTest.java
deleted file mode 100644
index 7afd60d68..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/NdefMessageTest.java
+++ /dev/null
@@ -1,21 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.nfc.NdefMessage;
-import android.nfc.NdefRecord;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static org.junit.Assert.assertSame;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class NdefMessageTest {
-
- @Test
- public void getRecords() throws Exception {
- NdefRecord[] ndefRecords = {new NdefRecord("mumble".getBytes())};
- NdefMessage ndefMessage = new NdefMessage(ndefRecords);
-
- assertSame(ndefMessage.getRecords(), ndefRecords);
- }
-} \ No newline at end of file
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/NdefRecordTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/NdefRecordTest.java
deleted file mode 100644
index 943ec7df4..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/NdefRecordTest.java
+++ /dev/null
@@ -1,20 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.nfc.NdefRecord;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static org.junit.Assert.assertSame;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class NdefRecordTest {
-
- @Test
- public void getPayload() throws Exception {
- byte[] bytes = "mumble".getBytes();
- NdefRecord ndefRecord = new NdefRecord(bytes);
-
- assertSame(ndefRecord.getPayload(), bytes);
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/NetworkInfoTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/NetworkInfoTest.java
deleted file mode 100644
index 0e5cf7f10..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/NetworkInfoTest.java
+++ /dev/null
@@ -1,22 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.net.NetworkInfo;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.MatcherAssert.assertThat;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class NetworkInfoTest {
-
- @Test
- public void getDetailedState_shouldReturnTheAssignedState() throws Exception {
- NetworkInfo networkInfo = Robolectric.newInstanceOf(NetworkInfo.class);
- shadowOf(networkInfo).setDetailedState(NetworkInfo.DetailedState.SCANNING);
- assertThat(networkInfo.getDetailedState(), equalTo(NetworkInfo.DetailedState.SCANNING));
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/NfcAdapterTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/NfcAdapterTest.java
deleted file mode 100644
index e985bdfe0..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/NfcAdapterTest.java
+++ /dev/null
@@ -1,17 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.nfc.NfcAdapter;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static org.hamcrest.CoreMatchers.instanceOf;
-import static org.junit.Assert.assertThat;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class NfcAdapterTest {
- @Test
- public void getDefaultAdapter_shouldReturnAnAdapter() throws Exception {
- assertThat(NfcAdapter.getDefaultAdapter(null), instanceOf(NfcAdapter.class));
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/NotificationManagerTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/NotificationManagerTest.java
deleted file mode 100644
index 695fc957b..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/NotificationManagerTest.java
+++ /dev/null
@@ -1,96 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.app.Notification;
-import android.app.NotificationManager;
-import android.content.Context;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class NotificationManagerTest {
- private NotificationManager notificationManager;
- private Notification notification1 = new Notification();
- private Notification notification2 = new Notification();
-
- @Before public void setUp() {
- notificationManager = (NotificationManager) Robolectric.application.getSystemService(Context.NOTIFICATION_SERVICE);
- }
-
- @Test
- public void testNotify() throws Exception {
- notificationManager.notify(1, notification1);
- assertEquals(1, shadowOf(notificationManager).size());
- assertEquals(notification1, shadowOf(notificationManager).getNotification(1));
-
- notificationManager.notify(31, notification2);
- assertEquals(2, shadowOf(notificationManager).size());
- assertEquals(notification2, shadowOf(notificationManager).getNotification(31));
- }
-
- @Test
- public void testNotifyReplaces() throws Exception {
- notificationManager.notify(1, notification1);
-
- notificationManager.notify(1, notification2);
- assertEquals(1, shadowOf(notificationManager).size());
- assertEquals(notification2, shadowOf(notificationManager).getNotification(1));
- }
-
- @Test
- public void testNotifyWithTag() throws Exception {
- notificationManager.notify("a tag", 1, notification1);
- assertEquals(1, shadowOf(notificationManager).size());
- assertEquals(notification1, shadowOf(notificationManager).getNotification("a tag"));
- }
-
- @Test
- public void notifyWithTag_shouldReturnNullForNullTag() throws Exception {
- notificationManager.notify("a tag", 1, notification1);
- assertEquals(1, shadowOf(notificationManager).size());
- assertNull(shadowOf(notificationManager).getNotification(null));
- }
-
- @Test
- public void notifyWithTag_shouldReturnNullForUnknownTag() throws Exception {
- notificationManager.notify("a tag", 1, notification1);
- assertEquals(1, shadowOf(notificationManager).size());
- assertNull(shadowOf(notificationManager).getNotification("unknown tag"));
- }
-
- @Test
- public void testCancel() throws Exception {
- notificationManager.notify(1, notification1);
- notificationManager.cancel(1);
-
- assertEquals(0, shadowOf(notificationManager).size());
- assertNull(shadowOf(notificationManager).getNotification(1));
- }
-
- @Test
- public void testCancelWithTag() throws Exception {
- notificationManager.notify("a tag", 1, notification1);
- notificationManager.cancel("a tag", 1);
-
- assertEquals(0, shadowOf(notificationManager).size());
- assertNull(shadowOf(notificationManager).getNotification(1));
- assertNull(shadowOf(notificationManager).getNotification("a tag"));
- }
-
- @Test
- public void testCancelAll() throws Exception {
- notificationManager.notify(1, notification1);
- notificationManager.notify(31, notification2);
- notificationManager.cancelAll();
-
- assertEquals(0, shadowOf(notificationManager).size());
- assertNull(shadowOf(notificationManager).getNotification(1));
- assertNull(shadowOf(notificationManager).getNotification(31));
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/NotificationTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/NotificationTest.java
deleted file mode 100644
index 03b2b3d01..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/NotificationTest.java
+++ /dev/null
@@ -1,23 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.app.Activity;
-import android.app.Notification;
-import android.app.PendingIntent;
-import android.content.Intent;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static org.hamcrest.core.Is.is;
-import static org.junit.Assert.assertThat;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class NotificationTest {
- @Test
- public void setLatestEventInfo__shouldCaptureContentIntent() throws Exception {
- PendingIntent pendingIntent = PendingIntent.getActivity(new Activity(), 0, new Intent(), 0);
- Notification notification = new Notification();
- notification.setLatestEventInfo(new Activity(), "title", "content", pendingIntent);
- assertThat(pendingIntent, is(notification.contentIntent));
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/PagerAdapterTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/PagerAdapterTest.java
deleted file mode 100644
index 6f9d9810b..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/PagerAdapterTest.java
+++ /dev/null
@@ -1,44 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.database.DataSetObserver;
-import android.support.v4.view.PagerAdapter;
-import android.view.View;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-import static junit.framework.Assert.assertTrue;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class PagerAdapterTest {
- @Test
- public void shouldNotifyDataSetChanged() throws Exception {
- PagerAdapter pagerAdapter = new NullPagerAdapter();
- TestDataSetObserver datasetObserver= new TestDataSetObserver();
- shadowOf(pagerAdapter).registerDataSetObserver(datasetObserver);
- pagerAdapter.notifyDataSetChanged();
-
- assertTrue(datasetObserver.onChangedWasCalled);
- }
-
- private static class NullPagerAdapter extends PagerAdapter {
- @Override
- public int getCount() {
- return 0;
- }
-
- @Override
- public boolean isViewFromObject(View view, Object object) {
- return false;
- }
- }
-
- private class TestDataSetObserver extends DataSetObserver {
- boolean onChangedWasCalled;
- @Override
- public void onChanged() {
- onChangedWasCalled = true;
- }
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/PaintTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/PaintTest.java
deleted file mode 100644
index 42b8d056e..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/PaintTest.java
+++ /dev/null
@@ -1,44 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import android.graphics.Paint;
-
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-import static org.junit.Assert.*;
-
-
-@RunWith(WithTestDefaultsRunner.class)
-public class PaintTest {
-
- @Test
- public void shouldGetIsDitherInfo() {
- Paint paint = Robolectric.newInstanceOf(Paint.class);
- assertFalse(paint.isAntiAlias());
- ShadowPaint shadowPaint = shadowOf(paint);
- shadowPaint.setAntiAlias(true);
- assertTrue(paint.isAntiAlias());
- }
-
- @Test
- public void shouldGetIsAntiAlias() {
- Paint paint = Robolectric.newInstanceOf(Paint.class);
- assertFalse(paint.isAntiAlias());
- ShadowPaint shadowPaint = shadowOf(paint);
- shadowPaint.setAntiAlias(true);
- assertTrue(paint.isAntiAlias());
- }
-
- @Test
- public void testCtor() {
- Paint paint = Robolectric.newInstanceOf(Paint.class);
- assertFalse(paint.isAntiAlias());
- ShadowPaint shadowPaint = shadowOf(paint);
- shadowPaint.__constructor__( Paint.ANTI_ALIAS_FLAG );
- assertTrue(paint.isAntiAlias());
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/PairTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/PairTest.java
deleted file mode 100644
index 763ea1838..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/PairTest.java
+++ /dev/null
@@ -1,38 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.junit.Assert.assertThat;
-
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import android.util.Pair;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class PairTest {
-
- @Test
- public void testConstructor() throws Exception {
- Pair<String, Integer> pair = new Pair<String, Integer>("a", 1);
- assertThat(pair.first, equalTo("a"));
- assertThat(pair.second, equalTo(1));
- }
-
- @Test
- public void testStaticCreate() throws Exception {
- Pair<String, String> p = Pair.create("Foo", "Bar");
- assertThat(p.first, equalTo("Foo"));
- assertThat(p.second, equalTo("Bar"));
- }
-
- @Test
- public void testEquals() throws Exception {
- assertThat(Pair.create("1", 2), equalTo(Pair.create("1", 2)));
- }
-
- @Test
- public void testHash() throws Exception {
- assertThat(Pair.create("1", 2).hashCode(), equalTo(Pair.create("1", 2).hashCode()));
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ParcelTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/ParcelTest.java
deleted file mode 100644
index 763be0d77..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ParcelTest.java
+++ /dev/null
@@ -1,513 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.CoreMatchers.notNullValue;
-import static org.hamcrest.CoreMatchers.nullValue;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertThat;
-import static org.junit.Assert.assertTrue;
-
-import android.accounts.Account;
-import android.content.Intent;
-import android.os.Bundle;
-import android.os.Parcel;
-
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class ParcelTest {
-
- private Parcel parcel;
- private ShadowParcel shadowParcel;
-
- @Before
- public void setup() {
- parcel = Parcel.obtain();
- shadowParcel = Robolectric.shadowOf(parcel);
- }
-
- @Test
- public void testObtain() {
- assertThat(parcel, notNullValue());
- assertThat(shadowParcel.getIndex(), equalTo(0));
- assertThat(shadowParcel.getParcelData().size(), equalTo(0));
- }
-
- @Test
- public void testReadIntWhenEmpty() {
- assertThat(parcel.readInt(), equalTo(0));
- }
-
- @Test
- public void testReadLongWhenEmpty() {
- assertThat(parcel.readLong(), equalTo(0l));
- }
-
- @Test
- public void testReadStringWhenEmpty() {
- assertThat(parcel.readString(), nullValue());
- }
-
- @Test
- public void testReadWriteSingleString() {
- String val = "test";
- parcel.writeString(val);
- parcel.setDataPosition(0);
- assertThat(parcel.readString(), equalTo(val));
- }
-
- @Test
- public void testWriteNullString() {
- parcel.writeString( null );
- parcel.setDataPosition(0);
- assertThat( parcel.readString(), nullValue() );
- assertThat( shadowParcel.getIndex(), equalTo( 1 ) );
- assertThat( shadowParcel.getParcelData().size(), equalTo( 1 ) );
- }
-
- @Test
- public void testReadWriteMultipleStrings() {
- for (int i = 0; i < 10; ++i) {
- parcel.writeString(Integer.toString(i));
- }
- parcel.setDataPosition(0);
- for (int i = 0; i < 10; ++i) {
- assertThat(parcel.readString(), equalTo(Integer.toString(i)));
- }
- // now try to read past the number of items written and see what happens
- assertThat(parcel.readString(), nullValue());
- }
-
- @Test
- public void testReadWriteSingleInt() {
- int val = 5;
- parcel.writeInt(val);
- parcel.setDataPosition(0);
- assertThat(parcel.readInt(), equalTo(val));
- }
-
- @Test
- public void testReadWriteIntArray() throws Exception {
- final int[] ints = {1, 2};
- parcel.writeIntArray(ints);
- parcel.setDataPosition(0);
- final int[] ints2 = new int[ints.length];
- parcel.readIntArray(ints2);
- assertTrue(Arrays.equals(ints, ints2));
- }
-
- @Test
- public void testReadWriteLongArray() throws Exception {
- final long[] longs = {1, 2};
- parcel.writeLongArray(longs);
- parcel.setDataPosition(0);
- final long[] longs2 = new long[longs.length];
- parcel.readLongArray(longs2);
- assertTrue(Arrays.equals(longs, longs2));
- }
-
- @Test
- public void testReadWriteSingleFloat() {
- float val = 5.2f;
- parcel.writeFloat(val);
- parcel.setDataPosition(0);
- assertThat(parcel.readFloat(), equalTo(val));
- }
-
- @Test
- public void testReadWriteFloatArray() throws Exception {
- final float[] floats = {1.1f, 2.0f};
- parcel.writeFloatArray(floats);
- parcel.setDataPosition(0);
- final float[] floats2 = new float[floats.length];
- parcel.readFloatArray(floats2);
- assertTrue(Arrays.equals(floats, floats2));
- }
-
- @Test
- public void testReadWriteDoubleArray() throws Exception {
- final double[] doubles = {1.1f, 2.0f};
- parcel.writeDoubleArray(doubles);
- parcel.setDataPosition(0);
- final double[] doubles2 = new double[doubles.length];
- parcel.readDoubleArray(doubles2);
- assertTrue(Arrays.equals(doubles, doubles2));
- }
-
- @Test
- public void testReadWriteStringArray() throws Exception {
- final String[] strings = {"foo", "bar"};
- parcel.writeStringArray(strings);
- parcel.setDataPosition(0);
- final String[] strings2 = new String[strings.length];
- parcel.readStringArray(strings2);
- assertTrue(Arrays.equals(strings, strings2));
- }
-
- @Test
- public void testReadWriteMultipleInts() {
- for (int i = 0; i < 10; ++i) {
- parcel.writeInt(i);
- }
- parcel.setDataPosition(0);
- for (int i = 0; i < 10; ++i) {
- assertThat(parcel.readInt(), equalTo(i));
- }
- // now try to read past the number of items written and see what happens
- assertThat(parcel.readInt(), equalTo(0));
- }
-
- @Test
- public void testReadWriteSingleByte() {
- byte val = 1;
- parcel.writeByte(val);
- parcel.setDataPosition(0);
- assertThat(parcel.readByte(), equalTo(val));
- }
-
- @Test
- public void testReadWriteMultipleBytes() {
- for (byte i = Byte.MIN_VALUE; i < Byte.MAX_VALUE; ++i) {
- parcel.writeByte(i);
- }
- parcel.setDataPosition(0);
- for (byte i = Byte.MIN_VALUE; i < Byte.MAX_VALUE; ++i) {
- assertThat(parcel.readByte(), equalTo(i));
- }
- // now try to read past the number of items written and see what happens
- assertThat(parcel.readByte(), equalTo((byte) 0));
- }
-
-
- @Test
- public void testReadWriteStringInt() {
- for (int i = 0; i < 10; ++i) {
- parcel.writeString(Integer.toString(i));
- parcel.writeInt(i);
- }
- parcel.setDataPosition(0);
- for (int i = 0; i < 10; ++i) {
- assertThat(parcel.readString(), equalTo(Integer.toString(i)));
- assertThat(parcel.readInt(), equalTo(i));
- }
- // now try to read past the number of items written and see what happens
- assertThat(parcel.readString(), nullValue());
- assertThat(parcel.readInt(), equalTo(0));
- }
-
- @Test
- public void testReadWriteSingleLong() {
- long val = 5;
- parcel.writeLong(val);
- parcel.setDataPosition(0);
- assertThat(parcel.readLong(), equalTo(val));
- }
-
- @Test
- public void testReadWriteMultipleLongs() {
- for (long i = 0; i < 10; ++i) {
- parcel.writeLong(i);
- }
- parcel.setDataPosition(0);
- for (long i = 0; i < 10; ++i) {
- assertThat(parcel.readLong(), equalTo(i));
- }
- // now try to read past the number of items written and see what happens
- assertThat(parcel.readLong(), equalTo(0l));
- }
-
- @Test
- public void testReadWriteStringLong() {
- for (long i = 0; i < 10; ++i) {
- parcel.writeString(Long.toString(i));
- parcel.writeLong(i);
- }
- parcel.setDataPosition(0);
- for (long i = 0; i < 10; ++i) {
- assertThat(parcel.readString(), equalTo(Long.toString(i)));
- assertThat(parcel.readLong(), equalTo(i));
- }
- // now try to read past the number of items written and see what happens
- assertThat(parcel.readString(), nullValue());
- assertThat(parcel.readLong(), equalTo(0l));
- }
-
- @Test
- public void testReadWriteParcelable() {
- Intent i1 = new Intent("anAction");
- parcel.writeParcelable(i1, 0);
-
- parcel.setDataPosition(0);
-
- Intent i2 = parcel.readParcelable(Intent.class.getClassLoader());
- assertEquals(i1, i2);
- }
-
- @Test
- public void testReadWriteSimpleBundle() {
- Bundle b1 = new Bundle();
- b1.putString("hello", "world");
- parcel.writeBundle(b1);
- parcel.setDataPosition(0);
- Bundle b2 = parcel.readBundle();
-
- assertEquals(b1, b2);
- assertEquals("world", b2.getString("hello"));
-
- parcel.setDataPosition(0);
- parcel.writeBundle(b1);
- parcel.setDataPosition(0);
- b2 = parcel.readBundle(null /* ClassLoader */);
- assertEquals(b1, b2);
- assertEquals("world", b2.getString("hello"));
- }
-
- @Test
- public void testReadWriteNestedBundles() {
- Account account = new Account("accountName", "accountType");
- Bundle innerBundle = new Bundle();
- innerBundle.putString("hello", "world");
- innerBundle.putParcelable("account", account);
- Bundle b1 = new Bundle();
- b1.putBundle("bundle", innerBundle);
- b1.putInt("int", 23);
- parcel.writeBundle(b1);
- parcel.setDataPosition(0);
- Bundle b2 = parcel.readBundle();
-
- assertEquals(b1, b2);
- assertEquals(innerBundle, b2.getBundle("bundle"));
- assertEquals(23, b2.getInt("int"));
- assertEquals("world", b2.getBundle("bundle").getString("hello"));
-
- parcel.setDataPosition(0);
- parcel.writeBundle(b1);
- parcel.setDataPosition(0);
- b2 = parcel.readBundle(null /* ClassLoader */);
- assertEquals(b1, b2);
- assertEquals(innerBundle, b2.getBundle("bundle"));
- assertEquals(23, b2.getInt("int"));
- assertEquals("world", b2.getBundle("bundle").getString("hello"));
- }
-
- @Test
- public void testReadWriteBundleWithDifferentValueTypes() {
- Bundle b1 = new Bundle();
- b1.putString("hello", "world");
- b1.putBoolean("boolean", true);
- b1.putByte("byte", (byte) 0xAA);
- b1.putShort("short", (short)0xBABE);
- b1.putInt("int", 1);
- b1.putFloat("float", 0.5f);
- b1.putDouble("double", 1.25);
- parcel.writeBundle(b1);
- parcel.setDataPosition(0);
-
- Bundle b2 = parcel.readBundle();
-
- assertEquals(b1, b2);
- assertEquals("world", b2.getString("hello"));
- assertEquals(true, b2.getBoolean("boolean"));
- assertEquals((byte) 0xAA, b2.getByte("byte"));
- assertEquals((short) 0xBABE, b2.getShort("short"));
- assertEquals(1, b2.getInt("int"));
- assertEquals(0.5f, b2.getFloat("float"), 0.05);
- assertEquals(1.25, b2.getDouble("double"), 0.05);
-
- parcel.setDataPosition(0);
- parcel.writeBundle(b1);
- parcel.setDataPosition(0);
- b2 = parcel.readBundle(null /* ClassLoader */);
- assertEquals(b1, b2);
- assertEquals("world", b2.getString("hello"));
- assertEquals(true, b2.getBoolean("boolean"));
- assertEquals((byte) 0xAA, b2.getByte("byte"));
- assertEquals((short) 0xBABE, b2.getShort("short"));
- assertEquals(1, b2.getInt("int"));
- assertEquals(0.5f, b2.getFloat("float"), 0.05);
- assertEquals(1.25, b2.getDouble("double"), 0.05);
- }
-
- @Test
- public void testWriteCreateStringArray() {
- final String[] strings = { "foo", "bar" };
- parcel.writeStringArray(strings);
- parcel.setDataPosition(0);
- final String[] strings2 = parcel.createStringArray();
- assertTrue(Arrays.equals(strings, strings2));
- }
-
- @Test
- public void testReadWriteStringList() {
- final List<String> strings = Arrays.asList( "foo", "bar" );
- parcel.writeStringList(strings);
- parcel.setDataPosition(0);
- List<String> extractedStrings = new ArrayList<String>();
- parcel.readStringList(extractedStrings);
- assertEquals(strings, extractedStrings);
- }
-
- @Test
- public void testWriteCreateStringArrayList() {
- final List<String> strings = Arrays.asList( "foo", "bar" );
- parcel.writeStringList(strings);
- parcel.setDataPosition(0);
- List<String> extractedStrings = parcel.createStringArrayList();
- assertEquals(strings, extractedStrings);
- }
-
- @Test
- public void testReadWriteByteArray() throws Exception {
- final byte[] bytes = {1, 2};
- parcel.writeByteArray(bytes);
- parcel.setDataPosition(0);
- final byte[] bytes2 = new byte[bytes.length];
- parcel.readByteArray(bytes2);
- assertTrue(Arrays.equals(bytes, bytes2));
- }
-
- @Test
- public void testReadWriteBooleanArray() {
- final boolean[] booleans = {false, true, true};
- parcel.writeBooleanArray(booleans);
- parcel.setDataPosition(0);
- final boolean[] booleans2 = new boolean[booleans.length];
- parcel.readBooleanArray(booleans2);
- assertTrue(Arrays.equals(booleans, booleans2));
- }
-
- @Test
- public void testReadWriteCharArray() {
- final char[] chars = {'a', 'b', 'c'};
- parcel.writeCharArray(chars);
- parcel.setDataPosition(0);
- final char[] chars2 = new char[chars.length];
- parcel.readCharArray(chars2);
- assertTrue(Arrays.equals(chars, chars2));
- }
-
- @Test
- public void testWriteCreateBooleanArray() {
- final boolean[] booleans = {false, true, true};
- parcel.writeBooleanArray(booleans);
- parcel.setDataPosition(0);
- final boolean[] booleans2 = parcel.createBooleanArray();
- assertTrue(Arrays.equals(booleans, booleans2));
- }
-
- @Test
- public void testWriteCreateByteArray() {
- final byte[] bytes = {1, 2};
- parcel.writeByteArray(bytes);
- parcel.setDataPosition(0);
- final byte[] bytes2 = parcel.createByteArray();
- assertTrue(Arrays.equals(bytes, bytes2));
- }
-
- @Test
- public void testWriteCreateCharArray() {
- final char[] chars = {'a', 'b', 'c'};
- parcel.writeCharArray(chars);
- parcel.setDataPosition(0);
- final char[] chars2 = parcel.createCharArray();
- assertTrue(Arrays.equals(chars, chars2));
- }
-
- @Test
- public void testWriteCreateIntArray() {
- final int[] ints = {1, 2};
- parcel.writeIntArray(ints);
- parcel.setDataPosition(0);
- final int[] ints2 = parcel.createIntArray();
- assertTrue(Arrays.equals(ints, ints2));
- }
-
- @Test
- public void testWriteCreateLongArray() {
- final long[] longs = {1, 2};
- parcel.writeLongArray(longs);
- parcel.setDataPosition(0);
- final long[] longs2 = parcel.createLongArray();
- assertTrue(Arrays.equals(longs, longs2));
- }
-
- @Test
- public void testWriteCreateFloatArray() {
- final float[] floats = {1.5f, 2.25f};
- parcel.writeFloatArray(floats);
- parcel.setDataPosition(0);
- final float[] floats2 = parcel.createFloatArray();
- assertTrue(Arrays.equals(floats, floats2));
- }
-
- @Test
- public void testWriteCreateDoubleArray() {
- final double[] doubles = {1.2, 2.2};
- parcel.writeDoubleArray(doubles);
- parcel.setDataPosition(0);
- final double[] doubles2 = parcel.createDoubleArray();
- assertTrue(Arrays.equals(doubles, doubles2));
- }
-
- @Test
- public void testDataPositionAfterStringWrite() {
- parcel.writeString("string");
- assertEquals(10, parcel.dataPosition());
- }
-
- @Test
- public void testDataPositionAfterByteWrite() {
- parcel.writeByte((byte) 0);
- assertEquals(1, parcel.dataPosition());
- }
-
- @Test
- public void testDataPositionAfterIntWrite() {
- parcel.writeInt(1);
- assertEquals(4, parcel.dataPosition());
- }
-
- @Test
- public void testDataPositionAfterLongWrite() {
- parcel.writeLong(23);
- assertEquals(8, parcel.dataPosition());
- }
-
- @Test
- public void testDataPositionAfterFloatWrite() {
- parcel.writeFloat(0.5f);
- assertEquals(4, parcel.dataPosition());
- }
-
- @Test
- public void testDataPositionAfterDoubleWrite() {
- parcel.writeDouble(8.8);
- assertEquals(8, parcel.dataPosition());
- }
-
- @Test
- public void testResetDataPositionAfterWrite() {
- parcel.writeInt(4);
- parcel.setDataPosition(0);
- assertEquals(0, parcel.dataPosition());
- }
-
- @Test
- public void testOverwritePreviousValue() {
- parcel.writeInt(4);
- parcel.setDataPosition(0);
- parcel.writeInt(34);
- parcel.setDataPosition(0);
- assertEquals(34, parcel.readInt());
- assertEquals(4, parcel.dataSize());
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/PasswordTransformationMethodTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/PasswordTransformationMethodTest.java
deleted file mode 100644
index da38879b3..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/PasswordTransformationMethodTest.java
+++ /dev/null
@@ -1,56 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.hamcrest.CoreMatchers;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.MatcherAssert.assertThat;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class PasswordTransformationMethodTest {
-
- private ShadowPasswordTransformationMethod transformationMethod;
-
- @Before
- public void setUp(){
- transformationMethod = new ShadowPasswordTransformationMethod();
- }
-
- @Test
- public void shouldMaskInputCharacters(){
- CharSequence output = transformationMethod.getTransformation("foobar", null);
- assertThat(output.toString(), is("\u2022\u2022\u2022\u2022\u2022\u2022")); //using the escaped characters for cross platform compatibility.
- }
-
- @Test
- public void shouldTransformSpacesWithText(){
- CharSequence output = transformationMethod.getTransformation(" baz ", null);
- assertThat(output.toString(), is("\u2022\u2022\u2022\u2022\u2022"));
- }
-
- @Test
- public void shouldTransformSpacesWithoutText(){
- CharSequence output = transformationMethod.getTransformation(" ", null);
- assertThat(output.toString(), is("\u2022\u2022\u2022\u2022"));
- }
-
- @Test
- public void shouldNotTransformBlank(){
- CharSequence output = transformationMethod.getTransformation("", null);
- assertThat(output.toString(), is(""));
- }
-
- @Test
- public void shouldNotTransformNull(){
- CharSequence output = transformationMethod.getTransformation(null, null);
- assertThat(output.toString(), is(""));
- }
-
- @Test
- public void shouldRetrieveAnInstance(){
- assertThat(ShadowPasswordTransformationMethod.getInstance(), is(CoreMatchers.<Object>notNullValue()));
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/PathTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/PathTest.java
deleted file mode 100644
index 23b10e58d..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/PathTest.java
+++ /dev/null
@@ -1,51 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.graphics.Path;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import java.util.List;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-import static com.xtremelabs.robolectric.shadows.ShadowPath.Point.Type.LINE_TO;
-import static com.xtremelabs.robolectric.shadows.ShadowPath.Point.Type.MOVE_TO;
-import static org.junit.Assert.assertEquals;
-
-
-@RunWith(WithTestDefaultsRunner.class)
-public class PathTest {
-
- @Test
- public void testGradTo() {
- Path path = Robolectric.newInstanceOf(Path.class);
- path.quadTo(0, 5, 10, 15);
- ShadowPath shadowPath = shadowOf(path);
- assertEquals(shadowPath.getQuadDescription(), "Add a quadratic bezier from last point, approaching (0.0,5.0), ending at (10.0,15.0)");
- }
-
- @Test
- public void testMoveTo() throws Exception {
- Path path = Robolectric.newInstanceOf(Path.class);
- path.moveTo(2, 3);
- path.moveTo(3, 4);
-
- List<ShadowPath.Point> moveToPoints = shadowOf(path).getPoints();
- assertEquals(2, moveToPoints.size());
- assertEquals(new ShadowPath.Point(2, 3, MOVE_TO), moveToPoints.get(0));
- assertEquals(new ShadowPath.Point(3, 4, MOVE_TO), moveToPoints.get(1));
- }
-
- @Test
- public void testLineTo() throws Exception {
- Path path = Robolectric.newInstanceOf(Path.class);
- path.lineTo(2, 3);
- path.lineTo(3, 4);
-
- List<ShadowPath.Point> lineToPoints = shadowOf(path).getPoints();
- assertEquals(2, lineToPoints.size());
- assertEquals(new ShadowPath.Point(2, 3, LINE_TO), lineToPoints.get(0));
- assertEquals(new ShadowPath.Point(3, 4, LINE_TO), lineToPoints.get(1));
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/PendingIntentTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/PendingIntentTest.java
deleted file mode 100644
index 154307b03..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/PendingIntentTest.java
+++ /dev/null
@@ -1,138 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.CoreMatchers.not;
-import static org.hamcrest.CoreMatchers.sameInstance;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertThat;
-
-import android.app.Activity;
-import android.app.PendingIntent;
-import android.content.Intent;
-import android.content.IntentSender;
-import android.content.TestIntentSender;
-import android.os.Parcel;
-
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class PendingIntentTest {
- @Test
- public void shouldGetIntentSender() {
- Intent expectedIntent = new Intent();
- PendingIntent service = PendingIntent.getService(null, 0, expectedIntent, 0);
-
- IntentSender intentSender = service.getIntentSender();
- assertThat(expectedIntent, equalTo(((TestIntentSender) intentSender).intent));
- }
-
- @Test
- public void getBroadcast__shouldCreateIntentForBroadcast() throws Exception {
- Intent intent = new Intent();
- PendingIntent pendingIntent = PendingIntent.getBroadcast(Robolectric.application, 99, intent, 100);
- ShadowPendingIntent shadow = shadowOf(pendingIntent);
- assertThat(shadow.isActivityIntent(), is(false));
- assertThat(shadow.isBroadcastIntent(), is(true));
- assertThat(shadow.isServiceIntent(), is(false));
- assertThat(intent, equalTo(shadow.getSavedIntent()));
- assertThat(Robolectric.application, equalTo(shadow.getSavedContext()));
- }
-
- @Test
- public void getActivity__shouldCreateIntentForBroadcast() throws Exception {
- Intent intent = new Intent();
- PendingIntent pendingIntent = PendingIntent.getActivity(Robolectric.application, 99, intent, 100);
- ShadowPendingIntent shadow = shadowOf(pendingIntent);
- assertThat(shadow.isActivityIntent(), is(true));
- assertThat(shadow.isBroadcastIntent(), is(false));
- assertThat(shadow.isServiceIntent(), is(false));
- assertThat(intent, equalTo(shadow.getSavedIntent()));
- assertThat(Robolectric.application, equalTo(shadow.getSavedContext()));
- }
-
- @Test
- public void getService__shouldCreateIntentForBroadcast() throws Exception {
- Intent intent = new Intent();
- PendingIntent pendingIntent = PendingIntent.getService(Robolectric.application, 99, intent, 100);
- ShadowPendingIntent shadow = shadowOf(pendingIntent);
- assertThat(shadow.isActivityIntent(), is(false));
- assertThat(shadow.isBroadcastIntent(), is(false));
- assertThat(shadow.isServiceIntent(), is(true));
- assertThat(intent, equalTo(shadow.getSavedIntent()));
- assertThat(Robolectric.application, equalTo(shadow.getSavedContext()));
- }
-
- @Test
- public void send__shouldFillInIntentData() throws Exception {
- Intent intent = new Intent();
- Activity context = new Activity();
- PendingIntent forActivity = PendingIntent.getActivity(context, 99, intent, 100);
-
- Activity otherContext = new Activity();
- Intent fillIntent = new Intent();
- fillIntent.putExtra("TEST", 23);
- forActivity.send(otherContext, 0, fillIntent);
-
- Intent i = shadowOf(otherContext).getNextStartedActivity();
- assertThat(i, sameInstance(intent));
- assertThat(i.getIntExtra("TEST", -1), equalTo(23));
- }
-
- @Test
- public void testEquals() throws Exception {
- PendingIntent pi1 = PendingIntent.getActivity(Robolectric.application, 99,
- new Intent("action"), 100);
- PendingIntent pi2 = PendingIntent.getActivity(null, 99, new Intent("action"), 100);
- PendingIntent pi3 = PendingIntent.getService(Robolectric.application, 99,
- new Intent("action"), 100);
- assertThat(pi1, equalTo(pi2));
- assertThat(pi1, not(equalTo(pi3)));
- }
-
- @Test
- public void parcelIo_nullPendingIntent() {
- verifyPendingIntentReadIsWhatWasWrittenToParcel(null);
- }
-
- @Test
- public void parcelIo_shouldGetBackBroadcastIntentWrittenToParcelWithNullIntent() {
- verifyPendingIntentReadIsWhatWasWrittenToParcel(PendingIntent
- .getBroadcast(Robolectric.application, 99, null, 100));
- }
-
- @Test
- public void parcelIo_shouldGetBackBroadcastIntentWrittenToParcel() {
- verifyPendingIntentReadIsWhatWasWrittenToParcel(PendingIntent
- .getBroadcast(Robolectric.application, 99, new Intent(), 100));
- }
-
- @Test
- public void parcelIo_shouldGetBackActivityIntentWrittenToParcel() {
- verifyPendingIntentReadIsWhatWasWrittenToParcel(PendingIntent
- .getActivity(Robolectric.application, 99, new Intent(), 100));
- }
-
- @Test
- public void parcelIo_shouldGetBackServiceIntentWrittenToParcel() {
- verifyPendingIntentReadIsWhatWasWrittenToParcel(PendingIntent
- .getService(Robolectric.application, 99, new Intent(), 100));
- }
-
- private void verifyPendingIntentReadIsWhatWasWrittenToParcel(PendingIntent expected) {
- Parcel parcel = Parcel.obtain();
- PendingIntent.writePendingIntentOrNullToParcel(expected, parcel);
- parcel.setDataPosition(0);
- PendingIntent actual = PendingIntent.readPendingIntentOrNullFromParcel(parcel);
- if (expected == null) {
- assertNull(actual);
- } else {
- assertThat(expected, equalTo(actual));
- }
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/PeriodicSyncTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/PeriodicSyncTest.java
deleted file mode 100644
index 71a0353b5..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/PeriodicSyncTest.java
+++ /dev/null
@@ -1,29 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.accounts.Account;
-import android.content.PeriodicSync;
-import android.os.Bundle;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.CoreMatchers.is;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertThat;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class PeriodicSyncTest {
-
- @Test
- public void shouldHaveConstructor() throws Exception {
- Account a = new Account("a", "b");
- PeriodicSync sync = new PeriodicSync(a, "auth",
- new Bundle(), 120l);
-
- assertThat(sync.account, is(a));
- assertThat(sync.authority, equalTo("auth"));
- assertThat(sync.period, equalTo(120l));
- assertNotNull(sync.extras);
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/PhoneNumberUtilTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/PhoneNumberUtilTest.java
deleted file mode 100644
index b9014cf4c..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/PhoneNumberUtilTest.java
+++ /dev/null
@@ -1,23 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.telephony.PhoneNumberUtils;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.MatcherAssert.assertThat;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class PhoneNumberUtilTest {
- @Test
- public void testFormatNumber() {
- assertThat(PhoneNumberUtils.formatNumber("12345678901"), equalTo("12345678901-formatted"));
- }
-
- @Test
- public void testStripSeparators() {
- assertThat(PhoneNumberUtils.stripSeparators("12345678901"), equalTo("12345678901-stripped"));
- }
-
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/PopupWindowTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/PopupWindowTest.java
deleted file mode 100644
index bca27e2db..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/PopupWindowTest.java
+++ /dev/null
@@ -1,178 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.content.Context;
-import android.graphics.drawable.BitmapDrawable;
-import android.view.MotionEvent;
-import android.view.View;
-import android.widget.PopupWindow;
-import com.xtremelabs.robolectric.R;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import com.xtremelabs.robolectric.tester.android.view.TestWindowManager;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.experimental.runners.Enclosed;
-import org.junit.runner.RunWith;
-
-import static android.view.MotionEvent.ACTION_DOWN;
-import static android.view.MotionEvent.obtain;
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-import static junit.framework.Assert.assertEquals;
-import static junit.framework.Assert.assertNotNull;
-import static junit.framework.Assert.assertSame;
-import static org.hamcrest.CoreMatchers.is;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.*;
-import static org.junit.Assert.assertTrue;
-
-@RunWith(Enclosed.class)
-public class PopupWindowTest {
-
- @RunWith(WithTestDefaultsRunner.class)
- public static class WithoutContentView {
-
- private PopupWindow popupWindow;
-
- @Before
- public void beforeTests() {
- popupWindow = new PopupWindow();
- }
-
- @Test
- public void testSetContentView() {
- View contentView = new View(null);
- popupWindow.setContentView(contentView);
-
- assertThat(popupWindow.getContentView(), is(contentView));
- }
-
- @Test
- public void testSetWidth() {
- popupWindow.setWidth(1);
-
- assertThat(popupWindow.getWidth(), is(1));
- }
-
- @Test
- public void testSetHeight() {
- popupWindow.setHeight(2);
-
- assertThat(popupWindow.getHeight(), is(2));
- }
-
- @Test
- public void testSetFocusable() {
- popupWindow.setFocusable(true);
-
- assertTrue(popupWindow.isFocusable());
- }
-
- @Test
- public void testSetTouchable() {
- popupWindow.setTouchable(true);
-
- assertTrue(popupWindow.isTouchable());
- }
-
- @Test
- public void testSetOutsideTouchable() {
- popupWindow.setOutsideTouchable(true);
-
- assertTrue(popupWindow.isOutsideTouchable());
- }
-
- @Test
- public void testShowing() {
- shadowOf(popupWindow).setShowing(true);
-
- assertTrue(popupWindow.isShowing());
- }
-
- @Test
- public void testDismiss() {
- shadowOf(popupWindow).setShowing(true);
-
- assertTrue(popupWindow.isShowing());
-
- popupWindow.dismiss();
-
- assertFalse(popupWindow.isShowing());
- }
-
- @SuppressWarnings("RedundantCast") //For some reason this is needed because of a compile error without it
- @Test
- public void testBackgroundDrawable() {
- BitmapDrawable bitmapDrawable = new BitmapDrawable();
- popupWindow.setBackgroundDrawable(bitmapDrawable);
-
- assertThat((BitmapDrawable) popupWindow.getBackground(), is(bitmapDrawable));
- }
-
- @Test
- public void testTouchInterceptor() {
- popupWindow.setTouchInterceptor(new View.OnTouchListener() {
- @Override
- public boolean onTouch(View v, MotionEvent event) {
- return event.getAction() == ACTION_DOWN;
- }
- });
-
- assertTrue(shadowOf(popupWindow).dispatchTouchEvent(obtain(1, 1, ACTION_DOWN, 1f, 1f, 0)));
- }
- }
-
- @RunWith(WithTestDefaultsRunner.class)
- public static class WithContentView {
-
- private TestWindowManager windowManager;
- private View contentView;
- private View anchor;
-
- @Before
- public void setUp() throws Exception {
- windowManager = (TestWindowManager) Robolectric.application.getSystemService(Context.WINDOW_SERVICE);
- contentView = new View(Robolectric.application);
- contentView.setId(R.id.content_view);
- anchor = new View(Robolectric.application);
- }
-
- @Test
- public void showAsDropDown_sticksWindowIntoWindowManager() throws Exception {
- PopupWindow popupWindow = new PopupWindow(contentView, 0, 0, true);
- popupWindow.showAsDropDown(anchor);
- assertNotNull(windowManager.getViews().get(0).findViewById(R.id.content_view));
- }
-
- @Test
- public void showAsDropdownWithOffsets_setsOffsetFields() throws Exception {
- PopupWindow popupWindow = new PopupWindow(contentView, 0, 0, true);
- popupWindow.showAsDropDown(anchor, 56, 69);
- assertEquals(shadowOf(popupWindow).getXOffset(), 56);
- assertEquals(shadowOf(popupWindow).getYOffset(), 69);
- }
-
- @Test
- public void supportsViewConstructor() throws Exception {
- PopupWindow popupWindow = new PopupWindow(contentView);
- popupWindow.showAsDropDown(anchor);
- assertNotNull(windowManager.getViews().get(0).findViewById(R.id.content_view));
- }
-
- @Test
- public void backgroundDrawableIsBehindPopupViewContainer() throws Exception {
- PopupWindow popupWindow = new PopupWindow(contentView);
- BitmapDrawable background = new BitmapDrawable();
- popupWindow.setBackgroundDrawable(background);
- popupWindow.showAsDropDown(anchor);
- assertSame(background, windowManager.getViews().get(0).getBackground());
- }
-
- @Test
- public void dismiss_removesContainerFromWindowManager() throws Exception {
- PopupWindow popupWindow = new PopupWindow(contentView);
- popupWindow.showAsDropDown(anchor);
- popupWindow.dismiss();
- assertEquals(0, windowManager.getViews().size());
- }
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/PowerManagerTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/PowerManagerTest.java
deleted file mode 100644
index f82284806..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/PowerManagerTest.java
+++ /dev/null
@@ -1,77 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import static junit.framework.Assert.assertFalse;
-import static junit.framework.Assert.assertNotNull;
-import static junit.framework.Assert.assertTrue;
-
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import android.content.Context;
-import android.os.PowerManager;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class PowerManagerTest {
-
- PowerManager powerManager;
- ShadowPowerManager shadowPowerManager;
-
- @Before
- public void before() {
- powerManager = (PowerManager) Robolectric.application.getSystemService(Context.POWER_SERVICE);
- shadowPowerManager = Robolectric.shadowOf(powerManager);
- }
-
- @Test
- public void testIsScreenOn() {
- assertTrue(powerManager.isScreenOn());
- shadowPowerManager.setIsScreenOn(false);
- assertFalse(powerManager.isScreenOn());
- }
-
- @Test
- public void shouldCreateWakeLock() throws Exception {
- assertNotNull(powerManager.newWakeLock(0, "TAG"));
- }
-
- @Test
- public void shouldAcquireAndReleaseReferenceCountedLock() throws Exception {
- PowerManager.WakeLock lock = powerManager.newWakeLock(0, "TAG");
- assertFalse(lock.isHeld());
- lock.acquire();
- assertTrue(lock.isHeld());
- lock.acquire();
-
- assertTrue(lock.isHeld());
- lock.release();
-
- assertTrue(lock.isHeld());
- lock.release();
- assertFalse(lock.isHeld());
- }
-
- @Test
- public void shouldAcquireAndReleaseNonReferenceCountedLock() throws Exception {
- PowerManager.WakeLock lock = powerManager.newWakeLock(0, "TAG");
- lock.setReferenceCounted(false);
-
- assertFalse(lock.isHeld());
- lock.acquire();
- assertTrue(lock.isHeld());
- lock.acquire();
- assertTrue(lock.isHeld());
-
- lock.release();
-
- assertFalse(lock.isHeld());
- }
-
- @Test(expected = RuntimeException.class)
- public void shouldThrowRuntimeExceptionIfLockisUnderlocked() throws Exception {
- PowerManager.WakeLock lock = powerManager.newWakeLock(0, "TAG");
- lock.release();
- }
-} \ No newline at end of file
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/PreferenceActivityTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/PreferenceActivityTest.java
deleted file mode 100644
index 6f95f31b2..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/PreferenceActivityTest.java
+++ /dev/null
@@ -1,64 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.CoreMatchers.instanceOf;
-import static org.hamcrest.CoreMatchers.nullValue;
-import static org.hamcrest.CoreMatchers.notNullValue;
-import static org.junit.Assert.assertThat;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import android.app.Activity;
-import android.preference.PreferenceActivity;
-import android.widget.ListView;
-
-import com.xtremelabs.robolectric.R;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class PreferenceActivityTest {
-
- private TestPreferenceActivity activity;
- private ShadowPreferenceActivity shadow;
-
- @Before
- public void setUp() throws Exception {
- activity = new TestPreferenceActivity();
- shadow = Robolectric.shadowOf(activity);
- }
-
- @Test
- public void shouldGetListView() {
- shadow.setListView( new ListView( new Activity() ) );
- assertThat( activity.getListView(), notNullValue() );
- }
-
- @Test
- public void shouldInheritFromListActivity() {
- assertThat(shadow, instanceOf(ShadowListActivity.class));
- }
-
- @Test
- public void shouldNotInitializePreferenceScreen() {
- assertThat(activity.getPreferenceScreen(), nullValue());
- }
-
- @Test
- public void shouldRecordPreferencesResourceId() {
- assertThat(shadow.getPreferencesResId(), equalTo(-1));
- activity.addPreferencesFromResource(R.xml.preferences);
- assertThat(shadow.getPreferencesResId(), equalTo(R.xml.preferences));
- }
-
- @Test
- public void shouldLoadPreferenceScreen() {
- activity.addPreferencesFromResource(R.xml.preferences);
- assertThat( activity.getPreferenceScreen().getPreferenceCount(), equalTo(6));
- }
-
- private static class TestPreferenceActivity extends PreferenceActivity {
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/PreferenceCategoryTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/PreferenceCategoryTest.java
deleted file mode 100644
index 9a4b8102c..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/PreferenceCategoryTest.java
+++ /dev/null
@@ -1,32 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import static org.hamcrest.CoreMatchers.instanceOf;
-import static org.junit.Assert.assertThat;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import android.app.Activity;
-import android.preference.PreferenceCategory;
-
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class PreferenceCategoryTest {
-
- private PreferenceCategory category;
- private ShadowPreferenceCategory shadow;
-
- @Before
- public void setUp() throws Exception {
- category = new PreferenceCategory(new Activity());
- shadow = Robolectric.shadowOf(category);
- }
-
- @Test
- public void shouldInheritFromPreferenceGroup() {
- assertThat(shadow, instanceOf(ShadowPreferenceGroup.class));
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/PreferenceGroupTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/PreferenceGroupTest.java
deleted file mode 100644
index 2cd332840..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/PreferenceGroupTest.java
+++ /dev/null
@@ -1,179 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.CoreMatchers.instanceOf;
-import static org.hamcrest.CoreMatchers.sameInstance;
-import static org.junit.Assert.assertThat;
-
-import java.util.HashMap;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import android.app.Activity;
-import android.content.Context;
-import android.preference.Preference;
-import android.preference.PreferenceGroup;
-import android.util.AttributeSet;
-
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import com.xtremelabs.robolectric.tester.android.util.TestAttributeSet;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class PreferenceGroupTest {
-
- private TestPreferenceGroup group;
- private ShadowPreferenceGroup shadow;
- private Context context;
- private TestAttributeSet attrs;
- private Preference pref1, pref2;
-
- @Before
- public void setUp() throws Exception {
- context = new Activity();
- attrs = new TestAttributeSet( new HashMap<String, String>() );
-
- group = new TestPreferenceGroup(context, attrs);
- shadow = Robolectric.shadowOf(group);
-
- pref1 = new Preference(context);
- pref1.setKey("pref1");
-
- pref2 = new Preference(context);
- pref2.setKey("pref2");
- }
-
- @Test
- public void shouldInheritFromPreference() {
- assertThat(shadow, instanceOf(ShadowPreference.class));
- }
-
- @Test
- public void shouldAddPreferences() {
- assertThat( group.getPreferenceCount(), equalTo(0));
-
- // First add succeeds
- assertThat( group.addPreference(pref1), equalTo(true));
- assertThat( group.getPreferenceCount(), equalTo(1));
-
- // Dupe add fails silently
- assertThat( group.addPreference(pref1), equalTo(true));
- assertThat( group.getPreferenceCount(), equalTo(1));
-
- // Second add succeeds
- assertThat( group.addPreference(pref2), equalTo(true));
- assertThat( group.getPreferenceCount(), equalTo(2));
- }
-
- @Test
- public void shouldAddItemFromInflater() {
- assertThat( group.getPreferenceCount(), equalTo(0));
-
- // First add succeeds
- group.addItemFromInflater(pref1);
- assertThat( group.getPreferenceCount(), equalTo(1));
-
- // Dupe add fails silently
- group.addItemFromInflater(pref1);
- assertThat( group.getPreferenceCount(), equalTo(1));
-
- // Second add succeeds
- group.addItemFromInflater(pref2);
- assertThat( group.getPreferenceCount(), equalTo(2));
- }
-
- @Test
- public void shouldGetPreference() {
- group.addPreference(pref1);
- group.addPreference(pref2);
-
- assertThat( group.getPreference(0), sameInstance(pref1));
- assertThat( group.getPreference(1), sameInstance(pref2));
- }
-
- @Test
- public void shouldGetPreferenceCount() {
- assertThat( group.getPreferenceCount(), equalTo(0));
- group.addPreference(pref1);
- assertThat( group.getPreferenceCount(), equalTo(1));
- group.addPreference(pref2);
- assertThat( group.getPreferenceCount(), equalTo(2));
- }
-
- @Test
- public void shouldRemovePreference() {
- group.addPreference(pref1);
- group.addPreference(pref2);
- assertThat( group.getPreferenceCount(), equalTo(2));
-
- // First remove succeeds
- assertThat( group.removePreference(pref1), equalTo(true));
- assertThat( group.getPreferenceCount(), equalTo(1));
-
- // Dupe remove fails
- assertThat( group.removePreference(pref1), equalTo(false));
- assertThat( group.getPreferenceCount(), equalTo(1));
-
- // Second remove succeeds
- assertThat( group.removePreference(pref2), equalTo(true));
- assertThat( group.getPreferenceCount(), equalTo(0));
- }
-
- @Test
- public void shouldRemoveAll() {
- group.addPreference(pref1);
- group.addPreference(pref2);
- assertThat( group.getPreferenceCount(), equalTo(2));
-
- group.removeAll();
- assertThat( group.getPreferenceCount(), equalTo(0));
- }
-
- @Test
- public void shouldFindPreference() {
- group.addPreference(pref1);
- group.addPreference(pref2);
-
- assertThat( group.findPreference(pref1.getKey()), sameInstance(pref1));
- assertThat( group.findPreference(pref2.getKey()), sameInstance(pref2));
- }
-
- @Test
- public void shouldFindPreferenceRecursively() {
- TestPreferenceGroup group2 = new TestPreferenceGroup(context, attrs);
- group2.addPreference(pref2);
-
- group.addPreference(pref1);
- group.addPreference(group2);
-
- assertThat( group.findPreference(pref2.getKey()), sameInstance(pref2));
- }
-
- @Test
- public void shouldSetEnabledRecursively() {
- boolean[] values = { false, true };
-
- TestPreferenceGroup group2 = new TestPreferenceGroup(context, attrs);
- group2.addPreference(pref2);
-
- group.addPreference(pref1);
- group.addPreference(group2);
-
- for( boolean enabled : values ) {
- group.setEnabled(enabled);
-
- assertThat(group.isEnabled(), equalTo(enabled));
- assertThat(group2.isEnabled(), equalTo(enabled));
- assertThat(pref1.isEnabled(), equalTo(enabled));
- assertThat(pref2.isEnabled(), equalTo(enabled));
- }
- }
-
- private static class TestPreferenceGroup extends PreferenceGroup {
- public TestPreferenceGroup(Context context, AttributeSet attrs) {
- super(context, attrs);
- }
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/PreferenceManagerTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/PreferenceManagerTest.java
deleted file mode 100644
index 1197565e1..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/PreferenceManagerTest.java
+++ /dev/null
@@ -1,35 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.content.Context;
-import android.content.SharedPreferences;
-import android.content.SharedPreferences.Editor;
-import android.preference.PreferenceManager;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import com.xtremelabs.robolectric.tester.android.content.TestSharedPreferences;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import java.util.Map;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class PreferenceManagerTest {
- @Test
- public void shouldProvideDefaultSharedPreferences() throws Exception {
- Map<String, Map<String, Object>> content = Robolectric.getShadowApplication().getSharedPreferenceMap();
-
- TestSharedPreferences testPrefs = new TestSharedPreferences(content, "__default__", Context.MODE_PRIVATE);
- Editor editor = testPrefs.edit();
- editor.putInt("foobar", 13);
- editor.commit();
-
- SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(Robolectric.application);
-
- assertNotNull(prefs);
- assertEquals(13, prefs.getInt("foobar", 0));
- }
-
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/PreferenceScreenTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/PreferenceScreenTest.java
deleted file mode 100644
index e2be12b8d..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/PreferenceScreenTest.java
+++ /dev/null
@@ -1,42 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.app.Activity;
-import android.app.Dialog;
-import android.preference.PreferenceScreen;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static org.hamcrest.CoreMatchers.instanceOf;
-import static org.hamcrest.CoreMatchers.nullValue;
-import static org.hamcrest.CoreMatchers.sameInstance;
-import static org.junit.Assert.assertThat;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class PreferenceScreenTest {
-
- private PreferenceScreen screen;
- private ShadowPreferenceScreen shadow;
-
- @Before
- public void setUp() throws Exception {
- screen = Robolectric.newInstanceOf(PreferenceScreen.class);
- shadow = Robolectric.shadowOf(screen);
- }
-
- @Test
- public void shouldInheritFromPreferenceGroup() {
- assertThat(shadow, instanceOf(ShadowPreferenceGroup.class));
- }
-
- @Test
- public void shouldSetDialog() {
- Dialog dialog = new Dialog(new Activity());
-
- assertThat(screen.getDialog(), nullValue());
- shadow.setDialog(dialog);
- assertThat(screen.getDialog(), sameInstance(dialog));
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/PreferenceTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/PreferenceTest.java
deleted file mode 100644
index 8cec55a15..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/PreferenceTest.java
+++ /dev/null
@@ -1,266 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.CoreMatchers.not;
-import static org.hamcrest.CoreMatchers.nullValue;
-import static org.hamcrest.CoreMatchers.notNullValue;
-import static org.hamcrest.CoreMatchers.sameInstance;
-import static org.junit.Assert.assertThat;
-
-import java.util.HashMap;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import android.app.Activity;
-import android.content.Context;
-import android.content.Intent;
-import android.preference.Preference;
-import android.preference.Preference.OnPreferenceClickListener;
-import android.util.AttributeSet;
-
-import com.xtremelabs.robolectric.R;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import com.xtremelabs.robolectric.tester.android.util.TestAttributeSet;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class PreferenceTest {
-
- private TestPreference preference;
- private ShadowPreference shadow;
-
- private Context context;
- private TestAttributeSet attrs;
-
- private boolean clicked = false;
-
- @Before
- public void setup() {
- context = new Activity();
- attrs = new TestAttributeSet( new HashMap<String, String>() );
- preference = new TestPreference(context, attrs);
- shadow = Robolectric.shadowOf( preference );
- }
-
- @Test
- public void shouldConstruct() {
- int defStyle = 7;
-
- preference = new TestPreference(context, attrs, defStyle);
- shadow = Robolectric.shadowOf(preference);
- assertThat(shadow.getContext(), sameInstance(context));
- assertThat(shadow.getAttrs(), sameInstance((AttributeSet)attrs));
- assertThat(shadow.getDefStyle(), equalTo(defStyle));
-
- preference = new TestPreference(context, attrs);
- shadow = Robolectric.shadowOf(preference);
- assertThat(shadow.getContext(), sameInstance( context ));
- assertThat(shadow.getAttrs(), sameInstance((AttributeSet)attrs));
- assertThat(shadow.getDefStyle(), equalTo(0));
-
- preference = new TestPreference(context);
- shadow = Robolectric.shadowOf(preference);
- assertThat(shadow.getContext(), sameInstance( context ));
- assertThat(shadow.getAttrs(), nullValue());
- assertThat(shadow.getDefStyle(), equalTo(0));
-}
-
- @Test
- public void shouldInitializeFromAttributes() {
- String key = "key_value";
- HashMap<String, String> hash = new HashMap<String, String>();
- hash.put( "android:key", key );
- attrs = new TestAttributeSet( hash );
-
- preference = new TestPreference(context, attrs);
- assertThat( preference.getKey(), equalTo(key) );
- }
-
- @Test
- public void shouldHaveAKey() {
- String key = "key_value";
-
- assertThat(preference.getKey(), nullValue());
- preference.setKey(key);
- assertThat(preference.getKey(), equalTo(key));
- }
-
- @Test
- public void shouldHaveATitle() {
- CharSequence title = "Test Preference";
-
- assertThat(preference.getTitle(), nullValue());
- preference.setTitle(title);
- assertThat(preference.getTitle(), equalTo(title));
- }
-
- @Test
- public void shouldSetTitleByResourceId() {
- CharSequence expected = "Hello";
-
- assertThat(preference.getTitle(), not(equalTo(expected)));
- preference.setTitle(R.string.hello);
- assertThat(preference.getTitle(), equalTo(expected));
- }
-
- @Test
- public void shouldHaveASummary() {
- CharSequence summary = "This is only a test.";
-
- assertThat(preference.getSummary(), nullValue());
- preference.setSummary(summary);
- assertThat(preference.getSummary(), equalTo(summary));
- }
-
- @Test
- public void shouldSetSummaryByResourceId() {
- CharSequence expected = "Hello";
-
- assertThat(preference.getSummary(), not(equalTo(expected)));
- preference.setSummary(R.string.hello);
- assertThat(preference.getSummary(), equalTo(expected));
- }
-
- @Test
- public void shouldRememberDefaultValue() {
- Object defaultValue = "Zoodles was here";
-
- assertThat(shadow.getDefaultValue(), nullValue());
- preference.setDefaultValue(defaultValue);
- assertThat(shadow.getDefaultValue(), sameInstance(defaultValue));
- }
-
- @Test
- public void shouldOrder() {
- int[] values = { 0, 1, 2, 2011 };
-
- for(int order : values) {
- preference.setOrder(order);
- assertThat(preference.getOrder(), equalTo(order));
- }
- }
-
- @Test
- public void shouldEnable() {
- assertThat(preference.isEnabled(), equalTo(true));
-
- preference.setEnabled(false);
- assertThat(preference.isEnabled(), equalTo(false));
-
- preference.setEnabled(true);
- assertThat(preference.isEnabled(), equalTo(true));
- }
-
- @Test
- public void testPersistent() {
- boolean[] values = { true, false };
-
- for( boolean shouldPersist : values ) {
- shadow.setPersistent(shouldPersist);
- assertThat(preference.shouldPersist(), equalTo(shouldPersist));
- assertThat(preference.isPersistent(), equalTo(shouldPersist));
- }
- }
-
- @Test
- public void shouldPersistedIn() {
- int defaultValue = 727;
- int[] values = { 0, 1, 2, 2011 };
-
- for(int persistedInt : values) {
- shadow.persistInt(persistedInt);
-
- shadow.setPersistent(false);
- assertThat(preference.getPersistedInt(defaultValue), equalTo(defaultValue));
-
- shadow.setPersistent(true);
- assertThat(preference.getPersistedInt(defaultValue), equalTo(persistedInt));
- }
- }
-
- @Test
- public void shouldRememberOnClickListener() {
- Preference.OnPreferenceClickListener onPreferenceClickListener = new OnPreferenceClickListener() {
- @Override
- public boolean onPreferenceClick(Preference preference) {
- return true;
- }
- };
-
- preference.setOnPreferenceClickListener(onPreferenceClickListener);
- assertThat(shadow.getOnPreferenceClickListener(), sameInstance(onPreferenceClickListener));
- }
-
- @Test
- public void shouldClickThroughToClickListener() {
- Preference.OnPreferenceClickListener onPreferenceClickListener = new OnPreferenceClickListener() {
- @Override
- public boolean onPreferenceClick(Preference preference) {
- clicked = true;
- return true;
- }
- };
- preference.setOnPreferenceClickListener(onPreferenceClickListener);
-
- assertThat( clicked, equalTo(false));
- assertThat( shadow.click(), equalTo(true));
- assertThat( clicked, equalTo(true));
- }
-
- @Test
- public void shouldCallChangeListener() {
- Integer[] values = { 0, 1, 2, 2011 };
-
- for(Integer newValue : values) {
- assertThat(preference.callChangeListener(newValue), equalTo(true));
- assertThat(shadow.getCallChangeListenerValue(), sameInstance((Object)newValue));
- }
- }
-
- @Test
- public void shouldReturnIntent() {
- assertThat( preference.getIntent(), nullValue() );
- preference.setIntent( new Intent() );
- assertThat( preference.getIntent(), notNullValue() );
- }
-
- @Test
- public void shouldRememberDependency() {
- assertThat( preference.getDependency(), nullValue() );
- preference.setDependency( "TEST_PREF_KEY" );
- assertThat( preference.getDependency(), notNullValue() );
- assertThat( preference.getDependency(), equalTo("TEST_PREF_KEY") );
- }
-
- private static class TestPreference extends Preference {
- public TestPreference(Context context) {
- super(context);
- }
-
- public TestPreference(Context context, AttributeSet attrs) {
- super(context, attrs);
- }
-
- public TestPreference(Context context, AttributeSet attrs, int defStyle) {
- super(context, attrs, defStyle);
- }
-
- public boolean shouldPersist() {
- return super.shouldPersist();
- }
-
- public int getPersistedInt(int defaultReturnValue) {
- return super.getPersistedInt(defaultReturnValue);
- }
-
- public boolean persistInt(int value) {
- return super.persistInt(value);
- }
-
- public boolean callChangeListener(Object newValue) {
- return super.callChangeListener(newValue);
- }
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ProcessTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/ProcessTest.java
deleted file mode 100644
index e49ff5efb..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ProcessTest.java
+++ /dev/null
@@ -1,28 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.CoreMatchers.not;
-import static org.junit.Assert.assertThat;
-
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class ProcessTest {
-
- @Test
- public void testMyPidIsJvmProcessId() {
- int pid = android.os.Process.myPid();
-
- assertThat(pid, not(equalTo(0)));
- }
-
- @Test
- public void testSetPid() {
- ShadowProcess.setPid(47);
-
- assertThat(android.os.Process.myPid(), equalTo(47));
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ProgressBarTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/ProgressBarTest.java
deleted file mode 100644
index 5b419e34e..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ProgressBarTest.java
+++ /dev/null
@@ -1,107 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.widget.ProgressBar;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertThat;
-import static org.junit.Assert.assertTrue;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class ProgressBarTest {
-
- private int[] testValues = {0, 1, 2, 100};
- private ProgressBar progressBar;
-
- @Before
- public void setUp() {
- progressBar = new ProgressBar(null);
- }
-
- @Test
- public void shouldInitMaxTo100() {
- assertThat(progressBar.getMax(), equalTo(100));
- }
-
- @Test
- public void testMax() {
- for (int max : testValues) {
- progressBar.setMax(max);
- assertThat(progressBar.getMax(), equalTo(max));
- }
- }
-
- @Test
- public void testProgress() {
- for (int progress : testValues) {
- progressBar.setProgress(progress);
- assertThat(progressBar.getProgress(), equalTo(progress));
- }
- }
-
- @Test
- public void testSecondaryProgress() {
- for (int progress : testValues) {
- progressBar.setSecondaryProgress(progress);
- assertThat(progressBar.getSecondaryProgress(), equalTo(progress));
- }
- }
-
- @Test
- public void testIsDeterminate() throws Exception {
- assertFalse(progressBar.isIndeterminate());
- progressBar.setIndeterminate(true);
- assertTrue(progressBar.isIndeterminate());
- }
-
- @Test
- public void shouldReturnZeroAsProgressWhenIndeterminate() throws Exception {
- progressBar.setProgress(10);
- progressBar.setSecondaryProgress(20);
- progressBar.setIndeterminate(true);
- assertEquals(0, progressBar.getProgress());
- assertEquals(0, progressBar.getSecondaryProgress());
- progressBar.setIndeterminate(false);
-
- assertEquals(10, progressBar.getProgress());
- assertEquals(20, progressBar.getSecondaryProgress());
- }
-
- @Test
- public void shouldNotSetProgressWhenIndeterminate() throws Exception {
- progressBar.setIndeterminate(true);
- progressBar.setProgress(10);
- progressBar.setSecondaryProgress(20);
- progressBar.setIndeterminate(false);
-
- assertEquals(0, progressBar.getProgress());
- assertEquals(0, progressBar.getSecondaryProgress());
- }
-
- @Test
- public void testIncrementProgressBy() throws Exception {
- assertEquals(0, progressBar.getProgress());
- progressBar.incrementProgressBy(1);
- assertEquals(1, progressBar.getProgress());
- progressBar.incrementProgressBy(1);
- assertEquals(2, progressBar.getProgress());
-
- assertEquals(0, progressBar.getSecondaryProgress());
- progressBar.incrementSecondaryProgressBy(1);
- assertEquals(1, progressBar.getSecondaryProgress());
- progressBar.incrementSecondaryProgressBy(1);
- assertEquals(2, progressBar.getSecondaryProgress());
- }
-
- @Test
- public void shouldRespectMax() throws Exception {
- progressBar.setMax(20);
- progressBar.setProgress(50);
- assertEquals(20, progressBar.getProgress());
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ProgressDialogTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/ProgressDialogTest.java
deleted file mode 100644
index f809bae8e..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ProgressDialogTest.java
+++ /dev/null
@@ -1,153 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.app.Activity;
-import android.app.ProgressDialog;
-import android.content.Context;
-import android.content.DialogInterface;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import java.util.concurrent.Callable;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-import static junit.framework.Assert.assertNull;
-import static org.hamcrest.CoreMatchers.instanceOf;
-import static org.hamcrest.CoreMatchers.nullValue;
-import static org.hamcrest.core.Is.is;
-import static org.hamcrest.core.IsEqual.equalTo;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertThat;
-import static org.junit.Assert.assertTrue;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class ProgressDialogTest {
-
- private ProgressDialog dialog;
- private ShadowProgressDialog shadow;
-
- @Before
- public void setUp() {
- dialog = new ProgressDialog(null);
- shadow = Robolectric.shadowOf(dialog);
- }
-
- @Test
- public void shouldExtendAlertDialog() {
- assertThat(shadow, instanceOf(ShadowAlertDialog.class));
- }
-
- @Test
- public void shouldSetMessage() {
- CharSequence message = "This is only a test";
-
- assertThat(shadow.getMessage(), nullValue());
- dialog.setMessage(message);
- assertThat((CharSequence) shadow.getMessage(), equalTo(message));
- }
-
- @Test
- public void shouldSetIndeterminate() {
- assertThat(dialog.isIndeterminate(), equalTo(false));
-
- dialog.setIndeterminate(true);
- assertThat(dialog.isIndeterminate(), equalTo(true));
-
- dialog.setIndeterminate(false);
- assertThat(dialog.isIndeterminate(), equalTo(false));
- }
-
- @Test
- public void show_shouldCreateAProgressDialog() {
- Context context = new Activity();
- TestOnCancelListener cancelListener = new TestOnCancelListener();
- ProgressDialog progressDialog = ProgressDialog.show(context, "Title", "Message", true, true, cancelListener);
- ShadowProgressDialog shadowProgressDialog = shadowOf(progressDialog);
- assertThat(shadowProgressDialog.getContext(), is(context));
- assertThat(shadowProgressDialog.getMessage(), equalTo("Message"));
- assertTrue(shadowProgressDialog.isIndeterminate());
- assertTrue(shadowProgressDialog.isCancelable());
-
- progressDialog.cancel();
- assertThat(cancelListener.onCancelDialogInterface, is((DialogInterface) progressDialog));
- }
-
- @Test
- public void show_setsLatestAlertDialogAndLatestDialog_3args() throws Exception{
- assertLatestDialogsSet("Title", "Message", false, false, null, new Callable<ProgressDialog>() {
- @Override
- public ProgressDialog call() throws Exception {
- return ProgressDialog.show(Robolectric.application, "Title", "Message");
- }
- }
- );
- }
-
- @Test
- public void show_setsLatestAlertDialogAndLatestDialog_4args() throws Exception{
- assertLatestDialogsSet("Title", "Message", true, false, null, new Callable<ProgressDialog>() {
- @Override
- public ProgressDialog call() throws Exception {
- return ProgressDialog.show(Robolectric.application, "Title", "Message", true);
- }
- });
- }
-
- @Test
- public void show_setsLatestAlertDialogAndLatestDialog_5args() throws Exception{
- assertLatestDialogsSet("Title", "Message", true, true, null, new Callable<ProgressDialog>() {
- @Override
- public ProgressDialog call() throws Exception {
- return ProgressDialog.show(Robolectric.application, "Title", "Message", true, true);
- }
- });
- }
-
- @Test
- public void show_setsLatestAlertDialogAndLatestDialog_6args() throws Exception{
- final DialogInterface.OnCancelListener cancelListener = new DialogInterface.OnCancelListener() {
- @Override
- public void onCancel(DialogInterface dialog) {
- }
- };
-
- assertLatestDialogsSet("Title", "Message", true, true, cancelListener, new Callable<ProgressDialog>() {
- @Override
- public ProgressDialog call() throws Exception {
- return ProgressDialog.show(Robolectric.application, "Title", "Message", true, true, cancelListener);
- }
- });
- }
-
- private void assertLatestDialogsSet(CharSequence expectedTitle, CharSequence expectedMessage, boolean expectedIndeterminate,
- boolean expectedCancelable, DialogInterface.OnCancelListener expectedCancelListener,
- Callable<ProgressDialog> callable) throws Exception {
- assertNull(ShadowDialog.getLatestDialog());
- assertNull(ShadowAlertDialog.getLatestAlertDialog());
-
- dialog = callable.call();
-
- assertNotNull(dialog);
- assertEquals(dialog, ShadowDialog.getLatestDialog());
- assertEquals(dialog, ShadowAlertDialog.getLatestAlertDialog());
-
- assertEquals(expectedIndeterminate, dialog.isIndeterminate());
- assertEquals(expectedMessage, shadowOf(dialog).getMessage());
- assertEquals(expectedTitle, shadowOf(dialog).getTitle());
- assertEquals(expectedCancelable, shadowOf(dialog).isCancelable());
- assertEquals(expectedCancelListener, shadowOf(dialog).getOnCancelListener());
- }
-
- private static class TestOnCancelListener implements DialogInterface.OnCancelListener {
- public DialogInterface onCancelDialogInterface;
-
- @Override
- public void onCancel(DialogInterface dialogInterface) {
- onCancelDialogInterface = dialogInterface;
-
- }
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/RadioButtonTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/RadioButtonTest.java
deleted file mode 100644
index 1f47f5051..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/RadioButtonTest.java
+++ /dev/null
@@ -1,69 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.widget.RadioButton;
-import android.widget.RadioGroup;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertThat;
-import static org.junit.Assert.assertTrue;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class RadioButtonTest {
- @Test
- public void canBeExplicitlyChecked() throws Exception {
- RadioButton radioButton = new RadioButton(null);
- assertFalse(radioButton.isChecked());
-
- radioButton.setChecked(true);
- assertTrue(radioButton.isChecked());
-
- radioButton.setChecked(false);
- assertFalse(radioButton.isChecked());
- }
-
- @Test
- public void canBeToggledBetweenCheckedState() throws Exception {
- RadioButton radioButton = new RadioButton(null);
- assertFalse(radioButton.isChecked());
-
- radioButton.toggle();
- assertTrue(radioButton.isChecked());
-
- radioButton.toggle();
- assertFalse(radioButton.isChecked());
- }
-
- @Test
- public void canBeClickedToToggleCheckedState() throws Exception {
- RadioButton radioButton = new RadioButton(null);
- assertFalse(radioButton.isChecked());
-
- radioButton.performClick();
- assertTrue(radioButton.isChecked());
-
- radioButton.performClick();
- assertFalse(radioButton.isChecked());
- }
-
- @Test
- public void shouldInformRadioGroupThatItIsChecked() throws Exception {
- RadioButton radioButton1 = new RadioButton(null);
- radioButton1.setId(99);
- RadioButton radioButton2 = new RadioButton(null);
- radioButton2.setId(100);
-
- RadioGroup radioGroup = new RadioGroup(null);
- radioGroup.addView(radioButton1);
- radioGroup.addView(radioButton2);
-
- radioButton1.setChecked(true);
- assertThat(radioGroup.getCheckedRadioButtonId(), equalTo(radioButton1.getId()));
-
- radioButton2.setChecked(true);
- assertThat(radioGroup.getCheckedRadioButtonId(), equalTo(radioButton2.getId()));
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/RadioGroupTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/RadioGroupTest.java
deleted file mode 100644
index 115948dd4..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/RadioGroupTest.java
+++ /dev/null
@@ -1,63 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.widget.RadioGroup;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertThat;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class RadioGroupTest {
- private static final int BUTTON_ID = 3245;
-
- @Test
- public void checkedRadioButtonId() throws Exception {
- RadioGroup radioGroup = new RadioGroup(null);
- assertThat(radioGroup.getCheckedRadioButtonId(), equalTo(-1));
- radioGroup.check(99);
- assertThat(radioGroup.getCheckedRadioButtonId(), equalTo(99));
- }
-
- @Test
- public void check_shouldCallOnCheckedChangeListener() throws Exception {
- RadioGroup radioGroup = new RadioGroup(null);
- TestOnCheckedChangeListener listener = new TestOnCheckedChangeListener();
- radioGroup.setOnCheckedChangeListener(listener);
-
- radioGroup.check(BUTTON_ID);
-
- assertEquals(Arrays.asList(BUTTON_ID), listener.onCheckedChangedCheckedIds);
- assertEquals(Arrays.asList(radioGroup), listener.onCheckedChangedGroups);
- }
-
- @Test
- public void clearCheck_shouldCallOnCheckedChangeListenerTwice() throws Exception {
- RadioGroup radioGroup = new RadioGroup(null);
- TestOnCheckedChangeListener listener = new TestOnCheckedChangeListener();
-
- radioGroup.check(BUTTON_ID);
- radioGroup.setOnCheckedChangeListener(listener);
- radioGroup.clearCheck();
-
- assertEquals(Arrays.asList(BUTTON_ID, -1), listener.onCheckedChangedCheckedIds);
- assertEquals(Arrays.asList(radioGroup, radioGroup), listener.onCheckedChangedGroups);
-
- }
-
- private static class TestOnCheckedChangeListener implements RadioGroup.OnCheckedChangeListener {
- public ArrayList<RadioGroup> onCheckedChangedGroups = new ArrayList<RadioGroup>();
- public ArrayList<Integer> onCheckedChangedCheckedIds = new ArrayList<Integer>();
-
- @Override
- public void onCheckedChanged(RadioGroup group, int checkedId) {
- onCheckedChangedGroups.add(group);
- onCheckedChangedCheckedIds.add(checkedId);
- }
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/RatingBarTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/RatingBarTest.java
deleted file mode 100644
index 081a8c48e..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/RatingBarTest.java
+++ /dev/null
@@ -1,71 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import static org.hamcrest.CoreMatchers.instanceOf;
-import static org.hamcrest.CoreMatchers.nullValue;
-import static org.hamcrest.CoreMatchers.sameInstance;
-import static org.junit.Assert.assertThat;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import android.app.Activity;
-import android.content.Context;
-import android.widget.RatingBar;
-
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import com.xtremelabs.robolectric.util.Transcript;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class RatingBarTest {
-
- private RatingBar ratingBar;
- private ShadowRatingBar shadow;
- private RatingBar.OnRatingBarChangeListener listener;
- private Transcript transcript;
-
- @Before
- public void setup() {
- ratingBar = new RatingBar(new Activity());
- shadow = Robolectric.shadowOf(ratingBar);
- listener = new TestRatingBarChangedListener();
- transcript = new Transcript();
- ratingBar.setOnRatingBarChangeListener(listener);
- }
-
- @Test
- public void testOnSeekBarChangedListener() {
- assertThat(shadow.getOnRatingBarChangeListener(), sameInstance(listener));
- ratingBar.setOnRatingBarChangeListener(null);
- assertThat(shadow.getOnRatingBarChangeListener(), nullValue());
- }
-
- @Test
- public void testOnChangeNotification() {
- ratingBar.setRating(5.0f);
- transcript.assertEventsSoFar("onRatingChanged() - 5.0");
- }
-
- private class TestRatingBarChangedListener implements RatingBar.OnRatingBarChangeListener {
-
- @Override
- public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
- transcript.add("onRatingChanged() - " + rating);
- }
- }
-
- @Test
- public void testInheritance() {
- TestRatingBar ratingBar = new TestRatingBar(new Activity());
- ShadowRatingBar shadow = Robolectric.shadowOf(ratingBar);
- assertThat(shadow, instanceOf(ShadowAbsSeekBar.class));
- }
-
- private static class TestRatingBar extends RatingBar {
-
- public TestRatingBar(Context context) {
- super(context);
- }
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/RectTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/RectTest.java
deleted file mode 100644
index 5406e3c25..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/RectTest.java
+++ /dev/null
@@ -1,192 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.graphics.Rect;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static org.hamcrest.CoreMatchers.is;
-import static org.junit.Assert.assertThat;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class RectTest {
- @Before
- public void setUp() {
- }
-
- @Test
- public void constructorSetsCoordinates() {
- Rect r = new Rect(1, 2, 3, 4);
- assertThat(r.left, is(1));
- assertThat(r.top, is(2));
- assertThat(r.right, is(3));
- assertThat(r.bottom, is(4));
- }
-
- @Test
- public void secondConstructorSetsCoordinates() {
- Rect existingRect = new Rect(1, 2, 3, 4);
- Rect r = new Rect(existingRect);
- assertThat(r.left, is(1));
- assertThat(r.top, is(2));
- assertThat(r.right, is(3));
- assertThat(r.bottom, is(4));
- }
-
-
- @Test
- public void width() {
- Rect r = new Rect(0, 0, 10, 10);
- assertThat(r.width(), is(10));
- }
-
- @Test
- public void height() {
- Rect r = new Rect(0, 0, 10, 10);
- assertThat(r.height(), is(10));
- }
-
- @Test
- public void doesntEqual() {
- Rect a = new Rect(1, 2, 3, 4);
- Rect b = new Rect(2, 3, 4, 5);
- assertThat(a.equals(b), is(false));
- }
-
- @Test
- public void equals() {
- Rect a = new Rect(1, 2, 3, 4);
- Rect b = new Rect(1, 2, 3, 4);
- assertThat(a.equals(b), is(true));
- }
-
- @Test
- public void doesntContainPoint() {
- Rect r = new Rect(0, 0, 10, 10);
- assertThat(r.contains(11, 11), is(false));
- }
-
- @Test
- public void containsPoint() {
- Rect r = new Rect(0, 0, 10, 10);
- assertThat(r.contains(5, 5), is(true));
- }
-
- @Test
- public void doesntContainPointOnLeftEdge() {
- Rect r = new Rect(0, 0, 10, 10);
- assertThat(r.contains(0, 5), is(false));
- }
-
- @Test
- public void doesntContainPointOnRightEdge() {
- Rect r = new Rect(0, 0, 10, 10);
- assertThat(r.contains(10, 5), is(false));
- }
-
- @Test
- public void containsPointOnTopEdge() {
- Rect r = new Rect(0, 0, 10, 10);
- assertThat(r.contains(5, 0), is(true));
- }
-
- @Test
- public void containsPointOnBottomEdge() {
- Rect r = new Rect(0, 0, 10, 10);
- assertThat(r.contains(5, 10), is(true));
- }
-
- @Test
- public void doesntContainRect() {
- Rect a = new Rect(0, 0, 10, 10);
- Rect b = new Rect(11, 11, 12, 12);
- assertThat(a.contains(b), is(false));
- }
-
- @Test
- public void containsRect() {
- Rect a = new Rect(0, 0, 10, 10);
- Rect b = new Rect(8, 8, 9, 9);
- assertThat(a.contains(b), is(true));
- }
-
- @Test
- public void containsEqualRect() {
- Rect a = new Rect(0, 0, 10, 10);
- Rect b = new Rect(0, 0, 10, 10);
- assertThat(a.contains(b), is(true));
- }
-
- @Test
- public void intersectsButDoesntContainRect() {
- Rect a = new Rect(0, 0, 10, 10);
- Rect b = new Rect(5, 5, 15, 15);
- assertThat(a.contains(b), is(false));
- }
-
- @Test
- public void doesntIntersect() {
- Rect a = new Rect(0, 0, 10, 10);
- Rect b = new Rect(11, 11, 21, 21);
- assertThat(Rect.intersects(a, b), is(false));
- }
-
- @Test
- public void intersects() {
- Rect a = new Rect(0, 0, 10, 10);
- Rect b = new Rect(5, 0, 15, 10);
- assertThat(Rect.intersects(a, b), is(true));
- }
-
- @Test
- public void almostIntersects() {
- Rect a = new Rect(3, 0, 4, 2);
- Rect b = new Rect(1, 0, 3, 1);
- assertThat(Rect.intersects(a, b), is(false));
- }
-
- @Test
- public void intersectRect() {
- Rect a = new Rect(0, 0, 10, 10);
- Rect b = new Rect(5, 0, 15, 10);
- assertThat(a.intersect(b), is(true));
- }
-
- @Test
- public void intersectCoordinates() {
- Rect r = new Rect(0, 0, 10, 10);
- assertThat(r.intersect(5, 0, 15, 10), is(true));
- }
-
- @Test
- public void setWithIntsSetsCoordinates() {
- Rect r = new Rect();
- r.set(1, 2, 3, 4);
- assertThat(r.left, is(1));
- assertThat(r.top, is(2));
- assertThat(r.right, is(3));
- assertThat(r.bottom, is(4));
- }
-
- @Test
- public void setWithRectSetsCoordinates() {
- Rect rSrc = new Rect(1, 2, 3, 4);
- Rect r = new Rect();
- r.set(rSrc);
- assertThat(r.left, is(1));
- assertThat(r.top, is(2));
- assertThat(r.right, is(3));
- assertThat(r.bottom, is(4));
- }
-
- @Test
- public void offsetModifiesRect() {
- Rect r = new Rect(1, 2, 3, 4);
- r.offset(10, 20);
- assertThat(r.left, is(11));
- assertThat(r.top, is(22));
- assertThat(r.right, is(13));
- assertThat(r.bottom, is(24));
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/RemoteCallbackListTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/RemoteCallbackListTest.java
deleted file mode 100644
index 66029916d..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/RemoteCallbackListTest.java
+++ /dev/null
@@ -1,35 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.os.Binder;
-import android.os.IBinder;
-import android.os.IInterface;
-import android.os.RemoteCallbackList;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-
-import static org.hamcrest.CoreMatchers.sameInstance;
-import static org.hamcrest.MatcherAssert.assertThat;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class RemoteCallbackListTest {
- @Test
- public void testBasicWiring() throws Exception {
- RemoteCallbackList<Foo> fooRemoteCallbackList = new RemoteCallbackList<Foo>();
- Foo callback = new Foo();
- fooRemoteCallbackList.register(callback);
-
- fooRemoteCallbackList.beginBroadcast();
-
- assertThat(fooRemoteCallbackList.getBroadcastItem(0), sameInstance(callback));
- }
-
- public static class Foo implements IInterface {
-
- @Override
- public IBinder asBinder() {
- return new Binder();
- }
- }
-} \ No newline at end of file
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ResolveInfoTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/ResolveInfoTest.java
deleted file mode 100644
index 16230e077..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ResolveInfoTest.java
+++ /dev/null
@@ -1,39 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.junit.Assert.assertThat;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import android.content.pm.ResolveInfo;
-
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class ResolveInfoTest {
-
- private ResolveInfo mResolveInfo;
- private ShadowResolveInfo mShadowInfo;
-
- @Before
- public void setup() {
- mResolveInfo = ShadowResolveInfo.newResolveInfo("name", "package", "activity");
- mShadowInfo = Robolectric.shadowOf(mResolveInfo);
- }
-
- @Test
- public void testLoadLabel() {
- mShadowInfo.setLabel("test");
- assertThat("test", equalTo(mResolveInfo.loadLabel(null)));
- }
-
- @Test
- public void testNewResolveInfoWithActivity() {
- assertThat(mResolveInfo.loadLabel(null).toString(), equalTo("name"));
- assertThat(mResolveInfo.activityInfo.packageName, equalTo("package"));
- assertThat(mResolveInfo.activityInfo.name, equalTo("activity"));
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ResourcesTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/ResourcesTest.java
deleted file mode 100644
index e6a240ae0..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ResourcesTest.java
+++ /dev/null
@@ -1,144 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.CoreMatchers.instanceOf;
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.CoreMatchers.notNullValue;
-import static org.junit.Assert.assertThat;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import android.app.Activity;
-import android.content.res.Configuration;
-import android.content.res.Resources;
-import android.graphics.drawable.AnimationDrawable;
-import android.graphics.drawable.BitmapDrawable;
-import android.graphics.drawable.ColorDrawable;
-import android.graphics.drawable.NinePatchDrawable;
-
-import com.xtremelabs.robolectric.R;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import com.xtremelabs.robolectric.RobolectricTestRunnerTest.RunnerForTesting;
-import com.xtremelabs.robolectric.annotation.Values;
-import com.xtremelabs.robolectric.util.TestR;
-
-
-@RunWith(WithTestDefaultsRunner.class)
-public class ResourcesTest {
-
- private Resources resources;
- private ShadowContextWrapper shadowApp;
-
- @Before
- public void setup() {
- resources = new Activity().getResources();
- shadowApp = shadowOf( Robolectric.application );
- }
-
- @Test(expected = Resources.NotFoundException.class)
- public void getStringArray_shouldThrowExceptionIfNotFound() throws Exception {
- resources.getStringArray(-1);
- }
-
- @Test
- public void testConfiguration() {
- Configuration configuration = resources.getConfiguration();
- assertThat(configuration, notNullValue());
- assertThat(configuration.locale, notNullValue());
- }
-
- @Test
- public void testConfigurationReturnsTheSameInstance() {
- assertThat(resources.getConfiguration(), is(resources.getConfiguration()));
- }
-
- @Test
- public void testNewTheme() {
- assertThat(resources.newTheme(), notNullValue());
- }
-
- /**
- * a missing R.class will result in an BitmapDrawable getting returned
- * by default
- */
- @Test
- public void testGetDrawableNullRClass() {
- shadowApp.getResourceLoader().setLocalRClass( null );
- assertThat( resources.getDrawable( TestR.anim.test_anim_1 ), instanceOf( BitmapDrawable.class ) );
- }
-
- /**
- * given an R.anim.id value, will return an AnimationDrawable
- */
- @Test
- public void testGetAnimationDrawable() {
- shadowApp.getResourceLoader().setLocalRClass( TestR.class );
- assertThat( resources.getDrawable( TestR.anim.test_anim_1 ), instanceOf( AnimationDrawable.class ) );
- }
-
- @Test
- @Values( locale="fr" )
- public void testGetResourceFromSpecificLocale(){
- String hello=resources.getString( R.string.hello );
- assertThat( hello, equalTo( "Bonjour" ) );
- }
-
- /**
- * given an R.color.id value, will return a ColorDrawable
- */
- @Test
- public void testGetColorDrawable() {
- shadowApp.getResourceLoader().setLocalRClass( TestR.class );
- assertThat( resources.getDrawable( TestR.color.test_color_1 ), instanceOf( ColorDrawable.class ) );
- }
-
- /**
- * given an R.drawable.id value, will return a BitmapDrawable
- */
- @Test
- public void testGetBitmapDrawable() {
- shadowApp.getResourceLoader().setLocalRClass( TestR.class );
- assertThat( resources.getDrawable( TestR.drawable.test_drawable_1 ), instanceOf( BitmapDrawable.class ) );
- }
-
- /**
- * given an R.drawable.id value, will return a NinePatchDrawable for .9.png file
- */
- @Test
- public void testGetNinePatchDrawable() {
- assertThat( resources.getDrawable( R.drawable.nine_patch_drawable ), instanceOf( NinePatchDrawable.class ) );
- }
-
- /**
- * given a value that doesn't in one of R's inner classes, will return a BitmapDrawable
- */
- @Test
- public void testGetBitmapDrawableForUnknownId() {
- shadowApp.getResourceLoader().setLocalRClass( TestR.class );
- assertThat( resources.getDrawable( Integer.MAX_VALUE ), instanceOf( BitmapDrawable.class ) );
- }
- @Test
- public void testDensity() {
- Activity activity = new Activity();
- assertThat(activity.getResources().getDisplayMetrics().density, equalTo(1f));
-
- shadowOf(activity.getResources()).setDensity(1.5f);
- assertThat(activity.getResources().getDisplayMetrics().density, equalTo(1.5f));
-
- Activity anotherActivity = new Activity();
- assertThat(anotherActivity.getResources().getDisplayMetrics().density, equalTo(1.5f));
- }
-
- @Test
- public void displayMetricsShouldNotHaveLotsOfZeros() throws Exception {
- Activity activity = new Activity();
- assertThat(activity.getResources().getDisplayMetrics().heightPixels, equalTo(800));
- assertThat(activity.getResources().getDisplayMetrics().widthPixels, equalTo(480));
- }
-
-
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ResultReceiverTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/ResultReceiverTest.java
deleted file mode 100644
index 53e5e65ef..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ResultReceiverTest.java
+++ /dev/null
@@ -1,38 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.os.Bundle;
-import android.os.Handler;
-import android.os.ResultReceiver;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static org.junit.Assert.assertEquals;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class ResultReceiverTest {
- @Test
- public void callingSend_shouldCallOverridenOnReceiveResultWithTheSameArguments() throws Exception {
- TestResultReceiver testResultReceiver = new TestResultReceiver(null);
- Bundle bundle = new Bundle();
-
- testResultReceiver.send(5, bundle);
- assertEquals(5, testResultReceiver.resultCode);
- assertEquals(bundle, testResultReceiver.resultData);
- }
-
- static class TestResultReceiver extends ResultReceiver {
- int resultCode;
- Bundle resultData;
-
- public TestResultReceiver(Handler handler) {
- super(handler);
- }
-
- @Override
- protected void onReceiveResult(int resultCode, Bundle resultData) {
- this.resultCode = resultCode;
- this.resultData = resultData;
- }
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/SQLiteCursorTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/SQLiteCursorTest.java
deleted file mode 100644
index 9cd0d2536..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/SQLiteCursorTest.java
+++ /dev/null
@@ -1,365 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-
-import android.database.sqlite.SQLiteCursor;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import com.xtremelabs.robolectric.util.DatabaseConfig;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import java.sql.Connection;
-import java.sql.PreparedStatement;
-import java.sql.ResultSet;
-import java.sql.Statement;
-
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.CoreMatchers.notNullValue;
-import static org.junit.Assert.assertThat;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class SQLiteCursorTest {
-
- private Connection connection;
- private ResultSet resultSet;
- private SQLiteCursor cursor;
-
- @Before
- public void setUp() throws Exception {
- connection = DatabaseConfig.getMemoryConnection();
-
- Statement statement = connection.createStatement();
- statement.execute("CREATE TABLE table_name(" +
- "id INTEGER PRIMARY KEY, name VARCHAR(255), long_value BIGINT," +
- "float_value REAL, double_value DOUBLE, blob_value BINARY, clob_value CLOB );");
-
- addPeople();
- setupCursor();
- }
-
- @After
- public void tearDown() throws Exception {
- connection.close();
- }
-
- @Test
- public void testGetColumnNames() throws Exception {
- String[] columnNames = cursor.getColumnNames();
-
- assertColumnNames(columnNames);
- }
-
- @Test
- public void testGetColumnNamesEmpty() throws Exception {
- setupEmptyResult();
- String[] columnNames = cursor.getColumnNames();
-
- // Column names are present even with an empty result.
- assertThat(columnNames, notNullValue());
- assertColumnNames(columnNames);
- }
-
- @Test
- public void testGetColumnIndex() throws Exception {
- assertThat(cursor.getColumnIndex("id"), equalTo(0));
- assertThat(cursor.getColumnIndex("name"), equalTo(1));
- }
-
- @Test
- public void testGetColumnIndexNotFound() throws Exception {
- assertThat(cursor.getColumnIndex("Fred"), equalTo(-1));
- }
-
- @Test
- public void testGetColumnIndexEmpty() throws Exception {
- setupEmptyResult();
-
- assertThat(cursor.getColumnIndex("id"), equalTo(0));
- assertThat(cursor.getColumnIndex("name"), equalTo(1));
- }
-
- @Test
- public void testGetColumnIndexOrThrow() throws Exception {
- assertThat(cursor.getColumnIndexOrThrow("id"), equalTo(0));
- assertThat(cursor.getColumnIndexOrThrow("name"), equalTo(1));
- }
-
- @Test(expected = IllegalArgumentException.class)
- public void testGetColumnIndexOrThrowNotFound() throws Exception {
- cursor.getColumnIndexOrThrow("Fred");
- }
-
- @Test
- public void testGetColumnIndexOrThrowEmpty() throws Exception {
- setupEmptyResult();
-
- assertThat(cursor.getColumnIndexOrThrow("name"), equalTo(1));
- }
-
- @Test(expected = IllegalArgumentException.class)
- public void testGetColumnIndexOrThrowNotFoundEmpty() throws Exception {
- setupEmptyResult();
-
- cursor.getColumnIndexOrThrow("Fred");
- }
-
- @Test
- public void testMoveToFirst() throws Exception {
- assertThat(cursor.moveToFirst(), equalTo(true));
- assertThat(cursor.getInt(0), equalTo(1234));
- assertThat(cursor.getString(1), equalTo("Chuck"));
- }
-
- @Test
- public void testMoveToFirstEmpty() throws Exception {
- setupEmptyResult();
-
- assertThat(cursor.moveToFirst(), equalTo(false));
- }
-
- @Test
- public void testMoveToNext() throws Exception {
- cursor.moveToFirst();
-
- assertThat(cursor.moveToNext(), equalTo(true));
- assertThat(cursor.getInt(0), equalTo(1235));
- assertThat(cursor.getString(1), equalTo("Julie"));
- }
-
- @Test
- public void testMoveToNextPastEnd() throws Exception {
- cursor.moveToFirst();
-
- cursor.moveToNext();
- cursor.moveToNext();
- cursor.moveToNext();
-
- assertThat(cursor.moveToNext(), equalTo(false));
- }
-
- @Test
- public void testMoveBackwards() throws Exception {
- assertThat(cursor.getPosition(), equalTo(-1));
-
- cursor.moveToFirst();
- assertThat(cursor.getPosition(), equalTo(0));
- cursor.moveToNext();
- assertThat(cursor.getPosition(), equalTo(1));
- cursor.moveToNext();
- assertThat(cursor.getPosition(), equalTo(2));
-
- cursor.moveToFirst();
- assertThat(cursor.getPosition(), equalTo(0));
- cursor.moveToNext();
- assertThat(cursor.getPosition(), equalTo(1));
- cursor.moveToNext();
- assertThat(cursor.getPosition(), equalTo(2));
-
- cursor.moveToPosition(1);
- assertThat(cursor.getPosition(), equalTo(1));
- }
-
- @Test
- public void testMoveToNextEmpty() throws Exception {
- setupEmptyResult();
-
- cursor.moveToFirst();
- assertThat(cursor.moveToNext(), equalTo(false));
- }
-
- @Test
- public void testMoveToPrevious() throws Exception {
- cursor.moveToFirst();
- cursor.moveToNext();
-
- assertThat(cursor.moveToPrevious(), equalTo(true));
- assertThat(cursor.getInt(0), equalTo(1234));
- assertThat(cursor.getString(1), equalTo("Chuck"));
- }
-
- @Test
- public void testMoveToPreviousPastStart() throws Exception {
- cursor.moveToFirst();
-
- // Possible to move cursor before the first item
- assertThat(cursor.moveToPrevious(), equalTo(true));
- // After that, attempts to move cursor back return false
- assertThat(cursor.moveToPrevious(), equalTo(false));
- }
-
- @Test
- public void testMoveToPreviousEmpty() throws Exception {
- setupEmptyResult();
- cursor.moveToFirst();
-
- assertThat(cursor.moveToPrevious(), equalTo(false));
- }
-
- @Test
- public void testGetPosition() throws Exception {
- cursor.moveToFirst();
- assertThat(cursor.getPosition(), equalTo(0));
-
- cursor.moveToNext();
- assertThat(cursor.getPosition(), equalTo(1));
- }
-
- @Test
- public void testGetBlob() throws Exception {
- String sql = "UPDATE table_name set blob_value=? where id=1234";
- byte[] byteData = sql.getBytes();
-
- PreparedStatement statement = connection.prepareStatement(sql);
- statement.setObject(1, byteData);
- statement.executeUpdate();
-
- setupCursor();
- cursor.moveToFirst();
-
- byte[] retrievedByteData = cursor.getBlob(5);
- assertThat(byteData.length, equalTo(retrievedByteData.length));
-
- for (int i = 0; i < byteData.length; i++) {
- assertThat(byteData[i], equalTo(retrievedByteData[i]));
- }
- }
-
- @Test
- public void testGetClob() throws Exception {
- String sql = "UPDATE table_name set clob_value=? where id=1234";
- String s = "Don't CLOBber my data, please. Thank you.";
-
- PreparedStatement statement = connection.prepareStatement(sql);
- statement.setObject(1, s);
- statement.executeUpdate();
-
- setupCursor();
- cursor.moveToFirst();
-
- String actual = cursor.getString(6);
- assertThat(s, equalTo(actual));
- }
-
- @Test
- public void testGetString() throws Exception {
- cursor.moveToFirst();
-
- String[] data = {"Chuck", "Julie", "Chris"};
-
- for (String aData : data) {
- assertThat(cursor.getString(1), equalTo(aData));
- cursor.moveToNext();
- }
- }
-
- @Test
- public void testGetInt() throws Exception {
- cursor.moveToFirst();
-
- int[] data = {1234, 1235, 1236};
-
- for (int aData : data) {
- assertThat(cursor.getInt(0), equalTo(aData));
- cursor.moveToNext();
- }
- }
-
- @Test
- public void testGetLong() throws Exception {
- cursor.moveToFirst();
-
- assertThat(cursor.getLong(2), equalTo(3463L));
- }
-
- @Test
- public void testGetFloat() throws Exception {
- cursor.moveToFirst();
-
- assertThat(cursor.getFloat(3), equalTo((float) 1.5));
- }
-
- @Test
- public void testGetDouble() throws Exception {
- cursor.moveToFirst();
-
- assertThat(cursor.getDouble(4), equalTo(3.14159));
- }
-
- @Test
- public void testClose() throws Exception {
- assertThat(cursor.isClosed(), equalTo(false));
- cursor.close();
- assertThat(cursor.isClosed(), equalTo(true));
- }
-
- @Test
- public void testIsNullWhenNull() throws Exception {
- cursor.moveToFirst();
- assertThat(cursor.moveToNext(), equalTo(true));
-
- assertThat(cursor.isNull(cursor.getColumnIndex("id")), equalTo(false));
- assertThat(cursor.isNull(cursor.getColumnIndex("name")), equalTo(false));
-
- assertThat(cursor.isNull(cursor.getColumnIndex("long_value")), equalTo(true));
- assertThat(cursor.isNull(cursor.getColumnIndex("float_value")), equalTo(true));
- assertThat(cursor.isNull(cursor.getColumnIndex("double_value")), equalTo(true));
- }
-
- @Test
- public void testIsNullWhenNotNull() throws Exception {
- cursor.moveToFirst();
-
- for (int i = 0; i < 5; i++) {
- assertThat(cursor.isNull(i), equalTo(false));
- }
- }
-
- @Test
- public void testIsNullWhenIndexOutOfBounds() throws Exception {
- cursor.moveToFirst();
-
- // column index 5 is out-of-bounds
- assertThat(cursor.isNull(5), equalTo(true));
- }
-
- private void addPeople() throws Exception {
- String[] inserts = {
- "INSERT INTO table_name (id, name, long_value, float_value, double_value) VALUES(1234, 'Chuck', 3463, 1.5, 3.14159);",
- "INSERT INTO table_name (id, name) VALUES(1235, 'Julie');",
- "INSERT INTO table_name (id, name) VALUES(1236, 'Chris');"
- };
-
- for (String insert : inserts) {
- connection.createStatement().executeUpdate(insert);
- }
- }
-
- private void setupCursor() throws Exception {
- Statement statement = connection.createStatement(DatabaseConfig.getResultSetType(), ResultSet.CONCUR_READ_ONLY);
- String sql ="SELECT * FROM table_name;";
- resultSet = statement.executeQuery("SELECT * FROM table_name;");
- cursor = new SQLiteCursor(null, null, null, null);
- Robolectric.shadowOf(cursor).setResultSet(resultSet, sql);
- }
-
- private void setupEmptyResult() throws Exception {
- Statement statement = connection.createStatement();
- statement.executeUpdate("DELETE FROM table_name;");
-
- setupCursor();
- }
-
- private void assertColumnNames(String[] columnNames) {
- assertThat(columnNames.length, equalTo(7));
- assertThat(columnNames[0], equalTo("id"));
- assertThat(columnNames[1], equalTo("name"));
- assertThat(columnNames[2], equalTo("long_value"));
- assertThat(columnNames[3], equalTo("float_value"));
- assertThat(columnNames[4], equalTo("double_value"));
- assertThat(columnNames[5], equalTo("blob_value"));
- assertThat(columnNames[6], equalTo("clob_value"));
- }
-
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/SQLiteDatabaseTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/SQLiteDatabaseTest.java
deleted file mode 100644
index 729b09cbc..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/SQLiteDatabaseTest.java
+++ /dev/null
@@ -1,46 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.content.ContentValues;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import com.xtremelabs.robolectric.util.DatabaseConfig;
-import com.xtremelabs.robolectric.util.SQLiteMap;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import java.sql.ResultSet;
-import java.sql.Statement;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.CoreMatchers.not;
-import static org.junit.Assert.assertThat;
-
-@DatabaseConfig.UsingDatabaseMap(SQLiteMap.class)
-@RunWith(WithTestDefaultsRunner.class)
-public class SQLiteDatabaseTest extends DatabaseTestBase {
-
- @Test
- public void shouldUseSQLiteDatabaseMap() throws Exception {
- assertThat(DatabaseConfig.getDatabaseMap().getClass().getName(),
- equalTo(SQLiteMap.class.getName()));
- }
-
- @Test
- public void testReplace() throws Exception {
- long id = addChuck();
- assertThat(id, not(equalTo(-1L)));
-
- ContentValues values = new ContentValues();
- values.put("id", id);
- values.put("name", "Norris");
-
- long replaceId = database.replace("table_name", null, values);
- assertThat(replaceId, equalTo(id));
-
- Statement statement = shadowOf(database).getConnection().createStatement();
- ResultSet resultSet = statement.executeQuery("SELECT name FROM table_name where id = "+id);
-
- assertThat(resultSet.next(), equalTo(true));
- assertThat(resultSet.getString(1), equalTo("Norris"));
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/SQLiteOpenHelperTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/SQLiteOpenHelperTest.java
deleted file mode 100644
index 563dc477a..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/SQLiteOpenHelperTest.java
+++ /dev/null
@@ -1,132 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-
-import android.content.Context;
-import android.database.sqlite.SQLiteDatabase;
-import android.database.sqlite.SQLiteDatabase.CursorFactory;
-import android.database.sqlite.SQLiteOpenHelper;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.CoreMatchers.notNullValue;
-import static org.hamcrest.CoreMatchers.sameInstance;
-import static org.junit.Assert.assertThat;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class SQLiteOpenHelperTest {
-
- private TestOpenHelper helper;
-
- @Before
- public void setUp() throws Exception {
- helper = new TestOpenHelper(null, "path", null, 1);
- }
-
- @Test
- public void testInitialGetReadableDatabase() throws Exception {
- SQLiteDatabase database = helper.getReadableDatabase();
- assertInitialDB(database);
- }
-
- @Test
- public void testSubsequentGetReadableDatabase() throws Exception {
- SQLiteDatabase database = helper.getReadableDatabase();
- helper.reset();
- database = helper.getReadableDatabase();
-
- assertSubsequentDB(database);
- }
-
- @Test
- public void testSameDBInstanceSubsequentGetReadableDatabase() throws Exception {
- SQLiteDatabase db1 = helper.getReadableDatabase();
- SQLiteDatabase db2 = helper.getReadableDatabase();
-
- assertThat(db1, sameInstance(db2));
- }
-
- @Test
- public void testInitialGetWritableDatabase() throws Exception {
- SQLiteDatabase database = helper.getWritableDatabase();
- assertInitialDB(database);
- }
-
- @Test
- public void testSubsequentGetWritableDatabase() throws Exception {
- helper.getWritableDatabase();
- helper.reset();
-
- assertSubsequentDB(helper.getWritableDatabase());
- }
-
- @Test
- public void testSameDBInstanceSubsequentGetWritableDatabase() throws Exception {
- SQLiteDatabase db1 = helper.getWritableDatabase();
- SQLiteDatabase db2 = helper.getWritableDatabase();
-
- assertThat(db1, sameInstance(db2));
- }
-
- @Test
- public void testClose() throws Exception {
- SQLiteDatabase database = helper.getWritableDatabase();
-
- assertThat(database.isOpen(), equalTo(true));
- helper.close();
- assertThat(database.isOpen(), equalTo(false));
- }
-
- private void assertInitialDB(SQLiteDatabase database) {
- assertDatabaseOpened(database);
- assertThat(helper.onCreateCalled, equalTo(true));
- }
-
- private void assertSubsequentDB(SQLiteDatabase database) {
- assertDatabaseOpened(database);
- assertThat(helper.onCreateCalled, equalTo(false));
- }
-
- private void assertDatabaseOpened(SQLiteDatabase database) {
- assertThat(database, notNullValue());
- assertThat(database.isOpen(), equalTo(true));
- assertThat(helper.onOpenCalled, equalTo(true));
- assertThat(helper.onUpgradeCalled, equalTo(false));
- }
-
- private class TestOpenHelper extends SQLiteOpenHelper {
-
- public boolean onCreateCalled;
- public boolean onUpgradeCalled;
- public boolean onOpenCalled;
-
- public TestOpenHelper(Context context, String name,
- CursorFactory factory, int version) {
- super(context, name, factory, version);
- reset();
- }
-
- @Override
- public void onCreate(SQLiteDatabase database) {
- onCreateCalled = true;
- }
-
- @Override
- public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) {
- onUpgradeCalled = true;
- }
-
- @Override
- public void onOpen(SQLiteDatabase database) {
- onOpenCalled = true;
- }
-
- public void reset() {
- onCreateCalled = false;
- onUpgradeCalled = false;
- onOpenCalled = false;
- }
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/SQLiteQueryBuilderTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/SQLiteQueryBuilderTest.java
deleted file mode 100644
index 41dc516d2..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/SQLiteQueryBuilderTest.java
+++ /dev/null
@@ -1,152 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-
-import android.database.sqlite.SQLiteQueryBuilder;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.junit.Assert.assertThat;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class SQLiteQueryBuilderTest {
-
- SQLiteQueryBuilder builder;
-
- @Before
- public void setUp() throws Exception {
- builder = new SQLiteQueryBuilder();
- }
-
- @Test
- public void testDistinct() {
- String sql = SQLiteQueryBuilder.buildQueryString(
- true,
- "table_name",
- new String[]{"id", "name"},
- null, null, null, null, null);
- assertThat(sql, equalTo("SELECT DISTINCT id, name FROM table_name"));
-
- }
-
- @Test
- public void testSelectColumn() {
- String sql = SQLiteQueryBuilder.buildQueryString(
- false,
- "table_name",
- new String[]{"id"},
- null, null, null, null, null);
- assertThat(sql, equalTo("SELECT id FROM table_name"));
- }
-
- @Test
- public void testSelectColumns() {
- String sql = SQLiteQueryBuilder.buildQueryString(
- false,
- "table_name",
- new String[]{"id", "name"},
- null, null, null, null, null);
- assertThat(sql, equalTo("SELECT id, name FROM table_name"));
- }
-
- @Test
- public void testSelectAllColumns() {
- String sql = SQLiteQueryBuilder.buildQueryString(
- false,
- "table_name",
- null, null, null, null, null, null);
- assertThat(sql, equalTo("SELECT * FROM table_name"));
- }
-
- @Test
- public void testWhereClause() {
- String sql = SQLiteQueryBuilder.buildQueryString(
- false,
- "table_name",
- new String[]{"person", "department", "division"},
- "(id = 2 AND name = 'Chuck')", null, null, null, null);
- assertThat(sql, equalTo("SELECT person, department, division FROM table_name WHERE (id = 2 AND name = 'Chuck')"));
- }
-
- @Test
- public void testEmptyWhereClause() {
- String sql = SQLiteQueryBuilder.buildQueryString(
- false,
- "table_name",
- new String[]{"person", "department", "division"},
- null, "person", null, null, null);
- assertThat(sql, equalTo("SELECT person, department, division FROM table_name GROUP BY person"));
- }
-
- @Test
- public void testGroupBy() {
- String sql = SQLiteQueryBuilder.buildQueryString(
- false,
- "table_name",
- new String[]{"person", "department", "division"},
- "(id = 2 AND name = 'Chuck')", "person", null, null, null);
- assertThat(sql, equalTo("SELECT person, department, division FROM table_name WHERE (id = 2 AND name = 'Chuck') GROUP BY person"));
- }
-
- @Test
- public void testEmptyGroupBy() {
- String sql = SQLiteQueryBuilder.buildQueryString(
- false,
- "table_name",
- new String[]{"person", "department", "division"},
- "(id = 2 AND name = 'Chuck')", null, "SUM(hours) < 20", null, null);
- assertThat(sql, equalTo("SELECT person, department, division FROM table_name WHERE (id = 2 AND name = 'Chuck') HAVING SUM(hours) < 20"));
- }
-
- @Test
- public void testHaving() {
- String sql = SQLiteQueryBuilder.buildQueryString(
- false,
- "table_name",
- new String[]{"person", "department", "division"},
- "(id = 2 AND name = 'Chuck')", "person", "SUM(hours) < 20", null, null);
- assertThat(sql, equalTo("SELECT person, department, division FROM table_name WHERE (id = 2 AND name = 'Chuck') GROUP BY person HAVING SUM(hours) < 20"));
- }
-
- @Test
- public void testEmptyHaving() {
- String sql = SQLiteQueryBuilder.buildQueryString(
- false,
- "table_name",
- new String[]{"person", "department", "division"},
- "(id = 2 AND name = 'Chuck')", "person", null, "id ASC", null);
- assertThat(sql, equalTo("SELECT person, department, division FROM table_name WHERE (id = 2 AND name = 'Chuck') GROUP BY person ORDER BY id ASC"));
- }
-
- @Test
- public void testSortOrder() {
- String sql = SQLiteQueryBuilder.buildQueryString(
- false,
- "table_name",
- new String[]{"person", "department", "division"},
- "(id = 2 AND name = 'Chuck')", "person", "SUM(hours) < 20", "id ASC", null);
- assertThat(sql, equalTo("SELECT person, department, division FROM table_name WHERE (id = 2 AND name = 'Chuck') GROUP BY person HAVING SUM(hours) < 20 ORDER BY id ASC"));
- }
-
- @Test
- public void testEmptySortOrder() {
- String sql = SQLiteQueryBuilder.buildQueryString(
- false,
- "table_name",
- new String[]{"person", "department", "division"},
- "(id = 2 AND name = 'Chuck')", "person", "SUM(hours) < 20", null, "10");
- assertThat(sql, equalTo("SELECT person, department, division FROM table_name WHERE (id = 2 AND name = 'Chuck') GROUP BY person HAVING SUM(hours) < 20 LIMIT 10"));
- }
-
- @Test
- public void testLimit() {
- String sql = SQLiteQueryBuilder.buildQueryString(
- false,
- "table_name",
- new String[]{"person", "department", "division"},
- "(id = 2 AND name = 'Chuck')", "person", "SUM(hours) < 20", "id ASC", "10");
- assertThat(sql, equalTo("SELECT person, department, division FROM table_name WHERE (id = 2 AND name = 'Chuck') GROUP BY person HAVING SUM(hours) < 20 ORDER BY id ASC LIMIT 10"));
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/SQLiteStatementTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/SQLiteStatementTest.java
deleted file mode 100644
index 00e512680..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/SQLiteStatementTest.java
+++ /dev/null
@@ -1,104 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.database.sqlite.SQLiteDatabase;
-import android.database.sqlite.SQLiteDoneException;
-import android.database.sqlite.SQLiteStatement;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import java.sql.ResultSet;
-import java.sql.Statement;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.junit.Assert.assertThat;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class SQLiteStatementTest {
- private SQLiteDatabase database;
-
- @Before
- public void setUp() throws Exception {
- database = SQLiteDatabase.openDatabase("path", null, 0);
- SQLiteStatement createStatement = database.compileStatement("CREATE TABLE `routine` (`id` INTEGER PRIMARY KEY AUTOINCREMENT , `name` VARCHAR , `lastUsed` INTEGER DEFAULT 0 , UNIQUE (`name`)) ;");
- createStatement.execute();
-
- SQLiteStatement createStatement2 = database.compileStatement("CREATE TABLE `countme` (`id` INTEGER PRIMARY KEY AUTOINCREMENT , `name` VARCHAR , `lastUsed` INTEGER DEFAULT 0 , UNIQUE (`name`)) ;");
- createStatement2.execute();
- }
-
- @After
- public void tearDown() throws Exception {
- database.close();
- }
-
- @Test
- public void testExecuteInsert() throws Exception {
- SQLiteStatement insertStatement = database.compileStatement("INSERT INTO `routine` (`name` ,`lastUsed` ) VALUES (?,?)");
- insertStatement.bindString(1, "Leg Press");
- insertStatement.bindLong(2, 0);
- long pkeyOne = insertStatement.executeInsert();
- insertStatement.clearBindings();
- insertStatement.bindString(1, "Bench Press");
- insertStatement.bindLong(2, 1);
- long pkeyTwo = insertStatement.executeInsert();
-
- assertThat(pkeyOne, equalTo(1L));
- assertThat(pkeyTwo, equalTo(2L));
-
- Statement statement = shadowOf(database).getConnection().createStatement();
- ResultSet resultSet = statement.executeQuery("SELECT COUNT(*) FROM `routine`");
- assertThat(resultSet.next(), equalTo(true));
- assertThat(resultSet.getInt(1), equalTo(2));
-
- statement = shadowOf(database).getConnection().createStatement();
- resultSet = statement.executeQuery("SELECT `id`, `name` ,`lastUsed` FROM `routine`");
- assertThat(resultSet.next(), equalTo(true));
- assertThat(resultSet.getInt(1), equalTo(1));
- assertThat(resultSet.getString(2), equalTo("Leg Press"));
- assertThat(resultSet.getInt(3), equalTo(0));
- assertThat(resultSet.next(), equalTo(true));
- assertThat(resultSet.getLong(1), equalTo(2L));
- assertThat(resultSet.getString(2), equalTo("Bench Press"));
- assertThat(resultSet.getInt(3), equalTo(1));
- }
-
- @Test
- public void simpleQueryTest() throws Exception {
-
- SQLiteStatement stmt = database.compileStatement("SELECT count(*) FROM `countme`");
- assertThat(stmt.simpleQueryForLong(), equalTo(0L));
- assertThat(stmt.simpleQueryForString(), equalTo("0"));
-
- SQLiteStatement insertStatement = database.compileStatement("INSERT INTO `countme` (`name` ,`lastUsed` ) VALUES (?,?)");
- insertStatement.bindString(1, "Leg Press");
- insertStatement.bindLong(2, 0);
- insertStatement.executeInsert();
- assertThat(stmt.simpleQueryForLong(), equalTo(1L));
- assertThat(stmt.simpleQueryForString(), equalTo("1"));
- insertStatement.bindString(1, "Bench Press");
- insertStatement.bindLong(2, 1);
- insertStatement.executeInsert();
- assertThat(stmt.simpleQueryForLong(), equalTo(2L));
- assertThat(stmt.simpleQueryForString(), equalTo("2"));
- }
-
- @Test(expected = SQLiteDoneException.class)
- public void simpleQueryForStringThrowsSQLiteDoneExceptionTest() throws Exception {
- //throw SQLiteDOneException if no rows returned.
- SQLiteStatement stmt = database.compileStatement("SELECT * FROM `countme` where `name`= 'cessationoftime'");
-
- assertThat(stmt.simpleQueryForString(), equalTo("0"));
- }
-
- @Test(expected = SQLiteDoneException.class)
- public void simpleQueryForLongThrowsSQLiteDoneExceptionTest() throws Exception {
- //throw SQLiteDOneException if no rows returned.
- SQLiteStatement stmt = database.compileStatement("SELECT * FROM `countme` where `name`= 'cessationoftime'");
- assertThat(stmt.simpleQueryForLong(), equalTo(0L));
-
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ScanResultTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/ScanResultTest.java
deleted file mode 100644
index 95dd98103..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ScanResultTest.java
+++ /dev/null
@@ -1,26 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.net.wifi.ScanResult;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-import static junit.framework.Assert.assertNotNull;
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.MatcherAssert.assertThat;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class ScanResultTest {
-
- @Test
- public void shouldConstruct() throws Exception {
- ScanResult scanResult = ShadowScanResult.newInstance("SSID", "BSSID", "Caps", 11, 42);
- assertThat(scanResult.SSID, equalTo("SSID"));
- assertThat(scanResult.BSSID, equalTo("BSSID"));
- assertThat(scanResult.capabilities, equalTo("Caps"));
- assertThat(scanResult.level, equalTo(11));
- assertThat(scanResult.frequency, equalTo(42));
- assertNotNull(shadowOf(scanResult).realObject);
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ScrollViewTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/ScrollViewTest.java
deleted file mode 100644
index 99fe1e195..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ScrollViewTest.java
+++ /dev/null
@@ -1,20 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.widget.ScrollView;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static junit.framework.Assert.assertEquals;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class ScrollViewTest {
- @Test
- public void shouldSmoothScrollTo() throws Exception {
- ScrollView scrollView = new ScrollView(null);
- scrollView.smoothScrollTo(7, 6);
-
- assertEquals(7, scrollView.getScrollX());
- assertEquals(6, scrollView.getScrollY());
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/SeekBarTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/SeekBarTest.java
deleted file mode 100644
index 35e7bf204..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/SeekBarTest.java
+++ /dev/null
@@ -1,63 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import static org.hamcrest.CoreMatchers.nullValue;
-import static org.hamcrest.CoreMatchers.sameInstance;
-import static org.junit.Assert.assertThat;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import android.app.Activity;
-import android.widget.SeekBar;
-
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import com.xtremelabs.robolectric.util.Transcript;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class SeekBarTest {
-
- private SeekBar seekBar;
- private ShadowSeekBar shadow;
- private SeekBar.OnSeekBarChangeListener listener;
- private Transcript transcript;
-
- @Before
- public void setup() {
- seekBar = new SeekBar(new Activity());
- shadow = Robolectric.shadowOf(seekBar);
- listener = new TestSeekBarChangedListener();
- transcript = new Transcript();
- seekBar.setOnSeekBarChangeListener(listener);
- }
-
- @Test
- public void testOnSeekBarChangedListener() {
- assertThat(shadow.getOnSeekBarChangeListener(), sameInstance(listener));
- seekBar.setOnSeekBarChangeListener(null);
- assertThat(shadow.getOnSeekBarChangeListener(), nullValue());
- }
-
- @Test
- public void testOnChangeNotification() {
- seekBar.setProgress(5);
- transcript.assertEventsSoFar("onProgressChanged() - 5");
- }
-
- private class TestSeekBarChangedListener implements SeekBar.OnSeekBarChangeListener {
-
- @Override
- public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
- transcript.add("onProgressChanged() - " + progress);
- }
-
- @Override
- public void onStartTrackingTouch(SeekBar seekBar) {
- }
-
- @Override
- public void onStopTrackingTouch(SeekBar seekBar) {
- }
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/SensorManagerTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/SensorManagerTest.java
deleted file mode 100644
index 2d2fa8f94..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/SensorManagerTest.java
+++ /dev/null
@@ -1,82 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.content.Context;
-import android.hardware.Sensor;
-import android.hardware.SensorEvent;
-import android.hardware.SensorEventListener;
-import android.hardware.SensorManager;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-import static org.junit.Assert.*;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class SensorManagerTest {
-
- private SensorManager sensorManager;
- private ShadowSensorManager shadow;
-
- @Before
- public void setup() {
- sensorManager = (SensorManager) Robolectric.application.getSystemService(Context.SENSOR_SERVICE);
- shadow = shadowOf(sensorManager);
- }
-
- @After
- public void tearDown() {
- sensorManager = null;
- shadow = null;
- }
-
- @Test
- public void shouldReturnHasListenerAfterRegisteringListener() {
- SensorEventListener listener = registerListener();
-
- assertTrue(shadow.hasListener(listener));
- }
-
- private SensorEventListener registerListener() {
- SensorEventListener listener = new TestSensorEventListener();
- Sensor sensor = sensorManager.getDefaultSensor(SensorManager.SENSOR_ACCELEROMETER);
- sensorManager.registerListener(listener, sensor, SensorManager.SENSOR_DELAY_NORMAL);
-
- return listener;
- }
-
- @Test
- public void shouldReturnHasNoListenerAfterUnregisterListener() {
- SensorEventListener listener = registerListener();
- sensorManager.unregisterListener(listener, sensorManager.getDefaultSensor(SensorManager.SENSOR_ACCELEROMETER));
-
- assertFalse(shadow.hasListener(listener));
- }
-
- @Test
- public void shouldReturnHasNoListenerByDefault() {
- SensorEventListener listener = new TestSensorEventListener();
-
- assertFalse(shadow.hasListener(listener));
- }
-
- @Test
- public void shouldCreateSensorEvent() {
- assertTrue(shadow.createSensorEvent() instanceof SensorEvent);
- }
-
- private class TestSensorEventListener implements SensorEventListener {
-
- @Override
- public void onAccuracyChanged(Sensor sensor, int accuracy) {
- }
-
- @Override
- public void onSensorChanged(SensorEvent event) {
- }
-
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ServiceTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/ServiceTest.java
deleted file mode 100644
index 8c06eacb2..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ServiceTest.java
+++ /dev/null
@@ -1,77 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import static com.xtremelabs.robolectric.Robolectric.newInstanceOf;
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-import static org.hamcrest.CoreMatchers.is;
-import static org.junit.Assert.assertThat;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import android.app.Service;
-import android.appwidget.AppWidgetProvider;
-import android.content.Intent;
-import android.content.IntentFilter;
-import android.content.ServiceConnection;
-import android.media.MediaScannerConnection;
-import android.os.IBinder;
-
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class ServiceTest {
-
- @Test(expected = IllegalStateException.class)
- public void shouldComplainIfServiceIsDestroyedWithRegisteredBroadcastReceivers() throws Exception {
- MyService service = new MyService();
- service.registerReceiver(new AppWidgetProvider(), new IntentFilter());
- service.onDestroy();
- }
-
- @Test
- public void shouldNotComplainIfServiceIsDestroyedWhileAnotherServiceHasRegisteredBroadcastReceivers() throws Exception {
- MyService service = new MyService();
-
- MyService service2 = new MyService();
- service2.registerReceiver(new AppWidgetProvider(), new IntentFilter());
-
- service.onDestroy(); // should not throw exception
- }
-
- @Test
- public void shouldUnbindServiceSuccessfully() {
- MyService service = new MyService();
- ServiceConnection conn = Robolectric.newInstanceOf(MediaScannerConnection.class);
- service.unbindService(conn);
- }
-
- @Test (expected=IllegalArgumentException.class)
- public void shouldUnbindServiceWithExceptionWhenRequested() {
- MyService service = new MyService();
- shadowOf(service).setUnbindServiceShouldThrowIllegalArgument(true);
-
- ServiceConnection conn = newInstanceOf(MediaScannerConnection.class);
- service.unbindService(conn);
- }
-
- @Test
- public void stopForeground() {
- MyService service = new MyService();
- service.stopForeground(true);
-
- ShadowService shadowService = shadowOf(service);
- assertThat(shadowService.isForegroundStopped(), is(true));
- assertThat(shadowService.getNotificationShouldRemoved(), is(true));
- }
-
- private static class MyService extends Service {
- @Override public void onDestroy() {
- super.onDestroy();
- }
-
- @Override public IBinder onBind(Intent intent) {
- return null;
- }
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/SettingsTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/SettingsTest.java
deleted file mode 100644
index b131831bd..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/SettingsTest.java
+++ /dev/null
@@ -1,104 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.app.Activity;
-import android.app.Application;
-import android.content.ContentResolver;
-import android.provider.Settings;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.CoreMatchers.nullValue;
-import static org.junit.Assert.assertThat;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class SettingsTest {
- private Activity activity;
- private ContentResolver contentResolver;
-
- @Before
- public void setUp() throws Exception {
- activity = new Activity();
- contentResolver = activity.getContentResolver();
- }
-
- @Test
- public void whileApplicationStaysSame_shouldRememberOldSettings() throws Exception {
- Settings.System.putInt(contentResolver, "property", 1);
- assertThat(Settings.System.getInt(contentResolver, "property", 0), equalTo(1));
-
- activity = new Activity();
- contentResolver = activity.getContentResolver();
- assertThat(Settings.System.getInt(contentResolver, "property", 0), equalTo(1));
- }
-
- @Test
- public void whenApplicationChanges_shouldStartWithNewSettings() throws Exception {
- Settings.System.putInt(contentResolver, "property", 1);
- assertThat(Settings.System.getInt(contentResolver, "property", 0), equalTo(1));
-
- Robolectric.application = new Application();
- activity = new Activity();
- contentResolver = activity.getContentResolver();
- assertThat(Settings.System.getInt(contentResolver, "property", 0), equalTo(0));
- }
-
- @Test
- public void testSystemGetInt() throws Exception {
- assertThat(Settings.System.getInt(contentResolver, "property", 0), equalTo(0));
- assertThat(Settings.System.getInt(contentResolver, "property", 2), equalTo(2));
-
- Settings.System.putInt(contentResolver, "property", 1);
- assertThat(Settings.System.getInt(contentResolver, "property", 0), equalTo(1));
- }
-
- @Test
- public void testSecureGetInt() throws Exception {
- assertThat(Settings.Secure.getInt(contentResolver, "property", 0), equalTo(0));
- assertThat(Settings.Secure.getInt(contentResolver, "property", 2), equalTo(2));
-
- Settings.Secure.putInt(contentResolver, "property", 1);
- assertThat(Settings.Secure.getInt(contentResolver, "property", 0), equalTo(1));
- }
-
- @Test
- public void testSystemGetString() throws Exception {
- assertThat(Settings.System.getString(contentResolver, "property"), nullValue());
-
- Settings.System.putString(contentResolver, "property", "value");
- assertThat(Settings.System.getString(contentResolver, "property"), equalTo("value"));
- }
-
- @Test
- public void testSystemGetLong() throws Exception {
- assertThat(Settings.System.getLong(contentResolver, "property", 10L), equalTo(10L));
- Settings.System.putLong(contentResolver, "property", 42L);
- assertThat(Settings.System.getLong(contentResolver, "property"), equalTo(42L));
- assertThat(Settings.System.getLong(contentResolver, "property", 10L), equalTo(42L));
- }
-
- @Test
- public void testSystemGetFloat() throws Exception {
- assertThat(Settings.System.getFloat(contentResolver, "property", 23.23f), equalTo(23.23f));
- Settings.System.putFloat(contentResolver, "property", 42.42f);
- assertThat(Settings.System.getFloat(contentResolver, "property", 10L), equalTo(42.42f));
- }
-
- @Test(expected = Settings.SettingNotFoundException.class)
- public void testSystemGetLong_exception() throws Exception {
- Settings.System.getLong(contentResolver, "property");
- }
-
- @Test(expected = Settings.SettingNotFoundException.class)
- public void testSystemGetInt_exception() throws Exception {
- Settings.System.getInt(contentResolver, "property");
- }
-
- @Test(expected = Settings.SettingNotFoundException.class)
- public void testSystemGetFloat_exception() throws Exception {
- Settings.System.getFloat(contentResolver, "property");
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ShadowAutoCompleteTextViewTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/ShadowAutoCompleteTextViewTest.java
deleted file mode 100644
index 4a98f3e32..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ShadowAutoCompleteTextViewTest.java
+++ /dev/null
@@ -1,94 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertSame;
-import static org.mockito.Mockito.mock;
-
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import android.content.Context;
-import android.widget.AdapterView.OnItemClickListener;
-import android.widget.ArrayAdapter;
-import android.widget.AutoCompleteTextView;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class ShadowAutoCompleteTextViewTest {
-
- @Test
- public void shouldStoreAdapter() {
- AutoCompleteTextView autoCompleteTextView =
- new AutoCompleteTextView(Robolectric.application);
- ArrayAdapter<Object> adapter = new ArrayAdapter<Object>(Robolectric.application, 0);
-
- autoCompleteTextView.setAdapter(adapter);
-
- assertSame(adapter, autoCompleteTextView.getAdapter());
- }
-
- @Test
- public void shouldHaveDefaultThresholdOfTwo() {
- AutoCompleteTextView autoCompleteTextView =
- new AutoCompleteTextView(Robolectric.application);
-
- assertEquals(2, autoCompleteTextView.getThreshold());
- }
-
- @Test
- public void shouldStoreThreshold() {
- AutoCompleteTextView autoCompleteTextView =
- new AutoCompleteTextView(Robolectric.application);
-
- autoCompleteTextView.setThreshold(123);
-
- assertEquals(123, autoCompleteTextView.getThreshold());
- }
-
- @Test
- public void shouldNotStoreThresholdLessThanOne() {
- AutoCompleteTextView autoCompleteTextView =
- new AutoCompleteTextView(Robolectric.application);
-
- autoCompleteTextView.setThreshold(-1);
-
- assertEquals(1, autoCompleteTextView.getThreshold());
- }
-
- @Test
- public void shouldStoreOnItemClickListener() {
- AutoCompleteTextView autoCompleteTextView =
- new AutoCompleteTextView(Robolectric.application);
- OnItemClickListener listener = mock(OnItemClickListener.class);
-
- autoCompleteTextView.setOnItemClickListener(listener);
-
- assertSame(listener, autoCompleteTextView.getOnItemClickListener());
- }
-
- @Test
- public void shouldReplaceTextAndUpdateSelection() {
- String text = "hello world";
- ReplaceableAutoCompleteTextView autoCompleteTextView =
- new ReplaceableAutoCompleteTextView(Robolectric.application);
-
- autoCompleteTextView.publicReplaceText(text);
-
- assertEquals(text, autoCompleteTextView.getText().toString());
- assertEquals(text.length(), autoCompleteTextView.getSelectionStart());
- assertEquals(text.length(), autoCompleteTextView.getSelectionEnd());
- }
-
- private static class ReplaceableAutoCompleteTextView extends AutoCompleteTextView {
-
- public ReplaceableAutoCompleteTextView(Context context) {
- super(context);
- }
-
- public void publicReplaceText(CharSequence text) {
- replaceText(text);
- }
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ShadowBinderTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/ShadowBinderTest.java
deleted file mode 100644
index ebe634085..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ShadowBinderTest.java
+++ /dev/null
@@ -1,44 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.os.Binder;
-import android.os.Parcel;
-import android.os.RemoteException;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static junit.framework.Assert.assertTrue;
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.CoreMatchers.sameInstance;
-import static org.hamcrest.MatcherAssert.assertThat;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class ShadowBinderTest {
- @Test
- public void transactCallsOnTransact() throws Exception {
- TestBinder testBinder = new TestBinder();
- Parcel data = Parcel.obtain();
- Parcel reply = Parcel.obtain();
- assertTrue(testBinder.transact(2, data, reply, 3));
- assertThat(testBinder.code, equalTo(2));
- assertThat(testBinder.data, sameInstance(data));
- assertThat(testBinder.reply, sameInstance(reply));
- assertThat(testBinder.flags, equalTo(3));
- }
-
- static class TestBinder extends Binder {
- int code;
- Parcel data;
- Parcel reply;
- int flags;
-
- @Override
- protected boolean onTransact(int code, Parcel data, Parcel reply, int flags) throws RemoteException {
- this.code = code;
- this.data = data;
- this.reply = reply;
- this.flags = flags;
- return true;
- }
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ShadowEditTextTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/ShadowEditTextTest.java
deleted file mode 100644
index e9dda18a0..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ShadowEditTextTest.java
+++ /dev/null
@@ -1,26 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.widget.EditText;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import com.xtremelabs.robolectric.tester.android.util.TestAttributeSet;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import java.util.HashMap;
-
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.junit.Assert.assertThat;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class ShadowEditTextTest {
- @Test
- public void shouldRespectMaxLength() throws Exception {
- HashMap<String, String> hash = new HashMap<String, String>();
- hash.put("android:maxLength", "5");
- TestAttributeSet attributeSet = new TestAttributeSet(hash);
- EditText editText = new EditText(Robolectric.application, attributeSet);
- editText.setText("0123456678");
- assertThat(editText.getText().toString(), equalTo("01234"));
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ShapeDrawableTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/ShapeDrawableTest.java
deleted file mode 100644
index e2348a279..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ShapeDrawableTest.java
+++ /dev/null
@@ -1,22 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.graphics.Paint;
-import android.graphics.drawable.ShapeDrawable;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static org.hamcrest.core.Is.is;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertThat;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class ShapeDrawableTest {
- @Test
- public void getPaint_ShouldReturnTheSamePaint() throws Exception {
- ShapeDrawable shapeDrawable = new ShapeDrawable();
- Paint paint = shapeDrawable.getPaint();
- assertNotNull(paint);
- assertThat(shapeDrawable.getPaint(), is(paint));
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/SignatureTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/SignatureTest.java
deleted file mode 100644
index c12e17acf..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/SignatureTest.java
+++ /dev/null
@@ -1,52 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.CoreMatchers.not;
-import static org.junit.Assert.assertArrayEquals;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertThat;
-
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import android.content.pm.Signature;
-import android.os.Parcel;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class SignatureTest {
-
- @Test
- public void shouldHaveByteArrayConstructorAndToByteArray() {
- byte[] bytes = { (byte) 0xAC, (byte) 0xDE };
- Signature signature = new Signature(bytes);
-
- assertArrayEquals(bytes, signature.toByteArray());
- }
-
- @Test
- public void shouldHaveCreator() throws Exception {
- byte[] bytes = { (byte) 0xAC, (byte) 0xDE };
- Signature expected = new Signature(bytes);
- Parcel p = Parcel.obtain();
- expected.writeToParcel(p, 0);
-
- p.setDataPosition(0);
-
- Signature actual = Signature.CREATOR.createFromParcel(p);
- assertEquals(expected, actual);
- }
-
- @Test
- public void shouldProvideEqualsAndHashCode() throws Exception {
- assertThat(new Signature(new byte[] { (byte) 0xAC }),
- equalTo(new Signature(new byte[] { (byte) 0xAC })));
- assertThat(new Signature(new byte[] { (byte) 0xAC }),
- not(equalTo(new Signature(new byte[] { (byte) 0xDE }))));
- assertThat(new Signature(new byte[] { (byte) 0xAC }).hashCode(),
- equalTo(new Signature(new byte[] { (byte) 0xAC }).hashCode()));
- assertThat(new Signature(new byte[] { (byte) 0xAC }).hashCode(),
- not(equalTo(new Signature(new byte[] { (byte) 0xDE }).hashCode())));
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/SmsManagerTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/SmsManagerTest.java
deleted file mode 100644
index 34c367ff6..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/SmsManagerTest.java
+++ /dev/null
@@ -1,71 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import junit.framework.Assert;
-
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import android.telephony.SmsManager;
-
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class SmsManagerTest {
-
- private SmsManager smsManager;
- private ShadowSmsManager shadowSmsManager;
-
- private String testDestinationAddress = "destinationAddress";
- private String testScAddress = "testServiceCenterAddress";
- private String testText = "testSmsBodyText";
-
- @Before
- public void setup() {
- Robolectric.bindShadowClass(ShadowSmsManager.class);
- smsManager = SmsManager.getDefault();
- shadowSmsManager = Robolectric.shadowOf(smsManager);
- }
-
- @After
- public void tearDown() {
- smsManager = null;
- shadowSmsManager = null;
- }
-
- @Test
- public void shouldHaveShadowSmsManager() {
- Assert.assertNotNull(shadowSmsManager);
- }
-
- @Test
- public void shouldStoreLastSentTextMessageParameters() {
-
- smsManager.sendTextMessage(testDestinationAddress, testScAddress, testText, null, null);
-
- ShadowSmsManager.TextSmsParams lastParams = shadowSmsManager.getLastSentTextMessageParams();
-
- Assert.assertEquals(testDestinationAddress, lastParams.getDestinationAddress());
- Assert.assertEquals(testScAddress, lastParams.getScAddress());
- Assert.assertEquals(testText, lastParams.getText());
- }
-
- @Test
- public void shouldClearLastSentTestMessageParameters() {
- smsManager.sendTextMessage(testDestinationAddress, testScAddress, testText, null, null);
- shadowSmsManager.clearLastSentTextMessageParams();
- Assert.assertNull(shadowSmsManager.getLastSentTextMessageParams());
- }
-
- @Test(expected=IllegalArgumentException.class)
- public void sendTextMessage_shouldThrowExceptionWithEmptyDestination() {
- smsManager.sendTextMessage("", testScAddress, testText, null, null);
- }
-
- @Test(expected=IllegalArgumentException.class)
- public void sentTextMessage_shouldThrowExceptionWithEmptyText() {
- smsManager.sendTextMessage(testDestinationAddress, testScAddress, "", null, null);
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/SpannableStringBuilderTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/SpannableStringBuilderTest.java
deleted file mode 100644
index 12fd9568a..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/SpannableStringBuilderTest.java
+++ /dev/null
@@ -1,47 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.text.SpannableStringBuilder;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.junit.Assert.assertThat;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class SpannableStringBuilderTest {
-
- @Test
- public void testAppend() throws Exception {
- SpannableStringBuilder builder = new SpannableStringBuilder("abc");
- builder.append('d').append("e").append("f");
- assertThat(builder.toString(), equalTo("abcdef"));
- }
-
- @Test
- public void testLength() throws Exception {
- SpannableStringBuilder builder = new SpannableStringBuilder("abc");
- assertThat(builder.length(), equalTo(3));
- }
-
- @Test
- public void testReplace() throws Exception {
- SpannableStringBuilder builder = new SpannableStringBuilder("abc");
- assertThat(builder.replace(2, 3, "").toString(), equalTo("ab"));
- assertThat(builder.replace(0, 2, "xyz").toString(), equalTo("xyz"));
- }
-
- @Test
- public void testInsert() throws Exception {
- SpannableStringBuilder builder = new SpannableStringBuilder("abc");
- assertThat(builder.insert(1, "xy").toString(), equalTo("axybc"));
- }
-
- @Test
- public void testDelete() throws Exception {
- SpannableStringBuilder builder = new SpannableStringBuilder("abc");
- assertThat(builder.length(), equalTo(3));
- builder.delete( 0, 3 );
- assertThat( builder.length(), equalTo(0));
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/SpannableStringTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/SpannableStringTest.java
deleted file mode 100644
index fff069d1e..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/SpannableStringTest.java
+++ /dev/null
@@ -1,136 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.CoreMatchers.notNullValue;
-import static org.hamcrest.CoreMatchers.sameInstance;
-import static org.junit.Assert.assertThat;
-
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import android.text.SpannableString;
-import android.text.style.URLSpan;
-import android.text.style.UnderlineSpan;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class SpannableStringTest {
-
- private SpannableString spanStr;
-
- private static final String TEST_STRING =
- "Visit us at http://www.foobar.com for more selections";
-
- @Before
- public void setUp() throws Exception {
- spanStr = new SpannableString(TEST_STRING);
- }
-
- @Test
- public void testToString() {
- assertThat(spanStr.toString(), sameInstance(TEST_STRING));
- }
-
- @Test
- public void testSetSpan() {
- URLSpan s1 = new URLSpan("http://www.foobar.com");
- UnderlineSpan s2 = new UnderlineSpan();
- spanStr.setSpan(s1, 12, 33, 0);
- spanStr.setSpan(s2, 1, 10, 0);
-
- assertBothSpans(s1, s2);
- }
-
- @Test
- public void testRemoveSpan() {
- URLSpan s1 = new URLSpan("http://www.foobar.com");
- UnderlineSpan s2 = new UnderlineSpan();
- spanStr.setSpan(s1, 12, 33, 0);
- spanStr.setSpan(s2, 1, 10, 0);
- spanStr.removeSpan(s1);
-
- Object[] spans = spanStr.getSpans(0, TEST_STRING.length(), Object.class);
- assertThat(spans, notNullValue());
- assertThat(spans.length, equalTo(1));
- assertThat((UnderlineSpan) spans[0], sameInstance(s2));
- }
-
- @Test
- public void testGetSpans() {
- URLSpan s1 = new URLSpan("http://www.foobar.com");
- UnderlineSpan s2 = new UnderlineSpan();
- spanStr.setSpan(s1, 1, 10, 0);
- spanStr.setSpan(s2, 20, 30, 0);
-
- Object[] spans = spanStr.getSpans(0, TEST_STRING.length(), Object.class);
- assertThat(spans, notNullValue());
- assertThat(spans.length, equalTo(2));
- assertBothSpans(s1, s2);
-
- spans = spanStr.getSpans(0, TEST_STRING.length(), URLSpan.class);
- assertThat(spans, notNullValue());
- assertThat(spans.length, equalTo(1));
- assertThat((URLSpan) spans[0], sameInstance(s1));
-
- spans = spanStr.getSpans(11, 35, Object.class);
- assertThat(spans, notNullValue());
- assertThat(spans.length, equalTo(1));
- assertThat((UnderlineSpan) spans[0], sameInstance(s2));
-
- spans = spanStr.getSpans(21, 35, Object.class);
- assertThat(spans, notNullValue());
- assertThat(spans.length, equalTo(1));
- assertThat((UnderlineSpan) spans[0], sameInstance(s2));
-
- spans = spanStr.getSpans(5, 15, Object.class);
- assertThat(spans, notNullValue());
- assertThat(spans.length, equalTo(1));
- assertThat((URLSpan) spans[0], sameInstance(s1));
- }
-
- @Test
- public void testGetSpanStart() {
- URLSpan s1 = new URLSpan("http://www.foobar.com");
- UnderlineSpan s2 = new UnderlineSpan();
-
- assertThat(spanStr.getSpanStart(s1), equalTo(-1));
- assertThat(spanStr.getSpanStart(s2), equalTo(-1));
-
- spanStr.setSpan(s1, 0, 4, 0);
- assertThat(spanStr.getSpanStart(s1), equalTo(0));
-
- spanStr.setSpan(s2, 2, TEST_STRING.length(), 0);
- assertThat(spanStr.getSpanStart(s2), equalTo(2));
- }
-
- @Test
- public void testGetSpanEnd() {
- URLSpan s1 = new URLSpan("http://www.foobar.com");
- UnderlineSpan s2 = new UnderlineSpan();
-
- assertThat(spanStr.getSpanEnd(s1), equalTo(-1));
- assertThat(spanStr.getSpanEnd(s2), equalTo(-1));
-
- spanStr.setSpan(s1, 0, 4, 0);
- assertThat(spanStr.getSpanEnd(s1), equalTo(4));
-
- spanStr.setSpan(s2, 2, TEST_STRING.length(), 0);
- assertThat(spanStr.getSpanEnd(s2), equalTo(TEST_STRING.length()));
- }
-
- private void assertBothSpans(URLSpan s1, UnderlineSpan s2) {
- Object[] spans = spanStr.getSpans(0, TEST_STRING.length(), Object.class);
- if (spans[0] instanceof URLSpan) {
- assertThat((URLSpan) spans[0], sameInstance(s1));
- } else {
- assertThat((UnderlineSpan) spans[0], sameInstance(s2));
- }
- if (spans[1] instanceof UnderlineSpan) {
- assertThat((UnderlineSpan) spans[1], sameInstance(s2));
- } else {
- assertThat((URLSpan) spans[1], sameInstance(s1));
- }
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/SparseArrayTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/SparseArrayTest.java
deleted file mode 100644
index db0141ca1..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/SparseArrayTest.java
+++ /dev/null
@@ -1,177 +0,0 @@
-/*
- * Copyright (C) 2006 The Android Open Source Project
- * Copyright (C) 2011 Eric Bowman
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.xtremelabs.robolectric.shadows;
-
-import android.util.SparseArray;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import com.xtremelabs.robolectric.bytecode.ShadowWrangler;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-
-/**
- * Tests for shadow implementation of SparseArray. Basically copied & pasted the
- * real SparseArray tests from the 2.2 SDK.
- *
- * @author Eric Bowman (ebowman@boboco.ie)
- * @since 2011-02-25 11:01
- */
-@RunWith(WithTestDefaultsRunner.class)
-public class SparseArrayTest {
- private static final int[] KEYS = {12, 23, 4, 6, 8, 1, 3, -12, 0, -3, 11, 14, -23};
- private static final Integer[] VALUES = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
- private static final int LENGTH = VALUES.length;
- private static final int NON_EXISTED_KEY = 123;
- private static final Integer VALUE_FOR_NON_EXISTED_KEY = -1;
-
- @Test
- public void testSparseArrayWithDefaultCapacity() {
- ShadowWrangler.getInstance().logMissingInvokedShadowMethods();
- SparseArray<Integer> sparseArray = new SparseArray<Integer>();
- assertEquals(0, sparseArray.size());
-
- int length = VALUES.length;
-
- for (int i = 0; i < length; i++) {
- sparseArray.put(KEYS[i], VALUES[i]);
- assertEquals(i + 1, sparseArray.size());
- }
-
- for (int i = 0; i < length; i++) {
- assertEquals(new Integer(i), sparseArray.get(KEYS[i]));
- }
-
- for (int i = 0; i < length; i++) {
- assertEquals(sparseArray.indexOfValue(VALUES[i]), sparseArray.indexOfKey(KEYS[i]));
- }
-
- // for key already exist, old value will be replaced
- int existKey = KEYS[0];
- Integer oldValue = VALUES[0]; // 0
- Integer newValue = 100;
- assertEquals(oldValue, sparseArray.get(existKey));
- assertEquals(LENGTH, sparseArray.size());
- sparseArray.put(existKey, newValue);
- assertEquals(newValue, sparseArray.get(existKey));
- assertEquals(LENGTH, sparseArray.size());
-
- assertEquals(VALUE_FOR_NON_EXISTED_KEY,
- sparseArray.get(NON_EXISTED_KEY, VALUE_FOR_NON_EXISTED_KEY));
- assertNull(sparseArray.get(NON_EXISTED_KEY)); // the default value is null
-
- int size = sparseArray.size();
- sparseArray.append(NON_EXISTED_KEY, VALUE_FOR_NON_EXISTED_KEY);
- assertEquals(size + 1, sparseArray.size());
- assertEquals(size, sparseArray.indexOfKey(NON_EXISTED_KEY));
- assertEquals(size, sparseArray.indexOfValue(VALUE_FOR_NON_EXISTED_KEY));
- assertEquals(NON_EXISTED_KEY, sparseArray.keyAt(size));
- assertEquals(VALUE_FOR_NON_EXISTED_KEY, sparseArray.valueAt(size));
-
- sparseArray.setValueAt(size, VALUES[1]);
- assertTrue(VALUE_FOR_NON_EXISTED_KEY != sparseArray.valueAt(size));
- assertEquals(VALUES[1], sparseArray.valueAt(size));
-
- size = sparseArray.size();
- assertEquals(VALUES[1], sparseArray.get(KEYS[1]));
- assertFalse(VALUE_FOR_NON_EXISTED_KEY == VALUES[1]);
- sparseArray.delete(KEYS[1]);
- assertEquals(VALUE_FOR_NON_EXISTED_KEY,
- sparseArray.get(KEYS[1], VALUE_FOR_NON_EXISTED_KEY));
- assertEquals(size - 1, sparseArray.size());
-
- size = sparseArray.size();
- assertEquals(VALUES[2], sparseArray.get(KEYS[2]));
- assertFalse(VALUE_FOR_NON_EXISTED_KEY == VALUES[2]);
- sparseArray.remove(KEYS[2]);
- assertEquals(VALUE_FOR_NON_EXISTED_KEY,
- sparseArray.get(KEYS[2], VALUE_FOR_NON_EXISTED_KEY));
- assertEquals(size - 1, sparseArray.size());
-
- sparseArray.clear();
- assertEquals(0, sparseArray.size());
- }
-
- @Test
- public void testSparseArrayWithSpecifiedCapacity() {
- SparseArray<Integer> sparseArray = new SparseArray<Integer>(5);
- assertEquals(0, sparseArray.size());
-
- int length = VALUES.length;
-
- for (int i = 0; i < length; i++) {
- sparseArray.put(KEYS[i], VALUES[i]);
- assertEquals(i + 1, sparseArray.size());
- }
-
- for (int i = 0; i < length; i++) {
- assertEquals(VALUES[i], sparseArray.get(KEYS[i]));
- }
-
- for (int i = 0; i < length; i++) {
- assertEquals(sparseArray.indexOfValue(VALUES[i]), sparseArray.indexOfKey(KEYS[i]));
- }
-
- // for key already exist, old value will be replaced
- int existKey = KEYS[0];
- Integer oldValue = VALUES[0]; // 0
- Integer newValue = 100;
- assertEquals(oldValue, sparseArray.get(existKey));
- assertEquals(LENGTH, sparseArray.size());
- sparseArray.put(existKey, newValue);
- assertEquals(newValue, sparseArray.get(existKey));
- assertEquals(LENGTH, sparseArray.size());
-
- assertEquals(VALUE_FOR_NON_EXISTED_KEY,
- sparseArray.get(NON_EXISTED_KEY, VALUE_FOR_NON_EXISTED_KEY));
- assertNull(sparseArray.get(NON_EXISTED_KEY)); // the default value is null
-
- int size = sparseArray.size();
- sparseArray.append(NON_EXISTED_KEY, VALUE_FOR_NON_EXISTED_KEY);
- assertEquals(size + 1, sparseArray.size());
- assertEquals(size, sparseArray.indexOfKey(NON_EXISTED_KEY));
- assertEquals(size, sparseArray.indexOfValue(VALUE_FOR_NON_EXISTED_KEY));
- assertEquals(NON_EXISTED_KEY, sparseArray.keyAt(size));
- assertEquals(VALUE_FOR_NON_EXISTED_KEY, sparseArray.valueAt(size));
-
- sparseArray.setValueAt(size, VALUES[1]);
- assertTrue(VALUE_FOR_NON_EXISTED_KEY != sparseArray.valueAt(size));
- assertEquals(VALUES[1], sparseArray.valueAt(size));
-
- size = sparseArray.size();
- assertEquals(VALUES[1], sparseArray.get(KEYS[1]));
- assertFalse(VALUE_FOR_NON_EXISTED_KEY == VALUES[1]);
- sparseArray.delete(KEYS[1]);
- assertEquals(VALUE_FOR_NON_EXISTED_KEY,
- sparseArray.get(KEYS[1], VALUE_FOR_NON_EXISTED_KEY));
- assertEquals(size - 1, sparseArray.size());
-
- size = sparseArray.size();
- assertEquals(VALUES[2], sparseArray.get(KEYS[2]));
- assertFalse(VALUE_FOR_NON_EXISTED_KEY == VALUES[2]);
- sparseArray.remove(KEYS[2]);
- assertEquals(VALUE_FOR_NON_EXISTED_KEY,
- sparseArray.get(KEYS[2], VALUE_FOR_NON_EXISTED_KEY));
- assertEquals(size - 1, sparseArray.size());
-
- sparseArray.clear();
- assertEquals(0, sparseArray.size());
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/SpinnerTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/SpinnerTest.java
deleted file mode 100644
index 1a21b7cff..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/SpinnerTest.java
+++ /dev/null
@@ -1,29 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.app.Activity;
-import android.widget.Spinner;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static org.hamcrest.CoreMatchers.is;
-import static org.junit.Assert.assertThat;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class SpinnerTest {
-
- private Spinner spinner;
-
- @Before
- public void beforeTests() {
- spinner = new Spinner(new Activity());
- }
-
- @Test
- public void testPrompt() {
- spinner.setPrompt("foo");
-
- assertThat(spinner.getPrompt().toString(), is("foo"));
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/SslErrorHandlerTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/SslErrorHandlerTest.java
deleted file mode 100644
index ed10a0c1b..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/SslErrorHandlerTest.java
+++ /dev/null
@@ -1,47 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import android.webkit.SslErrorHandler;
-
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.CoreMatchers.instanceOf;
-import static org.junit.Assert.assertThat;
-
-
-@RunWith(WithTestDefaultsRunner.class)
-public class SslErrorHandlerTest {
-
- private SslErrorHandler handler;
- private ShadowSslErrorHandler shadow;
-
- @Before
- public void setUp() throws Exception {
- handler = Robolectric.newInstanceOf(SslErrorHandler.class);
- shadow = Robolectric.shadowOf(handler);
- }
-
- @Test
- public void shouldInheritFromShadowHandler() {
- assertThat(shadow, instanceOf(ShadowHandler.class));
- }
-
- @Test
- public void shouldRecordCancel() {
- assertThat(shadow.wasCancelCalled(), equalTo(false));
- handler.cancel();
- assertThat(shadow.wasCancelCalled(), equalTo(true));
- }
-
- @Test
- public void shouldRecordProceed() {
- assertThat(shadow.wasProceedCalled(), equalTo(false));
- handler.proceed();
- assertThat(shadow.wasProceedCalled(), equalTo(true));
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/StatFsTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/StatFsTest.java
deleted file mode 100644
index 0c5d7efcc..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/StatFsTest.java
+++ /dev/null
@@ -1,63 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.junit.Assert.assertThat;
-
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import android.os.StatFs;
-
-import java.io.File;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class StatFsTest {
- @Test
- public void shouldRegisterStats() throws Exception {
- ShadowStatFs.registerStats("/tmp", 100, 20, 10);
- StatFs statsFs = new StatFs("/tmp");
-
- assertThat(statsFs.getBlockCount(), equalTo(100));
- assertThat(statsFs.getFreeBlocks(), equalTo(20));
- assertThat(statsFs.getAvailableBlocks(), equalTo(10));
- assertThat(statsFs.getBlockSize(), equalTo(ShadowStatFs.BLOCK_SIZE));
- }
-
- @Test
- public void shouldRegisterStatsWithFile() throws Exception {
- ShadowStatFs.registerStats(new File("/tmp"), 100, 20, 10);
- StatFs statsFs = new StatFs("/tmp");
-
- assertThat(statsFs.getBlockCount(), equalTo(100));
- assertThat(statsFs.getFreeBlocks(), equalTo(20));
- assertThat(statsFs.getAvailableBlocks(), equalTo(10));
- assertThat(statsFs.getBlockSize(), equalTo(ShadowStatFs.BLOCK_SIZE));
- }
-
- @Test
- public void shouldResetStateBetweenTests() throws Exception {
- StatFs statsFs = new StatFs("/tmp");
- assertThat(statsFs.getBlockCount(), equalTo(0));
- assertThat(statsFs.getFreeBlocks(), equalTo(0));
- assertThat(statsFs.getAvailableBlocks(), equalTo(0));
- assertThat(statsFs.getBlockSize(), equalTo(ShadowStatFs.BLOCK_SIZE));
- }
-
- @Test
- public void shouldRestat() throws Exception {
- ShadowStatFs.registerStats("/tmp", 100, 20, 10);
- StatFs statsFs = new StatFs("/tmp");
-
- assertThat(statsFs.getBlockCount(), equalTo(100));
- assertThat(statsFs.getFreeBlocks(), equalTo(20));
- assertThat(statsFs.getAvailableBlocks(), equalTo(10));
-
- ShadowStatFs.registerStats("/tmp", 3, 2, 1);
-
- statsFs.restat("/tmp");
- assertThat(statsFs.getBlockCount(), equalTo(3));
- assertThat(statsFs.getFreeBlocks(), equalTo(2));
- assertThat(statsFs.getAvailableBlocks(), equalTo(1));
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/StateListDrawableTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/StateListDrawableTest.java
deleted file mode 100644
index 96be401fb..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/StateListDrawableTest.java
+++ /dev/null
@@ -1,45 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.R;
-import android.graphics.drawable.Drawable;
-import android.graphics.drawable.StateListDrawable;
-import android.util.StateSet;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-import static org.hamcrest.CoreMatchers.is;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertThat;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class StateListDrawableTest {
-
- @Test
- public void testAddStateWithDrawable() {
- Drawable drawable = ShadowDrawable.createFromPath("/foo");
-
- StateListDrawable stateListDrawable = new StateListDrawable();
- int[] states = {R.attr.state_pressed};
- stateListDrawable.addState(states, drawable);
-
- ShadowStateListDrawable shadow = shadowOf(stateListDrawable);
- Drawable drawableForState = shadow.getDrawableForState(states);
- assertNotNull(drawableForState);
- assertThat(((ShadowBitmapDrawable) shadowOf(drawableForState)).getPath(), is("/foo"));
- }
-
- @Test
- public void testAddDrawableWithWildCardState() {
- Drawable drawable = ShadowDrawable.createFromPath("/foo");
-
- StateListDrawable stateListDrawable = new StateListDrawable();
- stateListDrawable.addState(StateSet.WILD_CARD, drawable);
-
- ShadowStateListDrawable shadow = shadowOf(stateListDrawable);
- Drawable drawableForState = shadow.getDrawableForState(StateSet.WILD_CARD);
- assertNotNull(drawableForState);
- assertThat(((ShadowBitmapDrawable) shadowOf(drawableForState)).getPath(), is("/foo"));
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/SyncResultTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/SyncResultTest.java
deleted file mode 100644
index 5ccfa4467..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/SyncResultTest.java
+++ /dev/null
@@ -1,59 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import static junit.framework.Assert.assertFalse;
-import static junit.framework.Assert.assertTrue;
-import static org.hamcrest.CoreMatchers.*;
-import static org.junit.Assert.assertThat;
-
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import android.content.SyncResult;
-
-
-@RunWith(WithTestDefaultsRunner.class)
-public class SyncResultTest {
-
- @Test
- public void testConstructor() throws Exception {
- SyncResult result = new SyncResult();
- assertThat(result.stats, not(nullValue()));
- }
-
- @Test
- public void hasSoftError() throws Exception {
- SyncResult result = new SyncResult();
- assertFalse(result.hasSoftError());
- result.stats.numIoExceptions++;
- assertTrue(result.hasSoftError());
- assertTrue(result.hasError());
- }
-
- @Test
- public void hasHardError() throws Exception {
- SyncResult result = new SyncResult();
- assertFalse(result.hasHardError());
- result.stats.numAuthExceptions++;
- assertTrue(result.hasHardError());
- assertTrue(result.hasError());
- }
-
- @Test
- public void testMadeSomeProgress() throws Exception {
- SyncResult result = new SyncResult();
- assertFalse(result.madeSomeProgress());
- result.stats.numInserts++;
- assertTrue(result.madeSomeProgress());
- }
-
- @Test
- public void testClear() throws Exception {
- SyncResult result = new SyncResult();
- result.moreRecordsToGet = true;
- result.stats.numInserts++;
- result.clear();
- assertFalse(result.moreRecordsToGet);
- assertThat(result.stats.numInserts, is(0L));
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/TabActivityTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/TabActivityTest.java
deleted file mode 100644
index 6d0460e5a..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/TabActivityTest.java
+++ /dev/null
@@ -1,33 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.app.TabActivity;
-import android.widget.TabHost;
-import android.widget.TabWidget;
-import com.xtremelabs.robolectric.R;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static org.hamcrest.CoreMatchers.instanceOf;
-import static org.hamcrest.core.IsEqual.equalTo;
-import static org.junit.Assert.assertThat;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class TabActivityTest {
-
- @Test
- public void tabActivityShouldNotMakeNewTabHostEveryGet() throws Exception {
- TabActivity activity = new TabActivity();
- TabHost tabHost1 = activity.getTabHost();
- TabHost tabHost2 = activity.getTabHost();
-
- assertThat(tabHost1, equalTo(tabHost2));
- }
-
- @Test
- public void shouldGetTabWidget() throws Exception {
- TabActivity activity = new TabActivity();
- activity.setContentView(R.layout.tab_activity);
- assertThat(activity.getTabWidget(), instanceOf(TabWidget.class));
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/TabHostTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/TabHostTest.java
deleted file mode 100644
index cdd45db75..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/TabHostTest.java
+++ /dev/null
@@ -1,206 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.app.Activity;
-import android.app.TabActivity;
-import android.view.View;
-import android.widget.TabHost;
-import android.widget.TabHost.TabContentFactory;
-import android.widget.TabWidget;
-import android.widget.TextView;
-import com.xtremelabs.robolectric.R;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-import static org.hamcrest.CoreMatchers.instanceOf;
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.core.IsEqual.equalTo;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertThat;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class TabHostTest {
-
- @Test
- public void newTabSpec_shouldMakeATabSpec() throws Exception {
- TabHost tabHost = new TabHost(null);
- TabHost.TabSpec tabSpec = tabHost.newTabSpec("Foo");
- assertThat(tabSpec.getTag(), equalTo("Foo"));
- }
-
- @Test
- public void shouldAddTabsToLayoutWhenAddedToHost() {
- TabHost tabHost = new TabHost(null);
-
- View fooView = new View(null);
- TabHost.TabSpec foo = tabHost.newTabSpec("Foo").setIndicator(fooView);
-
- View barView = new View(null);
- TabHost.TabSpec bar = tabHost.newTabSpec("Bar").setIndicator(barView);
-
- tabHost.addTab(foo);
- tabHost.addTab(bar);
-
- assertThat(tabHost.getChildAt(0), is(fooView));
- assertThat(tabHost.getChildAt(1), is(barView));
- }
-
- @Test
- public void shouldReturnTabSpecsByTag() throws Exception {
- TabHost tabHost = new TabHost(null);
- TabHost.TabSpec foo = tabHost.newTabSpec("Foo");
- TabHost.TabSpec bar = tabHost.newTabSpec("Bar");
- TabHost.TabSpec baz = tabHost.newTabSpec("Baz");
-
- tabHost.addTab(foo);
- tabHost.addTab(bar);
- tabHost.addTab(baz);
-
- assertThat(shadowOf(tabHost).getSpecByTag("Bar"), is(bar));
- assertThat(shadowOf(tabHost).getSpecByTag("Baz"), is(baz));
- assertNull(shadowOf(tabHost).getSpecByTag("Whammie"));
- }
-
- @Test
- public void shouldFireTheTabChangeListenerWhenCurrentTabIsSet() throws Exception {
- TabHost tabHost = new TabHost(null);
-
- TabHost.TabSpec foo = tabHost.newTabSpec("Foo");
- TabHost.TabSpec bar = tabHost.newTabSpec("Bar");
- TabHost.TabSpec baz = tabHost.newTabSpec("Baz");
-
- tabHost.addTab(foo);
- tabHost.addTab(bar);
- tabHost.addTab(baz);
-
- TestOnTabChangeListener listener = new TestOnTabChangeListener();
- tabHost.setOnTabChangedListener(listener);
-
- tabHost.setCurrentTab(2);
-
- assertThat(listener.tag, equalTo("Baz"));
- }
-
- @Test
- public void shouldFireTheTabChangeListenerWhenTheCurrentTabIsSetByTag() throws Exception {
- TabHost tabHost = new TabHost(null);
-
- TabHost.TabSpec foo = tabHost.newTabSpec("Foo");
- TabHost.TabSpec bar = tabHost.newTabSpec("Bar");
- TabHost.TabSpec baz = tabHost.newTabSpec("Baz");
-
- tabHost.addTab(foo);
- tabHost.addTab(bar);
- tabHost.addTab(baz);
-
- TestOnTabChangeListener listener = new TestOnTabChangeListener();
- tabHost.setOnTabChangedListener(listener);
-
- tabHost.setCurrentTabByTag("Bar");
-
- assertThat(listener.tag, equalTo("Bar"));
- }
-
- @Test
- public void shouldRetrieveTheCurrentViewFromTabContentFactory() {
- TabHost tabHost = new TabHost(null);
-
- TabHost.TabSpec foo = tabHost.newTabSpec("Foo").setContent(
- new TabContentFactory() {
- public View createTabContent(String tag) {
- TextView tv = new TextView(null);
- tv.setText("The Text of " + tag);
- return tv;
- }
- });
-
- tabHost.addTab(foo);
- tabHost.setCurrentTabByTag("Foo");
- TextView textView = (TextView) tabHost.getCurrentView();
-
- assertThat(textView.getText().toString(), equalTo("The Text of Foo"));
- }
- @Test
- public void shouldRetrieveTheCurrentViewFromViewId() {
- Activity a = new Activity();
- a.setContentView(com.xtremelabs.robolectric.R.layout.main);
- TabHost tabHost = new TabHost(a);
- TabHost.TabSpec foo = tabHost.newTabSpec("Foo")
- .setContent(com.xtremelabs.robolectric.R.id.title);
-
- tabHost.addTab(foo);
- tabHost.setCurrentTabByTag("Foo");
- TextView textView = (TextView) tabHost.getCurrentView();
-
- assertThat(textView.getText().toString(), equalTo("Main Layout"));
- }
-
- private static class TestOnTabChangeListener implements TabHost.OnTabChangeListener {
- private String tag;
-
- @Override
- public void onTabChanged(String tag) {
- this.tag = tag;
- }
- }
-
- @Test
- public void canGetCurrentTabTag() throws Exception {
- TabHost tabHost = new TabHost(null);
-
- TabHost.TabSpec foo = tabHost.newTabSpec("Foo");
- TabHost.TabSpec bar = tabHost.newTabSpec("Bar");
- TabHost.TabSpec baz = tabHost.newTabSpec("Baz");
-
- tabHost.addTab(foo);
- tabHost.addTab(bar);
- tabHost.addTab(baz);
-
- tabHost.setCurrentTabByTag("Bar");
-
- assertThat(tabHost.getCurrentTabTag(), equalTo("Bar"));
- }
-
- @Test
- public void canGetCurrentTab() throws Exception {
- TabHost tabHost = new TabHost(null);
-
- TabHost.TabSpec foo = tabHost.newTabSpec("Foo");
- TabHost.TabSpec bar = tabHost.newTabSpec("Bar");
- TabHost.TabSpec baz = tabHost.newTabSpec("Baz");
-
- tabHost.addTab(foo);
- tabHost.addTab(bar);
- tabHost.addTab(baz);
- assertThat(shadowOf(tabHost).getCurrentTabSpec(), equalTo(foo));
- assertThat(tabHost.getCurrentTab(), equalTo(0));
- tabHost.setCurrentTabByTag("Bar");
- assertThat(tabHost.getCurrentTab(), equalTo(1));
- assertThat(shadowOf(tabHost).getCurrentTabSpec(), equalTo(bar));
- tabHost.setCurrentTabByTag("Foo");
- assertThat(tabHost.getCurrentTab(), equalTo(0));
- assertThat(shadowOf(tabHost).getCurrentTabSpec(), equalTo(foo));
- tabHost.setCurrentTabByTag("Baz");
- assertThat(tabHost.getCurrentTab(), equalTo(2));
- assertThat(shadowOf(tabHost).getCurrentTabSpec(), equalTo(baz));
- }
-
- @Test
- public void setCurrentTabByTagShouldAcceptNullAsParameter() throws Exception {
- TabHost tabHost = new TabHost(null);
- TabHost.TabSpec foo = tabHost.newTabSpec("Foo");
- tabHost.addTab(foo);
-
- tabHost.setCurrentTabByTag(null);
- assertThat(tabHost.getCurrentTabTag(), equalTo("Foo"));
- }
-
- @Test
- public void shouldGetTabWidget() throws Exception {
- TabActivity activity = new TabActivity();
- activity.setContentView(R.layout.tab_activity);
- TabHost host = new TabHost(activity);
- assertThat(host.getTabWidget(), instanceOf(TabWidget.class));
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/TabSpecTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/TabSpecTest.java
deleted file mode 100644
index 74959bca2..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/TabSpecTest.java
+++ /dev/null
@@ -1,119 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.content.Intent;
-import android.graphics.Canvas;
-import android.graphics.ColorFilter;
-import android.graphics.drawable.Drawable;
-import android.view.View;
-import android.widget.TabHost;
-import android.widget.TabHost.TabContentFactory;
-import android.widget.TextView;
-import com.xtremelabs.robolectric.R;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-import static org.hamcrest.core.Is.is;
-import static org.hamcrest.core.IsEqual.equalTo;
-import static org.junit.Assert.assertThat;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class TabSpecTest {
- Drawable icon1;
-
- @Before
- public void init() {
- icon1 = new TestIcon();
- }
-
- @Test
- public void shouldGetAndSetTheIndicator() throws Exception {
- TabHost.TabSpec spec = new TabHost(null).newTabSpec("foo");
- View view = new View(null);
- TabHost.TabSpec self = spec.setIndicator(view);
- assertThat(self, is(spec));
- assertThat(shadowOf(spec).getIndicatorAsView(), is(view));
- }
-
- @Test
- public void shouldGetAndSetTheIntentContent() throws Exception {
- TabHost.TabSpec spec = new TabHost(null).newTabSpec("foo");
- Intent intent = new Intent();
- TabHost.TabSpec self = spec.setContent(intent);
- assertThat(self, is(spec));
- assertThat(shadowOf(spec).getContentAsIntent(), is(intent));
- }
-
-
-
- @Test
- public void shouldGetAndSetTheIndicatorLabel() throws Exception {
- TabHost.TabSpec spec = new TabHost(null).newTabSpec("foo")
- .setContent(R.layout.main).setIndicator("labelText");
-
- assertThat(shadowOf(spec).getIndicatorLabel(), is("labelText"));
- assertThat(shadowOf(spec).getText(), is("labelText"));
- }
- @Test
- public void shouldGetAndSetTheIndicatorLabelAndIcon() throws Exception {
- TabHost.TabSpec spec = new TabHost(null).newTabSpec("foo")
- .setContent(R.layout.main).setIndicator("labelText",icon1);
-
- assertThat(shadowOf(spec).getIndicatorLabel(), is("labelText"));
- assertThat(shadowOf(spec).getText(), is("labelText"));
- assertThat(shadowOf(spec).getIndicatorIcon(), is(icon1));
- }
-
- @Test
- public void shouldSetTheContentView() throws Exception {
- TabHost.TabSpec foo = new TabHost(null).newTabSpec("Foo").setContent(
- new TabContentFactory() {
- public View createTabContent(String tag) {
- TextView tv = new TextView(null);
- tv.setText("The Text of " + tag);
- return tv;
- }
- });
-
- ShadowTabSpec shadowFoo = shadowOf(foo);
- TextView textView = (TextView) shadowFoo.getContentView();
-
-
- assertThat(textView.getText().toString(), equalTo("The Text of Foo"));
- }
-
- @Test
- public void shouldSetTheContentViewId() throws Exception {
- TabHost.TabSpec foo = new TabHost(null).newTabSpec("Foo")
- .setContent(R.id.title);
-
- ShadowTabSpec shadowFoo = shadowOf(foo);
- int viewId = shadowFoo.getContentViewId();
-
- assertThat(viewId, equalTo(R.id.title));
-}
-
- private class TestIcon extends Drawable {
-
- @Override
- public void draw(Canvas canvas) {
- }
-
- @Override
- public void setAlpha(int alpha) {
- }
-
- @Override
- public void setColorFilter(ColorFilter cf) {
- }
-
- @Override
- public int getOpacity() {
- return 0;
- }
-
- }
-
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/TelephonyManagerTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/TelephonyManagerTest.java
deleted file mode 100644
index c2a468914..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/TelephonyManagerTest.java
+++ /dev/null
@@ -1,94 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.telephony.PhoneStateListener;
-import android.telephony.TelephonyManager;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static android.content.Context.TELEPHONY_SERVICE;
-import static com.xtremelabs.robolectric.Robolectric.application;
-import static com.xtremelabs.robolectric.Robolectric.newInstanceOf;
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.CoreMatchers.notNullValue;
-import static org.hamcrest.CoreMatchers.sameInstance;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertThat;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class TelephonyManagerTest {
-
- private TelephonyManager manager;
- private ShadowTelephonyManager shadowManager;
- private MyPhoneStateListener listener;
-
- @Before
- public void setUp() throws Exception {
- manager = newInstanceOf(TelephonyManager.class);
- shadowManager = shadowOf(manager);
-
- listener = new MyPhoneStateListener();
- }
-
- @Test
- public void testListen() {
- manager.listen(listener, PhoneStateListener.LISTEN_CALL_STATE);
- assertThat(shadowManager.getListener(), notNullValue());
- assertThat((MyPhoneStateListener) shadowManager.getListener(), sameInstance(listener));
- assertThat(shadowManager.getEventFlags(), equalTo(PhoneStateListener.LISTEN_CALL_STATE));
- }
-
- @Test
- public void shouldGiveDeviceId() {
- String testId = "TESTING123";
- TelephonyManager telephonyManager = (TelephonyManager) application.getSystemService(TELEPHONY_SERVICE);
- shadowOf(telephonyManager).setDeviceId(testId);
- assertEquals(testId, telephonyManager.getDeviceId());
- }
-
- @Test
- public void shouldGiveNetworkOperatorName() {
- TelephonyManager telephonyManager = (TelephonyManager) application.getSystemService(TELEPHONY_SERVICE);
- ShadowTelephonyManager shadowTelephonyManager = shadowOf(telephonyManager);
- shadowTelephonyManager.setNetworkOperatorName("SomeOperatorName");
- assertEquals("SomeOperatorName", telephonyManager.getNetworkOperatorName());
- }
-
- @Test
- public void shouldGiveNetworkCountryIso() {
- TelephonyManager telephonyManager = (TelephonyManager) application.getSystemService(TELEPHONY_SERVICE);
- ShadowTelephonyManager shadowTelephonyManager = shadowOf(telephonyManager);
- shadowTelephonyManager.setNetworkCountryIso("SomeIso");
- assertEquals("SomeIso", telephonyManager.getNetworkCountryIso());
- }
-
- @Test
- public void shouldGiveNetworkOperator() {
- TelephonyManager telephonyManager = (TelephonyManager) application.getSystemService(TELEPHONY_SERVICE);
- ShadowTelephonyManager shadowTelephonyManager = shadowOf(telephonyManager);
- shadowTelephonyManager.setNetworkOperator("SomeOperator");
- assertEquals("SomeOperator", telephonyManager.getNetworkOperator());
- }
-
- @Test(expected = SecurityException.class)
- public void getDeviceId_shouldThrowSecurityExceptionWhenReadPhoneStatePermissionNotGranted() throws Exception {
- shadowManager.setReadPhoneStatePermission(false);
- manager.getDeviceId();
- }
-
- @Test
- public void shouldGivePhoneType() {
- TelephonyManager telephonyManager = (TelephonyManager) application.getSystemService(TELEPHONY_SERVICE);
- ShadowTelephonyManager shadowTelephonyManager = shadowOf(telephonyManager);
- shadowTelephonyManager.setPhoneType( TelephonyManager.PHONE_TYPE_CDMA );
- assertEquals(TelephonyManager.PHONE_TYPE_CDMA, telephonyManager.getPhoneType());
- shadowTelephonyManager.setPhoneType( TelephonyManager.PHONE_TYPE_GSM );
- assertEquals(TelephonyManager.PHONE_TYPE_GSM, telephonyManager.getPhoneType());
- }
-
- private class MyPhoneStateListener extends PhoneStateListener {
-
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/TestFragment.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/TestFragment.java
deleted file mode 100644
index 9eb2b2539..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/TestFragment.java
+++ /dev/null
@@ -1,99 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.app.Activity;
-import android.content.Context;
-import android.os.Bundle;
-import android.support.v4.app.Fragment;
-import android.view.LayoutInflater;
-import android.view.View;
-import android.view.ViewGroup;
-import android.widget.Button;
-import android.widget.FrameLayout;
-
-import com.xtremelabs.robolectric.R;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.util.Transcript;
-
-public class TestFragment extends Fragment {
- public static final int FRAGMENT_VIEW_ID = 2323;
- public boolean onAttachWasCalled;
- public boolean onCreateWasCalled;
- public boolean onCreateViewWasCalled;
- public boolean onActivityCreatedWasCalled;
- public LayoutInflater onCreateViewInflater;
- public View onCreateViewReturnValue;
- public boolean onStartWasCalled;
- public boolean onResumeWasCalled;
- public boolean onSaveInstanceStateWasCalled;
- public boolean onPauseWasCalled;
- public Activity onAttachActivity;
- public Bundle onActivityCreated_savedInstanceState;
- public Bundle onCreateSavedInstanceState;
-
- Transcript transcript = new Transcript();
-
- @Override
- public void onAttach(Activity activity) {
- onAttachWasCalled = true;
- onAttachActivity = activity;
- transcript.add("onAttach");
- }
-
- @Override
- public void onCreate(Bundle savedInstanceState) {
- onCreateWasCalled = true;
- transcript.add("onCreate");
- onCreateSavedInstanceState = savedInstanceState;
- }
-
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
- onCreateViewWasCalled = true;
- onCreateViewInflater = inflater;
-
- Context context = Robolectric.application.getApplicationContext();
- Button button = new Button(context);
- button.setId(R.id.button);
- FrameLayout view = new FrameLayout(context);
- view.addView(button);
-
- onCreateViewReturnValue = view;
- onCreateViewReturnValue.setId(FRAGMENT_VIEW_ID);
- transcript.add("onCreateView");
- return onCreateViewReturnValue;
- }
-
- @Override
- public void onViewCreated(View view, Bundle savedInstanceState) {
- transcript.add("onViewCreated");
- }
-
- @Override
- public void onActivityCreated(Bundle savedInstanceState) {
- onActivityCreatedWasCalled = true;
- onActivityCreated_savedInstanceState = savedInstanceState;
- transcript.add("onActivityCreated");
- }
-
- @Override
- public void onStart() {
- onStartWasCalled = true;
- transcript.add("onStart");
- }
-
- @Override
- public void onResume() {
- onResumeWasCalled = true;
- transcript.add("onResume");
- }
-
- @Override
- public void onSaveInstanceState(Bundle outState) {
- onSaveInstanceStateWasCalled = true;
- }
-
- @Override
- public void onPause() {
- onPauseWasCalled = true;
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/TestParcelable.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/TestParcelable.java
deleted file mode 100644
index 2d9d3d691..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/TestParcelable.java
+++ /dev/null
@@ -1,34 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.os.Parcel;
-import android.os.Parcelable;
-
-class TestParcelable implements Parcelable {
- int contents;
-
- public TestParcelable(int contents) {
- this.contents = contents;
- }
-
- @Override
- public int describeContents() {
- return 0;
- }
-
- public static final Creator<TestParcelable> CREATOR =
- new Creator<TestParcelable>() {
- @Override
- public TestParcelable createFromParcel(Parcel source) {
- return new TestParcelable(source.readInt());
- }
-
- @Override
- public TestParcelable[] newArray(int size) {
- return new TestParcelable[0];
- }
- };
- @Override
- public void writeToParcel(Parcel dest, int flags) {
- dest.writeInt(contents);
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/TestService.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/TestService.java
deleted file mode 100644
index 2ffa82478..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/TestService.java
+++ /dev/null
@@ -1,29 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.app.Service;
-import android.content.ComponentName;
-import android.content.Intent;
-import android.content.ServiceConnection;
-import android.os.IBinder;
-
-class TestService extends Service implements ServiceConnection {
- ComponentName name;
- IBinder service;
- ComponentName nameUnbound;
-
- @Override
- public IBinder onBind(Intent intent) {
- return null;
- }
-
- @Override
- public void onServiceConnected(ComponentName name, IBinder service) {
- this.name = name;
- this.service = service;
- }
-
- @Override
- public void onServiceDisconnected(ComponentName name) {
- nameUnbound = name;
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/TextPaintTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/TextPaintTest.java
deleted file mode 100644
index 488f577a8..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/TextPaintTest.java
+++ /dev/null
@@ -1,19 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.text.TextPaint;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static junit.framework.Assert.assertEquals;
-
-
-@RunWith(WithTestDefaultsRunner.class)
-public class TextPaintTest {
-
- @Test
- public void measureText_returnsStringLengthAsMeasurement() throws Exception {
- TextPaint paint = new TextPaint();
- assertEquals(4f, paint.measureText("1234"));
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/TextUtilsTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/TextUtilsTest.java
deleted file mode 100644
index bff513751..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/TextUtilsTest.java
+++ /dev/null
@@ -1,65 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.text.TextUtils;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import java.util.Arrays;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static org.hamcrest.CoreMatchers.*;
-import static org.junit.Assert.*;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class TextUtilsTest {
- @Test
- public void testExpandTemplate() throws Exception {
- assertThat(
- (String) TextUtils.expandTemplate("a^1b^2c^3d", "A", "B", "C", "D"),
- equalTo("aAbBcCd"));
- }
-
- @Test
- public void testIsEmpty() throws Exception {
- assertThat(TextUtils.isEmpty(null), equalTo(true));
- assertThat(TextUtils.isEmpty(""), equalTo(true));
- assertThat(TextUtils.isEmpty(" "), equalTo(false));
- assertThat(TextUtils.isEmpty("123"), equalTo(false));
- }
-
- @Test public void testJoin() {
- assertThat(TextUtils.join(",", new String[] { "1" }), equalTo("1"));
- assertThat(TextUtils.join(",", new String[] { "1", "2", "3" }), equalTo("1,2,3"));
- assertThat(TextUtils.join(",", Arrays.asList("1", "2", "3")), equalTo("1,2,3"));
- }
-
- @Test
- public void testIsDigitsOnly() throws Exception {
- assertThat(TextUtils.isDigitsOnly("123456"), equalTo(true));
- assertThat(TextUtils.isDigitsOnly("124a56"), equalTo(false));
- }
-
- @Test
- public void testGetTrimmedLength() {
- assertThat(TextUtils.getTrimmedLength("123456"), equalTo(6));
- assertThat(TextUtils.getTrimmedLength(" \n \t 123456"), equalTo(6));
- assertThat(TextUtils.getTrimmedLength("123456 \n \t "), equalTo(6));
- assertThat(TextUtils.getTrimmedLength(" \n \t 123456 \n \t "), equalTo(6));
- assertThat(TextUtils.getTrimmedLength(" \n \t \n \t "), equalTo(0));
- }
-
- @Test
- public void testSplit() {
- //empty
- assertThat(TextUtils.split("", ",").length, equalTo(0));
-
- //one value
- assertArrayEquals(TextUtils.split("abc", ","), new String[]{"abc"});
-
- //two values
- assertArrayEquals(TextUtils.split("abc,def", ","), new String[]{"abc", "def"});
-
- //two values with space
- assertArrayEquals(TextUtils.split("abc, def", ","), new String[]{"abc", " def"});
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/TextViewTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/TextViewTest.java
deleted file mode 100644
index b529f861b..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/TextViewTest.java
+++ /dev/null
@@ -1,478 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.app.Activity;
-import android.graphics.Typeface;
-import android.text.*;
-import android.text.method.ArrowKeyMovementMethod;
-import android.text.method.MovementMethod;
-import android.text.style.URLSpan;
-import android.view.Gravity;
-import android.view.KeyEvent;
-import android.view.MotionEvent;
-import android.view.inputmethod.EditorInfo;
-import android.widget.TextView;
-import com.xtremelabs.robolectric.R;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import junit.framework.Assert;
-import org.hamcrest.CoreMatchers;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Random;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-import static java.util.Arrays.asList;
-import static junit.framework.Assert.assertFalse;
-import static org.hamcrest.CoreMatchers.*;
-import static org.junit.Assert.*;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.verify;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class TextViewTest {
-
- private static final String INITIAL_TEXT = "initial text";
- private static final String NEW_TEXT = "new text";
- private TextView textView;
-
- @Before
- public void setUp() throws Exception {
- textView = new TextView(new Activity());
- }
-
- @Test
- public void shouldTriggerTheImeListener() {
- TextView textView = new TextView(null);
- TestOnEditorActionListener actionListener = new TestOnEditorActionListener();
- textView.setOnEditorActionListener(actionListener);
-
- shadowOf(textView).triggerEditorAction(EditorInfo.IME_ACTION_GO);
-
- assertThat(actionListener.textView, is(textView));
- assertThat(actionListener.sentImeId, equalTo(EditorInfo.IME_ACTION_GO));
- }
-
- @Test
- public void testGetUrls() throws Exception {
- textView.setText("here's some text http://google.com/\nblah\thttp://another.com/123?456 blah");
-
- assertThat(urlStringsFrom(textView.getUrls()), equalTo(asList(
- "http://google.com/",
- "http://another.com/123?456"
- )));
- }
-
- @Test
- public void testGetGravity() throws Exception {
- assertThat(textView.getGravity(), not(equalTo(Gravity.CENTER)));
- textView.setGravity(Gravity.CENTER);
- assertThat(textView.getGravity(), equalTo(Gravity.CENTER));
- }
-
- @Test
- public void testMovementMethod() {
- MovementMethod movement = new ArrowKeyMovementMethod();
-
- assertNull(textView.getMovementMethod());
- textView.setMovementMethod(movement);
- assertThat(textView.getMovementMethod(), sameInstance(movement));
- }
-
- @Test
- public void testLinksClickable() {
- assertThat(textView.getLinksClickable(), equalTo(false));
-
- textView.setLinksClickable(true);
- assertThat(textView.getLinksClickable(), equalTo(true));
-
- textView.setLinksClickable(false);
- assertThat(textView.getLinksClickable(), equalTo(false));
- }
-
- @Test
- public void testGetTextAppearanceId() throws Exception {
- TextView textView = new TextView(null);
- textView.setTextAppearance(null, 5);
-
- assertThat(shadowOf(textView).getTextAppearanceId(), equalTo(5));
- }
-
- @Test
- public void shouldSetTextAndTextColorWhileInflatingXmlLayout() throws Exception {
- Activity activity = new Activity();
- activity.setContentView(R.layout.text_views);
-
- TextView black = (TextView) activity.findViewById(R.id.black_text_view);
- assertThat(black.getText().toString(), equalTo("Black Text"));
- assertThat(shadowOf(black).getTextColorHexValue(), equalTo(0));
-
- TextView white = (TextView) activity.findViewById(R.id.white_text_view);
- assertThat(white.getText().toString(), equalTo("White Text"));
- assertThat(shadowOf(white).getTextColorHexValue(), equalTo(activity.getResources().getColor(android.R.color.white)));
-
- TextView grey = (TextView) activity.findViewById(R.id.grey_text_view);
- assertThat(grey.getText().toString(), equalTo("Grey Text"));
- assertThat(shadowOf(grey).getTextColorHexValue(), equalTo(activity.getResources().getColor(R.color.grey42)));
- }
-
- @Test
- public void shouldSetHintAndHintColorWhileInflatingXmlLayout() throws Exception {
- Activity activity = new Activity();
- activity.setContentView(R.layout.text_views_hints);
-
- TextView black = (TextView) activity.findViewById(R.id.black_text_view_hint);
- assertThat(black.getHint().toString(), equalTo("Black Hint"));
- assertThat(shadowOf(black).getHintColorHexValue(), equalTo(0));
-
- TextView white = (TextView) activity.findViewById(R.id.white_text_view_hint);
- assertThat(white.getHint().toString(), equalTo("White Hint"));
- assertThat(shadowOf(white).getHintColorHexValue(), equalTo(activity.getResources().getColor(android.R.color.white)));
-
- TextView grey = (TextView) activity.findViewById(R.id.grey_text_view_hint);
- assertThat(grey.getHint().toString(), equalTo("Grey Hint"));
- assertThat(shadowOf(grey).getHintColorHexValue(), equalTo(activity.getResources().getColor(R.color.grey42)));
- }
-
- @Test
- public void shouldNotHaveTransformationMethodByDefault() {
- ShadowTextView view = new ShadowTextView();
- assertThat(view.getTransformationMethod(), is(CoreMatchers.<Object>nullValue()));
- }
-
- @Test
- public void shouldAllowSettingATransformationMethod() {
- ShadowTextView view = new ShadowTextView();
- view.setTransformationMethod(new ShadowPasswordTransformationMethod());
- assertEquals(view.getTransformationMethod().getClass(), ShadowPasswordTransformationMethod.class);
- }
-
- @Test
- public void testGetInputType() throws Exception {
- assertThat(textView.getInputType(), not(equalTo(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD)));
- textView.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
- assertThat(textView.getInputType(), equalTo(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD));
- }
-
- @Test
- public void givenATextViewWithATextWatcherAdded_WhenSettingTextWithTextResourceId_ShouldNotifyTextWatcher() {
- MockTextWatcher mockTextWatcher = new MockTextWatcher();
- textView.addTextChangedListener(mockTextWatcher);
-
- textView.setText(R.string.hello);
-
- assertEachTextWatcherEventWasInvoked(mockTextWatcher);
- }
-
- @Test
- public void givenATextViewWithATextWatcherAdded_WhenSettingTextWithCharSequence_ShouldNotifyTextWatcher() {
- MockTextWatcher mockTextWatcher = new MockTextWatcher();
- textView.addTextChangedListener(mockTextWatcher);
-
- textView.setText("text");
-
- assertEachTextWatcherEventWasInvoked(mockTextWatcher);
- }
-
- @Test
- public void givenATextViewWithATextWatcherAdded_WhenSettingNullText_ShouldNotifyTextWatcher() {
- MockTextWatcher mockTextWatcher = new MockTextWatcher();
- textView.addTextChangedListener(mockTextWatcher);
-
- textView.setText(null);
-
- assertEachTextWatcherEventWasInvoked(mockTextWatcher);
- }
-
- @Test
- public void givenATextViewWithMultipleTextWatchersAdded_WhenSettingText_ShouldNotifyEachTextWatcher() {
- List<MockTextWatcher> mockTextWatchers = anyNumberOfTextWatchers();
- for (MockTextWatcher textWatcher : mockTextWatchers) {
- textView.addTextChangedListener(textWatcher);
- }
-
- textView.setText("text");
-
- for (MockTextWatcher textWatcher : mockTextWatchers) {
- assertEachTextWatcherEventWasInvoked(textWatcher);
- }
- }
-
- @Test
- public void whenSettingText_ShouldFireBeforeTextChangedWithCorrectArguments() {
- textView.setText(INITIAL_TEXT);
- TextWatcher mockTextWatcher = mock(TextWatcher.class);
- textView.addTextChangedListener(mockTextWatcher);
-
- textView.setText(NEW_TEXT);
-
- verify(mockTextWatcher).beforeTextChanged(INITIAL_TEXT, 0, INITIAL_TEXT.length(), NEW_TEXT.length());
- }
-
- @Test
- public void whenSettingText_ShouldFireOnTextChangedWithCorrectArguments() {
- textView.setText(INITIAL_TEXT);
- TextWatcher mockTextWatcher = mock(TextWatcher.class);
- textView.addTextChangedListener(mockTextWatcher);
-
- textView.setText(NEW_TEXT);
-
- verify(mockTextWatcher).onTextChanged(NEW_TEXT, 0, INITIAL_TEXT.length(), NEW_TEXT.length());
- }
-
- @Test
- public void whenSettingText_ShouldFireAfterTextChangedWithCorrectArgument() {
- MockTextWatcher mockTextWatcher = new MockTextWatcher();
- textView.addTextChangedListener(mockTextWatcher);
-
- textView.setText(NEW_TEXT);
-
- assertThat(mockTextWatcher.afterTextChangeArgument.toString(), equalTo(NEW_TEXT));
- }
-
- @Test
- public void whenAppendingText_ShouldAppendNewTextAfterOldOne() {
- textView.setText(INITIAL_TEXT);
- textView.append(NEW_TEXT);
-
- assertEquals(INITIAL_TEXT + NEW_TEXT, textView.getText());
- }
-
- @Test
- public void whenAppendingText_ShouldFireBeforeTextChangedWithCorrectArguments() {
- textView.setText(INITIAL_TEXT);
- TextWatcher mockTextWatcher = mock(TextWatcher.class);
- textView.addTextChangedListener(mockTextWatcher);
-
- textView.append(NEW_TEXT);
-
- verify(mockTextWatcher).beforeTextChanged(INITIAL_TEXT, 0, INITIAL_TEXT.length(), INITIAL_TEXT.length() + NEW_TEXT.length());
- }
-
- @Test
- public void whenAppendingText_ShouldFireOnTextChangedWithCorrectArguments() {
- textView.setText(INITIAL_TEXT);
- TextWatcher mockTextWatcher = mock(TextWatcher.class);
- textView.addTextChangedListener(mockTextWatcher);
-
- textView.append(NEW_TEXT);
-
- verify(mockTextWatcher).onTextChanged(INITIAL_TEXT + NEW_TEXT, 0, INITIAL_TEXT.length(), INITIAL_TEXT.length() + NEW_TEXT.length());
- }
-
- @Test
- public void whenAppendingText_ShouldFireAfterTextChangedWithCorrectArgument() {
- textView.setText(INITIAL_TEXT);
- MockTextWatcher mockTextWatcher = new MockTextWatcher();
- textView.addTextChangedListener(mockTextWatcher);
-
- textView.append(NEW_TEXT);
-
- assertThat(mockTextWatcher.afterTextChangeArgument.toString(), equalTo(INITIAL_TEXT + NEW_TEXT));
- }
-
- @Test
- public void removeTextChangedListener_shouldRemoveTheListener() throws Exception {
- MockTextWatcher watcher = new MockTextWatcher();
- textView.addTextChangedListener(watcher);
- assertTrue(shadowOf(textView).getWatchers().contains(watcher));
-
- textView.removeTextChangedListener(watcher);
- assertFalse(shadowOf(textView).getWatchers().contains(watcher));
- }
-
- @Test
- public void getPaint_returnsMeasureTextEnabledObject() throws Exception {
- assertThat(textView.getPaint().measureText("12345"), equalTo(5f));
- }
-
- @Test
- public void append_whenSelectionIsAtTheEnd_shouldKeepSelectionAtTheEnd() throws Exception {
- textView.setText("1");
- shadowOf(textView).setSelection(0, 0);
- textView.append("2");
- assertEquals(0, textView.getSelectionEnd());
- assertEquals(0, textView.getSelectionStart());
-
- shadowOf(textView).setSelection(2, 2);
- textView.append("3");
- assertEquals(3, textView.getSelectionEnd());
- assertEquals(3, textView.getSelectionStart());
- }
-
- @Test
- public void append_whenSelectionReachesToEnd_shouldExtendSelectionToTheEnd() throws Exception {
- textView.setText("12");
- shadowOf(textView).setSelection(0, 2);
- textView.append("3");
- assertEquals(3, textView.getSelectionEnd());
- assertEquals(0, textView.getSelectionStart());
- }
-
- @Test
- public void testSetCompountDrawablesWithIntrinsicBounds_int_shouldCreateDrawablesWithResourceIds() throws Exception {
- textView.setCompoundDrawablesWithIntrinsicBounds(6, 7, 8, 9);
-
- Assert.assertEquals(6, shadowOf(textView.getCompoundDrawables()[0]).getLoadedFromResourceId());
- Assert.assertEquals(7, shadowOf(textView.getCompoundDrawables()[1]).getLoadedFromResourceId());
- Assert.assertEquals(8, shadowOf(textView.getCompoundDrawables()[2]).getLoadedFromResourceId());
- Assert.assertEquals(9, shadowOf(textView.getCompoundDrawables()[3]).getLoadedFromResourceId());
- }
-
- @Test
- public void testSetCompountDrawablesWithIntrinsicBounds_int_shouldNotCreateDrawablesForZero() throws Exception {
- textView.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
-
- Assert.assertNull(textView.getCompoundDrawables()[0]);
- Assert.assertNull(textView.getCompoundDrawables()[1]);
- Assert.assertNull(textView.getCompoundDrawables()[2]);
- Assert.assertNull(textView.getCompoundDrawables()[3]);
- }
-
- @Test
- public void canSetAndGetTypeface() throws Exception {
- Typeface typeface = Robolectric.newInstanceOf(Typeface.class);
- textView.setTypeface(typeface);
- Assert.assertEquals(typeface, textView.getTypeface());
- }
-
- @Test
- public void onTouchEvent_shouldCallMovementMethodOnTouchEventWithSetMotionEvent() throws Exception {
- TestMovementMethod testMovementMethod = new TestMovementMethod();
-
- textView.setMovementMethod(testMovementMethod);
- MotionEvent event = MotionEvent.obtain(0, 0, 0, 0, 0, 0);
- textView.dispatchTouchEvent(event);
-
- assertEquals(testMovementMethod.event, event);
- }
-
- @Test
- public void canSetAndGetLayout() throws Exception {
- StaticLayout layout = new StaticLayout(null, null, 0, null, 0, 0, true);
- shadowOf(textView).setLayout(layout);
- assertEquals(textView.getLayout(), layout);
- }
-
- @Test
- public void testGetError() {
- assertNull(textView.getError());
- CharSequence error = "myError";
- textView.setError(error);
- assertEquals(error, textView.getError());
- }
-
- private List<MockTextWatcher> anyNumberOfTextWatchers() {
- List<MockTextWatcher> mockTextWatchers = new ArrayList<MockTextWatcher>();
- int numberBetweenOneAndTen = new Random().nextInt(10) + 1;
- for (int i = 0; i < numberBetweenOneAndTen; i++) {
- mockTextWatchers.add(new MockTextWatcher());
- }
- return mockTextWatchers;
- }
-
- private void assertEachTextWatcherEventWasInvoked(MockTextWatcher mockTextWatcher) {
- assertTrue("Expected each TextWatcher event to have been invoked once", mockTextWatcher.methodsCalled.size() == 3);
-
- assertThat(mockTextWatcher.methodsCalled.get(0), equalTo("beforeTextChanged"));
- assertThat(mockTextWatcher.methodsCalled.get(1), equalTo("onTextChanged"));
- assertThat(mockTextWatcher.methodsCalled.get(2), equalTo("afterTextChanged"));
- }
-
- private List<String> urlStringsFrom(URLSpan[] urlSpans) {
- List<String> urls = new ArrayList<String>();
- for (URLSpan urlSpan : urlSpans) {
- urls.add(urlSpan.getURL());
- }
- return urls;
- }
-
- private static class TestOnEditorActionListener implements TextView.OnEditorActionListener {
- private TextView textView;
- private int sentImeId;
-
- @Override
- public boolean onEditorAction(TextView textView, int sentImeId, KeyEvent keyEvent) {
- this.textView = textView;
- this.sentImeId = sentImeId;
- return false;
- }
- }
-
- private static class MockTextWatcher implements TextWatcher {
-
- List<String> methodsCalled = new ArrayList<String>();
- Editable afterTextChangeArgument;
-
- @Override
- public void beforeTextChanged(CharSequence s, int start, int count, int after) {
- methodsCalled.add("beforeTextChanged");
- }
-
- @Override
- public void onTextChanged(CharSequence s, int start, int before, int count) {
- methodsCalled.add("onTextChanged");
- }
-
- @Override
- public void afterTextChanged(Editable s) {
- methodsCalled.add("afterTextChanged");
- afterTextChangeArgument = s;
- }
-
- }
-
- private static class TestMovementMethod implements MovementMethod {
- public MotionEvent event;
- public boolean touchEventWasCalled;
-
- @Override
- public void initialize(TextView widget, Spannable text) {
- }
-
- @Override
- public boolean onKeyDown(TextView widget, Spannable text, int keyCode, KeyEvent event) {
- return false;
- }
-
- @Override
- public boolean onKeyUp(TextView widget, Spannable text, int keyCode, KeyEvent event) {
- return false;
- }
-
- @Override
- public boolean onKeyOther(TextView view, Spannable text, KeyEvent event) {
- return false;
- }
-
- @Override
- public void onTakeFocus(TextView widget, Spannable text, int direction) {
- }
-
- @Override
- public boolean onTrackballEvent(TextView widget, Spannable text, MotionEvent event) {
- return false;
- }
-
- @Override
- public boolean onTouchEvent(TextView widget, Spannable text, MotionEvent event) {
- this.event = event;
- touchEventWasCalled = true;
- return false;
- }
-
- @Override
- public boolean canSelectArbitrarily() {
- return false;
- }
-
- @Override
- public boolean onGenericMotionEvent(TextView widget, Spannable text,
- MotionEvent event) {
- return false;
- }
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/TimeTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/TimeTest.java
deleted file mode 100755
index d1dc0e0c5..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/TimeTest.java
+++ /dev/null
@@ -1,238 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.text.format.Time;
-import android.util.TimeFormatException;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.CoreMatchers.not;
-import static org.junit.Assert.*;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class TimeTest {
- @Test
- public void shouldSetToNow() throws Exception {
- Time t = new Time();
- t.setToNow();
- assertThat(t.toMillis(false), not(equalTo(0l)));
- }
-
- @Test
- public void shouldHaveNoArgsConstructor() throws Exception {
- Time t = new Time();
- assertNotNull(t.timezone);
- }
-
- @Test
- public void shouldHaveCopyConstructor() throws Exception {
- Time t = new Time();
- t.setToNow();
- Time t2 = new Time(t);
- assertEquals(t.timezone, t2.timezone);
- assertEquals(t.year, t2.year);
- assertEquals(t.month, t2.month);
- assertEquals(t.monthDay, t2.monthDay);
- assertEquals(t.hour, t2.hour);
- assertEquals(t.minute, t2.minute);
- assertEquals(t.second, t2.second);
- }
-
- @Test
- public void shouldHaveSetTime() throws Exception {
- Time t = new Time();
- t.setToNow();
- Time t2 = new Time();
- t2.set(t);
- assertEquals(t.timezone, t2.timezone);
- assertEquals(t.year, t2.year);
- assertEquals(t.month, t2.month);
- assertEquals(t.monthDay, t2.monthDay);
- assertEquals(t.hour, t2.hour);
- assertEquals(t.minute, t2.minute);
- assertEquals(t.second, t2.second);
- }
-
- @Test
- public void shouldHaveSet3Args() throws Exception {
- Time t = new Time();
- t.set(1, 1, 2000);
- assertEquals(t.year, 2000);
- assertEquals(t.month, 1);
- assertEquals(t.monthDay, 1);
- }
-
- @Test
- public void shouldHaveSet6Args() throws Exception {
- Time t = new Time();
- t.set(1, 1, 1, 1, 1, 2000);
- assertEquals(t.year, 2000);
- assertEquals(t.month, 1);
- assertEquals(t.monthDay, 1);
- assertEquals(t.second, 1);
- assertEquals(t.minute, 1);
- assertEquals(t.hour, 1);
- }
-
- @Test
- public void shouldHaveTimeZoneConstructor() throws Exception {
- Time t = new Time("UTC");
- assertEquals(t.timezone, "UTC");
- }
-
- @Test
- public void shouldClear() throws Exception {
- Time t = new Time();
- t.setToNow();
- t.clear("UTC");
- assertEquals("UTC", t.timezone);
- assertEquals(0, t.year);
- assertEquals(0, t.month);
- assertEquals(0, t.monthDay);
- assertEquals(0, t.hour);
- assertEquals(0, t.minute);
- assertEquals(0, t.second);
- assertEquals(0, t.weekDay);
- assertEquals(0, t.yearDay);
- assertEquals(0, t.gmtoff);
- assertEquals(-1, t.isDst);
- }
-
- @Test
- public void shouldHaveToMillis() throws Exception {
- Time t = new Time();
- t.set(86400 * 1000);
- assertEquals(86400 * 1000, t.toMillis(false));
- }
-
- @Test
- public void shouldHaveCurrentTimeZone() throws Exception {
- assertNotNull(Time.getCurrentTimezone());
- }
-
- @Test
- public void shouldHaveCompareAndBeforeAfter() throws Exception {
- Time a = new Time();
- Time b = new Time();
- assertEquals(0, Time.compare(a, b));
- assertFalse(a.before(b));
- assertFalse(a.after(b));
- a.year = 2000;
- assertEquals(1, Time.compare(a, b));
- assertTrue(a.after(b));
- assertTrue(b.before(a));
- b.year = 2001;
- assertEquals(-1, Time.compare(a, b));
- assertTrue(b.after(a));
- assertTrue(a.before(b));
- }
-
- @Test
- public void shouldHaveParse() throws Exception {
- Time t = new Time("Europe/Berlin");
- assertFalse(t.parse("20081013T160000"));
- assertEquals(2008, t.year);
- assertEquals(9, t.month);
- assertEquals(13, t.monthDay);
- assertEquals(16, t.hour);
- assertEquals(0, t.minute);
- assertEquals(0, t.second);
-
- assertTrue(t.parse("20081013T160000Z"));
- assertEquals(2008, t.year);
- assertEquals(9, t.month);
- assertEquals(13, t.monthDay);
- assertEquals(16, t.hour);
- assertEquals(0, t.minute);
- assertEquals(0, t.second);
- }
-
- @Test(expected = TimeFormatException.class)
- public void shouldThrowTimeFormatException() throws Exception {
- Time t = new Time();
- t.parse("BLARGH");
- }
-
- @Test
- public void shouldHaveParseShort() throws Exception {
- Time t = new Time();
- t.parse("20081013");
- assertEquals(2008, t.year);
- assertEquals(9, t.month);
- assertEquals(13, t.monthDay);
- assertEquals(0, t.hour);
- assertEquals(0, t.minute);
- assertEquals(0, t.second);
- }
-
- @Test
- public void shouldFormat() throws Exception {
- Time t = new Time();
- assertEquals("Hallo epoch 01 1970 01", t.format("Hallo epoch %d %Y %d"));
- }
-
- @Test
- public void shouldFormat2445() throws Exception {
- Time t = new Time();
- assertEquals("19700101T000000", t.format2445());
- }
-
- @Test
- public void shouldFormat3339() throws Exception {
- Time t = new Time("Europe/Berlin");
- assertEquals("1970-01-01T00:00:00.000+00:00", t.format3339(false));
- assertEquals("1970-01-01", t.format3339(true));
- }
-
- @Test
- public void testIsEpoch() throws Exception {
- Time t = new Time();
- boolean isEpoch = Time.isEpoch(t);
- assertEquals(true, isEpoch);
- }
-
- @Test
- public void testGetJulianDay() throws Exception {
- Time time = new Time();
-
- time.set(0, 0, 0, 12, 5, 2008);
- time.timezone = "Australia/Sydney";
- long millis = time.normalize(true);
-
- // This is the Julian day for 12am for this day of the year
- int julianDay = Time.getJulianDay(millis, time.gmtoff);
-
- // Change the time during the day and check that we get the same
- // Julian day.
- for (int hour = 0; hour < 24; hour++) {
- for (int minute = 0; minute < 60; minute += 15) {
- time.set(0, minute, hour, 12, 5, 2008);
- millis = time.normalize(true);
- int day = Time.getJulianDay(millis, time.gmtoff);
-
- assertEquals(day, julianDay);
- }
- }
- }
-
- @Test
- public void testSetJulianDay() throws Exception {
- Time time = new Time();
- time.set(0, 0, 0, 12, 5, 2008);
- time.timezone = "Australia/Sydney";
- long millis = time.normalize(true);
-
- int julianDay = Time.getJulianDay(millis, time.gmtoff);
- time.setJulianDay(julianDay);
-
- assertTrue(time.hour == 0 || time.hour == 1);
- assertEquals(0, time.minute);
- assertEquals(0, time.second);
-
- millis = time.toMillis(false);
- int day = Time.getJulianDay(millis, time.gmtoff);
-
- assertEquals(day, julianDay);
- }
-} \ No newline at end of file
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ToastTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/ToastTest.java
deleted file mode 100644
index 7451ebc01..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ToastTest.java
+++ /dev/null
@@ -1,31 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import android.app.Activity;
-import android.widget.Toast;
-
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class ToastTest {
-
- @Test
- public void shouldHaveShortDuration() throws Exception {
- Toast toast = Toast.makeText(new Activity(), "short toast",
- Toast.LENGTH_SHORT);
- assertNotNull(toast);
- assertEquals(Toast.LENGTH_SHORT, toast.getDuration());
- }
-
- @Test
- public void shouldHaveLongDuration() throws Exception {
- Toast toast = Toast.makeText(new Activity(), "long toast",
- Toast.LENGTH_LONG);
- assertNotNull(toast);
- assertEquals(Toast.LENGTH_LONG, toast.getDuration());
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/TranslateAnimationTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/TranslateAnimationTest.java
deleted file mode 100644
index 716fe6d8e..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/TranslateAnimationTest.java
+++ /dev/null
@@ -1,52 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.view.animation.Animation;
-import android.view.animation.TranslateAnimation;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.junit.Assert.assertThat;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class TranslateAnimationTest {
-
- private TranslateAnimation animation;
- private ShadowTranslateAnimation shadow;
-
- @Before
- public void setUp() throws Exception {
- animation = new TranslateAnimation(1, 2, 3, 4, 5, 6, 7, 8);
- shadow = shadowOf(animation);
- }
-
- @Test
- public void animationParametersFromConstructor() throws Exception {
- assertThat(shadow.getFromXType(), equalTo(1));
- assertThat(shadow.getFromXValue(), equalTo(2f));
- assertThat(shadow.getToXType(), equalTo(3));
- assertThat(shadow.getToXValue(), equalTo(4f));
- assertThat(shadow.getFromYType(), equalTo(5));
- assertThat(shadow.getFromYValue(), equalTo(6f));
- assertThat(shadow.getToYType(), equalTo(7));
- assertThat(shadow.getToYValue(), equalTo(8f));
- }
-
- @Test
- public void animationParametersFromConstructor2() throws Exception {
- TranslateAnimation animation2 = new TranslateAnimation(1, 2, 3, 4);
- ShadowTranslateAnimation shadow2 = shadowOf(animation2);
- int defType = Animation.ABSOLUTE;
- assertThat(shadow2.getFromXType(), equalTo(defType));
- assertThat(shadow2.getFromXValue(), equalTo(1f));
- assertThat(shadow2.getToXType(), equalTo(defType));
- assertThat(shadow2.getToXValue(), equalTo(2f));
- assertThat(shadow2.getFromYType(), equalTo(defType));
- assertThat(shadow2.getFromYValue(), equalTo(3f));
- assertThat(shadow2.getToYType(), equalTo(defType));
- assertThat(shadow2.getToYValue(), equalTo(4f));
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/TypedArrayTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/TypedArrayTest.java
deleted file mode 100644
index 027371913..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/TypedArrayTest.java
+++ /dev/null
@@ -1,71 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.junit.Assert.assertNotNull;
-
-import android.app.Activity;
-
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class TypedArrayTest {
- private android.content.res.TypedArray typedArray;
-
- @Before
- public void setUp() throws Exception {
- typedArray = Robolectric.newInstanceOf(android.content.res.TypedArray.class);
- }
-
- @Test
- public void getResources() throws Exception {
- assertNotNull(new Activity().obtainStyledAttributes(null).getResources());
- }
-
- @Test
- public void testBooleanDefaultValue() {
- assertThat(typedArray.getBoolean(0, true), equalTo(true));
- assertThat(typedArray.getBoolean(0, false), equalTo(false));
- }
-
- @Test
- public void testIntDefaultValue() {
- assertThat(typedArray.getInt(0, 15), equalTo(15));
- assertThat(typedArray.getInteger(0, 24), equalTo(24));
- }
-
- @Test
- public void testFloatDefaultValue() {
- assertThat(typedArray.getFloat(0, 0.5f), equalTo(0.5f));
- }
-
- @Test
- public void testDimensionDefaultValue() {
- assertThat(typedArray.getDimension(0, 0.5f), equalTo(0.5f));
- }
-
- @Test
- public void testDimensionPixelOffsetDefaultValue() {
- assertThat(typedArray.getDimensionPixelOffset(0, 2), equalTo(2));
- }
-
- @Test
- public void testDimensionPixelSizeDefaultValue() {
- assertThat(typedArray.getDimensionPixelSize(0, 2), equalTo(2));
- }
-
- @Test
- public void testLayoutDimensionDefaultValue() {
- assertThat(typedArray.getLayoutDimension(0, 2), equalTo(2));
- }
-
- @Test
- public void testResourceIdDefaultValue() {
- assertThat(typedArray.getResourceId(0, 2), equalTo(2));
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/TypedValueTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/TypedValueTest.java
deleted file mode 100644
index 7cf2d5556..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/TypedValueTest.java
+++ /dev/null
@@ -1,80 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.util.DisplayMetrics;
-import android.util.TypedValue;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static org.hamcrest.core.IsEqual.equalTo;
-import static org.junit.Assert.assertThat;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class TypedValueTest {
-
- @Test
- public void testApplyDimensionIsWired() throws Exception {
- DisplayMetrics metrics = new DisplayMetrics();
- metrics.density = 0.5f;
- float convertedValue = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 100, metrics);
- assertThat(convertedValue, equalTo(50f));
- }
-
- @Test
- public void testCoerceBooleanToString() {
- String booleanFalseString = TypedValue.coerceToString(TypedValue.TYPE_INT_BOOLEAN, 0);
- String booleanTrueString = TypedValue.coerceToString(TypedValue.TYPE_INT_BOOLEAN, 1);
-
- assertThat(booleanFalseString, equalTo("false"));
- assertThat(booleanTrueString, equalTo("true"));
- }
-
- @Test
- public void testCoerceNullToString() {
- String nullString = TypedValue.coerceToString(TypedValue.TYPE_NULL, 0);
-
- assertThat(nullString, equalTo(null));
- }
-
- @Test
- public void testCoerceIntegerToString() {
- String intString = TypedValue.coerceToString(TypedValue.TYPE_INT_DEC, 37);
-
- assertThat(intString, equalTo("37"));
- }
-
- @Test
- public void testCoerceIntegerToHexString() {
- String hexString = TypedValue.coerceToString(TypedValue.TYPE_INT_HEX, 0xcafebabe);
-
- assertThat(hexString, equalTo("0xcafebabe"));
- }
-
- @Test
- public void testCoerceColorToString() {
- String colorString = TypedValue.coerceToString(TypedValue.TYPE_INT_COLOR_RGB8, 0xcafebabe);
-
- assertThat(colorString, equalTo("#cafebabe"));
- }
-
- @Test
- public void testSetTo() {
- TypedValue expectedValue = new TypedValue();
- expectedValue.assetCookie = 1;
- expectedValue.data = 3;
- expectedValue.density = 4;
- expectedValue.resourceId = 5;
- expectedValue.string = "string";
- expectedValue.type = 6;
-
- TypedValue actualValue = new TypedValue();
- actualValue.setTo(expectedValue);
-
- assertThat(expectedValue.assetCookie, equalTo(actualValue.assetCookie));
- assertThat(expectedValue.data, equalTo(actualValue.data));
- assertThat(expectedValue.density, equalTo(actualValue.density));
- assertThat(expectedValue.resourceId, equalTo(actualValue.resourceId));
- assertThat(expectedValue.string, equalTo(actualValue.string));
- assertThat(expectedValue.type, equalTo(actualValue.type));
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/UriMatcherTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/UriMatcherTest.java
deleted file mode 100644
index c3305af07..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/UriMatcherTest.java
+++ /dev/null
@@ -1,87 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.content.UriMatcher;
-import android.net.Uri;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import com.xtremelabs.robolectric.shadows.ShadowUriMatcher.MatchNode;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.CoreMatchers.nullValue;
-import static org.junit.Assert.assertThat;
-import static org.junit.matchers.JUnitMatchers.hasItem;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class UriMatcherTest {
- static final String AUTH = "com.foo";
- static final int NO_MATCH = -2;
-
- UriMatcher matcher;
- MatchNode root;
- Uri URI;
-
- @Before public void getMatcher() {
- URI = Uri.parse("content://" + AUTH);
- matcher = new UriMatcher(NO_MATCH);
- root = Robolectric.shadowOf(matcher).rootNode;
- }
-
- @Test public void canInstantiate() {
- assertThat(root.code, is(NO_MATCH));
- assertThat(root.map.isEmpty(), is(true));
- assertThat(root.number, is(nullValue()));
- assertThat(root.text, is(nullValue()));
- }
-
- @Test public void canAddBasicMatch() {
- MatchNode node = root;
- String path = "bar/cat";
-
- matcher.addURI(AUTH, path, 1);
- assertThat(node.map.keySet(), hasItem(AUTH));
-
- node = node.map.get(AUTH);
- assertThat(node.map.keySet(), hasItem("bar"));
-
- node = node.map.get("bar");
- assertThat(node.map.keySet(), hasItem("cat"));
-
- node = node.map.get("cat");
- assertThat(node.code, is(1));
- }
-
- @Test public void canAddWildcardMatches() {
- matcher.addURI(AUTH, "#", 1);
- matcher.addURI(AUTH, "*", 2);
- MatchNode node = root.map.get(AUTH);
-
- assertThat(node.number.code, is(1));
- assertThat(node.text.code, is(2));
- }
-
- @Test public void canMatch() {
- matcher.addURI(AUTH, "bar", 1);
- assertThat(matcher.match(Uri.withAppendedPath(URI, "bar")), is(1));
-
- matcher.addURI(AUTH, "bar/#", 2);
- assertThat(matcher.match(Uri.withAppendedPath(URI, "bar/1")), is(2));
-
- matcher.addURI(AUTH, "*", 3);
- assertThat(matcher.match(Uri.withAppendedPath(URI, "bar")), is(1));
- assertThat(matcher.match(Uri.withAppendedPath(URI, "cat")), is(3));
-
- matcher.addURI(AUTH, "transport/*/#/type", 4);
- assertThat(matcher.match(Uri.withAppendedPath(URI, "transport/land/45/type")), is(4));
- }
-
- @Test public void returnsRootCodeForIfNoMatch() {
- matcher.addURI(AUTH, "bar/#", 1);
- assertThat(matcher.match(Uri.withAppendedPath(URI, "cat")), is(NO_MATCH));
- assertThat(matcher.match(Uri.withAppendedPath(URI, "bar")), is(NO_MATCH));
- assertThat(matcher.match(Uri.withAppendedPath(URI, "bar/cat")), is(NO_MATCH));
- }
-
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/UriTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/UriTest.java
deleted file mode 100644
index 0706ffe01..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/UriTest.java
+++ /dev/null
@@ -1,25 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.net.Uri;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.MatcherAssert.assertThat;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class UriTest {
- @Test
- public void shouldParseUris() throws Exception {
- Uri testUri = Uri.parse("http://someplace.com:8080/a/path?param=value&another_param=another_value#top");
-
- assertThat(testUri.getQuery(), equalTo("param=value&another_param=another_value"));
- assertThat(testUri.getPort(), equalTo(8080));
- assertThat(testUri.getAuthority(), equalTo("someplace.com:8080"));
- assertThat(testUri.getHost(), equalTo("someplace.com"));
- assertThat(testUri.getFragment(), equalTo("top"));
- assertThat(testUri.getPath(), equalTo("/a/path"));
- assertThat(testUri.getScheme(), equalTo("http"));
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/VibratorTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/VibratorTest.java
deleted file mode 100644
index 235f80de1..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/VibratorTest.java
+++ /dev/null
@@ -1,57 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.CoreMatchers.is;
-import static org.junit.Assert.assertThat;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import android.app.Activity;
-import android.content.Context;
-import android.os.Vibrator;
-
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class VibratorTest {
- private Vibrator vibrator;
- private ShadowVibrator shadowVibrator;
-
- @Before
- public void before() {
- vibrator = (Vibrator) new Activity().getSystemService(Context.VIBRATOR_SERVICE);
- shadowVibrator = shadowOf(vibrator);
- }
-
- @Test
- public void vibrateMilliseconds() {
- vibrator.vibrate(5000);
-
- assertThat(shadowVibrator.isVibrating(), is(true));
- assertThat(shadowVibrator.getMilliseconds(), equalTo(5000L));
- }
-
- @Test
- public void vibratePattern() {
- long[] pattern = new long[] { 0, 200 };
- vibrator.vibrate(pattern, 2);
-
- assertThat(shadowVibrator.isVibrating(), is(true));
- assertThat(shadowVibrator.getPattern(), equalTo(pattern));
- assertThat(shadowVibrator.getRepeat(), equalTo(2));
- }
-
- @Test
- public void cancelled() {
- vibrator.vibrate(5000);
- assertThat(shadowVibrator.isVibrating(), is(true));
- assertThat(shadowVibrator.isCancelled(), is(false));
- vibrator.cancel();
-
- assertThat(shadowVibrator.isVibrating(), is(false));
- assertThat(shadowVibrator.isCancelled(), is(true));
- }
-} \ No newline at end of file
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/VideoViewTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/VideoViewTest.java
deleted file mode 100644
index c7f3ab57d..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/VideoViewTest.java
+++ /dev/null
@@ -1,157 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.CoreMatchers.sameInstance;
-import static org.hamcrest.CoreMatchers.nullValue;
-import static org.hamcrest.MatcherAssert.assertThat;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import android.media.MediaPlayer;
-import android.net.Uri;
-import android.widget.VideoView;
-
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class VideoViewTest {
-
- private VideoView view;
-
- @Before public void setUp() throws Exception {
- view = new VideoView(null);
- }
-
- @Test
- public void shouldSetOnPreparedListener() throws Exception {
- TestPreparedListener l = new TestPreparedListener();
- view.setOnPreparedListener(l);
- ShadowVideoView shadowVideoView = Robolectric.shadowOf(view);
- assertThat((TestPreparedListener)(shadowVideoView.getOnPreparedListener()), sameInstance(l));
- }
-
- @Test
- public void shouldSetOnErrorListener() throws Exception {
- TestErrorListener l = new TestErrorListener();
- view.setOnErrorListener(l);
- ShadowVideoView shadowVideoView = Robolectric.shadowOf(view);
- assertThat((TestErrorListener)(shadowVideoView.getOnErrorListener()), sameInstance(l));
- }
-
- @Test
- public void shouldSetOnCompletionListener() throws Exception {
- TestCompletionListener l = new TestCompletionListener();
- view.setOnCompletionListener(l);
- ShadowVideoView shadowVideoView = Robolectric.shadowOf(view);
- assertThat((TestCompletionListener)(shadowVideoView.getOnCompletionListener()), sameInstance(l));
- }
-
- @Test
- public void shouldSetVideoPath() throws Exception {
- view.setVideoPath("video.mp4");
- ShadowVideoView shadowVideoView = Robolectric.shadowOf(view);
- assertThat(shadowVideoView.getVideoPath(), equalTo("video.mp4"));
- view.setVideoPath(null);
- assertThat(shadowVideoView.getVideoPath(), nullValue());
- }
-
- @Test
- public void shouldSetVideoURI() throws Exception {
- view.setVideoURI(Uri.parse("video.mp4"));
- ShadowVideoView shadowVideoView = Robolectric.shadowOf(view);
- assertThat(shadowVideoView.getVideoURIString(), equalTo("video.mp4"));
- view.setVideoURI(null);
- assertThat(shadowVideoView.getVideoURIString(), nullValue());
- }
-
- @Test
- public void shoulDetermineIsPlaying() throws Exception {
- assertThat(view.isPlaying(), equalTo(false));
- view.start();
- assertThat(view.isPlaying(), equalTo(true));
- view.stopPlayback();
- assertThat(view.isPlaying(), equalTo(false));
- }
-
- @Test
- public void shouldStartPlaying() throws Exception {
- view.start();
- ShadowVideoView shadowVideoView = Robolectric.shadowOf(view);
- assertThat(shadowVideoView.getCurrentVideoState(), equalTo(ShadowVideoView.START));
- }
-
- @Test
- public void shouldStopPlayback() throws Exception {
- view.stopPlayback();
- ShadowVideoView shadowVideoView = Robolectric.shadowOf(view);
- assertThat(shadowVideoView.getCurrentVideoState(), equalTo(ShadowVideoView.STOP));
- }
-
- @Test
- public void shouldSuspendPlaying() throws Exception {
- view.start();
- view.suspend();
- ShadowVideoView shadowVideoView = Robolectric.shadowOf(view);
- assertThat(shadowVideoView.getPrevVideoState(), equalTo(ShadowVideoView.START));
- assertThat(shadowVideoView.getCurrentVideoState(), equalTo(ShadowVideoView.SUSPEND));
- }
-
- @Test
- public void shouldResumePlaying() throws Exception {
- view.start();
- view.suspend();
- view.resume();
- ShadowVideoView shadowVideoView = Robolectric.shadowOf(view);
- assertThat(shadowVideoView.getPrevVideoState(), equalTo(ShadowVideoView.SUSPEND));
- assertThat(shadowVideoView.getCurrentVideoState(), equalTo(ShadowVideoView.RESUME));
- }
-
-
- @Test
- public void shouldPausePlaying() throws Exception {
- view.start();
- view.pause();
- ShadowVideoView shadowVideoView = Robolectric.shadowOf(view);
- assertThat(shadowVideoView.getPrevVideoState(), equalTo(ShadowVideoView.START));
- assertThat(shadowVideoView.getCurrentVideoState(), equalTo(ShadowVideoView.PAUSE));
- }
-
- @Test
- public void shouldDetermineIfPausable() throws Exception {
- view.start();
- assertThat(view.canPause(), equalTo(true));
-
- view.pause();
- assertThat(view.canPause(), equalTo(false));
-
- view.resume();
- assertThat(view.canPause(), equalTo(true));
-
- view.suspend();
- assertThat(view.canPause(), equalTo(false));
- }
-
- /**
- * Helper classes
- */
-
- private class TestPreparedListener implements MediaPlayer.OnPreparedListener {
- @Override
- public void onPrepared(MediaPlayer mp) {}
- }
-
- private class TestErrorListener implements MediaPlayer.OnErrorListener {
- @Override
- public boolean onError(MediaPlayer mp, int what, int extra) {
- return false;
- }
- }
-
- private class TestCompletionListener implements MediaPlayer.OnCompletionListener {
- @Override
- public void onCompletion(MediaPlayer mp) {}
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ViewAnimatorTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/ViewAnimatorTest.java
deleted file mode 100644
index c54f6afac..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ViewAnimatorTest.java
+++ /dev/null
@@ -1,45 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.app.Activity;
-import android.view.View;
-import android.widget.ViewAnimator;
-import android.widget.ViewFlipper;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static org.junit.Assert.assertEquals;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class ViewAnimatorTest {
- protected ViewAnimator animator;
-
- @Before
- public void setUp() {
- animator = new ViewAnimator(new Activity());
- }
-
- @Test
- public void testHappyPath() {
- View v = new View(null);
- animator.addView(v);
-
- assertEquals(0, animator.getDisplayedChild());
- assertEquals(v, animator.getCurrentView());
- }
-
- @Test
- public void testAnimatorHandlesCyclingViews() {
- View v1 = new View(null);
- View v2 = new View(null);
-
- animator.addView(v1);
- animator.addView(v2);
-
- animator.showNext();
-
- assertEquals(1, animator.getDisplayedChild());
- assertEquals(v2, animator.getCurrentView());
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ViewConfigurationTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/ViewConfigurationTest.java
deleted file mode 100644
index 807858d87..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ViewConfigurationTest.java
+++ /dev/null
@@ -1,70 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.app.Activity;
-import android.view.ViewConfiguration;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-import static junit.framework.Assert.assertEquals;
-
-
-@RunWith(WithTestDefaultsRunner.class)
-public class ViewConfigurationTest {
-
- @Test
- public void methodsShouldReturnAndroidConstants() {
- Activity context = new Activity();
- ViewConfiguration viewConfiguration = ViewConfiguration.get(context);
-
- assertEquals(10, ViewConfiguration.getScrollBarSize());
- assertEquals(250, ViewConfiguration.getScrollBarFadeDuration());
- assertEquals(300, ViewConfiguration.getScrollDefaultDelay());
- assertEquals(12, ViewConfiguration.getFadingEdgeLength());
- assertEquals(125, ViewConfiguration.getPressedStateDuration());
- assertEquals(500, ViewConfiguration.getLongPressTimeout());
- assertEquals(115, ViewConfiguration.getTapTimeout());
- assertEquals(500, ViewConfiguration.getJumpTapTimeout());
- assertEquals(300, ViewConfiguration.getDoubleTapTimeout());
- assertEquals(12, ViewConfiguration.getEdgeSlop());
- assertEquals(16, ViewConfiguration.getTouchSlop());
- assertEquals(16, ViewConfiguration.getWindowTouchSlop());
- assertEquals(50, ViewConfiguration.getMinimumFlingVelocity());
- assertEquals(4000, ViewConfiguration.getMaximumFlingVelocity());
- assertEquals(320 * 480 * 4, ViewConfiguration.getMaximumDrawingCacheSize());
- assertEquals(3000, ViewConfiguration.getZoomControlsTimeout());
- assertEquals(500, ViewConfiguration.getGlobalActionKeyTimeout());
- assertEquals(0.015f, ViewConfiguration.getScrollFriction());
-
- assertEquals(1f, context.getResources().getDisplayMetrics().density);
-
- assertEquals(10, viewConfiguration.getScaledScrollBarSize());
- assertEquals(12, viewConfiguration.getScaledFadingEdgeLength());
- assertEquals(12, viewConfiguration.getScaledEdgeSlop());
- assertEquals(16, viewConfiguration.getScaledTouchSlop());
- assertEquals(32, viewConfiguration.getScaledPagingTouchSlop());
- assertEquals(100, viewConfiguration.getScaledDoubleTapSlop());
- assertEquals(16, viewConfiguration.getScaledWindowTouchSlop());
- assertEquals(50, viewConfiguration.getScaledMinimumFlingVelocity());
- assertEquals(4000, viewConfiguration.getScaledMaximumFlingVelocity());
- }
-
- @Test
- public void methodsShouldReturnScaledAndroidConstantsDependingOnPixelDensity() {
- Activity context = new Activity();
- shadowOf(context.getResources()).setDensity(1.5f);
- ViewConfiguration viewConfiguration = ViewConfiguration.get(context);
-
- assertEquals(15, viewConfiguration.getScaledScrollBarSize());
- assertEquals(18, viewConfiguration.getScaledFadingEdgeLength());
- assertEquals(18, viewConfiguration.getScaledEdgeSlop());
- assertEquals(24, viewConfiguration.getScaledTouchSlop());
- assertEquals(48, viewConfiguration.getScaledPagingTouchSlop());
- assertEquals(150, viewConfiguration.getScaledDoubleTapSlop());
- assertEquals(24, viewConfiguration.getScaledWindowTouchSlop());
- assertEquals(75, viewConfiguration.getScaledMinimumFlingVelocity());
- assertEquals(6000, viewConfiguration.getScaledMaximumFlingVelocity());
- }
-
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ViewFlipperTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/ViewFlipperTest.java
deleted file mode 100644
index 7c5b5519b..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ViewFlipperTest.java
+++ /dev/null
@@ -1,32 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.app.Activity;
-import android.widget.ViewFlipper;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static org.junit.Assert.assertEquals;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class ViewFlipperTest {
- protected ViewFlipper flipper;
-
- @Before
- public void setUp() {
- flipper = new ViewFlipper(new Activity());
- }
-
- @Test
- public void testStartFlipping() {
- flipper.startFlipping();
- assertEquals("flipping", true, flipper.isFlipping());
- }
-
- @Test
- public void testStopFlipping() {
- flipper.stopFlipping();
- assertEquals("flipping", false, flipper.isFlipping());
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ViewGroupTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/ViewGroupTest.java
deleted file mode 100644
index 74a0225ea..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ViewGroupTest.java
+++ /dev/null
@@ -1,336 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.app.Application;
-import android.view.View;
-import android.view.ViewGroup;
-import android.view.animation.Animation;
-import android.view.animation.Animation.AnimationListener;
-import android.widget.FrameLayout;
-import android.widget.LinearLayout;
-import com.xtremelabs.robolectric.R;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import com.xtremelabs.robolectric.res.ResourceLoader;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import java.io.ByteArrayOutputStream;
-import java.io.PrintStream;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.CoreMatchers.sameInstance;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.core.IsNull.nullValue;
-import static org.junit.Assert.*;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class ViewGroupTest {
- private String defaultLineSeparator;
- private ViewGroup root;
- private View child1;
- private View child2;
- private ViewGroup child3;
- private View child3a;
- private View child3b;
- private Application context;
-
- @Before
- public void setUp() throws Exception {
- context = new Application();
- ShadowApplication.bind(context, new ResourceLoader(10, R.class, null, null));
-
- root = new FrameLayout(context);
-
- child1 = new View(context);
- child2 = new View(context);
- child3 = new FrameLayout(context);
- child3a = new View(context);
- child3b = new View(context);
-
- root.addView(child1);
- root.addView(child2);
- root.addView(child3);
-
- child3.addView(child3a);
- child3.addView(child3b);
-
- defaultLineSeparator = System.getProperty("line.separator");
- System.setProperty("line.separator", "\n");
- }
-
- @After
- public void tearDown() throws Exception {
- System.setProperty("line.separator", defaultLineSeparator);
- }
-
- @Test
- public void testLayoutAnimationListener() {
- assertThat(root.getLayoutAnimationListener(), nullValue());
-
- AnimationListener animationListener = new AnimationListener() {
- @Override
- public void onAnimationEnd(Animation a) { }
-
- @Override
- public void onAnimationRepeat(Animation a) { }
-
- @Override
- public void onAnimationStart(Animation a) { }
- };
- root.setLayoutAnimationListener(animationListener);
-
- assertThat(root.getLayoutAnimationListener(), sameInstance(animationListener));
- }
-
- @Test
- public void testRemoveChildAt() throws Exception {
- root.removeViewAt(1);
-
- assertThat(root.getChildCount(), equalTo(2));
- assertThat(root.getChildAt(0), sameInstance(child1));
- assertThat(root.getChildAt(1), sameInstance((View) child3));
-
- assertThat(child2.getParent(), nullValue());
- }
-
- @Test
- public void testAddViewAt() throws Exception {
- root.removeAllViews();
- root.addView(child1);
- root.addView(child2);
- root.addView(child3, 1);
- assertThat(root.getChildAt(0), sameInstance(child1));
- assertThat(root.getChildAt(1), sameInstance((View) child3));
- assertThat(root.getChildAt(2), sameInstance(child2));
- }
-
- @Test
- public void shouldfindViewWithTag() {
- root.removeAllViews();
- child1.setTag("tag1");
- child2.setTag("tag2");
- child3.setTag("tag3");
- root.addView(child1);
- root.addView(child2);
- root.addView(child3, 1);
- assertThat(root.findViewWithTag("tag1"), sameInstance(child1));
- assertThat(root.findViewWithTag("tag2"), sameInstance(child2));
- assertThat((ViewGroup) root.findViewWithTag("tag3"), sameInstance(child3));
- }
-
- @Test
- public void shouldNotfindViewWithTagReturnNull() {
- root.removeAllViews();
- child1.setTag("tag1");
- child2.setTag("tag2");
- child3.setTag("tag3");
- root.addView(child1);
- root.addView(child2);
- root.addView(child3, 1);
- assertThat(root.findViewWithTag("tag21"), equalTo(null));
- assertThat((ViewGroup) root.findViewWithTag("tag23"), equalTo(null));
- }
-
- @Test
- public void shouldfindViewWithTagFromCorrectViewGroup() {
- root.removeAllViews();
- child1.setTag("tag1");
- child2.setTag("tag2");
- child3.setTag("tag3");
- root.addView(child1);
- root.addView(child2);
- root.addView(child3);
-
- child3a.setTag("tag1");
- child3b.setTag("tag2");
-
- //can find views by tag from root
- assertThat(root.findViewWithTag("tag1"), sameInstance(child1));
- assertThat(root.findViewWithTag("tag2"), sameInstance(child2));
- assertThat((ViewGroup) root.findViewWithTag("tag3"), sameInstance(child3));
-
- //can find views by tag from child3
- assertThat(child3.findViewWithTag("tag1"), sameInstance(child3a));
- assertThat(child3.findViewWithTag("tag2"), sameInstance(child3b));
- }
-
- @Test
- public void shouldFindViewWithTag_whenViewGroupOverridesGetTag() throws Exception {
- ViewGroup viewGroup = new LinearLayout(Robolectric.application) {
- @Override
- public Object getTag() {
- return "blarg";
- }
- };
- assertThat((ViewGroup) viewGroup.findViewWithTag("blarg"), sameInstance(viewGroup));
- }
-
- @Test
- public void hasFocus_shouldReturnTrueIfAnyChildHasFocus() throws Exception {
- assertFalse(root.hasFocus());
-
- child1.requestFocus();
- assertTrue(root.hasFocus());
-
- child1.clearFocus();
- assertFalse(root.hasFocus());
-
- child3b.requestFocus();
- assertTrue(root.hasFocus());
-
- child3b.clearFocus();
- assertFalse(root.hasFocus());
-
- root.requestFocus();
- assertTrue(root.hasFocus());
- }
-
- @Test
- public void clearFocus_shouldRecursivelyClearTheFocusOfAllChildren() throws Exception {
- child3a.requestFocus();
-
- root.clearFocus();
-
- assertFalse(child3a.hasFocus());
- assertFalse(child3.hasFocus());
- assertFalse(root.hasFocus());
-
- root.requestFocus();
- root.clearFocus();
- assertFalse(root.hasFocus());
- }
-
- @Test
- public void findFocus_shouldRecursivelyFindTheViewWithFocus() {
- child3a.requestFocus();
-
- assertSame(child3a, root.findFocus());
- }
-
- @Test
- public void findFocus_shouldReturnThisBeforeChildrenWithFocus() {
- child3a.requestFocus();
- child3.requestFocus();
-
- assertSame(child3, root.findFocus());
- }
-
- @Test
- public void dump_shouldDumpStructure() throws Exception {
- child3.setId(R.id.snippet_text);
-
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- shadowOf(root).dump(new PrintStream(out), 0);
- assertEquals("<FrameLayout>\n" +
- " <View/>\n" +
- " <View/>\n" +
- " <FrameLayout id=\"id/snippet_text\">\n" +
- " <View/>\n" +
- " <View/>\n" +
- " </FrameLayout>\n" +
- "</FrameLayout>\n", out.toString());
- }
-
- @Test
- public void testRemoveView() {
- root.removeView(new View(context));
- assertThat(root.getChildCount(), equalTo(3));
-
- root.removeView(child2);
- assertThat(root.getChildCount(), equalTo(2));
- assertThat(root.getChildAt(0), sameInstance(child1));
- assertThat(root.getChildAt(1), sameInstance((View) child3));
-
- root.removeView(child2);
- assertThat(root.getChildCount(), equalTo(2));
- assertThat(root.getChildAt(0), sameInstance(child1));
- assertThat(root.getChildAt(1), sameInstance((View) child3));
-
- root.removeView(child1);
- root.removeView(child3);
- assertThat(root.getChildCount(), equalTo(0));
- }
-
- @Test
- public void testRemoveViewInLayout() {
- root.removeViewInLayout(new View(context));
- assertThat(root.getChildCount(), equalTo(3));
-
- root.removeViewInLayout(child2);
- assertThat(root.getChildCount(), equalTo(2));
- assertThat(root.getChildAt(0), sameInstance(child1));
- assertThat(root.getChildAt(1), sameInstance((View) child3));
-
- root.removeViewInLayout(child2);
- assertThat(root.getChildCount(), equalTo(2));
- assertThat(root.getChildAt(0), sameInstance(child1));
- assertThat(root.getChildAt(1), sameInstance((View) child3));
-
- root.removeViewInLayout(child1);
- root.removeViewInLayout(child3);
- assertThat(root.getChildCount(), equalTo(0));
- }
-
- @Test
- public void testRemoveViews() {
- root.removeViews(0, 0);
- assertThat(root.getChildCount(), equalTo(3));
-
- root.removeViews(2, 1);
- assertThat(root.getChildCount(), equalTo(2));
- assertThat(root.getChildAt(0), sameInstance(child1));
- assertThat(root.getChildAt(1), sameInstance(child2));
-
- root.removeViews(0, 1);
- assertThat(root.getChildCount(), equalTo(1));
- assertThat(root.getChildAt(0), sameInstance(child2));
-
- root.removeViews(0, 1);
- assertThat(root.getChildCount(), equalTo(0));
-
- root.addView(child1);
- root.addView(child2);
- root.addView(child3);
-
- root.removeViews(1, 1);
- assertThat(root.getChildCount(), equalTo(2));
- assertThat(root.getChildAt(0), sameInstance(child1));
- assertThat(root.getChildAt(1), sameInstance((View) child3));
-
- root.removeViews(0, 2);
- assertThat(root.getChildCount(), equalTo(0));
- }
-
- @Test
- public void testRemoveViewsInLayout() {
- root.removeViewsInLayout(0, 0);
- assertThat(root.getChildCount(), equalTo(3));
-
- root.removeViewsInLayout(2, 1);
- assertThat(root.getChildCount(), equalTo(2));
- assertThat(root.getChildAt(0), sameInstance(child1));
- assertThat(root.getChildAt(1), sameInstance(child2));
-
- root.removeViewsInLayout(0, 1);
- assertThat(root.getChildCount(), equalTo(1));
- assertThat(root.getChildAt(0), sameInstance(child2));
-
- root.removeViewsInLayout(0, 1);
- assertThat(root.getChildCount(), equalTo(0));
-
- root.addView(child1);
- root.addView(child2);
- root.addView(child3);
-
- root.removeViewsInLayout(1, 1);
- assertThat(root.getChildCount(), equalTo(2));
- assertThat(root.getChildAt(0), sameInstance(child1));
- assertThat(root.getChildAt(1), sameInstance((View) child3));
-
- root.removeViewsInLayout(0, 2);
- assertThat(root.getChildCount(), equalTo(0));
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ViewInnerTextTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/ViewInnerTextTest.java
deleted file mode 100644
index 99b39b68d..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ViewInnerTextTest.java
+++ /dev/null
@@ -1,76 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.app.Activity;
-import android.content.Context;
-import android.view.View;
-import android.widget.LinearLayout;
-import android.widget.TextView;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-import static org.junit.Assert.assertEquals;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class ViewInnerTextTest {
- private Context activity;
-
- @Before
- public void setUp() throws Exception {
- activity = new Activity();
- }
-
- @Test
- public void testInnerText() throws Exception {
- LinearLayout top = new LinearLayout(activity);
- top.addView(textView("blah"));
- top.addView(new View(activity));
- top.addView(textView("a b c"));
-
- LinearLayout innerLayout = new LinearLayout(activity);
- top.addView(innerLayout);
-
- innerLayout.addView(textView("d e f"));
- innerLayout.addView(textView("g h i"));
- innerLayout.addView(textView(""));
- innerLayout.addView(textView(null));
- innerLayout.addView(textView("jkl!"));
-
- top.addView(textView("mnop"));
-
- assertEquals("blah a b c d e f g h i jkl! mnop", shadowOf(top).innerText());
- }
-
- @Test
- public void shouldOnlyIncludeViewTextViewsText() throws Exception {
- LinearLayout top = new LinearLayout(activity);
- top.addView(textView("blah", View.VISIBLE));
- top.addView(textView("blarg", View.GONE));
- top.addView(textView("arrg", View.INVISIBLE));
-
- assertEquals("blah", shadowOf(top).innerText());
- }
-
- @Test
- public void shouldNotPrefixBogusSpaces() throws Exception {
- LinearLayout top = new LinearLayout(activity);
- top.addView(textView("blarg", View.GONE));
- top.addView(textView("arrg", View.INVISIBLE));
- top.addView(textView("blah", View.VISIBLE));
-
- assertEquals("blah", shadowOf(top).innerText());
- }
-
- private TextView textView(String text) {
- return textView(text, View.VISIBLE);
- }
-
- private TextView textView(String text, int visibility) {
- TextView textView = new TextView(activity);
- textView.setText(text);
- textView.setVisibility(visibility);
- return textView;
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ViewMeasureSpecTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/ViewMeasureSpecTest.java
deleted file mode 100644
index 0d5603e2d..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ViewMeasureSpecTest.java
+++ /dev/null
@@ -1,46 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import static org.junit.Assert.assertEquals;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-
-import android.view.View;
-import android.view.View.MeasureSpec;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class ViewMeasureSpecTest {
-
- @Test
- public void testMode() throws Exception {
- assertEquals(View.MeasureSpec.UNSPECIFIED,
- MeasureSpec.getMode(MeasureSpec.makeMeasureSpec(512, View.MeasureSpec.UNSPECIFIED)));
- assertEquals(View.MeasureSpec.EXACTLY,
- MeasureSpec.getMode(MeasureSpec.makeMeasureSpec(600, View.MeasureSpec.EXACTLY)));
- assertEquals(View.MeasureSpec.AT_MOST,
- MeasureSpec.getMode(MeasureSpec.makeMeasureSpec(320, View.MeasureSpec.AT_MOST)));
- }
-
- @Test
- public void testSize() throws Exception {
- assertEquals(512,
- MeasureSpec.getSize(MeasureSpec.makeMeasureSpec(512, View.MeasureSpec.UNSPECIFIED)));
- assertEquals(800,
- MeasureSpec.getSize(MeasureSpec.makeMeasureSpec(800, View.MeasureSpec.EXACTLY)));
- assertEquals(1280,
- MeasureSpec.getSize(MeasureSpec.makeMeasureSpec(1280, View.MeasureSpec.AT_MOST)));
- }
-
- @Test
- public void testToString() throws Exception {
- assertEquals("MeasureSpec: UNSPECIFIED 512",
- MeasureSpec.toString(MeasureSpec.makeMeasureSpec(512, View.MeasureSpec.UNSPECIFIED)));
- assertEquals("MeasureSpec: EXACTLY 480",
- MeasureSpec.toString(MeasureSpec.makeMeasureSpec(480, View.MeasureSpec.EXACTLY)));
- assertEquals("MeasureSpec: AT_MOST 960",
- MeasureSpec.toString(MeasureSpec.makeMeasureSpec(960, View.MeasureSpec.AT_MOST)));
- }
-
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ViewPagerTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/ViewPagerTest.java
deleted file mode 100644
index edcc5e6c4..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ViewPagerTest.java
+++ /dev/null
@@ -1,69 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.app.Activity;
-import android.support.v4.view.PagerAdapter;
-import android.support.v4.view.ViewPager;
-import android.view.View;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static junit.framework.Assert.*;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class ViewPagerTest {
-
- private ViewPager pager;
- private TestPagerAdapter adapter;
-
- @Before
- public void setUp() throws Exception {
- pager = new ViewPager(new Activity());
- adapter = new TestPagerAdapter();
- }
-
- @Test
- public void shouldSetAndGetAdapter() throws Exception {
- assertNull(pager.getAdapter());
-
- pager.setAdapter(adapter);
- assertSame(adapter, pager.getAdapter());
- }
-
- @Test
- public void test_getAndSetCurrentItem() throws Exception {
- pager.setCurrentItem(2);
- assertEquals(2, pager.getCurrentItem());
- }
-
- @Test
- public void setCurrentItem_shouldInvokeListener() throws Exception {
- TestOnPageChangeListener listener = new TestOnPageChangeListener();
- pager.setOnPageChangeListener(listener);
- assertFalse(listener.onPageSelectedCalled);
- pager.setCurrentItem(2);
- assertTrue(listener.onPageSelectedCalled);
- }
-
- private static class TestPagerAdapter extends PagerAdapter {
- @Override
- public int getCount() {
- return 0;
- }
-
- @Override
- public boolean isViewFromObject(View view, Object object) {
- return false;
- }
- }
-
- private static class TestOnPageChangeListener extends ViewPager.SimpleOnPageChangeListener {
- public boolean onPageSelectedCalled;
-
- @Override
- public void onPageSelected(int position) {
- onPageSelectedCalled = true;
- }
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ViewStubTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/ViewStubTest.java
deleted file mode 100644
index f84110967..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ViewStubTest.java
+++ /dev/null
@@ -1,61 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.content.Context;
-import android.view.View;
-import android.view.ViewStub;
-import android.widget.LinearLayout;
-import com.xtremelabs.robolectric.R;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import com.xtremelabs.robolectric.tester.android.util.TestAttributeSet;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static org.junit.Assert.*;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class ViewStubTest {
- private Context ctxt;
-
- @Before public void setUp() throws Exception {
- ctxt = Robolectric.application;
- }
-
- @Test
- public void inflate_shouldReplaceOriginalWithLayout() throws Exception {
- ViewStub viewStub = new ViewStub(ctxt);
- int stubId = 12345;
- int inflatedId = 12346;
-
- viewStub.setId(stubId);
- viewStub.setInflatedId(inflatedId);
- viewStub.setLayoutResource(R.layout.media);
-
- LinearLayout root = new LinearLayout(ctxt);
- root.addView(new View(ctxt));
- root.addView(viewStub);
- root.addView(new View(ctxt));
-
- View inflatedView = viewStub.inflate();
- assertNotNull(inflatedView);
- assertSame(inflatedView, root.findViewById(inflatedId));
-
- assertNull(root.findViewById(stubId));
-
- assertEquals(1, root.indexOfChild(inflatedView));
- assertEquals(3, root.getChildCount());
- }
-
- @Test
- public void shouldApplyAttributes() throws Exception {
- ViewStub viewStub = new ViewStub(ctxt,
- new TestAttributeSet()
- .put("android:inflatedId", "@+id/include_id")
- .put("android:layout", "@layout/media")
- );
-
- assertEquals(R.id.include_id, viewStub.getInflatedId());
- assertEquals(R.layout.media, viewStub.getLayoutResource());
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ViewTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/ViewTest.java
deleted file mode 100644
index c0f130179..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ViewTest.java
+++ /dev/null
@@ -1,516 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.app.Activity;
-import android.content.Context;
-import android.graphics.Point;
-import android.graphics.Rect;
-import android.graphics.drawable.ColorDrawable;
-import android.view.*;
-import android.view.View.MeasureSpec;
-import android.view.animation.Animation;
-import android.widget.LinearLayout;
-import com.xtremelabs.robolectric.R;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import com.xtremelabs.robolectric.util.*;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-import static junit.framework.Assert.assertEquals;
-import static org.hamcrest.CoreMatchers.*;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.junit.Assert.*;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class ViewTest {
- private View view;
-
- @Before
- public void setUp() throws Exception {
- view = new View(new Activity());
- }
-
- @Test
- public void testHasEmptyLayoutParams() throws Exception {
- ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
- assertThat(layoutParams, notNullValue());
- }
-
- @Test
- public void layout_shouldAffectWidthAndHeight() throws Exception {
- assertThat(view.getWidth(), equalTo(0));
- assertThat(view.getHeight(), equalTo(0));
-
- view.layout(100, 200, 303, 404);
- assertThat(view.getWidth(), equalTo(303 - 100));
- assertThat(view.getHeight(), equalTo(404 - 200));
- }
-
- @Test
- public void shouldFocus() throws Exception {
- final Transcript transcript = new Transcript();
-
- view.setOnFocusChangeListener(new View.OnFocusChangeListener() {
- @Override
- public void onFocusChange(View v, boolean hasFocus) {
- transcript.add(hasFocus ? "Gained focus" : "Lost focus");
- }
- });
-
- assertFalse(view.isFocused());
- assertFalse(view.hasFocus());
- transcript.assertNoEventsSoFar();
-
- view.requestFocus();
- assertTrue(view.isFocused());
- assertTrue(view.hasFocus());
- transcript.assertEventsSoFar("Gained focus");
-
- view.clearFocus();
- assertFalse(view.isFocused());
- assertFalse(view.hasFocus());
- transcript.assertEventsSoFar("Lost focus");
- }
-
- @Test
- public void shouldNotBeFocusableByDefault() throws Exception {
- assertFalse(view.isFocusable());
-
- view.setFocusable(true);
- assertTrue(view.isFocusable());
- }
-
- @Test
- public void shouldKnowIfThisOrAncestorsAreVisible() throws Exception {
- assertTrue(shadowOf(view).derivedIsVisible());
-
- ViewGroup grandParent = new LinearLayout(null);
- ViewGroup parent = new LinearLayout(null);
- grandParent.addView(parent);
- parent.addView(view);
-
- grandParent.setVisibility(View.GONE);
-
- assertFalse(shadowOf(view).derivedIsVisible());
- }
-
- @Test
- public void shouldInflateMergeRootedLayoutAndNotCreateReferentialLoops() throws Exception {
- LinearLayout root = new LinearLayout(null);
- root.inflate(new Activity(), R.layout.inner_merge, root);
- for (int i = 0; i < root.getChildCount(); i++) {
- View child = root.getChildAt(i);
- assertNotSame(root, child);
- }
- }
-
- @Test
- public void performLongClick_shouldClickOnView() throws Exception {
- TestOnLongClickListener clickListener = new TestOnLongClickListener();
- view.setOnLongClickListener(clickListener);
- shadowOf(view).performLongClick();
-
- assertTrue(clickListener.clicked);
- }
-
- @Test
- public void checkedClick_shouldClickOnView() throws Exception {
- TestOnClickListener clickListener = new TestOnClickListener();
- view.setOnClickListener(clickListener);
- shadowOf(view).checkedPerformClick();
-
- assertTrue(clickListener.clicked);
- }
-
- @Test(expected = RuntimeException.class)
- public void checkedClick_shouldThrowIfViewIsNotVisible() throws Exception {
- ViewGroup grandParent = new LinearLayout(null);
- ViewGroup parent = new LinearLayout(null);
- grandParent.addView(parent);
- parent.addView(view);
- grandParent.setVisibility(View.GONE);
-
- shadowOf(view).checkedPerformClick();
- }
-
- @Test(expected = RuntimeException.class)
- public void checkedClick_shouldThrowIfViewIsDisabled() throws Exception {
- view.setEnabled(false);
- shadowOf(view).checkedPerformClick();
- }
-
- @Test
- public void getBackground_shouldReturnNullIfNoBackgroundHasBeenSet() throws Exception {
- assertThat(view.getBackground(), nullValue());
- }
-
- @Test
- public void shouldSetBackgroundColor() {
- view.setBackgroundColor(R.color.android_red);
- int intColor = view.getResources().getColor(R.color.android_red);
-
- assertThat((ColorDrawable) view.getBackground(), equalTo(new ColorDrawable(intColor)));
- }
-
- @Test
- public void shouldSetBackgroundResource() throws Exception {
- view.setBackgroundResource(R.drawable.an_image);
- assertThat(view.getBackground(), equalTo(view.getResources().getDrawable(R.drawable.an_image)));
- }
-
- @Test
- public void shouldRecordBackgroundColor() {
- int[] colors = {0, 1, 727};
-
- for (int color : colors) {
- view.setBackgroundColor(color);
- assertThat(shadowOf(view).getBackgroundColor(), equalTo(color));
- }
- }
-
- @Test
- public void shouldPostActionsToTheMessageQueue() throws Exception {
- Robolectric.pauseMainLooper();
-
- TestRunnable runnable = new TestRunnable();
- view.post(runnable);
- assertFalse(runnable.wasRun);
-
- Robolectric.unPauseMainLooper();
- assertTrue(runnable.wasRun);
- }
-
- @Test
- public void shouldPostInvalidateDelayed() throws Exception {
- Robolectric.pauseMainLooper();
-
- view.postInvalidateDelayed(100);
- ShadowView shadowView = shadowOf(view);
- assertFalse(shadowView.wasInvalidated());
-
- Robolectric.unPauseMainLooper();
- assertTrue(shadowView.wasInvalidated());
- }
-
- @Test
- public void shouldPostActionsToTheMessageQueueWithDelay() throws Exception {
- Robolectric.pauseMainLooper();
-
- TestRunnable runnable = new TestRunnable();
- view.postDelayed(runnable, 1);
- assertFalse(runnable.wasRun);
-
- Robolectric.getUiThreadScheduler().advanceBy(1);
- assertTrue(runnable.wasRun);
- }
-
- @Test
- public void shouldSupportAllConstructors() throws Exception {
- new View(null);
- new View(null, null);
- new View(null, null, 0);
- }
-
- @Test
- public void shouldSetAnimation() throws Exception {
- Animation anim = new TestAnimation();
- view.setAnimation(anim);
- assertThat(view.getAnimation(), sameInstance(anim));
- }
-
- @Test
- public void shouldStartAndClearAnimation() throws Exception {
- Animation anim = new TestAnimation();
- TestAnimationListener listener = new TestAnimationListener();
- anim.setAnimationListener(listener);
- assertThat(listener.wasStartCalled, equalTo(false));
- assertThat(listener.wasRepeatCalled, equalTo(false));
- assertThat(listener.wasEndCalled, equalTo(false));
- view.startAnimation(anim);
- assertThat(listener.wasStartCalled, equalTo(true));
- assertThat(listener.wasRepeatCalled, equalTo(false));
- assertThat(listener.wasEndCalled, equalTo(false));
- view.clearAnimation();
- assertThat(listener.wasStartCalled, equalTo(true));
- assertThat(listener.wasRepeatCalled, equalTo(false));
- assertThat(listener.wasEndCalled, equalTo(true));
- }
-
- @Test
- public void shouldFindViewWithTag() {
- view.setTag("tagged");
- assertThat(view.findViewWithTag("tagged"), sameInstance(view));
- }
-
- @Test
- public void shouldFindViewWithTag_whenViewOverridesGetTag() throws Exception {
- View view = new View(Robolectric.application) {
- @Override
- public Object getTag() {
- return "blarg";
- }
- };
- assertThat(view.findViewWithTag("blarg"), sameInstance(view));
- }
-
- @Test
- public void scrollTo_shouldStoreTheScrolledCoordinates() throws Exception {
- view.scrollTo(1, 2);
- assertThat(shadowOf(view).scrollToCoordinates, equalTo(new Point(1, 2)));
- }
-
- @Test
- public void shouldScrollTo() throws Exception {
- view.scrollTo(7, 6);
-
- assertEquals(7, view.getScrollX());
- assertEquals(6, view.getScrollY());
- }
-
- @Test
- public void shouldGetScrollXAndY() {
- assertEquals(0, view.getScrollX());
- assertEquals(0, view.getScrollY());
- }
-
- @Test
- public void getViewTreeObserver_shouldReturnTheSameObserverFromMultipleCalls() throws Exception {
- ViewTreeObserver observer = view.getViewTreeObserver();
- assertThat(observer, instanceOf(ViewTreeObserver.class));
- assertThat(view.getViewTreeObserver(), sameInstance(observer));
- }
-
- @Test
- public void dispatchTouchEvent_sendsMotionEventToOnTouchEvent() throws Exception {
- TouchableView touchableView = new TouchableView(null);
- MotionEvent event = MotionEvent.obtain(0L, 0L, MotionEvent.ACTION_DOWN, 12f, 34f, 0);
- touchableView.dispatchTouchEvent(event);
- assertThat(touchableView.event, sameInstance(event));
- view.dispatchTouchEvent(event);
- assertThat(shadowOf(view).getLastTouchEvent(), sameInstance(event));
- }
-
- @Test
- public void dispatchTouchEvent_listensToTrueFromListener() throws Exception {
- view.setOnTouchListener(new View.OnTouchListener() {
- @Override
- public boolean onTouch(View view, MotionEvent motionEvent) {
- return true;
- }
- });
- MotionEvent event = MotionEvent.obtain(0L, 0L, MotionEvent.ACTION_DOWN, 12f, 34f, 0);
- view.dispatchTouchEvent(event);
- assertThat(shadowOf(view).getLastTouchEvent(), nullValue());
- }
-
- @Test
- public void dispatchTouchEvent_listensToFalseFromListener() throws Exception {
- view.setOnTouchListener(new View.OnTouchListener() {
- @Override
- public boolean onTouch(View view, MotionEvent motionEvent) {
- return false;
- }
- });
- MotionEvent event = MotionEvent.obtain(0L, 0L, MotionEvent.ACTION_DOWN, 12f, 34f, 0);
- view.dispatchTouchEvent(event);
- assertThat(shadowOf(view).getLastTouchEvent(), sameInstance(event));
- }
-
- @Test
- public void dispatchFocusEvent_sendsFocusToOnFocusChanged() throws Exception {
- FocusableView focusableView = new FocusableView(null);
- focusableView.requestFocus();
- assertThat(focusableView.onFocusChangedWasCalled, equalTo(true));
- }
-
- @Test
- public void test_nextFocusDownId() throws Exception {
- assertEquals(View.NO_ID, view.getNextFocusDownId());
-
- view.setNextFocusDownId(R.id.icon);
- assertEquals(R.id.icon, view.getNextFocusDownId());
- }
-
- @Test
- public void dispatchOnAnimationEnd() throws Exception {
- TestView view1 = new TestView(new Activity());
- assertFalse(view1.onAnimationEndWasCalled);
- shadowOf(view1).finishedAnimation();
- assertTrue(view1.onAnimationEndWasCalled);
- }
-
- @Test
- public void test_measuredDimension() {
- // View does not provide its own onMeasure implementation
- TestView view1 = new TestView(new Activity());
-
- assertThat(view1.getHeight(), equalTo(0));
- assertThat(view1.getWidth(), equalTo(0));
- assertThat(view1.getMeasuredHeight(), equalTo(0));
- assertThat(view1.getMeasuredWidth(), equalTo(0));
-
- view1.measure( MeasureSpec.makeMeasureSpec(150, MeasureSpec.AT_MOST),
- MeasureSpec.makeMeasureSpec(300, MeasureSpec.AT_MOST) );
-
- assertThat(view1.getHeight(), equalTo(0));
- assertThat(view1.getWidth(), equalTo(0));
- assertThat(view1.getMeasuredHeight(), equalTo(300));
- assertThat(view1.getMeasuredWidth(), equalTo(150));
- }
-
- @Test
- public void test_measuredDimensionCustomView() {
- // View provides its own onMeasure implementation
- TestView2 view2 = new TestView2(new Activity());
-
- assertThat(view2.getHeight(), equalTo(0));
- assertThat(view2.getWidth(), equalTo(0));
- assertThat(view2.getMeasuredHeight(), equalTo(0));
- assertThat(view2.getMeasuredWidth(), equalTo(0));
-
- view2.measure( MeasureSpec.makeMeasureSpec(1000, MeasureSpec.AT_MOST),
- MeasureSpec.makeMeasureSpec(600, MeasureSpec.AT_MOST) );
-
- assertThat(view2.getHeight(), equalTo(0));
- assertThat(view2.getWidth(), equalTo(0));
- assertThat(view2.getMeasuredHeight(), equalTo(400));
- assertThat(view2.getMeasuredWidth(), equalTo(800));
- }
-
- @Test
- public void testFilterTouchesWhenObscured() {
- assertFalse(view.getFilterTouchesWhenObscured());
-
- view.setFilterTouchesWhenObscured(true);
- assertTrue(view.getFilterTouchesWhenObscured());
-
- view.setFilterTouchesWhenObscured(false);
- assertFalse(view.getFilterTouchesWhenObscured());
- }
-
- @Test
- public void testFilterTouchesWhenObscuredWhenLoadedFromXml() {
- LinearLayout root = new LinearLayout(null);
- ShadowView.inflate(new Activity(), R.layout.views, root);
-
- View defaultView = root.findViewById(R.id.default_view);
- assertFalse(defaultView.getFilterTouchesWhenObscured());
-
- View filterFalseView = root.findViewById(R.id.filter_touches_false_view);
- assertFalse(filterFalseView.getFilterTouchesWhenObscured());
-
- View filterTrueView = root.findViewById(R.id.filter_touches_true_view);
- assertTrue(filterTrueView.getFilterTouchesWhenObscured());
- }
-
- @Test
- public void testClickable() {
- assertFalse(view.isClickable());
-
- view.setClickable(true);
- assertTrue(view.isClickable());
-
- view.setClickable(false);
- assertFalse(view.isClickable());
- }
-
- @Test
- public void testClickableWhenLoadedFromXml() {
- LinearLayout root = new LinearLayout(null);
- ShadowView.inflate(new Activity(), R.layout.views, root);
-
- View defaultView = root.findViewById(R.id.default_view);
- assertFalse(defaultView.isClickable());
-
- View clickableFalseView = root.findViewById(R.id.clickable_false_view);
- assertFalse(clickableFalseView.isClickable());
-
- View clickableTrueView = root.findViewById(R.id.clickable_true_view);
- assertTrue(clickableTrueView.isClickable());
- }
-
- @Test
- public void testFocusable() {
- assertFalse(view.isFocusable());
-
- view.setFocusable(true);
- assertTrue(view.isFocusable());
-
- view.setFocusable(false);
- assertFalse(view.isFocusable());
- }
-
- @Test
- public void testFocusableWhenLoadedFromXml() {
- LinearLayout root = new LinearLayout(null);
- ShadowView.inflate(new Activity(), R.layout.views, root);
-
- View defaultView = root.findViewById(R.id.default_view);
- assertFalse(defaultView.isFocusable());
-
- View focusableFalseView = root.findViewById(R.id.focusable_false_view);
- assertFalse(focusableFalseView.isFocusable());
-
- View focusableTrueView = root.findViewById(R.id.focusable_true_view);
- assertTrue(focusableTrueView.isFocusable());
- }
-
- private static class TestAnimation extends Animation {
- }
-
- private static class TouchableView extends View {
- MotionEvent event;
-
- public TouchableView(Context context) {
- super(context);
- }
-
- @Override
- public boolean onTouchEvent(MotionEvent event) {
- this.event = event;
- return false;
- }
- }
-
- private static class TestView extends View {
- boolean onAnimationEndWasCalled;
-
- public TestView(Context context) {
- super(context);
- }
-
- @Override
- protected void onAnimationEnd() {
- super.onAnimationEnd();
- onAnimationEndWasCalled = true;
- }
- }
-
- private static class FocusableView extends View {
- boolean onFocusChangedWasCalled;
-
- public FocusableView(Context context) {
- super(context);
- }
-
- @Override
- protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
- super.onFocusChanged(gainFocus, direction, previouslyFocusedRect);
-
- onFocusChangedWasCalled = true;
- }
- }
-
- private static class TestView2 extends View {
- public TestView2(Context context) {
- super(context);
- }
-
- @Override
- protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
- super.onMeasure(800, 400);
- }
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ViewTreeObserverTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/ViewTreeObserverTest.java
deleted file mode 100644
index 946f25b2d..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/ViewTreeObserverTest.java
+++ /dev/null
@@ -1,79 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.view.ViewTreeObserver;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import java.util.List;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class ViewTreeObserverTest {
-
- private ViewTreeObserver viewTreeObserver;
- private TestOnGlobalLayoutListener listener1;
- private TestOnGlobalLayoutListener listener2;
-
- @Before
- public void setUp() throws Exception {
- viewTreeObserver = Robolectric.Reflection.newInstanceOf(ViewTreeObserver.class);
- listener1 = new TestOnGlobalLayoutListener();
- listener2 = new TestOnGlobalLayoutListener();
- }
-
- @Test
- public void shouldRecordMultipleOnGlobalLayoutListenersAndFireThemWhenAsked() throws Exception {
- viewTreeObserver.addOnGlobalLayoutListener(listener1);
- viewTreeObserver.addOnGlobalLayoutListener(listener2);
-
- shadowOf(viewTreeObserver).fireOnGlobalLayoutListeners();
- assertTrue(listener1.onGlobalLayoutWasCalled);
- assertTrue(listener2.onGlobalLayoutWasCalled);
-
- listener1.reset();
- listener2.reset();
- viewTreeObserver.removeGlobalOnLayoutListener(listener1);
- shadowOf(viewTreeObserver).fireOnGlobalLayoutListeners();
-
- assertFalse(listener1.onGlobalLayoutWasCalled);
- assertTrue(listener2.onGlobalLayoutWasCalled);
-
- listener1.reset();
- listener2.reset();
- viewTreeObserver.removeGlobalOnLayoutListener(listener2);
- shadowOf(viewTreeObserver).fireOnGlobalLayoutListeners();
-
- assertFalse(listener1.onGlobalLayoutWasCalled);
- assertFalse(listener2.onGlobalLayoutWasCalled);
- }
-
- @Test
- public void getGlobalLayoutListeners_shouldReturnTheListeners() throws Exception {
- viewTreeObserver.addOnGlobalLayoutListener(listener1);
- viewTreeObserver.addOnGlobalLayoutListener(listener2);
-
- List<ViewTreeObserver.OnGlobalLayoutListener> listeners = shadowOf(viewTreeObserver).getOnGlobalLayoutListeners();
- assertTrue(listeners.size() == 2);
- assertTrue(listeners.contains(listener1));
- assertTrue(listeners.contains(listener2));
- }
-
- private static class TestOnGlobalLayoutListener implements ViewTreeObserver.OnGlobalLayoutListener {
- boolean onGlobalLayoutWasCalled;
-
- @Override
- public void onGlobalLayout() {
- onGlobalLayoutWasCalled = true;
- }
-
- public void reset() {
- onGlobalLayoutWasCalled = false;
- }
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/WebViewTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/WebViewTest.java
deleted file mode 100644
index c287d7138..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/WebViewTest.java
+++ /dev/null
@@ -1,184 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.graphics.Picture;
-import android.webkit.WebChromeClient;
-import android.webkit.WebSettings;
-import android.webkit.WebView;
-import android.webkit.WebViewClient;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-import static junit.framework.Assert.assertEquals;
-import static junit.framework.Assert.assertTrue;
-import static org.hamcrest.CoreMatchers.*;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertThat;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class WebViewTest {
-
- private WebView webView;
- private ShadowWebView shadowWebView;
-
- @Before
- public void setUp() throws Exception {
- webView = new WebView(null);
- shadowWebView = Robolectric.shadowOf(webView);
- }
-
- @Test
- public void shouldRecordLastLoadedUrl() {
- webView.loadUrl("http://example.com");
- assertThat(shadowOf(webView).getLastLoadedUrl(), equalTo("http://example.com"));
- }
-
- @Test
- public void shouldRecordLastLoadedData() {
- webView.loadData("<html><body><h1>Hi</h1></body></html>", "text/html", "utf-8");
- ShadowWebView.LoadData lastLoadData = shadowOf(webView).getLastLoadData();
- assertThat(lastLoadData.data, equalTo("<html><body><h1>Hi</h1></body></html>"));
- assertThat(lastLoadData.mimeType, equalTo("text/html"));
- assertThat(lastLoadData.encoding, equalTo("utf-8"));
- }
-
- @Test
- public void shouldRecordLastLoadDataWithBaseURL() throws Exception {
- webView.loadDataWithBaseURL("base/url", "<html><body><h1>Hi</h1></body></html>", "text/html", "utf-8", "history/url");
- ShadowWebView.LoadDataWithBaseURL lastLoadData = shadowOf(webView).getLastLoadDataWithBaseURL();
- assertThat(lastLoadData.baseUrl, equalTo("base/url"));
- assertThat(lastLoadData.data, equalTo("<html><body><h1>Hi</h1></body></html>"));
- assertThat(lastLoadData.mimeType, equalTo("text/html"));
- assertThat(lastLoadData.encoding, equalTo("utf-8"));
- assertThat(lastLoadData.historyUrl, equalTo("history/url"));
- }
-
- @Test
- public void shouldReturnSettings() {
- WebSettings webSettings = webView.getSettings();
-
- assertThat(webSettings, notNullValue());
- }
-
- @Test
- public void shouldRecordWebViewClient() {
- WebViewClient webViewClient = new WebViewClient();
-
- assertThat(shadowWebView.getWebViewClient(), nullValue());
- webView.setWebViewClient(webViewClient);
- assertThat(shadowWebView.getWebViewClient(), sameInstance(webViewClient));
- }
-
- @Test
- public void shouldRecordWebChromeClient() {
- WebChromeClient webChromeClient = new WebChromeClient();
- assertThat(shadowWebView.getWebChromeClient(), nullValue());
- webView.setWebChromeClient(webChromeClient);
- assertThat(shadowWebView.getWebChromeClient(), sameInstance(webChromeClient));
- }
-
- @Test
- public void shouldRecordPictureListener() {
- WebView.PictureListener pictureListener = new WebView.PictureListener() {
- @Override
- public void onNewPicture(WebView view, Picture picture) {
- ;
- }
- };
-
- assertThat(shadowWebView.getPictureListener(), nullValue());
- webView.setPictureListener(pictureListener);
- assertThat(shadowWebView.getPictureListener(), sameInstance(pictureListener));
- }
-
- @Test
- public void shouldRecordJavascriptInteraces() {
- String[] names = {"name1", "name2"};
- for (String name : names) {
- Object obj = new Object();
- assertThat(shadowWebView.getJavascriptInterface(name), nullValue());
- webView.addJavascriptInterface(obj, name);
- assertThat(shadowWebView.getJavascriptInterface(name), sameInstance(obj));
- }
- }
-
- @Test
- public void shouldStartPostRun() {
- Runnable testRun = new Runnable() {
- public void run() {
- //Do something...
- return;
- }
- };
- assertThat(shadowWebView.getRunFlag(), equalTo(false));
- shadowWebView.post(testRun);
- assertThat(shadowWebView.getRunFlag(), equalTo(true));
- }
-
- @Test
- public void shouldStoreCanGoBack() throws Exception {
- shadowWebView.setCanGoBack(false);
- assertFalse(webView.canGoBack());
- shadowWebView.setCanGoBack(true);
- assertTrue(webView.canGoBack());
- }
-
- @Test
- public void shouldStoreTheNumberOfTimesGoBackWasCalled() throws Exception {
- assertEquals(0, shadowWebView.getGoBackInvocations());
- webView.goBack();
- assertEquals(1, shadowWebView.getGoBackInvocations());
- webView.goBack();
- webView.goBack();
- assertEquals(3, shadowWebView.getGoBackInvocations());
- }
-
- @Test
- public void shouldRecordClearCacheWithoutDiskFiles() {
- assertThat(shadowWebView.wasClearCacheCalled(), equalTo(false));
-
- webView.clearCache(false);
- assertThat(shadowWebView.wasClearCacheCalled(), equalTo(true));
- assertThat(shadowWebView.didClearCacheIncludeDiskFiles(), equalTo(false));
- }
-
- @Test
- public void shouldRecordClearCacheWithDiskFiles() {
- assertThat(shadowWebView.wasClearCacheCalled(), equalTo(false));
-
- webView.clearCache(true);
- assertThat(shadowWebView.wasClearCacheCalled(), equalTo(true));
- assertThat(shadowWebView.didClearCacheIncludeDiskFiles(), equalTo(true));
- }
-
- @Test
- public void shouldRecordClearFormData() {
- assertThat(shadowWebView.wasClearFormDataCalled(), equalTo(false));
- webView.clearFormData();
- assertThat(shadowWebView.wasClearFormDataCalled(), equalTo(true));
- }
-
- @Test
- public void shouldRecordClearHistory() {
- assertThat(shadowWebView.wasClearHistoryCalled(), equalTo(false));
- webView.clearHistory();
- assertThat(shadowWebView.wasClearHistoryCalled(), equalTo(true));
- }
-
- @Test
- public void shouldRecordClearView() {
- assertThat(shadowWebView.wasClearViewCalled(), equalTo(false));
- webView.clearView();
- assertThat(shadowWebView.wasClearViewCalled(), equalTo(true));
- }
-
- @Test
- public void shouldRecordDestroy() {
- assertThat(shadowWebView.wasDestroyCalled(), equalTo(false));
- webView.destroy();
- assertThat(shadowWebView.wasDestroyCalled(), equalTo(true));
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/WifiConfigurationTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/WifiConfigurationTest.java
deleted file mode 100644
index 32cb56c78..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/WifiConfigurationTest.java
+++ /dev/null
@@ -1,63 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.net.wifi.WifiConfiguration;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-import static junit.framework.Assert.assertNotNull;
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.junit.Assert.assertThat;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class WifiConfigurationTest {
- @Test
- public void shouldSetTheBitSetsAndWepKeyArrays() throws Exception {
- WifiConfiguration wifiConfiguration = new WifiConfiguration();
- assertNotNull(wifiConfiguration.allowedAuthAlgorithms);
- }
-
- @Test
- public void shouldCopy() throws Exception {
- WifiConfiguration wifiConfiguration = new WifiConfiguration();
-
- wifiConfiguration.networkId = 1;
- wifiConfiguration.SSID = "SSID";
- wifiConfiguration.BSSID = "BSSID";
- wifiConfiguration.preSharedKey = "preSharedKey";
- wifiConfiguration.status = 666;
- wifiConfiguration.wepTxKeyIndex = 777;
- wifiConfiguration.priority = 2;
- wifiConfiguration.hiddenSSID = true;
- wifiConfiguration.allowedKeyManagement.set(1);
- wifiConfiguration.allowedProtocols.set(2);
- wifiConfiguration.allowedAuthAlgorithms.set(3);
- wifiConfiguration.allowedPairwiseCiphers.set(4);
- wifiConfiguration.allowedGroupCiphers.set(5);
- wifiConfiguration.wepKeys[0] = "0";
- wifiConfiguration.wepKeys[1] = "1";
- wifiConfiguration.wepKeys[2] = "2";
- wifiConfiguration.wepKeys[3] = "3";
-
- WifiConfiguration copy = shadowOf(wifiConfiguration).copy();
-
- assertThat(copy.networkId, equalTo(1));
- assertThat(copy.SSID, equalTo("SSID"));
- assertThat(copy.BSSID, equalTo("BSSID"));
- assertThat(copy.preSharedKey, equalTo("preSharedKey"));
- assertThat(copy.status, equalTo(666));
- assertThat(copy.wepTxKeyIndex, equalTo(777));
- assertThat(copy.priority, equalTo(2));
- assertThat(copy.hiddenSSID, equalTo(true));
- assertThat(copy.allowedKeyManagement.get(1), equalTo(true));
- assertThat(copy.allowedProtocols.get(2), equalTo(true));
- assertThat(copy.allowedAuthAlgorithms.get(3), equalTo(true));
- assertThat(copy.allowedPairwiseCiphers.get(4), equalTo(true));
- assertThat(copy.allowedGroupCiphers.get(5), equalTo(true));
- assertThat(copy.wepKeys[0], equalTo("0"));
- assertThat(copy.wepKeys[1], equalTo("1"));
- assertThat(copy.wepKeys[2], equalTo("2"));
- assertThat(copy.wepKeys[3], equalTo("3"));
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/WifiInfoTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/WifiInfoTest.java
deleted file mode 100644
index 431ebc27b..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/WifiInfoTest.java
+++ /dev/null
@@ -1,28 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.net.wifi.WifiInfo;
-import android.net.wifi.WifiManager;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static android.content.Context.WIFI_SERVICE;
-import static com.xtremelabs.robolectric.Robolectric.application;
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.MatcherAssert.assertThat;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class WifiInfoTest {
-
- @Test
- public void shouldReturnMacAddress() {
- WifiManager wifiManager = (WifiManager) application.getSystemService(WIFI_SERVICE);
- WifiInfo wifiInfo = wifiManager.getConnectionInfo();
- shadowOf(wifiInfo).setMacAddress("mac address");
-
- wifiManager = (WifiManager) application.getSystemService(WIFI_SERVICE);
- wifiInfo = wifiManager.getConnectionInfo();
- assertThat(wifiInfo.getMacAddress(), equalTo("mac address"));
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/shadows/WifiManagerTest.java b/v1/src/test/java/com/xtremelabs/robolectric/shadows/WifiManagerTest.java
deleted file mode 100644
index b9e867454..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/shadows/WifiManagerTest.java
+++ /dev/null
@@ -1,207 +0,0 @@
-package com.xtremelabs.robolectric.shadows;
-
-import android.net.wifi.ScanResult;
-import android.net.wifi.WifiConfiguration;
-import android.net.wifi.WifiInfo;
-import android.net.wifi.WifiManager;
-import android.util.Pair;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import java.security.InvalidParameterException;
-import java.util.ArrayList;
-import java.util.List;
-
-import static android.content.Context.WIFI_SERVICE;
-import static com.xtremelabs.robolectric.Robolectric.application;
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-import static junit.framework.Assert.assertTrue;
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.CoreMatchers.not;
-import static org.hamcrest.CoreMatchers.sameInstance;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertThat;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class WifiManagerTest {
-
- private WifiManager wifiManager;
- private ShadowWifiManager shadowWifiManager;
-
- @Before
- public void setUp() throws Exception {
- wifiManager = (WifiManager) application.getSystemService(WIFI_SERVICE);
- shadowWifiManager = shadowOf(wifiManager);
- }
-
- @Test
- public void shouldReturnWifiInfo() {
- assertEquals(wifiManager.getConnectionInfo().getClass(), WifiInfo.class);
- }
-
- @Test(expected = SecurityException.class)
- public void setWifiEnabled_shouldThrowSecurityExceptionWhenAccessWifiStatePermissionNotGranted() throws Exception {
- shadowWifiManager.setAccessWifiStatePermission(false);
- wifiManager.setWifiEnabled(true);
- }
-
- @Test(expected = SecurityException.class)
- public void isWifiEnabled_shouldThrowSecurityExceptionWhenAccessWifiStatePermissionNotGranted() throws Exception {
- shadowWifiManager.setAccessWifiStatePermission(false);
- wifiManager.isWifiEnabled();
- }
-
- @Test(expected = SecurityException.class)
- public void getConnectionInfo_shouldThrowSecurityExceptionWhenAccessWifiStatePermissionNotGranted() throws Exception {
- shadowWifiManager.setAccessWifiStatePermission(false);
- wifiManager.getConnectionInfo();
- }
-
- @Test
- public void shouldEnableNetworks() throws Exception {
- int networkId = 666;
- wifiManager.enableNetwork(networkId, true);
- Pair<Integer, Boolean> lastEnabled = shadowWifiManager.getLastEnabledNetwork();
- assertThat(lastEnabled, equalTo(new Pair<Integer, Boolean>(666, true)));
-
- int anotherNetworkId = 777;
- wifiManager.enableNetwork(anotherNetworkId, false);
- lastEnabled = shadowWifiManager.getLastEnabledNetwork();
- assertThat(lastEnabled, equalTo(new Pair<Integer, Boolean>(777, false)));
- }
-
- @Test
- public void shouldReturnSetScanResults() throws Exception {
- List<ScanResult> scanResults = new ArrayList<ScanResult>();
- shadowWifiManager.setScanResults(scanResults);
- assertThat(wifiManager.getScanResults(), sameInstance(scanResults));
- }
-
- @Test
- public void shouldRecordTheLastAddedNetwork() throws Exception {
- WifiConfiguration wifiConfiguration = new WifiConfiguration();
- wifiConfiguration.networkId = -1;
- int networkId = wifiManager.addNetwork(wifiConfiguration);
- assertThat(networkId, equalTo(0));
- assertThat(wifiManager.getConfiguredNetworks().get(0), not(sameInstance(wifiConfiguration)));
- assertThat(wifiConfiguration.networkId, equalTo(-1));
- assertThat(wifiManager.getConfiguredNetworks().get(0).networkId, equalTo(0));
-
- WifiConfiguration anotherConfig = new WifiConfiguration();
- assertThat(wifiManager.addNetwork(anotherConfig), equalTo(1));
- assertThat(anotherConfig.networkId, equalTo(-1));
- assertThat(wifiManager.getConfiguredNetworks().get(1).networkId, equalTo(1));
- }
-
- @Test
- public void updateNetwork_shouldReplaceNetworks() throws Exception {
- WifiConfiguration wifiConfiguration = new WifiConfiguration();
- wifiConfiguration.networkId = -1;
- wifiManager.addNetwork(wifiConfiguration);
-
- WifiConfiguration anotherConfig = new WifiConfiguration();
- int networkId = wifiManager.addNetwork(anotherConfig);
-
- assertThat(networkId, equalTo(1));
- WifiConfiguration configuration = new WifiConfiguration();
- configuration.networkId = networkId;
- configuration.priority = 44;
-
- assertThat(wifiManager.updateNetwork(configuration), equalTo(networkId));
- List<WifiConfiguration> configuredNetworks = wifiManager.getConfiguredNetworks();
- assertThat(configuredNetworks.size(), equalTo(2));
- assertThat(configuration.priority, equalTo(44));
- assertThat(configuredNetworks.get(1).priority, equalTo(44));
- }
-
- @Test
- public void updateNetwork_shouldRejectNullandNewConfigs() throws Exception {
- WifiConfiguration config = new WifiConfiguration();
- config.networkId = -1;
- assertThat(wifiManager.updateNetwork(config), equalTo(-1));
- assertThat(wifiManager.updateNetwork(null), equalTo(-1));
- assertTrue(wifiManager.getConfiguredNetworks().isEmpty());
- }
-
- @Test
- public void shouldSaveConfigurations() throws Exception {
- shadowWifiManager.wasSaved = false;
- assertThat(wifiManager.saveConfiguration(), equalTo(true));
- assertThat(shadowWifiManager.wasSaved, equalTo(true));
- }
-
- @Test
- public void shouldCreateWifiLock() throws Exception {
- assertNotNull(wifiManager.createWifiLock("TAG"));
- assertNotNull(wifiManager.createWifiLock(1, "TAG"));
- }
-
- @Test
- public void shouldAcquireAndReleaseWifilockRefCounted() throws Exception {
- WifiManager.WifiLock lock = wifiManager.createWifiLock("TAG");
- lock.acquire();
- lock.acquire();
- assertTrue(lock.isHeld());
- lock.release();
- assertTrue(lock.isHeld());
- lock.release();
- assertFalse(lock.isHeld());
- }
-
- @Test
- public void shouldAcquireAndReleaseWifilockNonRefCounted() throws Exception {
- WifiManager.WifiLock lock = wifiManager.createWifiLock("TAG");
- lock.setReferenceCounted(false);
- lock.acquire();
- assertTrue(lock.isHeld());
- lock.acquire();
- assertTrue(lock.isHeld());
- lock.release();
- assertFalse(lock.isHeld());
- }
-
- @Test(expected = RuntimeException.class)
- public void shouldThrowRuntimeExceptionIfLockisUnderlocked() throws Exception {
- WifiManager.WifiLock lock = wifiManager.createWifiLock("TAG");
- lock.release();
- }
-
- @Test(expected = UnsupportedOperationException.class)
- public void shouldThrowUnsupportedOperationIfLockisOverlocked() throws Exception {
- WifiManager.WifiLock lock = wifiManager.createWifiLock("TAG");
- for (int i=0; i<ShadowWifiManager.ShadowWifiLock.MAX_ACTIVE_LOCKS; i++) lock.acquire();
- }
-
- @Test
- public void shouldCalculateSignalLevelSetBefore() {
- ShadowWifiManager.setSignalLevelInPercent(0.5f);
- assertEquals(2, WifiManager.calculateSignalLevel(0, 5));
- assertEquals(2, WifiManager.calculateSignalLevel(2, 5));
-
- ShadowWifiManager.setSignalLevelInPercent(0.9f);
- assertEquals(3, WifiManager.calculateSignalLevel(0, 5));
- assertEquals(3, WifiManager.calculateSignalLevel(2, 5));
-
- ShadowWifiManager.setSignalLevelInPercent(1f);
- assertEquals(3, WifiManager.calculateSignalLevel(0, 4));
- assertEquals(3, WifiManager.calculateSignalLevel(2, 4));
-
- ShadowWifiManager.setSignalLevelInPercent(0);
- assertEquals(0, WifiManager.calculateSignalLevel(0, 5));
- assertEquals(0, WifiManager.calculateSignalLevel(2, 5));
- }
-
- @Test(expected = IllegalArgumentException.class)
- public void shouldThrowIllegalArgumentExceptionWhenSignalLevelToLow() {
- ShadowWifiManager.setSignalLevelInPercent(-0.01f);
- }
-
- @Test(expected = IllegalArgumentException.class)
- public void shouldThrowIllegalArgumentExceptionWhenSignalLevelToHigh() {
- ShadowWifiManager.setSignalLevelInPercent(1.01f);
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/tester/android/content/TestSharedPreferencesTest.java b/v1/src/test/java/com/xtremelabs/robolectric/tester/android/content/TestSharedPreferencesTest.java
deleted file mode 100644
index 21be3b845..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/tester/android/content/TestSharedPreferencesTest.java
+++ /dev/null
@@ -1,144 +0,0 @@
-package com.xtremelabs.robolectric.tester.android.content;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.junit.Assert.*;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import android.content.SharedPreferences;
-
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-
-/**
- * TestSharedPreferencesTest
- */
-@RunWith(WithTestDefaultsRunner.class)
-public class TestSharedPreferencesTest {
- protected final static String FILENAME = "filename";
- private HashMap<String, Map<String, Object>> content;
- private SharedPreferences.Editor editor;
- private TestSharedPreferences sharedPreferences;
-
- @Before
- public void setUp() {
- content = new HashMap<String, Map<String, Object>>();
-
- sharedPreferences = new TestSharedPreferences(content, FILENAME, 3);
- editor = sharedPreferences.edit();
- editor.putBoolean("boolean", true);
- editor.putFloat("float", 1.1f);
- editor.putInt("int", 2);
- editor.putLong("long", 3l);
- editor.putString("string", "foobar");
- }
-
- @Test
- public void commit_shouldStoreValues() throws Exception {
- editor.commit();
-
- TestSharedPreferences anotherSharedPreferences = new TestSharedPreferences(content, FILENAME, 3);
- assertTrue(anotherSharedPreferences.getBoolean("boolean", false));
- assertThat(anotherSharedPreferences.getFloat("float", 666f), equalTo(1.1f));
- assertThat(anotherSharedPreferences.getInt("int", 666), equalTo(2));
- assertThat(anotherSharedPreferences.getLong("long", 666l), equalTo(3l));
- assertThat(anotherSharedPreferences.getString("string", "wacka wa"), equalTo("foobar"));
- }
-
- @Test
- public void getAll_shouldReturnAllValues() throws Exception {
- editor.commit();
- Map<String, ?> all = sharedPreferences.getAll();
- assertThat(all.size(), equalTo(5));
- assertThat((Integer) all.get("int"), equalTo(2));
- }
-
- @Test
- public void commit_shouldRemoveValuesThenSetValues() throws Exception {
- content.put(FILENAME, new HashMap<String, Object>());
- content.get(FILENAME).put("deleteMe", "foo");
-
- editor.remove("deleteMe");
-
- editor.putString("dontDeleteMe", "baz");
- editor.remove("dontDeleteMe");
-
- editor.commit();
-
- TestSharedPreferences anotherSharedPreferences = new TestSharedPreferences(content, FILENAME, 3);
- assertTrue(anotherSharedPreferences.getBoolean("boolean", false));
- assertThat(anotherSharedPreferences.getFloat("float", 666f), equalTo(1.1f));
- assertThat(anotherSharedPreferences.getInt("int", 666), equalTo(2));
- assertThat(anotherSharedPreferences.getLong("long", 666l), equalTo(3l));
- assertThat(anotherSharedPreferences.getString("string", "wacka wa"), equalTo("foobar"));
-
- assertThat(anotherSharedPreferences.getString("deleteMe", "awol"), equalTo("awol"));
- assertThat(anotherSharedPreferences.getString("dontDeleteMe", "oops"), equalTo("baz"));
- }
-
- @Test
- public void commit_shouldClearThenSetValues() throws Exception {
- content.put(FILENAME, new HashMap<String, Object>());
- content.get(FILENAME).put("deleteMe", "foo");
-
- editor.clear();
- editor.putString("dontDeleteMe", "baz");
-
- editor.commit();
-
- TestSharedPreferences anotherSharedPreferences = new TestSharedPreferences(content, FILENAME, 3);
- assertTrue(anotherSharedPreferences.getBoolean("boolean", false));
- assertThat(anotherSharedPreferences.getFloat("float", 666f), equalTo(1.1f));
- assertThat(anotherSharedPreferences.getInt("int", 666), equalTo(2));
- assertThat(anotherSharedPreferences.getLong("long", 666l), equalTo(3l));
- assertThat(anotherSharedPreferences.getString("string", "wacka wa"), equalTo("foobar"));
-
- assertThat(anotherSharedPreferences.getString("deleteMe", "awol"), equalTo("awol"));
- assertThat(anotherSharedPreferences.getString("dontDeleteMe", "oops"), equalTo("baz"));
- }
-
- @Test
- public void apply_shouldStoreValues() throws Exception {
- editor.apply();
-
- TestSharedPreferences anotherSharedPreferences = new TestSharedPreferences(content, FILENAME, 3);
- assertThat(anotherSharedPreferences.getString("string", "wacka wa"), equalTo("foobar"));
- }
-
- @Test
- public void shouldReturnDefaultValues() throws Exception {
- TestSharedPreferences anotherSharedPreferences = new TestSharedPreferences(content, "bazBang", 3);
-
- assertFalse(anotherSharedPreferences.getBoolean("boolean", false));
- assertThat(anotherSharedPreferences.getFloat("float", 666f), equalTo(666f));
- assertThat(anotherSharedPreferences.getInt("int", 666), equalTo(666));
- assertThat(anotherSharedPreferences.getLong("long", 666l), equalTo(666l));
- assertThat(anotherSharedPreferences.getString("string", "wacka wa"), equalTo("wacka wa"));
- }
-
- @Test
- public void shouldStoreRegisteredListeners() {
- TestSharedPreferences anotherSharedPreferences = new TestSharedPreferences(content, "bazBang", 3);
- anotherSharedPreferences.registerOnSharedPreferenceChangeListener(testListener);
- assertTrue(anotherSharedPreferences.hasListener(testListener));
- }
-
- @Test
- public void shouldRemoveRegisteredListenersOnUnresgister() {
- TestSharedPreferences anotherSharedPreferences = new TestSharedPreferences(content, "bazBang", 3);
- anotherSharedPreferences.registerOnSharedPreferenceChangeListener(testListener);
-
- anotherSharedPreferences.unregisterOnSharedPreferenceChangeListener(testListener);
- assertFalse(anotherSharedPreferences.hasListener(testListener));
- }
-
- private SharedPreferences.OnSharedPreferenceChangeListener testListener = new SharedPreferences.OnSharedPreferenceChangeListener() {
- @Override
- public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
- }
- };
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/tester/android/database/SimpleTestCursorTest.java b/v1/src/test/java/com/xtremelabs/robolectric/tester/android/database/SimpleTestCursorTest.java
deleted file mode 100644
index 5d9f1f788..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/tester/android/database/SimpleTestCursorTest.java
+++ /dev/null
@@ -1,69 +0,0 @@
-package com.xtremelabs.robolectric.tester.android.database;
-
-import android.content.ContentResolver;
-import android.net.Uri;
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import com.xtremelabs.robolectric.shadows.ShadowContentResolver;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import java.util.ArrayList;
-
-import static com.xtremelabs.robolectric.Robolectric.shadowOf;
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.junit.Assert.assertThat;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class SimpleTestCursorTest {
- private Uri uri;
- private SimpleTestCursor cursor;
- private ContentResolver contentResolver;
-
- @Before
- public void setup() throws Exception {
- contentResolver = Robolectric.application.getContentResolver();
- ShadowContentResolver shadowContentResolver = shadowOf(contentResolver);
- uri = Uri.parse("http://foo");
- cursor = new SimpleTestCursor();
- shadowContentResolver.setCursor(uri, cursor);
- ArrayList<String> columnNames = new ArrayList<String>();
- columnNames.add("stringColumn");
- columnNames.add("longColumn");
- cursor.setColumnNames(columnNames);
- }
-
- @Test
- public void doingQueryShouldMakeQueryParamsAvailable() throws Exception {
- contentResolver.query(uri, new String[]{"projection"}, "selection", new String[]{"selection"}, "sortOrder");
- assertThat(cursor.uri, equalTo(uri));
- assertThat(cursor.projection[0], equalTo("projection"));
- assertThat(cursor.selection, equalTo("selection"));
- assertThat(cursor.selectionArgs[0], equalTo("selection"));
- assertThat(cursor.sortOrder, equalTo("sortOrder"));
- }
-
- @Test
- public void canGetStringsAndLongs() throws Exception {
- cursor.setResults(new Object[][]{new Object[]{"aString", 1234L}});
- assertThat(cursor.moveToNext(), equalTo(true));
- assertThat(cursor.getString(cursor.getColumnIndex("stringColumn")), equalTo("aString"));
- assertThat(cursor.getLong(cursor.getColumnIndex("longColumn")), equalTo(1234L));
- }
-
- @Test
- public void moveToNextAdvancesToNextRow() throws Exception {
- cursor.setResults(new Object[][] { new Object[] { "aString", 1234L }, new Object[] { "anotherString", 5678L }});
- assertThat(cursor.moveToNext(), equalTo(true));
- assertThat(cursor.moveToNext(), equalTo(true));
- assertThat(cursor.getString(cursor.getColumnIndex("stringColumn")), equalTo("anotherString"));
- assertThat(cursor.getLong(cursor.getColumnIndex("longColumn")), equalTo(5678L));
- }
-
- @Test
- public void closeIsRemembered() throws Exception {
- cursor.close();
- assertThat(cursor.getCloseWasCalled(), equalTo(true));
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/tester/android/view/TestMenuTest.java b/v1/src/test/java/com/xtremelabs/robolectric/tester/android/view/TestMenuTest.java
deleted file mode 100644
index ad24100ca..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/tester/android/view/TestMenuTest.java
+++ /dev/null
@@ -1,65 +0,0 @@
-package com.xtremelabs.robolectric.tester.android.view;
-
-import static org.junit.Assert.assertNotNull;
-import junit.framework.Assert;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import com.xtremelabs.robolectric.shadows.ShadowActivity;
-import com.xtremelabs.robolectric.tester.android.view.TestMenuItem;
-
-import android.app.Activity;
-import android.content.Intent;
-
-
-@RunWith(WithTestDefaultsRunner.class)
-public class TestMenuTest {
-
- @Test
- public void addAndRemoveMenuItems() {
- TestMenu testMenu = new TestMenu(new MyActivity());
- //TestMenuItem testMenuItem = new TestMenuItem(R.id.menu_about);
- testMenu.add(0, 10,0,0);
-
- TestMenuItem testMenuItem = (TestMenuItem) testMenu.findItem(10);
-
- Assert.assertEquals(10, testMenuItem.getItemId());
-
- testMenu.removeItem(10);
-
- testMenuItem = (TestMenuItem) testMenu.findItem(10);
- Assert.assertNull(testMenuItem);
-
- }
-
- @Test
- public void clickWithIntent() {
- MyActivity activity = new MyActivity();
-
- TestMenu testMenu = new TestMenu(activity);
- testMenu.add(0, 10,0,0);
-
- TestMenuItem testMenuItem = (TestMenuItem) testMenu.findItem(10);
- Assert.assertNull(testMenuItem.getIntent());
-
- Intent intent = new Intent(activity, MyActivity.class);
- testMenuItem.setIntent(intent);
- testMenuItem.click();
-
- Assert.assertNotNull(testMenuItem);
-
- ShadowActivity shadowActivity = Robolectric.shadowOf(activity);
- Intent startedIntent = shadowActivity.getNextStartedActivity();
- assertNotNull(startedIntent);
- }
-
- private static class MyActivity extends Activity {
- @Override protected void onDestroy() {
- super.onDestroy();
- }
- }
-
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/tester/android/view/TestWindowTest.java b/v1/src/test/java/com/xtremelabs/robolectric/tester/android/view/TestWindowTest.java
deleted file mode 100644
index b5cec3939..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/tester/android/view/TestWindowTest.java
+++ /dev/null
@@ -1,16 +0,0 @@
-package com.xtremelabs.robolectric.tester.android.view;
-
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Assert;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class TestWindowTest {
-
- @Test
- public void windowManager__shouldNotBeNull() throws Exception {
- TestWindow window = new TestWindow(null);
- Assert.assertNotNull(window.getWindowManager());
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/tester/org/apache/http/FakeHttpLayerTest.java b/v1/src/test/java/com/xtremelabs/robolectric/tester/org/apache/http/FakeHttpLayerTest.java
deleted file mode 100644
index 88534f08f..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/tester/org/apache/http/FakeHttpLayerTest.java
+++ /dev/null
@@ -1,96 +0,0 @@
-package com.xtremelabs.robolectric.tester.org.apache.http;
-
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.apache.http.HttpEntity;
-import org.apache.http.client.methods.HttpGet;
-import org.apache.http.client.methods.HttpPost;
-import org.apache.http.client.methods.HttpPut;
-import org.apache.http.entity.StringEntity;
-import org.apache.http.message.BasicHeader;
-import org.apache.http.util.EntityUtils;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import java.io.IOException;
-
-import static org.hamcrest.core.IsEqual.equalTo;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertThat;
-import static org.junit.Assert.assertTrue;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class FakeHttpLayerTest {
-
- private FakeHttpLayer.RequestMatcherBuilder requestMatcherBuilder;
-
- @Before
- public void setUp() throws Exception {
- requestMatcherBuilder = new FakeHttpLayer.RequestMatcherBuilder();
- }
-
- @Test
- public void requestMatcherBuilder_shouldAddHost() throws Exception {
- requestMatcherBuilder.host("example.com");
- assertThat("example.com", equalTo(requestMatcherBuilder.getHostname()));
- }
-
- @Test
- public void requestMatcherBuilder_shouldAddMethod() throws Exception {
- requestMatcherBuilder.method("POST");
- assertThat("POST", equalTo(requestMatcherBuilder.getMethod()));
- }
-
- @Test
- public void requestMatcherBuilder_shouldAddPath() throws Exception {
- requestMatcherBuilder.path("foo/bar");
- assertThat("/foo/bar", equalTo(requestMatcherBuilder.getPath()));
- }
-
- @Test
- public void requestMatcherBuilder_shouldAddParams() throws Exception {
- requestMatcherBuilder.param("param1", "param one");
- assertThat("param one", equalTo(requestMatcherBuilder.getParam("param1")));
- }
-
- @Test
- public void requestMatcherBuilder_shouldAddHeaders() throws Exception {
- requestMatcherBuilder.header("header1", "header one");
- assertThat("header one", equalTo(requestMatcherBuilder.getHeader("header1")));
- }
-
- @Test
- public void matches__shouldMatchHeaders() throws Exception {
- requestMatcherBuilder.header("header1", "header one");
- HttpGet match = new HttpGet("example.com");
- HttpGet noMatch = new HttpGet("example.com");
- match.setHeader(new BasicHeader("header1", "header one"));
- noMatch.setHeader(new BasicHeader("header1", "header not a match"));
-
- assertFalse(requestMatcherBuilder.matches(new HttpGet("example.com")));
- assertFalse(requestMatcherBuilder.matches(noMatch));
- assertTrue(requestMatcherBuilder.matches(match));
- }
-
- @Test
- public void matches__shouldMatchPostBody() throws Exception {
- final String expectedText = "some post body text";
-
- requestMatcherBuilder.postBody(new FakeHttpLayer.RequestMatcherBuilder.PostBodyMatcher() {
- @Override
- public boolean matches(HttpEntity actualPostBody) throws IOException {
- return EntityUtils.toString(actualPostBody).equals(expectedText);
- }
- });
-
- HttpPut match = new HttpPut("example.com");
- match.setEntity(new StringEntity(expectedText));
-
- HttpPost noMatch = new HttpPost("example.com");
- noMatch.setEntity(new StringEntity("some text that does not match"));
-
- assertFalse(requestMatcherBuilder.matches(new HttpGet("example.com")));
- assertFalse(requestMatcherBuilder.matches(noMatch));
- assertTrue(requestMatcherBuilder.matches(match));
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/tester/org/apache/http/ParamsParserTest.java b/v1/src/test/java/com/xtremelabs/robolectric/tester/org/apache/http/ParamsParserTest.java
deleted file mode 100644
index 4b57d1547..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/tester/org/apache/http/ParamsParserTest.java
+++ /dev/null
@@ -1,35 +0,0 @@
-package com.xtremelabs.robolectric.tester.org.apache.http;
-
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.apache.http.client.methods.HttpGet;
-import org.apache.http.client.methods.HttpPost;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import java.util.Map;
-
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.MatcherAssert.assertThat;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class ParamsParserTest {
- @Test
- public void parseParams_shouldParsePostEntitiesIntoParams() throws Exception {
- HttpPost post = new HttpPost("example.com");
- TestHttpResponse response = new TestHttpResponse();
- response.setResponseBody("param1=foobar");
-
- post.setEntity(response.getEntity());
- Map<String,String> params = ParamsParser.parseParams(post);
-
- assertThat("foobar", equalTo(params.get("param1")));
- }
-
- @Test
- public void parseParams_shouldNotParseNonPostEntitiesIntoParams() throws Exception {
- HttpGet httpGet = new HttpGet("example.com");
- TestHttpResponse response = new TestHttpResponse();
- response.setResponseBody("param1=foobar");
- assertThat(ParamsParser.parseParams(httpGet).size(), equalTo(0));
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/tester/org/apache/http/TestHttpResponseTest.java b/v1/src/test/java/com/xtremelabs/robolectric/tester/org/apache/http/TestHttpResponseTest.java
deleted file mode 100644
index 0a37a9afd..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/tester/org/apache/http/TestHttpResponseTest.java
+++ /dev/null
@@ -1,129 +0,0 @@
-package com.xtremelabs.robolectric.tester.org.apache.http;
-
-import org.apache.http.Header;
-import org.apache.http.HeaderIterator;
-import org.apache.http.HttpResponse;
-import org.apache.http.message.BasicHeader;
-import org.hamcrest.CoreMatchers;
-import org.junit.Test;
-
-import static org.hamcrest.CoreMatchers.nullValue;
-import static org.hamcrest.core.Is.is;
-import static org.hamcrest.core.IsEqual.equalTo;
-import static org.junit.Assert.assertThat;
-
-public class TestHttpResponseTest {
-
- @Test
- public void shouldSupportGetFirstHeader() throws Exception {
- HttpResponse resp =
- new TestHttpResponse(304, "REDIRECTED",
- new BasicHeader("Location", "http://bar.com"));
-
- assertThat(resp.getFirstHeader("None"), nullValue());
- assertThat(new TestHttpResponse(200, "OK").getFirstHeader("Foo"), nullValue());
-
- for (String l : new String[] { "location", "Location" }) {
- assertThat(resp.getFirstHeader(l).getValue(), equalTo("http://bar.com"));
- }
- }
-
- @Test
- public void shouldSupportGetLastHeader() throws Exception {
- HttpResponse resp =
- new TestHttpResponse(304, "REDIRECTED",
- new BasicHeader("Location", "http://bar.com"),
- new BasicHeader("Location", "http://zombo.com"));
-
- assertThat(resp.getLastHeader("None"), nullValue());
-
- for (String l : new String[] { "location", "Location" }) {
- assertThat(resp.getLastHeader(l).getValue(), equalTo("http://zombo.com"));
- }
- }
-
- @Test
- public void shouldSupportContainsHeader() throws Exception {
- HttpResponse resp =
- new TestHttpResponse(304, "ZOMBO",
- new BasicHeader("X-Zombo-Com", "Welcome"));
-
- assertThat(resp.containsHeader("X-Zombo-Com"), is(true));
- assertThat(resp.containsHeader("Location"), is(false));
- }
-
- @Test
- public void shouldSupportHeaderIterator() throws Exception {
- HttpResponse resp =
- new TestHttpResponse(304, "REDIRECTED",
- new BasicHeader("Location", "http://bar.com"),
- new BasicHeader("Location", "http://zombo.com"));
-
- HeaderIterator it = resp.headerIterator();
-
- assertThat(it.hasNext(), is(true));
- assertThat(it.nextHeader().getValue(), equalTo("http://bar.com"));
- assertThat(it.nextHeader().getValue(), equalTo("http://zombo.com"));
- assertThat(it.hasNext(), is(false));
- }
-
- @Test
- public void shouldSupportHeaderIteratorWithArg() throws Exception {
- HttpResponse resp =
- new TestHttpResponse(304, "REDIRECTED",
- new BasicHeader("Location", "http://bar.com"),
- new BasicHeader("X-Zombo-Com", "http://zombo.com"),
- new BasicHeader("Location", "http://foo.com"));
-
- HeaderIterator it = resp.headerIterator("Location");
-
- assertThat(it.hasNext(), is(true));
- assertThat(it.nextHeader().getValue(), equalTo("http://bar.com"));
- assertThat(it.hasNext(), is(true));
- assertThat(it.nextHeader().getValue(), equalTo("http://foo.com"));
- assertThat(it.hasNext(), is(false));
- }
-
-
- @Test
- public void shouldSupportGetHeadersWithArg() throws Exception {
- HttpResponse resp =
- new TestHttpResponse(304, "REDIRECTED",
- new BasicHeader("Location", "http://bar.com"),
- new BasicHeader("X-Zombo-Com", "http://zombo.com"),
- new BasicHeader("Location", "http://foo.com"));
-
-
- Header[] headers = resp.getHeaders("Location");
- assertThat(headers.length, is(2));
- assertThat(headers[0].getValue(), CoreMatchers.equalTo("http://bar.com"));
- assertThat(headers[1].getValue(), CoreMatchers.equalTo("http://foo.com"));
- }
-
- @Test
- public void canAddNewBasicHeader() {
- TestHttpResponse response = new TestHttpResponse(200, "abc");
- assertThat(response.getAllHeaders().length, is(0));
- response.addHeader(new BasicHeader("foo", "bar"));
- assertThat(response.getAllHeaders().length, is(1));
- assertThat(response.getHeaders("foo")[0].getValue(), CoreMatchers.equalTo("bar"));
- }
-
- @Test
- public void canOverrideExistingHeaderValue() {
- TestHttpResponse response = new TestHttpResponse(200, "abc", new BasicHeader("foo", "bar"));
- response.setHeader(new BasicHeader("foo", "bletch"));
- assertThat(response.getAllHeaders().length, is(1));
- assertThat(response.getHeaders("foo")[0].getValue(), CoreMatchers.equalTo("bletch"));
- }
-
- @Test
- public void onlyOverridesFirstHeaderValue() {
- TestHttpResponse response = new TestHttpResponse(200, "abc", new BasicHeader("foo", "bar"), new BasicHeader("foo", "baz"));
- response.setHeader(new BasicHeader("foo", "bletch"));
- assertThat(response.getAllHeaders().length, is(2));
- assertThat(response.getHeaders("foo")[0].getValue(), CoreMatchers.equalTo("bletch"));
- assertThat(response.getHeaders("foo")[1].getValue(), CoreMatchers.equalTo("baz"));
- }
-
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/util/CustomView.java b/v1/src/test/java/com/xtremelabs/robolectric/util/CustomView.java
deleted file mode 100644
index 8bfd20b32..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/util/CustomView.java
+++ /dev/null
@@ -1,16 +0,0 @@
-package com.xtremelabs.robolectric.util;
-
-import android.content.Context;
-import android.util.AttributeSet;
-import android.widget.LinearLayout;
-import com.xtremelabs.robolectric.R;
-
-public class CustomView extends LinearLayout {
- public int attributeResourceValue;
-
- public CustomView(Context context, AttributeSet attrs) {
- super(context, attrs);
- inflate(context, R.layout.inner_merge, this);
- attributeResourceValue = attrs.getAttributeResourceValue("some namespace", "message", -1);
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/util/CustomView2.java b/v1/src/test/java/com/xtremelabs/robolectric/util/CustomView2.java
deleted file mode 100644
index 4f0dedf01..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/util/CustomView2.java
+++ /dev/null
@@ -1,17 +0,0 @@
-package com.xtremelabs.robolectric.util;
-
-import android.content.Context;
-import android.util.AttributeSet;
-import android.widget.LinearLayout;
-
-public class CustomView2 extends LinearLayout {
- public int childCountAfterInflate;
-
- public CustomView2(Context context, AttributeSet attrs) {
- super(context, attrs);
- }
-
- @Override protected void onFinishInflate() {
- childCountAfterInflate = getChildCount();
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/util/DatabaseConfigTest.java b/v1/src/test/java/com/xtremelabs/robolectric/util/DatabaseConfigTest.java
deleted file mode 100644
index 78c599230..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/util/DatabaseConfigTest.java
+++ /dev/null
@@ -1,90 +0,0 @@
-package com.xtremelabs.robolectric.util;
-
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import com.xtremelabs.robolectric.util.DatabaseConfig.DatabaseMap;
-import com.xtremelabs.robolectric.util.DatabaseConfig.NullDatabaseMapException;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import java.sql.ResultSet;
-
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.junit.Assert.assertThat;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class DatabaseConfigTest {
-
- @Before
- public void setup() {
- DatabaseConfig.setDatabaseMap(new H2Map());
- }
-
- @Test
- public void testSettingDatabaseMapLoadsCorrectly() throws Exception {
- assertThat(DatabaseConfig.getDatabaseMap().getClass().getName(), equalTo(H2Map.class.getName()));
- assertThat(DatabaseConfig.isMapLoaded(), equalTo(false));
- DatabaseConfig.getMemoryConnection(); //load map
- assertThat(DatabaseConfig.isMapLoaded(), equalTo(true));
- assertThat(DatabaseConfig.getResultSetType(), equalTo(ResultSet.TYPE_SCROLL_INSENSITIVE));
-
- H2Map_TypeForwardOnly ForwardOnlyMap = new H2Map_TypeForwardOnly();
- DatabaseConfig.setDatabaseMap(ForwardOnlyMap);
- assertThat(DatabaseConfig.isMapLoaded(), equalTo(false));
- assertThat(DatabaseConfig.getDatabaseMap(), equalTo((DatabaseMap) ForwardOnlyMap));
- DatabaseConfig.getMemoryConnection(); //load map
- assertThat(DatabaseConfig.isMapLoaded(), equalTo(true));
- assertThat(DatabaseConfig.getDatabaseMap().getClass().getName(), equalTo(H2Map_TypeForwardOnly.class.getName()));
- assertThat(DatabaseConfig.getResultSetType(), equalTo(ResultSet.TYPE_FORWARD_ONLY));
- }
-
- @Test
- public void testMapIsNotNull() throws Exception {
- assertThat(DatabaseConfig.isMapNull(), equalTo(false));
- }
-
- private void setDatabaseMapNull() {
- DatabaseConfig.setDatabaseMap(null);
- assertThat(DatabaseConfig.isMapNull(), equalTo(true));
- assertThat(DatabaseConfig.isMapLoaded(), equalTo(false));
- }
-
- @Test(expected = NullDatabaseMapException.class)
- public void testLoadingNullMapThrowsException() throws Exception {
- setDatabaseMapNull();
- DatabaseConfig.getMemoryConnection(); //attempt to load driver for map and throw exception
- }
-
- @Test(expected = NullDatabaseMapException.class)
- public void testGetScrubSQLThrowsExceptionWithNullMap() throws Exception {
- setDatabaseMapNull();
- DatabaseConfig.getScrubSQL("");
- }
-
- @Test(expected = NullDatabaseMapException.class)
- public void testGetSelectLastInsertIdentityThrowsExceptionWithNullMap() throws Exception {
- setDatabaseMapNull();
- DatabaseConfig.getSelectLastInsertIdentity();
- }
-
- @Test(expected = NullDatabaseMapException.class)
- public void testGetResultSetTypeThrowsExceptionWithNullMap() throws Exception {
- setDatabaseMapNull();
- DatabaseConfig.getResultSetType();
- }
-
- @Test
- public void testGetScrubSQL() throws Exception {
- assertThat(DatabaseConfig.getScrubSQL("autoincrement"), equalTo(DatabaseConfig.getDatabaseMap().getScrubSQL("autoincrement")));
- }
-
- @Test
- public void testGetSelectLastInsertIdentity() throws Exception {
- assertThat(DatabaseConfig.getSelectLastInsertIdentity(), equalTo(DatabaseConfig.getDatabaseMap().getSelectLastInsertIdentity()));
- }
-
- @Test
- public void testGetResultSetType() throws Exception {
- assertThat(DatabaseConfig.getResultSetType(), equalTo(DatabaseConfig.getDatabaseMap().getResultSetType()));
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/util/H2MapTest.java b/v1/src/test/java/com/xtremelabs/robolectric/util/H2MapTest.java
deleted file mode 100644
index 3e7dd16f7..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/util/H2MapTest.java
+++ /dev/null
@@ -1,78 +0,0 @@
-package com.xtremelabs.robolectric.util;
-
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import java.sql.ResultSet;
-import java.sql.SQLException;
-
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.junit.Assert.assertThat;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class H2MapTest {
-
- H2Map map;
-
- @Before
- public void setUp() throws Exception {
- map = new H2Map();
- }
-
- @Test
- public void testDriverClassName() {
- assertThat(map.getDriverClassName(), equalTo("org.h2.Driver"));
- }
-
- @Test
- public void testConnectionString() {
- assertThat(map.getConnectionString(), equalTo("jdbc:h2:mem:"));
- }
-
- @Test
- public void testScrubSQLReplacesAutoIncrement() throws SQLException {
- assertThat(map.getScrubSQL("autoincrement"), equalTo("auto_increment"));
- }
-
- @Test
- public void testScrubSQLReplacesIntegerWithBigInt() throws SQLException {
- assertThat(map.getScrubSQL("integer"), equalTo("bigint(19)"));
- }
-
- @Test
- public void testScrubSQLAcceptsIntegerPrimaryKey() throws SQLException {
- map.getScrubSQL("INTEGER PRIMARY KEY AUTOINCREMENT");
- }
-
- @Test(expected = SQLException.class)
- public void testScrubSQLRejectsIntPrimaryKeyThrowsException() throws SQLException {
- map.getScrubSQL("INT PRIMARY KEY AUTOINCREMENT");
- }
-
- @Test(expected = SQLException.class)
- public void testScrubSQLRejectsCharPrimaryKeyThrowsException2() throws SQLException {
- map.getScrubSQL("CHAR PRIMARY KEY AUTOINCREMENT");
- }
-
- @Test
- public void testGetSelectLastInsertIdentity() throws SQLException {
- assertThat(map.getSelectLastInsertIdentity(), equalTo("SELECT IDENTITY();"));
- }
-
- @Test
- public void testGetH2ResultSetIs_TYPE_SCROLL_INSENSITIVE() throws SQLException {
- assertThat(map.getResultSetType(), equalTo(ResultSet.TYPE_SCROLL_INSENSITIVE));
- }
-
- @Test
- public void scrubSQL_shouldRemoveConflictAlgorithms() throws Exception {
- assertThat(map.getScrubSQL("INSERT INTO "), equalTo("INSERT INTO "));
- assertThat(map.getScrubSQL("INSERT OR ROLLBACK INTO "), equalTo("INSERT INTO "));
- assertThat(map.getScrubSQL("INSERT OR ABORT INTO "), equalTo("INSERT INTO "));
- assertThat(map.getScrubSQL("INSERT OR FAIL INTO "), equalTo("INSERT INTO "));
- assertThat(map.getScrubSQL("INSERT OR IGNORE INTO "), equalTo("INSERT INTO "));
- assertThat(map.getScrubSQL("INSERT OR REPLACE INTO "), equalTo("INSERT INTO "));
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/util/H2Map_TypeForwardOnlyTest.java b/v1/src/test/java/com/xtremelabs/robolectric/util/H2Map_TypeForwardOnlyTest.java
deleted file mode 100644
index 673112c37..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/util/H2Map_TypeForwardOnlyTest.java
+++ /dev/null
@@ -1,30 +0,0 @@
-package com.xtremelabs.robolectric.util;
-
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.junit.Assert.assertThat;
-
-import java.sql.ResultSet;
-import java.sql.SQLException;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class H2Map_TypeForwardOnlyTest {
-
- H2Map_TypeForwardOnly map;
- @Before
- public void setUp() throws Exception {
- map = new H2Map_TypeForwardOnly();
- }
-
-
-
- @Test
- public void testGetH2ResultSetIs_TYPE_FORWARD_ONLY() throws SQLException {
- assertThat(map.getResultSetType(),equalTo(ResultSet.TYPE_FORWARD_ONLY));
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/util/H2Test.java b/v1/src/test/java/com/xtremelabs/robolectric/util/H2Test.java
deleted file mode 100644
index 6abac3b87..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/util/H2Test.java
+++ /dev/null
@@ -1,39 +0,0 @@
-package com.xtremelabs.robolectric.util;
-
-import android.content.ContentValues;
-import android.database.sqlite.SQLiteDatabase;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import java.sql.SQLException;
-
-import static com.xtremelabs.robolectric.util.SQLite.buildInsertString;
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.junit.Assert.assertThat;
-
-@DatabaseConfig.UsingDatabaseMap(H2Map.class)
-@RunWith(WithTestDefaultsRunner.class)
-public class H2Test {
- ContentValues values;
- @Before
-
- public void setUp() throws Exception {
- String byteString = "byte_string";
- byte[] byteData = byteString.getBytes();
-
- values = new ContentValues();
- values.put("name", "Chuck");
- values.put("int_value", 33);
- values.put("float_value", (float) 1.5);
- values.put("byte_data", byteData);
- }
-
- @Test
- public void testBuildInsertString() throws SQLException {
- SQLite.SQLStringAndBindings insertString = buildInsertString("table_name", values, SQLiteDatabase.CONFLICT_REPLACE);
- assertThat(insertString.sql, equalTo("INSERT INTO table_name (float_value, byte_data, name, int_value) VALUES (?, ?, ?, ?);"));
- SQLiteTestHelper.verifyColumnValues(insertString.columnValues);
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/util/NullDatabaseMap.java b/v1/src/test/java/com/xtremelabs/robolectric/util/NullDatabaseMap.java
deleted file mode 100644
index d80fb481f..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/util/NullDatabaseMap.java
+++ /dev/null
@@ -1,34 +0,0 @@
-package com.xtremelabs.robolectric.util;
-
-import com.xtremelabs.robolectric.util.DatabaseConfig.DatabaseMap;
-
-import java.sql.ResultSet;
-import java.sql.SQLException;
-
-public class NullDatabaseMap implements DatabaseMap {
-
- @Override
- public String getDriverClassName() {
- return "com.xtremelabs.robolectric.util.NullDatabaseMap";
- }
-
- @Override
- public String getConnectionString() {
- return null;
- }
-
- @Override
- public String getScrubSQL(String sql) throws SQLException {
- return null;
- }
-
- @Override
- public String getSelectLastInsertIdentity() {
- return null;
- }
-
- @Override
- public int getResultSetType() {
- return ResultSet.TYPE_FORWARD_ONLY;
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/util/NullDatabaseMapTest.java b/v1/src/test/java/com/xtremelabs/robolectric/util/NullDatabaseMapTest.java
deleted file mode 100644
index 14fc326f6..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/util/NullDatabaseMapTest.java
+++ /dev/null
@@ -1,62 +0,0 @@
-package com.xtremelabs.robolectric.util;
-
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import com.xtremelabs.robolectric.util.DatabaseConfig.CannotLoadDatabaseMapDriverException;
-import com.xtremelabs.robolectric.util.DatabaseConfig.UsingDatabaseMap;
-import org.junit.Assert;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import java.sql.Connection;
-
-/**
- * the @UsingDatabaseMap integration test
- * @author cvanvranken
- *
- */
-@UsingDatabaseMap(NullDatabaseMap.class)
-@RunWith(WithTestDefaultsRunner.class)
-public class NullDatabaseMapTest {
-
- @Test
- public void CanChangeDatabaseMapUsingAnnotation() {
- Assert.assertTrue(DatabaseConfig.getDatabaseMap().getClass().getName()
- .equals(NullDatabaseMap.class.getName()));
- Assert.assertTrue(DatabaseConfig.getDatabaseMap().getConnectionString() == null);
- Assert.assertTrue(DatabaseConfig.getDatabaseMap()
- .getSelectLastInsertIdentity() == null);
- Assert.assertTrue(DatabaseConfig.getDatabaseMap().getDriverClassName() == "com.xtremelabs.robolectric.util.NullDatabaseMap");
- }
-
- @Test
- public void MapIsSetButIsNotLoaded() {
- Assert.assertTrue(DatabaseConfig.getDatabaseMap().getClass().getName()
- .equals(NullDatabaseMap.class.getName()));
- // check that the map has been set but not loaded.
- Assert.assertFalse(DatabaseConfig.isMapLoaded());
- }
-
- @Test
- public void MapLoadsButConnectionFails() {
- Assert.assertFalse(DatabaseConfig.isMapLoaded());
- Connection connection = null;
-
- boolean expectedError = false;
-
- try {
- connection = DatabaseConfig.getMemoryConnection();
- // we should never reach this,
- //since the connection should not actually be made
- Assert.assertTrue(false);
- } catch (CannotLoadDatabaseMapDriverException e) {
- //This error is expected.
- expectedError = true;
- }
- Assert.assertTrue(expectedError);
- Assert.assertTrue(connection == null);
- // driver should have loaded because the class name was valid,
- // even if the memoryConnectionString was invalid
- Assert.assertTrue(DatabaseConfig.isMapLoaded());
-
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/util/PropertiesHelperTest.java b/v1/src/test/java/com/xtremelabs/robolectric/util/PropertiesHelperTest.java
deleted file mode 100644
index f87055dbb..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/util/PropertiesHelperTest.java
+++ /dev/null
@@ -1,27 +0,0 @@
-package com.xtremelabs.robolectric.util;
-
-import org.junit.Test;
-
-import java.util.Properties;
-
-import static org.junit.Assert.assertEquals;
-
-public class PropertiesHelperTest {
- @Test
- public void shouldDoVariableSubstitutionUsingSystemProperties() throws Exception {
- System.setProperty("blinfiddle.ox.heart", "orange juice");
- System.setProperty("ornithopter.defenestration", "nickel");
-
- assertEquals(PropertiesHelper.doSingleSubstitution("presenting: ${blinfiddle.ox.heart} -- ${ornithopter.defenestration}.", null), "presenting: orange juice -- nickel.");
- }
-
- @Test
- public void shouldDoVariableSubstitutionOnProperties() throws Exception {
- Properties properties = new Properties();
- properties.setProperty("result", "{${first.value} + ${system.value.xbf5547}}");
- System.setProperty("system.value.xbf5547", "system");
- properties.setProperty("first.value", "first");
- PropertiesHelper.doSubstitutions(properties);
- assertEquals("{first + system}", properties.getProperty("result"));
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/util/RobolectricBackgroundExecutorServiceTest.java b/v1/src/test/java/com/xtremelabs/robolectric/util/RobolectricBackgroundExecutorServiceTest.java
deleted file mode 100644
index 2225406f2..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/util/RobolectricBackgroundExecutorServiceTest.java
+++ /dev/null
@@ -1,77 +0,0 @@
-package com.xtremelabs.robolectric.util;
-
-import com.xtremelabs.robolectric.Robolectric;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import java.util.concurrent.Callable;
-import java.util.concurrent.Future;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class RobolectricBackgroundExecutorServiceTest {
- private Transcript transcript;
- private RobolectricBackgroundExecutorService executorService;
- private Runnable runnable;
-
- @Before public void setUp() throws Exception {
- transcript = new Transcript();
- executorService = new RobolectricBackgroundExecutorService();
-
- Robolectric.getBackgroundScheduler().pause();
-
- runnable = new Runnable() {
- @Override public void run() {
- transcript.add("background event ran");
- }
- };
- }
-
- @Test
- public void execute_shouldRunStuffOnBackgroundThread() throws Exception {
- executorService.execute(runnable);
-
- transcript.assertNoEventsSoFar();
-
- Robolectric.runBackgroundTasks();
- transcript.assertEventsSoFar("background event ran");
- }
-
- @Test
- public void submitRunnable_shouldRunStuffOnBackgroundThread() throws Exception {
- Future<String> future = executorService.submit(runnable, "foo");
-
- transcript.assertNoEventsSoFar();
- assertFalse(future.isDone());
-
- Robolectric.runBackgroundTasks();
- transcript.assertEventsSoFar("background event ran");
- assertTrue(future.isDone());
-
- assertEquals("foo", future.get());
- }
-
- @Test
- public void submitCallable_shouldRunStuffOnBackgroundThread() throws Exception {
- Future<String> future = executorService.submit(new Callable<String>() {
- @Override public String call() throws Exception {
- runnable.run();
- return "foo";
- }
- });
-
- transcript.assertNoEventsSoFar();
- assertFalse(future.isDone());
-
- Robolectric.runBackgroundTasks();
- transcript.assertEventsSoFar("background event ran");
- assertTrue(future.isDone());
-
- assertEquals("foo", future.get());
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/util/SQLiteTestHelper.java b/v1/src/test/java/com/xtremelabs/robolectric/util/SQLiteTestHelper.java
deleted file mode 100644
index 2734fef42..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/util/SQLiteTestHelper.java
+++ /dev/null
@@ -1,17 +0,0 @@
-package com.xtremelabs.robolectric.util;
-
-import java.util.List;
-
-import static org.hamcrest.CoreMatchers.instanceOf;
-import static org.junit.Assert.assertThat;
-
-public class SQLiteTestHelper {
-
- static void verifyColumnValues(List<Object> colValues) {
- assertThat(colValues.get(0), instanceOf(Float.class));
- assertThat(colValues.get(1), instanceOf(byte[].class));
- assertThat(colValues.get(2), instanceOf(String.class));
- assertThat(colValues.get(3), instanceOf(Integer.class));
- }
-
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/util/SQLite_Test.java b/v1/src/test/java/com/xtremelabs/robolectric/util/SQLite_Test.java
deleted file mode 100644
index b692cbebf..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/util/SQLite_Test.java
+++ /dev/null
@@ -1,70 +0,0 @@
-package com.xtremelabs.robolectric.util;
-
-import android.content.ContentValues;
-import android.database.sqlite.SQLiteDatabase;
-import com.xtremelabs.robolectric.WithTestDefaultsRunner;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static com.xtremelabs.robolectric.util.SQLite.*;
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.junit.Assert.assertThat;
-
-@RunWith(WithTestDefaultsRunner.class)
-public class SQLite_Test {
- ContentValues values;
- @Before
- public void setUp() throws Exception {
- String byteString = "byte_string";
- byte[] byteData = byteString.getBytes();
-
- values = new ContentValues();
- values.put("name", "Chuck");
- values.put("int_value", 33);
- values.put("float_value", (float) 1.5);
- values.put("byte_data", byteData);
- }
-
- @Test
- public void testBuildInsertString() throws Exception {
- SQLite.SQLStringAndBindings insertString = buildInsertString("table_name", values, SQLiteDatabase.CONFLICT_NONE);
- assertThat(insertString.sql, equalTo("INSERT INTO table_name (float_value, byte_data, name, int_value) VALUES (?, ?, ?, ?);"));
- SQLiteTestHelper.verifyColumnValues(insertString.columnValues);
- }
-
- @Test
- public void testBuildUpdateString() {
- SQLite.SQLStringAndBindings insertString = buildUpdateString("table_name", values, "id=?", new String[]{"1234"});
- assertThat(insertString.sql, equalTo("UPDATE table_name SET float_value=?, byte_data=?, name=?, int_value=? WHERE id='1234';"));
- SQLiteTestHelper.verifyColumnValues(insertString.columnValues);
- }
-
- @Test
- public void testBuildDeleteString() {
- String deleteString = buildDeleteString("table_name", "id=?", new String[]{"1234"});
- assertThat(deleteString, equalTo("DELETE FROM table_name WHERE id='1234';"));
- }
-
- @Test
- public void testBuildWhereClause() {
- String whereClause = buildWhereClause("id=? AND name=? AND int_value=?", new String[]{"1234", "Chuck", "33"});
- assertThat(whereClause, equalTo("id='1234' AND name='Chuck' AND int_value='33'"));
- }
-
- @Test
- public void testBuildColumnValuesClause() {
- SQLStringAndBindings columnValuesClause = buildColumnValuesClause(values);
-
- assertThat(columnValuesClause.sql, equalTo("(float_value, byte_data, name, int_value) VALUES (?, ?, ?, ?)"));
- SQLiteTestHelper.verifyColumnValues(columnValuesClause.columnValues);
- }
-
- @Test
- public void testBuildColumnAssignmentsClause() {
- SQLStringAndBindings columnAssignmentsClause = buildColumnAssignmentsClause(values);
-
- assertThat(columnAssignmentsClause.sql, equalTo("float_value=?, byte_data=?, name=?, int_value=?"));
- SQLiteTestHelper.verifyColumnValues(columnAssignmentsClause.columnValues);
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/util/SchedulerTest.java b/v1/src/test/java/com/xtremelabs/robolectric/util/SchedulerTest.java
deleted file mode 100644
index cadf246e8..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/util/SchedulerTest.java
+++ /dev/null
@@ -1,164 +0,0 @@
-package com.xtremelabs.robolectric.util;
-
-import org.junit.Before;
-import org.junit.Test;
-
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.junit.Assert.assertThat;
-
-public class SchedulerTest {
- private Transcript transcript;
- private Scheduler scheduler;
-
- @Before
- public void setUp() throws Exception {
- scheduler = new Scheduler();
- scheduler.pause();
- transcript = new Transcript();
- }
-
- @Test
- public void testTick_ReturnsTrueIffSomeJobWasRun() throws Exception {
- scheduler.postDelayed(new AddToTranscript("one"), 0);
- scheduler.postDelayed(new AddToTranscript("two"), 0);
- scheduler.postDelayed(new AddToTranscript("three"), 1000);
-
- assertThat(scheduler.advanceBy(0), equalTo(true));
- transcript.assertEventsSoFar("one", "two");
-
- assertThat(scheduler.advanceBy(0), equalTo(false));
- transcript.assertNoEventsSoFar();
-
- assertThat(scheduler.advanceBy(1000), equalTo(true));
- transcript.assertEventsSoFar("three");
- }
-
- @Test
- public void testShadowPostDelayed() throws Exception {
- scheduler.postDelayed(new AddToTranscript("one"), 1000);
- scheduler.postDelayed(new AddToTranscript("two"), 2000);
- scheduler.postDelayed(new AddToTranscript("three"), 3000);
-
- scheduler.advanceBy(1000);
- transcript.assertEventsSoFar("one");
-
- scheduler.advanceBy(500);
- transcript.assertNoEventsSoFar();
-
- scheduler.advanceBy(501);
- transcript.assertEventsSoFar("two");
-
- scheduler.advanceBy(999);
- transcript.assertEventsSoFar("three");
- }
-
- @Test
- public void testShadowPostAtFrontOfQueue() throws Exception {
- scheduler.post(new AddToTranscript("one"));
- scheduler.post(new AddToTranscript("two"));
- scheduler.postAtFrontOfQueue(new AddToTranscript("three"));
-
- scheduler.runOneTask();
- transcript.assertEventsSoFar("three");
-
- scheduler.runOneTask();
- transcript.assertEventsSoFar("one");
-
- scheduler.runOneTask();
- transcript.assertEventsSoFar("two");
- }
-
- @Test
- public void testShadowPostAtFrontOfQueue_whenUnpaused() throws Exception {
- scheduler.unPause();
- scheduler.postAtFrontOfQueue(new AddToTranscript("three"));
- transcript.assertEventsSoFar("three");
- }
-
- @Test
- public void testShadowPostDelayed_WhenMoreItemsAreAdded() throws Exception {
- scheduler.postDelayed(new Runnable() {
- @Override
- public void run() {
- transcript.add("one");
- scheduler.postDelayed(new Runnable() {
- @Override
- public void run() {
- transcript.add("two");
- scheduler.postDelayed(new AddToTranscript("three"), 1000);
- }
- }, 1000);
- }
- }, 1000);
-
- scheduler.advanceBy(1000);
- transcript.assertEventsSoFar("one");
-
- scheduler.advanceBy(500);
- transcript.assertNoEventsSoFar();
-
- scheduler.advanceBy(501);
- transcript.assertEventsSoFar("two");
-
- scheduler.advanceBy(999);
- transcript.assertEventsSoFar("three");
- }
-
- @Test
- public void removeShouldRemoveAllInstancesOfRunnableFromQueue() throws Exception {
- scheduler.post(new TestRunnable());
- TestRunnable runnable = new TestRunnable();
- scheduler.post(runnable);
- scheduler.post(runnable);
- assertThat(scheduler.enqueuedTaskCount(), equalTo(3));
- scheduler.remove(runnable);
- assertThat(scheduler.enqueuedTaskCount(), equalTo(1));
- scheduler.advanceToLastPostedRunnable();
- assertThat(runnable.wasRun, equalTo(false));
- }
-
- @Test
- public void resetShouldUnPause() throws Exception {
- scheduler.pause();
-
- TestRunnable runnable = new TestRunnable();
- scheduler.post(runnable);
-
- assertThat(runnable.wasRun, equalTo(false));
-
- scheduler.reset();
- scheduler.post(runnable);
- assertThat(runnable.wasRun, equalTo(true));
- }
-
- @Test
- public void resetShouldClearPendingRunnables() throws Exception {
- scheduler.pause();
-
- TestRunnable runnable1 = new TestRunnable();
- scheduler.post(runnable1);
-
- assertThat(runnable1.wasRun, equalTo(false));
-
- scheduler.reset();
-
- TestRunnable runnable2 = new TestRunnable();
- scheduler.post(runnable2);
-
- assertThat(runnable1.wasRun, equalTo(false));
- assertThat(runnable2.wasRun, equalTo(true));
- }
-
- private class AddToTranscript implements Runnable {
- private String event;
-
- public AddToTranscript(String event) {
- this.event = event;
- }
-
- @Override
- public void run() {
- transcript.add(event);
- }
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/util/StringsTest.java b/v1/src/test/java/com/xtremelabs/robolectric/util/StringsTest.java
deleted file mode 100644
index 3aece8288..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/util/StringsTest.java
+++ /dev/null
@@ -1,16 +0,0 @@
-package com.xtremelabs.robolectric.util;
-
-import org.junit.Test;
-
-import java.io.ByteArrayInputStream;
-import java.io.InputStream;
-
-import static junit.framework.Assert.assertEquals;
-
-public class StringsTest {
- @Test
- public void shouldGetStringFromStream() throws Exception {
- InputStream stream = new ByteArrayInputStream("some random string".getBytes());
- assertEquals("some random string", Strings.fromStream(stream));
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/util/TestAnimationListener.java b/v1/src/test/java/com/xtremelabs/robolectric/util/TestAnimationListener.java
deleted file mode 100644
index 692a75a45..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/util/TestAnimationListener.java
+++ /dev/null
@@ -1,26 +0,0 @@
-package com.xtremelabs.robolectric.util;
-
-import android.view.animation.Animation;
-import android.view.animation.Animation.AnimationListener;
-
-public class TestAnimationListener implements AnimationListener {
-
- public boolean wasStartCalled = false;
- public boolean wasEndCalled = false;
- public boolean wasRepeatCalled = false;
-
- @Override
- public void onAnimationStart(Animation animation) {
- wasStartCalled = true;
- }
-
- @Override
- public void onAnimationEnd(Animation animation) {
- wasEndCalled = true;
- }
-
- @Override
- public void onAnimationRepeat(Animation animation) {
- wasRepeatCalled = true;
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/util/TestBroadcastReceiver.java b/v1/src/test/java/com/xtremelabs/robolectric/util/TestBroadcastReceiver.java
deleted file mode 100644
index 334b5c6e0..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/util/TestBroadcastReceiver.java
+++ /dev/null
@@ -1,16 +0,0 @@
-package com.xtremelabs.robolectric.util;
-
-import android.content.BroadcastReceiver;
-import android.content.Context;
-import android.content.Intent;
-
-public class TestBroadcastReceiver extends BroadcastReceiver {
- public Context context;
- public Intent intent;
-
- @Override
- public void onReceive(Context context, Intent intent) {
- this.context = context;
- this.intent = intent;
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/util/TestOnClickListener.java b/v1/src/test/java/com/xtremelabs/robolectric/util/TestOnClickListener.java
deleted file mode 100644
index a27064ccd..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/util/TestOnClickListener.java
+++ /dev/null
@@ -1,11 +0,0 @@
-package com.xtremelabs.robolectric.util;
-
-import android.view.View;
-
-public class TestOnClickListener implements View.OnClickListener {
- public boolean clicked = false;
-
- @Override public void onClick(View v) {
- clicked = true;
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/util/TestOnLongClickListener.java b/v1/src/test/java/com/xtremelabs/robolectric/util/TestOnLongClickListener.java
deleted file mode 100644
index bb8f244e4..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/util/TestOnLongClickListener.java
+++ /dev/null
@@ -1,13 +0,0 @@
-package com.xtremelabs.robolectric.util;
-
-import android.view.View;
-
-public class TestOnLongClickListener implements View.OnLongClickListener {
- public boolean clicked = false;
-
- @Override
- public boolean onLongClick(View view) {
- clicked = true;
- return true;
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/util/TestR.java b/v1/src/test/java/com/xtremelabs/robolectric/util/TestR.java
deleted file mode 100644
index 9db68a0f0..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/util/TestR.java
+++ /dev/null
@@ -1,22 +0,0 @@
-package com.xtremelabs.robolectric.util;
-
-/**
- * Test class used as a substitute for com.xtremelabs.robolectric.res.ResourceLoader's
- * reference to the application R class
- */
-public final class TestR {
-
- private static int base = 1025;
-
- public static final class anim {
- public static final int test_anim_1 = ++base;
- }
-
- public static class color {
- public static final int test_color_1 = ++base;
- }
-
- public static class drawable {
- public static final int test_drawable_1 = ++base;
- }
-} \ No newline at end of file
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/util/TestRunnable.java b/v1/src/test/java/com/xtremelabs/robolectric/util/TestRunnable.java
deleted file mode 100644
index 96695ac87..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/util/TestRunnable.java
+++ /dev/null
@@ -1,9 +0,0 @@
-package com.xtremelabs.robolectric.util;
-
-public class TestRunnable implements Runnable {
- public boolean wasRun = false;
-
- @Override public void run() {
- wasRun = true;
- }
-}
diff --git a/v1/src/test/java/com/xtremelabs/robolectric/util/TestUtil.java b/v1/src/test/java/com/xtremelabs/robolectric/util/TestUtil.java
deleted file mode 100644
index ee18eb5dc..000000000
--- a/v1/src/test/java/com/xtremelabs/robolectric/util/TestUtil.java
+++ /dev/null
@@ -1,95 +0,0 @@
-package com.xtremelabs.robolectric.util;
-
-import com.xtremelabs.robolectric.RobolectricConfig;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.util.Collection;
-import java.util.Map;
-import java.util.Properties;
-
-import static org.junit.Assert.assertTrue;
-
-public abstract class TestUtil {
- public static File testDirLocation;
-
- public static void assertEquals(Collection<?> expected, Collection<?> actual) {
- org.junit.Assert.assertEquals(stringify(expected), stringify(actual));
- }
-
- public static String stringify(Collection<?> collection) {
- StringBuilder buf = new StringBuilder();
- for (Object o : collection) {
- if (buf.length() > 0) buf.append("\n");
- buf.append(o);
- }
- return buf.toString();
- }
-
- public static <T> void assertInstanceOf(Class<? extends T> expectedClass, T object) {
- Class actualClass = object.getClass();
- assertTrue(expectedClass + " should be assignable from " + actualClass,
- expectedClass.isAssignableFrom(actualClass));
- }
-
- public static File file(String... pathParts) {
- return file(new File("."), pathParts);
- }
-
- public static File file(File f, String... pathParts) {
- for (String pathPart : pathParts) {
- f = new File(f, pathPart);
- }
- return f;
- }
-
- public static File resourcesBaseDir() {
- if (testDirLocation == null) {
- File testDir = file("src", "test", "resources");
- if (hasTestManifest(testDir)) return testDirLocation = testDir;
-
- File roboTestDir = file("robolectric", "src", "test", "resources");
- if (hasTestManifest(roboTestDir)) return testDirLocation = roboTestDir;
-
- File submoduleDir = file("submodules", "robolectric", "src", "test", "resources");
- if (hasTestManifest(submoduleDir)) return testDirLocation = submoduleDir;
-
- //required for robolectric-sqlite to find resources to test against
- File roboSiblingTestDir = file(new File(new File(".").getAbsolutePath()).getParentFile().getParentFile(),"robolectric", "src", "test", "resources");
- if (hasTestManifest(roboSiblingTestDir)) return testDirLocation = roboSiblingTestDir;
-
- throw new RuntimeException("can't find your TestAndroidManifest.xml in "
- + testDir.getAbsolutePath() + " or " + roboTestDir.getAbsolutePath() + "\n or " + roboSiblingTestDir.getAbsolutePath());
- } else {
- return testDirLocation;
- }
- }
-
- private static boolean hasTestManifest(File testDir) {
- return new File(testDir, "TestAndroidManifest.xml").isFile();
- }
-
- public static File resourceFile(String... pathParts) {
- return file(resourcesBaseDir(), pathParts);
- }
-
- public static RobolectricConfig newConfig(String androidManifestFile) {
- return new RobolectricConfig(resourceFile(androidManifestFile), null, null);
- }
-
- public static File getSystemResourceDir(String... paths) throws Exception {
-
- Map<String,String> env = System.getenv();
- String sdkDir;
- if (env.containsKey("ANDROID_HOME")) {
- sdkDir = env.get("ANDROID_HOME");
- } else {
- Properties localProperties = new Properties();
- localProperties.load(new FileInputStream(new File("local.properties")));
- PropertiesHelper.doSubstitutions(localProperties);
- sdkDir = localProperties.getProperty("sdk.dir");
- }
-
- return file(new File(sdkDir, "platforms/android-10/data/res/"), paths);
- }
-}
diff --git a/v1/src/test/resources/TestAndroidManifest.xml b/v1/src/test/resources/TestAndroidManifest.xml
deleted file mode 100644
index 40bc48554..000000000
--- a/v1/src/test/resources/TestAndroidManifest.xml
+++ /dev/null
@@ -1,5 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.xtremelabs.robolectric">
- <uses-sdk android:targetSdkVersion="10"/>
-</manifest>
diff --git a/v1/src/test/resources/TestAndroidManifestWithAppName.xml b/v1/src/test/resources/TestAndroidManifestWithAppName.xml
deleted file mode 100644
index 30b4b9e77..000000000
--- a/v1/src/test/resources/TestAndroidManifestWithAppName.xml
+++ /dev/null
@@ -1,6 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.xtremelabs.robolectric">
-
- <application android:name="com.xtremelabs.robolectric.TestApplication"/>
-</manifest>
diff --git a/v1/src/test/resources/TestAndroidManifestWithBadAppName.xml b/v1/src/test/resources/TestAndroidManifestWithBadAppName.xml
deleted file mode 100644
index 0e3f7420e..000000000
--- a/v1/src/test/resources/TestAndroidManifestWithBadAppName.xml
+++ /dev/null
@@ -1,6 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.xtremelabs.robolectric">
-
- <application android:name="com.xtremelabs.robolectric.BogusTestApplication"/>
-</manifest>
diff --git a/v1/src/test/resources/TestAndroidManifestWithFlags.xml b/v1/src/test/resources/TestAndroidManifestWithFlags.xml
deleted file mode 100644
index 72eb10d14..000000000
--- a/v1/src/test/resources/TestAndroidManifestWithFlags.xml
+++ /dev/null
@@ -1,20 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.xtremelabs.robolectric">
- <application android:name="com.xtremelabs.robolectric.TestApplication"
- android:allowBackup="true"
- android:allowClearUserData="true"
- android:allowTaskReparenting="true"
- android:debuggable="true"
- android:hasCode="true"
- android:killAfterRestore="true"
- android:persistent="true"
- android:resizeable="true"
- android:restoreAnyVersion="true"
- android:largeScreens="true"
- android:normalScreens="true"
- android:smallScreens="true"
- android:anyDensity="true"
- android:testOnly="true"
- android:vmSafeMode="true" />
-</manifest>
diff --git a/v1/src/test/resources/TestAndroidManifestWithMinSdkVersionOnly.xml b/v1/src/test/resources/TestAndroidManifestWithMinSdkVersionOnly.xml
deleted file mode 100644
index 279b80e84..000000000
--- a/v1/src/test/resources/TestAndroidManifestWithMinSdkVersionOnly.xml
+++ /dev/null
@@ -1,4 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<manifest xmlns:android="http://schemas.android.com/apk/res/android">
- <uses-sdk android:minSdkVersion="3"/>
-</manifest>
diff --git a/v1/src/test/resources/TestAndroidManifestWithNoProcess.xml b/v1/src/test/resources/TestAndroidManifestWithNoProcess.xml
deleted file mode 100644
index 262353e2b..000000000
--- a/v1/src/test/resources/TestAndroidManifestWithNoProcess.xml
+++ /dev/null
@@ -1,5 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.xtremelabs.robolectric">
- <application android:name="com.xtremelabs.robolectric.TestApplication"/>
-</manifest>
diff --git a/v1/src/test/resources/TestAndroidManifestWithPackageName.xml b/v1/src/test/resources/TestAndroidManifestWithPackageName.xml
deleted file mode 100644
index a3f980e40..000000000
--- a/v1/src/test/resources/TestAndroidManifestWithPackageName.xml
+++ /dev/null
@@ -1,4 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.wacka.wa">
-</manifest>
diff --git a/v1/src/test/resources/TestAndroidManifestWithProcess.xml b/v1/src/test/resources/TestAndroidManifestWithProcess.xml
deleted file mode 100644
index 511f651a5..000000000
--- a/v1/src/test/resources/TestAndroidManifestWithProcess.xml
+++ /dev/null
@@ -1,6 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.xtremelabs.robolectric">
- <application android:name="com.xtremelabs.robolectric.TestApplication"
- android:process="robolectricprocess"/>
-</manifest>
diff --git a/v1/src/test/resources/TestAndroidManifestWithReceivers.xml b/v1/src/test/resources/TestAndroidManifestWithReceivers.xml
deleted file mode 100644
index 4b631a50c..000000000
--- a/v1/src/test/resources/TestAndroidManifestWithReceivers.xml
+++ /dev/null
@@ -1,45 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.xtremelabs.robolectric"
- >
- <application>
- <receiver android:name="com.xtremelabs.robolectric.RobolectricConfigTest.ConfigTestReceiver"
- android:permission="com.ignored.PERM">
- <intent-filter>
- <action android:name="com.xtremelabs.robolectric.ACTION1"/>
- <category android:name="com.ignored"/>
- </intent-filter>
- <intent-filter>
- <action android:name="com.xtremelabs.robolectric.ACTION2"/>
- <category android:name="com.ignored"/>
- </intent-filter>
- </receiver>
-
- <receiver android:name="com.xtremelabs.robolectric.test.ConfigTestReceiver">
- <intent-filter>
- <action android:name="com.xtremelabs.robolectric.ACTION_SUPERSET_PACKAGE"/>
- </intent-filter>
- </receiver>
- <receiver android:name="com.xtremelabs.ConfigTestReceiver">
- <intent-filter>
- <action android:name="com.xtremelabs.robolectric.ACTION_SUBSET_PACKAGE"/>
- </intent-filter>
- </receiver>
- <receiver android:name=".DotConfigTestReceiver">
- <intent-filter>
- <action android:name="com.xtremelabs.robolectric.ACTION_DOT_PACKAGE"/>
- </intent-filter>
- </receiver>
- <receiver android:name=".test.ConfigTestReceiver">
- <intent-filter>
- <action android:name="com.xtremelabs.robolectric.ACTION_DOT_SUBPACKAGE"/>
- </intent-filter>
- </receiver>
- <receiver android:name="com.foo.Receiver">
- <intent-filter>
- <action android:name="com.xtremelabs.robolectric.ACTION_DIFFERENT_PACKAGE"/>
- </intent-filter>
- </receiver>
-
- </application>
-</manifest>
diff --git a/v1/src/test/resources/TestAndroidManifestWithSdkVersion.xml b/v1/src/test/resources/TestAndroidManifestWithSdkVersion.xml
deleted file mode 100644
index e96e71a23..000000000
--- a/v1/src/test/resources/TestAndroidManifestWithSdkVersion.xml
+++ /dev/null
@@ -1,5 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<manifest xmlns:android="http://schemas.android.com/apk/res/android">
- <uses-sdk android:minSdkVersion="3"/>
- <uses-sdk android:targetSdkVersion="42"/>
-</manifest>
diff --git a/v1/src/test/resources/assets/assetsHome.txt b/v1/src/test/resources/assets/assetsHome.txt
deleted file mode 100644
index 0b27d62de..000000000
--- a/v1/src/test/resources/assets/assetsHome.txt
+++ /dev/null
@@ -1 +0,0 @@
-assetsHome! \ No newline at end of file
diff --git a/v1/src/test/resources/assets/docs/extra/testing/hello.txt b/v1/src/test/resources/assets/docs/extra/testing/hello.txt
deleted file mode 100644
index 3462721fd..000000000
--- a/v1/src/test/resources/assets/docs/extra/testing/hello.txt
+++ /dev/null
@@ -1 +0,0 @@
-hello! \ No newline at end of file
diff --git a/v1/src/test/resources/res/drawable/animation_list.xml b/v1/src/test/resources/res/drawable/animation_list.xml
deleted file mode 100644
index 621aa206f..000000000
--- a/v1/src/test/resources/res/drawable/animation_list.xml
+++ /dev/null
@@ -1,6 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<animation-list xmlns:android="http://schemas.android.com/apk/res/android" android:oneshot="false">
- <item android:drawable="@drawable/an_image" android:duration="400"/>
- <item android:drawable="@drawable/an_other_image" android:duration="400"/>
- <item android:drawable="@drawable/third_image" android:duration="400"/>
-</animation-list> \ No newline at end of file
diff --git a/v1/src/test/resources/res/drawable/l0_red.png b/v1/src/test/resources/res/drawable/l0_red.png
deleted file mode 100644
index 2a264768a..000000000
--- a/v1/src/test/resources/res/drawable/l0_red.png
+++ /dev/null
Binary files differ
diff --git a/v1/src/test/resources/res/drawable/l1_orange.png b/v1/src/test/resources/res/drawable/l1_orange.png
deleted file mode 100644
index 016a52bdb..000000000
--- a/v1/src/test/resources/res/drawable/l1_orange.png
+++ /dev/null
Binary files differ
diff --git a/v1/src/test/resources/res/drawable/l2_yellow.png b/v1/src/test/resources/res/drawable/l2_yellow.png
deleted file mode 100644
index 30f971d6f..000000000
--- a/v1/src/test/resources/res/drawable/l2_yellow.png
+++ /dev/null
Binary files differ
diff --git a/v1/src/test/resources/res/drawable/l3_green.png b/v1/src/test/resources/res/drawable/l3_green.png
deleted file mode 100644
index 67ffb0a1a..000000000
--- a/v1/src/test/resources/res/drawable/l3_green.png
+++ /dev/null
Binary files differ
diff --git a/v1/src/test/resources/res/drawable/l4_blue.png b/v1/src/test/resources/res/drawable/l4_blue.png
deleted file mode 100644
index 5528619d5..000000000
--- a/v1/src/test/resources/res/drawable/l4_blue.png
+++ /dev/null
Binary files differ
diff --git a/v1/src/test/resources/res/drawable/l5_indigo.png b/v1/src/test/resources/res/drawable/l5_indigo.png
deleted file mode 100644
index fbc8e4297..000000000
--- a/v1/src/test/resources/res/drawable/l5_indigo.png
+++ /dev/null
Binary files differ
diff --git a/v1/src/test/resources/res/drawable/l6_violet.png b/v1/src/test/resources/res/drawable/l6_violet.png
deleted file mode 100644
index b9f4f8ddd..000000000
--- a/v1/src/test/resources/res/drawable/l6_violet.png
+++ /dev/null
Binary files differ
diff --git a/v1/src/test/resources/res/drawable/l7_white.png b/v1/src/test/resources/res/drawable/l7_white.png
deleted file mode 100644
index 288d33c43..000000000
--- a/v1/src/test/resources/res/drawable/l7_white.png
+++ /dev/null
Binary files differ
diff --git a/v1/src/test/resources/res/drawable/nine_patch_drawable.9.png b/v1/src/test/resources/res/drawable/nine_patch_drawable.9.png
deleted file mode 100644
index 6e25b0b6b..000000000
--- a/v1/src/test/resources/res/drawable/nine_patch_drawable.9.png
+++ /dev/null
Binary files differ
diff --git a/v1/src/test/resources/res/drawable/rainbow.xml b/v1/src/test/resources/res/drawable/rainbow.xml
deleted file mode 100644
index 7284f93a5..000000000
--- a/v1/src/test/resources/res/drawable/rainbow.xml
+++ /dev/null
@@ -1,11 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
- <item android:drawable="@drawable/l7_white" />
- <item android:drawable="@drawable/l0_red" />
- <item android:drawable="@drawable/l1_orange" />
- <item android:drawable="@drawable/l2_yellow" />
- <item android:drawable="@drawable/l3_green" />
- <item android:drawable="@drawable/l4_blue" />
- <item android:drawable="@drawable/l5_indigo" />
- <item android:drawable="@drawable/l6_violet" />
-</layer-list>
diff --git a/v1/src/test/resources/res/drawable/state_drawable.xml b/v1/src/test/resources/res/drawable/state_drawable.xml
deleted file mode 100644
index 0b150ed69..000000000
--- a/v1/src/test/resources/res/drawable/state_drawable.xml
+++ /dev/null
@@ -1,15 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<selector
- xmlns:android="http://schemas.android.com/apk/res/android">
-
- <item android:state_selected="true" android:drawable="@drawable/l0_red" />
- <item android:state_pressed="true" android:drawable="@drawable/l1_orange" />
- <item android:state_focused="true" android:drawable="@drawable/l2_yellow" />
- <item android:state_checkable="true" android:drawable="@drawable/l3_green" />
- <item android:state_checked="true" android:drawable="@drawable/l4_blue" />
- <item android:state_enabled="true" android:drawable="@drawable/l5_indigo" />
- <item android:state_window_focused="true" android:drawable="@drawable/l6_violet" />
-
- <item android:drawable="@drawable/l7_white" />
-
-</selector> \ No newline at end of file
diff --git a/v1/src/test/resources/res/layout-land/different_screen_sizes.xml b/v1/src/test/resources/res/layout-land/different_screen_sizes.xml
deleted file mode 100644
index d2850b097..000000000
--- a/v1/src/test/resources/res/layout-land/different_screen_sizes.xml
+++ /dev/null
@@ -1,12 +0,0 @@
-<LinearLayout
- xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- >
- <TextView
- android:id="@android:id/text1"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="land"
- />
-</LinearLayout>
diff --git a/v1/src/test/resources/res/layout-large-v16/different_screen_sizes.xml b/v1/src/test/resources/res/layout-large-v16/different_screen_sizes.xml
deleted file mode 100644
index 456fe4a10..000000000
--- a/v1/src/test/resources/res/layout-large-v16/different_screen_sizes.xml
+++ /dev/null
@@ -1,12 +0,0 @@
-<LinearLayout
- xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- >
- <TextView
- android:id="@android:id/text1"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="large-v16"
- />
-</LinearLayout>
diff --git a/v1/src/test/resources/res/layout-v11/different_screen_sizes.xml b/v1/src/test/resources/res/layout-v11/different_screen_sizes.xml
deleted file mode 100644
index 2ce503501..000000000
--- a/v1/src/test/resources/res/layout-v11/different_screen_sizes.xml
+++ /dev/null
@@ -1,12 +0,0 @@
-<LinearLayout
- xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- >
- <TextView
- android:id="@android:id/text1"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="v11"
- />
-</LinearLayout>
diff --git a/v1/src/test/resources/res/layout-xlarge-v11/different_screen_sizes.xml b/v1/src/test/resources/res/layout-xlarge-v11/different_screen_sizes.xml
deleted file mode 100644
index 29d2662f8..000000000
--- a/v1/src/test/resources/res/layout-xlarge-v11/different_screen_sizes.xml
+++ /dev/null
@@ -1,12 +0,0 @@
-<LinearLayout
- xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- >
- <TextView
- android:id="@android:id/text1"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="xlarge-v11"
- />
-</LinearLayout>
diff --git a/v1/src/test/resources/res/layout-xlarge/different_screen_sizes.xml b/v1/src/test/resources/res/layout-xlarge/different_screen_sizes.xml
deleted file mode 100644
index 141fee3b3..000000000
--- a/v1/src/test/resources/res/layout-xlarge/different_screen_sizes.xml
+++ /dev/null
@@ -1,12 +0,0 @@
-<LinearLayout
- xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- >
- <TextView
- android:id="@android:id/text1"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="xlarge"
- />
-</LinearLayout>
diff --git a/v1/src/test/resources/res/layout/.bogus_hidden_dir_for_tests/bad.xml b/v1/src/test/resources/res/layout/.bogus_hidden_dir_for_tests/bad.xml
deleted file mode 100644
index edff6257f..000000000
--- a/v1/src/test/resources/res/layout/.bogus_hidden_dir_for_tests/bad.xml
+++ /dev/null
@@ -1 +0,0 @@
-this is not a valid XML file \ No newline at end of file
diff --git a/v1/src/test/resources/res/layout/activity_list_item.xml b/v1/src/test/resources/res/layout/activity_list_item.xml
deleted file mode 100644
index 5d58857a3..000000000
--- a/v1/src/test/resources/res/layout/activity_list_item.xml
+++ /dev/null
@@ -1,18 +0,0 @@
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:paddingTop="1dip"
- android:paddingBottom="1dip"
- android:paddingLeft="6dip"
- android:paddingRight="6dip">
-
- <ImageView android:id="@+id/icon"
- android:layout_width="24dip"
- android:layout_height="24dip"/>
-
- <TextView android:id="@android:id/text1"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_gravity="center_horizontal"
- android:paddingLeft="6dip" />
-</LinearLayout>
diff --git a/v1/src/test/resources/res/layout/custom_layout.xml b/v1/src/test/resources/res/layout/custom_layout.xml
deleted file mode 100644
index 116e462a7..000000000
--- a/v1/src/test/resources/res/layout/custom_layout.xml
+++ /dev/null
@@ -1,5 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-
-<com.xtremelabs.robolectric.util.CustomView
- message="@string/hello"
- /> \ No newline at end of file
diff --git a/v1/src/test/resources/res/layout/custom_layout2.xml b/v1/src/test/resources/res/layout/custom_layout2.xml
deleted file mode 100644
index 4d825dae9..000000000
--- a/v1/src/test/resources/res/layout/custom_layout2.xml
+++ /dev/null
@@ -1,9 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-
-<com.xtremelabs.robolectric.util.CustomView2 message="@string/hello">
- <com.xtremelabs.robolectric.util.CustomView2>
- <TextView/>
- <TextView/>
- <TextView/>
- </com.xtremelabs.robolectric.util.CustomView2>
-</com.xtremelabs.robolectric.util.CustomView2> \ No newline at end of file
diff --git a/v1/src/test/resources/res/layout/different_screen_sizes.xml b/v1/src/test/resources/res/layout/different_screen_sizes.xml
deleted file mode 100644
index b989d9e10..000000000
--- a/v1/src/test/resources/res/layout/different_screen_sizes.xml
+++ /dev/null
@@ -1,12 +0,0 @@
-<LinearLayout
- xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- >
- <TextView
- android:id="@android:id/text1"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="default"
- />
-</LinearLayout>
diff --git a/v1/src/test/resources/res/layout/fragment_activity.xml b/v1/src/test/resources/res/layout/fragment_activity.xml
deleted file mode 100644
index 8e622f040..000000000
--- a/v1/src/test/resources/res/layout/fragment_activity.xml
+++ /dev/null
@@ -1,23 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-
-<LinearLayout
- xmlns:android="http://schemas.android.com/apk/res/android"
- android:id="@+id/fragment_container"
- android:orientation="vertical"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:gravity="center_horizontal"
- >
-
- <fragment
- android:id="@+id/fragment"
- android:tag="fragment_tag"
- android:name="com.xtremelabs.robolectric.shadows.TestFragment"
- />
-
- <LinearLayout
- android:id="@+id/dynamic_fragment_container"
- />
-
-
-</LinearLayout>
diff --git a/v1/src/test/resources/res/layout/included_layout_parent.xml b/v1/src/test/resources/res/layout/included_layout_parent.xml
deleted file mode 100644
index a0608d22e..000000000
--- a/v1/src/test/resources/res/layout/included_layout_parent.xml
+++ /dev/null
@@ -1,13 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-
-<LinearLayout
- xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:gravity="center_horizontal"
- >
-
- <include layout="@layout/included_linear_layout"/>
-
-</LinearLayout> \ No newline at end of file
diff --git a/v1/src/test/resources/res/layout/included_linear_layout.xml b/v1/src/test/resources/res/layout/included_linear_layout.xml
deleted file mode 100644
index 3d32f8390..000000000
--- a/v1/src/test/resources/res/layout/included_linear_layout.xml
+++ /dev/null
@@ -1,9 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-
-<LinearLayout
- xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:gravity="center_horizontal"
- />
diff --git a/v1/src/test/resources/res/layout/inner_merge.xml b/v1/src/test/resources/res/layout/inner_merge.xml
deleted file mode 100644
index 7bb23c303..000000000
--- a/v1/src/test/resources/res/layout/inner_merge.xml
+++ /dev/null
@@ -1,11 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-
-<merge
- xmlns:android="http://schemas.android.com/apk/res/android"
- >
- <TextView
- android:id="@+id/inner_text"
- android:layout_width="fill_parent"
- android:layout_height="10dip"
- />
-</merge>
diff --git a/v1/src/test/resources/res/layout/main.xml b/v1/src/test/resources/res/layout/main.xml
deleted file mode 100644
index a2c25e254..000000000
--- a/v1/src/test/resources/res/layout/main.xml
+++ /dev/null
@@ -1,71 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-
-<LinearLayout
- xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:gravity="center_horizontal"
- >
-
- <include layout="@layout/snippet"/>
-
- <View
- android:layout_width="fill_parent"
- android:layout_height="10dip"
- />
-
- <View
- android:id="@+id/time"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:textSize="14dip"
- android:textColor="#fff"
- android:enabled="false"
- android:contentDescription="@string/howdy"
- />
-
- <TextView
- android:id="@+id/title"
- android:layout_width="138dip"
- android:layout_height="wrap_content"
- android:maxHeight="46dip"
- android:singleLine="false"
- android:gravity="center_horizontal"
- android:text="Main Layout"
- android:textSize="18dip"
- android:textStyle="bold"
- android:textColor="#fff"
- android:drawableTop="@drawable/an_image"
- android:drawableRight="@drawable/an_other_image"
- android:drawableBottom="@drawable/third_image"
- android:drawableLeft="@drawable/fourth_image"
- />
-
- <TextView
- android:id="@+id/subtitle"
- android:layout_width="138dip"
- android:gravity="center_horizontal"
- android:layout_height="wrap_content"
- android:text="@string/hello"
- android:maxHeight="36dip"
- android:textSize="14dip"
- android:textColor="#fff"
- />
-
- <CheckBox android:id="@+id/true_checkbox" android:checked="true"/>
- <CheckBox android:id="@+id/false_checkbox" android:checked="false"/>
- <CheckBox android:id="@+id/default_checkbox"/>
-
- <ImageView
- android:id="@+id/image"
- android:src="@drawable/an_image"
- android:background="@drawable/image_background"
- />
-
- <Button
- android:id="@+id/button"
- android:onClick="onButtonClick"
- />
-
-</LinearLayout>
diff --git a/v1/src/test/resources/res/layout/mapview.xml b/v1/src/test/resources/res/layout/mapview.xml
deleted file mode 100644
index 4d6689475..000000000
--- a/v1/src/test/resources/res/layout/mapview.xml
+++ /dev/null
@@ -1,17 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-
-<RelativeLayout
- xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- >
-
- <com.google.android.maps.MapView
- android:id="@+id/map_view"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:clickable="true"
- android:apiKey="Your Maps API Key goes here"
- />
-</RelativeLayout> \ No newline at end of file
diff --git a/v1/src/test/resources/res/layout/media.xml b/v1/src/test/resources/res/layout/media.xml
deleted file mode 100644
index 2e958226d..000000000
--- a/v1/src/test/resources/res/layout/media.xml
+++ /dev/null
@@ -1,50 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-
-<LinearLayout
- xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:gravity="center_horizontal"
- >
-
- <include android:id="@+id/include_id" layout="@layout/snippet"/>
-
- <View
- android:layout_width="fill_parent"
- android:layout_height="10dip"
- />
-
- <TextView
- android:id="@+id/time"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:textSize="14dip"
- android:textColor="#fff"
- android:text="Media Layout"
- />
-
- <TextView
- android:id="@+id/title"
- android:layout_width="138dip"
- android:layout_height="wrap_content"
- android:maxHeight="46dip"
- android:singleLine="false"
- android:gravity="center_horizontal"
- android:textSize="18dip"
- android:textStyle="bold"
- android:textColor="#fff"
- />
-
- <TextView
- android:id="@+id/subtitle"
- android:layout_width="138dip"
- android:gravity="center_horizontal"
- android:layout_height="wrap_content"
- android:maxHeight="36dip"
- android:textSize="14dip"
- android:textColor="#fff"
- android:visibility="gone"
- />
-
-</LinearLayout>
diff --git a/v1/src/test/resources/res/layout/outer.xml b/v1/src/test/resources/res/layout/outer.xml
deleted file mode 100644
index ffa93d269..000000000
--- a/v1/src/test/resources/res/layout/outer.xml
+++ /dev/null
@@ -1,14 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-
-<LinearLayout
- xmlns:android="http://schemas.android.com/apk/res/android"
- android:id="@+id/outer_merge"
- android:orientation="vertical"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:gravity="center_horizontal"
- >
-
- <include android:id="@+id/include_id" layout="@layout/inner_merge"/>
-
-</LinearLayout>
diff --git a/v1/src/test/resources/res/layout/override_include.xml b/v1/src/test/resources/res/layout/override_include.xml
deleted file mode 100644
index bd38adce6..000000000
--- a/v1/src/test/resources/res/layout/override_include.xml
+++ /dev/null
@@ -1,17 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-
-<LinearLayout
- xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- >
-
- <include
- layout="@layout/snippet"
- android:visibility="invisible"
- />
-
- <include layout="@layout/inner_merge"/>
-
-
-</LinearLayout> \ No newline at end of file
diff --git a/v1/src/test/resources/res/layout/request_focus.xml b/v1/src/test/resources/res/layout/request_focus.xml
deleted file mode 100644
index 128711881..000000000
--- a/v1/src/test/resources/res/layout/request_focus.xml
+++ /dev/null
@@ -1,18 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-
-<LinearLayout
- xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- >
- <EditText
- android:id="@+id/edit_text"
- android:layout_width="fill_parent"
- android:layout_height="10dip"
- />
- <FrameLayout>
- <requestFocus/>
- <!-- focus should be given to the FrameLayout, *not* the EditText -->
- </FrameLayout>
- <View/>
-</LinearLayout> \ No newline at end of file
diff --git a/v1/src/test/resources/res/layout/request_focus_with_two_edit_texts.xml b/v1/src/test/resources/res/layout/request_focus_with_two_edit_texts.xml
deleted file mode 100644
index aa11bb649..000000000
--- a/v1/src/test/resources/res/layout/request_focus_with_two_edit_texts.xml
+++ /dev/null
@@ -1,19 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-
-<LinearLayout
- xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- >
- <EditText
- android:id="@+id/edit_text"
- android:layout_width="fill_parent"
- android:layout_height="10dip"
- />
- <EditText
- android:id="@+id/edit_text2"
- android:layout_width="fill_parent"
- android:layout_height="10dip"
- />
- <View/>
-</LinearLayout> \ No newline at end of file
diff --git a/v1/src/test/resources/res/layout/snippet.xml b/v1/src/test/resources/res/layout/snippet.xml
deleted file mode 100644
index c4a3676c3..000000000
--- a/v1/src/test/resources/res/layout/snippet.xml
+++ /dev/null
@@ -1,9 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-
-<TextView
- xmlns:android="http://schemas.android.com/apk/res/android"
- android:id="@+id/snippet_text"
- android:layout_width="fill_parent"
- android:layout_height="10dip"
- android:visibility="gone"
- />
diff --git a/v1/src/test/resources/res/layout/tab_activity.xml b/v1/src/test/resources/res/layout/tab_activity.xml
deleted file mode 100644
index cd7d860dd..000000000
--- a/v1/src/test/resources/res/layout/tab_activity.xml
+++ /dev/null
@@ -1,26 +0,0 @@
-<merge xmlns:android="http://schemas.android.com/apk/res/android"
- android:id="@+id/main"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent">
-
- <TabHost
- android:id="@android:id/tabhost"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent">
- <LinearLayout
- android:orientation="vertical"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent">
- <TabWidget
- android:id="@android:id/tabs"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:background="@color/listSeperator"/>
- <FrameLayout
- android:id="@android:id/tabcontent"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent">
- </FrameLayout>
- </LinearLayout>
- </TabHost>
-</merge> \ No newline at end of file
diff --git a/v1/src/test/resources/res/layout/text_views.xml b/v1/src/test/resources/res/layout/text_views.xml
deleted file mode 100644
index 4084f3d8b..000000000
--- a/v1/src/test/resources/res/layout/text_views.xml
+++ /dev/null
@@ -1,32 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-
-<LinearLayout
- xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- >
-
- <TextView
- android:id="@+id/black_text_view"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="Black Text"
- android:textColor="#000000"
- />
-
- <TextView
- android:id="@+id/white_text_view"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="White Text"
- android:textColor="@android:color/white"
- />
-
- <TextView
- android:id="@+id/grey_text_view"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="Grey Text"
- android:textColor="@color/grey42"
- />
-</LinearLayout>
diff --git a/v1/src/test/resources/res/layout/text_views_hints.xml b/v1/src/test/resources/res/layout/text_views_hints.xml
deleted file mode 100644
index b0e5dd079..000000000
--- a/v1/src/test/resources/res/layout/text_views_hints.xml
+++ /dev/null
@@ -1,31 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-
-<LinearLayout
- xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- >
- <TextView
- android:id="@+id/black_text_view_hint"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:hint="Black Hint"
- android:hintColor="#000000"
- />
-
- <TextView
- android:id="@+id/white_text_view_hint"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:hint="White Hint"
- android:hintColor="@android:color/white"
- />
-
- <TextView
- android:id="@+id/grey_text_view_hint"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:hint="Grey Hint"
- android:hintColor="@color/grey42"
- />
-</LinearLayout>
diff --git a/v1/src/test/resources/res/layout/toplevel_merge.xml b/v1/src/test/resources/res/layout/toplevel_merge.xml
deleted file mode 100644
index 24f462255..000000000
--- a/v1/src/test/resources/res/layout/toplevel_merge.xml
+++ /dev/null
@@ -1,20 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-
-<merge
- android:id="@+id/main"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- xmlns:android="http://schemas.android.com/apk/res/android">
-
-
-
- <View
- android:layout_width="fill_parent"
- android:layout_height="10dip"
- />
-
- <View
- android:layout_width="fill_parent"
- android:layout_height="10dip"
- />
- </merge> \ No newline at end of file
diff --git a/v1/src/test/resources/res/layout/views.xml b/v1/src/test/resources/res/layout/views.xml
deleted file mode 100644
index 5d96d40f7..000000000
--- a/v1/src/test/resources/res/layout/views.xml
+++ /dev/null
@@ -1,47 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content" >
-
- <View
- android:id="@+id/default_view"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content" />
-
- <View
- android:id="@+id/filter_touches_false_view"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:filterTouchesWhenObscured="false" />
-
- <View
- android:id="@+id/filter_touches_true_view"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:filterTouchesWhenObscured="true" />
-
- <View
- android:id="@+id/clickable_false_view"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:clickable="false" />
-
- <View
- android:id="@+id/clickable_true_view"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:clickable="true" />
-
- <View
- android:id="@+id/focusable_false_view"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:focusable="false" />
-
- <View
- android:id="@+id/focusable_true_view"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:focusable="true" />
-
-</LinearLayout>
diff --git a/v1/src/test/resources/res/layout/webview_holder.xml b/v1/src/test/resources/res/layout/webview_holder.xml
deleted file mode 100644
index 8ca954ded..000000000
--- a/v1/src/test/resources/res/layout/webview_holder.xml
+++ /dev/null
@@ -1,16 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-
-<LinearLayout
- xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- >
-
- <WebView
- android:id="@+id/web_view"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- />
-
-</LinearLayout>
diff --git a/v1/src/test/resources/res/layout/with_invalid_onclick.xml b/v1/src/test/resources/res/layout/with_invalid_onclick.xml
deleted file mode 100644
index 74ac195b9..000000000
--- a/v1/src/test/resources/res/layout/with_invalid_onclick.xml
+++ /dev/null
@@ -1,6 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Button
- xmlns:android="http://schemas.android.com/apk/res/android"
- android:id="@+id/invalid_onclick_button"
- android:onClick="someInvalidMethod"
- />
diff --git a/v1/src/test/resources/res/menu/test.xml b/v1/src/test/resources/res/menu/test.xml
deleted file mode 100644
index cd5a991dd..000000000
--- a/v1/src/test/resources/res/menu/test.xml
+++ /dev/null
@@ -1,6 +0,0 @@
-<menu xmlns:android="http://schemas.android.com/apk/res/android">
- <item android:id="@+id/test_menu_1"
- android:title="Test menu item 1" />
- <item android:id="@+id/test_menu_2"
- android:title="Test menu item 2" />
-</menu>
diff --git a/v1/src/test/resources/res/menu/test_withchilds.xml b/v1/src/test/resources/res/menu/test_withchilds.xml
deleted file mode 100644
index a1e868f3e..000000000
--- a/v1/src/test/resources/res/menu/test_withchilds.xml
+++ /dev/null
@@ -1,14 +0,0 @@
-<menu xmlns:android="http://schemas.android.com/apk/res/android">
- <item android:id="@+id/test_menu_1" android:title="Test menu item 1">
- </item>
- <group android:id="@+id/group_id_1">
- <item android:id="@+id/test_menu_2" android:title="Test menu item 2" />
- <item android:id="@+id/test_menu_3" android:title="Test menu item 3" />
- </group>
- <item android:id="@+id/test_submenu_1">
- <menu>
- <item android:id="@+id/test_menu_2" android:title="Test menu item 2" />
- <item android:id="@+id/test_menu_3" android:title="Test menu item 3" />
- </menu>
- </item>
-</menu>
diff --git a/v1/src/test/resources/res/raw/raw_no_ext b/v1/src/test/resources/res/raw/raw_no_ext
deleted file mode 100644
index bfc4c5f69..000000000
--- a/v1/src/test/resources/res/raw/raw_no_ext
+++ /dev/null
@@ -1 +0,0 @@
-no ext file contents \ No newline at end of file
diff --git a/v1/src/test/resources/res/raw/raw_resource.txt b/v1/src/test/resources/res/raw/raw_resource.txt
deleted file mode 100644
index 6f462288b..000000000
--- a/v1/src/test/resources/res/raw/raw_resource.txt
+++ /dev/null
@@ -1 +0,0 @@
-raw txt file contents \ No newline at end of file
diff --git a/v1/src/test/resources/res/values-fr/strings.xml b/v1/src/test/resources/res/values-fr/strings.xml
deleted file mode 100644
index 04fdf3fdf..000000000
--- a/v1/src/test/resources/res/values-fr/strings.xml
+++ /dev/null
@@ -1,4 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<resources>
- <string name="hello">Bonjour</string>
-</resources> \ No newline at end of file
diff --git a/v1/src/test/resources/res/values/attrs.xml b/v1/src/test/resources/res/values/attrs.xml
deleted file mode 100644
index b0f0b1298..000000000
--- a/v1/src/test/resources/res/values/attrs.xml
+++ /dev/null
@@ -1,9 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<resources>
- <declare-styleable name="com.xtremelabs.robolectric.util.CustomView">
- <attr name="itemType" format="enum">
- <enum name="integer" value="0"/>
- <enum name="string" value="1"/>
- </attr>
- </declare-styleable>
-</resources> \ No newline at end of file
diff --git a/v1/src/test/resources/res/values/colors.xml b/v1/src/test/resources/res/values/colors.xml
deleted file mode 100644
index 01f249b31..000000000
--- a/v1/src/test/resources/res/values/colors.xml
+++ /dev/null
@@ -1,16 +0,0 @@
-<resources>
- <color name="foreground">@color/grey42</color>
-
- <color name="clear">#00000001</color>
- <color name="white">#FFFFFF</color>
- <color name="black">#000000</color>
- <color name="grey42">#f5f5f5</color>
- <color name="color_with_alpha">#802C76AD</color>
-
- <color name="background">@color/grey42</color>
-
- <color name="android_namespaced_black">@android:color/black</color>
-
- <color name="android_red">red</color>
-
-</resources>
diff --git a/v1/src/test/resources/res/values/dimens.xml b/v1/src/test/resources/res/values/dimens.xml
deleted file mode 100644
index 1904b8965..000000000
--- a/v1/src/test/resources/res/values/dimens.xml
+++ /dev/null
@@ -1,7 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<resources>
- <dimen name="test_dp_dimen">8dp</dimen>
- <dimen name="test_dip_dimen">20dip</dimen>
- <dimen name="test_px_dimen">15px</dimen>
- <dimen name="test_sp_dimen">5sp</dimen>
-</resources> \ No newline at end of file
diff --git a/v1/src/test/resources/res/values/integer.xml b/v1/src/test/resources/res/values/integer.xml
deleted file mode 100644
index 915c73e1b..000000000
--- a/v1/src/test/resources/res/values/integer.xml
+++ /dev/null
@@ -1,8 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<resource>
-
- <string name="test_non_integer">This is not an integer</string>
- <integer name="test_integer1">2000</integer>
- <integer name="test_integer2">9</integer>
- <integer name="test_large_hex">0xFFFF0000</integer>
-</resource> \ No newline at end of file
diff --git a/v1/src/test/resources/res/values/plurals.xml b/v1/src/test/resources/res/values/plurals.xml
deleted file mode 100644
index 47021974b..000000000
--- a/v1/src/test/resources/res/values/plurals.xml
+++ /dev/null
@@ -1,9 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<resources>
- <plurals name="beer">
- <item quantity="zero">@string/howdy</item>
- <item quantity="one">One beer</item>
- <item quantity="two">Two beers</item>
- <item quantity="other">%d beers, yay!</item>
- </plurals>
-</resources> \ No newline at end of file
diff --git a/v1/src/test/resources/res/values/string_arrays.xml b/v1/src/test/resources/res/values/string_arrays.xml
deleted file mode 100644
index fc3841438..000000000
--- a/v1/src/test/resources/res/values/string_arrays.xml
+++ /dev/null
@@ -1,22 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<resources>
- <string-array name="more_items">
- <item>baz</item>
- <item>bang</item>
- </string-array>
-
- <string-array name="greetings">
- <item>hola</item>
- <item>@string/hello</item>
- </string-array>
-
- <string-array name="alertDialogTestItems">
- <item>Aloha</item>
- <item>Hawai</item>
- </string-array>
-
- <string-array name="emailAddressTypes">
- <item>Doggy</item>
- <item>Catty</item>
- </string-array>
-</resources> \ No newline at end of file
diff --git a/v1/src/test/resources/res/values/strings.xml b/v1/src/test/resources/res/values/strings.xml
deleted file mode 100644
index 7ba410ee2..000000000
--- a/v1/src/test/resources/res/values/strings.xml
+++ /dev/null
@@ -1,12 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<resources>
- <string name="greeting">@string/howdy</string>
- <string name="howdy">Howdy</string>
- <string name="hello">Hello</string>
- <string name="some_html"><b>Hello, <i>world</i></b></string>
- <string-array name="items">
- <item>foo</item>
- <item>bar</item>
- </string-array>
- <string name="copy">Local Copy</string>
-</resources> \ No newline at end of file
diff --git a/v1/src/test/resources/res/xml/preferences.xml b/v1/src/test/resources/res/xml/preferences.xml
deleted file mode 100644
index ad4f095fc..000000000
--- a/v1/src/test/resources/res/xml/preferences.xml
+++ /dev/null
@@ -1,46 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<PreferenceScreen
- xmlns:android="http://schemas.android.com/apk/res/android">
-
- <PreferenceCategory
- android:key="category"
- android:title="Category Test">
-
- <Preference
- android:key="inside_category"
- android:title="Inside Category Test"
- android:summary=""/>
-
- </PreferenceCategory>
-
- <CheckBoxPreference
- android:key="checkbox"
- android:title="Checkbox Test"
- android:summary=""
- android:defaultValue="true"
- />
-
- <EditTextPreference
- android:key="edit_text"
- android:title="EditText Test"
- android:summary=""
- />
-
- <ListPreference
- android:key="list"
- android:title="List Test"
- android:summary=""
- />
-
- <Preference
- android:key="preference"
- android:title="Preference Title"
- android:summary=""/>
-
- <RingtonePreference
- android:key="ringtone"
- android:title="Ringtone Test"
- android:summary=""
- />
-
-</PreferenceScreen> \ No newline at end of file
diff --git a/v1/update-downloads.rb b/v1/update-downloads.rb
deleted file mode 100755
index 308460555..000000000
--- a/v1/update-downloads.rb
+++ /dev/null
@@ -1,40 +0,0 @@
-#!/usr/bin/env ruby
-
-DOWNLOADS_FILE = 'pages/download.md'
-
-def need_pages_submodule
- unless File.exists?(DOWNLOADS_FILE)
- raise "Robolectric pages submodule isn't present. Run git submodule update --init"
- end
-end
-
-def fill_index_downloads
- require 'digest/sha1'
-
- download_html = "<!-- START_DOWNLOADS -->\n"
- Dir.glob('pages/downloads/*.jar').sort.reverse.each do |f|
- sha1 = Digest::SHA1.hexdigest File.read(f)
-
- fn = f.sub(/^pages\//, '')
- match = /robolectric-?([0-9]\.[0-9](\.[0-9])?)?(-all)?(-src)?\.jar/.match(f)
- version = match[1] if match
- version = "SNAPSHOT" unless version
- prerelease = /\.rc/.match(f)
- download_html += prerelease ? "<tr class=\"rc\">\n" : "<tr>\n"
- download_html += " <td class=\"link\"><a href=\"#{fn}\" onClick=\"javascript:pageTracker._trackPageView('#{fn}'); \">#{fn.sub(/downloads\//, '')}</a></td>\n"
- download_html += " <td class=\"version\">#{version}</td>\n"
- download_html += " <td class=\"size\">#{File.size(f) / 1024}k</td>\n"
- download_html += " <td class=\"date\">#{File.mtime(f).strftime("%Y/%m/%d %H:%M:%S %Z")}</td>\n"
- download_html += " <td class=\"sha\">#{sha1}</td>\n"
- download_html += "</tr>\n"
- end
- download_html += "<!-- END_DOWNLOADS -->"
-
- downloads_page = File.read(DOWNLOADS_FILE)
- matcher = /<!-- START_DOWNLOADS -->.*<!-- END_DOWNLOADS -->/m
- downloads_page = downloads_page.sub(matcher, download_html)
- File.open(DOWNLOADS_FILE, 'w') {|f| f.write(downloads_page)}
- puts "rewrote " + DOWNLOADS_FILE
-end
-
-fill_index_downloads \ No newline at end of file
diff --git a/v3/LICENSE.txt b/v3/LICENSE.txt
deleted file mode 100644
index 83e0c2e82..000000000
--- a/v3/LICENSE.txt
+++ /dev/null
@@ -1,23 +0,0 @@
-Found at: https://github.com/robolectric/robolectric/blob/master/LICENSE.txt
-
-The MIT License
-
-Copyright (c) 2010 Xtreme Labs and Pivotal Labs
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-THE SOFTWARE. \ No newline at end of file
diff --git a/v3/README.txt b/v3/README.txt
deleted file mode 100644
index e66e82ce6..000000000
--- a/v3/README.txt
+++ /dev/null
@@ -1,44 +0,0 @@
-Robolectric source code is distributed at https://github.com/robolectric/robolectric
-
-#
-# Jars built from source
-#
-Robolectric commit sha1: 626241e5080aae44ce3df7a8328e7b6d4dd42d7f
-
-Jars built from source:
-robolectric-*-3.0-SNAPSHOT.jar
-shadows-*-3.0-SNAPSHOT.jar
-runtime/shadows-core-3.0-SNAPSHOT-*.jar
-
-
-#
-# Jars built by Robolectric team
-#
-runtime/android-all-4.1.2_r1-robolectric-0.jar
-Download link: http://central.maven.org/maven2/org/robolectric/android-all/4.1.2_r1-robolectric-0/android-all-4.1.2_r1-robolectric-0.jar
-
-runtime/android-all-4.2.2_r1.2-robolectric-0.jar
-Download link: http://central.maven.org/maven2/org/robolectric/android-all/4.2.2_r1.2-robolectric-0/android-all-4.2.2_r1.2-robolectric-0.jar
-
-runtime/android-all-4.3_r2-robolectric-0.jar
-Download link: http://central.maven.org/maven2/org/robolectric/android-all/4.3_r2-robolectric-0/android-all-4.3_r2-robolectric-0.jar
-
-runtime/android-all-4.4_r1-robolectric-1.jar
-Download link: http://central.maven.org/maven2/org/robolectric/android-all/4.4_r1-robolectric-1/android-all-4.4_r1-robolectric-1.jar
-
-runtime/android-all-5.0.0_r2-robolectric-1.jar
-Download link: http://central.maven.org/maven2/org/robolectric/android-all/5.0.0_r2-robolectric-1/android-all-5.0.0_r2-robolectric-1.jar
-
-runtime/android-all-5.1.1_r9-robolectric-1.jar
-Download link: http://central.maven.org/maven2/org/robolectric/android-all/5.1.1_r9-robolectric-1/android-all-5.1.1_r9-robolectric-1.jar
-
-#
-# Other runtime only dependencies (included here for simplicity in test confinguration)
-#
-runtime/json-20080701.jar
-Download link: http://central.maven.org/maven2/org/json/json/20080701/json-20080701.jar
-license: http://www.json.org/license.html
-
-runtime/tagsoup-1.2.jar
-Download link: http://central.maven.org/maven2/org/ccil/cowan/tagsoup/tagsoup/1.2/tagsoup-1.2.jar
-license: http://home.ccil.org/~cowan/tagsoup/ (Apache v2)
diff --git a/v3/build.gradle b/v3/build.gradle
deleted file mode 100644
index 3d150220b..000000000
--- a/v3/build.gradle
+++ /dev/null
@@ -1,40 +0,0 @@
-apply plugin: 'java'
-
-// Create an implicit target which is a collection of jars
-// required for running Robolectric v3 tests
-
-// Heavily inspired by its google3 equivalent at
-// https://cs.corp.google.com/#piper///depot/google3/third_party/java/robolectric/v3_0_SNAPSHOT/BUILD
-
-sourceSets {
- main.java.srcDirs = []
- test.java.srcDirs = []
-}
-
-dependencies {
- compile "org.ow2.asm:asm:5.0.3"
- compile "org.ow2.asm:asm-commons:5.0.3"
- compile "org.ow2.asm:asm-tree:5.0.3"
- compile "org.ow2.asm:asm-util:5.0.3"
- compile "org.apache.ant:ant:1.8.0"
- compile "com.google.guava:guava:17.0"
- compile "org.apache.httpcomponents:httpclient:4.1.1"
- compile "org.bouncycastle:bcprov-jdk15on:1.48"
- compile "com.ibm.icu:icu4j:54.1.1"
-
- // Prebuilts only needed for Robolectric and less useful
- // for other teams.
- compile files("libs/sqlite4java-0.282.jar")
- compile files("libs/vtd-xml-2.11.jar")
-
- // Jars built by the Robolectric team used across all
- // Android versions
- compile fileTree(dir: ".", include: "*.jar")
-
- // Use highest version of Android supported by Robolectric for
- // compilation. Actual implementation jar will be decided at
- // runtime based on sdk version specified in test.
- compile files("runtime/android-all-5.0.0_r2-robolectric-1.jar")
- compile files("runtime/json-20080701.jar")
- compile files("runtime/shadows-core-3.1-SNAPSHOT-21.jar")
-}
diff --git a/v3/libs/README.txt b/v3/libs/README.txt
deleted file mode 100644
index 6fb9e1dda..000000000
--- a/v3/libs/README.txt
+++ /dev/null
@@ -1,11 +0,0 @@
-The following are links to where each of these jars were downloaded and a link
-to their license.
-
-sqlite4java-0.282:
-jar: http://central.maven.org/maven2/com/almworks/sqlite4java/sqlite4java/0.282/sqlite4java-0.282.jar
-license: https://code.google.com/p/sqlite4java/ (Apache v2)
-
-vtd-xml-2.11:
-jar: http://mvnrepository.com/artifact/com.ximpleware/vtd-xml/2.11
-license: http://sourceforge.net/projects/vtd-xml/ (GPL v2)
-
diff --git a/v3/libs/sqlite4java-0.282.jar b/v3/libs/sqlite4java-0.282.jar
deleted file mode 100644
index 686098fe4..000000000
--- a/v3/libs/sqlite4java-0.282.jar
+++ /dev/null
Binary files differ
diff --git a/v3/libs/vtd-xml-2.11.jar b/v3/libs/vtd-xml-2.11.jar
deleted file mode 100644
index ecf0e2f8c..000000000
--- a/v3/libs/vtd-xml-2.11.jar
+++ /dev/null
Binary files differ
diff --git a/v3/robolectric-3.1-SNAPSHOT.jar b/v3/robolectric-3.1-SNAPSHOT.jar
deleted file mode 100644
index 3fb61c386..000000000
--- a/v3/robolectric-3.1-SNAPSHOT.jar
+++ /dev/null
Binary files differ
diff --git a/v3/robolectric-annotations-3.1-SNAPSHOT.jar b/v3/robolectric-annotations-3.1-SNAPSHOT.jar
deleted file mode 100644
index a45832a4a..000000000
--- a/v3/robolectric-annotations-3.1-SNAPSHOT.jar
+++ /dev/null
Binary files differ
diff --git a/v3/robolectric-processor-3.1-SNAPSHOT.jar b/v3/robolectric-processor-3.1-SNAPSHOT.jar
deleted file mode 100644
index cc2d4fc09..000000000
--- a/v3/robolectric-processor-3.1-SNAPSHOT.jar
+++ /dev/null
Binary files differ
diff --git a/v3/robolectric-resources-3.1-SNAPSHOT.jar b/v3/robolectric-resources-3.1-SNAPSHOT.jar
deleted file mode 100644
index 92cd77ace..000000000
--- a/v3/robolectric-resources-3.1-SNAPSHOT.jar
+++ /dev/null
Binary files differ
diff --git a/v3/robolectric-utils-3.1-SNAPSHOT.jar b/v3/robolectric-utils-3.1-SNAPSHOT.jar
deleted file mode 100644
index 8fee988db..000000000
--- a/v3/robolectric-utils-3.1-SNAPSHOT.jar
+++ /dev/null
Binary files differ
diff --git a/v3/runtime/android-all-4.1.2_r1-robolectric-0.jar b/v3/runtime/android-all-4.1.2_r1-robolectric-0.jar
deleted file mode 100644
index 59850966c..000000000
--- a/v3/runtime/android-all-4.1.2_r1-robolectric-0.jar
+++ /dev/null
Binary files differ
diff --git a/v3/runtime/android-all-4.2.2_r1.2-robolectric-0.jar b/v3/runtime/android-all-4.2.2_r1.2-robolectric-0.jar
deleted file mode 100644
index 7884005e3..000000000
--- a/v3/runtime/android-all-4.2.2_r1.2-robolectric-0.jar
+++ /dev/null
Binary files differ
diff --git a/v3/runtime/android-all-4.3_r2-robolectric-0.jar b/v3/runtime/android-all-4.3_r2-robolectric-0.jar
deleted file mode 100644
index c9dffbc13..000000000
--- a/v3/runtime/android-all-4.3_r2-robolectric-0.jar
+++ /dev/null
Binary files differ
diff --git a/v3/runtime/android-all-4.4_r1-robolectric-1.jar b/v3/runtime/android-all-4.4_r1-robolectric-1.jar
deleted file mode 100644
index 6bed26eef..000000000
--- a/v3/runtime/android-all-4.4_r1-robolectric-1.jar
+++ /dev/null
Binary files differ
diff --git a/v3/runtime/android-all-5.0.0_r2-robolectric-1.jar b/v3/runtime/android-all-5.0.0_r2-robolectric-1.jar
deleted file mode 100644
index 7ba2a9085..000000000
--- a/v3/runtime/android-all-5.0.0_r2-robolectric-1.jar
+++ /dev/null
Binary files differ
diff --git a/v3/runtime/android-all-5.1.1_r9-robolectric-1.jar b/v3/runtime/android-all-5.1.1_r9-robolectric-1.jar
deleted file mode 100644
index 1fc7a47c9..000000000
--- a/v3/runtime/android-all-5.1.1_r9-robolectric-1.jar
+++ /dev/null
Binary files differ
diff --git a/v3/runtime/json-20080701.jar b/v3/runtime/json-20080701.jar
deleted file mode 100644
index c9a093edb..000000000
--- a/v3/runtime/json-20080701.jar
+++ /dev/null
Binary files differ
diff --git a/v3/runtime/shadows-core-3.1-SNAPSHOT-16.jar b/v3/runtime/shadows-core-3.1-SNAPSHOT-16.jar
deleted file mode 100644
index eb3778cdd..000000000
--- a/v3/runtime/shadows-core-3.1-SNAPSHOT-16.jar
+++ /dev/null
Binary files differ
diff --git a/v3/runtime/shadows-core-3.1-SNAPSHOT-17.jar b/v3/runtime/shadows-core-3.1-SNAPSHOT-17.jar
deleted file mode 100644
index dd75cdd48..000000000
--- a/v3/runtime/shadows-core-3.1-SNAPSHOT-17.jar
+++ /dev/null
Binary files differ
diff --git a/v3/runtime/shadows-core-3.1-SNAPSHOT-18.jar b/v3/runtime/shadows-core-3.1-SNAPSHOT-18.jar
deleted file mode 100644
index 1f95b992b..000000000
--- a/v3/runtime/shadows-core-3.1-SNAPSHOT-18.jar
+++ /dev/null
Binary files differ
diff --git a/v3/runtime/shadows-core-3.1-SNAPSHOT-19.jar b/v3/runtime/shadows-core-3.1-SNAPSHOT-19.jar
deleted file mode 100644
index 1dc68cdf7..000000000
--- a/v3/runtime/shadows-core-3.1-SNAPSHOT-19.jar
+++ /dev/null
Binary files differ
diff --git a/v3/runtime/shadows-core-3.1-SNAPSHOT-21.jar b/v3/runtime/shadows-core-3.1-SNAPSHOT-21.jar
deleted file mode 100644
index 06b2046b9..000000000
--- a/v3/runtime/shadows-core-3.1-SNAPSHOT-21.jar
+++ /dev/null
Binary files differ
diff --git a/v3/runtime/shadows-core-3.1-SNAPSHOT-22.jar b/v3/runtime/shadows-core-3.1-SNAPSHOT-22.jar
deleted file mode 100644
index 1847a0d8a..000000000
--- a/v3/runtime/shadows-core-3.1-SNAPSHOT-22.jar
+++ /dev/null
Binary files differ
diff --git a/v3/runtime/tagsoup-1.2.jar b/v3/runtime/tagsoup-1.2.jar
deleted file mode 100644
index af27803ec..000000000
--- a/v3/runtime/tagsoup-1.2.jar
+++ /dev/null
Binary files differ
diff --git a/v3/shadows-httpclient-3.1-SNAPSHOT.jar b/v3/shadows-httpclient-3.1-SNAPSHOT.jar
deleted file mode 100644
index ca48468c8..000000000
--- a/v3/shadows-httpclient-3.1-SNAPSHOT.jar
+++ /dev/null
Binary files differ
diff --git a/v3/shadows-multidex-3.1-SNAPSHOT.jar b/v3/shadows-multidex-3.1-SNAPSHOT.jar
deleted file mode 100644
index 75170b0bf..000000000
--- a/v3/shadows-multidex-3.1-SNAPSHOT.jar
+++ /dev/null
Binary files differ
diff --git a/v3/shadows-play-services-3.1-SNAPSHOT.jar b/v3/shadows-play-services-3.1-SNAPSHOT.jar
deleted file mode 100644
index ff6d3a391..000000000
--- a/v3/shadows-play-services-3.1-SNAPSHOT.jar
+++ /dev/null
Binary files differ
diff --git a/v3/shadows-support-v4-3.1-SNAPSHOT.jar b/v3/shadows-support-v4-3.1-SNAPSHOT.jar
deleted file mode 100644
index 9ee4e4487..000000000
--- a/v3/shadows-support-v4-3.1-SNAPSHOT.jar
+++ /dev/null
Binary files differ
diff --git a/v3/update_robolectric.sh b/v3/update_robolectric.sh
deleted file mode 100755
index 0dc8ef4cd..000000000
--- a/v3/update_robolectric.sh
+++ /dev/null
@@ -1,31 +0,0 @@
-# Script to update robolectric with an up to date snapshot.
-#
-# 1) Build and install Robolectric to your local mvn repository.
-# ./install-robolectric.sh
-#
-# 2) Create an Android repo
-#
-# 3) Run this script from $ANDROID_ROOT_DIR
-# ./external/robolectric/v3/update_robolectric.sh
-
-MVN_ROOT=$HOME/.m2/repository
-ROBOLECTRIC_DIR=external/robolectric/v3
-
-cp $MVN_ROOT/org/robolectric/robolectric/3.1-SNAPSHOT/robolectric-3.1-SNAPSHOT.jar $ROBOLECTRIC_DIR/.
-cp $MVN_ROOT/org/robolectric/robolectric-annotations/3.1-SNAPSHOT/robolectric-annotations-3.1-SNAPSHOT.jar $ROBOLECTRIC_DIR/.
-cp $MVN_ROOT/org/robolectric/robolectric-processor/3.1-SNAPSHOT/robolectric-processor-3.1-SNAPSHOT.jar $ROBOLECTRIC_DIR/.
-cp $MVN_ROOT/org/robolectric/robolectric-resources/3.1-SNAPSHOT/robolectric-resources-3.1-SNAPSHOT.jar $ROBOLECTRIC_DIR/.
-cp $MVN_ROOT/org/robolectric/robolectric-utils/3.1-SNAPSHOT/robolectric-utils-3.1-SNAPSHOT.jar $ROBOLECTRIC_DIR/.
-
-cp $MVN_ROOT/org/robolectric/shadows-httpclient/3.1-SNAPSHOT/shadows-httpclient-3.1-SNAPSHOT.jar $ROBOLECTRIC_DIR/.
-cp $MVN_ROOT/org/robolectric/shadows-support-v4/3.1-SNAPSHOT/shadows-support-v4-3.1-SNAPSHOT.jar $ROBOLECTRIC_DIR/.
-cp $MVN_ROOT/org/robolectric/shadows-multidex/3.1-SNAPSHOT/shadows-multidex-3.1-SNAPSHOT.jar $ROBOLECTRIC_DIR/.
-
-cp $MVN_ROOT/org/robolectric/shadows-play-services/3.1-SNAPSHOT/shadows-play-services-3.1-SNAPSHOT.jar $ROBOLECTRIC_DIR/.
-
-cp $MVN_ROOT/org/robolectric/shadows-core/3.1-SNAPSHOT/shadows-core-3.1-SNAPSHOT-16.jar $ROBOLECTRIC_DIR/runtime/.
-cp $MVN_ROOT/org/robolectric/shadows-core/3.1-SNAPSHOT/shadows-core-3.1-SNAPSHOT-17.jar $ROBOLECTRIC_DIR/runtime/.
-cp $MVN_ROOT/org/robolectric/shadows-core/3.1-SNAPSHOT/shadows-core-3.1-SNAPSHOT-18.jar $ROBOLECTRIC_DIR/runtime/.
-cp $MVN_ROOT/org/robolectric/shadows-core/3.1-SNAPSHOT/shadows-core-3.1-SNAPSHOT-19.jar $ROBOLECTRIC_DIR/runtime/.
-cp $MVN_ROOT/org/robolectric/shadows-core/3.1-SNAPSHOT/shadows-core-3.1-SNAPSHOT-21.jar $ROBOLECTRIC_DIR/runtime/.
-cp $MVN_ROOT/org/robolectric/shadows-core/3.1-SNAPSHOT/shadows-core-3.1-SNAPSHOT-22.jar $ROBOLECTRIC_DIR/runtime/.