com.twitter.sdk.android.core.Result Java Examples

The following examples show how to use com.twitter.sdk.android.core.Result. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TweetActivity.java    From twitter-kit-android with Apache License 2.0 6 votes vote down vote up
/**
 * loadTweets wraps TweetUtils.loadTweets to use a callback that ensures each view is given
 * a known id to simplify UI automation testing.
 */
private void loadTweets(final List<Long> tweetIds, final ViewGroup container,
                        final List<Integer> viewIds) {
    TweetUtils.loadTweets(tweetIds, new Callback<List<Tweet>>() {
        @Override
        public void success(Result<List<Tweet>> result) {
            final Context context = getActivity();
            if (context == null) return;
            for (int i = 0; i < result.data.size(); i++) {
                final BaseTweetView tv = new CompactTweetView(context, result.data.get(i),
                        R.style.tw__TweetDarkWithActionsStyle);
                tv.setOnActionCallback(actionCallback);
                tv.setId(viewIds.get(i));
                container.addView(tv);
            }
        }

        @Override
        public void failure(TwitterException exception) {
            Log.e(TAG, "loadTweets failure " + tweetIds, exception);
        }
    });
}
 
Example #2
Source File: TwitterNetwork.java    From EasyLogin with MIT License 6 votes vote down vote up
@Override
public void success(Result<TwitterSession> result) {
    TwitterSession session = result.data;
    TwitterAuthToken authToken = session.getAuthToken();
    String token = authToken.token;
    String secret = authToken.secret;
    AccessToken tempToken = new AccessToken.Builder(token)
            .secret(secret)
            .userName(session.getUserName())
            .userId(String.valueOf(session.getUserId()))
            .build();
    if (additionalEmailRequest) {
        requestEmail(session, tempToken);
    } else {
        accessToken = tempToken;
        callLoginSuccess();
    }

}
 
Example #3
Source File: TwitterNetwork.java    From EasyLogin with MIT License 6 votes vote down vote up
private void requestEmail(final TwitterSession session, final AccessToken tempToken) {
    TwitterAuthClient authClient = new TwitterAuthClient();
    authClient.requestEmail(session, new Callback<String>() {
        @Override
        public void success(Result<String> result) {
            final String email = result.data;
            if (TextUtils.isEmpty(email)) {
                logout();
                callLoginFailure("Before fetching an email, ensure that 'Request email addresses from users' is checked for your Twitter app.");
                return;
            }
            accessToken = new AccessToken.Builder(tempToken).email(email).build();
            callLoginSuccess();
        }

        @Override
        public void failure(TwitterException exception) {
            Log.e("TwitterNetwork", "Before fetching an email, ensure that 'Request email addresses from users' is checked for your Twitter app.");
            callLoginFailure(exception.getMessage());
        }
    });
}
 
Example #4
Source File: OAuth1aServiceTest.java    From twitter-kit-android with Apache License 2.0 6 votes vote down vote up
@Test
public void testCallbackWrapperSuccess() throws IOException {
    final String response = "oauth_token=7588892-kagSNqWge8gB1WwE3plnFsJHAZVfxWD7Vb57p0b4&"
            + "oauth_token_secret=PbKfYqSryyeKDWz4ebtY3o5ogNLG11WJuZBc9fQrQo&"
            + "screen_name=test&user_id=1";
    final Callback<OAuthResponse> callback = new Callback<OAuthResponse>() {
        @Override
        public void success(Result<OAuthResponse> result) {
            final OAuthResponse authResponse = result.data;
            assertEquals("7588892-kagSNqWge8gB1WwE3plnFsJHAZVfxWD7Vb57p0b4",
                    authResponse.authToken.token);
            assertEquals("PbKfYqSryyeKDWz4ebtY3o5ogNLG11WJuZBc9fQrQo",
                    authResponse.authToken.secret);
            assertEquals("test", authResponse.userName);
            assertEquals(1L, authResponse.userId);
        }

        @Override
        public void failure(TwitterException exception) {
            fail();
        }
    };
    setupCallbackWrapperTest(response, callback);
}
 
Example #5
Source File: OAuth1aServiceTest.java    From twitter-kit-android with Apache License 2.0 6 votes vote down vote up
@Test
public void testCallbackWrapperSuccess_noToken() throws IOException {
    final String response = "oauth_token_secret=PbKfYqSryyeKDWz4ebtY3o5ogNLG11WJuZBc9fQrQo&"
            + "screen_name=test&user_id=1";
    final Callback<OAuthResponse> callback = new Callback<OAuthResponse>() {
        @Override
        public void success(Result<OAuthResponse> result) {
            fail();
        }

        @Override
        public void failure(TwitterException exception) {
            assertNotNull(exception);
        }
    };
    setupCallbackWrapperTest(response, callback);
}
 
Example #6
Source File: TwitterSignUpActivity.java    From socialmediasignup with MIT License 6 votes vote down vote up
private void handleSuccess(final TwitterSession session) {
    TwitterApiClient twitterApiClient = TwitterCore.getInstance().getApiClient();
    AccountService accountService = twitterApiClient.getAccountService();
    call = accountService.verifyCredentials(false, true, true);
    call.enqueue(new Callback<User>() {
        @Override
        public void success(Result<User> userResult) {
            SocialMediaUser user = new SocialMediaUser();
            User data = userResult.data;
            user.setUserId(String.valueOf(data.getId()));
            user.setAccessToken(session.getAuthToken().token);
            user.setProfilePictureUrl(String.format(PROFILE_PIC_URL, data.screenName));
            user.setEmail(data.email != null ? data.email : "");
            user.setFullName(data.name);
            user.setUsername(data.screenName);
            user.setPageLink(String.format(PAGE_LINK, data.screenName));
            handleSuccess(SocialMediaSignUp.SocialMediaType.TWITTER, user);
        }

        public void failure(TwitterException error) {
            handleError(error);
        }
    });
}
 
Example #7
Source File: LoginActivity.java    From Simple-Blog-App with MIT License 6 votes vote down vote up
private void twitter() {
    TwitterConfig config = new TwitterConfig.Builder(this)
            .logger(new DefaultLogger(Log.DEBUG))
            .twitterAuthConfig(new TwitterAuthConfig(getResources().getString(R.string.com_twitter_sdk_android_CONSUMER_KEY), getResources().getString(R.string.com_twitter_sdk_android_CONSUMER_SECRET)))
            .debug(true)
            .build();
    Twitter.initialize(config);
    twitterLoginButton.setCallback(new Callback<TwitterSession>() {
        @Override
        public void success(Result<TwitterSession> result) {
            Log.d(TAG, "twitterLogin:success" + result);
            handleTwitterSession(result.data);
        }

        @Override
        public void failure(TwitterException exception) {
            Log.w(TAG, "twitterLogin:failure", exception);

        }
    });
}
 
Example #8
Source File: AuthHandler.java    From twitter-kit-android with Apache License 2.0 6 votes vote down vote up
/**
 * Called when {@link android.app.Activity#onActivityResult(int, int, android.content.Intent)}
 * is called to complete the authorization flow.
 *
 * @param requestCode the request code used for SSO
 * @param resultCode  the result code returned by the SSO activity
 * @param data        the result data returned by the SSO activity
 */
public boolean handleOnActivityResult(int requestCode, int resultCode, Intent data) {
    if (this.requestCode != requestCode) {
        return false;
    }

    final Callback<TwitterSession> callback = getCallback();
    if (callback != null) {
        if (resultCode == Activity.RESULT_OK) {
            final String token = data.getStringExtra(EXTRA_TOKEN);
            final String tokenSecret = data.getStringExtra(EXTRA_TOKEN_SECRET);
            final String screenName = data.getStringExtra(EXTRA_SCREEN_NAME);
            final long userId = data.getLongExtra(EXTRA_USER_ID, 0L);
            callback.success(new Result<>(new TwitterSession(
                    new TwitterAuthToken(token, tokenSecret), userId, screenName), null));
        } else if (data != null && data.hasExtra(EXTRA_AUTH_ERROR)) {
            callback.failure(
                    (TwitterAuthException) data.getSerializableExtra(EXTRA_AUTH_ERROR));
        } else {
            callback.failure(new TwitterAuthException("Authorize failed."));
        }
    }
    return true;
}
 
Example #9
Source File: TwitterAuthClient.java    From twitter-kit-android with Apache License 2.0 6 votes vote down vote up
/**
 * Requests the user's email address.
 *
 * @param session the user session
 * @param callback The callback interface to invoke when the request completes. If the user
 *                 denies access to the email address, or the email address is not available,
 *                 an error is returned.
 * @throws java.lang.IllegalArgumentException if session or callback are null.
 */
public void requestEmail(TwitterSession session, final Callback<String> callback) {
    final Call<User> verifyRequest = twitterCore.getApiClient(session).getAccountService()
            .verifyCredentials(false, false, true);

    verifyRequest.enqueue(new Callback<User>() {
        @Override
        public void success(Result<User> result) {
            callback.success(new Result<>(result.data.email, null));
        }

        @Override
        public void failure(TwitterException exception) {
            callback.failure(exception);
        }
    });
}
 
Example #10
Source File: FabricTwitterKitModule.java    From react-native-fabric-twitterkit with MIT License 6 votes vote down vote up
@ReactMethod
public void login(final Callback callback) {

    loginButton = new TwitterLoginButton(getCurrentActivity());
    loginButton.setCallback(new com.twitter.sdk.android.core.Callback<TwitterSession>() {
        @Override
        public void success(Result<TwitterSession> sessionResult) {
            WritableMap result = new WritableNativeMap();
            result.putString("authToken", sessionResult.data.getAuthToken().token);
            result.putString("authTokenSecret",sessionResult.data.getAuthToken().secret);
            result.putString("userID", sessionResult.data.getUserId()+"");
            result.putString("userName", sessionResult.data.getUserName());
            callback.invoke(null, result);
        }

        @Override
        public void failure(TwitterException exception) {
            exception.printStackTrace();
            callback.invoke(exception.getMessage());
        }
    });

    loginButton.performClick();
}
 
Example #11
Source File: OAuthController.java    From twitter-kit-android with Apache License 2.0 6 votes vote down vote up
/**
 * Package private for testing.
 */
Callback<OAuthResponse> newRequestTempTokenCallback() {
    return new Callback<OAuthResponse>() {
        @Override
        public void success(Result<OAuthResponse> result) {
            requestToken = result.data.authToken;
            final String authorizeUrl = oAuth1aService.getAuthorizeUrl(requestToken);
            // Step 2. Redirect user to web view to complete authorization flow.
            Twitter.getLogger().d(TwitterCore.TAG,
                    "Redirecting user to web view to complete authorization flow");
            setUpWebView(webView,
                    new OAuthWebViewClient(oAuth1aService.buildCallbackUrl(authConfig),
                            OAuthController.this), authorizeUrl, new OAuthWebChromeClient());
        }

        @Override
        public void failure(TwitterException error) {
            Twitter.getLogger().e(TwitterCore.TAG,
                    "Failed to get request token", error);
            // Create new exception that can be safely serialized since Retrofit errors may
            // throw a NotSerializableException.
            handleAuthError(AuthHandler.RESULT_CODE_ERROR,
                    new TwitterAuthException("Failed to get request token"));
        }
    };
}
 
Example #12
Source File: TimelineObservable.java    From photosearcher with Apache License 2.0 6 votes vote down vote up
public void next(Long maxPosition) {
    if (!mTimelineStateHolder.startTimelineRequest()) {
        return;
    }
    mTimeline.next(maxPosition, new Callback<TimelineResult<Tweet>>() {
        @Override
        public void success(Result<TimelineResult<Tweet>> result) {
            mTimelineStateHolder.setNextCursor(result.data.timelineCursor);
            mTweets.addAll(0, result.data.items);

            mNextSubject.onNext(new DataSetInsertResult(0, result.data.items.size()));

            mTimelineStateHolder.finishTimelineRequest();
        }

        @Override
        public void failure(TwitterException e) {
            mNextSubject.onError(e);

            mTimelineStateHolder.finishTimelineRequest();
        }
    });
}
 
Example #13
Source File: TimelineObservable.java    From photosearcher with Apache License 2.0 6 votes vote down vote up
private void fetchPrevious(Long minPosition) {
    mTimeline.previous(minPosition, new Callback<TimelineResult<Tweet>>() {
        @Override
        public void success(Result<TimelineResult<Tweet>> result) {
            mTimelineStateHolder.setPreviousCursor(result.data.timelineCursor);
            if (mRefreshing) {
                mTweets.clear();
            }
            int position = mTweets.size();
            mTweets.addAll(result.data.items);

            mPreviousSubject.onNext(new DataSetInsertResult(position, result.data.items.size()));

            mTimelineStateHolder.finishTimelineRequest();
            mRefreshing = false;
        }

        @Override
        public void failure(TwitterException e) {
            mPreviousSubject.onError(e);

            mTimelineStateHolder.finishTimelineRequest();
            mRefreshing = false;
        }
    });
}
 
Example #14
Source File: OAuth1aServiceTest.java    From twitter-kit-android with Apache License 2.0 6 votes vote down vote up
@Test
public void testCallbackWrapperSuccess_iOException() throws IOException {
    final Callback<OAuthResponse> callback = new Callback<OAuthResponse>() {
        @Override
        public void success(Result<OAuthResponse> result) {
            fail();
        }

        @Override
        public void failure(TwitterException exception) {
            assertNotNull(exception);
        }
    };
    final Callback<ResponseBody> callbackWrapper = service.getCallbackWrapper(callback);
    final ResponseBody responseBody = ResponseBody.create(MediaType.parse("application/json"), "");
    callbackWrapper.success(new Result<>(responseBody, Response.success(responseBody)));
}
 
Example #15
Source File: OAuthControllerTest.java    From twitter-kit-android with Apache License 2.0 6 votes vote down vote up
@Test
public void testNewAccessTokenCallback_success() {
    final Callback<OAuthResponse> callback = controller.newRequestAccessTokenCallback();
    final OAuthResponse oAuthResponse = new OAuthResponse(
            new TwitterAuthToken(TestFixtures.TOKEN, TestFixtures.SECRET),
            TestFixtures.SCREEN_NAME, TestFixtures.USER_ID);
    callback.success(new Result<>(oAuthResponse, null));

    final ArgumentCaptor<Intent> intentArgCaptor = ArgumentCaptor.forClass(Intent.class);
    verify(mockListener).onComplete(eq(Activity.RESULT_OK), intentArgCaptor.capture());
    final Intent data = intentArgCaptor.getValue();
    assertEquals(TestFixtures.SCREEN_NAME, data.getStringExtra(AuthHandler.EXTRA_SCREEN_NAME));
    assertEquals(TestFixtures.USER_ID, data.getLongExtra(AuthHandler.EXTRA_USER_ID, 0L));
    assertEquals(TestFixtures.TOKEN, data.getStringExtra(AuthHandler.EXTRA_TOKEN));
    assertEquals(TestFixtures.SECRET, data.getStringExtra(AuthHandler.EXTRA_TOKEN_SECRET));
}
 
Example #16
Source File: TweetActivity.java    From twitter-kit-android with Apache License 2.0 6 votes vote down vote up
/**
 * loadTweet wraps TweetUtils.loadTweet with a callback that ensures the view is given a
 * known id to simplify UI automation testing.
 */
private void loadTweet(long tweetId, final ViewGroup container, final int viewId) {
    final Callback<Tweet> singleTweetCallback = new Callback<Tweet>() {
        @Override
        public void success(Result<Tweet> result) {
            final Context context = getActivity();
            if (context == null) return;
            final Tweet tweet = result.data;
            final BaseTweetView tv = new TweetView(context, tweet,
                    R.style.tw__TweetLightWithActionsStyle);
            tv.setOnActionCallback(actionCallback);
            tv.setId(viewId);
            container.addView(tv);
        }

        @Override
        public void failure(TwitterException exception) {
            Log.e(TAG, "loadTweet failure", exception);
        }
    };
    TweetUtils.loadTweet(tweetId, singleTweetCallback);
}
 
Example #17
Source File: FixedTweetTimelineTest.java    From twitter-kit-android with Apache License 2.0 6 votes vote down vote up
@Test
public void testNext_succeedsWithFixedTweets() {
    final FixedTweetTimeline timeline = new FixedTweetTimeline(fixedTweets);
    timeline.next(ANY_ID, new Callback<TimelineResult<Tweet>>() {
        @Override
        public void success(Result<TimelineResult<Tweet>> result) {
            assertEquals(fixedTweets, result.data.items);
            assertEquals((Long) TestFixtures.TEST_PHOTO_TWEET.getId(),
                    result.data.timelineCursor.minPosition);
            assertEquals((Long) TestFixtures.TEST_TWEET.getId(),
                    result.data.timelineCursor.maxPosition);
            assertNull(result.response);
        }
        @Override
        public void failure(TwitterException exception) {
            fail("Expected FixedTweetTimeline next to always succeed.");
        }
    });
}
 
Example #18
Source File: TwitterServiceImpl.java    From twittererer with Apache License 2.0 6 votes vote down vote up
public Observable<Boolean> sendTweet(String tweetText) {
    return Observable.create(subscriber -> {
        Callback<Tweet> callback = new Callback<Tweet>() {
            @Override
            public void success(Result<Tweet> result) {
                Log.i(TAG, "Tweet tweeted");
                subscriber.onNext(true);
            }

            @Override
            public void failure(TwitterException e) {
                Log.e(TAG, e.getMessage(), e);
                subscriber.onError(e);
            }
        };

        getStatusesService().update(tweetText, null, null, null, null, null, null, null, null).enqueue(callback);
    });
}
 
Example #19
Source File: FixedTweetTimelineTest.java    From twitter-kit-android with Apache License 2.0 6 votes vote down vote up
@Test
public void testNext_succeedsWithEmptyTweets() {
    final FixedTweetTimeline timeline = new FixedTweetTimeline(fixedTweets);
    timeline.previous(ANY_ID, new Callback<TimelineResult<Tweet>>() {
        @Override
        public void success(Result<TimelineResult<Tweet>> result) {
            assertTrue(result.data.items.isEmpty());
            assertNull(result.data.timelineCursor.maxPosition);
            assertNull(result.data.timelineCursor.minPosition);
            assertNull(result.response);
        }

        @Override
        public void failure(TwitterException exception) {
            fail("Expected FixedTweetTimeline previous to always succeed.");
        }
    });
}
 
Example #20
Source File: OAuth2ServiceTest.java    From twitter-kit-android with Apache License 2.0 6 votes vote down vote up
@Test
public void testRequestGuestAuthToken_guestAuthSuccess() {

    service.api = new MockOAuth2Api();
    service.requestGuestAuthToken(new Callback<GuestAuthToken>() {
        @Override
        public void success(Result<GuestAuthToken> result) {
            assertEquals(GUEST_TOKEN, result.data);
        }

        @Override
        public void failure(TwitterException error) {
            fail();
        }
    });
}
 
Example #21
Source File: TimelineDelegateTest.java    From twitter-kit-android with Apache License 2.0 6 votes vote down vote up
@Test
public void testPreviousCallback_successReceivedItems() {
    delegate = new TimelineDelegate<>(mockTimeline, mockObservable, testItems);
    final TimelineStateHolder timelineStateHolder = new TimelineStateHolder(
            new TimelineCursor(ANY_POSITION, ANY_POSITION),
            new TimelineCursor(ANY_POSITION, ANY_POSITION));
    final TimelineDelegate.PreviousCallback cb
            = delegate.new PreviousCallback(timelineStateHolder);
    cb.success(new Result<>(new TimelineResult<>(TEST_TIMELINE_CURSOR, testExtraItems), null));
    // assert the previous TimelineCursor is set on the ScrollStateHolder
    assertEquals(TEST_MIN_POSITION, timelineStateHolder.positionForPrevious());
    assertEquals(ANY_POSITION, timelineStateHolder.positionForNext());
    // assert that extra items were appended in order received
    assertEquals(TOTAL_ITEMS, delegate.itemList.size());
    assertEquals(TEST_ITEM_2, delegate.getItem(0));
    assertEquals(TEST_ITEM_1, delegate.getItem(1));
    assertEquals(TEST_ITEM_4, delegate.getItem(2));
    assertEquals(TEST_ITEM_3, delegate.getItem(3));
    // assert observer's notifyChanged is called
    verify(mockObservable).notifyChanged();
}
 
Example #22
Source File: TweetUploadService.java    From twitter-kit-android with Apache License 2.0 6 votes vote down vote up
void uploadTweetWithMedia(TwitterSession session, String text, String mediaId) {
    final TwitterApiClient client = dependencyProvider.getTwitterApiClient(session);

    client.getStatusesService().update(text, null, null, null, null, null, null, true, mediaId)
            .enqueue(
                    new Callback<Tweet>() {
                        @Override
                        public void success(Result<Tweet> result) {
                            sendSuccessBroadcast(result.data.getId());
                            stopSelf();
                        }

                        @Override
                        public void failure(TwitterException exception) {
                            fail(exception);
                        }
                    });
}
 
Example #23
Source File: TimelineDelegateTest.java    From twitter-kit-android with Apache License 2.0 6 votes vote down vote up
@Test
public void testRefreshCallback_successReceivedItems() {
    delegate = new TimelineDelegate<>(mockTimeline, mockObservable, testItems);
    final TimelineStateHolder timelineStateHolder = new TimelineStateHolder(
            new TimelineCursor(ANY_POSITION, ANY_POSITION),
            new TimelineCursor(ANY_POSITION, ANY_POSITION));
    final TimelineDelegate.RefreshCallback cb = delegate.new RefreshCallback(null,
            timelineStateHolder);
    cb.success(new Result<>(new TimelineResult<>(TEST_TIMELINE_CURSOR, testExtraItems), null));
    // assert the next TimelineCursor is set on the ScrollStateHolder, previous unchanged
    assertEquals(TEST_MAX_POSITION, timelineStateHolder.positionForNext());
    assertEquals(ANY_POSITION, timelineStateHolder.positionForPrevious());
    // assert that extra items replaced the old items
    assertEquals(testExtraItems.size(), delegate.itemList.size());
    assertEquals(TEST_ITEM_4, delegate.getItem(0));
    assertEquals(TEST_ITEM_3, delegate.getItem(1));
    // assert observer's notifyChanged is called
    verify(mockObservable).notifyChanged();
}
 
Example #24
Source File: TwitterAuthClientTest.java    From twitter-kit-android with Apache License 2.0 6 votes vote down vote up
@Test
public void testRequestEmail_withFailure() {
    final IOException networkException = new IOException("Network failure");
    final Call<User> call = Calls.failure(networkException);
    setupMockAccountService(call);

    authClient.requestEmail(mock(TwitterSession.class), new Callback<String>() {
        @Override
        public void success(Result<String> result) {
            fail("Expected Callback#failure to be called");
        }

        @Override
        public void failure(TwitterException exception) {
            assertEquals(exception.getCause(), networkException);
        }
    });
}
 
Example #25
Source File: BaseTweetView.java    From twitter-kit-android with Apache License 2.0 6 votes vote down vote up
/**
 * LoadTweet will trigger a request to the Twitter API and hydrate the view with the result.
 * In the event of an error it will call the listener that was provided to setOnTwitterApiError.
 */
private void loadTweet() {
    final long tweetId = getTweetId();
    // create a callback to setTweet on the view or log a failure to load the Tweet
    final Callback<Tweet> repoCb = new Callback<Tweet>() {
        @Override
        public void success(Result<Tweet> result) {
            setTweet(result.data);
        }

        @Override
        public void failure(TwitterException exception) {
            Twitter.getLogger().d(TAG,
                    String.format(Locale.ENGLISH, TweetUtils.LOAD_TWEET_DEBUG, tweetId));
        }
    };
    dependencyProvider.getTweetUi().getTweetRepository().loadTweet(getTweetId(), repoCb);
}
 
Example #26
Source File: TimelineDelegateTest.java    From twitter-kit-android with Apache License 2.0 6 votes vote down vote up
@Test
public void testNextCallback_successReceivedItems() {
    delegate = new TimelineDelegate<>(mockTimeline, mockObservable, testItems);
    final TimelineStateHolder timelineStateHolder = new TimelineStateHolder(
            new TimelineCursor(ANY_POSITION, ANY_POSITION),
            new TimelineCursor(ANY_POSITION, ANY_POSITION));
    final TimelineDelegate.NextCallback cb = delegate.new NextCallback(null,
            timelineStateHolder);
    cb.success(new Result<>(new TimelineResult<>(TEST_TIMELINE_CURSOR, testExtraItems), null));
    // assert the next TimelineCursor is set on the ScrollStateHolder, previous unchanged
    assertEquals(TEST_MAX_POSITION, timelineStateHolder.positionForNext());
    assertEquals(ANY_POSITION, timelineStateHolder.positionForPrevious());
    // assert that extra items were prepended in reverse order
    assertEquals(TOTAL_ITEMS, delegate.itemList.size());
    assertEquals(TEST_ITEM_4, delegate.getItem(0));
    assertEquals(TEST_ITEM_3, delegate.getItem(1));
    assertEquals(TEST_ITEM_2, delegate.getItem(2));
    assertEquals(TEST_ITEM_1, delegate.getItem(3));
    // assert observer's notifyChanged is called
    verify(mockObservable).notifyChanged();
}
 
Example #27
Source File: LikeTweetActionTest.java    From twitter-kit-android with Apache License 2.0 6 votes vote down vote up
@Test
public void testFavoriteCallback_failureAlreadyFavorited() {
    final ToggleImageButton mockToggleButton = mock(ToggleImageButton.class);
    // locally unfavorited, but on server the tweet is favorited
    final Tweet tweet = TestFixtures.TEST_TWEET;
    final LikeTweetAction.LikeCallback callback
            = new LikeTweetAction.LikeCallback(mockToggleButton, tweet,
            mockCallback);
    final TwitterApiException alreadyFavoritedException = mock(TwitterApiException.class);
    when(alreadyFavoritedException.getErrorCode()).thenReturn(
            TwitterApiConstants.Errors.ALREADY_FAVORITED);
    // assert that
    // - the failure is treated as a cb success
    // - success result Tweet is marked as favorited
    callback.failure(alreadyFavoritedException);
    final ArgumentCaptor<Result<Tweet>> resultCaptor
            = ArgumentCaptor.forClass(Result.class);
    verify(mockCallback).success(resultCaptor.capture());
    assertEquals(tweet.getId(), resultCaptor.getValue().data.getId());
    assertTrue(resultCaptor.getValue().data.favorited);
}
 
Example #28
Source File: TwitterCoreMainActivity.java    From twitter-kit-android with Apache License 2.0 5 votes vote down vote up
private static void requestEmailAddress(final Context context, TwitterSession session) {
    new TwitterAuthClient().requestEmail(session, new Callback<String>() {
        @Override
        public void success(Result<String> result) {
            Toast.makeText(context, result.data, Toast.LENGTH_SHORT).show();
        }

        @Override
        public void failure(TwitterException exception) {
            Toast.makeText(context, exception.getMessage(), Toast.LENGTH_SHORT).show();
        }
    });
}
 
Example #29
Source File: TweetTimelineRecyclerViewAdapterTest.java    From twitter-kit-android with Apache License 2.0 5 votes vote down vote up
@Override
public void next(Long sinceId, Callback<TimelineResult<Tweet>> cb) {
    final List<Tweet> tweets = TestFixtures.getTweetList(numItems);
    final TimelineCursor timelineCursor = new TimelineCursor(tweets);
    final TimelineResult<Tweet> timelineResult
            = new TimelineResult<>(timelineCursor, tweets);
    cb.success(new Result<>(timelineResult, null));
}
 
Example #30
Source File: TwitterAuthClientTest.java    From twitter-kit-android with Apache License 2.0 5 votes vote down vote up
@Test
public void testCallbackWrapper_success() {
    final TwitterAuthClient.CallbackWrapper callbackWrapper
            = new TwitterAuthClient.CallbackWrapper(mockSessionManager, mockCallback);

    final TwitterSession mockSession = mock(TwitterSession.class);
    final Result<TwitterSession> mockResult = new Result<>(mockSession, null);
    callbackWrapper.success(mockResult);

    verify(mockSessionManager).setActiveSession(eq(mockSession));
    verify(mockCallback).success(eq(mockResult));
}