Search in sources :

Example 41 with Log

use of com.microsoft.appcenter.ingestion.models.Log in project mobile-center-sdk-android by Microsoft.

the class CrashesTest method manualProcessing.

@Test
public void manualProcessing() throws Exception {
    /* Setup mock for a crash in disk. */
    Context mockContext = mock(Context.class);
    Channel mockChannel = mock(Channel.class);
    ErrorReport report1 = new ErrorReport();
    report1.setId(UUIDUtils.randomUUID().toString());
    ErrorReport report2 = new ErrorReport();
    mockStatic(ErrorLogHelper.class);
    when(ErrorLogHelper.getStoredErrorLogFiles()).thenReturn(new File[] { mock(File.class), mock(File.class) });
    when(ErrorLogHelper.getNewMinidumpFiles()).thenReturn(new File[0]);
    when(ErrorLogHelper.getStoredThrowableFile(any(UUID.class))).thenReturn(mock(File.class));
    when(ErrorLogHelper.getErrorReportFromErrorLog(any(ManagedErrorLog.class), any(Throwable.class))).thenReturn(report1).thenReturn(report2);
    when(StorageHelper.InternalStorage.read(any(File.class))).thenReturn("");
    when(StorageHelper.InternalStorage.readObject(any(File.class))).thenReturn(new RuntimeException());
    LogSerializer logSerializer = mock(LogSerializer.class);
    when(logSerializer.deserializeLog(anyString())).thenAnswer(new Answer<ManagedErrorLog>() {

        @Override
        public ManagedErrorLog answer(InvocationOnMock invocation) throws Throwable {
            ManagedErrorLog log = mock(ManagedErrorLog.class);
            when(log.getId()).thenReturn(UUID.randomUUID());
            return log;
        }
    });
    Crashes crashes = Crashes.getInstance();
    crashes.setLogSerializer(logSerializer);
    /* Create listener for user confirmation. */
    CrashesListener listener = mock(CrashesListener.class);
    Crashes.setListener(listener);
    /* Set manual processing. */
    WrapperSdkExceptionManager.setAutomaticProcessing(false);
    /* Start crashes. */
    crashes.onStarting(mAppCenterHandler);
    crashes.onStarted(mockContext, "", mockChannel);
    /* No log queued. */
    verify(mockChannel, never()).enqueue(any(Log.class), eq(crashes.getGroupName()));
    /* Get crash reports. */
    Collection<ErrorReport> reports = WrapperSdkExceptionManager.getUnprocessedErrorReports().get();
    assertNotNull(reports);
    assertEquals(2, reports.size());
    Iterator<ErrorReport> iterator = reports.iterator();
    assertEquals(report1, iterator.next());
    assertEquals(report2, iterator.next());
    /* Listener not called yet on anything on manual processing. */
    verifyZeroInteractions(listener);
    /* Send only the first. */
    assertFalse(WrapperSdkExceptionManager.sendCrashReportsOrAwaitUserConfirmation(Collections.singletonList(report1.getId())).get());
    /* We used manual process function, listener not called. */
    verifyZeroInteractions(listener);
    /* No log sent until manual user confirmation in that mode (we are not in always send). */
    verify(mockChannel, never()).enqueue(any(ManagedErrorLog.class), eq(crashes.getGroupName()));
    /* Confirm with always send. */
    Crashes.notifyUserConfirmation(Crashes.ALWAYS_SEND);
    verifyStatic();
    StorageHelper.PreferencesStorage.putBoolean(Crashes.PREF_KEY_ALWAYS_SEND, true);
    when(StorageHelper.PreferencesStorage.getBoolean(eq(Crashes.PREF_KEY_ALWAYS_SEND), anyBoolean())).thenReturn(true);
    /* 1 log sent. Other one is filtered. */
    verify(mockChannel).enqueue(any(ManagedErrorLog.class), eq(crashes.getGroupName()));
    /* We can send attachments via wrapper instead of using listener (both work but irrelevant to test with listener). */
    ErrorAttachmentLog mockAttachment = mock(ErrorAttachmentLog.class);
    when(mockAttachment.getId()).thenReturn(UUID.randomUUID());
    when(mockAttachment.getData()).thenReturn(new byte[0]);
    when(mockAttachment.isValid()).thenReturn(true);
    WrapperSdkExceptionManager.sendErrorAttachments(report1.getId(), Collections.singletonList(mockAttachment));
    verify(mockChannel).enqueue(eq(mockAttachment), eq(crashes.getGroupName()));
    /* Send attachment with invalid UUID format for report identifier. */
    mockAttachment = mock(ErrorAttachmentLog.class);
    when(mockAttachment.getId()).thenReturn(UUID.randomUUID());
    when(mockAttachment.getData()).thenReturn(new byte[0]);
    when(mockAttachment.isValid()).thenReturn(true);
    WrapperSdkExceptionManager.sendErrorAttachments("not-a-uuid", Collections.singletonList(mockAttachment));
    verify(mockChannel, never()).enqueue(eq(mockAttachment), eq(crashes.getGroupName()));
    /* We used manual process function, listener not called and our mock channel does not send events. */
    verifyZeroInteractions(listener);
    /* Reset instance to test another tine with always send. */
    Crashes.unsetInstance();
    crashes = Crashes.getInstance();
    when(ErrorLogHelper.getErrorReportFromErrorLog(any(ManagedErrorLog.class), any(Throwable.class))).thenReturn(report1).thenReturn(report2);
    WrapperSdkExceptionManager.setAutomaticProcessing(false);
    crashes.setLogSerializer(logSerializer);
    crashes.onStarting(mAppCenterHandler);
    mockChannel = mock(Channel.class);
    crashes.onStarted(mockContext, "", mockChannel);
    assertTrue(Crashes.isEnabled().get());
    verify(mockChannel, never()).enqueue(any(ManagedErrorLog.class), eq(crashes.getGroupName()));
    /* Get crash reports, check always sent was returned and sent without confirmation. */
    assertTrue(WrapperSdkExceptionManager.sendCrashReportsOrAwaitUserConfirmation(Collections.singletonList(report2.getId())).get());
    verify(mockChannel).enqueue(any(ManagedErrorLog.class), eq(crashes.getGroupName()));
}
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) LogSerializer(com.microsoft.appcenter.ingestion.models.json.LogSerializer) ErrorReport(com.microsoft.appcenter.crashes.model.ErrorReport) ManagedErrorLog(com.microsoft.appcenter.crashes.ingestion.models.ManagedErrorLog) InvocationOnMock(org.mockito.invocation.InvocationOnMock) ErrorAttachmentLog(com.microsoft.appcenter.crashes.ingestion.models.ErrorAttachmentLog) UUID(java.util.UUID) File(java.io.File) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 42 with Log

use of com.microsoft.appcenter.ingestion.models.Log in project mobile-center-sdk-android by Microsoft.

the class CrashesTest method trackExceptionForWrapperSdk.

@Test
public void trackExceptionForWrapperSdk() {
    StackFrame frame = new StackFrame();
    frame.setClassName("1");
    frame.setFileName("2");
    frame.setLineNumber(3);
    frame.setMethodName("4");
    final com.microsoft.appcenter.crashes.ingestion.models.Exception exception = new com.microsoft.appcenter.crashes.ingestion.models.Exception();
    exception.setType("5");
    exception.setMessage("6");
    exception.setFrames(singletonList(frame));
    Crashes crashes = Crashes.getInstance();
    Channel mockChannel = mock(Channel.class);
    WrapperSdkExceptionManager.trackException(exception);
    verify(mockChannel, never()).enqueue(any(Log.class), eq(crashes.getGroupName()));
    crashes.onStarting(mAppCenterHandler);
    crashes.onStarted(mock(Context.class), "", mockChannel);
    WrapperSdkExceptionManager.trackException(exception);
    verify(mockChannel).enqueue(argThat(new ArgumentMatcher<Log>() {

        @Override
        public boolean matches(Object item) {
            return item instanceof HandledErrorLog && exception.equals(((HandledErrorLog) item).getException());
        }
    }), eq(crashes.getGroupName()));
    reset(mockChannel);
    WrapperSdkExceptionManager.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.equals(((HandledErrorLog) item).getException()) && ((HandledErrorLog) item).getProperties().size() == 0;
        }
    }), eq(crashes.getGroupName()));
    reset(mockChannel);
    WrapperSdkExceptionManager.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.equals(((HandledErrorLog) item).getException()) && ((HandledErrorLog) item).getProperties().size() == 5;
        }
    }), eq(crashes.getGroupName()));
    reset(mockChannel);
    final String longerMapItem = generateString(ErrorLogHelper.MAX_PROPERTY_ITEM_LENGTH + 1, '*');
    WrapperSdkExceptionManager.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.equals((errorLog.getException()))) {
                    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()));
}
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) HandledErrorLog(com.microsoft.appcenter.crashes.ingestion.models.HandledErrorLog) Matchers.anyString(org.mockito.Matchers.anyString) TestUtils.generateString(com.microsoft.appcenter.test.TestUtils.generateString) JSONException(org.json.JSONException) NativeException(com.microsoft.appcenter.crashes.model.NativeException) TestCrashException(com.microsoft.appcenter.crashes.model.TestCrashException) IOException(java.io.IOException) StackFrame(com.microsoft.appcenter.crashes.ingestion.models.StackFrame) ArgumentMatcher(org.mockito.ArgumentMatcher) Map(java.util.Map) HashMap(java.util.HashMap) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 43 with Log

use of com.microsoft.appcenter.ingestion.models.Log in project mobile-center-sdk-android by Microsoft.

the class CrashesTest method manuallyReportNullList.

@Test
public void manuallyReportNullList() throws Exception {
    /* Setup mock for a crash in disk. */
    Context mockContext = mock(Context.class);
    Channel mockChannel = mock(Channel.class);
    ErrorReport report1 = new ErrorReport();
    report1.setId(UUIDUtils.randomUUID().toString());
    ErrorReport report2 = new ErrorReport();
    mockStatic(ErrorLogHelper.class);
    when(ErrorLogHelper.getStoredErrorLogFiles()).thenReturn(new File[] { mock(File.class), mock(File.class) });
    when(ErrorLogHelper.getNewMinidumpFiles()).thenReturn(new File[0]);
    when(ErrorLogHelper.getStoredThrowableFile(any(UUID.class))).thenReturn(mock(File.class));
    when(ErrorLogHelper.getErrorReportFromErrorLog(any(ManagedErrorLog.class), any(Throwable.class))).thenReturn(report1).thenReturn(report2);
    when(StorageHelper.InternalStorage.read(any(File.class))).thenReturn("");
    when(StorageHelper.InternalStorage.readObject(any(File.class))).thenReturn(new RuntimeException());
    LogSerializer logSerializer = mock(LogSerializer.class);
    when(logSerializer.deserializeLog(anyString())).thenAnswer(new Answer<ManagedErrorLog>() {

        @Override
        public ManagedErrorLog answer(InvocationOnMock invocation) throws Throwable {
            ManagedErrorLog log = mock(ManagedErrorLog.class);
            when(log.getId()).thenReturn(UUID.randomUUID());
            return log;
        }
    });
    Crashes crashes = Crashes.getInstance();
    crashes.setLogSerializer(logSerializer);
    /* Set manual processing. */
    WrapperSdkExceptionManager.setAutomaticProcessing(false);
    /* Start crashes. */
    crashes.onStarting(mAppCenterHandler);
    crashes.onStarted(mockContext, "", mockChannel);
    /* No log queued. */
    verify(mockChannel, never()).enqueue(any(Log.class), eq(crashes.getGroupName()));
    /* Get crash reports. */
    Collection<ErrorReport> reports = WrapperSdkExceptionManager.getUnprocessedErrorReports().get();
    assertNotNull(reports);
    assertEquals(2, reports.size());
    Iterator<ErrorReport> iterator = reports.iterator();
    assertEquals(report1, iterator.next());
    assertEquals(report2, iterator.next());
    /* Send nothing using null. */
    assertFalse(WrapperSdkExceptionManager.sendCrashReportsOrAwaitUserConfirmation(null).get());
    /* No log sent. */
    verify(mockChannel, never()).enqueue(any(ManagedErrorLog.class), eq(crashes.getGroupName()));
}
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) LogSerializer(com.microsoft.appcenter.ingestion.models.json.LogSerializer) ErrorReport(com.microsoft.appcenter.crashes.model.ErrorReport) ManagedErrorLog(com.microsoft.appcenter.crashes.ingestion.models.ManagedErrorLog) InvocationOnMock(org.mockito.invocation.InvocationOnMock) UUID(java.util.UUID) File(java.io.File) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 44 with Log

use of com.microsoft.appcenter.ingestion.models.Log in project mobile-center-sdk-android by Microsoft.

the class DistributeSerializerTest method serialize.

@Test
public void serialize() throws JSONException {
    LogContainer expectedContainer = new LogContainer();
    List<Log> logs = new ArrayList<>();
    {
        DistributionStartSessionLog log = new DistributionStartSessionLog();
        log.setTimestamp(new Date());
        logs.add(log);
    }
    expectedContainer.setLogs(logs);
    UUID sid = UUIDUtils.randomUUID();
    for (Log log : logs) {
        log.setSid(sid);
    }
    /* Serialize and deserialize logs container. */
    LogSerializer serializer = new DefaultLogSerializer();
    serializer.addLogFactory(DistributionStartSessionLog.TYPE, new DistributionStartSessionLogFactory());
    String payload = serializer.serializeContainer(expectedContainer);
    LogContainer actualContainer = serializer.deserializeContainer(payload);
    /* Verify that logs container successfully deserialized. */
    Assert.assertEquals(expectedContainer, actualContainer);
}
Also used : DistributionStartSessionLogFactory(com.microsoft.appcenter.distribute.ingestion.models.json.DistributionStartSessionLogFactory) DistributionStartSessionLog(com.microsoft.appcenter.distribute.ingestion.models.DistributionStartSessionLog) Log(com.microsoft.appcenter.ingestion.models.Log) DistributionStartSessionLog(com.microsoft.appcenter.distribute.ingestion.models.DistributionStartSessionLog) ArrayList(java.util.ArrayList) LogContainer(com.microsoft.appcenter.ingestion.models.LogContainer) DefaultLogSerializer(com.microsoft.appcenter.ingestion.models.json.DefaultLogSerializer) LogSerializer(com.microsoft.appcenter.ingestion.models.json.LogSerializer) UUID(java.util.UUID) Date(java.util.Date) DefaultLogSerializer(com.microsoft.appcenter.ingestion.models.json.DefaultLogSerializer) Test(org.junit.Test)

Example 45 with Log

use of com.microsoft.appcenter.ingestion.models.Log in project mobile-center-sdk-android by Microsoft.

the class DatabasePersistenceAndroidTest method putLargeLogAndDeleteAll.

@Test
public void putLargeLogAndDeleteAll() throws PersistenceException, IOException {
    /* Initialize database persistence. */
    DatabasePersistence persistence = new DatabasePersistence("test-persistence", "putLargeLog", 1);
    /* Set a mock log serializer. */
    LogSerializer logSerializer = new DefaultLogSerializer();
    logSerializer.addLogFactory(MOCK_LOG_TYPE, new MockLogFactory());
    persistence.setLogSerializer(logSerializer);
    try {
        /* Initial count is 0. */
        assertEquals(0, persistence.countLogs("test-p1"));
        /* Generate a large log and persist. */
        LogWithProperties log = AndroidTestUtils.generateMockLog();
        int size = 2 * 1024 * 1024;
        StringBuilder largeValue = new StringBuilder(size);
        for (int i = 0; i < size; i++) {
            largeValue.append("x");
        }
        Map<String, String> properties = new HashMap<>();
        properties.put("key", largeValue.toString());
        log.setProperties(properties);
        long id = persistence.putLog("test-p1", log);
        /* Count logs. */
        assertEquals(1, persistence.countLogs("test-p1"));
        /* Get a log from persistence. */
        List<Log> outputLogs = new ArrayList<>();
        persistence.getLogs("test-p1", 1, outputLogs);
        assertEquals(1, outputLogs.size());
        assertEquals(log, outputLogs.get(0));
        assertEquals(1, persistence.countLogs("test-p1"));
        /* Verify large file. */
        File file = persistence.getLargePayloadFile(persistence.getLargePayloadGroupDirectory("test-p1"), id);
        assertNotNull(file);
        String fileLog = StorageHelper.InternalStorage.read(file);
        assertNotNull(fileLog);
        assertTrue(fileLog.length() >= size);
        /* Delete entire group. */
        persistence.deleteLogs("test-p1");
        assertEquals(0, persistence.countLogs("test-p1"));
        /* Verify file delete and also parent directory since we used group deletion. */
        assertFalse(file.exists());
        assertFalse(file.getParentFile().exists());
    } finally {
        /* Close. */
        // noinspection ThrowFromFinallyBlock
        persistence.close();
    }
}
Also used : LogWithProperties(com.microsoft.appcenter.ingestion.models.LogWithProperties) HashMap(java.util.HashMap) Log(com.microsoft.appcenter.ingestion.models.Log) ArrayList(java.util.ArrayList) DefaultLogSerializer(com.microsoft.appcenter.ingestion.models.json.DefaultLogSerializer) LogSerializer(com.microsoft.appcenter.ingestion.models.json.LogSerializer) Mockito.anyString(org.mockito.Mockito.anyString) SuppressLint(android.annotation.SuppressLint) MockLogFactory(com.microsoft.appcenter.ingestion.models.json.MockLogFactory) File(java.io.File) DefaultLogSerializer(com.microsoft.appcenter.ingestion.models.json.DefaultLogSerializer) MediumTest(android.support.test.filters.MediumTest) Test(org.junit.Test)

Aggregations

Log (com.microsoft.appcenter.ingestion.models.Log)64 Test (org.junit.Test)50 ArrayList (java.util.ArrayList)27 AppCenterLog (com.microsoft.appcenter.utils.AppCenterLog)25 Context (android.content.Context)24 UUID (java.util.UUID)23 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)22 LogSerializer (com.microsoft.appcenter.ingestion.models.json.LogSerializer)20 EventLog (com.microsoft.appcenter.analytics.ingestion.models.EventLog)15 DefaultLogSerializer (com.microsoft.appcenter.ingestion.models.json.DefaultLogSerializer)15 StartSessionLog (com.microsoft.appcenter.analytics.ingestion.models.StartSessionLog)14 LogContainer (com.microsoft.appcenter.ingestion.models.LogContainer)14 Channel (com.microsoft.appcenter.channel.Channel)12 Persistence (com.microsoft.appcenter.persistence.Persistence)12 HashMap (java.util.HashMap)11 Matchers.anyString (org.mockito.Matchers.anyString)11 InvocationOnMock (org.mockito.invocation.InvocationOnMock)11 Date (java.util.Date)10 MediumTest (android.support.test.filters.MediumTest)9 IngestionHttp (com.microsoft.appcenter.ingestion.IngestionHttp)9