method2testcases
stringlengths 118
3.08k
|
---|
### Question:
Registrar { void registerBindable(Bindable bindable) { bindables().register(bindable); } Registrar(Register<Connectable> connectables, Register<Disconnectable> disconnectables, Register<Bindable> bindables); }### Answer:
@Test(expected = IllegalStateException.class) public void givenMissingRegister_whenRegisteringBindable_thenThrowsIllegalStateException() { registrar = new Registrar(null, null, null); Bindable bindable = mock(Bindable.class); registrar.registerBindable(bindable); }
@Test public void givenRegister_whenRegisteringBindable_thenRegistersBindableWithBinder() { Bindable bindable = mock(Bindable.class); registrar.registerBindable(bindable); verify(bindables).register(bindable); } |
### Question:
MerlinsBeard { public boolean isConnected() { NetworkInfo activeNetworkInfo = networkInfo(); return activeNetworkInfo != null && activeNetworkInfo.isConnected(); } MerlinsBeard(ConnectivityManager connectivityManager, AndroidVersion androidVersion, EndpointPinger captivePortalPinger, Ping CaptivePortalPing); @Deprecated static MerlinsBeard from(Context context); boolean isConnected(); boolean isConnectedToMobileNetwork(); boolean isConnectedToWifi(); String getMobileNetworkSubtypeName(); void hasInternetAccess(final InternetAccessCallback callback); @WorkerThread boolean hasInternetAccess(); }### Answer:
@Test public void givenNetworkIsDisconnected_whenCheckingForConnectivity_thenReturnsFalse() { given(connectivityManager.getActiveNetworkInfo()).willReturn(networkInfo); given(networkInfo.isConnected()).willReturn(DISCONNECTED); boolean connected = merlinsBeard.isConnected(); assertThat(connected).isFalse(); }
@Test public void givenNetworkIsNull_whenCheckingForConnectivity_thenReturnsFalse() { given(connectivityManager.getActiveNetworkInfo()).willReturn(null); boolean connected = merlinsBeard.isConnected(); assertThat(connected).isFalse(); }
@Test public void givenNetworkIsConnected_whenCheckingForConnectivity_thenReturnsTrue() { given(connectivityManager.getActiveNetworkInfo()).willReturn(networkInfo); given(networkInfo.isConnected()).willReturn(CONNECTED); boolean connected = merlinsBeard.isConnected(); assertThat(connected).isTrue(); } |
### Question:
DisconnectCallbackManager extends MerlinCallbackManager<Disconnectable> implements Disconnectable { @Override public void onDisconnect() { Logger.d("onDisconnect"); for (Disconnectable disconnectable : registerables()) { disconnectable.onDisconnect(); } } DisconnectCallbackManager(Register<Disconnectable> register); @Override void onDisconnect(); }### Answer:
@Test public void givenRegisteredDisconnectable_whenCallingOnDisconect_thenCallsDisconnectForDisconnectable() { Disconnectable disconnectable = givenRegisteredDisconnectable(); disconnectCallbackManager.onDisconnect(); verify(disconnectable).onDisconnect(); }
@Test public void givenMultipleRegisteredDisconnectables_whenCallingOnConnect_thenCallsConnectForAllDisconnectables() { List<Disconnectable> disconnectables = givenMultipleRegisteredDisconnectables(); disconnectCallbackManager.onDisconnect(); for (Disconnectable disconnectable : disconnectables) { verify(disconnectable).onDisconnect(); } } |
### Question:
ConnectCallbackManager extends MerlinCallbackManager<Connectable> { void onConnect() { Logger.d("onConnect"); for (Connectable connectable : registerables()) { connectable.onConnect(); } } ConnectCallbackManager(Register<Connectable> register); }### Answer:
@Test public void givenRegisteredConnectable_whenCallingOnConnect_thenCallsConnectForConnectable() { Connectable connectable = givenRegisteredConnectable(); connectCallbackManager.onConnect(); verify(connectable).onConnect(); }
@Test public void givenMultipleRegisteredConnectables_whenCallingOnConnect_thenCallsConnectForAllConnectables() { List<Connectable> connectables = givenMultipleRegisteredConnectables(); connectCallbackManager.onConnect(); for (Connectable connectable : connectables) { verify(connectable).onConnect(); } }
@Test public void givenRegisteredConnectable_whenCallingOnConnectAndAddingConnectable_thenCallsConnectForConnectable() { Connectable connectable = givenRegisteredConnectableModifyingConnectables(); connectCallbackManager.onConnect(); verify(connectable).onConnect(); } |
### Question:
MerlinService extends Service { public static boolean isBound() { return isBound; } static boolean isBound(); @Override IBinder onBind(Intent intent); @Override boolean onUnbind(Intent intent); }### Answer:
@Test public void givenOnBindHasBeenCalled_whenCheckingIsBound_thenReturnsTrue() { givenBoundMerlinService(); boolean bound = MerlinService.isBound(); assertThat(bound).isTrue(); } |
### Question:
MerlinService extends Service { @Override public boolean onUnbind(Intent intent) { isBound = false; if (connectivityChangesRegister != null) { connectivityChangesRegister.unregister(); connectivityChangesRegister = null; } if (connectivityChangesForwarder != null) { connectivityChangesForwarder = null; } binder = null; return super.onUnbind(intent); } static boolean isBound(); @Override IBinder onBind(Intent intent); @Override boolean onUnbind(Intent intent); }### Answer:
@Test public void givenBoundMerlinService_whenCallingOnUnbind_thenUnregistersConnectivityChangesRegister() { givenBoundMerlinService(); merlinService.onUnbind(intent); verify(connectivityChangesRegister).unregister(); }
@Test public void givenUnboundService_whenNotifying_thenDoesNotForwardEvent() { MerlinService.LocalBinder localBinder = givenBoundMerlinService(); merlinService.onUnbind(null); localBinder.notify(ANY_CONNECTIVITY_CHANGE_EVENT); verifyZeroInteractions(connectivityChangesForwarder); } |
### Question:
MerlinService extends Service { @Override public IBinder onBind(Intent intent) { isBound = true; return binder; } static boolean isBound(); @Override IBinder onBind(Intent intent); @Override boolean onUnbind(Intent intent); }### Answer:
@Test public void givenConnectivityChangesRegisterIsNotBound_whenBindCompletes_thenThrowsException_andStopsWorkOnService() { thrown.expect(MerlinServiceDependencyMissingExceptionMatcher.from(ConnectivityChangesRegister.class)); MerlinService.LocalBinder binder = (MerlinService.LocalBinder) merlinService.onBind(intent); binder.setConnectivityChangesForwarder(connectivityChangesForwarder); binder.onBindComplete(); verifyZeroInteractions(connectivityChangesRegister); verifyZeroInteractions(connectivityChangesForwarder); }
@Test public void givenConnectivityChangesForwarderIsNotBound_whenBindCompletes_thenThrowsException_andStopsWorkOnService() { thrown.expect(MerlinServiceDependencyMissingExceptionMatcher.from(ConnectivityChangesForwarder.class)); MerlinService.LocalBinder binder = (MerlinService.LocalBinder) merlinService.onBind(intent); binder.setConnectivityChangesRegister(connectivityChangesRegister); binder.onBindComplete(); verifyZeroInteractions(connectivityChangesRegister); verifyZeroInteractions(connectivityChangesForwarder); } |
### Question:
ConnectivityCallbacks extends ConnectivityManager.NetworkCallback { @Override public void onAvailable(Network network) { notifyMerlinService(network); } ConnectivityCallbacks(MerlinService.ConnectivityChangesNotifier connectivityChangesNotifier,
ConnectivityChangeEventExtractor connectivityChangeEventExtractor); @Override void onAvailable(Network network); @Override void onLosing(Network network, int maxMsToLive); @Override void onLost(Network network); }### Answer:
@Test public void givenConnectedNetworkInfo_whenNetworkIsAvailable_thenNotifiesOfConnectedNetwork() { NetworkInfo networkInfo = givenNetworkInfoWith(CONNECTED, ANY_REASON, ANY_EXTRA_INFO); networkCallbacks.onAvailable(network); verify(connectivityChangesNotifier).notify(ConnectivityChangeEvent.createWithNetworkInfoChangeEvent( networkInfo.isConnected(), networkInfo.getExtraInfo(), networkInfo.getReason() )); }
@Test public void givenNoNetworkInfo_whenNetworkIsAvailable_thenNotifiesOfConnectedNetwork() { networkCallbacks.onAvailable(network); verify(connectivityChangesNotifier).notify(ConnectivityChangeEvent.createWithoutConnection()); }
@Test public void givenCannotNotify_whenNetworkIsAvailable_thenNeverNotifiesConnectivityChangeEvent() { given(connectivityChangesNotifier.canNotify()).willReturn(CANNOT_NOTIFY); networkCallbacks.onAvailable(MISSING_NETWORK); InOrder inOrder = inOrder(connectivityChangesNotifier); inOrder.verify(connectivityChangesNotifier).canNotify(); inOrder.verifyNoMoreInteractions(); } |
### Question:
ConnectivityCallbacks extends ConnectivityManager.NetworkCallback { @Override public void onLosing(Network network, int maxMsToLive) { notifyMerlinService(network); } ConnectivityCallbacks(MerlinService.ConnectivityChangesNotifier connectivityChangesNotifier,
ConnectivityChangeEventExtractor connectivityChangeEventExtractor); @Override void onAvailable(Network network); @Override void onLosing(Network network, int maxMsToLive); @Override void onLost(Network network); }### Answer:
@Test public void givenDisconnectedNetworkInfo_whenLosingNetwork_thenNotifiesOfDisconnectedNetwork() { NetworkInfo networkInfo = givenNetworkInfoWith(DISCONNECTED, ANY_REASON, ANY_EXTRA_INFO); networkCallbacks.onLosing(network, MAX_MS_TO_LIVE); verify(connectivityChangesNotifier).notify(ConnectivityChangeEvent.createWithNetworkInfoChangeEvent( networkInfo.isConnected(), networkInfo.getExtraInfo(), networkInfo.getReason() )); }
@Test public void givenNoNetworkInfo_whenLosingNetwork_thenNotifiesOfDisconnectedNetwork() { networkCallbacks.onLosing(network, MAX_MS_TO_LIVE); verify(connectivityChangesNotifier).notify(ConnectivityChangeEvent.createWithoutConnection()); }
@Test public void givenCannotNotify_whenLosingNetwork_thenNeverNotifiesConnectivityChangeEvent() { given(connectivityChangesNotifier.canNotify()).willReturn(CANNOT_NOTIFY); networkCallbacks.onLosing(MISSING_NETWORK, MAX_MS_TO_LIVE); InOrder inOrder = inOrder(connectivityChangesNotifier); inOrder.verify(connectivityChangesNotifier).canNotify(); inOrder.verifyNoMoreInteractions(); } |
### Question:
ConnectivityCallbacks extends ConnectivityManager.NetworkCallback { @Override public void onLost(Network network) { notifyMerlinService(network); } ConnectivityCallbacks(MerlinService.ConnectivityChangesNotifier connectivityChangesNotifier,
ConnectivityChangeEventExtractor connectivityChangeEventExtractor); @Override void onAvailable(Network network); @Override void onLosing(Network network, int maxMsToLive); @Override void onLost(Network network); }### Answer:
@Test public void givenDisconnectedNetworkInfo_whenNetworkIsLost_thenNotifiesOfLostNetwork() { NetworkInfo networkInfo = givenNetworkInfoWith(DISCONNECTED, ANY_REASON, ANY_EXTRA_INFO); networkCallbacks.onLost(network); verify(connectivityChangesNotifier).notify(ConnectivityChangeEvent.createWithNetworkInfoChangeEvent( networkInfo.isConnected(), networkInfo.getExtraInfo(), networkInfo.getReason() )); }
@Test public void givenNoNetworkInfo_whenNetworkIsLost_thenNotifiesOfLostNetwork() { networkCallbacks.onLost(network); verify(connectivityChangesNotifier).notify(ConnectivityChangeEvent.createWithoutConnection()); }
@Test public void givenCannotNotify_whenNetworkIsLost_thenNeverNotifiesConnectivityChangeEvent() { given(connectivityChangesNotifier.canNotify()).willReturn(CANNOT_NOTIFY); networkCallbacks.onLost(MISSING_NETWORK); InOrder inOrder = inOrder(connectivityChangesNotifier); inOrder.verify(connectivityChangesNotifier).canNotify(); inOrder.verifyNoMoreInteractions(); } |
### Question:
MerlinObservable { public static Observable<NetworkStatus> from(Context context) { return from(context, new Merlin.Builder()); } static Observable<NetworkStatus> from(Context context); static Observable<NetworkStatus> from(Context context, MerlinBuilder merlinBuilder); static Observable<NetworkStatus> from(Merlin merlin); }### Answer:
@Test public void unbindWhenUnsubscribed() { Subscription subscription = MerlinObservable.from(merlin) .subscribe(); subscription.unsubscribe(); verify(merlin).unbind(); }
@Test public void notCrashWhenCreatingWithAMerlinBuilderWithoutCallbacks() { Context context = mock(Context.class); Merlin.Builder merlinBuilder = new Merlin.Builder(); MerlinObservable.from(context, merlinBuilder).subscribe(); } |
### Question:
OktaManagementActivity extends Activity { static PendingIntent createStartIntent( Context context, PendingIntent completeIntent, PendingIntent cancelIntent) { Intent tokenExchangeIntent = new Intent(context, OktaManagementActivity.class); tokenExchangeIntent.putExtra(KEY_COMPLETE_INTENT, completeIntent); tokenExchangeIntent.putExtra(KEY_CANCEL_INTENT, cancelIntent); return PendingIntent.getActivity(context, 0, tokenExchangeIntent, PendingIntent.FLAG_UPDATE_CURRENT); } }### Answer:
@Test public void testOnCreateShouldExtractStateFromIntent() throws JSONException { OktaManagementActivity activity = Robolectric.buildActivity( OktaManagementActivity.class, createStartIntent() ).create().get(); assertThat(activity.mCompleteIntent).isEqualTo(this.mCompleteIntent); assertThat(activity.mCancelIntent).isEqualTo(this.mCancelIntent); }
@Test public void testOnStartShouldSignOutIfConfigurationHasChanged() throws CanceledException, JSONException { Context context = RuntimeEnvironment.application.getApplicationContext(); new OAuthClientConfiguration( context, context.getSharedPreferences(OAuthClientConfiguration.PREFS_NAME, MODE_PRIVATE), ConfigurationStreams.getOtherConfiguration() ); doNothing().when(mCancelIntent).send(); OktaManagementActivity activity = Robolectric.buildActivity( OktaManagementActivity.class ).newIntent(createStartIntent()).create().start().get(); assertThat(activity.isFinishing()).isTrue(); }
@Test public void testOnStartShouldCompleteIfStateIsAuthorized() throws CanceledException, JSONException { Context context = RuntimeEnvironment.application.getApplicationContext(); AuthStateManager stateManager = AuthStateManager.getInstance(context); stateManager.replace(mAuthState); when(mAuthState.isAuthorized()).thenReturn(true); doNothing().when(mCompleteIntent).send(); OktaManagementActivity activity = Robolectric.buildActivity( OktaManagementActivity.class, createStartIntent() ).create().start().get(); assertThat(activity.isFinishing()).isTrue(); } |
### Question:
AuthStateManager { @AnyThread @NonNull @VisibleForTesting AuthState readState() { mPrefsLock.lock(); try { String currentState = mPrefs.getString(KEY_STATE, null); if (currentState == null) { return new AuthState(); } try { return AuthState.jsonDeserialize(currentState); } catch (JSONException ex) { Log.w(TAG, "Failed to deserialize stored auth state - discarding"); return new AuthState(); } } finally { mPrefsLock.unlock(); } } @VisibleForTesting AuthStateManager(SharedPreferences prefs, ReentrantLock prefsLock); @AnyThread static AuthStateManager getInstance(@NonNull Context context); @AnyThread @NonNull AuthState getCurrent(); @AnyThread @NonNull AuthState replace(@NonNull AuthState state); @AnyThread @NonNull AuthState updateAfterAuthorization(
@Nullable AuthorizationResponse response,
@Nullable AuthorizationException ex); @AnyThread @NonNull AuthState updateAfterTokenResponse(
@Nullable TokenResponse response,
@Nullable AuthorizationException ex); }### Answer:
@Test public void testReadStateLocksPreferencesBeforeActing() { assertThat(mPrefs.contains(KEY_STATE)).isFalse(); mPrefsLock.lock(); try { sut.readState(); fail("Expected " + IllegalStateException.class.getSimpleName() + " to be thrown"); } catch (IllegalStateException e) { assertThat(mPrefsLock.getHoldCount()).isEqualTo(1); } mPrefsLock.unlock(); assertThat(sut.readState()).isNotNull(); assertThat(mPrefsLock.getHoldCount()).isEqualTo(0); assertThat(mPrefs.contains(KEY_STATE)).isFalse(); } |
### Question:
AuthStateManager { @AnyThread @VisibleForTesting void writeState(@Nullable AuthState state) { mPrefsLock.lock(); try { SharedPreferences.Editor editor = mPrefs.edit(); if (state == null) { editor.remove(KEY_STATE); } else { editor.putString(KEY_STATE, state.jsonSerializeString()); } if (!editor.commit()) { throw new IllegalStateException("Failed to write state to shared prefs"); } } finally { mPrefsLock.unlock(); } } @VisibleForTesting AuthStateManager(SharedPreferences prefs, ReentrantLock prefsLock); @AnyThread static AuthStateManager getInstance(@NonNull Context context); @AnyThread @NonNull AuthState getCurrent(); @AnyThread @NonNull AuthState replace(@NonNull AuthState state); @AnyThread @NonNull AuthState updateAfterAuthorization(
@Nullable AuthorizationResponse response,
@Nullable AuthorizationException ex); @AnyThread @NonNull AuthState updateAfterTokenResponse(
@Nullable TokenResponse response,
@Nullable AuthorizationException ex); }### Answer:
@Test public void testWriteStateLocksPreferencesBeforeActing() { assertThat(mPrefs.contains(KEY_STATE)).isFalse(); mPrefsLock.lock(); try { sut.writeState(new AuthState()); fail("Expected " + IllegalStateException.class.getSimpleName() + " to be thrown"); } catch (IllegalStateException e) { assertThat(mPrefsLock.getHoldCount()).isEqualTo(1); assertThat(mPrefs.contains(KEY_STATE)).isFalse(); } mPrefsLock.unlock(); sut.writeState(new AuthState()); assertThat(mPrefsLock.getHoldCount()).isEqualTo(0); assertThat(mPrefs.getString(KEY_STATE, null)).isNotNull(); }
@Test public void testWriteStateRemovesKeyWhenWritingNull() { sut.writeState(new AuthState()); assertThat(mPrefs.getString(KEY_STATE, null)).isNotNull(); sut.writeState(null); assertThat(mPrefs.contains(KEY_STATE)).isFalse(); } |
### Question:
SessionAuthenticationService { void performAuthorizationRequest( AuthorizationRequest request, String sessionToken, @Nullable OktaAppAuth.OktaNativeAuthListener listener) { if (sessionToken == null) { if (listener != null) { listener.onTokenFailure(AuthenticationError.createAuthenticationError( AuthenticationError.INVALID_SESSION_TOKEN, 0)); } return; } Map<String, String> additionalParameters = new HashMap<String, String>(); if (request.additionalParameters != null && !request.additionalParameters.isEmpty()) { additionalParameters.putAll(request.additionalParameters); } additionalParameters.put(SESSION_TOKEN_PARAMETER, sessionToken); AuthorizationRequest.Builder authRequestBuilder = new AuthorizationRequest.Builder( request.configuration, request.clientId, request.responseType, request.redirectUri) .setNonce(request.nonce) .setScopes(request.getScopeSet()) .setAdditionalParameters(additionalParameters); AuthenticationResult<AuthorizationResponse> authorizationResult = getAuthorizationCode( authRequestBuilder.build()); if (authorizationResult.getResponse() == null || authorizationResult.getResponse().authorizationCode == null) { if (listener != null) { listener.onTokenFailure(authorizationResult.getException()); } return; } AuthenticationResult<TokenResponse> tokenResponse = exchangeCodeForTokens( authorizationResult.getResponse()); if (!mStateManager.getCurrent().isAuthorized()) { if (listener != null) { listener.onTokenFailure(tokenResponse.getException()); } } else { if (listener != null) { listener.onSuccess(); } } } SessionAuthenticationService(
AuthStateManager manager,
AuthorizationService authorizationService,
ConnectionBuilder connectionBuilder); }### Answer:
@Test public void testInValidCredentialsPerformAuthorizationRequest() { FakeNativeOktaAuthListener listener = new FakeNativeOktaAuthListener(); sessionAuthenticationService.performAuthorizationRequest(request, null, listener); assertTrue(listener.hasCalledOnTokenFailure()); }
@Test public void testNullListenerPerformAuthorizationRequest() { sessionAuthenticationService.performAuthorizationRequest(request, VALID_SESSION, null); sessionAuthenticationService.performAuthorizationRequest(request, null, null); } |
### Question:
OAuthClientConfiguration { public String getClientId() { return mClientId; } @VisibleForTesting OAuthClientConfiguration(
final Context context,
final SharedPreferences prefs,
final InputStream configurationStream); @AnyThread static OAuthClientConfiguration getInstance(final Context context); boolean hasConfigurationChanged(); void acceptConfiguration(); boolean isValid(); @Nullable String getConfigurationError(); String getClientId(); Uri getRedirectUri(); Uri getEndSessionRedirectUri(); Uri getDiscoveryUri(); Set<String> getScopes(); }### Answer:
@Test public void testGetClientId() { assertThat(sut.getClientId()).isEqualTo("example_client_id"); } |
### Question:
OAuthClientConfiguration { public Uri getRedirectUri() { return mRedirectUri; } @VisibleForTesting OAuthClientConfiguration(
final Context context,
final SharedPreferences prefs,
final InputStream configurationStream); @AnyThread static OAuthClientConfiguration getInstance(final Context context); boolean hasConfigurationChanged(); void acceptConfiguration(); boolean isValid(); @Nullable String getConfigurationError(); String getClientId(); Uri getRedirectUri(); Uri getEndSessionRedirectUri(); Uri getDiscoveryUri(); Set<String> getScopes(); }### Answer:
@Test public void getRedirectUri() { assertThat(sut.getRedirectUri()).isEqualTo( Uri.parse("com.okta.appauth.android.test:/oauth2redirect")); } |
### Question:
OAuthClientConfiguration { public Uri getDiscoveryUri() { return mDiscoveryUri; } @VisibleForTesting OAuthClientConfiguration(
final Context context,
final SharedPreferences prefs,
final InputStream configurationStream); @AnyThread static OAuthClientConfiguration getInstance(final Context context); boolean hasConfigurationChanged(); void acceptConfiguration(); boolean isValid(); @Nullable String getConfigurationError(); String getClientId(); Uri getRedirectUri(); Uri getEndSessionRedirectUri(); Uri getDiscoveryUri(); Set<String> getScopes(); }### Answer:
@Test public void testGetDiscoveryUriAppendsWellKnownDiscovery() { assertThat(sut.getDiscoveryUri()).isEqualTo( Uri.parse("https: ); } |
### Question:
OAuthClientConfiguration { public Set<String> getScopes() { return mScopes; } @VisibleForTesting OAuthClientConfiguration(
final Context context,
final SharedPreferences prefs,
final InputStream configurationStream); @AnyThread static OAuthClientConfiguration getInstance(final Context context); boolean hasConfigurationChanged(); void acceptConfiguration(); boolean isValid(); @Nullable String getConfigurationError(); String getClientId(); Uri getRedirectUri(); Uri getEndSessionRedirectUri(); Uri getDiscoveryUri(); Set<String> getScopes(); }### Answer:
@Test public void testGetScopes() { assertThat(sut.getScopes()).contains("openid", "foo"); } |
### Question:
AuthStateManager { @AnyThread @NonNull public AuthState getCurrent() { if (mCurrentAuthState.get() != null) { return mCurrentAuthState.get(); } AuthState state = readState(); if (mCurrentAuthState.compareAndSet(null, state)) { return state; } else { return mCurrentAuthState.get(); } } @VisibleForTesting AuthStateManager(SharedPreferences prefs, ReentrantLock prefsLock); @AnyThread static AuthStateManager getInstance(@NonNull Context context); @AnyThread @NonNull AuthState getCurrent(); @AnyThread @NonNull AuthState replace(@NonNull AuthState state); @AnyThread @NonNull AuthState updateAfterAuthorization(
@Nullable AuthorizationResponse response,
@Nullable AuthorizationException ex); @AnyThread @NonNull AuthState updateAfterTokenResponse(
@Nullable TokenResponse response,
@Nullable AuthorizationException ex); }### Answer:
@Test public void testGetCurrentCachesState() { AuthState state = sut.getCurrent(); assertThat(sut.getCurrent()).isSameAs(state); assertThat(mPrefs.contains(KEY_STATE)).isFalse(); } |
### Question:
FileNameAuthorScoreStrategy implements ScoreStrategy<AuthorScore> { private Author extractAuthorFromFileName(String fileName) { Assert.isTrue(fileName.contains(SEPARATOR), "Format in " + fileName + " not understood, doesn't contain separator"); String authorIncludingSpecialCharacters = extractAuthorPart(fileName); String[] tokens = splitFirstnameAndLastname(authorIncludingSpecialCharacters); Name name = new PersonNameCategorizer().categorize(tokens); return new Author(name.getFirstName(), name.getLastName()); } @NotNull @Override AuthorScore score(BookImportContext context); static final String SEPARATOR; static final Pattern NAME_PATTERN; }### Answer:
@Test public void testExtractAuthorFromFileName() throws Exception { BookImportContext bookImportContext = createMock(BookImportContext.class); File mock = createMock(File.class); expect(mock.getName()).andReturn("Abbott, Megan - Dare Me.epub"); expect(bookImportContext.getFile()).andReturn(mock); replayAll(); Score<List<Author>> authorScores = new FileNameAuthorScoreStrategy().score(bookImportContext); List<Author> authors = authorScores.getValue(); verifyAll(); assertThat(authors, contains(new Author("Megan", "Abbott"))); assertThat(authorScores.getScore(), is(1.0)); } |
### Question:
FileNameAuthorScoreStrategy implements ScoreStrategy<AuthorScore> { @NotNull @Override public AuthorScore score(BookImportContext context) { return new AuthorScore(getAuthors(context.getFile()), FileNameAuthorScoreStrategy.class); } @NotNull @Override AuthorScore score(BookImportContext context); static final String SEPARATOR; static final Pattern NAME_PATTERN; }### Answer:
@Test public void testExtractAuthorFromOtherFileName() throws Exception { BookImportContext bookImportContext = createMock(BookImportContext.class); File mock = createMock(File.class); expect(mock.getName()).andReturn("P. L. Travers - Mary Poppins From A to Z(epub).epub"); expect(bookImportContext.getFile()).andReturn(mock); replayAll(); Score<List<Author>> authorScores = new FileNameAuthorScoreStrategy().score(bookImportContext); List<Author> authors = authorScores.getValue(); verifyAll(); assertThat(authors, hasItems(new Author("P. L.", "Travers"))); assertThat(authorScores.getScore(), is(1.0)); }
@Test public void testExtractAuthorFromOnlyLastname() throws Exception { BookImportContext bookImportContext = createMock(BookImportContext.class); File mock = createMock(File.class); expect(mock.getName()).andReturn("Travers - Mary Poppins From A to Z(epub).epub"); expect(bookImportContext.getFile()).andReturn(mock); replayAll(); Score<List<Author>> authorScores = new FileNameAuthorScoreStrategy().score(bookImportContext); List<Author> authors = authorScores.getValue(); double value = authorScores.getScore(); verifyAll(); assertThat(authors, hasItems(new Author("", "Travers"))); assertThat(authorScores.getScore(), is(1.0)); } |
### Question:
MetaDataAuthorScoreStrategy implements ScoreStrategy<AuthorScore> { @NotNull @Override public AuthorScore score(BookImportContext context) { try { List<nl.siegmann.epublib.domain.Author> epubAuthors = context.getEpubBook().getMetadata().getAuthors(); AuthorScore categorizerScore = getAuthorScoreUsingCategorizer(epubAuthors); AuthorScore metaDataScore = getAuthorScoreUsingPlainMetaData(epubAuthors); Ordering<AuthorScore> o = new Ordering<AuthorScore>() { @Override public int compare(AuthorScore left, AuthorScore right) { return Doubles.compare(left.getScore(), right.getScore()); } }; return o.max(Arrays.asList(categorizerScore, metaDataScore)); } catch (Exception e) { log.error("Could not determine score for {}", context); return new AuthorScore(Collections.<Author>emptyList(), MetaDataAuthorScoreStrategy.class); } } @NotNull @Override AuthorScore score(BookImportContext context); }### Answer:
@Test public void extractAuthorFromMetaData() { File file = new File("src/test/resources/epubs/Alexandre Dumas - The countess of Charney.epub"); BookImportContext bookImportContext = new BookImportContext(file); Score<List<Author>> authorScores = new MetaDataAuthorScoreStrategy().score(bookImportContext); List<Author> authors = authorScores.getValue(); assertThat(authors, hasItems(new Author("Alexandre", "Dumas"))); assertThat(authorScores.getScore(), is(1.0)); } |
### Question:
MetaDataIsbn13ScoreStrategy implements ScoreStrategy<Isbn13Score> { @NotNull @Override public Isbn13Score score(BookImportContext context) { Book epubBook = context.getEpubBook(); Metadata metadata = epubBook.getMetadata(); Isbn13Score isbn13UsingScheme = getIsbn13(metadata); if(isbn13UsingScheme == null) { return new Isbn13Score("", "", MetaDataIsbn13ScoreStrategy.class); } return isbn13UsingScheme; } @NotNull @Override Isbn13Score score(BookImportContext context); static final int ISBN_LENGTH; }### Answer:
@Test public void testIsbn() { MetaDataIsbn13ScoreStrategy strategy = new MetaDataIsbn13ScoreStrategy(); BookImportContext importContext = new BookBuilder().isbn("1234567890123").buildContext(); Isbn13Score score = strategy.score(importContext); assertThat(score.getValue(), is("1234567890123")); assertThat(score.getScore(), is(1.0)); } |
### Question:
MetaDataIsbn10ScoreStrategy implements ScoreStrategy<Isbn10Score> { @NotNull @Override public Isbn10Score score(BookImportContext context) { Book epubBook = context.getEpubBook(); Metadata metadata = epubBook.getMetadata(); Isbn10Score isbn10UsingScheme = getIsbn10(metadata); if (isbn10UsingScheme == null) { return new Isbn10Score("", "", MetaDataIsbn10ScoreStrategy.class); } return isbn10UsingScheme; } @NotNull @Override Isbn10Score score(BookImportContext context); static final int ISBN_LENGTH; }### Answer:
@Test public void testIsbn() { MetaDataIsbn10ScoreStrategy strategy = new MetaDataIsbn10ScoreStrategy(); BookImportContext importContext = new BookBuilder().isbn("1234567890").buildContext(); Isbn10Score score = strategy.score(importContext); assertThat(score.getValue(), is("1234567890")); assertThat(score.getScore(), is(1.0)); } |
### Question:
BookProducer { public Book produce(BookImportContext context) throws IOException { Book book = new Book(); book.setAuthors(new AuthorScorer().determineBestScore(context).getValue()); book.setSource("import"); book.setTitle(new TitleScorer().determineBestScore(context).getValue()); book.setLanguage((new LanguageScorer().determineBestScore(context).getValue())); book.setIsbn10(new Isbn10Scorer().determineBestScore(context).getValue()); book.setIsbn13(new Isbn13Scorer().determineBestScore(context).getValue()); book.setSummary(new SummaryScorer().determineBestScore(context).getValue()); book.setPublisher(new PublisherScorer().determineBestScore(context).getValue()); book.setPublicationDate(new PublicationDateScorer().determineBestScore(context).getValue()); book.setTags(new TagsScorer().determineBestScore(context).getValue()); Binary epub = getBinaryFromFile(context); book.setEpub(epub); book.setFileSizeInKb(epub.getContents().length / 1024); book.setCover(new CoverScorer().determineBestScore(context).getValue()); book.setContents(getContent(context.getEpubBook().getContents()) ); log.info("Produced book {}", book); return book; } Book produce(BookImportContext context); }### Answer:
@Test public void testEnrichBooks() throws Exception { BookImportContext bookImportContext = new BookImportContext(new File("src/test/resources/epubs/W. H. Davenport Adams - Some heroes of Travel.epub")); Book book = new BookProducer().produce(bookImportContext); assertThat(book.getFirstAuthor(), is(new Author("Davenport", "Adams W. H."))); } |
### Question:
Response { public int getCode() { return code; } int getCode(); Response setCode(int code); InputStream getData(); Response setData(InputStream data); String getDataAsString(); Bitmap getAsBitmap(); }### Answer:
@Test public void getCode() throws Exception { } |
### Question:
BitMapTask extends Task<String, Void, Bitmap> { @Override protected void onPreExecute() { super.onPreExecute(); } BitMapTask(DownZ.Method method, String url, ArrayList<RequestParams> params, ArrayList<HeaderParams> headers, HttpListener<Bitmap> callback); }### Answer:
@Test public void onPreExecute() throws Exception { } |
### Question:
BitMapTask extends Task<String, Void, Bitmap> { @Override protected Bitmap doInBackground(String... urls) { try { Response response = makeRequest(mUrl, method, params, headers); Bitmap bitmap = response.getAsBitmap(); if (this.mCacheManager != null) { if (this.mCacheManager.getDataFromCache(mUrl) == null) this.mCacheManager.addDataToCache(mUrl, bitmap); } return bitmap; } catch (Exception e) { e.printStackTrace(); error = true; } return null; } BitMapTask(DownZ.Method method, String url, ArrayList<RequestParams> params, ArrayList<HeaderParams> headers, HttpListener<Bitmap> callback); }### Answer:
@Test public void doInBackground() throws Exception { } |
### Question:
BitMapTask extends Task<String, Void, Bitmap> { @Override protected void onPostExecute(Bitmap data) { super.onPostExecute(data); if (!error) this.callback.onResponse(data); else this.callback.onError(); } BitMapTask(DownZ.Method method, String url, ArrayList<RequestParams> params, ArrayList<HeaderParams> headers, HttpListener<Bitmap> callback); }### Answer:
@Test public void onPostExecute() throws Exception { } |
### Question:
BitMapTask extends Task<String, Void, Bitmap> { @Override protected void onCancelled() { super.onCancelled(); if (this.mCacheManager != null) { this.mCacheManager.removeDataFromCache(mUrl); } } BitMapTask(DownZ.Method method, String url, ArrayList<RequestParams> params, ArrayList<HeaderParams> headers, HttpListener<Bitmap> callback); }### Answer:
@Test public void onCancelled() throws Exception { } |
### Question:
JsonArrayTask extends Task<String, Void, JSONArray> { @Override protected void onPreExecute() { super.onPreExecute(); } JsonArrayTask(DownZ.Method method, String url, ArrayList<RequestParams> params, ArrayList<HeaderParams> headers, HttpListener<JSONArray> callback); }### Answer:
@Test public void onPreExecute() throws Exception { } |
### Question:
JsonArrayTask extends Task<String, Void, JSONArray> { @Override protected JSONArray doInBackground(String... urls) { try { Response response = makeRequest(mUrl, method, params, headers); JSONArray json = new JSONArray(response.getDataAsString()); if (this.mCacheManager != null) { if (this.mCacheManager.getDataFromCache(mUrl) == null) this.mCacheManager.addDataToCache(mUrl, json); } return json; } catch (Exception e) { e.printStackTrace(); error = true; } return null; } JsonArrayTask(DownZ.Method method, String url, ArrayList<RequestParams> params, ArrayList<HeaderParams> headers, HttpListener<JSONArray> callback); }### Answer:
@Test public void doInBackground() throws Exception { } |
### Question:
JsonArrayTask extends Task<String, Void, JSONArray> { @Override protected void onPostExecute(JSONArray data) { super.onPostExecute(data); if (!error) this.callback.onResponse(data); else this.callback.onError(); } JsonArrayTask(DownZ.Method method, String url, ArrayList<RequestParams> params, ArrayList<HeaderParams> headers, HttpListener<JSONArray> callback); }### Answer:
@Test public void onPostExecute() throws Exception { } |
### Question:
JsonArrayTask extends Task<String, Void, JSONArray> { @Override protected void onCancelled() { super.onCancelled(); if (this.mCacheManager != null) { this.mCacheManager.removeDataFromCache(mUrl); } } JsonArrayTask(DownZ.Method method, String url, ArrayList<RequestParams> params, ArrayList<HeaderParams> headers, HttpListener<JSONArray> callback); }### Answer:
@Test public void onCancelled() throws Exception { } |
### Question:
RequestParams { public String getKey() { return key; } String getKey(); RequestParams setKey(String key); String getValue(); RequestParams setValue(String value); }### Answer:
@Test public void getKey() throws Exception { } |
### Question:
RequestParams { public RequestParams setKey(String key) { this.key = key; return this; } String getKey(); RequestParams setKey(String key); String getValue(); RequestParams setValue(String value); }### Answer:
@Test public void setKey() throws Exception { } |
### Question:
Response { public Response setCode(int code) { this.code = code; return this; } int getCode(); Response setCode(int code); InputStream getData(); Response setData(InputStream data); String getDataAsString(); Bitmap getAsBitmap(); }### Answer:
@Test public void setCode() throws Exception { } |
### Question:
RequestParams { public String getValue() { return value; } String getKey(); RequestParams setKey(String key); String getValue(); RequestParams setValue(String value); }### Answer:
@Test public void getValue() throws Exception { } |
### Question:
RequestParams { public RequestParams setValue(String value) { this.value = value; return this; } String getKey(); RequestParams setKey(String key); String getValue(); RequestParams setValue(String value); }### Answer:
@Test public void setValue() throws Exception { } |
### Question:
HeaderParams { public String getKey() { return key; } String getKey(); HeaderParams setKey(String key); String getValue(); HeaderParams setValue(String value); }### Answer:
@Test public void getKey() throws Exception { } |
### Question:
HeaderParams { public HeaderParams setKey(String key) { this.key = key; return this; } String getKey(); HeaderParams setKey(String key); String getValue(); HeaderParams setValue(String value); }### Answer:
@Test public void setKey() throws Exception { } |
### Question:
HeaderParams { public String getValue() { return value; } String getKey(); HeaderParams setKey(String key); String getValue(); HeaderParams setValue(String value); }### Answer:
@Test public void getValue() throws Exception { } |
### Question:
HeaderParams { public HeaderParams setValue(String value) { this.value = value; return this; } String getKey(); HeaderParams setKey(String key); String getValue(); HeaderParams setValue(String value); }### Answer:
@Test public void setValue() throws Exception { } |
### Question:
CacheManager extends LruCache<String, T> implements CacheManagerInterface<T> { @Override protected int sizeOf(String key, T data) { int bytesCount; if (data instanceof Bitmap) { bytesCount = ((Bitmap) data).getByteCount(); } else if (data instanceof JSONObject) { bytesCount = ((JSONObject) data).toString().getBytes().length; } else { bytesCount = ((JSONArray) data).toString().getBytes().length; } return bytesCount / 1024; } CacheManager(int cacheSize); @Override void addDataToCache(String key, T data); @Override void removeDataFromCache(String key); @Override T getDataFromCache(String key); @Override void evictUnused(); }### Answer:
@Test public void sizeOf() throws Exception { } |
### Question:
CacheManager extends LruCache<String, T> implements CacheManagerInterface<T> { @Override public void addDataToCache(String key, T data) { if (getDataFromCache(key) == null) { synchronized (this) { put(key, data); cacheHitTimestamp.put(key, SystemClock.uptimeMillis()); } } } CacheManager(int cacheSize); @Override void addDataToCache(String key, T data); @Override void removeDataFromCache(String key); @Override T getDataFromCache(String key); @Override void evictUnused(); }### Answer:
@Test public void addDataToCache() throws Exception { } |
### Question:
CacheManager extends LruCache<String, T> implements CacheManagerInterface<T> { @Override public void removeDataFromCache(String key) { if (getDataFromCache(key) != null) { synchronized (this) { remove(key); } } } CacheManager(int cacheSize); @Override void addDataToCache(String key, T data); @Override void removeDataFromCache(String key); @Override T getDataFromCache(String key); @Override void evictUnused(); }### Answer:
@Test public void removeDataFromCache() throws Exception { } |
### Question:
CacheManager extends LruCache<String, T> implements CacheManagerInterface<T> { @Override public T getDataFromCache(String key) { synchronized (this) { cacheHitTimestamp.put(key, SystemClock.uptimeMillis()); evictUnused(); } return get(key); } CacheManager(int cacheSize); @Override void addDataToCache(String key, T data); @Override void removeDataFromCache(String key); @Override T getDataFromCache(String key); @Override void evictUnused(); }### Answer:
@Test public void getDataFromCache() throws Exception { } |
### Question:
Response { public InputStream getData() { return inputStream; } int getCode(); Response setCode(int code); InputStream getData(); Response setData(InputStream data); String getDataAsString(); Bitmap getAsBitmap(); }### Answer:
@Test public void getData() throws Exception { } |
### Question:
CacheManager extends LruCache<String, T> implements CacheManagerInterface<T> { @Override public void evictUnused() { Map<String, T> items = snapshot(); for (String key : items.keySet()) { long cacheTime = cacheHitTimestamp.get(key); if (cacheTime + timeout < SystemClock.uptimeMillis()) { remove(key); } } } CacheManager(int cacheSize); @Override void addDataToCache(String key, T data); @Override void removeDataFromCache(String key); @Override T getDataFromCache(String key); @Override void evictUnused(); }### Answer:
@Test public void evictUnused() throws Exception { } |
### Question:
JsonArray extends Type<JSONArray> { public JsonArray setCallback(HttpListener<JSONArray> listener) { this.mListener = listener; this.mListener.onRequest(); JSONArray data; if (mCacheManager != null) { data = mCacheManager.getDataFromCache(url); if (data != null) { mListener.onResponse(data); return this; } } mTask = new JsonArrayTask(method, url, params, headers, mListener); mTask.setmCachemanager(mCacheManager); mTask.execute(); return this; } JsonArray(DownZ.Method m, String url, ArrayList<RequestParams> params, ArrayList<HeaderParams> headers); JsonArray setCallback(HttpListener<JSONArray> listener); boolean cancel(); JsonArray setCacheManager(CacheManagerInterface<JSONArray> cache); }### Answer:
@Test public void setCallback() throws Exception { } |
### Question:
JsonArray extends Type<JSONArray> { public boolean cancel() { if (mTask != null) { mTask.cancel(true); if (mTask.isCancelled()) { mListener.onCancel(); return true; } else { return false; } } return false; } JsonArray(DownZ.Method m, String url, ArrayList<RequestParams> params, ArrayList<HeaderParams> headers); JsonArray setCallback(HttpListener<JSONArray> listener); boolean cancel(); JsonArray setCacheManager(CacheManagerInterface<JSONArray> cache); }### Answer:
@Test public void cancel() throws Exception { } |
### Question:
JsonArray extends Type<JSONArray> { public JsonArray setCacheManager(CacheManagerInterface<JSONArray> cache) { this.mCacheManager = cache; return this; } JsonArray(DownZ.Method m, String url, ArrayList<RequestParams> params, ArrayList<HeaderParams> headers); JsonArray setCallback(HttpListener<JSONArray> listener); boolean cancel(); JsonArray setCacheManager(CacheManagerInterface<JSONArray> cache); }### Answer:
@Test public void setCacheManager() throws Exception { } |
### Question:
BitMap extends Type<Bitmap> { public BitMap setCallback(HttpListener<Bitmap> listener) { this.listener = listener; this.listener.onRequest(); Bitmap data; if (mCacheManager != null) { data = mCacheManager.getDataFromCache(url); if (data != null) { this.listener.onResponse(data); return this; } } mTask = new BitMapTask(method, url, params, headers, this.listener); mTask.setmCachemanager(mCacheManager); mTask.execute(); return this; } BitMap(DownZ.Method m, String url, ArrayList<RequestParams> params, ArrayList<HeaderParams> headers); BitMap setCallback(HttpListener<Bitmap> listener); boolean cancel(); BitMap setCacheManager(CacheManagerInterface<Bitmap> cache); }### Answer:
@Test public void setCallback() throws Exception { } |
### Question:
BitMap extends Type<Bitmap> { public boolean cancel() { if (mTask != null) { mTask.cancel(true); if (mTask.isCancelled()) { listener.onCancel(); return true; } else { return false; } } return false; } BitMap(DownZ.Method m, String url, ArrayList<RequestParams> params, ArrayList<HeaderParams> headers); BitMap setCallback(HttpListener<Bitmap> listener); boolean cancel(); BitMap setCacheManager(CacheManagerInterface<Bitmap> cache); }### Answer:
@Test public void cancel() throws Exception { } |
### Question:
BitMap extends Type<Bitmap> { public BitMap setCacheManager(CacheManagerInterface<Bitmap> cache) { this.mCacheManager = cache; return this; } BitMap(DownZ.Method m, String url, ArrayList<RequestParams> params, ArrayList<HeaderParams> headers); BitMap setCallback(HttpListener<Bitmap> listener); boolean cancel(); BitMap setCacheManager(CacheManagerInterface<Bitmap> cache); }### Answer:
@Test public void setCacheManager() throws Exception { } |
### Question:
Type { public abstract Type setCacheManager(CacheManagerInterface<T> cacheManager); abstract Type setCacheManager(CacheManagerInterface<T> cacheManager); abstract Type setCallback(HttpListener<T> callback); abstract boolean cancel(); }### Answer:
@Test public void setCacheManager() throws Exception { } |
### Question:
Type { public abstract Type setCallback(HttpListener<T> callback); abstract Type setCacheManager(CacheManagerInterface<T> cacheManager); abstract Type setCallback(HttpListener<T> callback); abstract boolean cancel(); }### Answer:
@Test public void setCallback() throws Exception { } |
### Question:
Type { public abstract boolean cancel(); abstract Type setCacheManager(CacheManagerInterface<T> cacheManager); abstract Type setCallback(HttpListener<T> callback); abstract boolean cancel(); }### Answer:
@Test public void cancel() throws Exception { } |
### Question:
Response { public Response setData(InputStream data) { this.inputStream = data; return this; } int getCode(); Response setCode(int code); InputStream getData(); Response setData(InputStream data); String getDataAsString(); Bitmap getAsBitmap(); }### Answer:
@Test public void setData() throws Exception { } |
### Question:
JsonObject extends Type<JSONObject> { public JsonObject setCallback(HttpListener<JSONObject> listener) { this.mListener = listener; mListener.onRequest(); JSONObject data; if (mCacheManager != null) { data = mCacheManager.getDataFromCache(url); if (data != null) { mListener.onResponse(data); return this; } } mTask = new JsonObjectTask(method, url, params, headers, mListener); mTask.execute(); return this; } JsonObject(DownZ.Method m, String url, ArrayList<RequestParams> params, ArrayList<HeaderParams> headers); JsonObject setCallback(HttpListener<JSONObject> listener); boolean cancel(); JsonObject setCacheManager(CacheManagerInterface<JSONObject> cache); }### Answer:
@Test public void setCallback() throws Exception { } |
### Question:
JsonObject extends Type<JSONObject> { public boolean cancel() { if (mTask != null) { mTask.cancel(true); if (mTask.isCancelled()) { mListener.onCancel(); return true; } else { return false; } } return false; } JsonObject(DownZ.Method m, String url, ArrayList<RequestParams> params, ArrayList<HeaderParams> headers); JsonObject setCallback(HttpListener<JSONObject> listener); boolean cancel(); JsonObject setCacheManager(CacheManagerInterface<JSONObject> cache); }### Answer:
@Test public void cancel() throws Exception { } |
### Question:
JsonObject extends Type<JSONObject> { public JsonObject setCacheManager(CacheManagerInterface<JSONObject> cache) { this.mCacheManager = cache; return this; } JsonObject(DownZ.Method m, String url, ArrayList<RequestParams> params, ArrayList<HeaderParams> headers); JsonObject setCallback(HttpListener<JSONObject> listener); boolean cancel(); JsonObject setCacheManager(CacheManagerInterface<JSONObject> cache); }### Answer:
@Test public void setCacheManager() throws Exception { } |
### Question:
Response { public String getDataAsString() throws IOException { final int bufferSize = 1024; final char[] buffer = new char[bufferSize]; final StringBuilder out = new StringBuilder(); Reader in = new InputStreamReader(inputStream, "UTF-8"); for (; ; ) { int i = in.read(buffer, 0, buffer.length); if (i < 0) break; out.append(buffer, 0, i); } if (inputStream != null) { inputStream.close(); } return out.toString(); } int getCode(); Response setCode(int code); InputStream getData(); Response setData(InputStream data); String getDataAsString(); Bitmap getAsBitmap(); }### Answer:
@Test public void getDataAsString() throws Exception { } |
### Question:
Response { public Bitmap getAsBitmap() { Bitmap bitmap = BitmapFactory.decodeStream(this.inputStream); if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } return bitmap; } int getCode(); Response setCode(int code); InputStream getData(); Response setData(InputStream data); String getDataAsString(); Bitmap getAsBitmap(); }### Answer:
@Test public void getAsBitmap() throws Exception { } |
### Question:
JsonObjectTask extends Task<String, Void, JSONObject> { @Override protected void onPreExecute() { super.onPreExecute(); } JsonObjectTask(DownZ.Method method, String url, ArrayList<RequestParams> params, ArrayList<HeaderParams> headers, HttpListener<JSONObject> callback); }### Answer:
@Test public void onPreExecute() throws Exception { } |
### Question:
JsonObjectTask extends Task<String, Void, JSONObject> { @Override protected JSONObject doInBackground(String... urls) { try { Response response = makeRequest(mUrl, method, params, headers); JSONObject json = new JSONObject(response.getDataAsString()); if (this.mCacheManager != null) { if (this.mCacheManager.getDataFromCache(mUrl) == null) this.mCacheManager.addDataToCache(mUrl, json); } return json; } catch (Exception e) { e.printStackTrace(); error = true; } return null; } JsonObjectTask(DownZ.Method method, String url, ArrayList<RequestParams> params, ArrayList<HeaderParams> headers, HttpListener<JSONObject> callback); }### Answer:
@Test public void doInBackground() throws Exception { } |
### Question:
JsonObjectTask extends Task<String, Void, JSONObject> { @Override protected void onPostExecute(JSONObject data) { super.onPostExecute(data); if (!error) this.callback.onResponse(data); else this.callback.onError(); } JsonObjectTask(DownZ.Method method, String url, ArrayList<RequestParams> params, ArrayList<HeaderParams> headers, HttpListener<JSONObject> callback); }### Answer:
@Test public void onPostExecute() throws Exception { } |
### Question:
JsonObjectTask extends Task<String, Void, JSONObject> { @Override protected void onCancelled() { super.onCancelled(); if (this.mCacheManager != null) { this.mCacheManager.removeDataFromCache(mUrl); } } JsonObjectTask(DownZ.Method method, String url, ArrayList<RequestParams> params, ArrayList<HeaderParams> headers, HttpListener<JSONObject> callback); }### Answer:
@Test public void onCancelled() throws Exception { } |
### Question:
SnappyDecompressor { public static Buffer decompress(byte[] in) { return decompress(in, 0, in.length, null); } private SnappyDecompressor(); static Buffer decompress(byte[] in); static Buffer decompress(byte[] in, Buffer out); static Buffer decompress(byte[] in, int offset, int length); static Buffer decompress(Buffer in); static Buffer decompress(Buffer in, Buffer out); static Buffer decompress(byte[] in, int offset, int length, Buffer out); }### Answer:
@Test public void testSuperfluousData() { byte[] data = new byte[2]; try { SnappyDecompressor.decompress(data); Assert.fail("Exception was expected"); } catch(FormatViolationException e) { Assert.assertEquals(1, e.getOffset()); } } |
### Question:
DefaultDragHelper implements DragHelper { @Override public void onDragEnd(@NonNull WXComponent component, int from, int to) { if (WXEnvironment.isApkDebugable()) { WXLogUtils.d(TAG, "list on drag end : " + "from index " + from + " to index " + to); } mEventTrigger.triggerEvent(EVENT_END_DRAG, buildEvent(component.getRef(), from, to)); } DefaultDragHelper(@NonNull List<WXComponent> dataSource, @NonNull RecyclerView recyclerView, @NonNull EventTrigger trigger); @Override void onDragStart(@NonNull WXComponent component, int from); @Override void onDragEnd(@NonNull WXComponent component, int from, int to); @Override void onDragging(int fromPos, int toPos); @Override boolean isLongPressDragEnabled(); @Override void setLongPressDragEnabled(boolean enabled); @Override void startDrag(@NonNull RecyclerView.ViewHolder viewHolder); @Override boolean isDraggable(); @Override void setDraggable(boolean draggable); @Override void setDragExcluded(@NonNull RecyclerView.ViewHolder viewHolder, boolean isExcluded); @Override boolean isDragExcluded(@NonNull RecyclerView.ViewHolder viewHolder); }### Answer:
@Test public void onDragEnd() throws Exception { WXComponent c = new WXCell(WXSDKInstanceTest.createInstance(),new TestDomObject(),null,false); mFakeDragHelper.onDragEnd(c,1,2); verify(mockedEventTrigger).triggerEvent(eq("dragend"),anyMap()); } |
### Question:
DefaultDragHelper implements DragHelper { @Override public void onDragging(int fromPos, int toPos) { if (WXEnvironment.isApkDebugable()) { WXLogUtils.d(TAG, "list on dragging : from index " + fromPos + " to index " + toPos); } RecyclerView.Adapter adapter = mRecyclerView.getAdapter(); if (adapter == null) { WXLogUtils.e(TAG, "drag failed because of RecyclerView#Adapter is not bound"); return; } if (fromPos >= 0 && fromPos <= mDataSource.size() - 1 && toPos >= 0 && toPos <= mDataSource.size() - 1) { Collections.swap(mDataSource, fromPos, toPos); adapter.notifyItemMoved(fromPos, toPos); } } DefaultDragHelper(@NonNull List<WXComponent> dataSource, @NonNull RecyclerView recyclerView, @NonNull EventTrigger trigger); @Override void onDragStart(@NonNull WXComponent component, int from); @Override void onDragEnd(@NonNull WXComponent component, int from, int to); @Override void onDragging(int fromPos, int toPos); @Override boolean isLongPressDragEnabled(); @Override void setLongPressDragEnabled(boolean enabled); @Override void startDrag(@NonNull RecyclerView.ViewHolder viewHolder); @Override boolean isDraggable(); @Override void setDraggable(boolean draggable); @Override void setDragExcluded(@NonNull RecyclerView.ViewHolder viewHolder, boolean isExcluded); @Override boolean isDragExcluded(@NonNull RecyclerView.ViewHolder viewHolder); }### Answer:
@Test public void onDragging() throws Exception { assertEquals(mFakeDataSource.get(0),c1); assertEquals(mFakeDataSource.get(1),c2); mFakeDragHelper.onDragging(0,1); assertEquals(mFakeDataSource.get(0),c2); assertEquals(mFakeDataSource.get(1),c1); } |
### Question:
WXRefresh extends WXBaseRefresh implements WXSwipeLayout.WXOnRefreshListener { @Override public void onRefresh() { if(isDestoryed()){ return; } ImmutableDomObject dom; if ((dom = getDomObject())!= null && dom.getEvents().contains(Constants.Event.ONREFRESH)) { fireEvent(Constants.Event.ONREFRESH); } } @Deprecated WXRefresh(WXSDKInstance instance, WXDomObject dom, WXVContainer parent, String instanceId, boolean isLazy); WXRefresh(WXSDKInstance instance, WXDomObject node, WXVContainer parent, boolean lazy); @Override boolean canRecycled(); @Override void onRefresh(); @Override int getLayoutTopOffsetForSibling(); @Override void onPullingDown(float dy, int pullOutDistance, float viewHeight); @WXComponentProp(name = Constants.Name.DISPLAY) void setDisplay(String display); static final String HIDE; }### Answer:
@Test public void testOnRefresh() throws Exception { component.onRefresh(); } |
### Question:
WXRefresh extends WXBaseRefresh implements WXSwipeLayout.WXOnRefreshListener { @Override public void onPullingDown(float dy, int pullOutDistance, float viewHeight) { if (getDomObject().getEvents() != null && getDomObject().getEvents().contains(Constants.Event.ONPULLING_DOWN)) { Map<String, Object> data = new HashMap<>(); data.put(Constants.Name.DISTANCE_Y, dy); data.put(Constants.Name.PULLING_DISTANCE, pullOutDistance); data.put(Constants.Name.VIEW_HEIGHT, viewHeight); fireEvent(Constants.Event.ONPULLING_DOWN, data); } } @Deprecated WXRefresh(WXSDKInstance instance, WXDomObject dom, WXVContainer parent, String instanceId, boolean isLazy); WXRefresh(WXSDKInstance instance, WXDomObject node, WXVContainer parent, boolean lazy); @Override boolean canRecycled(); @Override void onRefresh(); @Override int getLayoutTopOffsetForSibling(); @Override void onPullingDown(float dy, int pullOutDistance, float viewHeight); @WXComponentProp(name = Constants.Name.DISPLAY) void setDisplay(String display); static final String HIDE; }### Answer:
@Test public void testOnPullingDown() throws Exception { component.onPullingDown(10,100,100); } |
### Question:
WXRefresh extends WXBaseRefresh implements WXSwipeLayout.WXOnRefreshListener { @Override protected boolean setProperty(String key, Object param) { switch (key) { case Constants.Name.DISPLAY: String display = WXUtils.getString(param,null); if (display != null) setDisplay(display); return true; } return super.setProperty(key,param); } @Deprecated WXRefresh(WXSDKInstance instance, WXDomObject dom, WXVContainer parent, String instanceId, boolean isLazy); WXRefresh(WXSDKInstance instance, WXDomObject node, WXVContainer parent, boolean lazy); @Override boolean canRecycled(); @Override void onRefresh(); @Override int getLayoutTopOffsetForSibling(); @Override void onPullingDown(float dy, int pullOutDistance, float viewHeight); @WXComponentProp(name = Constants.Name.DISPLAY) void setDisplay(String display); static final String HIDE; }### Answer:
@Test public void testSetProperty() throws Exception { component.setProperty(Constants.Name.DISPLAY,WXRefresh.HIDE); } |
### Question:
WXSliderNeighbor extends WXSlider { @Override protected boolean setProperty(String key, Object param) { String input; switch (key) { case NEIGHBOR_SCALE: input = WXUtils.getString(param, null); if (input != null) { setNeighborScale(input); } return true; case NEIGHBOR_ALPHA: input = WXUtils.getString(param, null); if (input != null) { setNeighborAlpha(input); } return true; case NEIGHBOR_SPACE: input = WXUtils.getString(param, null); if (input != null) { setNeighborSpace(input); } return true; case CURRENT_ITEM_SCALE: input = WXUtils.getString(param, null); if (input != null) { setCurrentItemScale(input); } return true; } return super.setProperty(key, param); } WXSliderNeighbor(WXSDKInstance instance, WXDomObject node, WXVContainer parent); @Override void bindData(WXComponent component); @WXComponentProp(name = NEIGHBOR_SCALE) void setNeighborScale(String input); @WXComponentProp(name = NEIGHBOR_ALPHA) void setNeighborAlpha(String input); @WXComponentProp(name = NEIGHBOR_SPACE) @SuppressWarnings("unused") void setNeighborSpace(String input); @WXComponentProp(name = CURRENT_ITEM_SCALE) @SuppressWarnings("unused") void setCurrentItemScale(String input); static final String NEIGHBOR_SCALE; static final String NEIGHBOR_ALPHA; static final String NEIGHBOR_SPACE; static final String CURRENT_ITEM_SCALE; }### Answer:
@Test public void testSetProperties() throws Exception { component.setProperty(WXSliderNeighbor.NEIGHBOR_ALPHA,0.4f); component.setProperty(WXSliderNeighbor.NEIGHBOR_SCALE,0.9f); } |
### Question:
WXSliderNeighbor extends WXSlider { ZoomTransformer createTransformer() { if(mCachedTransformer == null) { mCachedTransformer = new ZoomTransformer(); } return mCachedTransformer; } WXSliderNeighbor(WXSDKInstance instance, WXDomObject node, WXVContainer parent); @Override void bindData(WXComponent component); @WXComponentProp(name = NEIGHBOR_SCALE) void setNeighborScale(String input); @WXComponentProp(name = NEIGHBOR_ALPHA) void setNeighborAlpha(String input); @WXComponentProp(name = NEIGHBOR_SPACE) @SuppressWarnings("unused") void setNeighborSpace(String input); @WXComponentProp(name = CURRENT_ITEM_SCALE) @SuppressWarnings("unused") void setCurrentItemScale(String input); static final String NEIGHBOR_SCALE; static final String NEIGHBOR_ALPHA; static final String NEIGHBOR_SPACE; static final String CURRENT_ITEM_SCALE; }### Answer:
@Test public void testZoomTransformer() throws Exception { component = create(); TestComponent page = ComponentTest.createComponent(new TestDomObject(),component,TestComponent.class); TestComponent pageChild = ComponentTest.createComponent(new TestDomObject(),component,TestComponent.class); page.addChild(pageChild); component.addChild(page); ComponentTest.create(component); WXSliderNeighbor.ZoomTransformer transformer = component.createTransformer(); transformer.transformPage(page.getHostView(),0.2f); } |
### Question:
WXEmbed extends WXDiv implements WXSDKInstance.OnInstanceVisibleListener,NestedContainer { @Override protected boolean setProperty(String key, Object param) { switch (key) { case Constants.Name.SRC: String src = WXUtils.getString(param,null); if (src != null) setSrc(src); return true; } return super.setProperty(key, param); } @Deprecated WXEmbed(WXSDKInstance instance, WXDomObject dom, WXVContainer parent, String instanceId, boolean isLazy); WXEmbed(WXSDKInstance instance, WXDomObject node, WXVContainer parent); @Override void setOnNestEventListener(OnNestedInstanceEventListener listener); @Override ViewGroup getViewContainer(); @Override void renderNewURL(String url); @Override void reload(); String getOriginUrl(); void setOriginUrl(String originUrl); @WXComponentProp(name = Constants.Name.SRC) void setSrc(String src); String getSrc(); @Override void setVisibility(String visibility); @Override void destroy(); @Override void onAppear(); @Override void onDisappear(); @Override void onActivityStart(); @Override void onActivityResume(); @Override void onActivityPause(); @Override void onActivityStop(); @Override void onActivityDestroy(); static final String ITEM_ID; }### Answer:
@Test public void testSetProperty() throws Exception { component.setProperty(Constants.Name.SRC,"http: } |
### Question:
WXEmbed extends WXDiv implements WXSDKInstance.OnInstanceVisibleListener,NestedContainer { @Override public void setVisibility(String visibility) { super.setVisibility(visibility); boolean visible = TextUtils.equals(visibility, Constants.Value.VISIBLE); if (!TextUtils.isEmpty(src) && visible) { if (mNestedInstance == null) { loadContent(); } else { mNestedInstance.onViewAppear(); } } if (!visible) { if (mNestedInstance != null) { mNestedInstance.onViewDisappear(); } } mIsVisible = visible; } @Deprecated WXEmbed(WXSDKInstance instance, WXDomObject dom, WXVContainer parent, String instanceId, boolean isLazy); WXEmbed(WXSDKInstance instance, WXDomObject node, WXVContainer parent); @Override void setOnNestEventListener(OnNestedInstanceEventListener listener); @Override ViewGroup getViewContainer(); @Override void renderNewURL(String url); @Override void reload(); String getOriginUrl(); void setOriginUrl(String originUrl); @WXComponentProp(name = Constants.Name.SRC) void setSrc(String src); String getSrc(); @Override void setVisibility(String visibility); @Override void destroy(); @Override void onAppear(); @Override void onDisappear(); @Override void onActivityStart(); @Override void onActivityResume(); @Override void onActivityPause(); @Override void onActivityStop(); @Override void onActivityDestroy(); static final String ITEM_ID; }### Answer:
@Test public void testSetVisibility() throws Exception { component.setProperty(Constants.Name.VISIBILITY,Constants.Value.HIDDEN); component.setProperty(Constants.Name.SRC,"http: component.setProperty(Constants.Name.VISIBILITY,Constants.Value.VISIBLE); } |
### Question:
WXLoading extends WXBaseRefresh implements WXSwipeLayout.WXOnLoadingListener { @Override public void onLoading() { ImmutableDomObject domObject = getDomObject(); if (domObject != null && domObject.getEvents().contains(Constants.Event.ONLOADING)) { fireEvent(Constants.Event.ONLOADING); } } WXLoading(WXSDKInstance instance, WXDomObject node, WXVContainer parent, boolean lazy); @Override void onLoading(); @Override void onPullingUp(float dy, int pullOutDistance, float viewHeight); @Override boolean canRecycled(); @WXComponentProp(name = Constants.Name.DISPLAY) void setDisplay(String display); static final String HIDE; }### Answer:
@Test public void testOnLoading() throws Exception { component.onLoading(); } |
### Question:
WXLoading extends WXBaseRefresh implements WXSwipeLayout.WXOnLoadingListener { @Override protected boolean setProperty(String key, Object param) { switch (key) { case Constants.Name.DISPLAY: String display = WXUtils.getString(param,null); if (display != null) setDisplay(display); return true; } return super.setProperty(key, param); } WXLoading(WXSDKInstance instance, WXDomObject node, WXVContainer parent, boolean lazy); @Override void onLoading(); @Override void onPullingUp(float dy, int pullOutDistance, float viewHeight); @Override boolean canRecycled(); @WXComponentProp(name = Constants.Name.DISPLAY) void setDisplay(String display); static final String HIDE; }### Answer:
@Test public void testSetProperty() throws Exception { component.setProperty(Constants.Name.DISPLAY,WXLoading.HIDE); } |
### Question:
WXAnimationModule extends WXModule { @JSMethod public void transition(@Nullable String ref, @Nullable String animation, @Nullable String callBack) { if (!TextUtils.isEmpty(ref) && !TextUtils.isEmpty(animation) && mWXSDKInstance != null) { DOMAction animationActions = getAnimationAction(ref, animation, callBack); WXSDKManager.getInstance().getWXDomManager().postActionDelay(mWXSDKInstance.getInstanceId(), animationActions, false, WXDomHandler.DELAY_TIME); } } @JSMethod void transition(@Nullable String ref, @Nullable String animation, @Nullable String callBack); }### Answer:
@Test public void testTransition() throws Exception { module.transition("","",""); module.transition("test","test",""); } |
### Question:
WXTimerModule extends WXModule implements Destroyable, Handler.Callback { @JSMethod(uiThread = false) public void clearTimeout(@IntRange(from = 1) int funcId) { if (funcId <= 0) { return; } removeOrHoldMessage(MODULE_TIMEOUT, funcId); } WXTimerModule(); @JSMethod(uiThread = false) void setTimeout(@IntRange(from = 1) int funcId, @IntRange(from = 0) int delay); @JSMethod(uiThread = false) void setInterval(@IntRange(from = 1) int funcId, @IntRange(from = 0) int interval); @JSMethod(uiThread = false) void clearTimeout(@IntRange(from = 1) int funcId); @JSMethod(uiThread = false) void clearInterval(@IntRange(from = 1) int funcId); @Override void destroy(); @Override boolean handleMessage(Message msg); }### Answer:
@Test public void testClearTimeout() throws Exception { module.setTimeout(VALID_FUNC_ID, DELAY); module.clearTimeout(VALID_FUNC_ID); mLooper.idle(DELAY, TimeUnit.MILLISECONDS); Mockito.verify(module, never()).handleMessage(any(Message.class)); } |
### Question:
WXTimerModule extends WXModule implements Destroyable, Handler.Callback { @JSMethod(uiThread = false) public void clearInterval(@IntRange(from = 1) int funcId) { if (funcId <= 0) { return; } removeOrHoldMessage(MODULE_INTERVAL, funcId); } WXTimerModule(); @JSMethod(uiThread = false) void setTimeout(@IntRange(from = 1) int funcId, @IntRange(from = 0) int delay); @JSMethod(uiThread = false) void setInterval(@IntRange(from = 1) int funcId, @IntRange(from = 0) int interval); @JSMethod(uiThread = false) void clearTimeout(@IntRange(from = 1) int funcId); @JSMethod(uiThread = false) void clearInterval(@IntRange(from = 1) int funcId); @Override void destroy(); @Override boolean handleMessage(Message msg); }### Answer:
@Test public void testClearInterval() throws Exception { module.setInterval(VALID_FUNC_ID, DELAY); module.clearInterval(VALID_FUNC_ID); mLooper.idle(DELAY, TimeUnit.MILLISECONDS); Mockito.verify(module, never()).handleMessage(any(Message.class)); } |
### Question:
WXAttr implements Map<String, Object>,Cloneable { public static String getValue(Map<String, Object> attr) { if (attr == null) { return null; } Object src = attr.get(Constants.Name.VALUE); if (src == null) { src = attr.get("content"); if (src == null) { return null; } } return src.toString(); } WXAttr(); WXAttr(@NonNull Map<String,Object> standardMap); static String getPrefix(Map<String, Object> attr); static String getSuffix(Map<String, Object> attr); static String getValue(Map<String, Object> attr); WXImageQuality getImageQuality(); WXImageSharpen getImageSharpen(); String getImageSrc(); boolean canRecycled(); boolean showIndicators(); boolean autoPlay(); String getScope(); String getLoadMoreRetry(); String getLoadMoreOffset(); String optString(String key); boolean getIsRecycleImage(); String getScrollDirection(); float getElevation(int viewPortW); float getColumnWidth(); int getColumnCount(); float getColumnGap(); int getLayoutType(); @Override boolean equals(Object o); @Override int hashCode(); @Override void clear(); @Override boolean containsKey(Object key); @Override boolean containsValue(Object value); @NonNull @Override Set<Entry<String, Object>> entrySet(); @Override Object get(Object key); @Override boolean isEmpty(); @NonNull @Override Set<String> keySet(); @Override Object put(String key, Object value); @Override void putAll(Map<? extends String, ?> map); @Override Object remove(Object key); @Override int size(); @NonNull @Override Collection<Object> values(); }### Answer:
@Test public void testGetValue() throws Exception { assertEquals(null,WXAttr.getValue(attr)); attr.put(VALUE,"test"); assertEquals("test",WXAttr.getValue(attr)); } |
### Question:
WXFileUtils { public static String loadAsset(String path, Context context) { if (context == null || TextUtils.isEmpty(path)) { return null; } InputStream inputStream = null; try { inputStream = context.getAssets().open(path); return readStreamToString(inputStream); } catch (IOException e) { e.printStackTrace(); } return ""; } static String loadFileOrAsset(String path, Context context); static String loadAsset(String path, Context context); static boolean saveFile(String path, byte[] content, Context context); }### Answer:
@Test public void testLoadFileContent() throws Exception { File folder = new File("build/intermediates/bundles/debug/assets/"); if(!folder.exists()){ folder = new File("build/intermediates/bundles/debug/assets/"); folder.mkdirs(); } File file = new File(folder,"test"); System.out.println(file.getAbsolutePath()); if(!file.exists()){ file.createNewFile(); } WXFileUtils.loadAsset("test", RuntimeEnvironment.application); } |
### Question:
WXFileUtils { public static boolean saveFile(String path, byte[] content, Context context) { if (TextUtils.isEmpty(path) || content == null || context == null) { return false; } FileOutputStream outStream = null; try { outStream = new FileOutputStream(path); outStream.write(content); return true; } catch (Exception e) { WXLogUtils.e("WXFileUtils saveFile: " + WXLogUtils.getStackTrace(e)); } finally { if (outStream != null) { try { outStream.close(); } catch (IOException e) { e.printStackTrace(); } } } return false; } static String loadFileOrAsset(String path, Context context); static String loadAsset(String path, Context context); static boolean saveFile(String path, byte[] content, Context context); }### Answer:
@Test public void testSaveFile() throws Exception { WXFileUtils.saveFile("build/test","test".getBytes(),RuntimeEnvironment.application); } |
### Question:
WXUtils { public static float getFloat(Object value) { return getFloat(value, Float.NaN); } static boolean isUiThread(); static boolean isUndefined(float value); static float getFloatByViewport(Object value, int viewport); static float getFloat(Object value); static Float getFloat(Object value, @Nullable Float df); static float fastGetFloat(String raw, int precision); static float fastGetFloat(String raw); static int getInt(Object value); static Integer getInteger(@Nullable Object value, @Nullable Integer df); @Deprecated static long getLong(Object value); @Deprecated static double getDouble(Object value); static boolean isTabletDevice(); static Boolean getBoolean(@Nullable Object value, @Nullable Boolean df); static long getAvailMemory(Context context); static String getString(@Nullable Object value,@Nullable String df); static int parseUnitOrPercent(String raw, int unit); static String getBundleBanner(String content); static final char PERCENT; }### Answer:
@Test public void testGetFloat() throws Exception { float test_float = WXUtils.getFloat("12324.9px"); assertEquals(12324.9, test_float, 0.01); assertEquals(WXUtils.fastGetFloat("1.2345",2), 1.23f); } |
### Question:
WXAttr implements Map<String, Object>,Cloneable { public WXImageSharpen getImageSharpen() { Object obj = get(Constants.Name.SHARPEN); if (obj == null) { obj = get(Constants.Name.IMAGE_SHARPEN); } if (obj == null) { return WXImageSharpen.UNSHARPEN; } String imageSharpen = obj.toString(); WXImageSharpen waImageSharpen = WXImageSharpen.UNSHARPEN; if (imageSharpen.equals("sharpen")) { waImageSharpen = WXImageSharpen.SHARPEN; } return waImageSharpen; } WXAttr(); WXAttr(@NonNull Map<String,Object> standardMap); static String getPrefix(Map<String, Object> attr); static String getSuffix(Map<String, Object> attr); static String getValue(Map<String, Object> attr); WXImageQuality getImageQuality(); WXImageSharpen getImageSharpen(); String getImageSrc(); boolean canRecycled(); boolean showIndicators(); boolean autoPlay(); String getScope(); String getLoadMoreRetry(); String getLoadMoreOffset(); String optString(String key); boolean getIsRecycleImage(); String getScrollDirection(); float getElevation(int viewPortW); float getColumnWidth(); int getColumnCount(); float getColumnGap(); int getLayoutType(); @Override boolean equals(Object o); @Override int hashCode(); @Override void clear(); @Override boolean containsKey(Object key); @Override boolean containsValue(Object value); @NonNull @Override Set<Entry<String, Object>> entrySet(); @Override Object get(Object key); @Override boolean isEmpty(); @NonNull @Override Set<String> keySet(); @Override Object put(String key, Object value); @Override void putAll(Map<? extends String, ?> map); @Override Object remove(Object key); @Override int size(); @NonNull @Override Collection<Object> values(); }### Answer:
@Test public void testGetImageSharpen() throws Exception { assertEquals(WXImageSharpen.UNSHARPEN,attr.getImageSharpen()); } |
### Question:
WXUtils { public static int getInt(Object value) { return getInteger(value, 0); } static boolean isUiThread(); static boolean isUndefined(float value); static float getFloatByViewport(Object value, int viewport); static float getFloat(Object value); static Float getFloat(Object value, @Nullable Float df); static float fastGetFloat(String raw, int precision); static float fastGetFloat(String raw); static int getInt(Object value); static Integer getInteger(@Nullable Object value, @Nullable Integer df); @Deprecated static long getLong(Object value); @Deprecated static double getDouble(Object value); static boolean isTabletDevice(); static Boolean getBoolean(@Nullable Object value, @Nullable Boolean df); static long getAvailMemory(Context context); static String getString(@Nullable Object value,@Nullable String df); static int parseUnitOrPercent(String raw, int unit); static String getBundleBanner(String content); static final char PERCENT; }### Answer:
@Test public void testGetInt() throws Exception { int test_int = WXUtils.getInt("23px"); assertEquals(23, test_int); }
@Test public void testGetIntWX() throws Exception { Integer test_int = WXUtils.getInt("100wx"); Integer want = (int)(100 * TEST_DENSITY * 750 / TEST_SCREEN_WIDTH); assertEquals(test_int, want); test_int = WXUtils.getInt("100px"); want = 100; assertEquals(test_int, want); test_int = WXUtils.getInt("100"); want = 100; assertEquals(test_int, want); test_int = WXUtils.getInt(100); want = 100; assertEquals(test_int, want); test_int = WXUtils.getInt(100.1); want = 0; assertEquals(test_int, want); } |
### Question:
WXAttr implements Map<String, Object>,Cloneable { public String getImageSrc() { Object src = get(Constants.Name.SRC); if (src == null) { return null; } return src.toString(); } WXAttr(); WXAttr(@NonNull Map<String,Object> standardMap); static String getPrefix(Map<String, Object> attr); static String getSuffix(Map<String, Object> attr); static String getValue(Map<String, Object> attr); WXImageQuality getImageQuality(); WXImageSharpen getImageSharpen(); String getImageSrc(); boolean canRecycled(); boolean showIndicators(); boolean autoPlay(); String getScope(); String getLoadMoreRetry(); String getLoadMoreOffset(); String optString(String key); boolean getIsRecycleImage(); String getScrollDirection(); float getElevation(int viewPortW); float getColumnWidth(); int getColumnCount(); float getColumnGap(); int getLayoutType(); @Override boolean equals(Object o); @Override int hashCode(); @Override void clear(); @Override boolean containsKey(Object key); @Override boolean containsValue(Object value); @NonNull @Override Set<Entry<String, Object>> entrySet(); @Override Object get(Object key); @Override boolean isEmpty(); @NonNull @Override Set<String> keySet(); @Override Object put(String key, Object value); @Override void putAll(Map<? extends String, ?> map); @Override Object remove(Object key); @Override int size(); @NonNull @Override Collection<Object> values(); }### Answer:
@Test public void testGetImageSrc() throws Exception { assertEquals(null,attr.getImageSrc()); attr.put(SRC,"test"); assertEquals("test",attr.getImageSrc()); } |
### Question:
DefaultUriAdapter implements URIAdapter { @NonNull @Override public Uri rewrite(WXSDKInstance instance, String type, Uri uri) { if (TextUtils.isEmpty(instance.getBundleUrl())) { return uri; } Uri base = Uri.parse(instance.getBundleUrl()); Uri.Builder resultBuilder = uri.buildUpon(); if (uri.isRelative()) { if(uri.getEncodedPath().length() == 0){ return base; } else { resultBuilder = buildRelativeURI(resultBuilder, base, uri); return resultBuilder.build(); } } return uri; } @NonNull @Override Uri rewrite(WXSDKInstance instance, String type, Uri uri); }### Answer:
@Test public void testRewrite() throws Exception { final String host = "http: final String base = host + "/test/123/"; final String bundleWithSlash = base + "?arg=value"; final String bundle = base + "bundle.js?arg=value"; instance.renderByUrl("", bundle, null, null, 0, 0, WXRenderStrategy.APPEND_ONCE); testRelative(host, base, bundle); instance.renderByUrl("", bundleWithSlash, null, null, 0, 0, WXRenderStrategy.APPEND_ONCE); testRelative(host, base, bundleWithSlash); } |
### Question:
WXAttr implements Map<String, Object>,Cloneable { public boolean showIndicators() { Object obj = get(Constants.Name.SHOW_INDICATORS); if (obj == null) { return true; } try { return parseBoolean(String.valueOf(obj)); } catch (Exception e) { WXLogUtils.e("[WXAttr] showIndicators:", e); } return true; } WXAttr(); WXAttr(@NonNull Map<String,Object> standardMap); static String getPrefix(Map<String, Object> attr); static String getSuffix(Map<String, Object> attr); static String getValue(Map<String, Object> attr); WXImageQuality getImageQuality(); WXImageSharpen getImageSharpen(); String getImageSrc(); boolean canRecycled(); boolean showIndicators(); boolean autoPlay(); String getScope(); String getLoadMoreRetry(); String getLoadMoreOffset(); String optString(String key); boolean getIsRecycleImage(); String getScrollDirection(); float getElevation(int viewPortW); float getColumnWidth(); int getColumnCount(); float getColumnGap(); int getLayoutType(); @Override boolean equals(Object o); @Override int hashCode(); @Override void clear(); @Override boolean containsKey(Object key); @Override boolean containsValue(Object value); @NonNull @Override Set<Entry<String, Object>> entrySet(); @Override Object get(Object key); @Override boolean isEmpty(); @NonNull @Override Set<String> keySet(); @Override Object put(String key, Object value); @Override void putAll(Map<? extends String, ?> map); @Override Object remove(Object key); @Override int size(); @NonNull @Override Collection<Object> values(); }### Answer:
@Test public void testShowIndicators() throws Exception { assertEquals(true,attr.showIndicators()); } |
### Question:
WXAttr implements Map<String, Object>,Cloneable { public boolean autoPlay() { Object obj = get(Constants.Name.AUTO_PLAY); if (obj == null) { return false; } try { return parseBoolean(String.valueOf(obj)); } catch (Exception e) { WXLogUtils.e("[WXAttr] autoPlay:", e); } return false; } WXAttr(); WXAttr(@NonNull Map<String,Object> standardMap); static String getPrefix(Map<String, Object> attr); static String getSuffix(Map<String, Object> attr); static String getValue(Map<String, Object> attr); WXImageQuality getImageQuality(); WXImageSharpen getImageSharpen(); String getImageSrc(); boolean canRecycled(); boolean showIndicators(); boolean autoPlay(); String getScope(); String getLoadMoreRetry(); String getLoadMoreOffset(); String optString(String key); boolean getIsRecycleImage(); String getScrollDirection(); float getElevation(int viewPortW); float getColumnWidth(); int getColumnCount(); float getColumnGap(); int getLayoutType(); @Override boolean equals(Object o); @Override int hashCode(); @Override void clear(); @Override boolean containsKey(Object key); @Override boolean containsValue(Object value); @NonNull @Override Set<Entry<String, Object>> entrySet(); @Override Object get(Object key); @Override boolean isEmpty(); @NonNull @Override Set<String> keySet(); @Override Object put(String key, Object value); @Override void putAll(Map<? extends String, ?> map); @Override Object remove(Object key); @Override int size(); @NonNull @Override Collection<Object> values(); }### Answer:
@Test public void testAutoPlay() throws Exception { assertEquals(false,attr.autoPlay()); } |
### Question:
WXAttr implements Map<String, Object>,Cloneable { public String getScope() { Object src = get(Constants.Name.SCOPE); if (src == null) { return null; } return src.toString(); } WXAttr(); WXAttr(@NonNull Map<String,Object> standardMap); static String getPrefix(Map<String, Object> attr); static String getSuffix(Map<String, Object> attr); static String getValue(Map<String, Object> attr); WXImageQuality getImageQuality(); WXImageSharpen getImageSharpen(); String getImageSrc(); boolean canRecycled(); boolean showIndicators(); boolean autoPlay(); String getScope(); String getLoadMoreRetry(); String getLoadMoreOffset(); String optString(String key); boolean getIsRecycleImage(); String getScrollDirection(); float getElevation(int viewPortW); float getColumnWidth(); int getColumnCount(); float getColumnGap(); int getLayoutType(); @Override boolean equals(Object o); @Override int hashCode(); @Override void clear(); @Override boolean containsKey(Object key); @Override boolean containsValue(Object value); @NonNull @Override Set<Entry<String, Object>> entrySet(); @Override Object get(Object key); @Override boolean isEmpty(); @NonNull @Override Set<String> keySet(); @Override Object put(String key, Object value); @Override void putAll(Map<? extends String, ?> map); @Override Object remove(Object key); @Override int size(); @NonNull @Override Collection<Object> values(); }### Answer:
@Test public void testGetScope() throws Exception { assertEquals(null,attr.getScope()); } |
### Question:
WXAttr implements Map<String, Object>,Cloneable { public String getLoadMoreRetry() { Object src = get(Constants.Name.LOADMORERETRY); if (src == null) { return null; } return src.toString(); } WXAttr(); WXAttr(@NonNull Map<String,Object> standardMap); static String getPrefix(Map<String, Object> attr); static String getSuffix(Map<String, Object> attr); static String getValue(Map<String, Object> attr); WXImageQuality getImageQuality(); WXImageSharpen getImageSharpen(); String getImageSrc(); boolean canRecycled(); boolean showIndicators(); boolean autoPlay(); String getScope(); String getLoadMoreRetry(); String getLoadMoreOffset(); String optString(String key); boolean getIsRecycleImage(); String getScrollDirection(); float getElevation(int viewPortW); float getColumnWidth(); int getColumnCount(); float getColumnGap(); int getLayoutType(); @Override boolean equals(Object o); @Override int hashCode(); @Override void clear(); @Override boolean containsKey(Object key); @Override boolean containsValue(Object value); @NonNull @Override Set<Entry<String, Object>> entrySet(); @Override Object get(Object key); @Override boolean isEmpty(); @NonNull @Override Set<String> keySet(); @Override Object put(String key, Object value); @Override void putAll(Map<? extends String, ?> map); @Override Object remove(Object key); @Override int size(); @NonNull @Override Collection<Object> values(); }### Answer:
@Test public void testGetLoadMoreRetry() throws Exception { assertEquals(null,attr.getLoadMoreRetry()); } |
### Question:
WXAttr implements Map<String, Object>,Cloneable { public String getLoadMoreOffset() { Object src = get(Constants.Name.LOADMOREOFFSET); if (src == null) { return null; } return src.toString(); } WXAttr(); WXAttr(@NonNull Map<String,Object> standardMap); static String getPrefix(Map<String, Object> attr); static String getSuffix(Map<String, Object> attr); static String getValue(Map<String, Object> attr); WXImageQuality getImageQuality(); WXImageSharpen getImageSharpen(); String getImageSrc(); boolean canRecycled(); boolean showIndicators(); boolean autoPlay(); String getScope(); String getLoadMoreRetry(); String getLoadMoreOffset(); String optString(String key); boolean getIsRecycleImage(); String getScrollDirection(); float getElevation(int viewPortW); float getColumnWidth(); int getColumnCount(); float getColumnGap(); int getLayoutType(); @Override boolean equals(Object o); @Override int hashCode(); @Override void clear(); @Override boolean containsKey(Object key); @Override boolean containsValue(Object value); @NonNull @Override Set<Entry<String, Object>> entrySet(); @Override Object get(Object key); @Override boolean isEmpty(); @NonNull @Override Set<String> keySet(); @Override Object put(String key, Object value); @Override void putAll(Map<? extends String, ?> map); @Override Object remove(Object key); @Override int size(); @NonNull @Override Collection<Object> values(); }### Answer:
@Test public void testGetLoadMoreOffset() throws Exception { assertEquals(null,attr.getLoadMoreOffset()); } |
### Question:
WXAttr implements Map<String, Object>,Cloneable { public boolean getIsRecycleImage() { Object obj = get(Constants.Name.RECYCLE_IMAGE); if (obj == null) { return true; } try { return parseBoolean(String.valueOf(obj)); } catch (Exception e) { WXLogUtils.e("[WXAttr] recycleImage:", e); } return false; } WXAttr(); WXAttr(@NonNull Map<String,Object> standardMap); static String getPrefix(Map<String, Object> attr); static String getSuffix(Map<String, Object> attr); static String getValue(Map<String, Object> attr); WXImageQuality getImageQuality(); WXImageSharpen getImageSharpen(); String getImageSrc(); boolean canRecycled(); boolean showIndicators(); boolean autoPlay(); String getScope(); String getLoadMoreRetry(); String getLoadMoreOffset(); String optString(String key); boolean getIsRecycleImage(); String getScrollDirection(); float getElevation(int viewPortW); float getColumnWidth(); int getColumnCount(); float getColumnGap(); int getLayoutType(); @Override boolean equals(Object o); @Override int hashCode(); @Override void clear(); @Override boolean containsKey(Object key); @Override boolean containsValue(Object value); @NonNull @Override Set<Entry<String, Object>> entrySet(); @Override Object get(Object key); @Override boolean isEmpty(); @NonNull @Override Set<String> keySet(); @Override Object put(String key, Object value); @Override void putAll(Map<? extends String, ?> map); @Override Object remove(Object key); @Override int size(); @NonNull @Override Collection<Object> values(); }### Answer:
@Test public void testGetIsRecycleImage() throws Exception { assertEquals(true,attr.getIsRecycleImage()); } |
### Question:
WXAttr implements Map<String, Object>,Cloneable { public String getScrollDirection() { Object scrollDirection = get("scrollDirection"); if (scrollDirection == null) { return "vertical"; } return scrollDirection.toString(); } WXAttr(); WXAttr(@NonNull Map<String,Object> standardMap); static String getPrefix(Map<String, Object> attr); static String getSuffix(Map<String, Object> attr); static String getValue(Map<String, Object> attr); WXImageQuality getImageQuality(); WXImageSharpen getImageSharpen(); String getImageSrc(); boolean canRecycled(); boolean showIndicators(); boolean autoPlay(); String getScope(); String getLoadMoreRetry(); String getLoadMoreOffset(); String optString(String key); boolean getIsRecycleImage(); String getScrollDirection(); float getElevation(int viewPortW); float getColumnWidth(); int getColumnCount(); float getColumnGap(); int getLayoutType(); @Override boolean equals(Object o); @Override int hashCode(); @Override void clear(); @Override boolean containsKey(Object key); @Override boolean containsValue(Object value); @NonNull @Override Set<Entry<String, Object>> entrySet(); @Override Object get(Object key); @Override boolean isEmpty(); @NonNull @Override Set<String> keySet(); @Override Object put(String key, Object value); @Override void putAll(Map<? extends String, ?> map); @Override Object remove(Object key); @Override int size(); @NonNull @Override Collection<Object> values(); }### Answer:
@Test public void testGetScrollDirection() throws Exception { assertEquals("vertical",attr.getScrollDirection()); } |
### Question:
WXDomModule extends WXModule { public void callDomMethod(JSONObject task) { if (task == null) { return; } String method = (String) task.get(WXBridgeManager.METHOD); JSONArray args = (JSONArray) task.get(WXBridgeManager.ARGS); callDomMethod(method,args); } WXDomModule(WXSDKInstance instance); void callDomMethod(JSONObject task); Object callDomMethod(String method, JSONArray args); void invokeMethod(String ref, String method, JSONArray args); void postAction(RenderAction action); void postAction(DOMAction action, boolean createContext); static final String CREATE_BODY; static final String UPDATE_ATTRS; static final String UPDATE_STYLE; static final String REMOVE_ELEMENT; static final String ADD_ELEMENT; static final String MOVE_ELEMENT; static final String ADD_EVENT; static final String REMOVE_EVENT; static final String CREATE_FINISH; static final String REFRESH_FINISH; static final String UPDATE_FINISH; static final String SCROLL_TO_ELEMENT; static final String ADD_RULE; static final String GET_COMPONENT_RECT; static final String WXDOM; static final String INVOKE_METHOD; static final String[] METHODS; }### Answer:
@Test public void testCallDomMethod() throws Exception { module.callDomMethod(null); JSONObject obj = new JSONObject(); for (String m : METHODS) { obj.put(WXBridgeManager.METHOD,m); module.callDomMethod(obj); } obj = new JSONObject(); for (Object[] args:ARGS_CASES ) { JSONArray ary = new JSONArray(); if(args == null){ ary = null; }else { for (Object arg : args ) { ary.add(arg); } } obj.put(WXBridgeManager.ARGS,ary); for (String m : METHODS) { obj.put(WXBridgeManager.METHOD,m); module.callDomMethod(obj); } } } |