Search in sources :

Example 1 with Device

use of com.microsoft.appcenter.ingestion.models.Device in project AppCenter-SDK-Android by Microsoft.

the class ErrorLogHelperTest method createErrorLog.

@Test
public void createErrorLog() throws java.lang.Exception {
    /* Dummy coverage of utils class. */
    new ErrorLogHelper();
    /* Mock base. */
    Context mockContext = mock(Context.class);
    when(Process.myPid()).thenReturn(123);
    Date logTimestamp = new Date(1000L);
    whenNew(Date.class).withNoArguments().thenReturn(logTimestamp);
    whenNew(Date.class).withArguments(anyLong()).thenAnswer(new Answer<Date>() {

        @Override
        public Date answer(InvocationOnMock invocation) throws Throwable {
            return new Date((Long) invocation.getArguments()[0]);
        }
    });
    /* 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. */
    TestUtils.setInternalState(Build.VERSION.class, "SDK_INT", 23);
    TestUtils.setInternalState(Build.class, "SUPPORTED_ABIS", new String[] { "armeabi-v7a", "arm" });
    /* Test. */
    long launchTimeStamp = 2000;
    ManagedErrorLog errorLog = ErrorLogHelper.createErrorLog(mockContext, java.lang.Thread.currentThread(), new RuntimeException(new IOException(new TestCrashException())), java.lang.Thread.getAllStackTraces(), launchTimeStamp);
    assertNotNull(errorLog);
    assertNotNull(errorLog.getId());
    assertEquals(logTimestamp, errorLog.getTimestamp());
    assertEquals(mockDevice, errorLog.getDevice());
    assertEquals(Integer.valueOf(123), errorLog.getProcessId());
    assertEquals("right.process", errorLog.getProcessName());
    assertNull(errorLog.getParentProcessId());
    assertNull(errorLog.getParentProcessName());
    assertEquals("armeabi-v7a", errorLog.getArchitecture());
    assertEquals((Long) java.lang.Thread.currentThread().getId(), errorLog.getErrorThreadId());
    assertEquals(java.lang.Thread.currentThread().getName(), errorLog.getErrorThreadName());
    assertEquals(Boolean.TRUE, errorLog.getFatal());
    assertEquals(launchTimeStamp, errorLog.getAppLaunchTimestamp().getTime());
    /* Check first exception. */
    Exception topException = errorLog.getException();
    sanityCheck(topException);
    assertEquals(RuntimeException.class.getName(), topException.getType());
    assertNotNull(topException.getMessage());
    assertNotNull(topException.getInnerExceptions());
    assertEquals(1, topException.getInnerExceptions().size());
    /* Check second exception. */
    Exception middleException = topException.getInnerExceptions().get(0);
    sanityCheck(middleException);
    assertEquals(IOException.class.getName(), middleException.getType());
    assertNotNull(middleException.getInnerExceptions());
    assertEquals(1, middleException.getInnerExceptions().size());
    /* Check third exception. */
    Exception rootCauseException = middleException.getInnerExceptions().get(0);
    sanityCheck(rootCauseException);
    assertEquals(TestCrashException.class.getName(), rootCauseException.getType());
    assertNotNull(rootCauseException.getMessage());
    assertNull(rootCauseException.getInnerExceptions());
    /* Check threads. */
    assertNotNull(errorLog.getThreads());
    assertEquals(java.lang.Thread.getAllStackTraces().size(), errorLog.getThreads().size());
    for (Thread thread : errorLog.getThreads()) {
        assertNotNull(thread);
        assertTrue(thread.getId() > 0);
        assertNotNull(thread.getName());
        assertNotNull(thread.getFrames());
        for (StackFrame frame : thread.getFrames()) {
            assertNotNull(frame);
            assertNotNull(frame.getClassName());
            assertNotNull(frame.getMethodName());
        }
    }
}
Also used : Context(android.content.Context) TestCrashException(com.microsoft.appcenter.crashes.model.TestCrashException) Device(com.microsoft.appcenter.ingestion.models.Device) IOException(java.io.IOException) ActivityManager(android.app.ActivityManager) Date(java.util.Date) Exception(com.microsoft.appcenter.crashes.ingestion.models.Exception) TestCrashException(com.microsoft.appcenter.crashes.model.TestCrashException) IOException(java.io.IOException) Thread(com.microsoft.appcenter.crashes.ingestion.models.Thread) RunningAppProcessInfo(android.app.ActivityManager.RunningAppProcessInfo) ManagedErrorLog(com.microsoft.appcenter.crashes.ingestion.models.ManagedErrorLog) InvocationOnMock(org.mockito.invocation.InvocationOnMock) Build(android.os.Build) StackFrame(com.microsoft.appcenter.crashes.ingestion.models.StackFrame) Matchers.anyLong(org.mockito.Matchers.anyLong) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 2 with Device

use of com.microsoft.appcenter.ingestion.models.Device in project AppCenter-SDK-Android by Microsoft.

the class DeviceInfoActivity method onCreate.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_device_info);
    mNetworkStateHelper = NetworkStateHelper.getSharedInstance(this);
    mNetworkStateHelper.addListener(this);
    onNetworkStateUpdated(mNetworkStateHelper.isNetworkConnected());
    Device log;
    try {
        log = DeviceInfoHelper.getDeviceInfo(getApplicationContext());
    } catch (DeviceInfoHelper.DeviceInfoException e) {
        Toast.makeText(getBaseContext(), R.string.error_device_info, Toast.LENGTH_LONG).show();
        return;
    }
    final List<DeviceInfoDisplayModel> list = getDeviceInfoDisplayModelList(log);
    ArrayAdapter<DeviceInfoDisplayModel> adapter = new ArrayAdapter<DeviceInfoDisplayModel>(this, android.R.layout.simple_list_item_2, android.R.id.text1, list) {

        @NonNull
        @Override
        public View getView(int position, View convertView, @NonNull ViewGroup parent) {
            View view = super.getView(position, convertView, parent);
            TextView text1 = view.findViewById(android.R.id.text1);
            TextView text2 = view.findViewById(android.R.id.text2);
            text1.setText(list.get(position).title);
            text2.setText(list.get(position).value);
            return view;
        }
    };
    ((ListView) findViewById(R.id.device_info_list_view)).setAdapter(adapter);
}
Also used : ListView(android.widget.ListView) Device(com.microsoft.appcenter.ingestion.models.Device) ViewGroup(android.view.ViewGroup) NonNull(android.support.annotation.NonNull) TextView(android.widget.TextView) DeviceInfoHelper(com.microsoft.appcenter.utils.DeviceInfoHelper) TextView(android.widget.TextView) View(android.view.View) ListView(android.widget.ListView) ArrayAdapter(android.widget.ArrayAdapter)

Example 3 with Device

use of com.microsoft.appcenter.ingestion.models.Device in project AppCenter-SDK-Android by Microsoft.

the class ChannelLogDecorateTest method checkLogAttributes.

@Test
public void checkLogAttributes() throws DeviceInfoHelper.DeviceInfoException {
    mockStatic(DeviceInfoHelper.class);
    Device device = mock(Device.class);
    when(DeviceInfoHelper.getDeviceInfo(any(Context.class))).thenReturn(device);
    mockStatic(IdHelper.class);
    Channel channel = new DefaultChannel(mock(Context.class), UUID.randomUUID().toString(), mock(Persistence.class), mock(Ingestion.class), mock(Handler.class));
    channel.addGroup("", 0, 0, 0, null);
    /* Test a log that should be decorated. */
    for (int i = 0; i < 3; i++) {
        Log log = mock(Log.class);
        channel.enqueue(log, "");
        verify(log).setDevice(device);
        verify(log).setTimestamp(any(Date.class));
    }
    /* Check cache was used, meaning only 1 call to generate a device. */
    verifyStatic();
    DeviceInfoHelper.getDeviceInfo(any(Context.class));
    /* Test a log that is already decorated. */
    Log log2 = mock(Log.class);
    when(log2.getDevice()).thenReturn(device);
    when(log2.getTimestamp()).thenReturn(new Date(123L));
    channel.enqueue(log2, "");
    verify(log2, never()).setDevice(any(Device.class));
    verify(log2, never()).setTimestamp(any(Date.class));
    /* Simulate update to wrapper SDK. */
    Device device2 = mock(Device.class);
    when(DeviceInfoHelper.getDeviceInfo(any(Context.class))).thenReturn(device2);
    channel.invalidateDeviceCache();
    /* Generate some logs to verify device properties have been updated. */
    for (int i = 0; i < 3; i++) {
        Log log3 = mock(Log.class);
        channel.enqueue(log3, "");
        verify(log3).setDevice(device2);
        verify(log3).setTimestamp(any(Date.class));
    }
    /* Check only 1 device has been generated after cache invalidate. */
    verifyStatic(times(2));
    DeviceInfoHelper.getDeviceInfo(any(Context.class));
}
Also used : Context(android.content.Context) Persistence(com.microsoft.appcenter.persistence.Persistence) Log(com.microsoft.appcenter.ingestion.models.Log) Device(com.microsoft.appcenter.ingestion.models.Device) Handler(android.os.Handler) Date(java.util.Date) Ingestion(com.microsoft.appcenter.ingestion.Ingestion) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 4 with Device

use of com.microsoft.appcenter.ingestion.models.Device in project AppCenter-SDK-Android by Microsoft.

the class DeviceInfoHelper method getDeviceInfo.

/**
 * Gets device information.
 *
 * @param context The context of the application.
 * @return {@link Device}
 * @throws DeviceInfoException If device information cannot be retrieved
 */
public static synchronized Device getDeviceInfo(Context context) throws DeviceInfoException {
    Device device = new Device();
    /* Application version. */
    PackageInfo packageInfo;
    try {
        PackageManager packageManager = context.getPackageManager();
        packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
        device.setAppVersion(packageInfo.versionName);
        device.setAppBuild(String.valueOf(packageInfo.versionCode));
    } catch (Exception e) {
        AppCenterLog.error(AppCenter.LOG_TAG, "Cannot retrieve package info", e);
        throw new DeviceInfoException("Cannot retrieve package info", e);
    }
    /* Application namespace. */
    device.setAppNamespace(context.getPackageName());
    /* Carrier info. */
    try {
        TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        String networkCountryIso = telephonyManager.getNetworkCountryIso();
        if (!TextUtils.isEmpty(networkCountryIso)) {
            device.setCarrierCountry(networkCountryIso);
        }
        String networkOperatorName = telephonyManager.getNetworkOperatorName();
        if (!TextUtils.isEmpty(networkOperatorName)) {
            device.setCarrierName(networkOperatorName);
        }
    } catch (Exception e) {
        AppCenterLog.error(AppCenter.LOG_TAG, "Cannot retrieve carrier info", e);
    }
    /* Locale. */
    device.setLocale(Locale.getDefault().toString());
    /* Hardware info. */
    device.setModel(Build.MODEL);
    device.setOemName(Build.MANUFACTURER);
    /* OS version. */
    device.setOsApiLevel(Build.VERSION.SDK_INT);
    device.setOsName(OS_NAME);
    device.setOsVersion(Build.VERSION.RELEASE);
    device.setOsBuild(Build.ID);
    /* Screen size. */
    try {
        device.setScreenSize(getScreenSize(context));
    } catch (Exception e) {
        AppCenterLog.error(AppCenter.LOG_TAG, "Cannot retrieve screen size", e);
    }
    /* Set SDK name and version. Don't add the BuildConfig import or it will trigger a Javadoc warning... */
    device.setSdkName(com.microsoft.appcenter.BuildConfig.SDK_NAME);
    device.setSdkVersion(com.microsoft.appcenter.BuildConfig.VERSION_NAME);
    /* Timezone offset in minutes (including DST). */
    device.setTimeZoneOffset(TimeZone.getDefault().getOffset(System.currentTimeMillis()) / 60 / 1000);
    /* Add wrapper SDK information if any. */
    if (sWrapperSdk != null) {
        device.setWrapperSdkVersion(sWrapperSdk.getWrapperSdkVersion());
        device.setWrapperSdkName(sWrapperSdk.getWrapperSdkName());
        device.setWrapperRuntimeVersion(sWrapperSdk.getWrapperRuntimeVersion());
        device.setLiveUpdateReleaseLabel(sWrapperSdk.getLiveUpdateReleaseLabel());
        device.setLiveUpdateDeploymentKey(sWrapperSdk.getLiveUpdateDeploymentKey());
        device.setLiveUpdatePackageHash(sWrapperSdk.getLiveUpdatePackageHash());
    }
    /* Return device properties. */
    return device;
}
Also used : PackageManager(android.content.pm.PackageManager) TelephonyManager(android.telephony.TelephonyManager) Device(com.microsoft.appcenter.ingestion.models.Device) PackageInfo(android.content.pm.PackageInfo)

Example 5 with Device

use of com.microsoft.appcenter.ingestion.models.Device in project AppCenter-SDK-Android by Microsoft.

the class DeviceInfoHelperTest method getDeviceInfoMissingScreenSize.

@Test
public void getDeviceInfoMissingScreenSize() throws DeviceInfoHelper.DeviceInfoException, PackageManager.NameNotFoundException {
    /* Mocking instances. */
    Context contextMock = mock(Context.class);
    PackageManager packageManagerMock = mock(PackageManager.class);
    mockStatic(AppCenterLog.class);
    /* Delegates to mock instances. */
    when(contextMock.getPackageManager()).thenReturn(packageManagerMock);
    when(contextMock.getSystemService(Context.TELEPHONY_SERVICE)).thenReturn(mock(TelephonyManager.class));
    when(contextMock.getSystemService(Context.WINDOW_SERVICE)).thenThrow(new RuntimeException());
    // noinspection WrongConstant
    when(packageManagerMock.getPackageInfo(anyString(), anyInt())).thenReturn(mock(PackageInfo.class));
    /* Verify. */
    Device device = DeviceInfoHelper.getDeviceInfo(contextMock);
    assertNull(device.getScreenSize());
    verifyStatic();
    AppCenterLog.error(eq(AppCenter.LOG_TAG), anyString(), any(Exception.class));
}
Also used : Context(android.content.Context) PackageManager(android.content.pm.PackageManager) TelephonyManager(android.telephony.TelephonyManager) PackageInfo(android.content.pm.PackageInfo) Device(com.microsoft.appcenter.ingestion.models.Device) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Aggregations

Device (com.microsoft.appcenter.ingestion.models.Device)46 Test (org.junit.Test)32 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)29 Context (android.content.Context)18 File (java.io.File)15 Date (java.util.Date)11 ManagedErrorLog (com.microsoft.appcenter.crashes.ingestion.models.ManagedErrorLog)10 Matchers.anyString (org.mockito.Matchers.anyString)10 TestCrashException (com.microsoft.appcenter.crashes.model.TestCrashException)9 IOException (java.io.IOException)9 ErrorReport (com.microsoft.appcenter.crashes.model.ErrorReport)8 Log (com.microsoft.appcenter.ingestion.models.Log)8 JSONException (org.json.JSONException)8 PackageInfo (android.content.pm.PackageInfo)7 PackageManager (android.content.pm.PackageManager)7 Build (android.os.Build)7 InvocationOnMock (org.mockito.invocation.InvocationOnMock)7 TelephonyManager (android.telephony.TelephonyManager)6 Log.getStackTraceString (android.util.Log.getStackTraceString)6 DefaultLogSerializer (com.microsoft.appcenter.ingestion.models.json.DefaultLogSerializer)6