@UsesMocks({SocializeEntityLoader.class, EntityLoaderUtils.class})
  public void testShowEntityById() {
    final Entity entity = new Entity();

    SocializeEntityUtils utils =
        new SocializeEntityUtils() {
          @Override
          public void getEntity(Activity context, long id, EntityGetListener listener) {
            listener.onGet(entity);
          }
        };

    SocializeEntityLoader entityLoader = AndroidMock.createMock(SocializeEntityLoader.class);
    EntityLoaderUtils entityLoaderUtils = AndroidMock.createMock(EntityLoaderUtils.class);

    AndroidMock.expect(entityLoaderUtils.initEntityLoader()).andReturn(entityLoader);
    AndroidMock.expect(entityLoader.canLoad(TestUtils.getActivity(this), entity)).andReturn(true);

    entityLoader.loadEntity(TestUtils.getActivity(this), entity);

    AndroidMock.replay(entityLoaderUtils, entityLoader);

    utils.setEntityLoaderUtils(entityLoaderUtils);
    utils.showEntity(TestUtils.getActivity(this), 123, null);

    AndroidMock.verify(entityLoaderUtils, entityLoader);
  }
  public void testApiAsyncGetCallsAddOnResponse() throws Throwable {

    final String endpoint = "foobar";
    final String id = null;

    SocializeObject obj = new SocializeObject();

    api.setResponseFactory(responseFactory);

    AndroidMock.expect(responseFactory.newEntityResponse()).andReturn(mockEntityResponse);
    AndroidMock.expect(provider.get(mockSession, endpoint, id)).andReturn(obj);

    mockEntityResponse.addResult(obj);

    AndroidMock.replay(responseFactory);
    AndroidMock.replay(provider);
    AndroidMock.replay(mockEntityResponse);

    runTestOnUiThread(
        new Runnable() {
          @Override
          public void run() {
            api.getAsync(mockSession, endpoint, id, listener);
          }
        });

    assertTrue("Timeout waiting for countdown latch", signal.await(timeout, TimeUnit.SECONDS));

    AndroidMock.verify(responseFactory);
    AndroidMock.verify(provider);
    AndroidMock.verify(mockEntityResponse);
  }
  @UsesMocks({SocializeConfig.class, MockContext.class, Intent.class})
  public void test_registerC2DM() {
    final String senderId = "foobar";

    NotificationRegistrationState notificationRegistrationState =
        AndroidMock.createMock(NotificationRegistrationState.class);
    SocializeConfig config = AndroidMock.createMock(SocializeConfig.class);
    MockContext context = AndroidMock.createNiceMock(MockContext.class);
    final Intent registrationIntent = AndroidMock.createMock(Intent.class);

    AndroidMock.expect(notificationRegistrationState.isC2dmPending()).andReturn(false);

    notificationRegistrationState.setC2dmPendingRequestTime(AndroidMock.anyLong());
    notificationRegistrationState.save(context);

    AndroidMock.expect(config.getProperty(SocializeConfig.SOCIALIZE_C2DM_SENDER_ID))
        .andReturn(senderId);

    AndroidMock.expect(
            registrationIntent.putExtra(
                SocializeNotificationRegistrationSystem.EXTRA_APPLICATION_PENDING_INTENT,
                (PendingIntent) null))
        .andReturn(registrationIntent);
    AndroidMock.expect(
            registrationIntent.putExtra(
                SocializeNotificationRegistrationSystem.EXTRA_SENDER, senderId))
        .andReturn(registrationIntent);
    AndroidMock.expect(context.startService(registrationIntent)).andReturn(null);

    AndroidMock.replay(notificationRegistrationState, config, context, registrationIntent);

    SocializeNotificationRegistrationSystem system =
        new SocializeNotificationRegistrationSystem() {
          @Override
          public boolean isRegisteredC2DM() {
            return false;
          }

          @Override
          protected Intent newIntent(String action) {
            return registrationIntent;
          }

          @Override
          protected PendingIntent newPendingIntent(Context context) {
            return null;
          }
        };

    system.setConfig(config);
    system.setNotificationRegistrationState(notificationRegistrationState);

    system.registerC2DM(context);

    AndroidMock.verify(notificationRegistrationState, config, context, registrationIntent);
  }
  @SuppressWarnings("unchecked")
  public void test_doRegistrationSocialize() throws SocializeException {

    final String registrationId = "foobar";
    final User user = new User();

    DeviceRegistration registration = AndroidMock.createMock(DeviceRegistration.class);
    NotificationRegistrationState notificationRegistrationState =
        AndroidMock.createMock(NotificationRegistrationState.class);

    DeviceRegistrationSystem deviceRegistrationSystem =
        new DeviceRegistrationSystem() {
          @Override
          public void registerDevice(
              SocializeSession session,
              DeviceRegistration registration,
              DeviceRegistrationListener listener) {
            listener.onSuccess();
          }
        };

    IBeanFactory<DeviceRegistration> deviceRegistrationFactory =
        AndroidMock.createMock(IBeanFactory.class);
    SocializeSession session = AndroidMock.createMock(SocializeSession.class);

    AndroidMock.expect(deviceRegistrationFactory.getBean()).andReturn(registration);
    AndroidMock.expect(session.getUser()).andReturn(user);

    registration.setRegistrationId(registrationId);
    notificationRegistrationState.setC2DMRegistrationId(registrationId);
    notificationRegistrationState.setRegisteredSocialize(user);
    notificationRegistrationState.save(getContext());

    AndroidMock.replay(
        deviceRegistrationFactory, registration, notificationRegistrationState, session);

    PublicSocializeNotificationRegistrationSystem system =
        new PublicSocializeNotificationRegistrationSystem();

    system.setDeviceRegistrationFactory(deviceRegistrationFactory);
    system.setDeviceRegistrationSystem(deviceRegistrationSystem);
    system.setNotificationRegistrationState(notificationRegistrationState);

    system.doRegistrationSocialize(getContext(), session, registrationId);

    AndroidMock.verify(
        deviceRegistrationFactory, registration, notificationRegistrationState, session);
  }
  public void testApiAsyncCallsListOnProviderPaginated() throws Throwable {

    final String endpoint = "foobar";
    final String key = "foobar_key";
    final String ids[] = null;

    final int start = 0, end = 10;

    final ListResult<SocializeObject> returned =
        new ListResult<SocializeObject>(new LinkedList<SocializeObject>());

    AndroidMock.expect(provider.list(mockSession, endpoint, key, ids, "id", start, end))
        .andReturn(returned);
    AndroidMock.replay(provider);

    runTestOnUiThread(
        new Runnable() {
          @Override
          public void run() {
            api.listAsync(mockSession, endpoint, key, ids, start, end, listener);
          }
        });

    assertTrue("Timeout waiting for countdown latch", signal.await(timeout, TimeUnit.SECONDS));

    AndroidMock.verify(provider);
  }
  /**
   * In addition to {@link AbstractTestCaseForClientMessageHandler#setUp()} is set up also a mock
   * for {@link ILocationService}.
   */
  @Override
  protected void setUp() {
    super.setUp();

    locationServiceMock = AndroidMock.createStrictMock(ILocationService.class);

    AndroidMock.expect(cdcMock.getLocationService()).andReturn(locationServiceMock).anyTimes();
  }
  public void testDialogDismissWorksOnError() throws Throwable {
    AndroidMock.expect(
            provider.authenticate("/authenticate/", "test_key", "test_secret", "test_uuid"))
        .andThrow(new SocializeException("TEST ERROR IGNORE ME!"));
    AndroidMock.replay(provider);

    final ProgressDialog authProgress =
        ProgressDialog.show(getActivity(), "Authenticating", "Please wait...");

    final SocializeAuthListener alistener =
        new SocializeAuthListener() {

          @Override
          public void onAuthSuccess(SocializeSession session) {
            authProgress.dismiss();
            signal.countDown();
            fail();
          }

          @Override
          public void onAuthFail(SocializeException error) {
            authProgress.dismiss();
            signal.countDown();
            fail();
          }

          @Override
          public void onError(SocializeException error) {
            authProgress.dismiss();
            signal.countDown();
          }

          @Override
          public void onCancel() {
            authProgress.dismiss();
            signal.countDown();
            fail();
          }
        };

    runTestOnUiThread(
        new Runnable() {
          @Override
          public void run() {
            api.authenticateAsync(
                getContext(),
                "test_key",
                "test_secret",
                "test_uuid",
                null,
                alistener,
                mockSessionConsumer,
                false);
          }
        });

    assertTrue("Timeout waiting for countdown latch", signal.await(timeout, TimeUnit.SECONDS));
  }
  public void testLastKnownLocationNotAvailable() {

    final String strProvider = "foobar";

    AndroidMock.expect(appUtils.hasPermission(context, "android.permission.ACCESS_FINE_LOCATION"))
        .andReturn(true)
        .anyTimes();
    AndroidMock.expect(
            locationManager.getBestProvider(
                (Criteria) AndroidMock.anyObject(), AndroidMock.eq(true)))
        .andReturn(strProvider)
        .anyTimes();
    AndroidMock.expect(locationManager.getLastKnownLocation(strProvider))
        .andReturn(null)
        .anyTimes();
    AndroidMock.expect(locationManager.isProviderEnabled(strProvider)).andReturn(true).anyTimes();
    AndroidMock.expect(locationListenerFactory.getBean()).andReturn(listener).anyTimes();

    locationManager.requestLocationUpdates(context, strProvider, 1L, 0.0f, listener);

    AndroidMock.replay(locationListenerFactory);
    AndroidMock.replay(appUtils);
    AndroidMock.replay(locationManager);

    DefaultLocationProvider provider = new DefaultLocationProvider();
    provider.setLocationManager(locationManager);
    provider.setAppUtils(appUtils);
    provider.setLocationListenerFactory(locationListenerFactory);
    provider.init(context);

    Location loc = provider.getLastKnownLocation();

    AndroidMock.verify(locationListenerFactory);
    AndroidMock.verify(appUtils);
    AndroidMock.verify(locationManager);

    assertNull(loc);
  }
  public void testDoesNotHavePermission() {

    AndroidMock.expect(appUtils.hasPermission(context, "android.permission.ACCESS_FINE_LOCATION"))
        .andReturn(false)
        .anyTimes();
    AndroidMock.expect(appUtils.hasPermission(context, "android.permission.ACCESS_COARSE_LOCATION"))
        .andReturn(false)
        .anyTimes();
    AndroidMock.expect(locationListenerFactory.getBean()).andReturn(listener);

    AndroidMock.replay(appUtils);
    AndroidMock.replay(locationListenerFactory);

    DefaultLocationProvider provider = new DefaultLocationProvider();
    provider.setAppUtils(appUtils);
    provider.setLocationListenerFactory(locationListenerFactory);
    provider.init(context);

    assertNull(provider.getLastKnownLocation());

    AndroidMock.verify(appUtils);
    AndroidMock.verify(locationListenerFactory);
  }
  public void testLastKnownLocationAvailable() {

    final String strProvider = "foobar";

    Location location = AndroidMock.createMock(Location.class, strProvider);

    AndroidMock.expect(appUtils.hasPermission(context, "android.permission.ACCESS_FINE_LOCATION"))
        .andReturn(true);
    AndroidMock.expect(
            locationManager.getBestProvider(
                (Criteria) AndroidMock.anyObject(), AndroidMock.eq(true)))
        .andReturn(strProvider);
    AndroidMock.expect(locationManager.getLastKnownLocation(strProvider)).andReturn(location);
    AndroidMock.expect(config.getBooleanProperty(SocializeConfig.SOCIALIZE_LOCATION_ENABLED, true))
        .andReturn(true)
        .anyTimes();

    locationManager.removeUpdates(listener);

    AndroidMock.expect(locationListenerFactory.getBean()).andReturn(listener);

    AndroidMock.replay(appUtils, locationManager, locationListenerFactory, config);

    DefaultLocationProvider provider = new DefaultLocationProvider();
    provider.setLocationManager(locationManager);
    provider.setAppUtils(appUtils);
    provider.setConfig(config);
    provider.setLocationListenerFactory(locationListenerFactory);
    provider.init(context);

    Location loc = provider.getLocation(getContext());

    AndroidMock.verify(appUtils, locationManager, locationListenerFactory, config);

    assertNotNull(loc);
    assertSame(location, loc);
  }
  public void test_isRegistrationPending() {
    NotificationRegistrationState notificationRegistrationState =
        AndroidMock.createMock(NotificationRegistrationState.class);

    AndroidMock.expect(notificationRegistrationState.isC2dmPending()).andReturn(true);
    AndroidMock.replay(notificationRegistrationState);

    SocializeNotificationRegistrationSystem system = new SocializeNotificationRegistrationSystem();

    system.setNotificationRegistrationState(notificationRegistrationState);

    assertTrue(system.isRegistrationPending());

    AndroidMock.verify(notificationRegistrationState);
  }
  public void testApiAsyncListCallsSetResultsOnResponse() throws Throwable {

    final String endpoint = "foobar";
    final String key = "foobar_key";
    final String[] ids = null;

    final ListResult<SocializeObject> returned =
        new ListResult<SocializeObject>(new LinkedList<SocializeObject>());

    api.setResponseFactory(responseFactory);

    AndroidMock.expect(responseFactory.newEntityResponse()).andReturn(mockEntityResponse);
    AndroidMock.expect(
            provider.list(
                mockSession, endpoint, key, ids, "id", 0, SocializeConfig.MAX_LIST_RESULTS))
        .andReturn(returned);
    mockEntityResponse.setResults(returned);

    AndroidMock.replay(responseFactory);
    AndroidMock.replay(provider);
    AndroidMock.replay(mockEntityResponse);

    runTestOnUiThread(
        new Runnable() {
          @Override
          public void run() {
            api.listAsync(mockSession, endpoint, key, ids, listener);
          }
        });

    assertTrue("Timeout waiting for countdown latch", signal.await(timeout, TimeUnit.SECONDS));

    AndroidMock.verify(responseFactory);
    AndroidMock.verify(provider);
    AndroidMock.verify(mockEntityResponse);
  }
  public void test_isRegisteredSocialize() {
    NotificationRegistrationState notificationRegistrationState =
        AndroidMock.createMock(NotificationRegistrationState.class);

    final User user = new User();
    AndroidMock.expect(notificationRegistrationState.isRegisteredSocialize(user)).andReturn(true);
    AndroidMock.replay(notificationRegistrationState);

    SocializeNotificationRegistrationSystem system = new SocializeNotificationRegistrationSystem();

    system.setNotificationRegistrationState(notificationRegistrationState);

    assertTrue(system.isRegisteredSocialize(user));

    AndroidMock.verify(notificationRegistrationState);
  }
  @UsesMocks({
    NotificationAuthenticator.class,
    ActivitySystem.class,
    SocializeSession.class,
    SocializeAction.class,
    User.class,
    NotificationMessage.class
  })
  public void test_translate() throws SocializeException {

    NotificationAuthenticator notificationAuthenticator =
        AndroidMock.createMock(NotificationAuthenticator.class);
    ActivitySystem activitySystem = AndroidMock.createMock(ActivitySystem.class);
    SocializeSession session = AndroidMock.createMock(SocializeSession.class);
    SocializeAction action = AndroidMock.createMock(SocializeAction.class);
    User user = AndroidMock.createMock(User.class);
    NotificationMessage message = AndroidMock.createMock(NotificationMessage.class);

    final long actionId = 69L;
    final long userId = 1001L;
    final ActionType type = ActionType.COMMENT;
    final Context context = getContext();

    AndroidMock.expect(message.getActionId()).andReturn(actionId).anyTimes();
    AndroidMock.expect(message.getActionType()).andReturn(type).anyTimes();
    AndroidMock.expect(notificationAuthenticator.authenticate(context)).andReturn(session);
    AndroidMock.expect(activitySystem.getAction(session, actionId, type)).andReturn(action);
    AndroidMock.expect(action.getUser()).andReturn(user);
    AndroidMock.expect(user.getId()).andReturn(userId).anyTimes();

    AndroidMock.replay(notificationAuthenticator, activitySystem, session, action, user, message);

    SocializeActionMessageTranslator translator = new SocializeActionMessageTranslator();
    Bundle data = new Bundle();

    translator.setActivitySystem(activitySystem);
    translator.setNotificationAuthenticator(notificationAuthenticator);

    SocializeAction translated = translator.translate(context, data, message);

    AndroidMock.verify(notificationAuthenticator, activitySystem, session, action, user, message);

    assertNotNull(translated);
    assertSame(action, translated);
    assertNotNull(data.getString(Socialize.ACTION_ID));
    assertNotNull(data.getString(Socialize.USER_ID));

    assertEquals(String.valueOf(actionId), data.getString(Socialize.ACTION_ID));
    assertEquals(String.valueOf(userId), data.getString(Socialize.USER_ID));
  }
  public void testApiAsyncCallsPutOnProviderWithList() throws Throwable {

    final String endpoint = "foobar";
    final List<SocializeObject> objects = new ArrayList<SocializeObject>();

    AndroidMock.expect(provider.put(mockSession, endpoint, objects)).andReturn(null);
    AndroidMock.replay(provider);

    runTestOnUiThread(
        new Runnable() {
          @Override
          public void run() {
            api.putAsync(mockSession, endpoint, objects, listener);
          }
        });

    assertTrue("Timeout waiting for countdown latch", signal.await(timeout, TimeUnit.SECONDS));

    AndroidMock.verify(provider);
  }
  public void testApiAsyncCallsGetOnProvider() throws Throwable {

    final String endpoint = "foobar";
    final String id = null;

    AndroidMock.expect(provider.get(mockSession, endpoint, id)).andReturn(new SocializeObject());
    AndroidMock.replay(provider);

    runTestOnUiThread(
        new Runnable() {
          @Override
          public void run() {
            api.getAsync(mockSession, endpoint, id, listener);
          }
        });

    assertTrue("Timeout waiting for countdown latch", signal.await(timeout, TimeUnit.SECONDS));

    AndroidMock.verify(provider);
  }
 /** Mocks the location of this device (Client). */
 private void initMyLocation() {
   Location myLocation = new Location((String) null);
   myLocation.setLatitude(52.673978d);
   myLocation.setLongitude(8.802951d);
   AndroidMock.expect(locationServiceMock.getCurrentLocation()).andReturn(myLocation).anyTimes();
 }
 /** Creates a new {@link FeatureMessage} and adds it to the {@link #cdcMock}. */
 private void initFeatures() {
   features = new FeatureMessage(false, 0, 0, 0, 0, false, false, location, bearing, speed, false);
   AndroidMock.expect(cdcMock.getFeatures()).andReturn(features).anyTimes();
 }
  @SuppressWarnings("unchecked")
  protected void doOnClickTest(final AUTH_REPSONSE response) {

    final String consumerKey = "foo";
    final String consumerSecret = "bar";
    final String fbId = "foobar_FB";

    SocializeConfig config = AndroidMock.createMock(SocializeConfig.class);
    SocializeAuthListener listener = AndroidMock.createMock(SocializeAuthListener.class);
    DialogFactory<ProgressDialog> dialogFactory = AndroidMock.createMock(DialogFactory.class);
    ProgressDialog dialog = AndroidMock.createMock(ProgressDialog.class, getContext());
    View view = AndroidMock.createMock(View.class, getContext());
    final SocializeSession session = AndroidMock.createMock(SocializeSession.class);
    final SocializeException error = new SocializeException("DUMMY - IGNORE ME");

    final PublicSocialize socialize =
        new PublicSocialize() {

          @Override
          public void authenticate(
              Context context,
              String consumerKey,
              String consumerSecret,
              AuthProviderInfo authProviderInfo,
              SocializeAuthListener listener) {
            addResult(0, consumerKey);
            addResult(1, consumerSecret);
            addResult(2, authProviderInfo);

            // Call each method of the listener for the test
            switch (response) {
              case SUCCESS:
                listener.onAuthSuccess(session);
                break;
              case CANCEL:
                listener.onCancel();
                break;
              case ERROR:
                listener.onError(error);
                break;
              case FAIL:
                listener.onAuthFail(error);
                break;
            }
          }
        };

    view.setEnabled(false);

    AndroidMock.expect(config.getProperty(SocializeConfig.SOCIALIZE_CONSUMER_KEY))
        .andReturn(consumerKey);
    AndroidMock.expect(config.getProperty(SocializeConfig.SOCIALIZE_CONSUMER_SECRET))
        .andReturn(consumerSecret);
    AndroidMock.expect(config.getProperty(SocializeConfig.FACEBOOK_APP_ID)).andReturn(fbId);
    AndroidMock.expect(dialogFactory.show(getContext(), "Authentication", "Authenticating..."))
        .andReturn(dialog);

    dialog.dismiss();
    view.setEnabled(true);

    switch (response) {
      case SUCCESS:
        listener.onAuthSuccess(session);
        break;
      case CANCEL:
        listener.onCancel();
        break;
      case ERROR:
        listener.onError(error);
        break;
      case FAIL:
        listener.onAuthFail(error);
        break;
    }

    AndroidMock.replay(config);
    AndroidMock.replay(dialogFactory);
    AndroidMock.replay(dialog);
    AndroidMock.replay(view);
    AndroidMock.replay(listener);

    FacebookAuthClickListener facebookAuthClickListener =
        new FacebookAuthClickListener() {
          @Override
          protected SocializeService getSocialize() {
            return socialize;
          }
        };

    facebookAuthClickListener.setConfig(config);
    facebookAuthClickListener.setDialogFactory(dialogFactory);
    facebookAuthClickListener.setListener(listener);

    facebookAuthClickListener.onClick(view);

    AndroidMock.verify(config);
    AndroidMock.verify(dialogFactory);
    AndroidMock.verify(dialog);
    AndroidMock.verify(view);
    AndroidMock.verify(listener);

    final String consumerKeyAfter = getResult(0);
    final String consumerSecretAfter = getResult(1);
    final AuthProviderInfo authProviderInfo = getResult(2);

    assertEquals(consumerKey, consumerKeyAfter);
    assertEquals(consumerSecret, consumerSecretAfter);

    assertTrue((authProviderInfo instanceof FacebookAuthProviderInfo));

    FacebookAuthProviderInfo fba = (FacebookAuthProviderInfo) authProviderInfo;

    assertEquals(AuthProviderType.FACEBOOK, fba.getType());
    assertEquals(fbId, fba.getAppId());
  }
 @Override
 protected void setupToJSONExpectations() throws JSONException {
   AndroidMock.expect(object.getName()).andReturn(mockName);
   AndroidMock.expect(json.put("name", mockName)).andReturn(json);
 }
 @Override
 protected void setupFromJSONExpectations() throws Exception {
   AndroidMock.expect(json.has("name")).andReturn(true);
   AndroidMock.expect(json.getString("name")).andReturn(mockName);
   object.setName(mockName);
 }
  public void testApiAsyncCallsAuthenticateOnProvider() throws Throwable {

    AndroidMock.expect(
            provider.authenticate("/authenticate/", "test_key", "test_secret", "test_uuid"))
        .andReturn(mockSession);

    mockSessionConsumer.setSession(mockSession);

    AndroidMock.replay(provider);
    AndroidMock.replay(mockSessionConsumer);

    final SocializeAuthListener alistener =
        new SocializeAuthListener() {

          @Override
          public void onAuthSuccess(SocializeSession session) {
            System.out.println("Api listener onResult fired");
            signal.countDown();
          }

          @Override
          public void onAuthFail(SocializeException error) {
            System.out.println("Api listener onAuthFail fired");
            signal.countDown();
          }

          @Override
          public void onError(SocializeException error) {
            System.out.println("Api listener onError fired");
            signal.countDown();
          }

          @Override
          public void onCancel() {
            System.out.println("Api listener onCancel fired");
            signal.countDown();
            fail();
          }
        };

    final Context context = getContext();

    runTestOnUiThread(
        new Runnable() {
          @Override
          public void run() {
            api.authenticateAsync(
                context,
                "test_key",
                "test_secret",
                "test_uuid",
                null,
                alistener,
                mockSessionConsumer,
                false);
          }
        });

    assertTrue("Timeout waiting for countdown latch", signal.await(timeout, TimeUnit.SECONDS));

    AndroidMock.verify(provider);
    AndroidMock.verify(mockSessionConsumer);
  }