Skip to content

Commit

Permalink
plusonelabs#356 Change the way content providers are mocked for testi…
Browse files Browse the repository at this point in the history
…ng. Now results to play are inserted in the widget's Settings
  • Loading branch information
yvolk committed Dec 29, 2019
1 parent 7fd5dcf commit 078c068
Show file tree
Hide file tree
Showing 24 changed files with 289 additions and 158 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ protected int getNumberOfOpenTasksSources() {

@Before
public void setUp() throws Exception {
provider = MockCalendarContentProvider.getContentProvider(getNumberOfOpenTasksSources());
provider = MockCalendarContentProvider.getContentProvider();
factory = new RemoteViewsFactory(provider.getContext(), provider.getWidgetId());
assertTrue(factory.getWidgetEntries().get(0) instanceof LastEntry);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,9 +75,11 @@ public void testBirthdayOneDayOnly() throws IOException, JSONException {
}

private void playAtOneTime(QueryResultsStorage inputs, DateTime now, int entriesWithoutLastExpected) {
provider.clear();
provider.addResults(inputs.getResults());
DateUtil.setNow(now);
EnvironmentChangedReceiver.sleep(MIN_MILLIS_BETWEEN_RELOADS);
provider.setPreferences();
factory.onDataSetChanged();
factory.logWidgetEntries(TAG);
assertEquals(entriesWithoutLastExpected == 0 ? 0 : entriesWithoutLastExpected + 1,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ public void testIssue354() throws IOException, JSONException {
provider.addResults(inputs.getResults());
Log.d(method, "Results executed at " + inputs.getResults().get(0).getExecutedAt());

provider.setPreferences();
factory.onDataSetChanged();
factory.logWidgetEntries(method);
assertEquals("Number of entries", 40, factory.getWidgetEntries().size());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@

import android.util.Log;

import org.andstatus.todoagenda.calendar.CalendarEvent;
import org.andstatus.todoagenda.provider.QueryRow;
import org.andstatus.todoagenda.util.DateUtil;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.LocalDateTime;
Expand All @@ -21,6 +23,7 @@
* @author [email protected]
*/
public class IllegalInstantDueToTimeZoneTransitionTest extends BaseWidgetTest {
private static final String TAG = IllegalInstantDueToTimeZoneTransitionTest.class.getSimpleName();

private int eventId = 0;

Expand All @@ -40,9 +43,15 @@ public void testIllegalInstantDueToTimeZoneOffsetTransition() {
oneTimeDst("2015-10-25T00:00:00+00:00");
oneTimeDst("2011-03-27T00:00:00+00:00");
oneTimeDst("1980-04-06T00:00:00+00:00");
provider.addRow(new CalendarEvent(provider.getContext(), provider.getWidgetId(),
provider.getSettings().getTimeZone(),false)
.setStartDate(DateUtil.startOfTomorrow(provider.getSettings().getTimeZone()))
.setEventSource(provider.getFirstActiveEventSource())
.setTitle("This will be the only event that will be shown"));
provider.setPreferences();
factory.onDataSetChanged();
factory.logWidgetEntries(TAG);
assertEquals(1, provider.getQueriesCount());
assertEquals(3, factory.getWidgetEntries().size());
}

private void oneTimeDst(String iso8601time) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ public void testInsidePeriod() throws IOException, JSONException {
provider.saveSettings();
DateTime now = new DateTime(2015, 8, 30, 0, 0, 1, 0, provider.getSettings().getTimeZone());
DateUtil.setNow(now);
provider.setPreferences();
factory.onDataSetChanged();
factory.logWidgetEntries(method);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ public void testEventWhichCarryOverToTheNextDay() {

DateUtil.setNow(today.plusHours(10).plusMinutes(33));
provider.addRow(event);
provider.setPreferences();
factory.onDataSetChanged();
CalendarEntry entry1 = null;
CalendarEntry entry2 = null;
Expand Down Expand Up @@ -106,6 +107,7 @@ private CalendarEntry getSundayEntryAt(CalendarEvent event, DateTime currentDate
DateUtil.setNow(currentDateTime);
provider.clear();
provider.addRow(event);
provider.setPreferences();
factory.onDataSetChanged();
Log.i(TAG, "getSundayEntryAt " + currentDateTime);
factory.logWidgetEntries(TAG);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ public void testTodaysOngoingEvent() {

DateUtil.setNow(today.plusHours(10).plusMinutes(33));
provider.addRow(event);
provider.setPreferences();
factory.onDataSetChanged();
factory.logWidgetEntries(TAG);
CalendarEntry entry = null;
Expand Down Expand Up @@ -66,6 +67,7 @@ public void testYesterdaysOngoingEvent() {

DateUtil.setNow(today.plusHours(10).plusMinutes(33));
provider.addRow(event);
provider.setPreferences();
factory.onDataSetChanged();
factory.logWidgetEntries(TAG);
CalendarEntry entry = null;
Expand Down Expand Up @@ -96,6 +98,7 @@ public void testEventWhichCarryOverToTheNextDay() {

DateUtil.setNow(today.plusHours(20).plusMinutes(33));
provider.addRow(event);
provider.setPreferences();
factory.onDataSetChanged();
factory.logWidgetEntries(TAG);
CalendarEntry entry = null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ public void testPastDueHeaderWithTasks() throws IOException, JSONException {
provider.addResults(inputs.getResults());
Log.d(method, "Results executed at " + inputs.getResults().get(0).getExecutedAt());

provider.setPreferences();
factory.onDataSetChanged();
factory.logWidgetEntries(method);
assertEquals("Past and Due header", DateUtil.DATETIME_MIN, factory.getWidgetEntries().get(0).entryDate);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ void generateEventInstances() {
provider.addRow(new QueryRow().setEventId(eventId).setTitle("Work each day")
.setBegin(millis).setEnd(millis + TimeUnit.HOURS.toMillis(9)));
}
provider.setPreferences();
factory.onDataSetChanged();
factory.logWidgetEntries(TAG);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ private void assertOneEvent(CalendarEvent event, boolean equal) {
EnvironmentChangedReceiver.sleep(MIN_MILLIS_BETWEEN_RELOADS);
provider.clear();
provider.addRow(event);
provider.setPreferences();
factory.onDataSetChanged();

assertFalse(provider.getSettings().toString(),
Expand All @@ -95,7 +96,6 @@ private void assertOneEvent(CalendarEvent event, boolean equal) {
source.source.getId()).source.isAvailable);

factory.logWidgetEntries(TAG);
assertEquals(1, provider.getQueriesCount());
assertEquals(factory.getWidgetEntries().toString(), 3, factory.getWidgetEntries().size());
WidgetEntry entry = factory.getWidgetEntries().get(1);
assertTrue(entry instanceof CalendarEntry);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ public void testIssue327() throws IOException, JSONException {
provider.addResults(inputs.getResults());
Log.d(method, "Results executed at " + inputs.getResults().get(0).getExecutedAt());

provider.setPreferences();
factory.onDataSetChanged();
factory.logWidgetEntries(method);
assertEquals("Number of entries", 43, factory.getWidgetEntries().size());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ public void testIssue205() throws IOException, JSONException {
provider.addResults(inputs.getResults());
Log.d(method, "Results executed at " + inputs.getResults().get(0).getExecutedAt());

provider.setPreferences();
factory.onDataSetChanged();
factory.logWidgetEntries(method);
assertEquals("Number of entries", 11, factory.getWidgetEntries().size());
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,6 @@
package org.andstatus.todoagenda.provider;

import android.content.Context;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.net.Uri;
import android.test.mock.MockContentProvider;
import android.test.mock.MockContentResolver;
import android.util.Log;

import androidx.annotation.NonNull;
Expand All @@ -17,10 +12,8 @@
import org.andstatus.todoagenda.prefs.AllSettings;
import org.andstatus.todoagenda.prefs.ApplicationPreferences;
import org.andstatus.todoagenda.prefs.InstanceSettings;
import org.andstatus.todoagenda.prefs.MockSettingsProvider;
import org.andstatus.todoagenda.prefs.OrderedEventSource;
import org.andstatus.todoagenda.prefs.SettingsStorage;
import org.andstatus.todoagenda.testcompat.IsolatedContext;
import org.andstatus.todoagenda.util.DateUtil;
import org.andstatus.todoagenda.util.RawResourceUtils;
import org.joda.time.DateTimeZone;
Expand All @@ -31,7 +24,6 @@
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicInteger;

import static org.andstatus.todoagenda.prefs.AllSettings.getStorageKey;
Expand All @@ -41,44 +33,34 @@
/**
* @author [email protected]
*/
public class MockCalendarContentProvider extends MockContentProvider {
public class MockCalendarContentProvider {
final static String TAG = MockCalendarContentProvider.class.getSimpleName();
private static final int TEST_WIDGET_ID_MIN = 434892;
private static final String[] ZONE_IDS = {"America/Los_Angeles", "Europe/Moscow", "Asia/Kuala_Lumpur", "UTC"};
private volatile int queriesCount = 0;
private final List<QueryResult> results = new CopyOnWriteArrayList<>();
private final int numberOfOpenTaskSources;
private final QueryResultsStorage results = new QueryResultsStorage();
private final Context context;

private final static AtomicInteger widgetId = new AtomicInteger(TEST_WIDGET_ID_MIN);
private final static AtomicInteger lastWidgetId = new AtomicInteger(TEST_WIDGET_ID_MIN);
private final int widgetId;

public static MockCalendarContentProvider getContentProvider(int numberOfOpenTasksSources) throws JSONException {
MockContentResolver mockResolver = new MockContentResolver();
Context targetContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
Context isolatedContext = new IsolatedContext(mockResolver, targetContext);
MockCalendarContentProvider contentProvider =
new MockCalendarContentProvider(isolatedContext, numberOfOpenTasksSources);

mockResolver.addProvider("com.android.calendar", contentProvider);
if (numberOfOpenTasksSources > 0) {
mockResolver.addProvider("org.dmfs.tasks", contentProvider);
}
mockResolver.addProvider("settings", new MockSettingsProvider());
public static MockCalendarContentProvider getContentProvider() {
DateTimeZone zone = DateTimeZone.forID(ZONE_IDS[(int)(System.currentTimeMillis() % ZONE_IDS.length)]);
DateTimeZone.setDefault(zone);
Log.i(TAG, "Default Time zone set to " + zone);

contentProvider.setPreferences(isolatedContext);
Context targetContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
MockCalendarContentProvider contentProvider = new MockCalendarContentProvider(targetContext);
return contentProvider;
}

private MockCalendarContentProvider(Context context, int numberOfOpenTaskSources) {
super(context);
this.numberOfOpenTaskSources = numberOfOpenTaskSources;
private MockCalendarContentProvider(Context context) {
this.context = context;
widgetId = lastWidgetId.incrementAndGet();
}

private void setPreferences(Context context) throws JSONException {
DateTimeZone zone = DateTimeZone.forID(ZONE_IDS[(int)(System.currentTimeMillis() % ZONE_IDS.length)]);
DateTimeZone.setDefault(zone);
Log.i(TAG, "Default Time zone set to " + zone);

InstanceSettings settings = AllSettings.instanceFromId(context, widgetId.incrementAndGet());
public void setPreferences() {
InstanceSettings settings = AllSettings.instanceFromId(context, widgetId);
settings.setQueryResults(results);
AllSettings.loadFromTestData(context, settings);
}

Expand All @@ -97,44 +79,6 @@ public static void tearDown() {
ApplicationPreferences.setWidgetId(ApplicationProvider.getApplicationContext(), TEST_WIDGET_ID_MIN);
}

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

@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
if ("content://com.android.calendar/calendars".equals(uri.toString())) {
Log.i(TAG, "query: Available Calendar sources");
MatrixCursor cursor = new MatrixCursor(projection);
cursor.addRow(new Object[]{1L, TAG, 0x00FF00, "[email protected]"});
return cursor;
}
if ("content://org.dmfs.tasks/tasklists".equals(uri.toString())) {
Log.i(TAG, "query: Available OpenTasks sources");
if (numberOfOpenTaskSources == 0) return null;

MatrixCursor cursor = new MatrixCursor(projection);
for(int i = 0; i < numberOfOpenTaskSources; i++) {
cursor.addRow(new Object[]{2 + i, TAG + ".task" + i, 0x0FF0000,
"[email protected]"});
}
return cursor;
}
if ("content://com.android.calendar/TasksAccounts".equals(uri.toString())) {
Log.i(TAG, "query: Available Samsung task sources");
return null;
}

Log.i(TAG, "query: " + uri);
queriesCount++;
if (results.size() < queriesCount) {
return null;
} else {
return results.get(queriesCount - 1).query(projection);
}
}

public void addResults(List<QueryResult> results) {
for (QueryResult result : results) {
addResult(result);
Expand All @@ -149,7 +93,7 @@ public void addResults(List<QueryResult> results) {
}

public void addResult(QueryResult result) {
results.add(result);
results.addResult(result);
}

public void addRow(CalendarEvent event) {
Expand All @@ -168,10 +112,14 @@ public void addRow(CalendarEvent event) {
}

public void addRow(QueryRow queryRow) {
if (results.isEmpty()) {
addResult(new QueryResult(EventProviderType.CALENDAR, getSettings().getWidgetId(), DateUtil.now(getSettings().getTimeZone())));
}
results.get(0).addRow(queryRow);
EventProviderType providerType = EventProviderType.CALENDAR;
QueryResult result = results.findLast(providerType).orElseGet( () -> {
QueryResult r2 = new QueryResult(providerType, getSettings().getWidgetId(),
DateUtil.now(getSettings().getTimeZone()));
results.addResult(r2);
return r2;
});
result.addRow(queryRow);
}

@NonNull
Expand All @@ -180,16 +128,11 @@ public InstanceSettings getSettings() {
}

public void clear() {
queriesCount = 0;
results.clear();
}

public int getQueriesCount() {
return queriesCount;
}

public int getWidgetId() {
return widgetId.get();
return widgetId;
}

public void startEditing() {
Expand All @@ -213,4 +156,8 @@ public OrderedEventSource getFirstActiveEventSource() {
}
return OrderedEventSource.EMPTY;
}

public Context getContext() {
return context;
}
}
Loading

0 comments on commit 078c068

Please sign in to comment.