Search in sources :

Example 6 with ErrorReport

use of com.microsoft.azure.mobile.crashes.model.ErrorReport in project mobile-center-sdk-android by Microsoft.

the class CrashesTest method crashInLastSession.

@Test
public void crashInLastSession() throws JSONException, IOException, ClassNotFoundException {
    final int tOffset = 10;
    final long appLaunchTOffset = 100L;
    final ManagedErrorLog errorLog = new ManagedErrorLog();
    errorLog.setId(UUIDUtils.randomUUID());
    errorLog.setErrorThreadName(Thread.currentThread().getName());
    errorLog.setToffset(tOffset);
    errorLog.setAppLaunchTOffset(appLaunchTOffset);
    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);
    /* This callback will be called after Crashes service is initialized. */
    final ResultCallback<ErrorReport> callback = new ResultCallback<ErrorReport>() {

        @Override
        public void onResult(ErrorReport data) {
            assertNotNull(data);
            assertEquals(errorReport, data);
        }
    };
    mockStatic(ErrorLogHelper.class);
    File lastErrorLogFile = errorStorageDirectory.newFile("last-error-log.json");
    when(ErrorLogHelper.getLastErrorLogFile()).thenReturn(lastErrorLogFile);
    when(ErrorLogHelper.getStoredThrowableFile(any(UUID.class))).thenReturn(errorStorageDirectory.newFile());
    when(ErrorLogHelper.getErrorReportFromErrorLog(errorLog, throwable)).thenReturn(errorReport);
    when(ErrorLogHelper.getStoredErrorLogFiles()).thenReturn(new File[] { lastErrorLogFile });
    when(StorageHelper.InternalStorage.read(any(File.class))).thenAnswer(new Answer<String>() {

        @Override
        public String answer(InvocationOnMock invocation) throws Throwable {
            /* Call twice for multiple listeners during initialize. */
            Crashes.getLastSessionCrashReport(callback);
            Crashes.getLastSessionCrashReport(callback);
            return "";
        }
    });
    when(StorageHelper.InternalStorage.readObject(any(File.class))).thenReturn(throwable);
    Crashes.getInstance().setLogSerializer(logSerializer);
    assertFalse(Crashes.hasCrashedInLastSession());
    /*
         * Last session error is only fetched upon initialization: enabled and channel ready.
         * Here the service is enabled by default but we are waiting channel to be ready, simulate that.
         */
    assertTrue(Crashes.isEnabled());
    Crashes.getInstance().onStarted(mock(Context.class), "", mock(Channel.class));
    assertTrue(Crashes.hasCrashedInLastSession());
    Crashes.getLastSessionCrashReport(new ResultCallback<ErrorReport>() {

        @Override
        public void onResult(ErrorReport errorReport) {
            assertNotNull(errorReport);
            assertEquals(errorLog.getId().toString(), errorReport.getId());
            assertEquals(errorLog.getErrorThreadName(), errorReport.getThreadName());
            assertEquals(new Date(tOffset - appLaunchTOffset), errorReport.getAppStartTime());
            assertEquals(new Date(tOffset), errorReport.getAppErrorTime());
            assertNotNull(errorReport.getDevice());
            assertEquals(throwable, errorReport.getThrowable());
        }
    });
}
Also used : Context(android.content.Context) ResultCallback(com.microsoft.azure.mobile.ResultCallback) Device(com.microsoft.azure.mobile.ingestion.models.Device) Channel(com.microsoft.azure.mobile.channel.Channel) LogSerializer(com.microsoft.azure.mobile.ingestion.models.json.LogSerializer) Matchers.anyString(org.mockito.Matchers.anyString) Date(java.util.Date) ErrorReport(com.microsoft.azure.mobile.crashes.model.ErrorReport) ManagedErrorLog(com.microsoft.azure.mobile.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 7 with ErrorReport

use of com.microsoft.azure.mobile.crashes.model.ErrorReport in project mobile-center-sdk-android by Microsoft.

the class Crashes method buildErrorReport.

@VisibleForTesting
@Nullable
ErrorReport buildErrorReport(ManagedErrorLog log) {
    UUID id = log.getId();
    if (mErrorReportCache.containsKey(id)) {
        return mErrorReportCache.get(id).report;
    } else {
        File file = ErrorLogHelper.getStoredThrowableFile(id);
        if (file != null) {
            try {
                Throwable throwable = StorageHelper.InternalStorage.readObject(file);
                ErrorReport report = ErrorLogHelper.getErrorReportFromErrorLog(log, throwable);
                mErrorReportCache.put(id, new ErrorLogReport(log, report));
                return report;
            } catch (ClassNotFoundException ignored) {
                MobileCenterLog.error(LOG_TAG, "Cannot read throwable file " + file.getName(), ignored);
            } catch (IOException ignored) {
                MobileCenterLog.error(LOG_TAG, "Cannot access serialized throwable file " + file.getName(), ignored);
            }
        }
    }
    return null;
}
Also used : ErrorReport(com.microsoft.azure.mobile.crashes.model.ErrorReport) IOException(java.io.IOException) UUID(java.util.UUID) File(java.io.File) VisibleForTesting(android.support.annotation.VisibleForTesting) Nullable(android.support.annotation.Nullable)

Example 8 with ErrorReport

use of com.microsoft.azure.mobile.crashes.model.ErrorReport in project mobile-center-sdk-android by Microsoft.

the class ErrorLogHelperTest method getErrorReportFromErrorLog.

@Test
public void getErrorReportFromErrorLog() throws DeviceInfoHelper.DeviceInfoException {
    /* Mock base. */
    Context mockContext = mock(Context.class);
    when(SystemClock.elapsedRealtime()).thenReturn(1000L);
    when(Process.myPid()).thenReturn(123);
    /* Mock device. */
    Device mockDevice = mock(Device.class);
    when(DeviceInfoHelper.getDeviceInfo(any(Context.class))).thenReturn(mockDevice);
    /* Mock process name. */
    ActivityManager activityManager = mock(ActivityManager.class);
    RunningAppProcessInfo runningAppProcessInfo = new RunningAppProcessInfo(null, 0, null);
    runningAppProcessInfo.pid = 123;
    runningAppProcessInfo.processName = "right.process";
    when(mockContext.getSystemService(Context.ACTIVITY_SERVICE)).thenReturn(activityManager);
    when(activityManager.getRunningAppProcesses()).thenReturn(Arrays.asList(mock(RunningAppProcessInfo.class), runningAppProcessInfo));
    /* Mock architecture. */
    Whitebox.setInternalState(Build.VERSION.class, "SDK_INT", 23);
    Whitebox.setInternalState(Build.class, "SUPPORTED_ABIS", new String[] { "armeabi-v7a", "arm" });
    /* Create an error log. */
    ManagedErrorLog errorLog = ErrorLogHelper.createErrorLog(mockContext, java.lang.Thread.currentThread(), new RuntimeException(new TestCrashException()), java.lang.Thread.getAllStackTraces(), 900, true);
    assertNotNull(errorLog);
    /* Test. */
    Throwable throwable = new RuntimeException();
    ErrorReport report = ErrorLogHelper.getErrorReportFromErrorLog(errorLog, throwable);
    assertNotNull(report);
    assertEquals(errorLog.getId().toString(), report.getId());
    assertEquals(errorLog.getErrorThreadName(), report.getThreadName());
    assertEquals(throwable, report.getThrowable());
    assertEquals(errorLog.getToffset() - errorLog.getAppLaunchTOffset(), report.getAppStartTime().getTime());
    assertEquals(errorLog.getToffset(), report.getAppErrorTime().getTime());
    assertEquals(errorLog.getDevice(), report.getDevice());
}
Also used : Context(android.content.Context) ErrorReport(com.microsoft.azure.mobile.crashes.model.ErrorReport) TestCrashException(com.microsoft.azure.mobile.crashes.model.TestCrashException) RunningAppProcessInfo(android.app.ActivityManager.RunningAppProcessInfo) ManagedErrorLog(com.microsoft.azure.mobile.crashes.ingestion.models.ManagedErrorLog) Device(com.microsoft.azure.mobile.ingestion.models.Device) Build(android.os.Build) ActivityManager(android.app.ActivityManager) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 9 with ErrorReport

use of com.microsoft.azure.mobile.crashes.model.ErrorReport in project mobile-center-sdk-android by Microsoft.

the class CrashesTest method crashTest.

/**
     * Crash and sending report test.
     * <p>
     * We can't truly restart application in tests, so some kind of crashes can't be tested by this method.
     * Out of memory or stack overflow - crash the test process;
     * UI states errors - problems with restart activity;
     * <p>
     * Also to avoid flakiness, please setup your test environment
     * (https://google.github.io/android-testing-support-library/docs/espresso/setup/index.html#setup-your-test-environment).
     * On your device, under Settings->Developer options disable the following 3 settings:
     * - Window animation scale
     * - Transition animation scale
     * - Animator duration scale
     *
     * @param titleId Title string resource to find list item.
     * @throws InterruptedException If the current thread is interrupted.
     */
private void crashTest(@StringRes int titleId) throws InterruptedException {
    /* Crash. */
    onView(allOf(withChild(withText(R.string.title_crashes)), withChild(withText(R.string.description_crashes)))).perform(click());
    CrashFailureHandler failureHandler = new CrashFailureHandler();
    onCrash(titleId).withFailureHandler(failureHandler).perform(click());
    /* Check error report. */
    assertTrue(Crashes.hasCrashedInLastSession());
    ErrorReport errorReport = CrashesPrivateHelper.getLastSessionCrashReport();
    assertNotNull(errorReport);
    assertNotNull(errorReport.getId());
    assertEquals(mContext.getMainLooper().getThread().getName(), errorReport.getThreadName());
    assertThat("AppStartTime", new Date().getTime() - errorReport.getAppStartTime().getTime(), lessThan(60000L));
    assertThat("AppErrorTime", new Date().getTime() - errorReport.getAppErrorTime().getTime(), lessThan(10000L));
    assertNotNull(errorReport.getDevice());
    assertEquals(failureHandler.uncaughtException.getClass(), errorReport.getThrowable().getClass());
    assertEquals(failureHandler.uncaughtException.getMessage(), errorReport.getThrowable().getMessage());
    assertArrayEquals(failureHandler.uncaughtException.getStackTrace(), errorReport.getThrowable().getStackTrace());
    /* Send report. */
    waitFor(onView(withText(R.string.crash_confirmation_dialog_send_button)).inRoot(isDialog()), 1000).perform(click());
    /* Check toasts. */
    waitFor(onToast(mActivityTestRule.getActivity(), withText(R.string.crash_before_sending)), CHECK_DELAY).check(matches(isDisplayed()));
    onView(isRoot()).perform(waitFor(CHECK_DELAY));
    waitFor(onToast(mActivityTestRule.getActivity(), anyOf(withContainsText(R.string.crash_sent_succeeded), withText(R.string.crash_sent_failed))), TOAST_DELAY).check(matches(isDisplayed()));
    onView(isRoot()).perform(waitFor(TOAST_DELAY));
}
Also used : ErrorReport(com.microsoft.azure.mobile.crashes.model.ErrorReport) Date(java.util.Date)

Example 10 with ErrorReport

use of com.microsoft.azure.mobile.crashes.model.ErrorReport in project mobile-center-sdk-android by Microsoft.

the class Crashes method getChannelListener.

@Override
protected Channel.GroupListener getChannelListener() {
    return new Channel.GroupListener() {

        /** Process callback (template method) */
        private void processCallback(Log log, final CallbackProcessor callbackProcessor) {
            if (log instanceof ManagedErrorLog) {
                ManagedErrorLog errorLog = (ManagedErrorLog) log;
                if (errorLog.getFatal()) {
                    final ErrorReport report = buildErrorReport(errorLog);
                    UUID id = errorLog.getId();
                    if (report != null) {
                        /* Clean up before calling callbacks if requested. */
                        if (callbackProcessor.shouldDeleteThrowable()) {
                            removeStoredThrowable(id);
                        }
                        /* Call back. */
                        HandlerUtils.runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                callbackProcessor.onCallBack(report);
                            }
                        });
                    } else
                        MobileCenterLog.warn(LOG_TAG, "Cannot find crash report for the error log: " + id);
                }
            } else {
                if (!(log instanceof ErrorAttachmentLog))
                    MobileCenterLog.warn(LOG_TAG, "A different type of log comes to crashes: " + log.getClass().getName());
            }
        }

        @Override
        public void onBeforeSending(Log log) {
            processCallback(log, new CallbackProcessor() {

                @Override
                public boolean shouldDeleteThrowable() {
                    return false;
                }

                @Override
                public void onCallBack(ErrorReport report) {
                    mCrashesListener.onBeforeSending(report);
                }
            });
        }

        @Override
        public void onSuccess(Log log) {
            processCallback(log, new CallbackProcessor() {

                @Override
                public boolean shouldDeleteThrowable() {
                    return true;
                }

                @Override
                public void onCallBack(ErrorReport report) {
                    mCrashesListener.onSendingSucceeded(report);
                }
            });
        }

        @Override
        public void onFailure(Log log, final Exception e) {
            processCallback(log, new CallbackProcessor() {

                @Override
                public boolean shouldDeleteThrowable() {
                    return true;
                }

                @Override
                public void onCallBack(ErrorReport report) {
                    mCrashesListener.onSendingFailed(report, e);
                }
            });
        }
    };
}
Also used : ErrorReport(com.microsoft.azure.mobile.crashes.model.ErrorReport) MobileCenterLog(com.microsoft.azure.mobile.utils.MobileCenterLog) ErrorAttachmentLog(com.microsoft.azure.mobile.crashes.ingestion.models.ErrorAttachmentLog) Log(com.microsoft.azure.mobile.ingestion.models.Log) ManagedErrorLog(com.microsoft.azure.mobile.crashes.ingestion.models.ManagedErrorLog) ManagedErrorLog(com.microsoft.azure.mobile.crashes.ingestion.models.ManagedErrorLog) ErrorAttachmentLog(com.microsoft.azure.mobile.crashes.ingestion.models.ErrorAttachmentLog) UUID(java.util.UUID) TestCrashException(com.microsoft.azure.mobile.crashes.model.TestCrashException) JSONException(org.json.JSONException) IOException(java.io.IOException)

Aggregations

ErrorReport (com.microsoft.azure.mobile.crashes.model.ErrorReport)22 ManagedErrorLog (com.microsoft.azure.mobile.crashes.ingestion.models.ManagedErrorLog)15 File (java.io.File)15 Test (org.junit.Test)15 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)13 Channel (com.microsoft.azure.mobile.channel.Channel)12 UUID (java.util.UUID)12 Context (android.content.Context)10 LogSerializer (com.microsoft.azure.mobile.ingestion.models.json.LogSerializer)8 ErrorAttachmentLog (com.microsoft.azure.mobile.crashes.ingestion.models.ErrorAttachmentLog)6 JSONException (org.json.JSONException)6 Log (com.microsoft.azure.mobile.ingestion.models.Log)5 MobileCenterLog (com.microsoft.azure.mobile.utils.MobileCenterLog)5 InvocationOnMock (org.mockito.invocation.InvocationOnMock)5 TestCrashException (com.microsoft.azure.mobile.crashes.model.TestCrashException)4 IOException (java.io.IOException)4 ResultCallback (com.microsoft.azure.mobile.ResultCallback)3 Date (java.util.Date)3 Device (com.microsoft.azure.mobile.ingestion.models.Device)2 ArgumentMatcher (org.mockito.ArgumentMatcher)2