Fix conflicts

This commit is contained in:
neslihanturan 2018-03-06 19:47:18 +03:00
commit 5b88111289
324 changed files with 9238 additions and 2883 deletions

View file

@ -1,5 +1,6 @@
package fr.free.nrw.commons;
import android.content.Context;
import android.content.SharedPreferences;
import android.support.v4.util.LruCache;
@ -54,57 +55,46 @@ public class TestCommonsApplication extends CommonsApplication {
@Override
public void onCreate() {
MockitoAnnotations.initMocks(this);
super.onCreate();
}
@Override
protected RefWatcher setupLeakCanary() {
// No leakcanary in unit tests.
return RefWatcher.DISABLED;
}
@Override
public CommonsApplicationComponent injector() {
if (mockApplicationComponent == null) {
mockApplicationComponent = DaggerCommonsApplicationComponent.builder()
.appModule(new CommonsApplicationModule(this) {
@Override
public AccountUtil providesAccountUtil() {
public AccountUtil providesAccountUtil(Context context) {
return accountUtil;
}
@Override
public SharedPreferences providesApplicationSharedPreferences() {
public SharedPreferences providesApplicationSharedPreferences(Context context) {
return appSharedPreferences;
}
@Override
public SharedPreferences providesDefaultSharedPreferences() {
public SharedPreferences providesDefaultSharedPreferences(Context context) {
return defaultSharedPreferences;
}
@Override
public SharedPreferences providesOtherSharedPreferences() {
public SharedPreferences providesOtherSharedPreferences(Context context) {
return otherSharedPreferences;
}
@Override
public UploadController providesUploadController(SessionManager sessionManager, SharedPreferences sharedPreferences) {
public UploadController providesUploadController(Context context, SessionManager sessionManager, SharedPreferences sharedPreferences) {
return uploadController;
}
@Override
public SessionManager providesSessionManager(MediaWikiApi mediaWikiApi) {
public SessionManager providesSessionManager(Context context, MediaWikiApi mediaWikiApi, SharedPreferences sharedPreferences) {
return sessionManager;
}
@Override
public MediaWikiApi provideMediaWikiApi() {
public MediaWikiApi provideMediaWikiApi(Context context, SharedPreferences sharedPreferences) {
return mediaWikiApi;
}
@Override
public LocationServiceManager provideLocationServiceManager() {
public LocationServiceManager provideLocationServiceManager(Context context) {
return locationServiceManager;
}
@ -114,7 +104,7 @@ public class TestCommonsApplication extends CommonsApplication {
}
@Override
public DBOpenHelper provideDBOpenHelper() {
public DBOpenHelper provideDBOpenHelper(Context context) {
return dbOpenHelper;
}
@ -129,7 +119,13 @@ public class TestCommonsApplication extends CommonsApplication {
}
}).build();
}
return mockApplicationComponent;
super.onCreate();
}
@Override
protected RefWatcher setupLeakCanary() {
// No leakcanary in unit tests.
return RefWatcher.DISABLED;
}
public AccountUtil getAccountUtil() {

View file

@ -0,0 +1,294 @@
package fr.free.nrw.commons.category;
import android.content.ContentProviderClient;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.RemoteException;
import android.support.annotation.NonNull;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.InOrder;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import fr.free.nrw.commons.BuildConfig;
import fr.free.nrw.commons.TestCommonsApplication;
import fr.free.nrw.commons.category.CategoryDao.Table;
import static fr.free.nrw.commons.category.CategoryContentProvider.BASE_URI;
import static fr.free.nrw.commons.category.CategoryContentProvider.uriForId;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertNull;
import static junit.framework.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Matchers.isA;
import static org.mockito.Matchers.isNull;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class, sdk = 21, application = TestCommonsApplication.class)
public class CategoryDaoTest {
@Mock
private ContentProviderClient client;
@Mock
private SQLiteDatabase database;
@Captor
private ArgumentCaptor<ContentValues> captor;
@Captor
private ArgumentCaptor<String[]> queryCaptor;
private CategoryDao testObject;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
testObject = new CategoryDao(() -> client);
}
@Test
public void createTable() {
Table.onCreate(database);
verify(database).execSQL(Table.CREATE_TABLE_STATEMENT);
}
@Test
public void deleteTable() {
Table.onDelete(database);
InOrder inOrder = Mockito.inOrder(database);
inOrder.verify(database).execSQL(Table.DROP_TABLE_STATEMENT);
inOrder.verify(database).execSQL(Table.CREATE_TABLE_STATEMENT);
}
@Test
public void migrateTableVersionFrom_v1_to_v2() {
Table.onUpdate(database, 1, 2);
// Table didnt exist before v5
verifyZeroInteractions(database);
}
@Test
public void migrateTableVersionFrom_v2_to_v3() {
Table.onUpdate(database, 2, 3);
// Table didnt exist before v5
verifyZeroInteractions(database);
}
@Test
public void migrateTableVersionFrom_v3_to_v4() {
Table.onUpdate(database, 3, 4);
// Table didnt exist before v5
verifyZeroInteractions(database);
}
@Test
public void migrateTableVersionFrom_v4_to_v5() {
Table.onUpdate(database, 4, 5);
verify(database).execSQL(Table.CREATE_TABLE_STATEMENT);
}
@Test
public void migrateTableVersionFrom_v5_to_v6() {
Table.onUpdate(database, 5, 6);
// Table didnt change in version 6
verifyZeroInteractions(database);
}
@Test
public void createFromCursor() {
MatrixCursor cursor = createCursor(1);
cursor.moveToFirst();
Category category = testObject.fromCursor(cursor);
assertEquals(uriForId(1), category.getContentUri());
assertEquals("foo", category.getName());
assertEquals(123, category.getLastUsed().getTime());
assertEquals(2, category.getTimesUsed());
}
@Test
public void saveExistingCategory() throws Exception {
MatrixCursor cursor = createCursor(1);
cursor.moveToFirst();
Category category = testObject.fromCursor(cursor);
testObject.save(category);
verify(client).update(eq(category.getContentUri()), captor.capture(), isNull(String.class), isNull(String[].class));
ContentValues cv = captor.getValue();
assertEquals(3, cv.size());
assertEquals(category.getName(), cv.getAsString(Table.COLUMN_NAME));
assertEquals(category.getLastUsed().getTime(), cv.getAsLong(Table.COLUMN_LAST_USED).longValue());
assertEquals(category.getTimesUsed(), cv.getAsInteger(Table.COLUMN_TIMES_USED).intValue());
}
@Test
public void saveNewCategory() throws Exception {
Uri contentUri = CategoryContentProvider.uriForId(111);
when(client.insert(isA(Uri.class), isA(ContentValues.class))).thenReturn(contentUri);
Category category = new Category(null, "foo", new Date(234L), 1);
testObject.save(category);
verify(client).insert(eq(BASE_URI), captor.capture());
ContentValues cv = captor.getValue();
assertEquals(3, cv.size());
assertEquals(category.getName(), cv.getAsString(Table.COLUMN_NAME));
assertEquals(category.getLastUsed().getTime(), cv.getAsLong(Table.COLUMN_LAST_USED).longValue());
assertEquals(category.getTimesUsed(), cv.getAsInteger(Table.COLUMN_TIMES_USED).intValue());
assertEquals(contentUri, category.getContentUri());
}
@Test(expected = RuntimeException.class)
public void testSaveTranslatesRemoteExceptions() throws Exception {
when(client.insert(isA(Uri.class), isA(ContentValues.class))).thenThrow(new RemoteException(""));
testObject.save(new Category());
}
@Test
public void whenTheresNoDataFindReturnsNull_nullCursor() throws Exception {
when(client.query(any(), any(), anyString(), any(), anyString())).thenReturn(null);
assertNull(testObject.find("foo"));
}
@Test
public void whenTheresNoDataFindReturnsNull_emptyCursor() throws Exception {
when(client.query(any(), any(), anyString(), any(), anyString())).thenReturn(createCursor(0));
assertNull(testObject.find("foo"));
}
@Test
public void cursorsAreClosedAfterUse() throws Exception {
Cursor mockCursor = mock(Cursor.class);
when(client.query(any(), any(), anyString(), any(), anyString())).thenReturn(mockCursor);
when(mockCursor.moveToFirst()).thenReturn(false);
testObject.find("foo");
verify(mockCursor).close();
}
@Test
public void findCategory() throws Exception {
when(client.query(any(), any(), anyString(), any(), anyString())).thenReturn(createCursor(1));
Category category = testObject.find("foo");
assertEquals(uriForId(1), category.getContentUri());
assertEquals("foo", category.getName());
assertEquals(123, category.getLastUsed().getTime());
assertEquals(2, category.getTimesUsed());
verify(client).query(
eq(BASE_URI),
eq(Table.ALL_FIELDS),
eq(Table.COLUMN_NAME + "=?"),
queryCaptor.capture(),
isNull(String.class)
);
assertEquals("foo", queryCaptor.getValue()[0]);
}
@Test(expected = RuntimeException.class)
public void findCategoryTranslatesExceptions() throws Exception {
when(client.query(any(), any(), anyString(), any(), anyString())).thenThrow(new RemoteException(""));
testObject.find("foo");
}
@Test(expected = RuntimeException.class)
public void recentCategoriesTranslatesExceptions() throws Exception {
when(client.query(any(), any(), anyString(), any(), anyString())).thenThrow(new RemoteException(""));
testObject.recentCategories(1);
}
@Test
public void recentCategoriesReturnsEmptyList_nullCursor() throws Exception {
when(client.query(any(), any(), anyString(), any(), anyString())).thenReturn(null);
assertTrue(testObject.recentCategories(1).isEmpty());
}
@Test
public void recentCategoriesReturnsEmptyList_emptyCursor() throws Exception {
when(client.query(any(), any(), anyString(), any(), anyString())).thenReturn(createCursor(0));
assertTrue(testObject.recentCategories(1).isEmpty());
}
@Test
public void cursorsAreClosedAfterRecentCategoriesQuery() throws Exception {
Cursor mockCursor = mock(Cursor.class);
when(client.query(any(), any(), anyString(), any(), anyString())).thenReturn(mockCursor);
when(mockCursor.moveToFirst()).thenReturn(false);
testObject.recentCategories(1);
verify(mockCursor).close();
}
@Test
public void recentCategoriesReturnsLessThanLimit() throws Exception {
when(client.query(any(), any(), anyString(), any(), anyString())).thenReturn(createCursor(1));
List<String> result = testObject.recentCategories(10);
assertEquals(1, result.size());
assertEquals("foo", result.get(0));
verify(client).query(
eq(BASE_URI),
eq(Table.ALL_FIELDS),
isNull(String.class),
queryCaptor.capture(),
eq(Table.COLUMN_LAST_USED + " DESC")
);
assertEquals(0, queryCaptor.getValue().length);
}
@Test
public void recentCategoriesHomorsLimit() throws Exception {
when(client.query(any(), any(), anyString(), any(), anyString())).thenReturn(createCursor(10));
List<String> result = testObject.recentCategories(5);
assertEquals(5, result.size());
}
@NonNull
private MatrixCursor createCursor(int rowCount) {
MatrixCursor cursor = new MatrixCursor(new String[]{
Table.COLUMN_ID,
Table.COLUMN_NAME,
Table.COLUMN_LAST_USED,
Table.COLUMN_TIMES_USED
}, rowCount);
for (int i = 0; i < rowCount; i++) {
cursor.addRow(Arrays.asList("1", "foo", "123", "2"));
}
return cursor;
}
}

View file

@ -0,0 +1,370 @@
package fr.free.nrw.commons.contributions;
import android.content.ContentProviderClient;
import android.content.ContentValues;
import android.database.MatrixCursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.RemoteException;
import android.support.annotation.NonNull;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.InOrder;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import java.util.Arrays;
import java.util.Date;
import fr.free.nrw.commons.BuildConfig;
import fr.free.nrw.commons.TestCommonsApplication;
import fr.free.nrw.commons.Utils;
import static fr.free.nrw.commons.contributions.Contribution.SOURCE_CAMERA;
import static fr.free.nrw.commons.contributions.Contribution.SOURCE_GALLERY;
import static fr.free.nrw.commons.contributions.Contribution.STATE_COMPLETED;
import static fr.free.nrw.commons.contributions.Contribution.STATE_QUEUED;
import static fr.free.nrw.commons.contributions.ContributionDao.Table;
import static fr.free.nrw.commons.contributions.ContributionsContentProvider.BASE_URI;
import static fr.free.nrw.commons.contributions.ContributionsContentProvider.uriForId;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Matchers.isA;
import static org.mockito.Matchers.isNull;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class, sdk = 21, application = TestCommonsApplication.class)
public class ContributionDaoTest {
private static final String LOCAL_URI = "http://example.com/";
@Mock
private ContentProviderClient client;
@Mock
private SQLiteDatabase database;
@Captor
private ArgumentCaptor<ContentValues> captor;
private Uri contentUri;
private ContributionDao testObject;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
contentUri = uriForId(111);
testObject = new ContributionDao(() -> client);
}
@Test
public void createTable() {
Table.onCreate(database);
verify(database).execSQL(Table.CREATE_TABLE_STATEMENT);
}
@Test
public void deleteTable() {
Table.onDelete(database);
InOrder inOrder = Mockito.inOrder(database);
inOrder.verify(database).execSQL(Table.DROP_TABLE_STATEMENT);
inOrder.verify(database).execSQL(Table.CREATE_TABLE_STATEMENT);
}
@Test
public void upgradeDatabase_v1_to_v2() {
Table.onUpdate(database, 1, 2);
InOrder inOrder = Mockito.inOrder(database);
inOrder.verify(database).execSQL(Table.ADD_DESCRIPTION_FIELD);
inOrder.verify(database).execSQL(Table.ADD_CREATOR_FIELD);
}
@Test
public void upgradeDatabase_v2_to_v3() {
Table.onUpdate(database, 2, 3);
InOrder inOrder = Mockito.inOrder(database);
inOrder.verify(database).execSQL(Table.ADD_MULTIPLE_FIELD);
inOrder.verify(database).execSQL(Table.SET_DEFAULT_MULTIPLE);
}
@Test
public void upgradeDatabase_v3_to_v4() {
Table.onUpdate(database, 3, 4);
// No changes
verifyZeroInteractions(database);
}
@Test
public void upgradeDatabase_v4_to_v5() {
Table.onUpdate(database, 4, 5);
// No changes
verifyZeroInteractions(database);
}
@Test
public void upgradeDatabase_v5_to_v6() {
Table.onUpdate(database, 5, 6);
InOrder inOrder = Mockito.inOrder(database);
inOrder.verify(database).execSQL(Table.ADD_WIDTH_FIELD);
inOrder.verify(database).execSQL(Table.SET_DEFAULT_WIDTH);
inOrder.verify(database).execSQL(Table.ADD_HEIGHT_FIELD);
inOrder.verify(database).execSQL(Table.SET_DEFAULT_HEIGHT);
inOrder.verify(database).execSQL(Table.ADD_LICENSE_FIELD);
inOrder.verify(database).execSQL(Table.SET_DEFAULT_LICENSE);
}
@Test
public void saveNewContribution_nonNullFields() throws Exception {
when(client.insert(isA(Uri.class), isA(ContentValues.class))).thenReturn(contentUri);
Contribution contribution = createContribution(true, null, null, null, null);
testObject.save(contribution);
assertEquals(contentUri, contribution.getContentUri());
verify(client).insert(eq(BASE_URI), captor.capture());
ContentValues cv = captor.getValue();
// Long fields
assertEquals(222L, cv.getAsLong(Table.COLUMN_LENGTH).longValue());
assertEquals(321L, cv.getAsLong(Table.COLUMN_TIMESTAMP).longValue());
assertEquals(333L, cv.getAsLong(Table.COLUMN_TRANSFERRED).longValue());
// Integer fields
assertEquals(STATE_COMPLETED, cv.getAsInteger(Table.COLUMN_STATE).intValue());
assertEquals(640, cv.getAsInteger(Table.COLUMN_WIDTH).intValue());
assertEquals(480, cv.getAsInteger(Table.COLUMN_HEIGHT).intValue());
// String fields
assertEquals(SOURCE_CAMERA, cv.getAsString(Table.COLUMN_SOURCE));
assertEquals("desc", cv.getAsString(Table.COLUMN_DESCRIPTION));
assertEquals("create", cv.getAsString(Table.COLUMN_CREATOR));
assertEquals("007", cv.getAsString(Table.COLUMN_LICENSE));
}
@Test
public void saveNewContribution_nullableFieldsAreNull() throws Exception {
when(client.insert(isA(Uri.class), isA(ContentValues.class))).thenReturn(contentUri);
Contribution contribution = createContribution(true, null, null, null, null);
testObject.save(contribution);
assertEquals(contentUri, contribution.getContentUri());
verify(client).insert(eq(BASE_URI), captor.capture());
ContentValues cv = captor.getValue();
// Nullable fields are absent if null
assertFalse(cv.containsKey(Table.COLUMN_LOCAL_URI));
assertFalse(cv.containsKey(Table.COLUMN_IMAGE_URL));
assertFalse(cv.containsKey(Table.COLUMN_UPLOADED));
}
@Test
public void saveNewContribution_nullableImageUrlUsesFileAsBackup() throws Exception {
when(client.insert(isA(Uri.class), isA(ContentValues.class))).thenReturn(contentUri);
Contribution contribution = createContribution(true, null, null, null, "file");
testObject.save(contribution);
assertEquals(contentUri, contribution.getContentUri());
verify(client).insert(eq(BASE_URI), captor.capture());
ContentValues cv = captor.getValue();
// Nullable fields are absent if null
assertFalse(cv.containsKey(Table.COLUMN_LOCAL_URI));
assertFalse(cv.containsKey(Table.COLUMN_UPLOADED));
assertEquals(Utils.makeThumbBaseUrl("file"), cv.getAsString(Table.COLUMN_IMAGE_URL));
}
@Test
public void saveNewContribution_nullableFieldsAreNonNull() throws Exception {
when(client.insert(isA(Uri.class), isA(ContentValues.class))).thenReturn(contentUri);
Contribution contribution = createContribution(true, Uri.parse(LOCAL_URI),
"image", new Date(456L), null);
testObject.save(contribution);
assertEquals(contentUri, contribution.getContentUri());
verify(client).insert(eq(BASE_URI), captor.capture());
ContentValues cv = captor.getValue();
assertEquals(LOCAL_URI, cv.getAsString(Table.COLUMN_LOCAL_URI));
assertEquals("image", cv.getAsString(Table.COLUMN_IMAGE_URL));
assertEquals(456L, cv.getAsLong(Table.COLUMN_UPLOADED).longValue());
}
@Test
public void saveNewContribution_booleanEncodesTrue() throws Exception {
when(client.insert(isA(Uri.class), isA(ContentValues.class))).thenReturn(contentUri);
Contribution contribution = createContribution(true, null, null, null, null);
testObject.save(contribution);
assertEquals(contentUri, contribution.getContentUri());
verify(client).insert(eq(BASE_URI), captor.capture());
ContentValues cv = captor.getValue();
// Boolean true --> 1 for ths encoding scheme
assertEquals("Boolean true should be encoded as 1", 1,
cv.getAsInteger(Table.COLUMN_MULTIPLE).intValue());
}
@Test
public void saveNewContribution_booleanEncodesFalse() throws Exception {
when(client.insert(isA(Uri.class), isA(ContentValues.class))).thenReturn(contentUri);
Contribution contribution = createContribution(false, null, null, null, null);
testObject.save(contribution);
assertEquals(contentUri, contribution.getContentUri());
verify(client).insert(eq(BASE_URI), captor.capture());
ContentValues cv = captor.getValue();
// Boolean true --> 1 for ths encoding scheme
assertEquals("Boolean false should be encoded as 0", 0,
cv.getAsInteger(Table.COLUMN_MULTIPLE).intValue());
}
@Test
public void saveExistingContribution() throws Exception {
Contribution contribution = createContribution(false, null, null, null, null);
contribution.setContentUri(contentUri);
testObject.save(contribution);
verify(client).update(eq(contentUri), isA(ContentValues.class), isNull(String.class), isNull(String[].class));
}
@Test(expected = RuntimeException.class)
public void saveTranslatesExceptions() throws Exception {
when(client.insert(isA(Uri.class), isA(ContentValues.class))).thenThrow(new RemoteException(""));
testObject.save(createContribution(false, null, null, null, null));
}
@Test(expected = RuntimeException.class)
public void deleteTranslatesExceptions() throws Exception {
when(client.delete(isA(Uri.class), any(), any())).thenThrow(new RemoteException(""));
Contribution contribution = createContribution(false, null, null, null, null);
contribution.setContentUri(contentUri);
testObject.delete(contribution);
}
@Test(expected = RuntimeException.class)
public void exceptionThrownWhenAttemptingToDeleteUnsavedContribution() {
testObject.delete(createContribution(false, null, null, null, null));
}
@Test
public void deleteExistingContribution() throws Exception {
Contribution contribution = createContribution(false, null, null, null, null);
contribution.setContentUri(contentUri);
testObject.delete(contribution);
verify(client).delete(eq(contentUri), isNull(String.class), isNull(String[].class));
}
@Test
public void createFromCursor() {
long created = 321L;
long uploaded = 456L;
MatrixCursor mc = createCursor(created, uploaded, false, LOCAL_URI);
Contribution c = testObject.fromCursor(mc);
assertEquals(uriForId(111), c.getContentUri());
assertEquals("file", c.getFilename());
assertEquals(LOCAL_URI, c.getLocalUri().toString());
assertEquals("image", c.getImageUrl());
assertEquals(created, c.getTimestamp().getTime());
assertEquals(created, c.getDateCreated().getTime());
assertEquals(STATE_QUEUED, c.getState());
assertEquals(222L, c.getDataLength());
assertEquals(uploaded, c.getDateUploaded().getTime());
assertEquals(88L, c.getTransferred());
assertEquals(SOURCE_GALLERY, c.getSource());
assertEquals("desc", c.getDescription());
assertEquals("create", c.getCreator());
assertEquals(640, c.getWidth());
assertEquals(480, c.getHeight());
assertEquals("007", c.getLicense());
}
@Test
public void createFromCursor_nullableTimestamps() {
MatrixCursor mc = createCursor(0L, 0L, false, LOCAL_URI);
Contribution c = testObject.fromCursor(mc);
assertNull(c.getTimestamp());
assertNull(c.getDateCreated());
assertNull(c.getDateUploaded());
}
@Test
public void createFromCursor_nullableLocalUri() {
MatrixCursor mc = createCursor(0L, 0L, false, "");
Contribution c = testObject.fromCursor(mc);
assertNull(c.getLocalUri());
assertNull(c.getDateCreated());
assertNull(c.getDateUploaded());
}
@Test
public void createFromCursor_booleanEncoding() {
MatrixCursor mcFalse = createCursor(0L, 0L, false, LOCAL_URI);
assertFalse(testObject.fromCursor(mcFalse).getMultiple());
MatrixCursor mcHammer = createCursor(0L, 0L, true, LOCAL_URI);
assertTrue(testObject.fromCursor(mcHammer).getMultiple());
}
@NonNull
private MatrixCursor createCursor(long created, long uploaded, boolean multiple, String localUri) {
MatrixCursor mc = new MatrixCursor(Table.ALL_FIELDS, 1);
mc.addRow(Arrays.asList("111", "file", localUri, "image",
created, STATE_QUEUED, 222L, uploaded, 88L, SOURCE_GALLERY, "desc",
"create", multiple ? 1 : 0, 640, 480, "007"));
mc.moveToFirst();
return mc;
}
@NonNull
private Contribution createContribution(boolean multiple, Uri localUri,
String imageUrl, Date dateUploaded, String filename) {
Contribution contribution = new Contribution(localUri, imageUrl, filename, "desc", 222L,
new Date(321L), dateUploaded, "create", "edit", "coords");
contribution.setState(STATE_COMPLETED);
contribution.setTransferred(333L);
contribution.setSource(SOURCE_CAMERA);
contribution.setLicense("007");
contribution.setMultiple(multiple);
contribution.setTimestamp(new Date(321L));
contribution.setWidth(640);
contribution.setHeight(480); // VGA should be enough for anyone, right?
return contribution;
}
}

View file

@ -0,0 +1,181 @@
package fr.free.nrw.commons.modifications;
import android.content.ContentProviderClient;
import android.content.ContentValues;
import android.database.MatrixCursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.RemoteException;
import android.support.annotation.NonNull;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.InOrder;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import java.util.Arrays;
import fr.free.nrw.commons.BuildConfig;
import fr.free.nrw.commons.TestCommonsApplication;
import static fr.free.nrw.commons.modifications.ModificationsContentProvider.BASE_URI;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.eq;
import static org.mockito.Matchers.isA;
import static org.mockito.Matchers.isNull;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class, sdk = 21, application = TestCommonsApplication.class)
public class ModifierSequenceDaoTest {
private static final String EXPECTED_MEDIA_URI = "http://example.com/";
@Mock
ContentProviderClient client;
@Mock
SQLiteDatabase database;
@Captor
ArgumentCaptor<ContentValues> contentValuesCaptor;
private ModifierSequenceDao testObject;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
testObject = new ModifierSequenceDao(() -> client);
}
@Test
public void createFromCursorWithEmptyModifiers() {
MatrixCursor cursor = createCursor("");
ModifierSequence seq = testObject.fromCursor(cursor);
assertEquals(EXPECTED_MEDIA_URI, seq.getMediaUri().toString());
assertEquals(BASE_URI.buildUpon().appendPath("1").toString(), seq.getContentUri().toString());
assertTrue(seq.getModifiers().isEmpty());
}
@Test
public void createFromCursorWtihCategoryModifier() {
MatrixCursor cursor = createCursor("{\"name\": \"CategoriesModifier\", \"data\": {}}");
ModifierSequence seq = testObject.fromCursor(cursor);
assertEquals(1, seq.getModifiers().size());
assertTrue(seq.getModifiers().get(0) instanceof CategoryModifier);
}
@Test
public void createFromCursorWithRemoveModifier() {
MatrixCursor cursor = createCursor("{\"name\": \"TemplateRemoverModifier\", \"data\": {}}");
ModifierSequence seq = testObject.fromCursor(cursor);
assertEquals(1, seq.getModifiers().size());
assertTrue(seq.getModifiers().get(0) instanceof TemplateRemoveModifier);
}
@Test
public void deleteSequence() throws Exception {
when(client.delete(isA(Uri.class), isNull(String.class), isNull(String[].class))).thenReturn(1);
ModifierSequence seq = testObject.fromCursor(createCursor(""));
testObject.delete(seq);
verify(client).delete(eq(seq.getContentUri()), isNull(String.class), isNull(String[].class));
}
@Test(expected = RuntimeException.class)
public void deleteTranslatesRemoteExceptions() throws Exception {
when(client.delete(isA(Uri.class), isNull(String.class), isNull(String[].class))).thenThrow(new RemoteException(""));
ModifierSequence seq = testObject.fromCursor(createCursor(""));
testObject.delete(seq);
}
@Test
public void saveExistingSequence() throws Exception {
String modifierJson = "{\"name\":\"CategoriesModifier\",\"data\":{}}";
String expectedData = "{\"modifiers\":[" + modifierJson + "]}";
MatrixCursor cursor = createCursor(modifierJson);
testObject.save(testObject.fromCursor(cursor));
verify(client).update(eq(testObject.fromCursor(cursor).getContentUri()), contentValuesCaptor.capture(), isNull(String.class), isNull(String[].class));
ContentValues cv = contentValuesCaptor.getValue();
assertEquals(2, cv.size());
assertEquals(EXPECTED_MEDIA_URI, cv.get(ModifierSequenceDao.Table.COLUMN_MEDIA_URI));
assertEquals(expectedData, cv.get(ModifierSequenceDao.Table.COLUMN_DATA));
}
@Test
public void saveNewSequence() throws Exception {
Uri expectedContentUri = BASE_URI.buildUpon().appendPath("1").build();
when(client.insert(isA(Uri.class), isA(ContentValues.class))).thenReturn(expectedContentUri);
ModifierSequence seq = new ModifierSequence(Uri.parse(EXPECTED_MEDIA_URI));
testObject.save(seq);
verify(client).insert(eq(ModificationsContentProvider.BASE_URI), contentValuesCaptor.capture());
ContentValues cv = contentValuesCaptor.getValue();
assertEquals(2, cv.size());
assertEquals(EXPECTED_MEDIA_URI, cv.get(ModifierSequenceDao.Table.COLUMN_MEDIA_URI));
assertEquals("{\"modifiers\":[]}", cv.get(ModifierSequenceDao.Table.COLUMN_DATA));
assertEquals(expectedContentUri.toString(), seq.getContentUri().toString());
}
@Test(expected = RuntimeException.class)
public void saveTranslatesRemoteExceptions() throws Exception {
when(client.insert(isA(Uri.class), isA(ContentValues.class))).thenThrow(new RemoteException(""));
testObject.save(new ModifierSequence(Uri.parse(EXPECTED_MEDIA_URI)));
}
@Test
public void createTable() {
ModifierSequenceDao.Table.onCreate(database);
verify(database).execSQL(ModifierSequenceDao.Table.CREATE_TABLE_STATEMENT);
}
@Test
public void updateTable() {
ModifierSequenceDao.Table.onUpdate(database, 1, 2);
InOrder inOrder = inOrder(database);
inOrder.verify(database).execSQL(ModifierSequenceDao.Table.DROP_TABLE_STATEMENT);
inOrder.verify(database).execSQL(ModifierSequenceDao.Table.CREATE_TABLE_STATEMENT);
}
@Test
public void deleteTable() {
ModifierSequenceDao.Table.onDelete(database);
InOrder inOrder = inOrder(database);
inOrder.verify(database).execSQL(ModifierSequenceDao.Table.DROP_TABLE_STATEMENT);
inOrder.verify(database).execSQL(ModifierSequenceDao.Table.CREATE_TABLE_STATEMENT);
}
@NonNull
private MatrixCursor createCursor(String modifierJson) {
MatrixCursor cursor = new MatrixCursor(new String[]{
ModifierSequenceDao.Table.COLUMN_ID,
ModifierSequenceDao.Table.COLUMN_MEDIA_URI,
ModifierSequenceDao.Table.COLUMN_DATA
}, 1);
cursor.addRow(Arrays.asList("1", EXPECTED_MEDIA_URI, "{\"modifiers\": [" + modifierJson + "]}"));
cursor.moveToFirst();
return cursor;
}
}

View file

@ -1,12 +1,15 @@
package fr.free.nrw.commons.mwapi;
import android.content.SharedPreferences;
import android.os.Build;
import android.preference.PreferenceManager;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.Config;
import java.io.IOException;
@ -34,11 +37,13 @@ public class ApacheHttpClientMediaWikiApiTest {
private ApacheHttpClientMediaWikiApi testObject;
private MockWebServer server;
private SharedPreferences sharedPreferences;
@Before
public void setUp() throws Exception {
server = new MockWebServer();
testObject = new ApacheHttpClientMediaWikiApi("http://" + server.getHostName() + ":" + server.getPort() + "/");
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(RuntimeEnvironment.application);
testObject = new ApacheHttpClientMediaWikiApi(RuntimeEnvironment.application, "http://" + server.getHostName() + ":" + server.getPort() + "/", sharedPreferences);
testObject.setWikiMediaToolforgeUrl("http://" + server.getHostName() + ":" + server.getPort() + "/");
}
@ -124,11 +129,11 @@ public class ApacheHttpClientMediaWikiApiTest {
RecordedRequest loginRequest = assertBasicRequestParameters(server, "POST");
body = parseBody(loginRequest.getBody().readUtf8());
assertEquals("1", body.get("rememberMe"));
assertEquals("true", body.get("rememberMe"));
assertEquals("foo", body.get("username"));
assertEquals("bar", body.get("password"));
assertEquals("baz", body.get("logintoken"));
assertEquals("1", body.get("logincontinue"));
assertEquals("true", body.get("logincontinue"));
assertEquals("2fa", body.get("OATHToken"));
assertEquals("xml", body.get("format"));

View file

@ -1,53 +1,92 @@
package fr.free.nrw.commons.nearby;
import android.app.Activity;
import android.location.LocationManager;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v7.widget.RecyclerView;
import android.view.MenuItem;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.Shadows;
import org.robolectric.android.controller.ActivityController;
import org.robolectric.annotation.Config;
import org.robolectric.shadow.api.Shadow;
import org.robolectric.shadows.ShadowLocationManager;
import edu.emory.mathcs.backport.java.util.Collections;
import fr.free.nrw.commons.BuildConfig;
import fr.free.nrw.commons.R;
import fr.free.nrw.commons.TestCommonsApplication;
import fr.free.nrw.commons.location.LatLng;
import fr.free.nrw.commons.location.LocationServiceManager;
import io.reactivex.android.plugins.RxAndroidPlugins;
import io.reactivex.plugins.RxJavaPlugins;
import io.reactivex.schedulers.Schedulers;
import static junit.framework.Assert.assertNotNull;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.when;
import static org.robolectric.Shadows.shadowOf;
@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class, sdk = 21, application = TestCommonsApplication.class)
public class NearbyActivityTest {
private static final LatLng ST_LOUIS_MO_LAT_LNG = new LatLng(38.627003, -90.199402, 0);
private static final LatLng ST_LOUIS_MO_LAT_LNG
= new LatLng(38.627003, -90.199402, 0);
private static final Place AIRPORT = new Place(
"name", Place.Label.AIRPORT,
"desc", null,
new LatLng(38.6270, -90.1994, 0),
null);
private ActivityController<NearbyActivity> activityController;
@Mock
private LocationServiceManager locationManager;
@Mock
private NearbyController nearbyController;
@InjectMocks
private NearbyActivity nearbyActivity;
@Before
public void setUp() throws Exception {
// ensure waiting all threads to complete
RxJavaPlugins.setIoSchedulerHandler(
scheduler -> Schedulers.trampoline());
RxJavaPlugins.setComputationSchedulerHandler(
scheduler -> Schedulers.trampoline());
RxJavaPlugins.setNewThreadSchedulerHandler(
scheduler -> Schedulers.trampoline());
RxAndroidPlugins.setInitMainThreadSchedulerHandler(
scheduler -> Schedulers.trampoline());
nearbyActivity = Robolectric.setupActivity(NearbyActivity.class);
// replace methods and fields with mocks
MockitoAnnotations.initMocks(this);
TestCommonsApplication application = (TestCommonsApplication) RuntimeEnvironment.application;
when(application.getLocationServiceManager().getLastLocation()).thenReturn(ST_LOUIS_MO_LAT_LNG);
when(application.getLocationServiceManager().isProviderEnabled()).thenReturn(true);
activityController = Robolectric.buildActivity(NearbyActivity.class);
nearbyActivity = activityController.get();
when(locationManager.getLastLocation()).thenReturn(ST_LOUIS_MO_LAT_LNG);
when(locationManager.isProviderEnabled()).thenReturn(true);
when(nearbyController.loadAttractionsFromLocation(any(LatLng.class), any(Context.class)))
.thenReturn(Collections.singletonList(AIRPORT));
}
@Test
public void activityLaunchesAndShowsList() {
activityController.create().resume().visible();
assertNotNull(nearbyActivity.getSupportFragmentManager().findFragmentByTag("NearbyListFragment"));
public void pressRefreshAndShowList() {
MenuItem refresh = shadowOf(nearbyActivity).getOptionsMenu().findItem(R.id.action_refresh);
nearbyActivity.onOptionsItemSelected(refresh);
Fragment nearbyListFragment = nearbyActivity.getSupportFragmentManager()
.findFragmentByTag(NearbyListFragment.class.getSimpleName());
assertNotNull(nearbyListFragment);
// one element (AIRPORT) exists in the list
RecyclerView view = nearbyListFragment.getView().findViewById(R.id.listView);
assertNotNull(view.findViewHolderForAdapterPosition(0));
assertNull(view.findViewHolderForAdapterPosition(1));
}
}

View file

@ -33,7 +33,15 @@ public class NearbyAdapterFactoryTest {
private static final Place PLACE = new Place("name", Place.Label.AIRPORT,
"desc", null, new LatLng(38.6270, -90.1994, 0), null);
private static final Place UNKNOWN_PLACE = new Place("name", Place.Label.UNKNOWN,
<<<<<<< HEAD
=======
<<<<<<< 27ac8ae0d72011bc651affecf7b1da2100ec927e
"?", null, new LatLng(39.7392, -104.9903, 0), null);
// ^ "?" is a special value for unknown class names from Wikidata query results
=======
>>>>>>> directNearbyUploadsNewLocal
"desc", null, new LatLng(39.7392, -104.9903, 0), null);
>>>>>>> Rename Description to Label to prevent misunderstandings
private Place clickedPlace;
@Test
@ -68,12 +76,13 @@ public class NearbyAdapterFactoryTest {
RendererViewHolder viewHolder = renderComponent(result);
// test that the values we gave are actually rendered
assertNotNull(viewHolder.itemView.findViewById(R.id.tvName));
assertEquals("name",
assertEquals(PLACE.name,
((TextView) viewHolder.itemView.findViewById(R.id.tvName)).getText().toString());
assertNotNull(viewHolder.itemView.findViewById(R.id.tvDesc));
assertEquals("airport",
assertEquals(PLACE.getLongDescription(),
((TextView) viewHolder.itemView.findViewById(R.id.tvDesc)).getText().toString());
assertNotNull(viewHolder.itemView.findViewById(R.id.distance));
@ -94,7 +103,7 @@ public class NearbyAdapterFactoryTest {
RendererViewHolder viewHolder = renderComponent(result);
assertNotNull(viewHolder.itemView.findViewById(R.id.tvDesc));
assertEquals("no description found",
assertEquals(RuntimeEnvironment.application.getString(R.string.no_description_found),
((TextView) viewHolder.itemView.findViewById(R.id.tvDesc)).getText().toString());
assertNotNull(viewHolder.itemView.findViewById(R.id.icon));