Search in sources :

Example 26 with Channel

use of com.microsoft.appcenter.channel.Channel in project mobile-center-sdk-android by Microsoft.

the class CrashesTest method trackException.

@Test
public void trackException() {
    /* Track exception test. */
    Crashes crashes = Crashes.getInstance();
    Channel mockChannel = mock(Channel.class);
    crashes.onStarting(mAppCenterHandler);
    crashes.onStarted(mock(Context.class), "", mockChannel);
    Crashes.trackException(EXCEPTION);
    verify(mockChannel).enqueue(argThat(new ArgumentMatcher<Log>() {

        @Override
        public boolean matches(Object item) {
            return item instanceof HandledErrorLog && EXCEPTION.getMessage().equals(((HandledErrorLog) item).getException().getMessage());
        }
    }), eq(crashes.getGroupName()));
    reset(mockChannel);
    Crashes.trackException(EXCEPTION, new HashMap<String, String>() {

        {
            put(null, null);
            put("", null);
            put(generateString(ErrorLogHelper.MAX_PROPERTY_ITEM_LENGTH + 1, '*'), null);
            put("1", null);
        }
    });
    verify(mockChannel).enqueue(argThat(new ArgumentMatcher<Log>() {

        @Override
        public boolean matches(Object item) {
            return item instanceof HandledErrorLog && EXCEPTION.getMessage().equals(((HandledErrorLog) item).getException().getMessage()) && ((HandledErrorLog) item).getProperties().size() == 0;
        }
    }), eq(crashes.getGroupName()));
    reset(mockChannel);
    Crashes.trackException(EXCEPTION, new HashMap<String, String>() {

        {
            for (int i = 0; i < 10; i++) {
                put("valid" + i, "valid");
            }
        }
    });
    verify(mockChannel).enqueue(argThat(new ArgumentMatcher<Log>() {

        @Override
        public boolean matches(Object item) {
            return item instanceof HandledErrorLog && EXCEPTION.getMessage().equals(((HandledErrorLog) item).getException().getMessage()) && ((HandledErrorLog) item).getProperties().size() == 5;
        }
    }), eq(crashes.getGroupName()));
    reset(mockChannel);
    final String longerMapItem = generateString(ErrorLogHelper.MAX_PROPERTY_ITEM_LENGTH + 1, '*');
    Crashes.trackException(EXCEPTION, new HashMap<String, String>() {

        {
            put(longerMapItem, longerMapItem);
        }
    });
    verify(mockChannel).enqueue(argThat(new ArgumentMatcher<Log>() {

        @Override
        public boolean matches(Object item) {
            if (item instanceof HandledErrorLog) {
                HandledErrorLog errorLog = (HandledErrorLog) item;
                if (EXCEPTION.getMessage().equals((errorLog.getException().getMessage()))) {
                    if (errorLog.getProperties().size() == 1) {
                        Map.Entry<String, String> entry = errorLog.getProperties().entrySet().iterator().next();
                        String truncatedMapItem = generateString(ErrorLogHelper.MAX_PROPERTY_ITEM_LENGTH, '*');
                        return entry.getKey().length() == ErrorLogHelper.MAX_PROPERTY_ITEM_LENGTH && entry.getValue().length() == ErrorLogHelper.MAX_PROPERTY_ITEM_LENGTH;
                    }
                }
            }
            return false;
        }
    }), eq(crashes.getGroupName()));
    HandledErrorLog mockLog = mock(HandledErrorLog.class);
    CrashesListener mockListener = mock(CrashesListener.class);
    crashes.setInstanceListener(mockListener);
    /* Crashes callback test for trackException. */
    crashes.getChannelListener().onBeforeSending(mockLog);
    verify(mockListener, never()).onBeforeSending(any(ErrorReport.class));
    crashes.getChannelListener().onSuccess(mockLog);
    verify(mockListener, never()).onSendingSucceeded(any(ErrorReport.class));
    crashes.getChannelListener().onFailure(mockLog, EXCEPTION);
    verify(mockListener, never()).onSendingFailed(any(ErrorReport.class), eq(EXCEPTION));
    ErrorAttachmentLog attachmentLog = mock(ErrorAttachmentLog.class);
    crashes.getChannelListener().onBeforeSending(attachmentLog);
    verify(mockListener, never()).onBeforeSending(any(ErrorReport.class));
    crashes.getChannelListener().onSuccess(attachmentLog);
    verify(mockListener, never()).onSendingSucceeded(any(ErrorReport.class));
    crashes.getChannelListener().onFailure(attachmentLog, EXCEPTION);
    verify(mockListener, never()).onSendingFailed(any(ErrorReport.class), eq(EXCEPTION));
}
Also used : Context(android.content.Context) SessionContext(com.microsoft.appcenter.SessionContext) Channel(com.microsoft.appcenter.channel.Channel) HandledErrorLog(com.microsoft.appcenter.crashes.ingestion.models.HandledErrorLog) Matchers.anyString(org.mockito.Matchers.anyString) TestUtils.generateString(com.microsoft.appcenter.test.TestUtils.generateString) ErrorReport(com.microsoft.appcenter.crashes.model.ErrorReport) ArgumentMatcher(org.mockito.ArgumentMatcher) ErrorAttachmentLog(com.microsoft.appcenter.crashes.ingestion.models.ErrorAttachmentLog) Map(java.util.Map) HashMap(java.util.HashMap) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 27 with Channel

use of com.microsoft.appcenter.channel.Channel in project mobile-center-sdk-android by Microsoft.

the class CrashesTest method printErrorOnJSONException.

@Test
public void printErrorOnJSONException() throws JSONException {
    Context mockContext = mock(Context.class);
    Channel mockChannel = mock(Channel.class);
    JSONException jsonException = new JSONException("Fake JSON exception");
    mockStatic(ErrorLogHelper.class);
    when(ErrorLogHelper.getStoredErrorLogFiles()).thenReturn(new File[] { mock(File.class) });
    when(ErrorLogHelper.getNewMinidumpFiles()).thenReturn(new File[0]);
    when(StorageHelper.InternalStorage.read(any(File.class))).thenReturn("");
    Crashes crashes = Crashes.getInstance();
    LogSerializer logSerializer = mock(LogSerializer.class);
    when(logSerializer.deserializeLog(anyString())).thenThrow(jsonException);
    crashes.setLogSerializer(logSerializer);
    crashes.onStarting(mAppCenterHandler);
    crashes.onStarted(mockContext, "", mockChannel);
    verify(mockChannel, never()).enqueue(any(Log.class), anyString());
    verifyStatic();
    AppCenterLog.error(eq(Crashes.LOG_TAG), anyString(), eq(jsonException));
}
Also used : Context(android.content.Context) SessionContext(com.microsoft.appcenter.SessionContext) HandledErrorLog(com.microsoft.appcenter.crashes.ingestion.models.HandledErrorLog) ManagedErrorLog(com.microsoft.appcenter.crashes.ingestion.models.ManagedErrorLog) Log(com.microsoft.appcenter.ingestion.models.Log) AppCenterLog(com.microsoft.appcenter.utils.AppCenterLog) ErrorAttachmentLog(com.microsoft.appcenter.crashes.ingestion.models.ErrorAttachmentLog) Channel(com.microsoft.appcenter.channel.Channel) JSONException(org.json.JSONException) LogSerializer(com.microsoft.appcenter.ingestion.models.json.LogSerializer) File(java.io.File) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 28 with Channel

use of com.microsoft.appcenter.channel.Channel in project mobile-center-sdk-android by Microsoft.

the class CrashesTest method setEnabled.

@Test
public void setEnabled() {
    /* Setup mock. */
    Crashes crashes = Crashes.getInstance();
    mockStatic(ErrorLogHelper.class);
    Channel mockChannel = mock(Channel.class);
    File dir = mock(File.class);
    File file1 = mock(File.class);
    File file2 = mock(File.class);
    when(ErrorLogHelper.getErrorStorageDirectory()).thenReturn(dir);
    when(ErrorLogHelper.getStoredErrorLogFiles()).thenReturn(new File[0]);
    when(ErrorLogHelper.getNewMinidumpFiles()).thenReturn(new File[0]);
    when(dir.listFiles()).thenReturn(new File[] { file1, file2 });
    /* Before start it's disabled. */
    assertFalse(Crashes.isEnabled().get());
    assertEquals(0, crashes.getInitializeTimestamp());
    /* Start. */
    crashes.onStarting(mAppCenterHandler);
    crashes.onStarted(mock(Context.class), "", mockChannel);
    verify(mockChannel).removeGroup(eq(crashes.getGroupName()));
    verify(mockChannel).addGroup(eq(crashes.getGroupName()), anyInt(), anyInt(), anyInt(), any(Channel.GroupListener.class));
    /* Test. */
    assertTrue(Crashes.isEnabled().get());
    Crashes.setEnabled(true);
    assertTrue(Crashes.isEnabled().get());
    assertTrue(crashes.getInitializeTimestamp() > 0);
    Crashes.setEnabled(false);
    assertFalse(Crashes.isEnabled().get());
    verify(mockChannel).clear(crashes.getGroupName());
    verify(mockChannel, times(2)).removeGroup(eq(crashes.getGroupName()));
    assertEquals(crashes.getInitializeTimestamp(), -1);
    assertFalse(Thread.getDefaultUncaughtExceptionHandler() instanceof UncaughtExceptionHandler);
    assertFalse(verify(file1).delete());
    assertFalse(verify(file2).delete());
    Crashes.trackException(EXCEPTION);
    verifyNoMoreInteractions(mockChannel);
    /* Enable back, testing double calls. */
    Crashes.setEnabled(true);
    assertTrue(Crashes.isEnabled().get());
    assertTrue(crashes.getInitializeTimestamp() > 0);
    assertTrue(Thread.getDefaultUncaughtExceptionHandler() instanceof UncaughtExceptionHandler);
    Crashes.setEnabled(true);
    assertTrue(Crashes.isEnabled().get());
    verify(mockChannel, times(2)).addGroup(eq(crashes.getGroupName()), anyInt(), anyInt(), anyInt(), any(Channel.GroupListener.class));
    Crashes.trackException(EXCEPTION);
    verify(mockChannel, times(1)).enqueue(any(ManagedErrorLog.class), eq(crashes.getGroupName()));
}
Also used : Context(android.content.Context) SessionContext(com.microsoft.appcenter.SessionContext) ManagedErrorLog(com.microsoft.appcenter.crashes.ingestion.models.ManagedErrorLog) Channel(com.microsoft.appcenter.channel.Channel) File(java.io.File) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 29 with Channel

use of com.microsoft.appcenter.channel.Channel in project mobile-center-sdk-android by Microsoft.

the class CrashesTest method crashInLastSession.

@Test
public void crashInLastSession() throws JSONException, IOException, ClassNotFoundException {
    final ManagedErrorLog errorLog = new ManagedErrorLog();
    errorLog.setId(UUIDUtils.randomUUID());
    errorLog.setErrorThreadName(Thread.currentThread().getName());
    Date logTimestamp = new Date(10);
    errorLog.setTimestamp(logTimestamp);
    Date appLaunchTimestamp = new Date(100L);
    errorLog.setAppLaunchTimestamp(appLaunchTimestamp);
    errorLog.setDevice(mock(Device.class));
    LogSerializer logSerializer = mock(LogSerializer.class);
    when(logSerializer.deserializeLog(anyString())).thenReturn(errorLog);
    final Throwable throwable = mock(Throwable.class);
    final ErrorReport errorReport = ErrorLogHelper.getErrorReportFromErrorLog(errorLog, throwable);
    mockStatic(ErrorLogHelper.class);
    File lastErrorLogFile = errorStorageDirectory.newFile("last-error-log.json");
    when(ErrorLogHelper.getLastErrorLogFile()).thenReturn(lastErrorLogFile);
    File throwableFile = errorStorageDirectory.newFile();
    new FileWriter(throwableFile).append("fake_data").close();
    when(ErrorLogHelper.getStoredThrowableFile(any(UUID.class))).thenReturn(throwableFile);
    when(ErrorLogHelper.getErrorReportFromErrorLog(errorLog, throwable)).thenReturn(errorReport);
    when(ErrorLogHelper.getStoredErrorLogFiles()).thenReturn(new File[] { lastErrorLogFile });
    when(ErrorLogHelper.getNewMinidumpFiles()).thenReturn(new File[0]);
    when(StorageHelper.InternalStorage.read(any(File.class))).thenReturn("");
    when(StorageHelper.InternalStorage.readObject(any(File.class))).thenReturn(throwable);
    Crashes crashes = Crashes.getInstance();
    crashes.setLogSerializer(logSerializer);
    assertFalse(Crashes.hasCrashedInLastSession().get());
    /*
         * Last session error is only fetched upon initialization: enabled and channel ready.
         * Here the service is disabled by default until stated, we are waiting channel to be ready, simulate that.
         */
    assertFalse(Crashes.isEnabled().get());
    assertFalse(Crashes.hasCrashedInLastSession().get());
    @SuppressWarnings("unchecked") AppCenterConsumer<ErrorReport> beforeCallback = (AppCenterConsumer<ErrorReport>) mock(AppCenterConsumer.class);
    Crashes.getLastSessionCrashReport().thenAccept(beforeCallback);
    verify(beforeCallback).accept(null);
    crashes.onStarting(mAppCenterHandler);
    crashes.onStarted(mock(Context.class), "", mock(Channel.class));
    assertTrue(Crashes.isEnabled().get());
    assertTrue(Crashes.hasCrashedInLastSession().get());
    /* Test with 2 callbacks and check result is the same for both callbacks. */
    @SuppressWarnings("unchecked") AppCenterConsumer<ErrorReport> afterCallback = (AppCenterConsumer<ErrorReport>) mock(AppCenterConsumer.class);
    AppCenterFuture<ErrorReport> future = Crashes.getLastSessionCrashReport();
    future.thenAccept(afterCallback);
    future.thenAccept(afterCallback);
    ArgumentCaptor<ErrorReport> errorReportCaptor = ArgumentCaptor.forClass(ErrorReport.class);
    verify(afterCallback, times(2)).accept(errorReportCaptor.capture());
    assertEquals(errorReportCaptor.getAllValues().get(0), errorReportCaptor.getAllValues().get(1));
    ErrorReport result = errorReportCaptor.getValue();
    assertNotNull(result);
    assertEquals(errorLog.getId().toString(), result.getId());
    assertEquals(errorLog.getErrorThreadName(), result.getThreadName());
    assertEquals(appLaunchTimestamp, result.getAppStartTime());
    assertEquals(logTimestamp, result.getAppErrorTime());
    assertNotNull(result.getDevice());
    assertEquals(throwable, result.getThrowable());
}
Also used : Context(android.content.Context) SessionContext(com.microsoft.appcenter.SessionContext) Device(com.microsoft.appcenter.ingestion.models.Device) FileWriter(java.io.FileWriter) Channel(com.microsoft.appcenter.channel.Channel) LogSerializer(com.microsoft.appcenter.ingestion.models.json.LogSerializer) Date(java.util.Date) ErrorReport(com.microsoft.appcenter.crashes.model.ErrorReport) ManagedErrorLog(com.microsoft.appcenter.crashes.ingestion.models.ManagedErrorLog) AppCenterConsumer(com.microsoft.appcenter.utils.async.AppCenterConsumer) UUID(java.util.UUID) File(java.io.File) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 30 with Channel

use of com.microsoft.appcenter.channel.Channel in project mobile-center-sdk-android by Microsoft.

the class CrashesTest method failToDeserializeLastSessionCrashReport.

@Test
public void failToDeserializeLastSessionCrashReport() throws JSONException, IOException, ClassNotFoundException {
    LogSerializer logSerializer = mock(LogSerializer.class);
    when(logSerializer.deserializeLog(anyString())).thenReturn(mock(ManagedErrorLog.class));
    mockStatic(ErrorLogHelper.class);
    File lastErrorLogFile = errorStorageDirectory.newFile("last-error-log.json");
    when(ErrorLogHelper.getLastErrorLogFile()).thenReturn(lastErrorLogFile);
    when(ErrorLogHelper.getStoredErrorLogFiles()).thenReturn(new File[] { lastErrorLogFile });
    when(ErrorLogHelper.getNewMinidumpFiles()).thenReturn(new File[0]);
    when(StorageHelper.InternalStorage.read(any(File.class))).thenReturn("");
    Crashes crashes = Crashes.getInstance();
    crashes.setLogSerializer(logSerializer);
    assertFalse(Crashes.hasCrashedInLastSession().get());
    JSONException jsonException = new JSONException("Fake JSON exception");
    when(logSerializer.deserializeLog(anyString())).thenThrow(jsonException);
    /*
         * Last session error is only fetched upon initialization: enabled and channel ready.
         * Here the service is disabled by default until started, we are waiting channel to be ready, simulate that.
         */
    assertFalse(Crashes.isEnabled().get());
    assertNull(Crashes.getLastSessionCrashReport().get());
    crashes.onStarting(mAppCenterHandler);
    crashes.onStarted(mock(Context.class), "", mock(Channel.class));
    assertTrue(Crashes.isEnabled().get());
    assertFalse(Crashes.hasCrashedInLastSession().get());
    assertNull(Crashes.getLastSessionCrashReport().get());
    /*
         * De-serializing fails twice: processing the log from last time as part of the bulk processing.
         * And loading that same file for exposing it in getLastErrorReport.
         */
    verifyStatic(times(2));
    AppCenterLog.error(eq(Crashes.LOG_TAG), anyString(), eq(jsonException));
}
Also used : Context(android.content.Context) SessionContext(com.microsoft.appcenter.SessionContext) ManagedErrorLog(com.microsoft.appcenter.crashes.ingestion.models.ManagedErrorLog) Channel(com.microsoft.appcenter.channel.Channel) JSONException(org.json.JSONException) LogSerializer(com.microsoft.appcenter.ingestion.models.json.LogSerializer) File(java.io.File) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Aggregations

Channel (com.microsoft.appcenter.channel.Channel)35 Context (android.content.Context)33 Test (org.junit.Test)32 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)32 SessionContext (com.microsoft.appcenter.SessionContext)14 Log (com.microsoft.appcenter.ingestion.models.Log)14 AppCenterLog (com.microsoft.appcenter.utils.AppCenterLog)14 ManagedErrorLog (com.microsoft.appcenter.crashes.ingestion.models.ManagedErrorLog)13 ErrorAttachmentLog (com.microsoft.appcenter.crashes.ingestion.models.ErrorAttachmentLog)11 File (java.io.File)11 LogSerializer (com.microsoft.appcenter.ingestion.models.json.LogSerializer)10 HandledErrorLog (com.microsoft.appcenter.crashes.ingestion.models.HandledErrorLog)9 ArgumentMatcher (org.mockito.ArgumentMatcher)9 PageLog (com.microsoft.appcenter.analytics.ingestion.models.PageLog)8 Matchers.anyString (org.mockito.Matchers.anyString)8 StartSessionLog (com.microsoft.appcenter.analytics.ingestion.models.StartSessionLog)7 ErrorReport (com.microsoft.appcenter.crashes.model.ErrorReport)7 EventLog (com.microsoft.appcenter.analytics.ingestion.models.EventLog)6 HashMap (java.util.HashMap)6 UUID (java.util.UUID)6