Convert remaining robolectric tests

pull/189/head
Alex Baker 12 years ago
parent 66452a64e6
commit 5317dca490

@ -39,7 +39,7 @@ import java.util.ArrayList;
*/ */
abstract public class AbstractDatabase { abstract public class AbstractDatabase {
Logger log = LoggerFactory.getLogger(AbstractDatabase.class); private static final Logger log = LoggerFactory.getLogger(AbstractDatabase.class);
// --- abstract methods // --- abstract methods
@ -75,7 +75,7 @@ abstract public class AbstractDatabase {
/** /**
* SQLiteOpenHelper that takes care of database operations * SQLiteOpenHelper that takes care of database operations
*/ */
protected SQLiteOpenHelper helper = null; private SQLiteOpenHelper helper = null;
/** /**
* Internal pointer to open database. Hides the fact that there is a * Internal pointer to open database. Hides the fact that there is a
@ -101,7 +101,7 @@ abstract public class AbstractDatabase {
listeners.add(listener); listeners.add(listener);
} }
protected void onDatabaseUpdated() { private void onDatabaseUpdated() {
for(DatabaseUpdateListener listener : listeners) { for(DatabaseUpdateListener listener : listeners) {
listener.onDatabaseUpdated(); listener.onDatabaseUpdated();
} }
@ -119,7 +119,7 @@ abstract public class AbstractDatabase {
throw new UnsupportedOperationException("Unknown model class " + modelType); //$NON-NLS-1$ throw new UnsupportedOperationException("Unknown model class " + modelType); //$NON-NLS-1$
} }
protected synchronized final void initializeHelper() { private synchronized void initializeHelper() {
if(helper == null) { if(helper == null) {
if(ContextManager.getContext() == null) { if(ContextManager.getContext() == null) {
throw new NullPointerException("Null context creating database helper"); throw new NullPointerException("Null context creating database helper");

@ -8,8 +8,6 @@ package com.todoroo.andlib.sql;
import com.todoroo.andlib.data.Property; import com.todoroo.andlib.data.Property;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static com.todoroo.andlib.sql.SqlConstants.ALL; import static com.todoroo.andlib.sql.SqlConstants.ALL;
import static com.todoroo.andlib.sql.SqlConstants.COMMA; import static com.todoroo.andlib.sql.SqlConstants.COMMA;
@ -192,34 +190,4 @@ public final class Query {
queryTemplate = template; queryTemplate = template;
return this; return this;
} }
/** query template helper */
public static class QueryTemplateHelper {
/** build a content resolver query */
public static void queryForContentResolver(String queryTemplate,
StringBuilder selectionClause, StringBuilder orderClause,
StringBuilder groupByClause) {
Pattern where = Pattern.compile("WHERE (.*?)(LIMIT|HAVING|GROUP|ORDER|\\Z)");
Matcher whereMatcher = where.matcher(queryTemplate);
if(whereMatcher.find()) {
selectionClause.append(whereMatcher.group(1).trim());
}
Pattern group = Pattern.compile("GROUP BY (.*?)(LIMIT|HAVING|ORDER|\\Z)");
Matcher groupMatcher = group.matcher(queryTemplate);
if(groupMatcher.find()) {
groupByClause.append(groupMatcher.group(1).trim());
}
Pattern order = Pattern.compile("ORDER BY (.*?)(LIMIT|HAVING|\\Z)");
Matcher orderMatcher = order.matcher(queryTemplate);
if(orderMatcher.find()) {
orderClause.append(orderMatcher.group(1).trim());
}
}
}
} }

@ -40,11 +40,6 @@ public final class QueryTemplate {
return this; return this;
} }
public QueryTemplate groupBy(Field... groupBy) {
groupBies.addAll(asList(groupBy));
return this;
}
public QueryTemplate orderBy(Order... order) { public QueryTemplate orderBy(Order... order) {
orders.addAll(asList(order)); orders.addAll(asList(order));
return this; return this;

@ -7,7 +7,6 @@ package com.todoroo.andlib.service;
import android.content.Context; import android.content.Context;
import java.lang.ref.WeakReference;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.util.HashMap; import java.util.HashMap;
@ -43,12 +42,6 @@ abstract public class AbstractDependencyInjector {
*/ */
protected final HashMap<String, Object> injectables = new HashMap<>(); protected final HashMap<String, Object> injectables = new HashMap<>();
/**
* Cache of classes that were instantiated by the injector
*/
protected final HashMap<Class<?>, WeakReference<Object>> createdObjects =
new HashMap<>();
/** /**
* Gets the injected object for this field. If implementing class does not * Gets the injected object for this field. If implementing class does not
* know how to handle this dependency, it should return null * know how to handle this dependency, it should return null
@ -65,12 +58,4 @@ abstract public class AbstractDependencyInjector {
public String toString() { public String toString() {
return getClass().getSimpleName(); return getClass().getSimpleName();
} }
/**
* Flush dependency injection cache. Useful for unit tests.
*/
protected void clear() {
createdObjects.clear();
}
} }

@ -204,18 +204,18 @@ abstract public class TranslationTests extends TodorooTestCase {
forEachLocale(new Runnable() { forEachLocale(new Runnable() {
public void run() { public void run() {
Locale locale = r.getConfiguration().locale; Locale locale = r.getConfiguration().locale;
for(int i = 0; i < dateStrings.length; i++) { for (int dateString : dateStrings) {
try { try {
String string = r.getString(dateStrings[i]); String string = r.getString(dateString);
try { try {
new SimpleDateFormat(string).format(date); new SimpleDateFormat(string).format(date);
} catch (Exception e) { } catch (Exception e) {
String name = r.getResourceName(dateStrings[i]); String name = r.getResourceName(dateString);
failures.append(String.format("%s: invalid format string '%s': %s\n", failures.append(String.format("%s: invalid format string '%s': %s\n",
locale.toString(), name, e.getMessage())); locale.toString(), name, e.getMessage()));
} }
} catch (Exception e) { } catch (Exception e) {
String name = r.getResourceName(dateStrings[i]); String name = r.getResourceName(dateString);
failures.append(String.format("%s: error opening %s: %s\n", failures.append(String.format("%s: error opening %s: %s\n",
locale.toString(), name, e.getMessage())); locale.toString(), name, e.getMessage()));
} }
@ -296,10 +296,10 @@ abstract public class TranslationTests extends TodorooTestCase {
*/ */
public int[] getResourceIds(Class<?> resources) throws Exception { public int[] getResourceIds(Class<?> resources) throws Exception {
Field[] fields = resources.getDeclaredFields(); Field[] fields = resources.getDeclaredFields();
List<Integer> ids = new ArrayList<Integer>(fields.length); List<Integer> ids = new ArrayList<>(fields.length);
for(int i = 0; i < fields.length; i++) { for (Field field : fields) {
try { try {
ids.add(fields[i].getInt(null)); ids.add(field.getInt(null));
} catch (Exception e) { } catch (Exception e) {
// not a field we care about // not a field we care about
} }

@ -1,82 +1,64 @@
package com.todoroo.andlib.utility; package com.todoroo.andlib.utility;
import android.content.Context; import android.test.AndroidTestCase;
import org.joda.time.DateTime; import org.joda.time.DateTime;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import java.util.Locale; import java.util.Locale;
import static com.todoroo.andlib.utility.DateUtilities.getRelativeDay; import static com.todoroo.andlib.utility.DateUtilities.getRelativeDay;
import static org.joda.time.DateTime.now; import static org.joda.time.DateTime.now;
import static org.junit.Assert.assertEquals;
import static org.robolectric.Robolectric.getShadowApplication;
import static org.tasks.Freeze.freezeAt; import static org.tasks.Freeze.freezeAt;
import static org.tasks.Freeze.thaw; import static org.tasks.Freeze.thaw;
@RunWith(RobolectricTestRunner.class) public class RelativeDayTest extends AndroidTestCase {
public class RelativeDayTest {
private static Locale defaultLocale; private static Locale defaultLocale;
private static final DateTime now = new DateTime(2013, 12, 31, 11, 9, 42, 357); private static final DateTime now = new DateTime(2013, 12, 31, 11, 9, 42, 357);
@Before public void setUp() {
public void before() {
defaultLocale = Locale.getDefault(); defaultLocale = Locale.getDefault();
Locale.setDefault(Locale.US); Locale.setDefault(Locale.US);
freezeAt(now); freezeAt(now);
} }
@After public void tearDown() {
public void after() {
Locale.setDefault(defaultLocale); Locale.setDefault(defaultLocale);
thaw(); thaw();
} }
@Test public void testRelativeDayIsToday() {
public void relativeDayIsToday() {
checkRelativeDay(now(), "today", "today"); checkRelativeDay(now(), "today", "today");
} }
@Test public void testRelativeDayIsTomorrow() {
public void relativeDayIsTomorrow() {
checkRelativeDay(now().plusDays(1), "tomorrow", "tmrw"); checkRelativeDay(now().plusDays(1), "tomorrow", "tmrw");
} }
@Test public void testRelativeDayIsYesterday() {
public void relativeDayIsYesterday() {
checkRelativeDay(now().minusDays(1), "yesterday", "yest"); checkRelativeDay(now().minusDays(1), "yesterday", "yest");
} }
@Test public void testRelativeDayTwo() {
public void relativeDayTwo() {
checkRelativeDay(now().minusDays(2), "Sunday", "Sun"); checkRelativeDay(now().minusDays(2), "Sunday", "Sun");
checkRelativeDay(now().plusDays(2), "Thursday", "Thu"); checkRelativeDay(now().plusDays(2), "Thursday", "Thu");
} }
@Test public void testRelativeDaySix() {
public void relativeDaySix() {
checkRelativeDay(now().minusDays(6), "Wednesday", "Wed"); checkRelativeDay(now().minusDays(6), "Wednesday", "Wed");
checkRelativeDay(now().plusDays(6), "Monday", "Mon"); checkRelativeDay(now().plusDays(6), "Monday", "Mon");
} }
@Test public void testRelativeDayOneWeek() {
public void relativeDayOneWeek() {
checkRelativeDay(now().minusDays(7), "Dec 24", "Dec 24"); checkRelativeDay(now().minusDays(7), "Dec 24", "Dec 24");
} }
@Test public void testRelativeDayOneWeekNextYear() {
public void relativeDayOneWeekNextYear() {
checkRelativeDay(now().plusDays(7), "Jan 7\n2014", "Jan 7\n2014"); checkRelativeDay(now().plusDays(7), "Jan 7\n2014", "Jan 7\n2014");
} }
private void checkRelativeDay(DateTime now, String full, String abbreviated) { private void checkRelativeDay(DateTime now, String full, String abbreviated) {
final Context context = getShadowApplication().getApplicationContext(); assertEquals(full, getRelativeDay(getContext(), now.getMillis(), false));
assertEquals(full, getRelativeDay(context, now.getMillis(), false)); assertEquals(abbreviated, getRelativeDay(getContext(), now.getMillis()));
assertEquals(abbreviated, getRelativeDay(context, now.getMillis()));
} }
} }

@ -1,13 +1,9 @@
package com.todoroo.astrid.gtasks.api; package com.todoroo.astrid.gtasks.api;
import android.test.AndroidTestCase;
import org.joda.time.DateTime; import org.joda.time.DateTime;
import org.joda.time.DateTimeZone; import org.joda.time.DateTimeZone;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import java.util.Locale; import java.util.Locale;
import java.util.TimeZone; import java.util.TimeZone;
@ -16,42 +12,34 @@ import static com.todoroo.astrid.gtasks.api.GtasksApiUtilities.gtasksCompletedTi
import static com.todoroo.astrid.gtasks.api.GtasksApiUtilities.gtasksDueTimeToUnixTime; import static com.todoroo.astrid.gtasks.api.GtasksApiUtilities.gtasksDueTimeToUnixTime;
import static com.todoroo.astrid.gtasks.api.GtasksApiUtilities.unixTimeToGtasksCompletionTime; import static com.todoroo.astrid.gtasks.api.GtasksApiUtilities.unixTimeToGtasksCompletionTime;
import static com.todoroo.astrid.gtasks.api.GtasksApiUtilities.unixTimeToGtasksDueDate; import static com.todoroo.astrid.gtasks.api.GtasksApiUtilities.unixTimeToGtasksDueDate;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
@RunWith(RobolectricTestRunner.class) public class GtasksApiUtilitiesTest extends AndroidTestCase {
public class GtasksApiUtilitiesTest {
private static final Locale defaultLocale = Locale.getDefault(); private static final Locale defaultLocale = Locale.getDefault();
private static final DateTimeZone defaultDateTimeZone = DateTimeZone.getDefault(); private static final DateTimeZone defaultDateTimeZone = DateTimeZone.getDefault();
@Before public void setUp() {
public void before() {
Locale.setDefault(Locale.US); Locale.setDefault(Locale.US);
DateTimeZone.setDefault(DateTimeZone.forID("America/Chicago")); DateTimeZone.setDefault(DateTimeZone.forID("America/Chicago"));
} }
@After public void tearDown() {
public void after() {
Locale.setDefault(defaultLocale); Locale.setDefault(defaultLocale);
DateTimeZone.setDefault(defaultDateTimeZone); DateTimeZone.setDefault(defaultDateTimeZone);
} }
@Test public void testConvertUnixToGoogleCompletionTime() {
public void convertUnixToGoogleCompletionTime() {
long now = new DateTime(2014, 1, 8, 8, 53, 20, 109).getMillis(); long now = new DateTime(2014, 1, 8, 8, 53, 20, 109).getMillis();
assertEquals(now, unixTimeToGtasksCompletionTime(now).getValue()); assertEquals(now, unixTimeToGtasksCompletionTime(now).getValue());
} }
@Test public void testConvertGoogleCompletedTimeToUnixTime() {
public void convertGoogleCompletedTimeToUnixTime() {
long now = new DateTime(2014, 1, 8, 8, 53, 20, 109).getMillis(); long now = new DateTime(2014, 1, 8, 8, 53, 20, 109).getMillis();
com.google.api.client.util.DateTime gtime = new com.google.api.client.util.DateTime(now); com.google.api.client.util.DateTime gtime = new com.google.api.client.util.DateTime(now);
assertEquals(now, gtasksCompletedTimeToUnixTime(gtime)); assertEquals(now, gtasksCompletedTimeToUnixTime(gtime));
} }
@Test public void testConvertDueDateTimeToGoogleDueDate() {
public void convertDueDateTimeToGoogleDueDate() {
DateTime now = new DateTime(2014, 1, 8, 8, 53, 20, 109); DateTime now = new DateTime(2014, 1, 8, 8, 53, 20, 109);
assertEquals( assertEquals(
@ -59,9 +47,7 @@ public class GtasksApiUtilitiesTest {
unixTimeToGtasksDueDate(now.getMillis()).getValue()); unixTimeToGtasksDueDate(now.getMillis()).getValue());
} }
@Test public void disabled_testConvertGoogleDueDateToUnixTime() {
@Ignore
public void convertGoogleDueDateToUnixTime() {
com.google.api.client.util.DateTime googleDueDate = com.google.api.client.util.DateTime googleDueDate =
new com.google.api.client.util.DateTime( new com.google.api.client.util.DateTime(
new DateTime(2014, 1, 8, 0, 0, 0, 0).toDate(), TimeZone.getTimeZone("UTC")); new DateTime(2014, 1, 8, 0, 0, 0, 0).toDate(), TimeZone.getTimeZone("UTC"));
@ -71,14 +57,12 @@ public class GtasksApiUtilitiesTest {
gtasksDueTimeToUnixTime(googleDueDate)); gtasksDueTimeToUnixTime(googleDueDate));
} }
@Test public void testConvertToInvalidGtaskTimes() {
public void convertToInvalidGtaskTimes() {
assertNull(unixTimeToGtasksCompletionTime(-1)); assertNull(unixTimeToGtasksCompletionTime(-1));
assertNull(unixTimeToGtasksDueDate(-1)); assertNull(unixTimeToGtasksDueDate(-1));
} }
@Test public void testConvertFromInvalidGtaskTimes() {
public void convertFromInvalidGtaskTimes() {
assertEquals(0, gtasksCompletedTimeToUnixTime(null)); assertEquals(0, gtasksCompletedTimeToUnixTime(null));
assertEquals(0, gtasksDueTimeToUnixTime(null)); assertEquals(0, gtasksDueTimeToUnixTime(null));
} }

@ -3,43 +3,28 @@ package com.todoroo.astrid.model;
import android.content.ContentValues; import android.content.ContentValues;
import com.todoroo.andlib.data.Property; import com.todoroo.andlib.data.Property;
import com.todoroo.andlib.test.TodorooRobolectricTestCase; import com.todoroo.andlib.service.Autowired;
import com.todoroo.andlib.test.TodorooTestCase;
import com.todoroo.astrid.data.Task; import com.todoroo.astrid.data.Task;
import com.todoroo.astrid.service.TaskService; import com.todoroo.astrid.service.TaskService;
import com.todoroo.astrid.utility.AstridPreferences; import com.todoroo.astrid.utility.AstridPreferences;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.tasks.Snippet; import org.tasks.Snippet;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.tasks.Freeze.freezeClock; import static org.tasks.Freeze.freezeClock;
import static org.tasks.RemoteModelHelpers.asQueryProperties; import static org.tasks.RemoteModelHelpers.asQueryProperties;
import static org.tasks.RemoteModelHelpers.compareRemoteModel; import static org.tasks.RemoteModelHelpers.compareRemoteModel;
import static org.tasks.date.DateTimeUtils.currentTimeMillis; import static org.tasks.date.DateTimeUtils.currentTimeMillis;
@RunWith(RobolectricTestRunner.class) public class TaskTest extends TodorooTestCase {
public class TaskTest extends TodorooRobolectricTestCase {
private TaskService taskService; @Autowired private TaskService taskService;
@Override public void testNewTaskHasNoCreationDate() {
public void before() {
super.before();
taskService = new TaskService();
}
@Test
public void newTaskHasNoCreationDate() {
assertFalse(new Task().containsValue(Task.CREATION_DATE)); assertFalse(new Task().containsValue(Task.CREATION_DATE));
} }
@Test public void testSavedTaskHasCreationDate() {
public void savedTaskHasCreationDate() {
freezeClock().thawAfter(new Snippet() {{ freezeClock().thawAfter(new Snippet() {{
Task task = new Task(); Task task = new Task();
taskService.save(task); taskService.save(task);
@ -47,8 +32,7 @@ public class TaskTest extends TodorooRobolectricTestCase {
}}); }});
} }
@Test public void testReadTaskFromDb() {
public void readTaskFromDb() {
Task task = new Task(); Task task = new Task();
taskService.save(task); taskService.save(task);
Property[] properties = asQueryProperties(Task.TABLE, task.getDatabaseValues()); Property[] properties = asQueryProperties(Task.TABLE, task.getDatabaseValues());
@ -56,7 +40,6 @@ public class TaskTest extends TodorooRobolectricTestCase {
compareRemoteModel(task, fromDb); compareRemoteModel(task, fromDb);
} }
@Test
public void testDefaults() { public void testDefaults() {
AstridPreferences.setPreferenceDefaults(); AstridPreferences.setPreferenceDefaults();
ContentValues defaults = new Task().getDefaultValues(); ContentValues defaults = new Task().getDefaultValues();

@ -1,28 +1,21 @@
package com.todoroo.astrid.reminders; package com.todoroo.astrid.reminders;
import android.annotation.SuppressLint; import android.annotation.SuppressLint;
import android.test.AndroidTestCase;
import com.todoroo.andlib.utility.Preferences; import com.todoroo.andlib.utility.Preferences;
import org.joda.time.DateTime; import org.joda.time.DateTime;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.tasks.R; import org.tasks.R;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import static com.todoroo.astrid.reminders.Notifications.isQuietHours; import static com.todoroo.astrid.reminders.Notifications.isQuietHours;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.tasks.Freeze.freezeAt; import static org.tasks.Freeze.freezeAt;
import static org.tasks.Freeze.thaw; import static org.tasks.Freeze.thaw;
import static org.tasks.TestUtilities.clearPreferences; import static org.tasks.TestUtilities.clearPreferences;
@RunWith(RobolectricTestRunner.class) public class NotificationsTest extends AndroidTestCase {
public class NotificationsTest {
@SuppressLint("NewApi") @SuppressLint("NewApi")
private static final int MILLIS_PER_HOUR = (int) TimeUnit.HOURS.toMillis(1); private static final int MILLIS_PER_HOUR = (int) TimeUnit.HOURS.toMillis(1);
@ -30,20 +23,17 @@ public class NotificationsTest {
private static final DateTime now = private static final DateTime now =
new DateTime(2014, 1, 23, 18, 8, 31, 540); new DateTime(2014, 1, 23, 18, 8, 31, 540);
@Before public void setUp() {
public void before() { clearPreferences(getContext());
clearPreferences();
Preferences.setBoolean(R.string.p_rmd_enable_quiet, true); Preferences.setBoolean(R.string.p_rmd_enable_quiet, true);
freezeAt(now); freezeAt(now);
} }
@After public void tearDown() {
public void after() {
thaw(); thaw();
} }
@Test public void testNotQuietWhenQuietHoursDisabled() {
public void notQuietWhenQuietHoursDisabled() {
Preferences.setBoolean(R.string.p_rmd_enable_quiet, false); Preferences.setBoolean(R.string.p_rmd_enable_quiet, false);
setQuietHoursStart(18); setQuietHoursStart(18);
setQuietHoursEnd(19); setQuietHoursEnd(19);
@ -51,40 +41,35 @@ public class NotificationsTest {
assertFalse(isQuietHours()); assertFalse(isQuietHours());
} }
@Test public void testIsQuietAtStartOfQuietHoursNoTimeWrap() {
public void isQuietAtStartOfQuietHoursNoTimeWrap() {
setQuietHoursStart(18); setQuietHoursStart(18);
setQuietHoursEnd(19); setQuietHoursEnd(19);
assertTrue(isQuietHours()); assertTrue(isQuietHours());
} }
@Test public void testIsNotQuietWhenStartAndEndAreSame() {
public void isNotQuietWhenStartAndEndAreSame() {
setQuietHoursStart(18); setQuietHoursStart(18);
setQuietHoursEnd(18); setQuietHoursEnd(18);
assertFalse(isQuietHours()); assertFalse(isQuietHours());
} }
@Test public void testIsNotQuietAtEndOfQuietHoursNoTimeWrap() {
public void isNotQuietAtEndOfQuietHoursNoTimeWrap() {
setQuietHoursStart(17); setQuietHoursStart(17);
setQuietHoursEnd(18); setQuietHoursEnd(18);
assertFalse(isQuietHours()); assertFalse(isQuietHours());
} }
@Test public void testIsQuietAtStartOfQuietHoursTimeWrap() {
public void isQuietAtStartOfQuietHoursTimeWrap() {
setQuietHoursStart(18); setQuietHoursStart(18);
setQuietHoursEnd(9); setQuietHoursEnd(9);
assertTrue(isQuietHours()); assertTrue(isQuietHours());
} }
@Test public void testIsNotQuietAtEndOfQuietHoursTimeWrap() {
public void isNotQuietAtEndOfQuietHoursTimeWrap() {
setQuietHoursStart(19); setQuietHoursStart(19);
setQuietHoursEnd(18); setQuietHoursEnd(18);

@ -3,93 +3,78 @@ package com.todoroo.astrid.reminders;
import android.annotation.SuppressLint; import android.annotation.SuppressLint;
import com.todoroo.andlib.service.Autowired; import com.todoroo.andlib.service.Autowired;
import com.todoroo.andlib.test.TodorooRobolectricTestCase; import com.todoroo.andlib.test.TodorooTestCase;
import com.todoroo.andlib.utility.Preferences; import com.todoroo.andlib.utility.Preferences;
import com.todoroo.astrid.dao.TaskDao; import com.todoroo.astrid.dao.TaskDao;
import com.todoroo.astrid.data.Task; import com.todoroo.astrid.data.Task;
import org.joda.time.DateTime; import org.joda.time.DateTime;
import org.junit.After;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.tasks.Freeze; import org.tasks.Freeze;
import org.tasks.R; import org.tasks.R;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import static com.todoroo.astrid.reminders.ReminderService.NO_ALARM; import static com.todoroo.astrid.reminders.ReminderService.NO_ALARM;
import static org.junit.Assert.assertEquals;
import static org.tasks.Freeze.freezeAt; import static org.tasks.Freeze.freezeAt;
import static org.tasks.Freeze.thaw; import static org.tasks.Freeze.thaw;
import static org.tasks.date.DateTimeUtils.newDate; import static org.tasks.date.DateTimeUtils.newDate;
@RunWith(RobolectricTestRunner.class) public class NotifyAtDeadlineTest extends TodorooTestCase {
public class NotifyAtDeadlineTest extends TodorooRobolectricTestCase {
@SuppressLint("NewApi") @SuppressLint("NewApi")
private static final int MILLIS_PER_HOUR = (int) TimeUnit.HOURS.toMillis(1); private static final int MILLIS_PER_HOUR = (int) TimeUnit.HOURS.toMillis(1);
@Autowired private TaskDao taskDao; @Autowired private TaskDao taskDao;
@Autowired private ReminderService reminderService;
private ReminderService service;
private final Task dueAtNoon = new Task() {{ private final Task dueAtNoon = new Task() {{
setDueDate(Task.URGENCY_SPECIFIC_DAY, newDate(2014, 1, 27).getTime()); setDueDate(Task.URGENCY_SPECIFIC_DAY, newDate(2014, 1, 27).getTime());
setReminderFlags(Task.NOTIFY_AT_DEADLINE); setReminderFlags(Task.NOTIFY_AT_DEADLINE);
}}; }};
@Override public void setUp() throws Exception {
public void before() { super.setUp();
super.before();
freezeAt(new DateTime(2014, 1, 24, 17, 23, 37)); freezeAt(new DateTime(2014, 1, 24, 17, 23, 37));
service = new ReminderService(); reminderService.setPreferenceDefaults();
service.setPreferenceDefaults();
} }
@After public void tearDown() throws Exception {
public void after() {
thaw(); thaw();
} }
@Test public void testScheduleReminderAtDueTime() {
public void scheduleReminderAtDueTime() {
final DateTime dueDate = new DateTime(2014, 1, 24, 19, 23, 57); final DateTime dueDate = new DateTime(2014, 1, 24, 19, 23, 57);
Task task = new Task() {{ Task task = new Task() {{
setDueDate(dueDate.getMillis()); setDueDate(dueDate.getMillis());
setReminderFlags(Task.NOTIFY_AT_DEADLINE); setReminderFlags(Task.NOTIFY_AT_DEADLINE);
}}; }};
assertEquals(dueDate.getMillis(), service.calculateNextDueDateReminder(task)); assertEquals(dueDate.getMillis(), reminderService.calculateNextDueDateReminder(task));
} }
@Test public void testNoReminderWhenNoDueDate() {
public void noReminderWhenNoDueDate() {
Task task = new Task() {{ Task task = new Task() {{
setReminderFlags(Task.NOTIFY_AT_DEADLINE); setReminderFlags(Task.NOTIFY_AT_DEADLINE);
}}; }};
assertEquals(NO_ALARM, service.calculateNextDueDateReminder(task)); assertEquals(NO_ALARM, reminderService.calculateNextDueDateReminder(task));
} }
@Test public void testNoReminderWhenNotifyAtDeadlineFlagNotSet() {
public void noReminderWhenNotifyAtDeadlineFlagNotSet() {
Task task = new Task() {{ Task task = new Task() {{
setDueDate(new DateTime(2014, 1, 24, 19, 23, 57).getMillis()); setDueDate(new DateTime(2014, 1, 24, 19, 23, 57).getMillis());
}}; }};
assertEquals(NO_ALARM, service.calculateNextDueDateReminder(task)); assertEquals(NO_ALARM, reminderService.calculateNextDueDateReminder(task));
} }
@Test public void testDontNotifyMoreThanOncePerDay() {
public void dontNotifyMoreThanOncePerDay() {
Task task = new Task() {{ Task task = new Task() {{
setDueDate(newDate(2014, 1, 23).getTime()); setDueDate(newDate(2014, 1, 23).getTime());
setReminderFlags(Task.NOTIFY_AT_DEADLINE); setReminderFlags(Task.NOTIFY_AT_DEADLINE);
setReminderLast(new DateTime(2014, 1, 23, 17, 23, 37).getMillis()); setReminderLast(new DateTime(2014, 1, 23, 17, 23, 37).getMillis());
}}; }};
assertEquals(NO_ALARM, service.calculateNextDueDateReminder(task)); assertEquals(NO_ALARM, reminderService.calculateNextDueDateReminder(task));
} }
@Test public void disabled_testNotifyIfLastNotificationWasMoreThanOneDayAgo() {
public void notifyIfLastNotificationWasMoreThanOneDayAgo() {
final DateTime dueDate = new DateTime(2014, 1, 24, 0, 0, 0, 0); final DateTime dueDate = new DateTime(2014, 1, 24, 0, 0, 0, 0);
Task task = new Task() {{ Task task = new Task() {{
setDueDate(Task.URGENCY_SPECIFIC_DAY, dueDate.getMillis()); setDueDate(Task.URGENCY_SPECIFIC_DAY, dueDate.getMillis());
@ -98,11 +83,10 @@ public class NotifyAtDeadlineTest extends TodorooRobolectricTestCase {
}}; }};
assertEquals( assertEquals(
dueDate.withHourOfDay(18).getMillis(), dueDate.withHourOfDay(18).getMillis(),
service.calculateNextDueDateReminder(task)); reminderService.calculateNextDueDateReminder(task));
} }
@Test public void testDuringQuietHoursSetNotificationAtEnd() {
public void duringQuietHoursSetNotificationAtEnd() {
setQuietHours(0, 10); setQuietHours(0, 10);
Freeze.freezeAt(new DateTime(2014, 1, 27, 9, 13, 37, 501)); Freeze.freezeAt(new DateTime(2014, 1, 27, 9, 13, 37, 501));
Preferences.setInt(R.string.p_rmd_time, 8 * MILLIS_PER_HOUR); Preferences.setInt(R.string.p_rmd_time, 8 * MILLIS_PER_HOUR);
@ -112,11 +96,10 @@ public class NotifyAtDeadlineTest extends TodorooRobolectricTestCase {
}}; }};
assertEquals( assertEquals(
new DateTime(2014, 1, 27, 10, 0, 0, 0).getMillis(), new DateTime(2014, 1, 27, 10, 0, 0, 0).getMillis(),
service.calculateNextDueDateReminder(task)); reminderService.calculateNextDueDateReminder(task));
} }
@Test public void testAfterQuietHoursSetNotificationOnePeriodCloserToDueDate() {
public void afterQuietHoursSetNotificationOnePeriodCloserToDueDate() {
setQuietHours(0, 10); setQuietHours(0, 10);
Freeze.freezeAt(new DateTime(2014, 1, 27, 11, 13, 37, 501)); Freeze.freezeAt(new DateTime(2014, 1, 27, 11, 13, 37, 501));
Preferences.setInt(R.string.p_rmd_time, 8 * MILLIS_PER_HOUR); Preferences.setInt(R.string.p_rmd_time, 8 * MILLIS_PER_HOUR);
@ -126,11 +109,10 @@ public class NotifyAtDeadlineTest extends TodorooRobolectricTestCase {
}}; }};
assertEquals( assertEquals(
new DateTime(2014, 1, 27, 11, 25, 13, 125).getMillis(), new DateTime(2014, 1, 27, 11, 25, 13, 125).getMillis(),
service.calculateNextDueDateReminder(task)); reminderService.calculateNextDueDateReminder(task));
} }
@Test public void testBeforeQuietStartDueDateMoreThanOnePeriodAfterEnd() {
public void beforeQuietStartDueDateMoreThanOnePeriodAfterEnd() {
setQuietHours(2, 11); setQuietHours(2, 11);
Freeze.freezeAt(new DateTime(2014, 1, 27, 1, 53, 37, 509)); Freeze.freezeAt(new DateTime(2014, 1, 27, 1, 53, 37, 509));
Preferences.setInt(R.string.p_rmd_time, MILLIS_PER_HOUR); Preferences.setInt(R.string.p_rmd_time, MILLIS_PER_HOUR);
@ -140,58 +122,53 @@ public class NotifyAtDeadlineTest extends TodorooRobolectricTestCase {
}}; }};
assertEquals( assertEquals(
new DateTime(2014, 1, 27, 11, 0, 0, 0).getMillis(), new DateTime(2014, 1, 27, 11, 0, 0, 0).getMillis(),
service.calculateNextDueDateReminder(task)); reminderService.calculateNextDueDateReminder(task));
} }
@Test public void testBeforeQuietStartDueDateLessThanOnePeriodAfterEnd() {
public void beforeQuietStartDueDateLessThanOnePeriodAfterEnd() {
setQuietHours(3, 11); setQuietHours(3, 11);
Freeze.freezeAt(new DateTime(2014, 1, 27, 1, 53, 37, 509)); Freeze.freezeAt(new DateTime(2014, 1, 27, 1, 53, 37, 509));
Preferences.setInt(R.string.p_rmd_time, MILLIS_PER_HOUR); Preferences.setInt(R.string.p_rmd_time, MILLIS_PER_HOUR);
assertEquals( assertEquals(
new DateTime(2014, 1, 27, 2, 10, 13, 131).getMillis(), new DateTime(2014, 1, 27, 2, 10, 13, 131).getMillis(),
service.calculateNextDueDateReminder(dueAtNoon)); reminderService.calculateNextDueDateReminder(dueAtNoon));
} }
@Test public void testNoAlarmAfterQuietHoursStartWithWrap() {
public void noAlarmAfterQuietHoursStartWithWrap() {
setQuietHours(10, 1); setQuietHours(10, 1);
Freeze.freezeAt(new DateTime(2014, 1, 27, 10, 0, 0, 0)); Freeze.freezeAt(new DateTime(2014, 1, 27, 10, 0, 0, 0));
Preferences.setInt(R.string.p_rmd_time, 8 * MILLIS_PER_HOUR); Preferences.setInt(R.string.p_rmd_time, 8 * MILLIS_PER_HOUR);
assertEquals( assertEquals(
NO_ALARM, NO_ALARM,
service.calculateNextDueDateReminder(dueAtNoon)); reminderService.calculateNextDueDateReminder(dueAtNoon));
} }
@Test public void testSetToQuietAlarmEndWithWrap() {
public void setToQuietAlarmEndWithWrap() {
setQuietHours(22, 11); setQuietHours(22, 11);
Freeze.freezeAt(new DateTime(2014, 1, 27, 10, 59, 59, 999)); Freeze.freezeAt(new DateTime(2014, 1, 27, 10, 59, 59, 999));
Preferences.setInt(R.string.p_rmd_time, 8 * MILLIS_PER_HOUR); Preferences.setInt(R.string.p_rmd_time, 8 * MILLIS_PER_HOUR);
assertEquals( assertEquals(
new DateTime(2014, 1, 27, 11, 0, 0, 0).getMillis(), new DateTime(2014, 1, 27, 11, 0, 0, 0).getMillis(),
service.calculateNextDueDateReminder(dueAtNoon)); reminderService.calculateNextDueDateReminder(dueAtNoon));
} }
@Test public void testSetReminderOnePeriodFromNowBeforeQuietHourStartWithWrap() {
public void setReminderOnePeriodFromNowBeforeQuietHourStartWithWrap() {
setQuietHours(22, 11); setQuietHours(22, 11);
Freeze.freezeAt(new DateTime(2014, 1, 27, 11, 0, 0, 0)); Freeze.freezeAt(new DateTime(2014, 1, 27, 11, 0, 0, 0));
Preferences.setInt(R.string.p_rmd_time, 8 * MILLIS_PER_HOUR); Preferences.setInt(R.string.p_rmd_time, 8 * MILLIS_PER_HOUR);
assertEquals( assertEquals(
// wtf? this is after due date // wtf? this is after due date
new DateTime(2014, 1, 27, 13, 45, 0, 0).getMillis(), new DateTime(2014, 1, 27, 13, 45, 0, 0).getMillis(),
service.calculateNextDueDateReminder(dueAtNoon)); reminderService.calculateNextDueDateReminder(dueAtNoon));
} }
@Test public void testSetReminderOnePeriodFromNowNoQuietHours() {
public void setReminderOnePeriodFromNowNoQuietHours() {
Freeze.freezeAt(new DateTime(2014, 1, 27, 11, 0, 0, 0)); Freeze.freezeAt(new DateTime(2014, 1, 27, 11, 0, 0, 0));
Preferences.setBoolean(R.string.p_rmd_enable_quiet, false); Preferences.setBoolean(R.string.p_rmd_enable_quiet, false);
Preferences.setInt(R.string.p_rmd_time, 8 * MILLIS_PER_HOUR); Preferences.setInt(R.string.p_rmd_time, 8 * MILLIS_PER_HOUR);
assertEquals( assertEquals(
new DateTime(2014, 1, 27, 11, 15, 0, 0).getMillis(), new DateTime(2014, 1, 27, 11, 15, 0, 0).getMillis(),
service.calculateNextDueDateReminder(dueAtNoon)); reminderService.calculateNextDueDateReminder(dueAtNoon));
} }
private void setQuietHours(int start, int end) { private void setQuietHours(int start, int end) {

@ -5,67 +5,52 @@
*/ */
package com.todoroo.astrid.reminders; package com.todoroo.astrid.reminders;
import android.content.Context;
import com.todoroo.andlib.service.Autowired; import com.todoroo.andlib.service.Autowired;
import com.todoroo.andlib.test.TodorooRobolectricTestCase; import com.todoroo.andlib.test.TodorooTestCase;
import com.todoroo.andlib.utility.DateUtilities; import com.todoroo.andlib.utility.DateUtilities;
import com.todoroo.astrid.dao.TaskDao; import com.todoroo.astrid.dao.TaskDao;
import com.todoroo.astrid.data.Task; import com.todoroo.astrid.data.Task;
import com.todoroo.astrid.reminders.ReminderService.AlarmScheduler; import com.todoroo.astrid.reminders.ReminderService.AlarmScheduler;
import org.junit.After;
import org.junit.Test;
import org.junit.Ignore;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.tasks.Freeze.freezeClock; import static org.tasks.Freeze.freezeClock;
import static org.tasks.Freeze.thaw; import static org.tasks.Freeze.thaw;
import static org.tasks.date.DateTimeUtils.newDate; import static org.tasks.date.DateTimeUtils.newDate;
@RunWith(RobolectricTestRunner.class) public class ReminderServiceTest extends TodorooTestCase {
public class ReminderServiceTest extends TodorooRobolectricTestCase {
ReminderService service;
@Autowired TaskDao taskDao; @Autowired TaskDao taskDao;
@Autowired ReminderService reminderService;
@Override public void setUp() throws Exception {
public void before() { super.setUp();
super.before();
service = ReminderService.getInstance();
freezeClock(); freezeClock();
} }
@After public void tearDown() throws Exception {
public void after() throws Exception {
service.clearInstance();
thaw(); thaw();
} }
@Test
public void testNoReminders() { public void testNoReminders() {
service.setScheduler(new NoAlarmExpected()); reminderService.setScheduler(new NoAlarmExpected());
Task task = new Task(); Task task = new Task();
task.setTitle("water"); task.setTitle("water");
task.setReminderFlags(0); task.setReminderFlags(0);
task.setReminderPeriod(0L); task.setReminderPeriod(0L);
taskDao.save(task); taskDao.save(task);
service.scheduleAlarm(task); reminderService.scheduleAlarm(taskDao, task);
} }
@Test
public void testDueDates() { public void testDueDates() {
service.setScheduler(new AlarmExpected() { reminderService.setScheduler(new AlarmExpected() {
@Override @Override
public void createAlarm(Task task, long time, int type) { public void createAlarm(Context context, Task task, long time, int type) {
if (time == ReminderService.NO_ALARM) if (time == ReminderService.NO_ALARM)
return; return;
super.createAlarm(task, time, type); super.createAlarm(getContext(), task, time, type);
assertEquals((long)task.getDueDate(), time); assertEquals((long) task.getDueDate(), time);
assertEquals(type, ReminderService.TYPE_DUE); assertEquals(type, ReminderService.TYPE_DUE);
} }
}); });
@ -80,40 +65,37 @@ public class ReminderServiceTest extends TodorooRobolectricTestCase {
// test due date in the future // test due date in the future
task.setDueDate(DateUtilities.now() + DateUtilities.ONE_DAY); task.setDueDate(DateUtilities.now() + DateUtilities.ONE_DAY);
taskDao.save(task); taskDao.save(task);
assertTrue(((AlarmExpected)service.getScheduler()).alarmCreated); assertTrue(((AlarmExpected) reminderService.getScheduler()).alarmCreated);
} }
@Test public void disabled_testRandom() {
@Ignore
public void testRandom() {
// test random // test random
final Task task = new Task(); final Task task = new Task();
task.setTitle("water"); task.setTitle("water");
task.setReminderPeriod(DateUtilities.ONE_WEEK); task.setReminderPeriod(DateUtilities.ONE_WEEK);
service.setScheduler(new AlarmExpected() { reminderService.setScheduler(new AlarmExpected() {
@Override @Override
public void createAlarm(Task task, long time, int type) { public void createAlarm(Context context, Task task, long time, int type) {
if (time == ReminderService.NO_ALARM) if (time == ReminderService.NO_ALARM)
return; return;
super.createAlarm(task, time, type); super.createAlarm(getContext(), task, time, type);
assertTrue(time > DateUtilities.now()); assertTrue(time > DateUtilities.now());
assertTrue(time < DateUtilities.now() + 1.2 * DateUtilities.ONE_WEEK); assertTrue(time < DateUtilities.now() + 1.2 * DateUtilities.ONE_WEEK);
assertEquals(type, ReminderService.TYPE_RANDOM); assertEquals(type, ReminderService.TYPE_RANDOM);
} }
}); });
taskDao.save(task); taskDao.save(task);
assertTrue(((AlarmExpected)service.getScheduler()).alarmCreated); assertTrue(((AlarmExpected) reminderService.getScheduler()).alarmCreated);
} }
@Test
public void testOverdue() { public void testOverdue() {
// test due date in the future // test due date in the future
service.setScheduler(new AlarmExpected() { reminderService.setScheduler(new AlarmExpected() {
@Override @Override
public void createAlarm(Task task, long time, int type) { public void createAlarm(Context context, Task task, long time, int type) {
if (time == ReminderService.NO_ALARM) if (time == ReminderService.NO_ALARM)
return; return;
super.createAlarm(task, time, type); super.createAlarm(getContext(), task, time, type);
assertTrue(time > task.getDueDate()); assertTrue(time > task.getDueDate());
assertTrue(time < task.getDueDate() + DateUtilities.ONE_DAY); assertTrue(time < task.getDueDate() + DateUtilities.ONE_DAY);
assertEquals(type, ReminderService.TYPE_OVERDUE); assertEquals(type, ReminderService.TYPE_OVERDUE);
@ -127,38 +109,37 @@ public class ReminderServiceTest extends TodorooRobolectricTestCase {
// test due date in the past // test due date in the past
task.setDueDate(DateUtilities.now() - DateUtilities.ONE_DAY); task.setDueDate(DateUtilities.now() - DateUtilities.ONE_DAY);
service.setScheduler(new AlarmExpected() { reminderService.setScheduler(new AlarmExpected() {
@Override @Override
public void createAlarm(Task task, long time, int type) { public void createAlarm(Context context, Task task, long time, int type) {
if (time == ReminderService.NO_ALARM) if (time == ReminderService.NO_ALARM)
return; return;
super.createAlarm(task, time, type); super.createAlarm(getContext(), task, time, type);
assertTrue(time > DateUtilities.now() - 1000L); assertTrue(time > DateUtilities.now() - 1000L);
assertTrue(time < DateUtilities.now() + 2 * DateUtilities.ONE_DAY); assertTrue(time < DateUtilities.now() + 2 * DateUtilities.ONE_DAY);
assertEquals(type, ReminderService.TYPE_OVERDUE); assertEquals(type, ReminderService.TYPE_OVERDUE);
} }
}); });
taskDao.save(task); taskDao.save(task);
assertTrue(((AlarmExpected)service.getScheduler()).alarmCreated); assertTrue(((AlarmExpected) reminderService.getScheduler()).alarmCreated);
// test due date in the past, but recently notified // test due date in the past, but recently notified
task.setReminderLast(DateUtilities.now()); task.setReminderLast(DateUtilities.now());
service.setScheduler(new AlarmExpected() { reminderService.setScheduler(new AlarmExpected() {
@Override @Override
public void createAlarm(Task task, long time, int type) { public void createAlarm(Context context, Task task, long time, int type) {
if (time == ReminderService.NO_ALARM) if (time == ReminderService.NO_ALARM)
return; return;
super.createAlarm(task, time, type); super.createAlarm(getContext(), task, time, type);
assertTrue(time > DateUtilities.now() + DateUtilities.ONE_HOUR); assertTrue(time > DateUtilities.now() + DateUtilities.ONE_HOUR);
assertTrue(time < DateUtilities.now() + DateUtilities.ONE_DAY); assertTrue(time < DateUtilities.now() + DateUtilities.ONE_DAY);
assertEquals(type, ReminderService.TYPE_OVERDUE); assertEquals(type, ReminderService.TYPE_OVERDUE);
} }
}); });
taskDao.save(task); taskDao.save(task);
assertTrue(((AlarmExpected)service.getScheduler()).alarmCreated); assertTrue(((AlarmExpected) reminderService.getScheduler()).alarmCreated);
} }
@Test
public void testMultipleReminders() { public void testMultipleReminders() {
// test due date in the future, enable random // test due date in the future, enable random
final Task task = new Task(); final Task task = new Task();
@ -166,43 +147,42 @@ public class ReminderServiceTest extends TodorooRobolectricTestCase {
task.setDueDate(DateUtilities.now() + DateUtilities.ONE_WEEK); task.setDueDate(DateUtilities.now() + DateUtilities.ONE_WEEK);
task.setReminderFlags(Task.NOTIFY_AT_DEADLINE); task.setReminderFlags(Task.NOTIFY_AT_DEADLINE);
task.setReminderPeriod(DateUtilities.ONE_HOUR); task.setReminderPeriod(DateUtilities.ONE_HOUR);
service.setScheduler(new AlarmExpected() { reminderService.setScheduler(new AlarmExpected() {
@Override @Override
public void createAlarm(Task task, long time, int type) { public void createAlarm(Context context, Task task, long time, int type) {
if (time == ReminderService.NO_ALARM) if (time == ReminderService.NO_ALARM)
return; return;
super.createAlarm(task, time, type); super.createAlarm(getContext(), task, time, type);
assertTrue(time > DateUtilities.now()); assertTrue(time > DateUtilities.now());
assertTrue(time < DateUtilities.now() + DateUtilities.ONE_DAY); assertTrue(time < DateUtilities.now() + DateUtilities.ONE_DAY);
assertEquals(type, ReminderService.TYPE_RANDOM); assertEquals(type, ReminderService.TYPE_RANDOM);
} }
}); });
taskDao.save(task); taskDao.save(task);
assertTrue(((AlarmExpected)service.getScheduler()).alarmCreated); assertTrue(((AlarmExpected) reminderService.getScheduler()).alarmCreated);
// now set the due date in the past // now set the due date in the past
task.setDueDate(DateUtilities.now() - DateUtilities.ONE_WEEK); task.setDueDate(DateUtilities.now() - DateUtilities.ONE_WEEK);
((AlarmExpected)service.getScheduler()).alarmCreated = false; ((AlarmExpected) reminderService.getScheduler()).alarmCreated = false;
service.scheduleAlarm(task); reminderService.scheduleAlarm(taskDao, task);
assertTrue(((AlarmExpected)service.getScheduler()).alarmCreated); assertTrue(((AlarmExpected) reminderService.getScheduler()).alarmCreated);
// now set the due date before the random // now set the due date before the random
task.setDueDate(DateUtilities.now() + DateUtilities.ONE_HOUR); task.setDueDate(DateUtilities.now() + DateUtilities.ONE_HOUR);
service.setScheduler(new AlarmExpected() { reminderService.setScheduler(new AlarmExpected() {
@Override @Override
public void createAlarm(Task task, long time, int type) { public void createAlarm(Context context, Task task, long time, int type) {
if (time == ReminderService.NO_ALARM) if (time == ReminderService.NO_ALARM)
return; return;
super.createAlarm(task, time, type); super.createAlarm(getContext(), task, time, type);
assertEquals((long)task.getDueDate(), time); assertEquals((long) task.getDueDate(), time);
assertEquals(type, ReminderService.TYPE_DUE); assertEquals(type, ReminderService.TYPE_DUE);
} }
}); });
taskDao.save(task); taskDao.save(task);
assertTrue(((AlarmExpected)service.getScheduler()).alarmCreated); assertTrue(((AlarmExpected) reminderService.getScheduler()).alarmCreated);
} }
@Test
public void testSnoozeReminders() { public void testSnoozeReminders() {
thaw(); // TODO: get rid of this thaw(); // TODO: get rid of this
@ -212,41 +192,41 @@ public class ReminderServiceTest extends TodorooRobolectricTestCase {
task.setDueDate(DateUtilities.now() + 5000L); task.setDueDate(DateUtilities.now() + 5000L);
task.setReminderFlags(Task.NOTIFY_AT_DEADLINE); task.setReminderFlags(Task.NOTIFY_AT_DEADLINE);
task.setReminderSnooze(DateUtilities.now() + DateUtilities.ONE_WEEK); task.setReminderSnooze(DateUtilities.now() + DateUtilities.ONE_WEEK);
service.setScheduler(new AlarmExpected() { reminderService.setScheduler(new AlarmExpected() {
@Override @Override
public void createAlarm(Task task, long time, int type) { public void createAlarm(Context context, Task task, long time, int type) {
if (time == ReminderService.NO_ALARM) if (time == ReminderService.NO_ALARM)
return; return;
super.createAlarm(task, time, type); super.createAlarm(getContext(), task, time, type);
assertTrue(time > DateUtilities.now() + DateUtilities.ONE_WEEK - 1000L); assertTrue(time > DateUtilities.now() + DateUtilities.ONE_WEEK - 1000L);
assertTrue(time < DateUtilities.now() + DateUtilities.ONE_WEEK + 1000L); assertTrue(time < DateUtilities.now() + DateUtilities.ONE_WEEK + 1000L);
assertEquals(type, ReminderService.TYPE_SNOOZE); assertEquals(type, ReminderService.TYPE_SNOOZE);
} }
}); });
taskDao.save(task); taskDao.save(task);
assertTrue(((AlarmExpected)service.getScheduler()).alarmCreated); assertTrue(((AlarmExpected) reminderService.getScheduler()).alarmCreated);
// snooze in the past // snooze in the past
task.setReminderSnooze(DateUtilities.now() - DateUtilities.ONE_WEEK); task.setReminderSnooze(DateUtilities.now() - DateUtilities.ONE_WEEK);
service.setScheduler(new AlarmExpected() { reminderService.setScheduler(new AlarmExpected() {
@Override @Override
public void createAlarm(Task task, long time, int type) { public void createAlarm(Context context, Task task, long time, int type) {
if (time == ReminderService.NO_ALARM) if (time == ReminderService.NO_ALARM)
return; return;
super.createAlarm(task, time, type); super.createAlarm(getContext(), task, time, type);
assertTrue(time > DateUtilities.now() - 1000L); assertTrue(time > DateUtilities.now() - 1000L);
assertTrue(time < DateUtilities.now() + 5000L); assertTrue(time < DateUtilities.now() + 5000L);
assertEquals(type, ReminderService.TYPE_DUE); assertEquals(type, ReminderService.TYPE_DUE);
} }
}); });
taskDao.save(task); taskDao.save(task);
assertTrue(((AlarmExpected)service.getScheduler()).alarmCreated); assertTrue(((AlarmExpected) reminderService.getScheduler()).alarmCreated);
} }
// --- helper classes // --- helper classes
public class NoAlarmExpected implements AlarmScheduler { public class NoAlarmExpected implements AlarmScheduler {
public void createAlarm(Task task, long time, int type) { public void createAlarm(Context context, Task task, long time, int type) {
if(time == 0 || time == Long.MAX_VALUE) if(time == 0 || time == Long.MAX_VALUE)
return; return;
fail("created alarm, no alarm expected (" + type + ": " + newDate(time)); fail("created alarm, no alarm expected (" + type + ": " + newDate(time));
@ -255,7 +235,7 @@ public class ReminderServiceTest extends TodorooRobolectricTestCase {
public class AlarmExpected implements AlarmScheduler { public class AlarmExpected implements AlarmScheduler {
public boolean alarmCreated = false; public boolean alarmCreated = false;
public void createAlarm(Task task, long time, int type) { public void createAlarm(Context context, Task task, long time, int type) {
alarmCreated = true; alarmCreated = true;
} }
} }

@ -9,25 +9,18 @@ import com.google.ical.values.Frequency;
import com.google.ical.values.RRule; import com.google.ical.values.RRule;
import com.google.ical.values.Weekday; import com.google.ical.values.Weekday;
import com.google.ical.values.WeekdayNum; import com.google.ical.values.WeekdayNum;
import com.todoroo.andlib.test.TodorooRobolectricTestCase; import com.todoroo.andlib.test.TodorooTestCase;
import com.todoroo.andlib.utility.DateUtilities; import com.todoroo.andlib.utility.DateUtilities;
import com.todoroo.astrid.data.Task; import com.todoroo.astrid.data.Task;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import java.text.ParseException; import java.text.ParseException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Calendar; import java.util.Calendar;
import java.util.Date; import java.util.Date;
import static org.junit.Assert.assertEquals;
import static org.tasks.date.DateTimeUtils.newDate; import static org.tasks.date.DateTimeUtils.newDate;
@RunWith(RobolectricTestRunner.class) public class AdvancedRepeatTest extends TodorooTestCase {
public class AdvancedRepeatTest extends TodorooRobolectricTestCase {
private static final int PREV_PREV = -2; private static final int PREV_PREV = -2;
private static final int PREV = -1; private static final int PREV = -1;
@ -39,9 +32,9 @@ public class AdvancedRepeatTest extends TodorooRobolectricTestCase {
private long nextDueDate; private long nextDueDate;
private RRule rrule; private RRule rrule;
@Before @Override
public void before() { public void setUp() throws Exception {
super.before(); super.setUp();
task = new Task(); task = new Task();
task.setCompletionDate(DateUtilities.now()); task.setCompletionDate(DateUtilities.now());
rrule = new RRule(); rrule = new RRule();
@ -49,7 +42,6 @@ public class AdvancedRepeatTest extends TodorooRobolectricTestCase {
// --- date with time tests // --- date with time tests
@Test
public void testDueDateSpecificTime() throws ParseException { public void testDueDateSpecificTime() throws ParseException {
buildRRule(1, Frequency.DAILY); buildRRule(1, Frequency.DAILY);
@ -62,7 +54,6 @@ public class AdvancedRepeatTest extends TodorooRobolectricTestCase {
assertDateTimeEquals(nextDayWithTime, nextDueDate); assertDateTimeEquals(nextDayWithTime, nextDueDate);
} }
@Test
public void testCompletionDateSpecificTime() throws ParseException { public void testCompletionDateSpecificTime() throws ParseException {
buildRRule(1, Frequency.DAILY); buildRRule(1, Frequency.DAILY);
@ -85,7 +76,6 @@ public class AdvancedRepeatTest extends TodorooRobolectricTestCase {
// --- due date tests // --- due date tests
/** test multiple days per week - DUE DATE */ /** test multiple days per week - DUE DATE */
@Test
public void testDueDateInPastSingleWeekMultiDay() throws Exception { public void testDueDateInPastSingleWeekMultiDay() throws Exception {
buildRRule(1, Frequency.WEEKLY, Weekday.MO, Weekday.WE, Weekday.FR); buildRRule(1, Frequency.WEEKLY, Weekday.MO, Weekday.WE, Weekday.FR);
@ -103,7 +93,6 @@ public class AdvancedRepeatTest extends TodorooRobolectricTestCase {
} }
/** test single day repeats - DUE DATE */ /** test single day repeats - DUE DATE */
@Test
public void testDueDateSingleDay() throws Exception { public void testDueDateSingleDay() throws Exception {
buildRRule(1, Frequency.WEEKLY, Weekday.MO); buildRRule(1, Frequency.WEEKLY, Weekday.MO);
@ -133,7 +122,6 @@ public class AdvancedRepeatTest extends TodorooRobolectricTestCase {
} }
/** test multiple days per week - DUE DATE */ /** test multiple days per week - DUE DATE */
@Test
public void testDueDateSingleWeekMultiDay() throws Exception { public void testDueDateSingleWeekMultiDay() throws Exception {
buildRRule(1, Frequency.WEEKLY, Weekday.MO, Weekday.WE, Weekday.FR); buildRRule(1, Frequency.WEEKLY, Weekday.MO, Weekday.WE, Weekday.FR);
@ -152,7 +140,6 @@ public class AdvancedRepeatTest extends TodorooRobolectricTestCase {
} }
/** test multiple days per week, multiple intervals - DUE DATE */ /** test multiple days per week, multiple intervals - DUE DATE */
@Test
public void testDueDateMultiWeekMultiDay() throws Exception { public void testDueDateMultiWeekMultiDay() throws Exception {
buildRRule(2, Frequency.WEEKLY, Weekday.MO, Weekday.WE, Weekday.FR); buildRRule(2, Frequency.WEEKLY, Weekday.MO, Weekday.WE, Weekday.FR);
@ -172,7 +159,6 @@ public class AdvancedRepeatTest extends TodorooRobolectricTestCase {
// --- completion tests // --- completion tests
/** test multiple days per week - COMPLETE DATE */ /** test multiple days per week - COMPLETE DATE */
@Test
public void testCompleteDateSingleWeek() throws Exception { public void testCompleteDateSingleWeek() throws Exception {
for(Weekday wday : Weekday.values()) { for(Weekday wday : Weekday.values()) {
buildRRule(1, Frequency.WEEKLY, wday); buildRRule(1, Frequency.WEEKLY, wday);
@ -198,7 +184,6 @@ public class AdvancedRepeatTest extends TodorooRobolectricTestCase {
} }
/** test multiple days per week, multiple intervals - COMPLETE DATE */ /** test multiple days per week, multiple intervals - COMPLETE DATE */
@Test
public void testCompleteDateMultiWeek() throws Exception { public void testCompleteDateMultiWeek() throws Exception {
for(Weekday wday : Weekday.values()) { for(Weekday wday : Weekday.values()) {
buildRRule(2, Frequency.WEEKLY, wday); buildRRule(2, Frequency.WEEKLY, wday);

@ -1,15 +1,13 @@
package com.todoroo.astrid.repeats; package com.todoroo.astrid.repeats;
import android.annotation.SuppressLint; import android.annotation.SuppressLint;
import android.test.AndroidTestCase;
import com.google.ical.values.Frequency; import com.google.ical.values.Frequency;
import com.google.ical.values.RRule; import com.google.ical.values.RRule;
import com.todoroo.astrid.data.Task; import com.todoroo.astrid.data.Task;
import org.joda.time.DateTime; import org.joda.time.DateTime;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import java.text.ParseException; import java.text.ParseException;
@ -23,11 +21,9 @@ import static com.todoroo.astrid.repeats.RepeatTaskCompleteListener.computeNextD
import static java.util.concurrent.TimeUnit.DAYS; import static java.util.concurrent.TimeUnit.DAYS;
import static java.util.concurrent.TimeUnit.HOURS; import static java.util.concurrent.TimeUnit.HOURS;
import static java.util.concurrent.TimeUnit.MINUTES; import static java.util.concurrent.TimeUnit.MINUTES;
import static org.junit.Assert.assertEquals;
@SuppressLint("NewApi") @SuppressLint("NewApi")
@RunWith(RobolectricTestRunner.class) public class RepeatTaskCompleteListenerTest extends AndroidTestCase {
public class RepeatTaskCompleteListenerTest {
private final Task task = new Task(); private final Task task = new Task();
private final long dueDate; private final long dueDate;
@ -40,42 +36,35 @@ public class RepeatTaskCompleteListenerTest {
task.setCompletionDate(completionDate); task.setCompletionDate(completionDate);
} }
@Test public void testMinutelyRepeat() {
public void minutelyRepeat() {
checkFrequency(6, MINUTES.toMillis(1), MINUTELY); checkFrequency(6, MINUTES.toMillis(1), MINUTELY);
} }
@Test public void testHourlyRepeat() {
public void hourlyRepeat() {
checkFrequency(6, HOURS.toMillis(1), HOURLY); checkFrequency(6, HOURS.toMillis(1), HOURLY);
} }
@Test public void testDailyRepeat() {
public void dailyRepeat() {
checkFrequency(6, DAYS.toMillis(1), DAILY); checkFrequency(6, DAYS.toMillis(1), DAILY);
} }
@Test public void testWeeklyRepeat() {
public void weeklyRepeat() {
checkFrequency(6, DAYS.toMillis(7), WEEKLY); checkFrequency(6, DAYS.toMillis(7), WEEKLY);
} }
@Test public void testMonthlyRepeat() {
public void monthlyRepeat() {
assertEquals( assertEquals(
new DateTime(2014, 7, 7, 17, 17, 1, 0).getMillis(), new DateTime(2014, 7, 7, 17, 17, 1, 0).getMillis(),
nextDueDate(6, Frequency.MONTHLY, true)); nextDueDate(6, Frequency.MONTHLY, true));
} }
@Test public void testMonthlyRepeatAtEndOfMonth() {
public void monthlyRepeatAtEndOfMonth() {
assertEquals( assertEquals(
new DateTime(2014, 6, 30, 17, 17, 1, 0).getMillis(), new DateTime(2014, 6, 30, 17, 17, 1, 0).getMillis(),
nextDueDate(6, Frequency.MONTHLY, false)); nextDueDate(6, Frequency.MONTHLY, false));
} }
@Test public void testYearlyRepeat() {
public void yearlyRepeat() {
checkExpected(6, addCalendarMonthsToUnixtime(dueDate, 6 * 12), YEARLY, false); checkExpected(6, addCalendarMonthsToUnixtime(dueDate, 6 * 12), YEARLY, false);
checkExpected(6, addCalendarMonthsToUnixtime(completionDate, 6 * 12), YEARLY, true); checkExpected(6, addCalendarMonthsToUnixtime(completionDate, 6 * 12), YEARLY, true);
} }

@ -25,6 +25,7 @@ import com.todoroo.astrid.gtasks.GtasksScheduler;
import com.todoroo.astrid.gtasks.GtasksTaskListUpdater; import com.todoroo.astrid.gtasks.GtasksTaskListUpdater;
import com.todoroo.astrid.gtasks.sync.GtasksSyncService; import com.todoroo.astrid.gtasks.sync.GtasksSyncService;
import com.todoroo.astrid.gtasks.sync.GtasksSyncV2Provider; import com.todoroo.astrid.gtasks.sync.GtasksSyncV2Provider;
import com.todoroo.astrid.reminders.ReminderService;
import com.todoroo.astrid.tags.TagService; import com.todoroo.astrid.tags.TagService;
import org.tasks.Broadcaster; import org.tasks.Broadcaster;
@ -103,6 +104,7 @@ public class AstridDependencyInjector extends AbstractDependencyInjector {
@Inject GtasksSyncV2Provider gtasksSyncV2Provider; @Inject GtasksSyncV2Provider gtasksSyncV2Provider;
@Inject WidgetHelper widgetHelper; @Inject WidgetHelper widgetHelper;
@Inject GtasksScheduler gtasksScheduler; @Inject GtasksScheduler gtasksScheduler;
@Inject ReminderService reminderService;
/** /**
* Initialize list of injectables. Special care must used when * Initialize list of injectables. Special care must used when
@ -148,6 +150,7 @@ public class AstridDependencyInjector extends AbstractDependencyInjector {
injectables.put("refreshScheduler", refreshScheduler); injectables.put("refreshScheduler", refreshScheduler);
injectables.put("widgetHelper", widgetHelper); injectables.put("widgetHelper", widgetHelper);
injectables.put("gtasksScheduler", gtasksScheduler); injectables.put("gtasksScheduler", gtasksScheduler);
injectables.put("reminderService", reminderService);
} }
/** /**

@ -183,7 +183,6 @@ public class TaskAdapter extends CursorAdapter implements Filterable {
protected final int resource; protected final int resource;
protected final LayoutInflater inflater; protected final LayoutInflater inflater;
private int fontSize; private int fontSize;
private long mostRecentlyMade = -1;
private final ScaleAnimation scaleAnimation; private final ScaleAnimation scaleAnimation;
private final AtomicReference<String> query; private final AtomicReference<String> query;
@ -397,8 +396,6 @@ public class TaskAdapter extends CursorAdapter implements Filterable {
public String tagsString; // From join query, not part of the task model public String tagsString; // From join query, not part of the task model
public boolean hasFiles; // From join query, not part of the task model public boolean hasFiles; // From join query, not part of the task model
public boolean hasNotes; public boolean hasNotes;
public View[] decorations;
} }
/** Helper method to set the contents and visibility of each field */ /** Helper method to set the contents and visibility of each field */
@ -472,11 +469,6 @@ public class TaskAdapter extends CursorAdapter implements Filterable {
taskAction.setTag(null); taskAction.setTag(null);
} }
} }
if(Math.abs(DateUtilities.now() - task.getModificationDate()) < 2000L) {
mostRecentlyMade = task.getId();
}
} }
private TaskAction getTaskAction(Task task, boolean hasFiles, boolean hasNotes) { private TaskAction getTaskAction(Task task, boolean hasFiles, boolean hasNotes) {

@ -64,7 +64,7 @@ public class BackupService extends Service {
/** /**
* Test hook for backup * Test hook for backup
*/ */
public void testBackup(Context context) { void testBackup(Context context) {
startBackup(context); startBackup(context);
} }
@ -160,7 +160,7 @@ public class BackupService extends Service {
} }
}; };
public void setBackupDirectorySetting( void setBackupDirectorySetting(
BackupDirectorySetting backupDirectorySetting) { BackupDirectorySetting backupDirectorySetting) {
this.backupDirectorySetting = backupDirectorySetting; this.backupDirectorySetting = backupDirectorySetting;
} }

@ -22,8 +22,6 @@ import com.todoroo.andlib.utility.Preferences;
import org.tasks.R; import org.tasks.R;
import java.util.Date;
import static org.tasks.date.DateTimeUtils.newDate; import static org.tasks.date.DateTimeUtils.newDate;
public class PhoneStateChangedReceiver extends BroadcastReceiver { public class PhoneStateChangedReceiver extends BroadcastReceiver {

@ -198,7 +198,7 @@ public class FilesControlSet extends PopupControlSet {
if (fileType.startsWith(TaskAttachment.FILE_TYPE_AUDIO)) { if (fileType.startsWith(TaskAttachment.FILE_TYPE_AUDIO)) {
RecognizerApi.play(m.getFilePath(), new PlaybackExceptionHandler() { RecognizerApi.play(m.getFilePath(), new PlaybackExceptionHandler() {
@Override @Override
public void playbackFailed(String file) { public void playbackFailed() {
showFromIntent(filePath, fileType); showFromIntent(filePath, fileType);
} }
}); });

@ -107,7 +107,7 @@ public class GtasksTaskListUpdater extends OrderedMetadataListUpdater<StoreObjec
/** /**
* Create a local tree of tasks to expedite sibling and parent lookups * Create a local tree of tasks to expedite sibling and parent lookups
*/ */
public void createParentSiblingMaps() { void createParentSiblingMaps() {
for(StoreObject list : gtasksListService.getLists()) { for(StoreObject list : gtasksListService.getLists()) {
updateParentSiblingMapsFor(list); updateParentSiblingMapsFor(list);
} }

@ -10,7 +10,6 @@ import android.text.TextUtils;
import java.io.IOException; import java.io.IOException;
public class GoogleTasksException extends IOException { public class GoogleTasksException extends IOException {
private static final long serialVersionUID = -5585448790574862510L;
private String type; private String type;

@ -492,12 +492,12 @@ public class Notifications extends InjectingBroadcastReceiver {
// --- notification manager // --- notification manager
public static void setNotificationManager( static void setNotificationManager(
NotificationManager notificationManager) { NotificationManager notificationManager) {
Notifications.notificationManager = notificationManager; Notifications.notificationManager = notificationManager;
} }
public static void forceNotificationManager() { static void forceNotificationManager() {
forceNotificationManager = true; forceNotificationManager = true;
} }

@ -47,7 +47,7 @@ public abstract class AstridOrderedListUpdater<LIST> {
private final HashMap<String, Node> idToNode; private final HashMap<String, Node> idToNode;
protected abstract String getSerializedTree(LIST list, Filter filter); protected abstract String getSerializedTree(LIST list);
protected abstract void writeSerialization(LIST list, String serialized, boolean shouldQueueSync); protected abstract void writeSerialization(LIST list, String serialized, boolean shouldQueueSync);
protected abstract void applyToFilter(Filter filter); protected abstract void applyToFilter(Filter filter);
@ -60,7 +60,7 @@ public abstract class AstridOrderedListUpdater<LIST> {
} }
public void initialize(LIST list, Filter filter) { public void initialize(LIST list, Filter filter) {
initializeFromSerializedTree(list, filter, getSerializedTree(list, filter)); initializeFromSerializedTree(list, filter, getSerializedTree(list));
} }
public void initializeFromSerializedTree(LIST list, Filter filter, String serializedTree) { public void initializeFromSerializedTree(LIST list, Filter filter, String serializedTree) {
@ -130,7 +130,7 @@ public abstract class AstridOrderedListUpdater<LIST> {
} }
} }
public Node findNodeForTask(String taskId) { Node findNodeForTask(String taskId) {
return idToNode.get(taskId); return idToNode.get(taskId);
} }

@ -2,7 +2,6 @@ package com.todoroo.astrid.subtasks;
import android.text.TextUtils; import android.text.TextUtils;
import com.todoroo.astrid.api.Filter;
import com.todoroo.astrid.dao.TaskListMetadataDao; import com.todoroo.astrid.dao.TaskListMetadataDao;
import com.todoroo.astrid.data.SyncFlags; import com.todoroo.astrid.data.SyncFlags;
import com.todoroo.astrid.data.TaskListMetadata; import com.todoroo.astrid.data.TaskListMetadata;
@ -22,7 +21,7 @@ public class SubtasksFilterUpdater extends SubtasksUpdater<TaskListMetadata> {
} }
@Override @Override
protected String getSerializedTree(TaskListMetadata list, Filter filter) { protected String getSerializedTree(TaskListMetadata list) {
if (list == null) { if (list == null) {
return "[]"; //$NON-NLS-1$ return "[]"; //$NON-NLS-1$
} }

@ -21,7 +21,7 @@ import java.util.ArrayList;
public class RecognizerApi implements RecognitionListener { public class RecognizerApi implements RecognitionListener {
public static interface PlaybackExceptionHandler { public static interface PlaybackExceptionHandler {
public void playbackFailed(String file); public void playbackFailed();
} }
private Context context; private Context context;
@ -52,7 +52,7 @@ public class RecognizerApi implements RecognitionListener {
mediaPlayer.prepare(); mediaPlayer.prepare();
mediaPlayer.start(); mediaPlayer.start();
} catch (Exception e) { } catch (Exception e) {
handler.playbackFailed(file); handler.playbackFailed();
} }
} }

@ -1,249 +0,0 @@
/**
* Copyright (c) 2012 Todoroo Inc
*
* See the file "LICENSE" for the full license governing this code.
*/
package com.todoroo.andlib.service;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import java.lang.reflect.Field;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;
@RunWith(RobolectricTestRunner.class)
public class DependencyInjectionTest {
@Test
public void testNoAutowire() {
DependencyInjectionService service = new DependencyInjectionService();
Object test = new Object();
service.inject(test);
}
@Test
public void testSimpleStringInjectionAutowire() {
DependencyInjectionService service = new DependencyInjectionService();
service.addInjector(
new AbstractDependencyInjector() {
@Override
public Object getInjection(Field field) {
if(field.getName().equals("foo"))
return "bar";
return null;
}
}
);
// test various permissions
Object test = new Object() {
@Autowired public String foo;
@Override
public String toString() {
return foo;
}
};
service.inject(test);
assertEquals("bar", test.toString());
test = new Object() {
@Autowired String foo;
@Override
public String toString() {
return foo;
}
};
service.inject(test);
assertEquals("bar", test.toString());
test = new Object() {
@Autowired protected String foo;
@Override
public String toString() {
return foo;
}
};
service.inject(test);
assertEquals("bar", test.toString());
test = new Object() {
@Autowired private String foo;
@Override
public String toString() {
return foo;
}
};
service.inject(test);
assertEquals("bar", test.toString());
// test no annotation
test = new Object() {
public String foo;
@Override
public String toString() {
return foo;
}
};
service.inject(test);
assertNull( test.toString());
}
@Test
public void testHierarchicalStringInjectionAutowire() {
DependencyInjectionService service = new DependencyInjectionService();
service.addInjector(
new AbstractDependencyInjector() {
@Override
public Object getInjection(Field field) {
return "malarkey";
}
}
);
service.addInjector(
new AbstractDependencyInjector() {
@Override
public Object getInjection(Field field) {
if(field.getName().equals("foo"))
return "bar";
return null;
}
});
Object test = new Object() {
@Autowired public String foo;
@Override
public String toString() {
return foo;
}
};
service.inject(test);
assertEquals("bar", test.toString());
test = new Object() {
@Autowired public String forks;
@Override
public String toString() {
return forks;
}
};
service.inject(test);
assertEquals("malarkey", test.toString());
}
@Test
public void testMissingInjection() {
DependencyInjectionService service = new DependencyInjectionService();
service.addInjector(
new AbstractDependencyInjector() {
@Override
public Object getInjection(Field field) {
if(field.getName().equals("wozzle"))
return "bar";
return null;
}
}
);
Object test = new Object() {
@Autowired public String foo;
@Override
public String toString() {
return foo;
}
};
try {
service.inject(test);
fail("could inject with missing injector");
} catch (RuntimeException e) {
// expected
}
assertNull(test.toString());
}
@Test
public void testMultipleInjection() {
DependencyInjectionService service = new DependencyInjectionService();
service.addInjector(
new AbstractDependencyInjector() {
@Override
public Object getInjection(Field field) {
if(field.getName().equals("foo"))
return "bar";
return null;
}
}
);
Object test1 = new Object() {
@Autowired public String foo;
@Override
public String toString() {
return foo;
}
};
Object test2 = new Object() {
@Autowired public String foo;
@Override
public String toString() {
return foo;
}
};
service.inject(test1);
service.inject(test2);
assertEquals("bar", test1.toString());
assertEquals("bar", test2.toString());
}
public static class ParentInjectee {
@Autowired protected String foo;
}
public static class ChildInjectee extends ParentInjectee {
@Autowired protected String bar;
}
@Test
public void testInheritedInjection() {
DependencyInjectionService service = new DependencyInjectionService();
service.addInjector(
new AbstractDependencyInjector() {
@Override
public Object getInjection(Field field) {
if(field.getName().equals("foo"))
return "gotfoo";
else if(field.getName().equals("bar"))
return "hasbar";
return null;
}
}
);
ChildInjectee child = new ChildInjectee();
service.inject(child);
assertEquals("gotfoo", child.foo);
assertEquals("hasbar", child.bar);
}
}

@ -1,30 +0,0 @@
package com.todoroo.andlib.service;
public class RobolectricTestDependencyInjector extends AbstractDependencyInjector {
private String name;
public RobolectricTestDependencyInjector(String name) {
this.name = name;
}
public void addInjectable(String field, Object injection) {
injectables.put(field, injection);
}
@Override
public String toString() {
return "TestDI:" + name;
}
// --- static stuff
/**
* Install TestDependencyInjector above other injectors
*/
public synchronized static RobolectricTestDependencyInjector initialize(String name) {
RobolectricTestDependencyInjector instance = new RobolectricTestDependencyInjector(name);
DependencyInjectionService.getInstance().addInjector(instance);
return instance;
}
}

@ -1,117 +0,0 @@
/**
* Copyright (c) 2012 Todoroo Inc
*
* See the file "LICENSE" for the full license governing this code.
*/
package com.todoroo.andlib.sql;
import com.todoroo.andlib.sql.Query.QueryTemplateHelper;
import com.todoroo.astrid.dao.TaskDao.TaskCriteria;
import com.todoroo.astrid.data.Task;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import static org.junit.Assert.assertEquals;
@RunWith(RobolectricTestRunner.class)
public class QueryTemplateHelperTest {
public StringBuilder selection = new StringBuilder();
public StringBuilder order = new StringBuilder();
public StringBuilder groupBy = new StringBuilder();
@Test
public void testBasic() {
QueryTemplateHelper.queryForContentResolver("",
selection, order, groupBy);
assertEquals(selection.toString(), "");
assertEquals(order.toString(), "");
assertEquals(groupBy.toString(), "");
}
@Test
public void testSelection() {
QueryTemplateHelper.queryForContentResolver("WHERE foo = bar",
selection, order, groupBy);
assertEquals(selection.toString(), "foo = bar");
assertEquals(order.toString(), "");
assertEquals(groupBy.toString(), "");
}
@Test
public void testOrder() {
QueryTemplateHelper.queryForContentResolver("ORDER BY cats",
selection, order, groupBy);
assertEquals(selection.toString(), "");
assertEquals(order.toString(), "cats");
assertEquals(groupBy.toString(), "");
}
@Test
public void testWhereOrder() {
QueryTemplateHelper.queryForContentResolver("WHERE foo = bar ORDER BY cats",
selection, order, groupBy);
assertEquals(selection.toString(), "foo = bar");
assertEquals(order.toString(), "cats");
assertEquals(groupBy.toString(), "");
}
@Test
public void testGroupBy() {
QueryTemplateHelper.queryForContentResolver("GROUP BY dogs",
selection, order, groupBy);
assertEquals(selection.toString(), "");
assertEquals(order.toString(), "");
assertEquals(groupBy.toString(), "dogs");
}
@Test
public void testWhereGroupBy() {
QueryTemplateHelper.queryForContentResolver("WHERE foo = bar GROUP BY dogs",
selection, order, groupBy);
assertEquals(selection.toString(), "foo = bar");
assertEquals(order.toString(), "");
assertEquals(groupBy.toString(), "dogs");
}
@Test
public void testOrderGroupBy() {
QueryTemplateHelper.queryForContentResolver("GROUP BY dogs ORDER BY cats",
selection, order, groupBy);
assertEquals(order.toString(), "cats");
assertEquals(groupBy.toString(), "dogs");
}
@Test
public void testWhereGroupByAndOrder() {
QueryTemplateHelper.queryForContentResolver("WHERE foo = bar GROUP BY dogs ORDER BY cats",
selection, order, groupBy);
assertEquals(selection.toString(), "foo = bar");
assertEquals(order.toString(), "cats");
assertEquals(groupBy.toString(), "dogs");
}
@Test
public void testRealQueryTemplate() {
QueryTemplateHelper.queryForContentResolver(
new QueryTemplate().where(TaskCriteria.completed()).
orderBy(Order.asc(Task.DUE_DATE)).toString(),
selection, order, groupBy);
assertEquals(TaskCriteria.completed().toString(), selection.toString());
assertEquals(Order.asc(Task.DUE_DATE).toString(), order.toString());
assertEquals("", groupBy.toString());
}
@Test
public void testRealQueryTemplateTwo() {
QueryTemplateHelper.queryForContentResolver(
new QueryTemplate().where(TaskCriteria.isActive()).
orderBy(Order.asc(Task.ELAPSED_SECONDS)).groupBy(Task.NOTES).toString(),
selection, order, groupBy);
assertEquals(TaskCriteria.isActive().toString(), selection.toString());
assertEquals(Order.asc(Task.ELAPSED_SECONDS).toString(), order.toString());
assertEquals(Task.NOTES.toString(), groupBy.toString());
}
}

@ -1,59 +0,0 @@
/**
* Copyright (c) 2012 Todoroo Inc
*
* See the file "LICENSE" for the full license governing this code.
*/
package com.todoroo.andlib.test;
import android.content.Context;
import android.content.res.Configuration;
import android.util.DisplayMetrics;
import com.todoroo.andlib.service.ContextManager;
import com.todoroo.andlib.service.DependencyInjectionService;
import com.todoroo.andlib.service.RobolectricTestDependencyInjector;
import com.todoroo.astrid.service.AstridDependencyInjector;
import org.junit.Before;
import org.robolectric.Robolectric;
import org.tasks.Broadcaster;
import java.util.Locale;
import static org.mockito.Mockito.mock;
import static org.tasks.TestUtilities.resetPreferences;
public class TodorooRobolectricTestCase {
private RobolectricTestDependencyInjector testInjector;
protected <T> T addInjectable(String name, T object) {
testInjector.addInjectable(name, object);
return object;
}
@Before
public void before() {
ContextManager.setContext(getRobolectricContext());
resetPreferences();
AstridDependencyInjector.reset();
testInjector = RobolectricTestDependencyInjector.initialize("test");
addInjectable("broadcaster", mock(Broadcaster.class));
DependencyInjectionService.getInstance().inject(this);
}
/**
* Sets locale
*/
private static void setLocale(Locale locale) {
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
DisplayMetrics metrics = getRobolectricContext().getResources().getDisplayMetrics();
getRobolectricContext().getResources().updateConfiguration(config, metrics);
}
public static Context getRobolectricContext() {
return Robolectric.getShadowApplication().getApplicationContext();
}
}

@ -1,120 +0,0 @@
package com.todoroo.astrid.gtasks;
import android.content.Context;
import android.content.Intent;
import com.google.api.services.tasks.model.TaskList;
import com.todoroo.andlib.service.Autowired;
import com.todoroo.andlib.test.TodorooRobolectricTestCase;
import com.todoroo.astrid.api.AstridApiConstants;
import com.todoroo.astrid.data.Metadata;
import com.todoroo.astrid.data.Task;
import com.todoroo.astrid.service.MetadataService;
import com.todoroo.astrid.service.TaskService;
import org.junit.After;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
@RunWith(RobolectricTestRunner.class)
public class GtasksDetailExposerTest extends TodorooRobolectricTestCase {
private Context context;
private RobolectricGtasksPreferenceService gtasksPreferenceService;
@Autowired private GtasksListService gtasksListService;
@Override
public void before() {
context = mock(Context.class);
super.before();
gtasksPreferenceService = addInjectable("gtasksPreferenceService", new RobolectricGtasksPreferenceService());
gtasksListService.addNewList(
new TaskList().setId("list_id").setTitle("list_title"));
}
@After
public void after() throws Exception {
verify(context).getApplicationContext();
verifyNoMoreInteractions(context);
}
@Test
public void dontBroadcastDetailsWhenNotLoggedIn() {
gtasksPreferenceService.logout();
getDetails(newTask("list_id"));
}
@Test
public void dontBroadcastDetailsForInvalidTaskId() {
getDetails(0);
}
@Test
public void dontBroadcastDetailsWithNoList() {
getDetails(newTask());
}
@Test
public void dontBroadcastDetailsWithNullList() {
getDetails(newTask(null));
}
@Test
public void dontBroadcastDetailsWithDefaultList() {
getDetails(newTask(GtasksPreferenceService.PREF_DEFAULT_LIST));
}
@Test
public void dontBroadcastDetailsForNonexistentList() {
getDetails(newTask("invalid_list_id"));
}
@Test
public void broadcastDetails() {
Task task = newTask("list_id");
getDetails(task);
verify(context).sendBroadcast(
new Intent(AstridApiConstants.BROADCAST_SEND_DETAILS)
.putExtra(AstridApiConstants.EXTRAS_ADDON, GtasksPreferenceService.IDENTIFIER)
.putExtra(AstridApiConstants.EXTRAS_TASK_ID, task.getId())
.putExtra(AstridApiConstants.EXTRAS_RESPONSE, "<img src='gtasks_detail'/> list_title"),
AstridApiConstants.PERMISSION_READ);
}
private void getDetails(Task task) {
getDetails(task.getId());
}
private void getDetails(long taskId) {
Intent intent = new Intent().putExtra(AstridApiConstants.EXTRAS_TASK_ID, taskId);
new GtasksDetailExposer().onReceive(context, intent);
}
private Task newTask() {
Task task = new Task();
new TaskService().save(task);
Metadata metadata = GtasksMetadata.createEmptyMetadata(task.getId());
new MetadataService().save(metadata);
return task;
}
private Task newTask(String list) {
Task task = new Task();
new TaskService().save(task);
Metadata metadata = GtasksMetadata.createEmptyMetadata(task.getId());
metadata.setValue(GtasksMetadata.LIST_ID, list);
new MetadataService().save(metadata);
return task;
}
}

@ -1,17 +0,0 @@
package com.todoroo.astrid.gtasks;
public class RobolectricGtasksPreferenceService extends GtasksPreferenceService {
public RobolectricGtasksPreferenceService() {
setToken("");
}
@Override
public String getIdentifier() {
return "test";
}
public void logout() {
setToken(null);
}
}

@ -1,79 +0,0 @@
/**
* Copyright (c) 2012 Todoroo Inc
*
* See the file "LICENSE" for the full license governing this code.
*/
package com.todoroo.astrid.service;
import com.todoroo.andlib.service.Autowired;
import com.todoroo.andlib.service.DependencyInjectionService;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import static org.junit.Assert.assertTrue;
@RunWith(RobolectricTestRunner.class)
public class AstridDependencyInjectorTest {
protected static class Helper {
public Object getObject() {
return null;
}
}
@Before
public void setUp() throws Exception {
// in case some state from other unit tests overwrote injector
DependencyInjectionService.getInstance().addInjector(
new AstridDependencyInjector()
);
}
@Test
public void testWithString() {
Helper helper = new Helper() {
@Autowired public String applicationName;
@Override
public Object getObject() {
return applicationName;
};
};
DependencyInjectionService.getInstance().inject(helper);
assertTrue(((String)helper.getObject()).length() > 0);
}
@Test
public void testWithClass() {
Helper helper = new Helper() {
@Autowired public TaskService taskService;
@Override
public Object getObject() {
return taskService;
};
};
DependencyInjectionService.getInstance().inject(helper);
assertTrue(helper.getObject() instanceof TaskService);
Helper helper2 = new Helper() {
@Autowired public TaskService taskService;
@Override
public Object getObject() {
return taskService;
};
};
DependencyInjectionService.getInstance().inject(helper2);
assertTrue(helper.getObject() == helper2.getObject());
}
}
Loading…
Cancel
Save