Search in sources :

Example 1 with DatabaseManager

use of com.microsoft.appcenter.utils.storage.DatabaseManager in project mobile-center-sdk-android by Microsoft.

the class DatabasePersistenceAndroidTest method upgradeFromVersion5to6.

@Test
public void upgradeFromVersion5to6() throws PersistenceException, JSONException {
    /* Initialize database persistence with old version. */
    ContentValues schema = new ContentValues(SCHEMA);
    DatabaseManager databaseManager = new DatabaseManager(sContext, DatabasePersistence.DATABASE, DatabasePersistence.TABLE, DatabasePersistence.VERSION_TIMESTAMP_COLUMN, schema, CREATE_LOGS_SQL, mock(DatabaseManager.Listener.class));
    /* Init log serializer. */
    LogSerializer logSerializer = new DefaultLogSerializer();
    logSerializer.addLogFactory(MOCK_LOG_TYPE, new MockLogFactory());
    logSerializer.addLogFactory(MockCommonSchemaLog.TYPE, new MockCommonSchemaLogFactory());
    /* Insert old data before upgrade. */
    Log oldLog = AndroidTestUtils.generateMockLog();
    try {
        ContentValues contentValues = new ContentValues();
        contentValues.put(DatabasePersistence.COLUMN_GROUP, "test");
        contentValues.put(DatabasePersistence.COLUMN_LOG, logSerializer.serializeLog(oldLog));
        databaseManager.put(contentValues, DatabasePersistence.COLUMN_PRIORITY);
    } finally {
        databaseManager.close();
    }
    /* Upgrade. */
    DatabasePersistence persistence = new DatabasePersistence(sContext);
    persistence.setLogSerializer(logSerializer);
    /* Prepare a common schema log. */
    MockCommonSchemaLog commonSchemaLog = new MockCommonSchemaLog();
    commonSchemaLog.setName("test");
    commonSchemaLog.setIKey("o:test");
    commonSchemaLog.setTimestamp(new Date());
    commonSchemaLog.setVer("3.0");
    commonSchemaLog.addTransmissionTarget("test-guid");
    /* Check upgrade. */
    try {
        /* Verify old data cleared. */
        assertEquals(0, persistence.countLogs("test"));
        /* Put new data. */
        persistence.putLog(commonSchemaLog, "test/one", NORMAL);
    } finally {
        persistence.close();
    }
    /* Get new data after restart. */
    persistence = new DatabasePersistence(sContext);
    persistence.setLogSerializer(logSerializer);
    try {
        /* Get new data. */
        assertEquals(1, persistence.countLogs("test/one"));
        List<Log> outputLogs = new ArrayList<>();
        persistence.getLogs("test/one", Collections.<String>emptyList(), 1, outputLogs);
        assertEquals(1, outputLogs.size());
        assertEquals(commonSchemaLog, outputLogs.get(0));
        /* Verify target token is encrypted. */
        ContentValues values = getContentValues(persistence, "test/one");
        String token = values.getAsString(DatabasePersistence.COLUMN_TARGET_TOKEN);
        assertNotNull(token);
        assertNotEquals("test-guid", token);
        assertEquals("test-guid", CryptoUtils.getInstance(sContext).decrypt(token).getDecryptedData());
        /* Verify target key stored as well. */
        String targetKey = values.getAsString(DatabasePersistence.COLUMN_TARGET_KEY);
        assertEquals(commonSchemaLog.getIKey(), "o:" + targetKey);
        /* Verify priority stored too. */
        assertEquals((Integer) NORMAL, values.getAsInteger(DatabasePersistence.COLUMN_PRIORITY));
    } finally {
        persistence.close();
    }
}
Also used : ContentValues(android.content.ContentValues) DatabaseManager(com.microsoft.appcenter.utils.storage.DatabaseManager) CommonSchemaLog(com.microsoft.appcenter.ingestion.models.one.CommonSchemaLog) MockCommonSchemaLog(com.microsoft.appcenter.ingestion.models.one.MockCommonSchemaLog) Log(com.microsoft.appcenter.ingestion.models.Log) MockLog(com.microsoft.appcenter.ingestion.models.json.MockLog) MockCommonSchemaLogFactory(com.microsoft.appcenter.ingestion.models.one.MockCommonSchemaLogFactory) 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) TestUtils.generateString(com.microsoft.appcenter.test.TestUtils.generateString) Date(java.util.Date) MockLogFactory(com.microsoft.appcenter.ingestion.models.json.MockLogFactory) MockCommonSchemaLog(com.microsoft.appcenter.ingestion.models.one.MockCommonSchemaLog) DefaultLogSerializer(com.microsoft.appcenter.ingestion.models.json.DefaultLogSerializer) MediumTest(androidx.test.filters.MediumTest) Test(org.junit.Test)

Example 2 with DatabaseManager

use of com.microsoft.appcenter.utils.storage.DatabaseManager in project mobile-center-sdk-android by Microsoft.

the class AbstractAppCenterTest method setUp.

@Before
public void setUp() throws Exception {
    AppCenter.unsetInstance();
    DummyService.sharedInstance = null;
    AnotherDummyService.sharedInstance = null;
    whenNew(DefaultChannel.class).withAnyArguments().thenReturn(mChannel);
    whenNew(StartServiceLog.class).withAnyArguments().thenReturn(mStartServiceLog);
    when(mApplication.getApplicationContext()).thenReturn(mApplication);
    mApplicationInfo = new ApplicationInfo();
    mApplicationInfo.flags = ApplicationInfo.FLAG_DEBUGGABLE;
    when(mApplication.getApplicationInfo()).thenReturn(mApplicationInfo);
    mockStatic(Constants.class);
    mockStatic(AppCenterLog.class);
    mockStatic(FileManager.class);
    mockStatic(SharedPreferencesManager.class);
    mockStatic(IdHelper.class);
    mockStatic(Thread.class);
    mockStatic(ShutdownHelper.class);
    mockStatic(DeviceInfoHelper.class);
    mockStatic(InstrumentationRegistryHelper.class);
    mockStatic(NetworkStateHelper.class);
    mockStatic(JSONUtils.class);
    /* Mock handlers. */
    Handler handler = mock(Handler.class);
    whenNew(Handler.class).withAnyArguments().thenReturn(handler);
    doAnswer(new Answer<Void>() {

        @Override
        public Void answer(InvocationOnMock invocation) {
            ((Runnable) invocation.getArguments()[0]).run();
            return null;
        }
    }).when(handler).post(any(Runnable.class));
    HandlerThread handlerThread = mock(HandlerThread.class);
    whenNew(HandlerThread.class).withAnyArguments().thenReturn(handlerThread);
    when(handlerThread.getLooper()).thenReturn(mock(Looper.class));
    addArgumentToRegistry(null);
    /* First call to com.microsoft.appcenter.AppCenter.isEnabled shall return true, initial state. */
    when(SharedPreferencesManager.getBoolean(anyString(), eq(true))).thenReturn(true);
    /* Then simulate further changes to state. */
    PowerMockito.doAnswer(new Answer<Void>() {

        @Override
        public Void answer(InvocationOnMock invocation) {
            /* Whenever the new state is persisted, make further calls return the new state. */
            String key = (String) invocation.getArguments()[0];
            boolean enabled = (Boolean) invocation.getArguments()[1];
            when(SharedPreferencesManager.getBoolean(key, true)).thenReturn(enabled);
            return null;
        }
    }).when(SharedPreferencesManager.class);
    SharedPreferencesManager.putBoolean(anyString(), anyBoolean());
    /* Mock empty database. */
    DatabaseManager databaseManager = mock(DatabaseManager.class);
    whenNew(DatabaseManager.class).withAnyArguments().thenReturn(databaseManager);
    when(databaseManager.getCursor(any(SQLiteQueryBuilder.class), any(String[].class), any(String[].class), anyString())).thenReturn(mock(Cursor.class));
    /* Mock network state helper. */
    when(NetworkStateHelper.getSharedInstance(any(Context.class))).thenReturn(mNetworkStateHelper);
}
Also used : Context(android.content.Context) DatabaseManager(com.microsoft.appcenter.utils.storage.DatabaseManager) ApplicationInfo(android.content.pm.ApplicationInfo) Handler(android.os.Handler) Matchers.anyString(org.mockito.Matchers.anyString) Cursor(android.database.Cursor) Looper(android.os.Looper) Answer(org.mockito.stubbing.Answer) PowerMockito.doAnswer(org.powermock.api.mockito.PowerMockito.doAnswer) HandlerThread(android.os.HandlerThread) InvocationOnMock(org.mockito.invocation.InvocationOnMock) Matchers.anyBoolean(org.mockito.Matchers.anyBoolean) SQLiteQueryBuilder(android.database.sqlite.SQLiteQueryBuilder) Before(org.junit.Before)

Example 3 with DatabaseManager

use of com.microsoft.appcenter.utils.storage.DatabaseManager in project mobile-center-sdk-android by Microsoft.

the class DatabasePersistenceTest method clearPendingLogState.

@Test
public void clearPendingLogState() throws Exception {
    /* groupCount should be <= 9. */
    final int groupCount = 4;
    final int logCount = 10;
    /* Mock logs. */
    List<List<ContentValues>> list = new ArrayList<>();
    for (int i = 0; i < groupCount; i++) {
        List<ContentValues> iterator = new ArrayList<>();
        for (long l = 1; l <= logCount; l++) {
            ContentValues values = mock(ContentValues.class);
            when(values.getAsLong(DatabaseManager.PRIMARY_KEY)).thenReturn(l + i * logCount);
            when(values.getAsString(DatabasePersistence.COLUMN_LOG)).thenReturn("{}");
            iterator.add(values);
        }
        list.add(iterator);
    }
    /* Mock instances. */
    DatabaseManager mockDatabaseManager = mock(DatabaseManager.class);
    whenNew(DatabaseManager.class).withAnyArguments().thenReturn(mockDatabaseManager);
    when(mockDatabaseManager.nextValues(any(Cursor.class))).thenCallRealMethod();
    for (int i = 0; i < groupCount; i++) {
        MockCursor mockCursor = new MockCursor(list.get(i));
        mockCursor.mockBuildValues(mockDatabaseManager);
        when(mockDatabaseManager.getCursor(any(SQLiteQueryBuilder.class), any(String[].class), eq(new String[] { String.valueOf(i) }), anyString())).thenReturn(mockCursor);
    }
    LogSerializer mockLogSerializer = mock(LogSerializer.class);
    when(mockLogSerializer.deserializeLog(anyString(), anyString())).thenReturn(mock(Log.class));
    /* Instantiate Database Persistence. */
    DatabasePersistence persistence = new DatabasePersistence(mock(Context.class));
    persistence.setLogSerializer(mockLogSerializer);
    /* Get logs. */
    for (int i = 0; i < groupCount; i++) {
        persistence.getLogs(String.valueOf(i), Collections.<String>emptyList(), logCount, new ArrayList<Log>());
    }
    /* Verify there are 4 pending groups. */
    assertEquals(groupCount, persistence.mPendingDbIdentifiersGroups.size());
    assertEquals(groupCount * logCount, persistence.mPendingDbIdentifiers.size());
    /* Clear all pending groups and verify. */
    persistence.clearPendingLogState();
    assertEquals(0, persistence.mPendingDbIdentifiersGroups.size());
    assertEquals(0, persistence.mPendingDbIdentifiers.size());
}
Also used : ContentValues(android.content.ContentValues) Context(android.content.Context) DatabaseManager(com.microsoft.appcenter.utils.storage.DatabaseManager) AppCenterLog(com.microsoft.appcenter.utils.AppCenterLog) Log(com.microsoft.appcenter.ingestion.models.Log) ArrayList(java.util.ArrayList) Matchers.anyString(org.mockito.Matchers.anyString) LogSerializer(com.microsoft.appcenter.ingestion.models.json.LogSerializer) Cursor(android.database.Cursor) ArrayList(java.util.ArrayList) List(java.util.List) SQLiteQueryBuilder(android.database.sqlite.SQLiteQueryBuilder) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 4 with DatabaseManager

use of com.microsoft.appcenter.utils.storage.DatabaseManager in project mobile-center-sdk-android by Microsoft.

the class DatabasePersistenceTest method getLogsWithGetCorruptedIdsException.

@Test
public void getLogsWithGetCorruptedIdsException() throws Exception {
    /* Mock instances. */
    mockStatic(AppCenterLog.class);
    DatabaseManager databaseManager = mock(DatabaseManager.class);
    whenNew(DatabaseManager.class).withAnyArguments().thenReturn(databaseManager);
    when(databaseManager.nextValues(any(Cursor.class))).thenCallRealMethod();
    /* Make corrupted log. */
    List<ContentValues> fieldValues = new ArrayList<>();
    {
        /* Empty record, "corrupted", cause identifier is null (and no other field either). */
        ContentValues contentValues = mock(ContentValues.class);
        when(contentValues.getAsLong(DatabaseManager.PRIMARY_KEY)).thenReturn(null);
        fieldValues.add(contentValues);
    }
    /* Mock log sequence retrieved from cursor. */
    MockCursor mockCursor = new MockCursor(fieldValues);
    mockCursor.mockBuildValues(databaseManager);
    when(databaseManager.getCursor(any(SQLiteQueryBuilder.class), isNull(String[].class), any(String[].class), anyString())).thenReturn(mockCursor);
    /* Mock second cursor with identifiers only. */
    Cursor failingCursor = mock(Cursor.class);
    when(failingCursor.moveToNext()).thenThrow(new SQLiteDiskIOException());
    when(databaseManager.getCursor(any(SQLiteQueryBuilder.class), isNotNull(String[].class), any(String[].class), anyString())).thenReturn(failingCursor);
    /* Get logs and verify we get only non corrupted logs. */
    DatabasePersistence persistence = new DatabasePersistence(mock(Context.class));
    ArrayList<Log> outLogs = new ArrayList<>();
    persistence.getLogs("mock", Collections.<String>emptyList(), 50, outLogs);
    assertEquals(0, outLogs.size());
    /* There is an error log. */
    verifyStatic();
    AppCenterLog.error(eq(AppCenter.LOG_TAG), anyString(), any(RuntimeException.class));
}
Also used : ContentValues(android.content.ContentValues) Context(android.content.Context) DatabaseManager(com.microsoft.appcenter.utils.storage.DatabaseManager) AppCenterLog(com.microsoft.appcenter.utils.AppCenterLog) Log(com.microsoft.appcenter.ingestion.models.Log) ArrayList(java.util.ArrayList) Cursor(android.database.Cursor) SQLiteDiskIOException(android.database.sqlite.SQLiteDiskIOException) SQLiteQueryBuilder(android.database.sqlite.SQLiteQueryBuilder) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 5 with DatabaseManager

use of com.microsoft.appcenter.utils.storage.DatabaseManager in project mobile-center-sdk-android by Microsoft.

the class DatabasePersistenceTest method getLogsWithGetCursorException.

@Test
public void getLogsWithGetCursorException() throws Exception {
    /* Mock instances. */
    mockStatic(AppCenterLog.class);
    DatabaseManager databaseManager = mock(DatabaseManager.class);
    whenNew(DatabaseManager.class).withAnyArguments().thenReturn(databaseManager);
    when(databaseManager.nextValues(any(Cursor.class))).thenCallRealMethod();
    when(databaseManager.getCursor(any(SQLiteQueryBuilder.class), any(String[].class), any(String[].class), anyString())).thenThrow(new RuntimeException());
    DatabasePersistence persistence = new DatabasePersistence(mock(Context.class), 1, DatabasePersistence.SCHEMA);
    /* Try to get logs. */
    ArrayList<Log> outLogs = new ArrayList<>();
    persistence.getLogs("mock", Collections.<String>emptyList(), 50, outLogs);
    assertEquals(0, outLogs.size());
    /* There is an error log. */
    verifyStatic();
    AppCenterLog.error(eq(AppCenter.LOG_TAG), anyString(), any(RuntimeException.class));
}
Also used : Context(android.content.Context) DatabaseManager(com.microsoft.appcenter.utils.storage.DatabaseManager) AppCenterLog(com.microsoft.appcenter.utils.AppCenterLog) Log(com.microsoft.appcenter.ingestion.models.Log) ArrayList(java.util.ArrayList) Cursor(android.database.Cursor) SQLiteQueryBuilder(android.database.sqlite.SQLiteQueryBuilder) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Aggregations

DatabaseManager (com.microsoft.appcenter.utils.storage.DatabaseManager)11 Context (android.content.Context)10 Test (org.junit.Test)10 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)9 Cursor (android.database.Cursor)8 SQLiteQueryBuilder (android.database.sqlite.SQLiteQueryBuilder)8 Log (com.microsoft.appcenter.ingestion.models.Log)8 AppCenterLog (com.microsoft.appcenter.utils.AppCenterLog)7 ArrayList (java.util.ArrayList)6 LogSerializer (com.microsoft.appcenter.ingestion.models.json.LogSerializer)5 ContentValues (android.content.ContentValues)4 Matchers.anyString (org.mockito.Matchers.anyString)3 InvocationOnMock (org.mockito.invocation.InvocationOnMock)2 ApplicationInfo (android.content.pm.ApplicationInfo)1 SQLiteDiskIOException (android.database.sqlite.SQLiteDiskIOException)1 Handler (android.os.Handler)1 HandlerThread (android.os.HandlerThread)1 Looper (android.os.Looper)1 MediumTest (androidx.test.filters.MediumTest)1 DefaultLogSerializer (com.microsoft.appcenter.ingestion.models.json.DefaultLogSerializer)1