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

The following examples show how to use com.twitter.sdk.android.core.TwitterSession. 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: 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 #2
Source File: TwitterAuthClient.java    From twitter-kit-android with Apache License 2.0 6 votes vote down vote up
/**
 * Requests authorization.
 *
 * @param activity The {@link android.app.Activity} context to use for the authorization flow.
 * @param callback The callback interface to invoke when authorization completes.
 * @throws java.lang.IllegalArgumentException if activity or callback is null.
 */
public void authorize(Activity activity, Callback<TwitterSession> callback) {
    if (activity == null) {
        throw new IllegalArgumentException("Activity must not be null.");
    }
    if (callback == null) {
        throw new IllegalArgumentException("Callback must not be null.");
    }

    if (activity.isFinishing()) {
        Twitter.getLogger()
                .e(TwitterCore.TAG, "Cannot authorize, activity is finishing.", null);
    } else {
        handleAuthorize(activity, callback);
    }
}
 
Example #3
Source File: TweetUploadService.java    From twitter-kit-android with Apache License 2.0 6 votes vote down vote up
void uploadTweet(final TwitterSession session, final String text, final Uri imageUri) {
    if (imageUri != null) {
        uploadMedia(session, imageUri, new Callback<Media>() {
            @Override
            public void success(Result<Media> result) {
                uploadTweetWithMedia(session, text, result.data.mediaIdString);
            }

            @Override
            public void failure(TwitterException exception) {
                fail(exception);
            }

        });
    } else {
        uploadTweetWithMedia(session, text, null);
    }
}
 
Example #4
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 #5
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 #6
Source File: LoginActivity.java    From cannonball-android with Apache License 2.0 6 votes vote down vote up
private void setUpTwitterButton() {
    twitterButton = (TwitterLoginButton) findViewById(R.id.twitter_button);
    twitterButton.setCallback(new Callback<TwitterSession>() {
        @Override
        public void success(Result<TwitterSession> result) {
            SessionRecorder.recordSessionActive("Login: twitter account active", result.data);
            Answers.getInstance().logLogin(new LoginEvent().putMethod("Twitter").putSuccess(true));
            startThemeChooser();
        }

        @Override
        public void failure(TwitterException exception) {
            Answers.getInstance().logLogin(new LoginEvent().putMethod("Twitter").putSuccess(false));
            Toast.makeText(getApplicationContext(),
                    getResources().getString(R.string.toast_twitter_signin_fail),
                    Toast.LENGTH_SHORT).show();
            Crashlytics.logException(exception);
        }
    });
}
 
Example #7
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 #8
Source File: ComposerActivity.java    From twitter-kit-android with Apache License 2.0 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    final Intent intent = getIntent();
    final TwitterAuthToken token = intent.getParcelableExtra(EXTRA_USER_TOKEN);
    final TwitterSession session = new TwitterSession(token, PLACEHOLDER_ID,
            PLACEHOLDER_SCREEN_NAME);
    final Uri imageUri = intent.getParcelableExtra(EXTRA_IMAGE_URI);
    final String text = intent.getStringExtra(EXTRA_TEXT);
    final String hashtags = intent.getStringExtra(EXTRA_HASHTAGS);
    final int themeResId = intent.getIntExtra(EXTRA_THEME, R.style.ComposerLight);

    setTheme(themeResId);
    setContentView(R.layout.tw__activity_composer);
    final ComposerView composerView = findViewById(R.id.tw__composer_view);
    composerController = new ComposerController(composerView, session, imageUri, text, hashtags,
            new FinisherImpl());
}
 
Example #9
Source File: ComposerControllerTest.java    From twitter-kit-android with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    mockComposerView = mock(ComposerView.class);
    mockContext = mock(Context.class);
    when(mockComposerView.getContext()).thenReturn(mockContext);

    mockFinisher = mock(ComposerActivity.Finisher.class);
    mockAuthToken = mock(TwitterAuthToken.class);
    mockTwitterSession = mock(TwitterSession.class);
    when(mockTwitterSession.getAuthToken()).thenReturn(mockAuthToken);

    final TwitterApiClient mockTwitterApiClient = mock(TwitterApiClient.class);
    mockAccountService = mock(AccountService.class);
    when(mockAccountService
            .verifyCredentials(any(Boolean.class), any(Boolean.class), any(Boolean.class)))
            .thenReturn(mock(Call.class));
    when(mockTwitterApiClient.getAccountService()).thenReturn(mockAccountService);


    mockDependencyProvider = mock(ComposerController.DependencyProvider.class);
    when(mockDependencyProvider.getApiClient(any(TwitterSession.class)))
            .thenReturn(mockTwitterApiClient);
    when(mockDependencyProvider.getTweetValidator()).thenReturn(new Validator());
}
 
Example #10
Source File: TweetRepositoryTest.java    From twitter-kit-android with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    anyIds.add(anyId);
    mockTwitterCore = mock(TwitterCore.class);
    mockApiClient = mock(TwitterApiClient.class);
    mockStatusesService = mock(StatusesService.class, Mockito.RETURNS_MOCKS);
    when(mockApiClient.getStatusesService()).thenReturn(mockStatusesService);
    mockFavoriteService = mock(FavoriteService.class, Mockito.RETURNS_MOCKS);
    when(mockApiClient.getFavoriteService()).thenReturn(mockFavoriteService);
    when(mockTwitterCore.getApiClient(any(TwitterSession.class))).thenReturn(mockApiClient);
    when(mockTwitterCore.getApiClient()).thenReturn(mockApiClient);
    mockSessionManager = mock(SessionManager.class);
    when(mockSessionManager.getActiveSession()).thenReturn(mock(TwitterSession.class));
    mockHandler = mock(Handler.class);
    tweetRepository = new TweetRepository(mockHandler, mockSessionManager, mockTwitterCore);
}
 
Example #11
Source File: TwitterAuthClientTest.java    From twitter-kit-android with Apache License 2.0 6 votes vote down vote up
@Test
public void testRequestEmail_withSuccess() {
    final User user = new UserBuilder().setEmail(TEST_EMAIL).build();
    final Call<User> call = Calls.response(user);
    setupMockAccountService(call);

    authClient.requestEmail(mock(TwitterSession.class), new Callback<String>() {
        @Override
        public void success(Result<String> result) {
            assertEquals(TEST_EMAIL, result.data);
        }

        @Override
        public void failure(TwitterException exception) {
            fail("Expected Callback#success to be called");
        }
    });
}
 
Example #12
Source File: LoginActivity.java    From twittererer with Apache License 2.0 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    loginButton = (TwitterLoginButton) findViewById(R.id.twitter_login_button);
    loginButton.setCallback(new Callback<TwitterSession>() {
        @Override
        public void success(Result<TwitterSession> result) {
            startActivity(new Intent(LoginActivity.this, TimelineActivity.class));
            finish();
        }

        @Override
        public void failure(TwitterException exception) {
            Toast.makeText(getApplicationContext(), exception.getMessage(), Toast.LENGTH_LONG).show();
        }
    });
}
 
Example #13
Source File: LoginMaster.java    From uPods-android with Apache License 2.0 6 votes vote down vote up
private void fetchTwitterUserData(final IOperationFinishWithDataCallback profileFetched) {
    TwitterSession session =
            Twitter.getSessionManager().getActiveSession();
    Twitter.getApiClient(session).getAccountService()
            .verifyCredentials(true, false, new Callback<User>() {
                @Override
                public void success(Result<User> userResult) {
                    User user = userResult.data;
                    userProfile = new UserProfile();
                    userProfile.setName(user.screenName);
                    String profileImage = user.profileImageUrlHttps;
                    profileImage = profileImage.replace("_normal", "");
                    userProfile.setProfileImageUrl(profileImage);
                    profileFetched.operationFinished(userProfile);
                }

                @Override
                public void failure(TwitterException e) {

                }
            });
}
 
Example #14
Source File: AuthHandlerTest.java    From twitter-kit-android with Apache License 2.0 6 votes vote down vote up
@Test
public void testHandleOnActivityResult_resultCodeOK() {
    // Verify that when handleOnActivityResult is called with ok, the listener receives the auth
    // response.
    final Callback<TwitterSession> mockCallback = mock(Callback.class);
    final AuthHandler authHandler = newAuthHandler(mockCallback);

    final boolean result = authHandler.handleOnActivityResult(TEST_REQUEST_CODE,
            Activity.RESULT_OK, new Intent()
                    .putExtra(AuthHandler.EXTRA_TOKEN, TestFixtures.TOKEN)
                    .putExtra(AuthHandler.EXTRA_TOKEN_SECRET, TestFixtures.SECRET)
                    .putExtra(AuthHandler.EXTRA_SCREEN_NAME, TestFixtures.SCREEN_NAME)
                    .putExtra(AuthHandler.EXTRA_USER_ID, TestFixtures.USER_ID));

    assertTrue(result);
    final ArgumentCaptor<Result> argCaptor = ArgumentCaptor.forClass(Result.class);
    verify(mockCallback).success(argCaptor.capture());
    final TwitterSession session = (TwitterSession) argCaptor.getValue().data;
    final TwitterAuthToken authToken = session.getAuthToken();
    assertEquals(TestFixtures.TOKEN, authToken.token);
    assertEquals(TestFixtures.SECRET, authToken.secret);
    assertEquals(TestFixtures.SCREEN_NAME, session.getUserName());
    assertEquals(TestFixtures.USER_ID, session.getUserId());
}
 
Example #15
Source File: TwitterToken.java    From ShareLoginPayUtil with Apache License 2.0 6 votes vote down vote up
public TwitterToken(TwitterSession session) {

        if (session == null) {
            return;
        }

        setUserId(session.getUserId());
        setUserName(session.getUserName());
        setOpenid(String.valueOf(session.getId()));

        if (session.getAuthToken() == null) {
            return;
        }

        setAccessToken(session.getAuthToken().token);
        setSecret(session.getAuthToken().secret);
    }
 
Example #16
Source File: TwitterSignUpActivity.java    From socialmediasignup with MIT License 6 votes vote down vote up
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    TwitterSession activeSession = TwitterCore.getInstance().getSessionManager().getActiveSession();
    if (activeSession != null) {
        handleSuccess(activeSession);
    } else {
        getTwitterAuthClient().authorize(this, new Callback<TwitterSession>() {
            @Override
            public void success(Result<TwitterSession> result) {
                startLoading();
                handleSuccess(result.data);
            }

            @Override
            public void failure(TwitterException exception) {
                handleError(exception);
            }
        });
    }
}
 
Example #17
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 #18
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 #19
Source File: TwitterCoreMainActivity.java    From twitter-kit-android with Apache License 2.0 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.twittercore_activity_main);
    ActionBar actionBar = getSupportActionBar();
    if (actionBar != null) {
        actionBar.setTitle(R.string.kit_twittercore);
    }

    // Set up the login button by setting callback to invoke when authorization request
    // completes
    loginButton = findViewById(R.id.login_button);
    loginButton.setCallback(new Callback<TwitterSession>() {
        @Override
        public void success(Result<TwitterSession> result) {
            requestEmailAddress(getApplicationContext(), result.data);
        }

        @Override
        public void failure(TwitterException exception) {
            // Upon error, show a toast message indicating that authorization request failed.
            Toast.makeText(getApplicationContext(), exception.getMessage(),
                    Toast.LENGTH_SHORT).show();
        }
    });
}
 
Example #20
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 #21
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 #22
Source File: TweetUploadServiceTest.java    From twitter-kit-android with Apache License 2.0 6 votes vote down vote up
@Test
public void testUploadTweet_withNoMediaFailure() {
    when(mockStatusesService.update(anyString(), isNull(Long.class), isNull(Boolean.class),
            isNull(Double.class), isNull(Double.class), isNull(String.class),
            isNull(Boolean.class), eq(true), isNull(String.class)))
            .thenReturn(Calls.failure(new IOException("")));

    service.uploadTweet(mock(TwitterSession.class), EXPECTED_TWEET_TEXT, null);

    verify(mockStatusesService).update(eq(EXPECTED_TWEET_TEXT), isNull(Long.class),
            isNull(Boolean.class), isNull(Double.class), isNull(Double.class),
            isNull(String.class), isNull(Boolean.class), eq(true), isNull(String.class));
    verifyZeroInteractions(mockMediaService);
    verify(service).fail(any(TwitterException.class));
    verify(service).stopSelf();
}
 
Example #23
Source File: TweetUploadServiceTest.java    From twitter-kit-android with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    context = RuntimeEnvironment.application;
    mockMediaService = mock(MediaService.class);
    mockStatusesService = mock(StatusesService.class);
    tweet =  new TweetBuilder().setId(123L).setText(EXPECTED_TWEET_TEXT).build();
    when(mockMediaService
            .upload(any(RequestBody.class), any(RequestBody.class), any(RequestBody.class)))
            .thenReturn(mock(Call.class));
    when(mockStatusesService.update(anyString(), isNull(Long.class), isNull(Boolean.class),
            isNull(Double.class), isNull(Double.class), isNull(String.class),
            isNull(Boolean.class), eq(true), isNull(String.class)))
            .thenReturn(Calls.response(tweet));

    mockTwitterApiClient = mock(TwitterApiClient.class);
    when(mockTwitterApiClient.getStatusesService()).thenReturn(mockStatusesService);
    when(mockTwitterApiClient.getMediaService()).thenReturn(mockMediaService);

    mockDependencyProvider = mock(TweetUploadService.DependencyProvider.class);
    when(mockDependencyProvider.getTwitterApiClient(any(TwitterSession.class)))
            .thenReturn(mockTwitterApiClient);

    service = spy(Robolectric.buildService(TweetUploadService.class).create().get());
    service.dependencyProvider = mockDependencyProvider;
}
 
Example #24
Source File: TweetUploadService.java    From twitter-kit-android with Apache License 2.0 5 votes vote down vote up
void uploadMedia(TwitterSession session, Uri imageUri, Callback<Media> callback) {
    final TwitterApiClient client = dependencyProvider.getTwitterApiClient(session);

    final String path = FileUtils.getPath(TweetUploadService.this, imageUri);
    if (path == null) {
        fail(new TwitterException("Uri file path resolved to null"));
        return;
    }
    final File file = new File(path);
    final String mimeType = FileUtils.getMimeType(file);
    final RequestBody media = RequestBody.create(MediaType.parse(mimeType), file);

    client.getMediaService().upload(media, null, null).enqueue(callback);
}
 
Example #25
Source File: AuthHandlerTest.java    From twitter-kit-android with Apache License 2.0 5 votes vote down vote up
@Test
public void testHandleOnActivityResult_resultCodeErrorDataWithNoAuthError() {
    // Verify that when handleOnActivityResult is called with an error code and intent data but
    // no auth error, the listener receives generic error.
    final Callback<TwitterSession> mockCallback = mock(Callback.class);
    final AuthHandler authHandler = newAuthHandler(mockCallback);

    final boolean result = authHandler.handleOnActivityResult(TEST_REQUEST_CODE,
            AuthHandler.RESULT_CODE_ERROR, new Intent());

    assertTrue(result);
    assertCallbackFailureErrorMsg(mockCallback, "Authorize failed.");
}
 
Example #26
Source File: AuthHandlerTest.java    From twitter-kit-android with Apache License 2.0 5 votes vote down vote up
@Test
public void testHandleOnActivityResult_unrecognizedRequestCode() {
    // Verify that when handleOnActivityResult is called with a different request code, the
    // listener is not called.
    final Callback<TwitterSession> mockCallback = mock(Callback.class);
    final AuthHandler authHandler = newAuthHandler(mockCallback);

    final boolean result = authHandler.handleOnActivityResult(TEST_REQUEST_CODE + 1,
            Activity.RESULT_CANCELED, null);

    assertFalse(result);
    verifyZeroInteractions(mockCallback);
}
 
Example #27
Source File: AuthHandlerTest.java    From twitter-kit-android with Apache License 2.0 5 votes vote down vote up
@Test
public void testHandleOnActivityResult_resultCodeCancel() {
    // Verify that when handleOnActivityResult is called with cancel code, the listener receives
    // the error.
    final Callback<TwitterSession> mockCallback = mock(Callback.class);
    final AuthHandler authHandler = newAuthHandler(mockCallback);
    final TwitterAuthException authException = new TwitterAuthException(TEST_CANCEL_MESSAGE);

    final boolean result = authHandler.handleOnActivityResult(TEST_REQUEST_CODE,
            Activity.RESULT_CANCELED, new Intent().putExtra(AuthHandler.EXTRA_AUTH_ERROR,
                    authException));

    assertTrue(result);
    assertCallbackFailureErrorMsg(mockCallback, authException.getMessage());
}
 
Example #28
Source File: OkHttpClientHelperTest.java    From twitter-kit-android with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetCustomOkHttpClient_userAuth() throws Exception {
    final Interceptor mockInterceptor = mock(Interceptor.class);
    final OkHttpClient customHttpClient = new OkHttpClient.Builder()
            .addInterceptor(mockInterceptor).build();

    final TwitterSession mockSession = mock(TwitterSession.class);
    final OkHttpClient guestAuthHttpClient = OkHttpClientHelper.getCustomOkHttpClient(
            customHttpClient,
            mockSession,
            new TwitterAuthConfig("", ""));

    final List<Interceptor> interceptors = guestAuthHttpClient.interceptors();
    assertTrue(interceptors.contains(mockInterceptor));
}
 
Example #29
Source File: TwitterSessionVerifierTest.java    From twitter-kit-android with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    mockAccountServiceProvider = mock(AccountServiceProvider.class);
    mockAccountService = mock(AccountService.class);
    when(mockAccountServiceProvider.getAccountService(any(TwitterSession.class))).thenReturn
            (mockAccountService);
    session = mock(TwitterSession.class);
    when(session.getId()).thenReturn(TestFixtures.USER_ID);
    verifier = new TwitterSessionVerifier(mockAccountServiceProvider);
}
 
Example #30
Source File: AuthHandlerTest.java    From twitter-kit-android with Apache License 2.0 5 votes vote down vote up
@Test
public void testHandleOnActivityResult_resultCodeErrorDataNull() {
    // Verify that when handleOnActivityResult is called with an error code and no intent data,
    // the listener receives generic error.
    final Callback<TwitterSession> mockCallback = mock(Callback.class);
    final AuthHandler authHandler = newAuthHandler(mockCallback);

    final boolean result = authHandler.handleOnActivityResult(TEST_REQUEST_CODE,
            AuthHandler.RESULT_CODE_ERROR, null);

    assertTrue(result);
    assertCallbackFailureErrorMsg(mockCallback, "Authorize failed.");
}