Clean up kotlin code

* static imports
* less nullable types
* format
pull/709/head
Quentin Hibon 5 years ago
parent 9d0fbb9ea9
commit dedeb13f46

@ -125,6 +125,7 @@ dependencies {
testImplementation "junit:junit:4.12"
testImplementation "org.mockito:mockito-core:2.28.2"
testImplementation "org.mockito:mockito-inline:2.8.9"
testImplementation "com.nhaarman.mockitokotlin2:mockito-kotlin:2.2.0"
}
kapt {

@ -38,19 +38,13 @@ import org.mockito.Mockito.mock
@Module
class TestModule {
@Provides fun ListHabitsBehavior() = mock(ListHabitsBehavior::class.java)
@Provides fun listHabitsBehavior(): ListHabitsBehavior = mock(ListHabitsBehavior::class.java)
}
@ActivityScope
@Component(
modules = arrayOf(
ActivityContextModule::class,
HabitsActivityModule::class,
ListHabitsModule::class,
HabitModule::class,
TestModule::class
),
dependencies = arrayOf(HabitsApplicationComponent::class)
modules = [ActivityContextModule::class, HabitsActivityModule::class, ListHabitsModule::class, HabitModule::class, TestModule::class],
dependencies = [HabitsApplicationComponent::class]
)
interface HabitsActivityTestComponent {
fun getCheckmarkPanelViewFactory(): CheckmarkPanelViewFactory

@ -25,7 +25,8 @@ import androidx.test.espresso.UiController
import androidx.test.espresso.ViewAction
import androidx.test.espresso.action.ViewActions
import androidx.test.espresso.matcher.ViewMatchers
import org.hamcrest.CoreMatchers
import org.hamcrest.CoreMatchers.allOf
import org.hamcrest.CoreMatchers.endsWith
import org.hamcrest.Matcher
import org.isoron.uhabits.BaseUserInterfaceTest
import org.isoron.uhabits.R
@ -56,12 +57,12 @@ object ListHabitsSteps {
private fun clickTextInsideOverflowMenu(id: Int) {
Espresso.onView(
CoreMatchers.allOf(
allOf(
ViewMatchers.withContentDescription("More options"),
ViewMatchers.withParent(
ViewMatchers.withParent(
ViewMatchers.withClassName(
CoreMatchers.endsWith("Toolbar")
endsWith("Toolbar")
)
)
)
@ -107,9 +108,9 @@ object ListHabitsSteps {
fun longPressCheckmarks(habit: String?, count: Int) {
CommonSteps.scrollToText(habit)
Espresso.onView(
CoreMatchers.allOf(
allOf(
ViewMatchers.hasDescendant(ViewMatchers.withText(habit)),
ViewMatchers.withClassName(CoreMatchers.endsWith("HabitCardView"))
ViewMatchers.withClassName(endsWith("HabitCardView"))
)
).perform(
longClickDescendantWithClass(CheckmarkButtonView::class.java, count)

@ -28,8 +28,8 @@ import org.isoron.uhabits.BaseUserInterfaceTest
object WidgetSteps {
@Throws(Exception::class)
fun clickCheckmarkWidget() {
val view_id = "org.isoron.uhabits:id/imageView"
BaseUserInterfaceTest.device.findObject(UiSelector().resourceId(view_id)).click()
val viewId = "org.isoron.uhabits:id/imageView"
BaseUserInterfaceTest.device.findObject(UiSelector().resourceId(viewId)).click()
}
@Throws(Exception::class)
@ -66,7 +66,7 @@ object WidgetSteps {
BaseUserInterfaceTest.device.findObject(UiSelector().description("Apps")).click()
BaseUserInterfaceTest.device.findObject(UiSelector().description("Widgets")).click()
} else {
val list_id = "com.android.launcher3:id/widgets_list_view"
val listId = "com.android.launcher3:id/widgets_list_view"
BaseUserInterfaceTest.device.pressHome()
BaseUserInterfaceTest.device.waitForIdle()
BaseUserInterfaceTest.device.drag(w / 2, h / 2, w / 2, h / 2, 8)
@ -76,10 +76,10 @@ object WidgetSteps {
}
button.click()
if (VERSION.SDK_INT >= 28) {
UiScrollable(UiSelector().resourceId(list_id))
UiScrollable(UiSelector().resourceId(listId))
.scrollForward()
}
UiScrollable(UiSelector().resourceId(list_id))
UiScrollable(UiSelector().resourceId(listId))
.scrollIntoView(UiSelector().text("Checkmark"))
}
}

@ -34,11 +34,12 @@ import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
private const val PATH = "habits/list/CheckmarkPanelView"
@RunWith(AndroidJUnit4::class)
@MediumTest
class EntryPanelViewTest : BaseViewTest() {
private val PATH = "habits/list/CheckmarkPanelView"
private lateinit var view: CheckmarkPanelView
@Before
@ -75,27 +76,6 @@ class EntryPanelViewTest : BaseViewTest() {
assertRenders(view, "$PATH/render.png")
}
// // Flaky test
// @Test
// fun testRender_withDifferentColor() {
// view.color = PaletteUtils.getAndroidTestColor(1)
// assertRenders(view, "$PATH/render_different_color.png")
// }
// // Flaky test
// @Test
// fun testRender_Reversed() {
// prefs.isCheckmarkSequenceReversed = true
// assertRenders(view, "$PATH/render_reversed.png")
// }
// // Flaky test
// @Test
// fun testRender_withOffset() {
// view.dataOffset = 3
// assertRenders(view, "$PATH/render_offset.png")
// }
@Test
fun testToggle() {
val timestamps = mutableListOf<Timestamp>()

@ -56,7 +56,7 @@ class HabitCardViewTest : BaseViewTest() {
view = component.getHabitCardViewFactory().create().apply {
habit = habit1
values = entries
score = habit1.scores.get(today).value
score = habit1.scores[today].value
isSelected = false
buttonCount = 5
}

@ -73,27 +73,6 @@ class NumberPanelViewTest : BaseViewTest() {
assertRenders(view, "$PATH/render.png")
}
// // Flaky test
// @Test
// fun testRender_withDifferentColor() {
// view.color = PaletteUtils.getAndroidTestColor(1)
// assertRenders(view, "$PATH/render_different_color.png")
// }
// // Flaky test
// @Test
// fun testRender_Reversed() {
// prefs.isCheckmarkSequenceReversed = true
// assertRenders(view, "$PATH/render_reversed.png")
// }
// // Flaky test
// @Test
// fun testRender_withOffset() {
// view.dataOffset = 3
// assertRenders(view, "$PATH/render_offset.png")
// }
@Test
fun testEdit() {
val timestamps = mutableListOf<Timestamp>()

@ -103,9 +103,8 @@ class IntentSchedulerTest : BaseAndroidTest() {
assertNull(ReminderReceiver.lastReceivedIntent)
setSystemTime("America/Chicago", 2020, JUNE, 2, 22, 46)
val intent = ReminderReceiver.lastReceivedIntent
assertNotNull(intent)
assertThat(parseId(intent?.data!!), equalTo(habit.id))
val intent = ReminderReceiver.lastReceivedIntent!!
assertThat(parseId(intent.data!!), equalTo(habit.id))
}
@Test
@ -123,7 +122,6 @@ class IntentSchedulerTest : BaseAndroidTest() {
assertNull(WidgetReceiver.lastReceivedIntent)
setSystemTime("America/Chicago", 2020, JUNE, 2, 22, 46)
val intent = WidgetReceiver.lastReceivedIntent
assertNotNull(intent)
WidgetReceiver.lastReceivedIntent!!
}
}

@ -68,13 +68,6 @@ public class CheckmarkWidgetViewTest extends BaseViewTest
assertRenders(view, PATH + "checked.png");
}
// @Test
// public void testRender_implicitlyChecked() throws IOException
// {
// view.setCheckmarkValue(Checkmark.YES_AUTO);
// view.refresh();
// assertRenders(view, PATH + "implicitly_checked.png");
// }
@Test
public void testRender_largeSize() throws IOException
@ -83,11 +76,4 @@ public class CheckmarkWidgetViewTest extends BaseViewTest
assertRenders(view, PATH + "large_size.png");
}
// @Test
// public void testRender_unchecked() throws IOException
// {
// view.setCheckmarkValue(Checkmark.NO);
// view.refresh();
// assertRenders(view, PATH + "unchecked.png");
// }
}

@ -25,6 +25,8 @@ import android.util.AttributeSet
import android.view.GestureDetector
import android.view.MotionEvent
import android.widget.Scroller
import kotlin.math.abs
import kotlin.math.max
/**
* An AndroidView that implements scrolling.
@ -71,7 +73,7 @@ class AndroidDataView(
dx: Float,
dy: Float,
): Boolean {
if (Math.abs(dx) > Math.abs(dy)) {
if (abs(dx) > abs(dy)) {
val parent = parent
parent?.requestDisallowInterceptTouchEvent(true)
}
@ -128,7 +130,7 @@ class AndroidDataView(
view?.let { v ->
var newDataOffset: Int =
scroller.currX / (v.dataColumnWidth * canvas.innerDensity).toInt()
newDataOffset = Math.max(0, newDataOffset)
newDataOffset = max(0, newDataOffset)
if (newDataOffset != v.dataOffset) {
v.dataOffset = newDataOffset
postInvalidate()

@ -42,7 +42,7 @@ class AndroidImage(private val bmp: Bitmap) : Image {
}
}
public fun Color.toInt(): Int {
fun Color.toInt(): Int {
return android.graphics.Color.argb(
(255 * this.alpha).roundToInt(),
(255 * this.red).roundToInt(),

@ -83,7 +83,7 @@ class HabitsApplication : Application() {
notificationTray.startListening()
val prefs = component.preferences
prefs.setLastAppVersion(BuildConfig.VERSION_CODE)
prefs.lastAppVersion = BuildConfig.VERSION_CODE
val taskRunner = component.taskRunner
taskRunner.execute {
@ -106,11 +106,11 @@ class HabitsApplication : Application() {
lateinit var component: HabitsApplicationComponent
fun isTestMode(): Boolean {
try {
return try {
Class.forName("org.isoron.uhabits.BaseAndroidTest")
return true
true
} catch (e: ClassNotFoundException) {
return false
false
}
}
}

@ -34,6 +34,7 @@ import org.isoron.uhabits.core.ui.screens.habits.list.ListHabitsBehavior
import org.isoron.uhabits.inject.ActivityContext
import org.isoron.uhabits.utils.InterfaceUtils
import javax.inject.Inject
import kotlin.math.roundToLong
class NumberPickerFactory
@Inject constructor(
@ -52,7 +53,7 @@ class NumberPickerFactory
val picker2 = view.findViewById<NumberPicker>(R.id.picker2)
val tvUnit = view.findViewById<TextView>(R.id.tvUnit)
val intValue = Math.round(value * 100).toInt()
val intValue = (value * 100).roundToLong().toInt()
picker.minValue = 0
picker.maxValue = Integer.MAX_VALUE / 100
@ -86,13 +87,12 @@ class NumberPickerFactory
}
InterfaceUtils.setupEditorAction(
picker,
TextView.OnEditorActionListener { _, actionId, _ ->
if (actionId == EditorInfo.IME_ACTION_DONE)
dialog.getButton(DialogInterface.BUTTON_POSITIVE).performClick()
false
}
)
picker
) { _, actionId, _ ->
if (actionId == EditorInfo.IME_ACTION_DONE)
dialog.getButton(DialogInterface.BUTTON_POSITIVE).performClick()
false
}
return dialog
}

@ -56,8 +56,7 @@ class TaskProgressBar(
fun update() {
val callback = {
val activeTaskCount = runner.activeTaskCount
val newVisibility = when (activeTaskCount) {
val newVisibility = when (runner.activeTaskCount) {
0 -> GONE
else -> VISIBLE
}

@ -36,7 +36,7 @@ class HabitTypeDialog : AppCompatDialogFragment() {
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
): View {
val binding = SelectHabitTypeBinding.inflate(inflater, container, false)
binding.buttonYesNo.setOnClickListener {

@ -48,9 +48,9 @@ import org.isoron.uhabits.utils.dim
import org.isoron.uhabits.utils.dp
import org.isoron.uhabits.utils.setupToolbar
import org.isoron.uhabits.utils.sres
import java.lang.Math.max
import java.lang.Math.min
import javax.inject.Inject
import kotlin.math.max
import kotlin.math.min
const val MAX_CHECKMARK_COUNT = 60

@ -39,12 +39,10 @@ class HabitCardListController @Inject constructor(
private val selectionMenu: Lazy<ListHabitsSelectionMenu>
) : HabitCardListView.Controller, ModelObservable.Listener {
private val NORMAL_MODE = NormalMode()
private val SELECTION_MODE = SelectionMode()
private var activeMode: Mode
init {
this.activeMode = NORMAL_MODE
this.activeMode = NormalMode()
adapter.observable.addListener(this)
}
@ -83,9 +81,9 @@ class HabitCardListController @Inject constructor(
activeMode.startDrag(position)
}
protected fun toggleSelection(position: Int) {
private fun toggleSelection(position: Int) {
adapter.toggleSelection(position)
activeMode = if (adapter.isSelectionEmpty) NORMAL_MODE else SELECTION_MODE
activeMode = if (adapter.isSelectionEmpty) NormalMode() else SelectionMode()
}
private fun cancelSelection() {
@ -116,8 +114,7 @@ class HabitCardListController @Inject constructor(
*/
internal inner class NormalMode : Mode {
override fun onItemClick(position: Int) {
val habit = adapter.getItem(position)
if (habit == null) return
val habit = adapter.getItem(position) ?: return
behavior.onClickHabit(habit)
}
@ -130,9 +127,9 @@ class HabitCardListController @Inject constructor(
startSelection(position)
}
protected fun startSelection(position: Int) {
private fun startSelection(position: Int) {
toggleSelection(position)
activeMode = SELECTION_MODE
activeMode = SelectionMode()
selectionMenu.get().onSelectionStart()
}
}
@ -158,8 +155,8 @@ class HabitCardListController @Inject constructor(
notifyListener()
}
protected fun notifyListener() {
if (activeMode === SELECTION_MODE)
private fun notifyListener() {
if (activeMode === SelectionMode())
selectionMenu.get().onSelectionChange()
else
selectionMenu.get().onSelectionFinish()

@ -170,22 +170,22 @@ class HabitCardListView(
inner class TouchHelperCallback : ItemTouchHelper.Callback() {
override fun getMovementFlags(
recyclerView: RecyclerView,
viewHolder: RecyclerView.ViewHolder
viewHolder: ViewHolder
): Int {
return makeMovementFlags(UP or DOWN, START or END)
}
override fun onMove(
recyclerView: RecyclerView,
from: RecyclerView.ViewHolder,
to: RecyclerView.ViewHolder
from: ViewHolder,
to: ViewHolder
): Boolean {
controller.get().drop(from.adapterPosition, to.adapterPosition)
return true
}
override fun onSwiped(
viewHolder: RecyclerView.ViewHolder,
viewHolder: ViewHolder,
direction: Int
) {
}

@ -59,8 +59,8 @@ class HabitCardViewFactory
class HabitCardView(
@ActivityContext context: Context,
private val checkmarkPanelFactory: CheckmarkPanelViewFactory,
private val numberPanelFactory: NumberPanelViewFactory,
checkmarkPanelFactory: CheckmarkPanelViewFactory,
numberPanelFactory: NumberPanelViewFactory,
private val behavior: ListHabitsBehavior
) : FrameLayout(context),
ModelObservable.Listener {
@ -174,7 +174,7 @@ class HabitCardView(
}
clipToPadding = false
layoutParams = FrameLayout.LayoutParams(MATCH_PARENT, WRAP_CONTENT)
layoutParams = LayoutParams(MATCH_PARENT, WRAP_CONTENT)
val margin = dp(3f).toInt()
setPadding(margin, 0, margin, margin)
addView(innerFrame)

@ -71,7 +71,7 @@ class NumberPanelView(
setupButtons()
}
override fun createButton() = buttonFactory.create()!!
override fun createButton() = buttonFactory.create()
@Synchronized
override fun setupButtons() {

@ -27,6 +27,7 @@ import org.isoron.uhabits.core.ui.screens.habits.show.views.OverviewCardState
import org.isoron.uhabits.databinding.ShowHabitOverviewBinding
import org.isoron.uhabits.utils.StyledResources
import org.isoron.uhabits.utils.toThemedAndroidColor
import kotlin.math.abs
class OverviewCardView(context: Context, attrs: AttributeSet) : LinearLayout(context, attrs) {
@ -36,7 +37,7 @@ class OverviewCardView(context: Context, attrs: AttributeSet) : LinearLayout(con
return String.format(
"%s%.0f%%",
if (percentageDiff >= 0) "+" else "\u2212",
Math.abs(percentageDiff) * 100
abs(percentageDiff) * 100
)
}

@ -68,7 +68,7 @@ class SyncActivity : AppCompatActivity(), SyncBehavior.Screen {
title = resources.getString(R.string.device_sync),
)
binding.syncLink.setOnClickListener { copyToClipboard() }
binding.instructions.setText(Html.fromHtml(resources.getString(R.string.sync_instructions)))
binding.instructions.text = Html.fromHtml(resources.getString(R.string.sync_instructions))
setContentView(binding.root)
}

@ -27,22 +27,22 @@ class AndroidCursor(private val cursor: android.database.Cursor) : Cursor {
override fun moveToNext() = cursor.moveToNext()
override fun getInt(index: Int): Int? {
if (cursor.isNull(index)) return null
else return cursor.getInt(index)
return if (cursor.isNull(index)) null
else cursor.getInt(index)
}
override fun getLong(index: Int): Long? {
if (cursor.isNull(index)) return null
else return cursor.getLong(index)
return if (cursor.isNull(index)) null
else cursor.getLong(index)
}
override fun getDouble(index: Int): Double? {
if (cursor.isNull(index)) return null
else return cursor.getDouble(index)
return if (cursor.isNull(index)) null
else cursor.getDouble(index)
}
override fun getString(index: Int): String? {
if (cursor.isNull(index)) return null
else return cursor.getString(index)
return if (cursor.isNull(index)) null
else cursor.getString(index)
}
}

@ -51,7 +51,7 @@ class AndroidDatabase(
return db.update(tableName, contValues, where, params)
}
override fun insert(tableName: String, values: Map<String, Any?>): Long? {
override fun insert(tableName: String, values: Map<String, Any?>): Long {
val contValues = mapToContentValues(values)
return db.insert(tableName, null, contValues)
}

@ -32,13 +32,8 @@ import org.isoron.uhabits.core.ui.screens.habits.list.ListHabitsBehavior
@ActivityScope
@Component(
modules = arrayOf(
ActivityContextModule::class,
HabitsActivityModule::class,
ListHabitsModule::class,
HabitModule::class
),
dependencies = arrayOf(HabitsApplicationComponent::class)
modules = [ActivityContextModule::class, HabitsActivityModule::class, ListHabitsModule::class, HabitModule::class],
dependencies = [HabitsApplicationComponent::class]
)
interface HabitsActivityComponent {
val colorPickerDialogFactory: ColorPickerDialogFactory

@ -44,9 +44,8 @@ class IntentParser
}
private fun parseHabit(uri: Uri): Habit {
val habit = habits.getById(parseId(uri))
return habits.getById(parseId(uri))
?: throw IllegalArgumentException("habit not found")
return habit
}
private fun parseTimestamp(intent: Intent): Timestamp {

@ -36,6 +36,7 @@ import org.isoron.uhabits.core.utils.DateFormats
import org.isoron.uhabits.inject.AppContext
import java.util.Date
import javax.inject.Inject
import kotlin.math.min
@AppScope
class IntentScheduler
@ -84,7 +85,7 @@ class IntentScheduler
}
private fun logReminderScheduled(habit: Habit, reminderTime: Long) {
val min = Math.min(5, habit.name.length)
val min = min(5, habit.name.length)
val name = habit.name.substring(0, min)
val df = DateFormats.getBackupDateFormat()
val time = df.format(Date(reminderTime))

@ -41,7 +41,7 @@ class PendingIntentFactory
) {
fun addCheckmark(habit: Habit, timestamp: Timestamp?): PendingIntent =
PendingIntent.getBroadcast(
getBroadcast(
context,
1,
Intent(context, WidgetReceiver::class.java).apply {
@ -53,7 +53,7 @@ class PendingIntentFactory
)
fun dismissNotification(habit: Habit): PendingIntent =
PendingIntent.getBroadcast(
getBroadcast(
context,
0,
Intent(context, ReminderReceiver::class.java).apply {
@ -64,7 +64,7 @@ class PendingIntentFactory
)
fun removeRepetition(habit: Habit): PendingIntent =
PendingIntent.getBroadcast(
getBroadcast(
context,
3,
Intent(context, WidgetReceiver::class.java).apply {
@ -90,7 +90,7 @@ class PendingIntentFactory
reminderTime: Long?,
timestamp: Long
): PendingIntent =
PendingIntent.getBroadcast(
getBroadcast(
context,
(habit.id!! % Integer.MAX_VALUE).toInt() + 1,
Intent(context, ReminderReceiver::class.java).apply {
@ -103,7 +103,7 @@ class PendingIntentFactory
)
fun snoozeNotification(habit: Habit): PendingIntent =
PendingIntent.getBroadcast(
getBroadcast(
context,
0,
Intent(context, ReminderReceiver::class.java).apply {
@ -114,7 +114,7 @@ class PendingIntentFactory
)
fun toggleCheckmark(habit: Habit, timestamp: Long?): PendingIntent =
PendingIntent.getBroadcast(
getBroadcast(
context,
2,
Intent(context, WidgetReceiver::class.java).apply {
@ -145,7 +145,7 @@ class PendingIntentFactory
)
fun updateWidgets(): PendingIntent =
PendingIntent.getBroadcast(
getBroadcast(
context,
0,
Intent(context, WidgetReceiver::class.java).apply {

@ -40,17 +40,17 @@ class RingtoneManager
PreferenceManager.getDefaultSharedPreferences(context)
fun getName(): String? {
try {
return try {
var ringtoneName = context.resources.getString(R.string.none)
val ringtoneUri = getURI()
if (ringtoneUri != null) {
val ringtone = getRingtone(context, ringtoneUri)
if (ringtone != null) ringtoneName = ringtone.getTitle(context)
}
return ringtoneName
ringtoneName
} catch (e: RuntimeException) {
e.printStackTrace()
return null
null
}
}

@ -80,8 +80,7 @@ class RemoteSyncServer(
try {
val url = "${preferences.syncBaseURL}/db/$key"
Log.i("RemoteSyncServer", "GET $url")
val data: SyncData = httpClient.get(url)
return@IO data
return@IO httpClient.get<SyncData>(url)
} catch (e: ServerResponseException) {
throw ServiceUnavailable()
} catch (e: ClientRequestException) {

@ -23,7 +23,7 @@ import android.content.Context
class CheckmarkWidgetProvider : BaseWidgetProvider() {
override fun getWidgetFromId(context: Context, id: Int): BaseWidget {
val habits = getHabitsFromWidgetId(id)
if (habits.size == 1) return CheckmarkWidget(context, id, habits[0])
else return StackWidget(context, id, StackWidgetType.CHECKMARK, habits)
return if (habits.size == 1) CheckmarkWidget(context, id, habits[0])
else StackWidget(context, id, StackWidgetType.CHECKMARK, habits)
}
}

@ -36,7 +36,7 @@ class FrequencyWidget(
override val defaultHeight: Int = 200
override val defaultWidth: Int = 200
override fun getOnClickPendingIntent(context: Context): PendingIntent? =
override fun getOnClickPendingIntent(context: Context): PendingIntent =
pendingIntentFactory.showHabit(habit)
override fun refreshData(v: View) {

@ -24,12 +24,12 @@ import android.content.Context
class FrequencyWidgetProvider : BaseWidgetProvider() {
override fun getWidgetFromId(context: Context, id: Int): BaseWidget {
val habits = getHabitsFromWidgetId(id)
if (habits.size == 1) return FrequencyWidget(
return if (habits.size == 1) FrequencyWidget(
context,
id,
habits[0],
preferences!!.firstWeekdayInt
preferences.firstWeekdayInt
)
else return StackWidget(context, id, StackWidgetType.FREQUENCY, habits)
else StackWidget(context, id, StackWidgetType.FREQUENCY, habits)
}
}

@ -41,7 +41,7 @@ class HistoryWidget(
override val defaultHeight: Int = 250
override val defaultWidth: Int = 250
override fun getOnClickPendingIntent(context: Context): PendingIntent? {
override fun getOnClickPendingIntent(context: Context): PendingIntent {
return pendingIntentFactory.showHabit(habit)
}

@ -23,11 +23,11 @@ import android.content.Context
class HistoryWidgetProvider : BaseWidgetProvider() {
override fun getWidgetFromId(context: Context, id: Int): BaseWidget {
val habits = getHabitsFromWidgetId(id)
if (habits.size == 1) return HistoryWidget(
return if (habits.size == 1) HistoryWidget(
context,
id,
habits[0]
)
else return StackWidget(context, id, StackWidgetType.HISTORY, habits)
else StackWidget(context, id, StackWidgetType.HISTORY, habits)
}
}

@ -36,7 +36,7 @@ class ScoreWidget(
override val defaultHeight: Int = 300
override val defaultWidth: Int = 300
override fun getOnClickPendingIntent(context: Context): PendingIntent? =
override fun getOnClickPendingIntent(context: Context): PendingIntent =
pendingIntentFactory.showHabit(habit)
override fun refreshData(view: View) {

@ -23,7 +23,7 @@ import android.content.Context
class ScoreWidgetProvider : BaseWidgetProvider() {
override fun getWidgetFromId(context: Context, id: Int): BaseWidget {
val habits = getHabitsFromWidgetId(id)
if (habits.size == 1) return ScoreWidget(context, id, habits[0])
else return StackWidget(context, id, StackWidgetType.SCORE, habits)
return if (habits.size == 1) ScoreWidget(context, id, habits[0])
else StackWidget(context, id, StackWidgetType.SCORE, habits)
}
}

@ -48,7 +48,10 @@ class StackWidgetService : RemoteViewsService() {
internal class StackRemoteViewsFactory(private val context: Context, intent: Intent) :
RemoteViewsFactory {
private val widgetId: Int
private val widgetId: Int = intent.getIntExtra(
AppWidgetManager.EXTRA_APPWIDGET_ID,
AppWidgetManager.INVALID_APPWIDGET_ID
)
private val habitIds: LongArray
private val widgetType: StackWidgetType?
private var remoteViews = ArrayList<RemoteViews>()
@ -148,15 +151,11 @@ internal class StackRemoteViewsFactory(private val context: Context, intent: Int
}
init {
widgetId = intent.getIntExtra(
AppWidgetManager.EXTRA_APPWIDGET_ID,
AppWidgetManager.INVALID_APPWIDGET_ID
)
val widgetTypeValue = intent.getIntExtra(StackWidgetService.WIDGET_TYPE, -1)
val habitIdsStr = intent.getStringExtra(StackWidgetService.HABIT_IDS)
if (widgetTypeValue < 0) throw RuntimeException("invalid widget type")
if (habitIdsStr == null) throw RuntimeException("habitIdsStr is null")
widgetType = StackWidgetType.Companion.getWidgetTypeFromValue(widgetTypeValue)
widgetType = StackWidgetType.getWidgetTypeFromValue(widgetTypeValue)
habitIds = splitLongs(habitIdsStr)
}
}

@ -37,7 +37,7 @@ class StreakWidget(
override val defaultHeight: Int = 200
override val defaultWidth: Int = 200
override fun getOnClickPendingIntent(context: Context): PendingIntent? =
override fun getOnClickPendingIntent(context: Context): PendingIntent =
pendingIntentFactory.showHabit(habit)
override fun refreshData(view: View) {

@ -23,7 +23,7 @@ import android.content.Context
class StreakWidgetProvider : BaseWidgetProvider() {
override fun getWidgetFromId(context: Context, id: Int): BaseWidget {
val habits = getHabitsFromWidgetId(id)
if (habits.size == 1) return StreakWidget(context, id, habits[0])
else return StackWidget(context, id, StackWidgetType.STREAKS, habits)
return if (habits.size == 1) StreakWidget(context, id, habits[0])
else StackWidget(context, id, StackWidgetType.STREAKS, habits)
}
}

@ -40,7 +40,7 @@ class TargetWidget(
override val defaultHeight: Int = 200
override val defaultWidth: Int = 200
override fun getOnClickPendingIntent(context: Context): PendingIntent? =
override fun getOnClickPendingIntent(context: Context): PendingIntent =
pendingIntentFactory.showHabit(habit)
override fun refreshData(view: View) = runBlocking {

@ -23,7 +23,7 @@ import android.content.Context
class TargetWidgetProvider : BaseWidgetProvider() {
override fun getWidgetFromId(context: Context, id: Int): BaseWidget {
val habits = getHabitsFromWidgetId(id)
if (habits.size == 1) return TargetWidget(context, id, habits[0])
else return StackWidget(context, id, StackWidgetType.TARGET, habits)
return if (habits.size == 1) TargetWidget(context, id, habits[0])
else StackWidget(context, id, StackWidgetType.TARGET, habits)
}
}

@ -37,14 +37,15 @@ import org.isoron.uhabits.inject.HabitsApplicationComponent
import org.isoron.uhabits.utils.InterfaceUtils.getDimension
import org.isoron.uhabits.utils.PaletteUtils.getAndroidTestColor
import org.isoron.uhabits.utils.StyledResources
import kotlin.math.min
class CheckmarkWidgetView : HabitWidgetView {
var activeColor: Int = 0
var percentage = 0f
var name: String? = null
protected lateinit var ring: RingView
protected lateinit var label: TextView
private lateinit var ring: RingView
private lateinit var label: TextView
var entryValue = 0
var entryState = 0
var isNumerical = false
@ -92,7 +93,7 @@ class CheckmarkWidgetView : HabitWidgetView {
postInvalidate()
}
protected val text: String
private val text: String
get() = if (isNumerical) {
(entryValue / 1000.0).toShortString()
} else when (entryState) {
@ -122,7 +123,7 @@ class CheckmarkWidgetView : HabitWidgetView {
val height = MeasureSpec.getSize(heightMeasureSpec)
var w = width.toFloat()
var h = width * 1.25f
val scale = Math.min(width / w, height / h)
val scale = min(width / w, height / h)
w *= scale
h *= scale
if (h < getDimension(context, R.dimen.checkmarkWidget_heightBreakpoint)) ring.visibility =
@ -131,7 +132,7 @@ class CheckmarkWidgetView : HabitWidgetView {
heightMeasureSpec = MeasureSpec.makeMeasureSpec(h.toInt(), MeasureSpec.EXACTLY)
var textSize = 0.15f * h
val maxTextSize = getDimension(context, R.dimen.smallerTextSize)
textSize = Math.min(textSize, maxTextSize)
textSize = min(textSize, maxTextSize)
label.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize)
ring.setTextSize(textSize)
ring.setThickness(0.15f * textSize)
@ -139,8 +140,7 @@ class CheckmarkWidgetView : HabitWidgetView {
}
private fun init() {
val appComponent: HabitsApplicationComponent
appComponent = (context.applicationContext as HabitsApplication).component
val appComponent: HabitsApplicationComponent = (context.applicationContext as HabitsApplication).component
preferences = appComponent.preferences
ring = findViewById<View>(R.id.scoreRing) as RingView
label = findViewById<View>(R.id.label) as TextView

@ -32,6 +32,7 @@ import org.isoron.uhabits.R
import org.isoron.uhabits.utils.InterfaceUtils.dpToPixels
import org.isoron.uhabits.utils.StyledResources
import java.util.Arrays
import kotlin.math.max
abstract class HabitWidgetView : FrameLayout {
protected var background: InsetDrawable? = null
@ -73,7 +74,7 @@ abstract class HabitWidgetView : FrameLayout {
Arrays.fill(radii, cornerRadius)
val shape = RoundRectShape(radii, null, null)
val innerDrawable = ShapeDrawable(shape)
val insetLeftTop = Math.max(shadowRadius - shadowOffset, 0)
val insetLeftTop = max(shadowRadius - shadowOffset, 0)
val insetRightBottom = shadowRadius + shadowOffset
background = InsetDrawable(
innerDrawable,

@ -18,6 +18,7 @@
*/
package org.isoron.uhabits
import com.nhaarman.mockitokotlin2.spy
import org.isoron.uhabits.core.commands.CommandRunner
import org.isoron.uhabits.core.models.HabitList
import org.isoron.uhabits.core.models.memory.MemoryModelFactory
@ -29,7 +30,6 @@ import org.junit.After
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mockito
import org.mockito.junit.MockitoJUnitRunner
@RunWith(MockitoJUnitRunner::class)
@ -46,7 +46,7 @@ open class BaseAndroidJVMTest {
setFixedLocalTime(fixedLocalTime)
setStartDayOffset(0, 0)
modelFactory = MemoryModelFactory()
habitList = Mockito.spy(modelFactory.buildHabitList())
habitList = spy(modelFactory.buildHabitList())
fixtures = HabitFixtures(modelFactory, habitList)
taskRunner = SingleThreadTaskRunner()
commandRunner = CommandRunner(taskRunner)

@ -18,6 +18,9 @@
*/
package org.isoron.uhabits.receivers
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.verify
import com.nhaarman.mockitokotlin2.verifyNoMoreInteractions
import org.isoron.uhabits.BaseAndroidJVMTest
import org.isoron.uhabits.core.models.Habit
import org.isoron.uhabits.core.models.Timestamp
@ -25,7 +28,6 @@ import org.isoron.uhabits.core.preferences.Preferences
import org.isoron.uhabits.core.reminders.ReminderScheduler
import org.isoron.uhabits.core.ui.NotificationTray
import org.junit.Test
import org.mockito.Mockito
class ReminderControllerTest : BaseAndroidJVMTest() {
private lateinit var controller: ReminderController
@ -34,9 +36,9 @@ class ReminderControllerTest : BaseAndroidJVMTest() {
private lateinit var preferences: Preferences
override fun setUp() {
super.setUp()
reminderScheduler = Mockito.mock(ReminderScheduler::class.java)
notificationTray = Mockito.mock(NotificationTray::class.java)
preferences = Mockito.mock(Preferences::class.java)
reminderScheduler = mock()
notificationTray = mock()
preferences = mock()
controller = ReminderController(
reminderScheduler,
notificationTray,
@ -47,24 +49,24 @@ class ReminderControllerTest : BaseAndroidJVMTest() {
@Test
@Throws(Exception::class)
fun testOnDismiss() {
Mockito.verifyNoMoreInteractions(reminderScheduler)
Mockito.verifyNoMoreInteractions(notificationTray)
Mockito.verifyNoMoreInteractions(preferences)
verifyNoMoreInteractions(reminderScheduler)
verifyNoMoreInteractions(notificationTray)
verifyNoMoreInteractions(preferences)
}
@Test
@Throws(Exception::class)
fun testOnShowReminder() {
val habit = Mockito.mock(Habit::class.java)
val habit: Habit = mock()
controller.onShowReminder(habit, Timestamp.ZERO.plus(100), 456)
Mockito.verify(notificationTray).show(habit, Timestamp.ZERO.plus(100), 456)
Mockito.verify(reminderScheduler).scheduleAll()
verify(notificationTray).show(habit, Timestamp.ZERO.plus(100), 456)
verify(reminderScheduler).scheduleAll()
}
@Test
@Throws(Exception::class)
fun testOnBootCompleted() {
controller.onBootCompleted()
Mockito.verify(reminderScheduler).scheduleAll()
verify(reminderScheduler).scheduleAll()
}
}

@ -55,10 +55,4 @@ class NumberButtonTest : BaseViewTest() {
val btn = NumberButton(theme.color(8), 99.0, 100.0, "steps", theme)
assertRenders(48, 48, "$base/render_below.png", btn)
}
//@Test
fun testRenderZero() = asyncTest {
val btn = NumberButton(theme.color(8), 0.0, 100.0, "steps", theme)
assertRenders(48, 48, "$base/render_zero.png", btn)
}
}

@ -74,6 +74,7 @@ kotlin {
implementation 'nl.jqno.equalsverifier:equalsverifier:2.4.8'
implementation 'org.apache.commons:commons-io:1.3.2'
implementation 'org.mockito:mockito-core:2.28.2'
implementation "com.nhaarman.mockitokotlin2:mockito-kotlin:2.2.0"
}
}
}

@ -51,7 +51,7 @@ interface Canvas {
fun fillCircle(centerX: Double, centerY: Double, radius: Double)
fun setTextAlign(align: TextAlign)
fun toImage(): Image
fun measureText(test: String): Double
fun measureText(text: String): Double
/**
* Fills entire canvas with the current color.

@ -21,7 +21,7 @@ package org.isoron.platform.gui
class FontAwesome {
companion object {
val CHECK = "\uf00c"
val TIMES = "\uf00d"
const val CHECK = "\uf00c"
const val TIMES = "\uf00d"
}
}

@ -153,10 +153,10 @@ private fun daysSince2000(year: Int, month: Int, day: Int): Int {
result += ceil((year - 2000) / 4.0).toInt()
result -= ceil((year - 2000) / 100.0).toInt()
result += ceil((year - 2000) / 400.0).toInt()
if (isLeapYear(year)) {
result += leapOffset[month - 1]
result += if (isLeapYear(year)) {
leapOffset[month - 1]
} else {
result += nonLeapOffset[month - 1]
nonLeapOffset[month - 1]
}
result += (day - 1)
return result

@ -23,6 +23,7 @@ import kotlinx.coroutines.runBlocking
import org.isoron.platform.io.JavaFileOpener
import org.isoron.platform.io.JavaResourceFile
import java.awt.BasicStroke
import java.awt.Graphics2D
import java.awt.RenderingHints.KEY_ANTIALIASING
import java.awt.RenderingHints.KEY_FRACTIONALMETRICS
import java.awt.RenderingHints.KEY_TEXT_ANTIALIASING
@ -54,7 +55,7 @@ class JavaCanvas(
private var textAlign = TextAlign.CENTER
val widthPx = image.width
val heightPx = image.height
val g2d = image.createGraphics()
val g2d: Graphics2D = image.createGraphics()
private val NOTO_REGULAR_FONT = createFont("fonts/NotoSans-Regular.ttf")
private val NOTO_BOLD_FONT = createFont("fonts/NotoSans-Bold.ttf")
@ -96,24 +97,28 @@ class JavaCanvas(
val bx = bounds.x.roundToInt()
val by = bounds.y.roundToInt()
if (textAlign == TextAlign.CENTER) {
g2d.drawString(
text,
toPixel(x) - bx - bWidth / 2,
toPixel(y) - by - bHeight / 2
)
} else if (textAlign == TextAlign.LEFT) {
g2d.drawString(
text,
toPixel(x) - bx,
toPixel(y) - by - bHeight / 2
)
} else {
g2d.drawString(
text,
toPixel(x) - bx - bWidth,
toPixel(y) - by - bHeight / 2
)
when (textAlign) {
TextAlign.CENTER -> {
g2d.drawString(
text,
toPixel(x) - bx - bWidth / 2,
toPixel(y) - by - bHeight / 2
)
}
TextAlign.LEFT -> {
g2d.drawString(
text,
toPixel(x) - bx,
toPixel(y) - by - bHeight / 2
)
}
else -> {
g2d.drawString(
text,
toPixel(x) - bx - bWidth,
toPixel(y) - by - bHeight / 2
)
}
}
}

@ -33,8 +33,8 @@ class JavaResourceFile(val path: String) : ResourceFile {
get() {
val mainPath = Paths.get("assets/main/$path")
val testPath = Paths.get("assets/test/$path")
if (Files.exists(mainPath)) return mainPath
else return testPath
return if (Files.exists(mainPath)) mainPath
else testPath
}
override suspend fun exists(): Boolean {

@ -71,7 +71,7 @@ object SQLParser {
val buffer = BufferedInputStream(stream)
val commands: MutableList<String> = ArrayList()
val sb = StringBuffer()
try {
buffer.use { buffer ->
val tokenizer = Tokenizer(buffer)
var state = STATE_NONE
while (tokenizer.hasNext()) {
@ -104,7 +104,7 @@ object SQLParser {
}
if (state == STATE_NONE || state == STATE_STRING) {
if (state == STATE_NONE && isWhitespace(c)) {
if (sb.length > 0 && sb[sb.length - 1] != ' ') {
if (sb.isNotEmpty() && sb[sb.length - 1] != ' ') {
sb.append(' ')
}
} else {
@ -112,8 +112,6 @@ object SQLParser {
}
}
}
} finally {
buffer.close()
}
if (sb.isNotEmpty()) {
commands.add(sb.toString().trim { it <= ' ' })

@ -37,6 +37,7 @@ import java.util.LinkedList
import java.util.Locale
import java.util.zip.ZipEntry
import java.util.zip.ZipOutputStream
import kotlin.math.min
/**
* Class that exports the application data to CSV files.
@ -77,7 +78,7 @@ class HabitsCSVExporter(
private fun sanitizeFilename(name: String): String {
val s = name.replace("[^ a-zA-Z0-9\\._-]+".toRegex(), "")
return s.substring(0, Math.min(s.length, 100))
return s.substring(0, min(s.length, 100))
}
private fun writeHabits() {

@ -53,7 +53,7 @@ class LoopDBImporter
override fun canHandle(file: File): Boolean {
if (!file.isSQLite3File()) return false
val db = opener.open(file)!!
val db = opener.open(file)
var canHandle = true
val c = db.query("select count(*) from SQLITE_MASTER where name='Habits' or name='Repetitions'")
if (!c.moveToNext() || c.getInt(0) != 2) {
@ -70,7 +70,7 @@ class LoopDBImporter
}
override fun importHabitsFromFile(file: File) {
val db = opener.open(file)!!
val db = opener.open(file)
val helper = MigrationHelper(db)
helper.migrateTo(DATABASE_VERSION)

@ -156,15 +156,15 @@ open class EntryList {
get() = begin.daysUntil(end) + 1
}
/**
* Converts a list of intervals into a list of entries. Entries that fall outside of any
* interval receive value UNKNOWN. Entries that fall within an interval but do not appear
* in [original] receive value YES_AUTO. Entries provided in [original] are copied over.
*
* The intervals should be sorted by timestamp. The first element in the list should
* correspond to the newest interval.
*/
companion object {
/**
* Converts a list of intervals into a list of entries. Entries that fall outside of any
* interval receive value UNKNOWN. Entries that fall within an interval but do not appear
* in [original] receive value YES_AUTO. Entries provided in [original] are copied over.
*
* The intervals should be sorted by timestamp. The first element in the list should
* correspond to the newest interval.
*/
fun buildEntriesFromInterval(
original: List<Entry>,
intervals: List<Interval>,

@ -31,13 +31,12 @@ interface ModelFactory {
fun buildHabit(): Habit {
val scores = buildScoreList()
val streaks = buildStreakList()
val habit = Habit(
return Habit(
scores = scores,
streaks = streaks,
originalEntries = buildOriginalEntries(),
computedEntries = buildComputedEntries(),
)
return habit
}
fun buildComputedEntries(): EntryList
fun buildOriginalEntries(): EntryList

@ -18,6 +18,7 @@
*/
package org.isoron.uhabits.core.models
import kotlin.math.pow
import kotlin.math.sqrt
data class Score(
@ -40,7 +41,7 @@ data class Score(
previousScore: Double,
checkmarkValue: Double,
): Double {
val multiplier = Math.pow(0.5, sqrt(frequency) / 13.0)
val multiplier = 0.5.pow(sqrt(frequency) / 13.0)
var score = previousScore * multiplier
score += checkmarkValue * (1 - multiplier)
return score

@ -109,7 +109,7 @@ class ScoreList {
}
}
if (values[offset] != Entry.SKIP) {
val percentageCompleted = Math.min(1.0, rollingSum / numerator)
val percentageCompleted = min(1.0, rollingSum / numerator)
previousValue = compute(freq, previousValue, percentageCompleted)
}
}

@ -47,7 +47,7 @@ class WeekdayList {
}
fun toArray(): BooleanArray {
return Arrays.copyOf(weekdays, 7)
return weekdays.copyOf(7)
}
fun toInteger(): Int {

@ -29,6 +29,8 @@ import org.isoron.uhabits.core.ui.callbacks.OnConfirmedCallback
import org.isoron.uhabits.core.utils.DateUtils
import java.io.File
import java.util.Random
import kotlin.math.max
import kotlin.math.min
class ShowHabitMenuPresenter(
private val commandRunner: CommandRunner,
@ -67,7 +69,7 @@ class ShowHabitMenuPresenter(
habit.originalEntries.clear()
var strength = 50.0
for (i in 0 until 365 * 5) {
if (i % 7 == 0) strength = Math.max(0.0, Math.min(100.0, strength + 10 * random.nextGaussian()))
if (i % 7 == 0) strength = max(0.0, min(100.0, strength + 10 * random.nextGaussian()))
if (random.nextInt(100) > strength) continue
var value = Entry.YES_MANUAL
if (habit.isNumerical) value = (1000 + 250 * random.nextGaussian() * strength / 100).toInt() * 1000

@ -39,9 +39,9 @@ class OverviewCardPresenter {
val lastMonth = today.minus(30)
val lastYear = today.minus(365)
val scores = habit.scores
val scoreToday = scores.get(today).value.toFloat()
val scoreLastMonth = scores.get(lastMonth).value.toFloat()
val scoreLastYear = scores.get(lastYear).value.toFloat()
val scoreToday = scores[today].value.toFloat()
val scoreLastMonth = scores[lastMonth].value.toFloat()
val scoreLastYear = scores[lastYear].value.toFloat()
val totalCount = habit.originalEntries.getKnown()
.filter { it.value == Entry.YES_MANUAL }
.count()

@ -39,13 +39,13 @@ class ScoreCardPresenter(
companion object {
val BUCKET_SIZES = intArrayOf(1, 7, 31, 92, 365)
fun getTruncateField(bucketSize: Int): DateUtils.TruncateField {
when (bucketSize) {
1 -> return DateUtils.TruncateField.DAY
7 -> return DateUtils.TruncateField.WEEK_NUMBER
31 -> return DateUtils.TruncateField.MONTH
92 -> return DateUtils.TruncateField.QUARTER
365 -> return DateUtils.TruncateField.YEAR
else -> return DateUtils.TruncateField.MONTH
return when (bucketSize) {
1 -> DateUtils.TruncateField.DAY
7 -> DateUtils.TruncateField.WEEK_NUMBER
31 -> DateUtils.TruncateField.MONTH
92 -> DateUtils.TruncateField.QUARTER
365 -> DateUtils.TruncateField.YEAR
else -> DateUtils.TruncateField.MONTH
}
}

@ -63,7 +63,7 @@ class BarChart(
val nColumns = floor((safeWidth) / barGroupWidth).toInt()
val marginLeft = (safeWidth - nColumns * barGroupWidth) / 2
val maxBarHeight = height - footerHeight - paddingTop
var maxValue = series.map { it.max()!! }.max()!!
var maxValue = series.map { it.maxOrNull()!! }.maxOrNull()!!
maxValue = max(maxValue, 1.0)
canvas.setColor(theme.cardBackgroundColor)

@ -192,15 +192,15 @@ class HistoryChart(
val value = if (offset >= series.size) Square.OFF else series[offset]
val squareColor: Color
val color = theme.color(paletteColor.paletteIndex)
when (value) {
squareColor = when (value) {
Square.ON -> {
squareColor = color
color
}
Square.OFF -> {
squareColor = theme.lowContrastTextColor
theme.lowContrastTextColor
}
Square.DIMMED, Square.HATCHED -> {
squareColor = color.blendWith(theme.cardBackgroundColor, 0.5)
color.blendWith(theme.cardBackgroundColor, 0.5)
}
}

@ -76,7 +76,7 @@ abstract class DateUtils {
if (fixedLocalTime != null) return fixedLocalTime as Long
val tz = getTimeZone()
val now = Date().getTime()
val now = Date().time
return now + tz.getOffset(now)
}

@ -37,7 +37,7 @@ open class MidnightTimer @Inject constructor() {
this.listeners.add(listener)
}
@Synchronized fun onPause() = executor.shutdownNow()
@Synchronized fun onPause(): MutableList<Runnable>? = executor.shutdownNow()
@Synchronized fun onResume() {
executor = Executors.newSingleThreadScheduledExecutor()

@ -59,11 +59,10 @@ class StringUtils {
@JvmStatic
fun splitLongs(str: String): LongArray {
val parts: Array<String> = org.apache.commons.lang3.StringUtils.split(str, ',')
val numbers = LongArray(parts.size) {
return LongArray(parts.size) {
i ->
parts[i].toLong()
}
return numbers
}
}
}

@ -18,6 +18,8 @@
*/
package org.isoron.uhabits.core
import com.nhaarman.mockitokotlin2.spy
import com.nhaarman.mockitokotlin2.validateMockitoUsage
import org.apache.commons.io.IOUtils
import org.isoron.uhabits.core.commands.CommandRunner
import org.isoron.uhabits.core.database.Database
@ -37,7 +39,6 @@ import org.junit.After
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mockito
import org.mockito.junit.MockitoJUnitRunner
import java.io.File
import java.io.FileInputStream
@ -78,7 +79,7 @@ open class BaseUnitTest {
setFixedLocalTime(FIXED_LOCAL_TIME)
setStartDayOffset(0, 0)
val memoryModelFactory = MemoryModelFactory()
habitList = Mockito.spy(memoryModelFactory.buildHabitList())
habitList = spy(memoryModelFactory.buildHabitList())
fixtures = HabitFixtures(memoryModelFactory, habitList)
modelFactory = memoryModelFactory
taskRunner = SingleThreadTaskRunner()
@ -88,7 +89,7 @@ open class BaseUnitTest {
@After
@Throws(Exception::class)
open fun tearDown() {
Mockito.validateMockitoUsage()
validateMockitoUsage()
setFixedLocalTime(null)
setStartDayOffset(0, 0)
}

@ -26,21 +26,21 @@ import org.junit.Before
import org.junit.Test
class ArchiveHabitsCommandTest : BaseUnitTest() {
private var command: ArchiveHabitsCommand? = null
private var habit: Habit? = null
private lateinit var command: ArchiveHabitsCommand
private lateinit var habit: Habit
@Before
@Throws(Exception::class)
override fun setUp() {
super.setUp()
habit = fixtures.createShortHabit()
habitList.add(habit!!)
command = ArchiveHabitsCommand(habitList, listOf(habit!!))
habitList.add(habit)
command = ArchiveHabitsCommand(habitList, listOf(habit))
}
@Test
fun testExecute() {
assertFalse(habit!!.isArchived)
command!!.run()
assertTrue(habit!!.isArchived)
assertFalse(habit.isArchived)
command.run()
assertTrue(habit.isArchived)
}
}

@ -18,7 +18,7 @@
*/
package org.isoron.uhabits.core.commands
import org.hamcrest.CoreMatchers
import org.hamcrest.CoreMatchers.equalTo
import org.hamcrest.MatcherAssert.assertThat
import org.isoron.uhabits.core.BaseUnitTest
import org.isoron.uhabits.core.models.Habit
@ -54,16 +54,13 @@ class ChangeHabitColorCommandTest : BaseUnitTest() {
private fun checkNewColors() {
for (habit in selected) {
assertThat(habit.color, CoreMatchers.equalTo(PaletteColor(0)))
assertThat(habit.color, equalTo(PaletteColor(0)))
}
}
private fun checkOriginalColors() {
var k = 0
for (habit in selected)
assertThat(
habit.color,
CoreMatchers.equalTo(PaletteColor(++k))
)
assertThat(habit.color, equalTo(PaletteColor(++k)))
}
}

@ -19,7 +19,7 @@
package org.isoron.uhabits.core.commands
import junit.framework.Assert.assertTrue
import org.hamcrest.CoreMatchers
import org.hamcrest.CoreMatchers.equalTo
import org.hamcrest.MatcherAssert.assertThat
import org.isoron.uhabits.core.BaseUnitTest
import org.isoron.uhabits.core.models.Habit
@ -46,13 +46,8 @@ class CreateHabitCommandTest : BaseUnitTest() {
fun testExecute() {
assertTrue(habitList.isEmpty)
command.run()
assertThat(habitList.size(), CoreMatchers.equalTo(1))
assertThat(habitList.size(), equalTo(1))
val habit = habitList.getByPosition(0)
assertThat(
habit.name,
CoreMatchers.equalTo(
model.name
)
)
assertThat(habit.name, equalTo(model.name))
}
}

@ -28,26 +28,26 @@ import org.junit.Before
import org.junit.Test
class CreateRepetitionCommandTest : BaseUnitTest() {
private var command: CreateRepetitionCommand? = null
private var habit: Habit? = null
private var today: Timestamp? = null
private lateinit var command: CreateRepetitionCommand
private lateinit var habit: Habit
private lateinit var today: Timestamp
@Before
@Throws(Exception::class)
override fun setUp() {
super.setUp()
habit = fixtures.createShortHabit()
habitList.add(habit!!)
habitList.add(habit)
today = getToday()
command = CreateRepetitionCommand(habitList, habit!!, today!!, 100)
command = CreateRepetitionCommand(habitList, habit, today, 100)
}
@Test
fun testExecute() {
val entries = habit!!.originalEntries
var entry = entries.get(today!!)
val entries = habit.originalEntries
var entry = entries.get(today)
assertEquals(Entry.YES_MANUAL, entry.value)
command!!.run()
entry = entries.get(today!!)
command.run()
entry = entries.get(today)
assertEquals(100, entry.value.toLong())
}
}

@ -18,7 +18,7 @@
*/
package org.isoron.uhabits.core.commands
import org.hamcrest.CoreMatchers
import org.hamcrest.CoreMatchers.equalTo
import org.hamcrest.MatcherAssert.assertThat
import org.isoron.uhabits.core.BaseUnitTest
import org.isoron.uhabits.core.models.Habit
@ -34,6 +34,7 @@ class DeleteHabitsCommandTest : BaseUnitTest() {
@get:Rule
var thrown = ExpectedException.none()!!
@Before
@Throws(Exception::class)
override fun setUp() {
@ -56,9 +57,9 @@ class DeleteHabitsCommandTest : BaseUnitTest() {
@Test
fun testExecute() {
assertThat(habitList.size(), CoreMatchers.equalTo(4))
assertThat(habitList.size(), equalTo(4))
command.run()
assertThat(habitList.size(), CoreMatchers.equalTo(1))
assertThat(habitList.getByPosition(0).name, CoreMatchers.equalTo("extra"))
assertThat(habitList.size(), equalTo(1))
assertThat(habitList.getByPosition(0).name, equalTo("extra"))
}
}

@ -36,6 +36,7 @@ class Version22Test : BaseUnitTest() {
var exception = ExpectedException.none()!!
private lateinit var db: Database
private lateinit var helper: MigrationHelper
@Throws(Exception::class)
override fun setUp() {
super.setUp()
@ -49,48 +50,25 @@ class Version22Test : BaseUnitTest() {
@Test
@Throws(Exception::class)
fun testKeepValidReps() {
db.query(
"select count(*) from repetitions"
) { c: Cursor ->
assertThat(
c.getInt(0),
equalTo(3)
)
db.query("select count(*) from repetitions") { c: Cursor ->
assertThat(c.getInt(0), equalTo(3))
}
helper.migrateTo(22)
db.query(
"select count(*) from repetitions"
) { c: Cursor ->
assertThat(
c.getInt(0),
equalTo(3)
)
db.query("select count(*) from repetitions") { c: Cursor ->
assertThat(c.getInt(0), equalTo(3))
}
}
@Test
@Throws(Exception::class)
fun testRemoveRepsWithInvalidId() {
db.execute(
"insert into Repetitions(habit, timestamp, value) " +
"values (99999, 100, 2)"
)
db.query(
"select count(*) from repetitions where habit = 99999"
) { c: Cursor ->
assertThat(
c.getInt(0),
equalTo(1)
)
db.execute("insert into Repetitions(habit, timestamp, value) values (99999, 100, 2)")
db.query("select count(*) from repetitions where habit = 99999") { c: Cursor ->
assertThat(c.getInt(0), equalTo(1))
}
helper.migrateTo(22)
db.query(
"select count(*) from repetitions where habit = 99999"
) { c: Cursor ->
assertThat(
c.getInt(0),
equalTo(0)
)
db.query("select count(*) from repetitions where habit = 99999") { c: Cursor ->
assertThat(c.getInt(0), equalTo(0))
}
}
@ -99,32 +77,19 @@ class Version22Test : BaseUnitTest() {
fun testDisallowNewRepsWithInvalidRef() {
helper.migrateTo(22)
exception.expectMessage(Matchers.containsString("SQLITE_CONSTRAINT"))
db.execute(
"insert into Repetitions(habit, timestamp, value) " +
"values (99999, 100, 2)"
)
db.execute("insert into Repetitions(habit, timestamp, value) values (99999, 100, 2)")
}
@Test
@Throws(Exception::class)
fun testRemoveRepetitionsWithNullTimestamp() {
db.execute("insert into repetitions(habit, value) values (0, 2)")
db.query(
"select count(*) from repetitions where timestamp is null"
) { c: Cursor ->
assertThat(
c.getInt(0),
equalTo(1)
)
db.query("select count(*) from repetitions where timestamp is null") { c: Cursor ->
assertThat(c.getInt(0), equalTo(1))
}
helper.migrateTo(22)
db.query(
"select count(*) from repetitions where timestamp is null"
) { c: Cursor ->
assertThat(
c.getInt(0),
equalTo(0)
)
db.query("select count(*) from repetitions where timestamp is null") { c: Cursor ->
assertThat(c.getInt(0), equalTo(0))
}
}
@ -140,22 +105,12 @@ class Version22Test : BaseUnitTest() {
@Throws(Exception::class)
fun testRemoveRepetitionsWithNullHabit() {
db.execute("insert into repetitions(timestamp, value) values (0, 2)")
db.query(
"select count(*) from repetitions where habit is null"
) { c: Cursor ->
assertThat(
c.getInt(0),
equalTo(1)
)
db.query("select count(*) from repetitions where habit is null") { c: Cursor ->
assertThat(c.getInt(0), equalTo(1))
}
helper.migrateTo(22)
db.query(
"select count(*) from repetitions where habit is null"
) { c: Cursor ->
assertThat(
c.getInt(0),
equalTo(0)
)
db.query("select count(*) from repetitions where habit is null") { c: Cursor ->
assertThat(c.getInt(0), equalTo(0))
}
}
@ -164,42 +119,21 @@ class Version22Test : BaseUnitTest() {
fun testDisallowNullHabit() {
helper.migrateTo(22)
exception.expectMessage(Matchers.containsString("SQLITE_CONSTRAINT"))
db.execute(
"insert into Repetitions(timestamp, value) " + "values (5, 2)"
)
db.execute("insert into Repetitions(timestamp, value) " + "values (5, 2)")
}
@Test
@Throws(Exception::class)
fun testRemoveDuplicateRepetitions() {
db.execute(
"insert into repetitions(habit, timestamp, value)" +
"values (0, 100, 2)"
)
db.execute(
"insert into repetitions(habit, timestamp, value)" +
"values (0, 100, 5)"
)
db.execute(
"insert into repetitions(habit, timestamp, value)" +
"values (0, 100, 10)"
)
db.query(
"select count(*) from repetitions where timestamp=100 and habit=0"
) { c: Cursor ->
assertThat(
c.getInt(0),
equalTo(3)
)
db.execute("insert into repetitions(habit, timestamp, value)values (0, 100, 2)")
db.execute("insert into repetitions(habit, timestamp, value)values (0, 100, 5)")
db.execute("insert into repetitions(habit, timestamp, value)values (0, 100, 10)")
db.query("select count(*) from repetitions where timestamp=100 and habit=0") { c: Cursor ->
assertThat(c.getInt(0), equalTo(3))
}
helper.migrateTo(22)
db.query(
"select count(*) from repetitions where timestamp=100 and habit=0"
) { c: Cursor ->
assertThat(
c.getInt(0),
equalTo(1)
)
db.query("select count(*) from repetitions where timestamp=100 and habit=0") { c: Cursor ->
assertThat(c.getInt(0), equalTo(1))
}
}
@ -207,14 +141,8 @@ class Version22Test : BaseUnitTest() {
@Throws(Exception::class)
fun testDisallowNewDuplicateTimestamps() {
helper.migrateTo(22)
db.execute(
"insert into repetitions(habit, timestamp, value)" +
"values (0, 100, 2)"
)
db.execute("insert into repetitions(habit, timestamp, value)values (0, 100, 2)")
exception.expectMessage(Matchers.containsString("SQLITE_CONSTRAINT"))
db.execute(
"insert into repetitions(habit, timestamp, value)" +
"values (0, 100, 5)"
)
db.execute("insert into repetitions(habit, timestamp, value)values (0, 100, 5)")
}
}

@ -18,7 +18,6 @@
*/
package org.isoron.uhabits.core.io
import junit.framework.Assert.assertNotNull
import junit.framework.Assert.assertTrue
import org.apache.commons.io.FileUtils
import org.apache.commons.io.IOUtils
@ -34,7 +33,7 @@ import java.util.LinkedList
import java.util.zip.ZipFile
class HabitsCSVExporterTest : BaseUnitTest() {
private var baseDir: File? = null
private lateinit var baseDir: File
@Before
@Throws(Exception::class)
override fun setUp() {
@ -42,7 +41,6 @@ class HabitsCSVExporterTest : BaseUnitTest() {
habitList.add(fixtures.createShortHabit())
habitList.add(fixtures.createEmptyHabit())
baseDir = Files.createTempDirectory("csv").toFile()
assertNotNull(baseDir)
}
@Throws(Exception::class)
@ -59,7 +57,7 @@ class HabitsCSVExporterTest : BaseUnitTest() {
val exporter = HabitsCSVExporter(
habitList,
selected,
baseDir!!
baseDir
)
val filename = exporter.writeArchive()
assertAbsolutePathExists(filename)
@ -84,7 +82,7 @@ class HabitsCSVExporterTest : BaseUnitTest() {
val stream = zip.getInputStream(entry)
val outputFilename = String.format(
"%s/%s",
baseDir!!.absolutePath,
baseDir.absolutePath,
entry.name
)
val out = File(outputFilename)
@ -96,7 +94,7 @@ class HabitsCSVExporterTest : BaseUnitTest() {
}
private fun assertPathExists(s: String) {
assertAbsolutePathExists(String.format("%s/%s", baseDir!!.absolutePath, s))
assertAbsolutePathExists(String.format("%s/%s", baseDir.absolutePath, s))
}
private fun assertAbsolutePathExists(s: String) {

@ -21,7 +21,7 @@ package org.isoron.uhabits.core.io
import junit.framework.Assert.assertFalse
import junit.framework.Assert.assertTrue
import org.hamcrest.MatcherAssert.assertThat
import org.hamcrest.core.IsEqual
import org.hamcrest.core.IsEqual.equalTo
import org.isoron.uhabits.core.BaseUnitTest
import org.isoron.uhabits.core.models.Entry
import org.isoron.uhabits.core.models.Frequency
@ -46,11 +46,11 @@ class ImportTest : BaseUnitTest() {
@Throws(IOException::class)
fun testHabitBullCSV() {
importFromFile("habitbull.csv")
assertThat(habitList.size(), IsEqual.equalTo(4))
assertThat(habitList.size(), equalTo(4))
val habit = habitList.getByPosition(0)
assertThat(habit.name, IsEqual.equalTo("Breed dragons"))
assertThat(habit.description, IsEqual.equalTo("with love and fire"))
assertThat(habit.frequency, IsEqual.equalTo(Frequency.DAILY))
assertThat(habit.name, equalTo("Breed dragons"))
assertThat(habit.description, equalTo("with love and fire"))
assertThat(habit.frequency, equalTo(Frequency.DAILY))
assertTrue(isChecked(habit, 2016, 3, 18))
assertTrue(isChecked(habit, 2016, 3, 19))
assertFalse(isChecked(habit, 2016, 3, 20))
@ -60,10 +60,10 @@ class ImportTest : BaseUnitTest() {
@Throws(IOException::class)
fun testLoopDB() {
importFromFile("loop.db")
assertThat(habitList.size(), IsEqual.equalTo(9))
assertThat(habitList.size(), equalTo(9))
val habit = habitList.getByPosition(0)
assertThat(habit.name, IsEqual.equalTo("Wake up early"))
assertThat(habit.frequency, IsEqual.equalTo(Frequency.THREE_TIMES_PER_WEEK))
assertThat(habit.name, equalTo("Wake up early"))
assertThat(habit.frequency, equalTo(Frequency.THREE_TIMES_PER_WEEK))
assertTrue(isChecked(habit, 2016, 3, 14))
assertTrue(isChecked(habit, 2016, 3, 16))
assertFalse(isChecked(habit, 2016, 3, 17))
@ -73,33 +73,33 @@ class ImportTest : BaseUnitTest() {
@Throws(IOException::class)
fun testRewireDB() {
importFromFile("rewire.db")
assertThat(habitList.size(), IsEqual.equalTo(3))
assertThat(habitList.size(), equalTo(3))
var habit = habitList.getByPosition(1)
assertThat(habit.name, IsEqual.equalTo("Wake up early"))
assertThat(habit.frequency, IsEqual.equalTo(Frequency.THREE_TIMES_PER_WEEK))
assertThat(habit.name, equalTo("Wake up early"))
assertThat(habit.frequency, equalTo(Frequency.THREE_TIMES_PER_WEEK))
assertFalse(habit.hasReminder())
assertFalse(isChecked(habit, 2015, 12, 31))
assertTrue(isChecked(habit, 2016, 1, 18))
assertTrue(isChecked(habit, 2016, 1, 28))
assertFalse(isChecked(habit, 2016, 3, 10))
habit = habitList.getByPosition(2)
assertThat(habit.name, IsEqual.equalTo("brush teeth"))
assertThat(habit.frequency, IsEqual.equalTo(Frequency.THREE_TIMES_PER_WEEK))
assertThat(habit.hasReminder(), IsEqual.equalTo(true))
assertThat(habit.name, equalTo("brush teeth"))
assertThat(habit.frequency, equalTo(Frequency.THREE_TIMES_PER_WEEK))
assertThat(habit.hasReminder(), equalTo(true))
val reminder = habit.reminder
assertThat(reminder!!.hour, IsEqual.equalTo(8))
assertThat(reminder.minute, IsEqual.equalTo(0))
assertThat(reminder!!.hour, equalTo(8))
assertThat(reminder.minute, equalTo(0))
val reminderDays = booleanArrayOf(false, true, true, true, true, true, false)
assertThat(reminder.days.toArray(), IsEqual.equalTo(reminderDays))
assertThat(reminder.days.toArray(), equalTo(reminderDays))
}
@Test
@Throws(IOException::class)
fun testTickmateDB() {
importFromFile("tickmate.db")
assertThat(habitList.size(), IsEqual.equalTo(3))
assertThat(habitList.size(), equalTo(3))
val h = habitList.getByPosition(2)
assertThat(h.name, IsEqual.equalTo("Vegan"))
assertThat(h.name, equalTo("Vegan"))
assertTrue(isChecked(h, 2016, 1, 24))
assertTrue(isChecked(h, 2016, 2, 5))
assertTrue(isChecked(h, 2016, 3, 18))

@ -19,10 +19,10 @@
package org.isoron.uhabits.core.models
import junit.framework.Assert.assertEquals
import junit.framework.Assert.assertNotNull
import junit.framework.Assert.assertFalse
import junit.framework.Assert.assertNull
import junit.framework.TestCase
import org.hamcrest.CoreMatchers
import org.hamcrest.CoreMatchers.equalTo
import org.hamcrest.CoreMatchers.not
import org.hamcrest.MatcherAssert.assertThat
import org.isoron.uhabits.core.BaseUnitTest
import org.junit.Rule
@ -64,48 +64,25 @@ class HabitListTest : BaseUnitTest() {
@Test
fun testSize() {
assertThat(habitList.size(), CoreMatchers.equalTo(10))
assertThat(activeHabits.size(), CoreMatchers.equalTo(6))
assertThat(reminderHabits.size(), CoreMatchers.equalTo(4))
assertThat(habitList.size(), equalTo(10))
assertThat(activeHabits.size(), equalTo(6))
assertThat(reminderHabits.size(), equalTo(4))
}
@Test
fun testGetByPosition() {
assertThat(
habitList.getByPosition(0),
CoreMatchers.equalTo(
habitsArray[0]
)
)
assertThat(
habitList.getByPosition(3),
CoreMatchers.equalTo(
habitsArray[3]
)
)
assertThat(
habitList.getByPosition(9),
CoreMatchers.equalTo(
habitsArray[9]
)
)
assertThat(
activeHabits.getByPosition(0),
CoreMatchers.equalTo(
habitsArray[2]
)
)
assertThat(
reminderHabits.getByPosition(1),
CoreMatchers.equalTo(habitsArray[3])
)
assertThat(habitList.getByPosition(0), equalTo(habitsArray[0]))
assertThat(habitList.getByPosition(3), equalTo(habitsArray[3]))
assertThat(habitList.getByPosition(9), equalTo(habitsArray[9]))
assertThat(activeHabits.getByPosition(0), equalTo(habitsArray[2]))
assertThat(reminderHabits.getByPosition(1), equalTo(habitsArray[3]))
}
@Test
fun testGetById() {
val habit1 = habitsArray[0]
val habit2 = habitList.getById(habit1.id!!)
assertThat(habit1, CoreMatchers.equalTo(habit2))
assertThat(habit1, equalTo(habit2))
}
@Test
@ -128,41 +105,41 @@ class HabitListTest : BaseUnitTest() {
}
list.primaryOrder = HabitList.Order.BY_POSITION
assertThat(list.getByPosition(0), CoreMatchers.equalTo(h3))
assertThat(list.getByPosition(1), CoreMatchers.equalTo(h1))
assertThat(list.getByPosition(2), CoreMatchers.equalTo(h4))
assertThat(list.getByPosition(3), CoreMatchers.equalTo(h2))
assertThat(list.getByPosition(0), equalTo(h3))
assertThat(list.getByPosition(1), equalTo(h1))
assertThat(list.getByPosition(2), equalTo(h4))
assertThat(list.getByPosition(3), equalTo(h2))
list.primaryOrder = HabitList.Order.BY_NAME_DESC
assertThat(list.getByPosition(0), CoreMatchers.equalTo(h4))
assertThat(list.getByPosition(1), CoreMatchers.equalTo(h3))
assertThat(list.getByPosition(2), CoreMatchers.equalTo(h2))
assertThat(list.getByPosition(3), CoreMatchers.equalTo(h1))
assertThat(list.getByPosition(0), equalTo(h4))
assertThat(list.getByPosition(1), equalTo(h3))
assertThat(list.getByPosition(2), equalTo(h2))
assertThat(list.getByPosition(3), equalTo(h1))
list.primaryOrder = HabitList.Order.BY_NAME_ASC
assertThat(list.getByPosition(0), CoreMatchers.equalTo(h1))
assertThat(list.getByPosition(1), CoreMatchers.equalTo(h2))
assertThat(list.getByPosition(2), CoreMatchers.equalTo(h3))
assertThat(list.getByPosition(3), CoreMatchers.equalTo(h4))
assertThat(list.getByPosition(0), equalTo(h1))
assertThat(list.getByPosition(1), equalTo(h2))
assertThat(list.getByPosition(2), equalTo(h3))
assertThat(list.getByPosition(3), equalTo(h4))
list.primaryOrder = HabitList.Order.BY_NAME_ASC
list.remove(h1)
list.add(h1)
assertThat(list.getByPosition(0), CoreMatchers.equalTo(h1))
assertThat(list.getByPosition(0), equalTo(h1))
list.primaryOrder = HabitList.Order.BY_COLOR_ASC
list.secondaryOrder = HabitList.Order.BY_NAME_ASC
assertThat(list.getByPosition(0), CoreMatchers.equalTo(h3))
assertThat(list.getByPosition(1), CoreMatchers.equalTo(h4))
assertThat(list.getByPosition(2), CoreMatchers.equalTo(h1))
assertThat(list.getByPosition(3), CoreMatchers.equalTo(h2))
assertThat(list.getByPosition(0), equalTo(h3))
assertThat(list.getByPosition(1), equalTo(h4))
assertThat(list.getByPosition(2), equalTo(h1))
assertThat(list.getByPosition(3), equalTo(h2))
list.primaryOrder = HabitList.Order.BY_COLOR_DESC
list.secondaryOrder = HabitList.Order.BY_NAME_ASC
assertThat(list.getByPosition(0), CoreMatchers.equalTo(h1))
assertThat(list.getByPosition(1), CoreMatchers.equalTo(h2))
assertThat(list.getByPosition(2), CoreMatchers.equalTo(h4))
assertThat(list.getByPosition(3), CoreMatchers.equalTo(h3))
assertThat(list.getByPosition(0), equalTo(h1))
assertThat(list.getByPosition(1), equalTo(h2))
assertThat(list.getByPosition(2), equalTo(h4))
assertThat(list.getByPosition(3), equalTo(h3))
list.primaryOrder = HabitList.Order.BY_POSITION
assertThat(list.getByPosition(0), CoreMatchers.equalTo(h3))
assertThat(list.getByPosition(1), CoreMatchers.equalTo(h1))
assertThat(list.getByPosition(2), CoreMatchers.equalTo(h4))
assertThat(list.getByPosition(3), CoreMatchers.equalTo(h2))
assertThat(list.getByPosition(0), equalTo(h3))
assertThat(list.getByPosition(1), equalTo(h1))
assertThat(list.getByPosition(2), equalTo(h4))
assertThat(list.getByPosition(3), equalTo(h2))
}
@Test
@ -182,18 +159,13 @@ class HabitListTest : BaseUnitTest() {
val actualSequence = IntArray(10)
for (j in 0..9) {
val habit = habitList.getByPosition(j)
assertThat(habit.position, CoreMatchers.equalTo(j))
assertThat(habit.position, equalTo(j))
actualSequence[j] = Math.toIntExact(habit.id!!)
}
assertThat(
actualSequence,
CoreMatchers.equalTo(
expectedSequence[i]
)
)
assertThat(actualSequence, equalTo(expectedSequence[i]))
}
assertThat(activeHabits.indexOf(habitsArray[5]), CoreMatchers.equalTo(0))
assertThat(activeHabits.indexOf(habitsArray[2]), CoreMatchers.equalTo(1))
assertThat(activeHabits.indexOf(habitsArray[5]), equalTo(0))
assertThat(activeHabits.indexOf(habitsArray[2]), equalTo(1))
}
@Test
@ -244,26 +216,20 @@ class HabitListTest : BaseUnitTest() {
""".trimIndent()
val writer = StringWriter()
list.writeCSV(writer)
assertThat(writer.toString(), CoreMatchers.equalTo(expectedCSV))
assertThat(writer.toString(), equalTo(expectedCSV))
}
@Test
@Throws(Exception::class)
fun testAdd() {
val h1 = fixtures.createEmptyHabit()
TestCase.assertFalse(h1.isArchived)
assertFalse(h1.isArchived)
assertNull(h1.id)
assertThat(habitList.indexOf(h1), CoreMatchers.equalTo(-1))
assertThat(habitList.indexOf(h1), equalTo(-1))
habitList.add(h1)
assertNotNull(h1.id)
assertThat(
habitList.indexOf(h1),
CoreMatchers.not(CoreMatchers.equalTo(-1))
)
assertThat(
activeHabits.indexOf(h1),
CoreMatchers.not(CoreMatchers.equalTo(-1))
)
h1.id!!
assertThat(habitList.indexOf(h1), not(equalTo(-1)))
assertThat(activeHabits.indexOf(h1), not(equalTo(-1)))
}
@Test

@ -19,9 +19,9 @@
package org.isoron.uhabits.core.models
import junit.framework.Assert.assertFalse
import junit.framework.Assert.assertNotNull
import junit.framework.Assert.assertTrue
import org.hamcrest.CoreMatchers
import org.hamcrest.CoreMatchers.`is`
import org.hamcrest.core.IsEqual.equalTo
import org.isoron.uhabits.core.BaseUnitTest
import org.isoron.uhabits.core.utils.DateUtils.Companion.getToday
import org.junit.Assert.assertNotEquals
@ -41,11 +41,9 @@ class HabitTest : BaseUnitTest() {
@Test
fun testUuidGeneration() {
val (_, _, _, _, _, _, _, _, _, _, _, _, _, uuid) = modelFactory.buildHabit()
val (_, _, _, _, _, _, _, _, _, _, _, _, _, uuid1) = modelFactory.buildHabit()
assertNotNull(uuid)
assertNotNull(uuid1)
assertNotEquals(uuid, uuid1)
val uuid1 = modelFactory.buildHabit().uuid!!
val uuid2 = modelFactory.buildHabit().uuid!!
assertNotEquals(uuid1, uuid2)
}
@Test
@ -57,18 +55,19 @@ class HabitTest : BaseUnitTest() {
model.reminder = Reminder(8, 30, WeekdayList(1))
val habit = modelFactory.buildHabit()
habit.copyFrom(model)
assertThat(habit.isArchived, CoreMatchers.`is`(model.isArchived))
assertThat(habit.color, CoreMatchers.`is`(model.color))
assertThat(habit.frequency, CoreMatchers.equalTo(model.frequency))
assertThat(habit.reminder, CoreMatchers.equalTo(model.reminder))
assertTrue(habit.isArchived == model.isArchived)
assertThat(habit.isArchived, `is`(model.isArchived))
assertThat(habit.color, `is`(model.color))
assertThat(habit.frequency, equalTo(model.frequency))
assertThat(habit.reminder, equalTo(model.reminder))
}
@Test
fun test_hasReminder() {
val h = modelFactory.buildHabit()
assertThat(h.hasReminder(), CoreMatchers.`is`(false))
assertThat(h.hasReminder(), `is`(false))
h.reminder = Reminder(8, 30, WeekdayList.EVERY_DAY)
assertThat(h.hasReminder(), CoreMatchers.`is`(true))
assertThat(h.hasReminder(), `is`(true))
}
@Test
@ -116,10 +115,7 @@ class HabitTest : BaseUnitTest() {
assertTrue(habitList.isEmpty)
val h = modelFactory.buildHabit()
habitList.add(h)
assertThat(h.id, CoreMatchers.equalTo(0L))
assertThat(
h.uriString,
CoreMatchers.equalTo("content://org.isoron.uhabits/habit/0")
)
assertThat(h.id, equalTo(0L))
assertThat(h.uriString, equalTo("content://org.isoron.uhabits/habit/0"))
}
}

@ -36,56 +36,26 @@ class ScoreTest : BaseUnitTest() {
fun test_compute_withDailyHabit() {
var check = 1
val freq = 1.0
assertThat(
compute(freq, 0.0, check.toDouble()),
IsCloseTo.closeTo(0.051922, E)
)
assertThat(
compute(freq, 0.5, check.toDouble()),
IsCloseTo.closeTo(0.525961, E)
)
assertThat(
compute(freq, 0.75, check.toDouble()),
IsCloseTo.closeTo(0.762981, E)
)
assertThat(compute(freq, 0.0, check.toDouble()), IsCloseTo.closeTo(0.051922, E))
assertThat(compute(freq, 0.5, check.toDouble()), IsCloseTo.closeTo(0.525961, E))
assertThat(compute(freq, 0.75, check.toDouble()), IsCloseTo.closeTo(0.762981, E))
check = 0
assertThat(compute(freq, 0.0, check.toDouble()), IsCloseTo.closeTo(0.0, E))
assertThat(
compute(freq, 0.5, check.toDouble()),
IsCloseTo.closeTo(0.474039, E)
)
assertThat(
compute(freq, 0.75, check.toDouble()),
IsCloseTo.closeTo(0.711058, E)
)
assertThat(compute(freq, 0.5, check.toDouble()), IsCloseTo.closeTo(0.474039, E))
assertThat(compute(freq, 0.75, check.toDouble()), IsCloseTo.closeTo(0.711058, E))
}
@Test
fun test_compute_withNonDailyHabit() {
var check = 1
val freq = 1 / 3.0
assertThat(
compute(freq, 0.0, check.toDouble()),
IsCloseTo.closeTo(0.030314, E)
)
assertThat(
compute(freq, 0.5, check.toDouble()),
IsCloseTo.closeTo(0.515157, E)
)
assertThat(
compute(freq, 0.75, check.toDouble()),
IsCloseTo.closeTo(0.757578, E)
)
assertThat(compute(freq, 0.0, check.toDouble()), IsCloseTo.closeTo(0.030314, E))
assertThat(compute(freq, 0.5, check.toDouble()), IsCloseTo.closeTo(0.515157, E))
assertThat(compute(freq, 0.75, check.toDouble()), IsCloseTo.closeTo(0.757578, E))
check = 0
assertThat(compute(freq, 0.0, check.toDouble()), IsCloseTo.closeTo(0.0, E))
assertThat(
compute(freq, 0.5, check.toDouble()),
IsCloseTo.closeTo(0.484842, E)
)
assertThat(
compute(freq, 0.75, check.toDouble()),
IsCloseTo.closeTo(0.727263, E)
)
assertThat(compute(freq, 0.5, check.toDouble()), IsCloseTo.closeTo(0.484842, E))
assertThat(compute(freq, 0.75, check.toDouble()), IsCloseTo.closeTo(0.727263, E))
}
companion object {

@ -18,16 +18,16 @@
*/
package org.isoron.uhabits.core.models
import org.hamcrest.CoreMatchers.equalTo
import org.hamcrest.MatcherAssert.assertThat
import org.hamcrest.core.IsEqual
import org.isoron.uhabits.core.BaseUnitTest
import org.isoron.uhabits.core.utils.DateUtils.Companion.getToday
import org.junit.Test
class StreakListTest : BaseUnitTest() {
private lateinit var habit: Habit
private var streaks: StreakList? = null
private var today: Timestamp? = null
private lateinit var streaks: StreakList
private lateinit var today: Timestamp
@Throws(Exception::class)
override fun setUp() {
@ -42,26 +42,26 @@ class StreakListTest : BaseUnitTest() {
@Test
@Throws(Exception::class)
fun testGetBest() {
var best = streaks!!.getBest(4)
assertThat(best.size, IsEqual.equalTo(4))
assertThat(best[0].length, IsEqual.equalTo(4))
assertThat(best[1].length, IsEqual.equalTo(3))
assertThat(best[2].length, IsEqual.equalTo(5))
assertThat(best[3].length, IsEqual.equalTo(6))
best = streaks!!.getBest(2)
assertThat(best.size, IsEqual.equalTo(2))
assertThat(best[0].length, IsEqual.equalTo(5))
assertThat(best[1].length, IsEqual.equalTo(6))
var best = streaks.getBest(4)
assertThat(best.size, equalTo(4))
assertThat(best[0].length, equalTo(4))
assertThat(best[1].length, equalTo(3))
assertThat(best[2].length, equalTo(5))
assertThat(best[3].length, equalTo(6))
best = streaks.getBest(2)
assertThat(best.size, equalTo(2))
assertThat(best[0].length, equalTo(5))
assertThat(best[1].length, equalTo(6))
}
@Test
fun testGetBest_withUnknowns() {
habit.originalEntries.clear()
habit.originalEntries.add(Entry(today!!, Entry.YES_MANUAL))
habit.originalEntries.add(Entry(today!!.minus(5), Entry.NO))
habit.originalEntries.add(Entry(today, Entry.YES_MANUAL))
habit.originalEntries.add(Entry(today.minus(5), Entry.NO))
habit.recompute()
val best = streaks!!.getBest(5)
assertThat(best.size, IsEqual.equalTo(1))
assertThat(best[0].length, IsEqual.equalTo(1))
val best = streaks.getBest(5)
assertThat(best.size, equalTo(1))
assertThat(best[0].length, equalTo(1))
}
}

@ -18,8 +18,8 @@
*/
package org.isoron.uhabits.core.models
import junit.framework.Assert.assertFalse
import junit.framework.Assert.assertTrue
import junit.framework.TestCase
import org.hamcrest.MatcherAssert.assertThat
import org.hamcrest.Matchers.equalTo
import org.hamcrest.Matchers.greaterThan
@ -39,10 +39,10 @@ class TimestampTest : BaseUnitTest() {
assertThat(t1.compareTo(t1), equalTo(0))
assertThat(t1.compareTo(t3), lessThan(0))
assertTrue(t1.isNewerThan(t2))
TestCase.assertFalse(t1.isNewerThan(t1))
TestCase.assertFalse(t2.isNewerThan(t1))
assertFalse(t1.isNewerThan(t1))
assertFalse(t2.isNewerThan(t1))
assertTrue(t2.isOlderThan(t1))
TestCase.assertFalse(t1.isOlderThan(t2))
assertFalse(t1.isOlderThan(t2))
}
@Test

@ -20,8 +20,8 @@ package org.isoron.uhabits.core.models
import junit.framework.Assert.assertFalse
import junit.framework.Assert.assertTrue
import org.hamcrest.CoreMatchers.equalTo
import org.hamcrest.MatcherAssert.assertThat
import org.hamcrest.core.IsEqual
import org.isoron.uhabits.core.BaseUnitTest
import org.junit.Test
@ -29,21 +29,13 @@ class WeekdayListTest : BaseUnitTest() {
@Test
fun test() {
val daysInt = 124
val daysArray = booleanArrayOf(
false,
false,
true,
true,
true,
true,
true
)
val daysArray = booleanArrayOf(false, false, true, true, true, true, true)
var list = WeekdayList(daysArray)
assertThat(list.toArray(), IsEqual.equalTo(daysArray))
assertThat(list.toInteger(), IsEqual.equalTo(daysInt))
assertThat(list.toArray(), equalTo(daysArray))
assertThat(list.toInteger(), equalTo(daysInt))
list = WeekdayList(daysInt)
assertThat(list.toArray(), IsEqual.equalTo(daysArray))
assertThat(list.toInteger(), IsEqual.equalTo(daysInt))
assertThat(list.toArray(), equalTo(daysArray))
assertThat(list.toInteger(), equalTo(daysInt))
}
@Test

@ -20,7 +20,6 @@
package org.isoron.uhabits.core.models.sqlite
import junit.framework.Assert.assertEquals
import junit.framework.Assert.assertNotNull
import junit.framework.Assert.assertNull
import org.isoron.uhabits.core.BaseUnitTest.Companion.buildMemoryDatabase
import org.isoron.uhabits.core.database.Repository
@ -87,22 +86,17 @@ class SQLiteEntryListTest {
val original = Entry(today, 150)
entries.add(original)
val retrieved = getByTimestamp(1, today)
assertNotNull(retrieved)
assertEquals(original, retrieved!!.toEntry())
val retrieved = getByTimestamp(1, today)!!
assertEquals(original, retrieved.toEntry())
val replacement = Entry(today, 90)
entries.add(replacement)
val retrieved2 = getByTimestamp(1, today)
assertNotNull(retrieved2)
assertEquals(replacement, retrieved2!!.toEntry())
val retrieved2 = getByTimestamp(1, today)!!
assertEquals(replacement, retrieved2.toEntry())
}
private fun getByTimestamp(
habitId: Int,
timestamp: Timestamp,
): EntryRecord? {
private fun getByTimestamp(habitId: Int, timestamp: Timestamp): EntryRecord? {
return repository.findFirst(
"where habit = ? and timestamp = ?",
habitId.toString(),

@ -18,9 +18,10 @@
*/
package org.isoron.uhabits.core.models.sqlite
import junit.framework.Assert.assertNotNull
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.verify
import junit.framework.Assert.assertNull
import org.hamcrest.CoreMatchers
import org.hamcrest.CoreMatchers.equalTo
import org.hamcrest.MatcherAssert.assertThat
import org.isoron.uhabits.core.BaseUnitTest
import org.isoron.uhabits.core.database.Database
@ -36,17 +37,17 @@ import org.isoron.uhabits.core.test.HabitFixtures
import org.junit.Rule
import org.junit.Test
import org.junit.rules.ExpectedException
import org.mockito.Mockito
import java.util.ArrayList
class SQLiteHabitListTest : BaseUnitTest() {
@get:Rule
var exception = ExpectedException.none()!!
private lateinit var repository: Repository<HabitRecord>
private lateinit var listener: ModelObservable.Listener
private var listener: ModelObservable.Listener = mock()
private lateinit var habitsArray: ArrayList<Habit>
private lateinit var activeHabits: HabitList
private lateinit var reminderHabits: HabitList
@Throws(Exception::class)
override fun setUp() {
super.setUp()
@ -54,10 +55,7 @@ class SQLiteHabitListTest : BaseUnitTest() {
modelFactory = SQLModelFactory(db)
habitList = SQLiteHabitList(modelFactory)
fixtures = HabitFixtures(modelFactory, habitList)
repository = Repository(
HabitRecord::class.java,
db
)
repository = Repository(HabitRecord::class.java, db)
habitsArray = ArrayList()
for (i in 0..9) {
val habit = fixtures.createEmptyHabit()
@ -78,7 +76,6 @@ class SQLiteHabitListTest : BaseUnitTest() {
.setReminderRequired(true)
.build()
)
listener = Mockito.mock(ModelObservable.Listener::class.java)
habitList.observable.addListener(listener)
}
@ -92,7 +89,7 @@ class SQLiteHabitListTest : BaseUnitTest() {
fun testAdd_withDuplicate() {
val habit = modelFactory.buildHabit()
habitList.add(habit)
Mockito.verify(listener)!!.onModelChange()
verify(listener).onModelChange()
exception.expect(IllegalArgumentException::class.java)
habitList.add(habit)
}
@ -103,10 +100,9 @@ class SQLiteHabitListTest : BaseUnitTest() {
habit.name = "Hello world with id"
habit.id = 12300L
habitList.add(habit)
assertThat(habit.id, CoreMatchers.equalTo(12300L))
assertThat(habit.id, equalTo(12300L))
val record = repository.find(12300L)
assertNotNull(record)
assertThat(record!!.name, CoreMatchers.equalTo(habit.name))
assertThat(record!!.name, equalTo(habit.name))
}
@Test
@ -115,27 +111,21 @@ class SQLiteHabitListTest : BaseUnitTest() {
habit.name = "Hello world"
assertNull(habit.id)
habitList.add(habit)
assertNotNull(habit.id)
val record = repository.find(
habit.id!!
)
assertNotNull(record)
assertThat(record!!.name, CoreMatchers.equalTo(habit.name))
val record = repository.find(habit.id!!)
assertThat(record!!.name, equalTo(habit.name))
}
@Test
fun testSize() {
assertThat(habitList.size(), CoreMatchers.equalTo(10))
assertThat(habitList.size(), equalTo(10))
}
@Test
fun testGetById() {
val h1 = habitList.getById(1)
assertNotNull(h1)
assertThat(h1!!.name, CoreMatchers.equalTo("habit 1"))
val h2 = habitList.getById(2)
assertNotNull(h2)
assertThat(h2, CoreMatchers.equalTo(h2))
val h1 = habitList.getById(1)!!
assertThat(h1.name, equalTo("habit 1"))
val h2 = habitList.getById(2)!!
assertThat(h2, equalTo(h2))
}
@Test
@ -148,19 +138,17 @@ class SQLiteHabitListTest : BaseUnitTest() {
@Test
fun testGetByPosition() {
val h = habitList.getByPosition(4)
assertNotNull(h)
assertThat(h.name, CoreMatchers.equalTo("habit 5"))
assertThat(h.name, equalTo("habit 5"))
}
@Test
fun testIndexOf() {
val h1 = habitList.getByPosition(5)
assertNotNull(h1)
assertThat(habitList.indexOf(h1), CoreMatchers.equalTo(5))
assertThat(habitList.indexOf(h1), equalTo(5))
val h2 = modelFactory.buildHabit()
assertThat(habitList.indexOf(h2), CoreMatchers.equalTo(-1))
assertThat(habitList.indexOf(h2), equalTo(-1))
h2.id = 1000L
assertThat(habitList.indexOf(h2), CoreMatchers.equalTo(-1))
assertThat(habitList.indexOf(h2), equalTo(-1))
}
@Test
@ -168,26 +156,21 @@ class SQLiteHabitListTest : BaseUnitTest() {
fun testRemove() {
val h = habitList.getById(2)
habitList.remove(h!!)
assertThat(habitList.indexOf(h), CoreMatchers.equalTo(-1))
assertThat(habitList.indexOf(h), equalTo(-1))
var rec = repository.find(2L)
assertNull(rec)
rec = repository.find(3L)
assertNotNull(rec)
assertThat(rec!!.position, CoreMatchers.equalTo(1))
rec = repository.find(3L)!!
assertThat(rec.position, equalTo(1))
}
@Test
fun testReorder() {
val habit3 = habitList.getById(3)
val habit4 = habitList.getById(4)
assertNotNull(habit3)
assertNotNull(habit4)
habitList.reorder(habit4!!, habit3!!)
val record3 = repository.find(3L)
assertNotNull(record3)
assertThat(record3!!.position, CoreMatchers.equalTo(3))
val record4 = repository.find(4L)
assertNotNull(record4)
assertThat(record4!!.position, CoreMatchers.equalTo(2))
val habit3 = habitList.getById(3)!!
val habit4 = habitList.getById(4)!!
habitList.reorder(habit4, habit3)
val record3 = repository.find(3L)!!
assertThat(record3.position, equalTo(3))
val record4 = repository.find(4L)!!
assertThat(record4.position, equalTo(2))
}
}

@ -18,8 +18,8 @@
*/
package org.isoron.uhabits.core.models.sqlite.records
import org.hamcrest.CoreMatchers.equalTo
import org.hamcrest.MatcherAssert.assertThat
import org.hamcrest.core.IsEqual
import org.isoron.uhabits.core.BaseUnitTest
import org.isoron.uhabits.core.models.Entry
import org.isoron.uhabits.core.models.Timestamp
@ -32,6 +32,6 @@ class EntryRecordTest : BaseUnitTest() {
val check = Entry(Timestamp.ZERO.plus(100), 50)
val record = EntryRecord()
record.copyFrom(check)
assertThat(check, IsEqual.equalTo(record.toEntry()))
assertThat(check, equalTo(record.toEntry()))
}
}

@ -18,8 +18,8 @@
*/
package org.isoron.uhabits.core.models.sqlite.records
import org.hamcrest.CoreMatchers.equalTo
import org.hamcrest.MatcherAssert.assertThat
import org.hamcrest.core.IsEqual
import org.isoron.uhabits.core.BaseUnitTest
import org.isoron.uhabits.core.models.Frequency
import org.isoron.uhabits.core.models.Habit
@ -31,41 +31,43 @@ import org.junit.Test
class HabitRecordTest : BaseUnitTest() {
@Test
fun testCopyRestore1() {
val original = modelFactory.buildHabit()
original.name = "Hello world"
original.question = "Did you greet the world today?"
original.color = PaletteColor(1)
original.isArchived = true
original.frequency = Frequency.THREE_TIMES_PER_WEEK
original.reminder = Reminder(8, 30, WeekdayList.EVERY_DAY)
original.id = 1000L
original.position = 20
val original = modelFactory.buildHabit().apply() {
name = "Hello world"
question = "Did you greet the world today?"
color = PaletteColor(1)
isArchived = true
frequency = Frequency.THREE_TIMES_PER_WEEK
reminder = Reminder(8, 30, WeekdayList.EVERY_DAY)
id = 1000L
position = 20
}
val record = HabitRecord()
record.copyFrom(original)
val duplicate = modelFactory.buildHabit()
record.copyTo(duplicate)
assertThat(original, IsEqual.equalTo(duplicate))
assertThat(original, equalTo(duplicate))
}
@Test
fun testCopyRestore2() {
val original = modelFactory.buildHabit()
original.name = "Hello world"
original.question = "Did you greet the world today?"
original.color = PaletteColor(5)
original.isArchived = false
original.frequency = Frequency.DAILY
original.reminder = null
original.id = 1L
original.position = 15
original.type = Habit.NUMBER_HABIT
original.targetValue = 100.0
original.targetType = Habit.AT_LEAST
original.unit = "miles"
val original = modelFactory.buildHabit().apply() {
name = "Hello world"
question = "Did you greet the world today?"
color = PaletteColor(5)
isArchived = false
frequency = Frequency.DAILY
reminder = null
id = 1L
position = 15
type = Habit.NUMBER_HABIT
targetValue = 100.0
targetType = Habit.AT_LEAST
unit = "miles"
}
val record = HabitRecord()
record.copyFrom(original)
val duplicate = modelFactory.buildHabit()
record.copyTo(duplicate)
assertThat(original, IsEqual.equalTo(duplicate))
assertThat(original, equalTo(duplicate))
}
}

@ -18,26 +18,25 @@
*/
package org.isoron.uhabits.core.preferences
import com.nhaarman.mockitokotlin2.mock
import junit.framework.Assert.assertFalse
import junit.framework.Assert.assertNull
import junit.framework.Assert.assertTrue
import org.hamcrest.CoreMatchers.equalTo
import org.hamcrest.MatcherAssert.assertThat
import org.hamcrest.core.IsEqual
import org.isoron.uhabits.core.BaseUnitTest
import org.isoron.uhabits.core.models.HabitList
import org.isoron.uhabits.core.models.Timestamp
import org.isoron.uhabits.core.models.Timestamp.ZERO
import org.isoron.uhabits.core.ui.ThemeSwitcher
import org.junit.Before
import org.junit.Test
import org.mockito.Mock
import java.io.File
class PreferencesTest : BaseUnitTest() {
private lateinit var prefs: Preferences
@Mock
private val listener: Preferences.Listener? = null
private var storage: PropertiesStorage? = null
private var listener: Preferences.Listener = mock()
private lateinit var storage: PropertiesStorage
@Before
@Throws(Exception::class)
@ -46,7 +45,7 @@ class PreferencesTest : BaseUnitTest() {
val file = File.createTempFile("prefs", ".properties")
file.deleteOnExit()
storage = PropertiesStorage(file)
prefs = Preferences(storage!!)
prefs = Preferences(storage)
prefs.addListener(listener)
}
@ -55,66 +54,57 @@ class PreferencesTest : BaseUnitTest() {
fun testClear() {
prefs.setDefaultHabitColor(99)
prefs.clear()
assertThat(prefs.getDefaultHabitColor(0), IsEqual.equalTo(0))
assertThat(prefs.getDefaultHabitColor(0), equalTo(0))
}
@Test
@Throws(Exception::class)
fun testHabitColor() {
assertThat(prefs.getDefaultHabitColor(999), IsEqual.equalTo(999))
assertThat(prefs.getDefaultHabitColor(999), equalTo(999))
prefs.setDefaultHabitColor(10)
assertThat(prefs.getDefaultHabitColor(999), IsEqual.equalTo(10))
assertThat(prefs.getDefaultHabitColor(999), equalTo(10))
}
@Test
@Throws(Exception::class)
fun testDefaultOrder() {
assertThat(
prefs.defaultPrimaryOrder,
IsEqual.equalTo(HabitList.Order.BY_POSITION)
)
assertThat(prefs.defaultPrimaryOrder, equalTo(HabitList.Order.BY_POSITION))
prefs.defaultPrimaryOrder = HabitList.Order.BY_SCORE_DESC
assertThat(prefs.defaultPrimaryOrder, equalTo(HabitList.Order.BY_SCORE_DESC))
storage.putString("pref_default_order", "BOGUS")
assertThat(prefs.defaultPrimaryOrder, equalTo(HabitList.Order.BY_POSITION))
assertThat(
prefs.defaultPrimaryOrder,
IsEqual.equalTo(HabitList.Order.BY_SCORE_DESC)
)
storage!!.putString("pref_default_order", "BOGUS")
assertThat(
prefs.defaultPrimaryOrder,
IsEqual.equalTo(HabitList.Order.BY_POSITION)
)
assertThat(
storage!!.getString("pref_default_order", ""),
IsEqual.equalTo("BY_POSITION")
storage.getString("pref_default_order", ""),
equalTo("BY_POSITION")
)
}
@Test
@Throws(Exception::class)
fun testScoreCardSpinnerPosition() {
assertThat(prefs.scoreCardSpinnerPosition, IsEqual.equalTo(1))
assertThat(prefs.scoreCardSpinnerPosition, equalTo(1))
prefs.scoreCardSpinnerPosition = 4
assertThat(prefs.scoreCardSpinnerPosition, IsEqual.equalTo(4))
storage!!.putInt("pref_score_view_interval", 9000)
assertThat(prefs.scoreCardSpinnerPosition, IsEqual.equalTo(4))
assertThat(prefs.scoreCardSpinnerPosition, equalTo(4))
storage.putInt("pref_score_view_interval", 9000)
assertThat(prefs.scoreCardSpinnerPosition, equalTo(4))
}
@Test
@Throws(Exception::class)
fun testLastHint() {
assertThat(prefs.lastHintNumber, IsEqual.equalTo(-1))
assertThat(prefs.lastHintNumber, equalTo(-1))
assertNull(prefs.lastHintTimestamp)
prefs.updateLastHint(34, Timestamp.ZERO.plus(100))
assertThat(prefs.lastHintNumber, IsEqual.equalTo(34))
assertThat(prefs.lastHintTimestamp, IsEqual.equalTo(Timestamp.ZERO.plus(100)))
prefs.updateLastHint(34, ZERO.plus(100))
assertThat(prefs.lastHintNumber, equalTo(34))
assertThat(prefs.lastHintTimestamp, equalTo(ZERO.plus(100)))
}
@Test
@Throws(Exception::class)
fun testTheme() {
assertThat(prefs.theme, IsEqual.equalTo(ThemeSwitcher.THEME_AUTOMATIC))
assertThat(prefs.theme, equalTo(ThemeSwitcher.THEME_AUTOMATIC))
prefs.theme = ThemeSwitcher.THEME_DARK
assertThat(prefs.theme, IsEqual.equalTo(ThemeSwitcher.THEME_DARK))
assertThat(prefs.theme, equalTo(ThemeSwitcher.THEME_DARK))
assertFalse(prefs.isPureBlackEnabled)
prefs.isPureBlackEnabled = true
assertTrue(prefs.isPureBlackEnabled)
@ -129,23 +119,23 @@ class PreferencesTest : BaseUnitTest() {
assertFalse(prefs.shouldMakeNotificationsLed())
prefs.setNotificationsLed(true)
assertTrue(prefs.shouldMakeNotificationsLed())
assertThat(prefs.snoozeInterval, IsEqual.equalTo(15L))
assertThat(prefs.snoozeInterval, equalTo(15L))
prefs.setSnoozeInterval(30)
assertThat(prefs.snoozeInterval, IsEqual.equalTo(30L))
assertThat(prefs.snoozeInterval, equalTo(30L))
}
@Test
@Throws(Exception::class)
fun testAppVersionAndLaunch() {
assertThat(prefs.lastAppVersion, IsEqual.equalTo(0))
assertThat(prefs.lastAppVersion, equalTo(0))
prefs.lastAppVersion = 23
assertThat(prefs.lastAppVersion, IsEqual.equalTo(23))
assertThat(prefs.lastAppVersion, equalTo(23))
assertTrue(prefs.isFirstRun)
prefs.isFirstRun = false
assertFalse(prefs.isFirstRun)
assertThat(prefs.launchCount, IsEqual.equalTo(0))
assertThat(prefs.launchCount, equalTo(0))
prefs.incrementLaunchCount()
assertThat(prefs.launchCount, IsEqual.equalTo(1))
assertThat(prefs.launchCount, equalTo(1))
}
@Test

@ -18,10 +18,11 @@
*/
package org.isoron.uhabits.core.preferences
import junit.framework.Assert.assertEquals
import junit.framework.Assert.assertFalse
import junit.framework.Assert.assertTrue
import junit.framework.TestCase
import org.hamcrest.CoreMatchers.equalTo
import org.hamcrest.MatcherAssert.assertThat
import org.hamcrest.core.IsEqual
import org.isoron.uhabits.core.BaseUnitTest
import org.junit.Before
import org.junit.Test
@ -29,7 +30,7 @@ import java.io.File
import java.util.Arrays
class PropertiesStorageTest : BaseUnitTest() {
private var storage: PropertiesStorage? = null
private lateinit var storage: PropertiesStorage
private lateinit var file: File
@Before
@ -44,39 +45,37 @@ class PropertiesStorageTest : BaseUnitTest() {
@Test
@Throws(Exception::class)
fun testPutGetRemove() {
storage!!.putBoolean("booleanKey", true)
assertTrue(storage!!.getBoolean("booleanKey", false))
TestCase.assertFalse(storage!!.getBoolean("random", false))
storage!!.putInt("intKey", 64)
assertThat(storage!!.getInt("intKey", 200), IsEqual.equalTo(64))
assertThat(storage!!.getInt("random", 200), IsEqual.equalTo(200))
storage!!.putLong("longKey", 64L)
assertThat(storage!!.getLong("intKey", 200L), IsEqual.equalTo(64L))
assertThat(storage!!.getLong("random", 200L), IsEqual.equalTo(200L))
storage!!.putString("stringKey", "Hello")
assertThat(storage!!.getString("stringKey", ""), IsEqual.equalTo("Hello"))
assertThat(storage!!.getString("random", ""), IsEqual.equalTo(""))
storage!!.remove("stringKey")
assertThat(storage!!.getString("stringKey", ""), IsEqual.equalTo(""))
storage!!.clear()
assertThat(storage!!.getLong("intKey", 200L), IsEqual.equalTo(200L))
TestCase.assertFalse(storage!!.getBoolean("booleanKey", false))
storage.putBoolean("booleanKey", true)
assertTrue(storage.getBoolean("booleanKey", false))
assertFalse(storage.getBoolean("random", false))
storage.putInt("intKey", 64)
assertThat(storage.getInt("intKey", 200), equalTo(64))
assertThat(storage.getInt("random", 200), equalTo(200))
storage.putLong("longKey", 64L)
assertThat(storage.getLong("intKey", 200L), equalTo(64L))
assertThat(storage.getLong("random", 200L), equalTo(200L))
storage.putString("stringKey", "Hello")
assertThat(storage.getString("stringKey", ""), equalTo("Hello"))
assertThat(storage.getString("random", ""), equalTo(""))
storage.remove("stringKey")
assertThat(storage.getString("stringKey", ""), equalTo(""))
storage.clear()
assertThat(storage.getLong("intKey", 200L), equalTo(200L))
assertFalse(storage.getBoolean("booleanKey", false))
}
@Test
@Throws(Exception::class)
fun testPersistence() {
storage!!.putBoolean("booleanKey", true)
storage!!.putInt("intKey", 64)
storage!!.putLong("longKey", 64L)
storage!!.putString("stringKey", "Hello")
val storage2 = PropertiesStorage(
file
)
storage.putBoolean("booleanKey", true)
storage.putInt("intKey", 64)
storage.putLong("longKey", 64L)
storage.putString("stringKey", "Hello")
val storage2 = PropertiesStorage(file)
assertTrue(storage2.getBoolean("booleanKey", false))
assertThat(storage2.getInt("intKey", 200), IsEqual.equalTo(64))
assertThat(storage2.getLong("intKey", 200L), IsEqual.equalTo(64L))
assertThat(storage2.getString("stringKey", ""), IsEqual.equalTo("Hello"))
assertThat(storage2.getInt("intKey", 200), equalTo(64))
assertThat(storage2.getLong("intKey", 200L), equalTo(64L))
assertThat(storage2.getString("stringKey", ""), equalTo("Hello"))
}
@Test
@ -86,18 +85,18 @@ class PropertiesStorageTest : BaseUnitTest() {
val expected2 = longArrayOf(1L)
val expected3 = longArrayOf()
val expected4 = longArrayOf()
storage!!.putLongArray("key1", expected1)
storage!!.putLongArray("key2", expected2)
storage!!.putLongArray("key3", expected3)
val actual1 = storage!!.getLongArray("key1", longArrayOf())
val actual2 = storage!!.getLongArray("key2", longArrayOf())
val actual3 = storage!!.getLongArray("key3", longArrayOf())
val actual4 = storage!!.getLongArray("invalidKey", longArrayOf())
storage.putLongArray("key1", expected1)
storage.putLongArray("key2", expected2)
storage.putLongArray("key3", expected3)
val actual1 = storage.getLongArray("key1", longArrayOf())
val actual2 = storage.getLongArray("key2", longArrayOf())
val actual3 = storage.getLongArray("key3", longArrayOf())
val actual4 = storage.getLongArray("invalidKey", longArrayOf())
assertTrue(Arrays.equals(actual1, expected1))
assertTrue(Arrays.equals(actual2, expected2))
assertTrue(Arrays.equals(actual3, expected3))
assertTrue(Arrays.equals(actual4, expected4))
TestCase.assertEquals("1,2,3,5", storage!!.getString("key1", ""))
TestCase.assertEquals(1, storage!!.getLong("key2", -1))
assertEquals("1,2,3,5", storage.getString("key1", ""))
assertEquals(1, storage.getLong("key2", -1))
}
}

@ -18,6 +18,10 @@
*/
package org.isoron.uhabits.core.reminders
import com.nhaarman.mockitokotlin2.eq
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.verify
import com.nhaarman.mockitokotlin2.whenever
import org.isoron.uhabits.core.BaseUnitTest
import org.isoron.uhabits.core.models.Habit
import org.isoron.uhabits.core.models.Reminder
@ -31,9 +35,7 @@ import org.isoron.uhabits.core.utils.DateUtils.Companion.setFixedTimeZone
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.ArgumentMatchers
import org.mockito.Mock
import org.mockito.Mockito
import org.mockito.ArgumentMatchers.anyLong
import org.mockito.junit.MockitoJUnitRunner
import java.util.Calendar
import java.util.TimeZone
@ -41,22 +43,20 @@ import java.util.TimeZone
@RunWith(MockitoJUnitRunner::class)
class ReminderSchedulerTest : BaseUnitTest() {
private val habitId = 10L
private var habit: Habit? = null
private var reminderScheduler: ReminderScheduler? = null
private lateinit var habit: Habit
private lateinit var reminderScheduler: ReminderScheduler
@Mock
private val sys: ReminderScheduler.SystemScheduler? = null
private val sys: ReminderScheduler.SystemScheduler = mock()
private val widgetPreferences: WidgetPreferences = mock()
@Mock
private val widgetPreferences: WidgetPreferences? = null
@Before
@Throws(Exception::class)
override fun setUp() {
super.setUp()
habit = fixtures.createEmptyHabit()
habit!!.id = habitId
habit.id = habitId
reminderScheduler =
ReminderScheduler(commandRunner, habitList, sys!!, widgetPreferences!!)
ReminderScheduler(commandRunner, habitList, sys, widgetPreferences)
setFixedTimeZone(TimeZone.getTimeZone("GMT-4"))
}
@ -73,16 +73,16 @@ class ReminderSchedulerTest : BaseUnitTest() {
habitList.add(h1)
habitList.add(h2)
habitList.add(h3)
reminderScheduler!!.scheduleAll()
Mockito.verify(sys)!!.scheduleShowReminder(
ArgumentMatchers.eq(unixTime(2015, 1, 27, 12, 30)),
ArgumentMatchers.eq(h1),
ArgumentMatchers.anyLong()
reminderScheduler.scheduleAll()
verify(sys).scheduleShowReminder(
eq(unixTime(2015, 1, 27, 12, 30)),
eq(h1),
anyLong()
)
Mockito.verify(sys)!!.scheduleShowReminder(
ArgumentMatchers.eq(unixTime(2015, 1, 26, 22, 30)),
ArgumentMatchers.eq(h2),
ArgumentMatchers.anyLong()
verify(sys).scheduleShowReminder(
eq(unixTime(2015, 1, 26, 22, 30)),
eq(h2),
anyLong()
)
}
@ -90,7 +90,7 @@ class ReminderSchedulerTest : BaseUnitTest() {
fun testSchedule_atSpecificTime() {
val atTime = unixTime(2015, 1, 30, 11, 30)
val expectedCheckmarkTime = unixTime(2015, 1, 30, 0, 0)
habit!!.reminder = Reminder(8, 30, WeekdayList.EVERY_DAY)
habit.reminder = Reminder(8, 30, WeekdayList.EVERY_DAY)
scheduleAndVerify(atTime, expectedCheckmarkTime, atTime)
}
@ -103,13 +103,14 @@ class ReminderSchedulerTest : BaseUnitTest() {
val regularReminderTime = applyTimezone(unixTime(2015, 1, 2, 8, 30))
val todayCheckmarkTime = unixTime(2015, 1, 1, 0, 0)
val tomorrowCheckmarkTime = unixTime(2015, 1, 2, 0, 0)
habit!!.reminder = Reminder(8, 30, WeekdayList.EVERY_DAY)
Mockito.`when`(widgetPreferences!!.getSnoozeTime(habitId)).thenReturn(snoozeTimeInFuture)
reminderScheduler!!.schedule(habit!!)
Mockito.verify(sys)!!.scheduleShowReminder(snoozeTimeInFuture, habit, todayCheckmarkTime)
Mockito.`when`(widgetPreferences.getSnoozeTime(habitId)).thenReturn(snoozeTimeInPast)
reminderScheduler!!.schedule(habit!!)
Mockito.verify(sys)!!.scheduleShowReminder(regularReminderTime, habit, tomorrowCheckmarkTime)
habit.reminder = Reminder(8, 30, WeekdayList.EVERY_DAY)
whenever(widgetPreferences.getSnoozeTime(habitId)).thenReturn(snoozeTimeInFuture)
reminderScheduler.schedule(habit)
verify(sys).scheduleShowReminder(snoozeTimeInFuture, habit, todayCheckmarkTime)
whenever(widgetPreferences.getSnoozeTime(habitId)).thenReturn(snoozeTimeInPast)
reminderScheduler.schedule(habit)
verify(sys)
.scheduleShowReminder(regularReminderTime, habit, tomorrowCheckmarkTime)
}
@Test
@ -118,7 +119,7 @@ class ReminderSchedulerTest : BaseUnitTest() {
setFixedLocalTime(now)
val expectedCheckmarkTime = unixTime(2015, 1, 26, 0, 0)
val expectedReminderTime = unixTime(2015, 1, 26, 12, 30)
habit!!.reminder = Reminder(8, 30, WeekdayList.EVERY_DAY)
habit.reminder = Reminder(8, 30, WeekdayList.EVERY_DAY)
scheduleAndVerify(null, expectedCheckmarkTime, expectedReminderTime)
}
@ -128,13 +129,13 @@ class ReminderSchedulerTest : BaseUnitTest() {
setFixedLocalTime(now)
val expectedCheckmarkTime = unixTime(2015, 1, 27, 0, 0)
val expectedReminderTime = unixTime(2015, 1, 27, 12, 30)
habit!!.reminder = Reminder(8, 30, WeekdayList.EVERY_DAY)
habit.reminder = Reminder(8, 30, WeekdayList.EVERY_DAY)
scheduleAndVerify(null, expectedCheckmarkTime, expectedReminderTime)
}
@Test
fun testSchedule_withoutReminder() {
reminderScheduler!!.schedule(habit!!)
reminderScheduler.schedule(habit)
}
override fun unixTime(year: Int, month: Int, day: Int, hour: Int, minute: Int): Long {
@ -148,11 +149,11 @@ class ReminderSchedulerTest : BaseUnitTest() {
expectedCheckmarkTime: Long,
expectedReminderTime: Long
) {
if (atTime == null) reminderScheduler!!.schedule(habit!!) else reminderScheduler!!.scheduleAtTime(
habit!!,
if (atTime == null) reminderScheduler.schedule(habit) else reminderScheduler.scheduleAtTime(
habit,
atTime
)
Mockito.verify(sys)!!.scheduleShowReminder(
verify(sys).scheduleShowReminder(
expectedReminderTime,
habit,
expectedCheckmarkTime

@ -18,28 +18,29 @@
*/
package org.isoron.uhabits.core.tasks
import com.nhaarman.mockitokotlin2.inOrder
import com.nhaarman.mockitokotlin2.mock
import org.isoron.uhabits.core.BaseUnitTest
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
import org.mockito.Mockito
@RunWith(JUnit4::class)
class SingleThreadTaskRunnerTest : BaseUnitTest() {
private var runner: SingleThreadTaskRunner? = null
private lateinit var task: Task
private lateinit var runner: SingleThreadTaskRunner
private var task: Task = mock()
@Throws(Exception::class)
override fun setUp() {
super.setUp()
runner = SingleThreadTaskRunner()
task = Mockito.mock(Task::class.java)
}
@Test
fun test() {
runner!!.execute(task)
val inOrder = Mockito.inOrder(task)
inOrder.verify(task).onAttached(runner!!)
runner.execute(task)
val inOrder = inOrder(task)
inOrder.verify(task).onAttached(runner)
inOrder.verify(task).onPreExecute()
inOrder.verify(task).doInBackground()
inOrder.verify(task).onPostExecute()

@ -18,20 +18,22 @@
*/
package org.isoron.uhabits.core.ui.screens.habits.list
import junit.framework.Assert.assertNotNull
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.reset
import com.nhaarman.mockitokotlin2.verify
import com.nhaarman.mockitokotlin2.verifyNoMoreInteractions
import org.hamcrest.CoreMatchers.equalTo
import org.hamcrest.MatcherAssert.assertThat
import org.hamcrest.core.IsEqual
import org.isoron.uhabits.core.BaseUnitTest
import org.isoron.uhabits.core.commands.CreateRepetitionCommand
import org.isoron.uhabits.core.commands.DeleteHabitsCommand
import org.isoron.uhabits.core.models.Entry
import org.isoron.uhabits.core.utils.DateUtils.Companion.getToday
import org.junit.Test
import org.mockito.Mockito
class HabitCardListCacheTest : BaseUnitTest() {
private var cache: HabitCardListCache? = null
private var listener: HabitCardListCache.Listener? = null
private lateinit var cache: HabitCardListCache
private lateinit var listener: HabitCardListCache.Listener
var today = getToday()
@Throws(Exception::class)
@ -42,86 +44,83 @@ class HabitCardListCacheTest : BaseUnitTest() {
if (i == 3) habitList.add(fixtures.createLongHabit()) else habitList.add(fixtures.createShortHabit())
}
cache = HabitCardListCache(habitList, commandRunner, taskRunner)
cache!!.setCheckmarkCount(10)
cache!!.refreshAllHabits()
cache!!.onAttached()
listener = Mockito.mock(
HabitCardListCache.Listener::class.java
)
cache!!.setListener(listener!!)
cache.setCheckmarkCount(10)
cache.refreshAllHabits()
cache.onAttached()
listener = mock()
cache.setListener(listener)
}
override fun tearDown() {
cache!!.onDetached()
cache.onDetached()
}
@Test
fun testCommandListener_all() {
assertThat(cache!!.habitCount, IsEqual.equalTo(10))
assertThat(cache.habitCount, equalTo(10))
val h = habitList.getByPosition(0)
commandRunner.run(
DeleteHabitsCommand(habitList, listOf(h))
)
Mockito.verify(listener)!!.onItemRemoved(0)
Mockito.verify(listener)!!.onRefreshFinished()
assertThat(cache!!.habitCount, IsEqual.equalTo(9))
verify(listener).onItemRemoved(0)
verify(listener).onRefreshFinished()
assertThat(cache.habitCount, equalTo(9))
}
@Test
fun testCommandListener_single() {
val h2 = habitList.getByPosition(2)
commandRunner.run(CreateRepetitionCommand(habitList, h2, today, Entry.NO))
Mockito.verify(listener)!!.onItemChanged(2)
Mockito.verify(listener)!!.onRefreshFinished()
Mockito.verifyNoMoreInteractions(listener)
verify(listener).onItemChanged(2)
verify(listener).onRefreshFinished()
verifyNoMoreInteractions(listener)
}
@Test
fun testGet() {
assertThat(cache!!.habitCount, IsEqual.equalTo(10))
assertThat(cache.habitCount, equalTo(10))
val h = habitList.getByPosition(3)
assertNotNull(h.id)
val score = h.scores[today].value
assertThat(cache!!.getHabitByPosition(3), IsEqual.equalTo(h))
assertThat(cache!!.getScore(h.id!!), IsEqual.equalTo(score))
val actualCheckmarks = cache!!.getCheckmarks(h.id!!)
assertThat(cache.getHabitByPosition(3), equalTo(h))
assertThat(cache.getScore(h.id!!), equalTo(score))
val actualCheckmarks = cache.getCheckmarks(h.id!!)
val expectedCheckmarks = h
.computedEntries
.getByInterval(today.minus(9), today)
.map { it.value }.toIntArray()
assertThat(actualCheckmarks, IsEqual.equalTo(expectedCheckmarks))
assertThat(actualCheckmarks, equalTo(expectedCheckmarks))
}
@Test
fun testRemoval() {
removeHabitAt(0)
removeHabitAt(3)
cache!!.refreshAllHabits()
Mockito.verify(listener)!!.onItemRemoved(0)
Mockito.verify(listener)!!.onItemRemoved(3)
Mockito.verify(listener)!!.onRefreshFinished()
assertThat(cache!!.habitCount, IsEqual.equalTo(8))
cache.refreshAllHabits()
verify(listener).onItemRemoved(0)
verify(listener).onItemRemoved(3)
verify(listener).onRefreshFinished()
assertThat(cache.habitCount, equalTo(8))
}
@Test
fun testRefreshWithNoChanges() {
cache!!.refreshAllHabits()
Mockito.verify(listener)!!.onRefreshFinished()
Mockito.verifyNoMoreInteractions(listener)
cache.refreshAllHabits()
verify(listener).onRefreshFinished()
verifyNoMoreInteractions(listener)
}
@Test
fun testReorder_onCache() {
val h2 = cache!!.getHabitByPosition(2)
val h3 = cache!!.getHabitByPosition(3)
val h7 = cache!!.getHabitByPosition(7)
cache!!.reorder(2, 7)
assertThat(cache!!.getHabitByPosition(2), IsEqual.equalTo(h3))
assertThat(cache!!.getHabitByPosition(7), IsEqual.equalTo(h2))
assertThat(cache!!.getHabitByPosition(6), IsEqual.equalTo(h7))
Mockito.verify(listener)!!.onItemMoved(2, 7)
Mockito.verifyNoMoreInteractions(listener)
val h2 = cache.getHabitByPosition(2)
val h3 = cache.getHabitByPosition(3)
val h7 = cache.getHabitByPosition(7)
cache.reorder(2, 7)
assertThat(cache.getHabitByPosition(2), equalTo(h3))
assertThat(cache.getHabitByPosition(7), equalTo(h2))
assertThat(cache.getHabitByPosition(6), equalTo(h7))
verify(listener).onItemMoved(2, 7)
verifyNoMoreInteractions(listener)
}
@Test
@ -129,26 +128,25 @@ class HabitCardListCacheTest : BaseUnitTest() {
val h2 = habitList.getByPosition(2)
val h3 = habitList.getByPosition(3)
val h7 = habitList.getByPosition(7)
assertThat(cache!!.getHabitByPosition(2), IsEqual.equalTo(h2))
assertThat(cache!!.getHabitByPosition(7), IsEqual.equalTo(h7))
Mockito.reset(listener)
assertThat(cache.getHabitByPosition(2), equalTo(h2))
assertThat(cache.getHabitByPosition(7), equalTo(h7))
reset(listener)
habitList.reorder(h2, h7)
cache!!.refreshAllHabits()
assertThat(cache!!.getHabitByPosition(2), IsEqual.equalTo(h3))
assertThat(cache!!.getHabitByPosition(7), IsEqual.equalTo(h2))
assertThat(cache!!.getHabitByPosition(6), IsEqual.equalTo(h7))
Mockito.verify(listener)!!.onItemMoved(3, 2)
Mockito.verify(listener)!!.onItemMoved(4, 3)
Mockito.verify(listener)!!.onItemMoved(5, 4)
Mockito.verify(listener)!!.onItemMoved(6, 5)
Mockito.verify(listener)!!.onItemMoved(7, 6)
Mockito.verify(listener)!!.onRefreshFinished()
Mockito.verifyNoMoreInteractions(listener)
cache.refreshAllHabits()
assertThat(cache.getHabitByPosition(2), equalTo(h3))
assertThat(cache.getHabitByPosition(7), equalTo(h2))
assertThat(cache.getHabitByPosition(6), equalTo(h7))
verify(listener).onItemMoved(3, 2)
verify(listener).onItemMoved(4, 3)
verify(listener).onItemMoved(5, 4)
verify(listener).onItemMoved(6, 5)
verify(listener).onItemMoved(7, 6)
verify(listener).onRefreshFinished()
verifyNoMoreInteractions(listener)
}
private fun removeHabitAt(position: Int) {
val h = habitList.getByPosition(position)
assertNotNull(h)
habitList.remove(h)
}
}

@ -18,9 +18,12 @@
*/
package org.isoron.uhabits.core.ui.screens.habits.list
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.verify
import com.nhaarman.mockitokotlin2.whenever
import junit.framework.Assert.assertFalse
import junit.framework.Assert.assertNull
import junit.framework.Assert.assertTrue
import junit.framework.TestCase
import org.hamcrest.MatcherAssert.assertThat
import org.hamcrest.Matchers.equalTo
import org.isoron.uhabits.core.BaseUnitTest
@ -29,42 +32,41 @@ import org.isoron.uhabits.core.preferences.Preferences
import org.isoron.uhabits.core.utils.DateUtils.Companion.getToday
import org.junit.Test
import org.mockito.Mock
import org.mockito.Mockito
class HintListTest : BaseUnitTest() {
private var hintList: HintList? = null
private lateinit var hintList: HintList
private lateinit var hints: Array<String>
@Mock
private val prefs: Preferences? = null
private var today: Timestamp? = null
private var yesterday: Timestamp? = null
private val prefs: Preferences = mock()
private lateinit var today: Timestamp
private lateinit var yesterday: Timestamp
@Throws(Exception::class)
override fun setUp() {
super.setUp()
today = getToday()
yesterday = today!!.minus(1)
yesterday = today.minus(1)
hints = arrayOf("hint1", "hint2", "hint3")
hintList = HintList(prefs!!, hints)
hintList = HintList(prefs, hints)
}
@Test
@Throws(Exception::class)
fun pop() {
Mockito.`when`(prefs!!.lastHintNumber).thenReturn(-1)
assertThat(hintList!!.pop(), equalTo("hint1"))
Mockito.verify(prefs).updateLastHint(0, today)
Mockito.`when`(prefs.lastHintNumber).thenReturn(2)
assertNull(hintList!!.pop())
whenever(prefs.lastHintNumber).thenReturn(-1)
assertThat(hintList.pop(), equalTo("hint1"))
verify(prefs).updateLastHint(0, today)
whenever(prefs.lastHintNumber).thenReturn(2)
assertNull(hintList.pop())
}
@Test
@Throws(Exception::class)
fun shouldShow() {
Mockito.`when`(prefs!!.lastHintTimestamp).thenReturn(today)
TestCase.assertFalse(hintList!!.shouldShow())
Mockito.`when`(prefs.lastHintTimestamp).thenReturn(yesterday)
assertTrue(hintList!!.shouldShow())
whenever(prefs.lastHintTimestamp).thenReturn(today)
assertFalse(hintList.shouldShow())
whenever(prefs.lastHintTimestamp).thenReturn(yesterday)
assertTrue(hintList.shouldShow())
}
}

@ -18,11 +18,18 @@
*/
package org.isoron.uhabits.core.ui.screens.habits.list
import com.nhaarman.mockitokotlin2.KArgumentCaptor
import com.nhaarman.mockitokotlin2.argumentCaptor
import com.nhaarman.mockitokotlin2.clearInvocations
import com.nhaarman.mockitokotlin2.eq
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.verify
import com.nhaarman.mockitokotlin2.whenever
import junit.framework.Assert.assertFalse
import junit.framework.Assert.assertTrue
import org.apache.commons.io.FileUtils
import org.hamcrest.CoreMatchers
import org.hamcrest.MatcherAssert.assertThat
import org.hamcrest.core.IsEqual.equalTo
import org.isoron.uhabits.core.BaseUnitTest
import org.isoron.uhabits.core.models.Entry
import org.isoron.uhabits.core.models.Habit
@ -31,32 +38,23 @@ import org.isoron.uhabits.core.utils.DateUtils.Companion.getToday
import org.isoron.uhabits.core.utils.DateUtils.Companion.getTodayWithOffset
import org.junit.Before
import org.junit.Test
import org.mockito.ArgumentCaptor
import org.mockito.ArgumentMatchers
import org.mockito.Captor
import org.mockito.Mock
import org.mockito.Mockito
import java.io.IOException
import java.nio.file.Files
class ListHabitsBehaviorTest : BaseUnitTest() {
@Mock
private val dirFinder: ListHabitsBehavior.DirFinder? = null
private val dirFinder: ListHabitsBehavior.DirFinder = mock()
@Mock
private val prefs: Preferences? = null
private var behavior: ListHabitsBehavior? = null
private val prefs: Preferences = mock()
private lateinit var behavior: ListHabitsBehavior
@Mock
private val screen: ListHabitsBehavior.Screen? = null
private var habit1: Habit? = null
private var habit2: Habit? = null
private val screen: ListHabitsBehavior.Screen = mock()
private lateinit var habit1: Habit
private lateinit var habit2: Habit
@Captor
var picker: ArgumentCaptor<ListHabitsBehavior.NumberPickerCallback>? = null
var picker: KArgumentCaptor<ListHabitsBehavior.NumberPickerCallback> = argumentCaptor()
@Mock
private val bugReporter: ListHabitsBehavior.BugReporter? = null
private val bugReporter: ListHabitsBehavior.BugReporter = mock()
@Before
@Throws(Exception::class)
@ -64,47 +62,37 @@ class ListHabitsBehaviorTest : BaseUnitTest() {
super.setUp()
habit1 = fixtures.createShortHabit()
habit2 = fixtures.createNumericalHabit()
habitList.add(habit1!!)
habitList.add(habit2!!)
Mockito.clearInvocations(habitList)
habitList.add(habit1)
habitList.add(habit2)
clearInvocations(habitList)
behavior = ListHabitsBehavior(
habitList,
dirFinder!!,
dirFinder,
taskRunner,
screen!!,
screen,
commandRunner,
prefs!!,
bugReporter!!
prefs,
bugReporter
)
}
@Test
fun testOnEdit() {
behavior!!.onEdit(habit2!!, getToday())
Mockito.verify(screen)!!.showNumberPicker(
ArgumentMatchers.eq(0.1),
ArgumentMatchers.eq("miles"),
picker!!.capture()
)
picker!!.value.onNumberPicked(100.0)
behavior.onEdit(habit2, getToday())
verify(screen).showNumberPicker(eq(0.1), eq("miles"), picker.capture())
picker.lastValue.onNumberPicked(100.0)
val today = getTodayWithOffset()
assertThat(
habit2!!.computedEntries.get(today).value,
CoreMatchers.equalTo(100000)
)
assertThat(habit2.computedEntries.get(today).value, equalTo(100000))
}
@Test
@Throws(Exception::class)
fun testOnExportCSV() {
val outputDir = Files.createTempDirectory("CSV").toFile()
Mockito.`when`(dirFinder!!.csvOutputDir).thenReturn(outputDir)
behavior!!.onExportCSV()
Mockito.verify(screen)!!.showSendFileScreen(ArgumentMatchers.any())
assertThat(
FileUtils.listFiles(outputDir, null, false).size,
CoreMatchers.equalTo(1)
)
whenever(dirFinder.csvOutputDir).thenReturn(outputDir)
behavior.onExportCSV()
verify(screen).showSendFileScreen(ArgumentMatchers.any())
assertThat(FileUtils.listFiles(outputDir, null, false).size, equalTo(1))
FileUtils.deleteDirectory(outputDir)
}
@ -113,69 +101,66 @@ class ListHabitsBehaviorTest : BaseUnitTest() {
fun testOnExportCSV_fail() {
val outputDir = Files.createTempDirectory("CSV").toFile()
outputDir.setWritable(false)
Mockito.`when`(dirFinder!!.csvOutputDir).thenReturn(outputDir)
behavior!!.onExportCSV()
Mockito.verify(screen)!!.showMessage(ListHabitsBehavior.Message.COULD_NOT_EXPORT)
whenever(dirFinder.csvOutputDir).thenReturn(outputDir)
behavior.onExportCSV()
verify(screen).showMessage(ListHabitsBehavior.Message.COULD_NOT_EXPORT)
assertTrue(outputDir.delete())
}
@Test
fun testOnHabitClick() {
behavior!!.onClickHabit(habit1!!)
Mockito.verify(screen)!!.showHabitScreen(
habit1!!
)
behavior.onClickHabit(habit1)
verify(screen).showHabitScreen(habit1)
}
@Test
fun testOnHabitReorder() {
val from = habit1
val to = habit2
behavior!!.onReorderHabit(from!!, to!!)
Mockito.verify(habitList)!!.reorder(from, to)
behavior.onReorderHabit(from, to)
verify(habitList).reorder(from, to)
}
@Test
fun testOnRepairDB() {
behavior!!.onRepairDB()
Mockito.verify(habitList)!!.repair()
Mockito.verify(screen)!!.showMessage(ListHabitsBehavior.Message.DATABASE_REPAIRED)
behavior.onRepairDB()
verify(habitList).repair()
verify(screen).showMessage(ListHabitsBehavior.Message.DATABASE_REPAIRED)
}
@Test
@Throws(IOException::class)
fun testOnSendBugReport() {
Mockito.`when`(bugReporter!!.bugReport).thenReturn("hello")
behavior!!.onSendBugReport()
Mockito.verify(bugReporter).dumpBugReportToFile()
Mockito.verify(screen)!!.showSendBugReportToDeveloperScreen("hello")
Mockito.`when`(bugReporter.bugReport).thenThrow(IOException())
behavior!!.onSendBugReport()
Mockito.verify(screen)!!
.showMessage(ListHabitsBehavior.Message.COULD_NOT_GENERATE_BUG_REPORT)
whenever(bugReporter.bugReport).thenReturn("hello")
behavior.onSendBugReport()
verify(bugReporter).dumpBugReportToFile()
verify(screen).showSendBugReportToDeveloperScreen("hello")
whenever(bugReporter.bugReport).thenThrow(IOException())
behavior.onSendBugReport()
verify(screen).showMessage(ListHabitsBehavior.Message.COULD_NOT_GENERATE_BUG_REPORT)
}
@Test
fun testOnStartup_firstLaunch() {
val today = getToday()
Mockito.`when`(prefs!!.isFirstRun).thenReturn(true)
behavior!!.onStartup()
Mockito.verify(prefs).isFirstRun = false
Mockito.verify(prefs).updateLastHint(-1, today)
Mockito.verify(screen)!!.showIntroScreen()
whenever(prefs.isFirstRun).thenReturn(true)
behavior.onStartup()
verify(prefs).isFirstRun = false
verify(prefs).updateLastHint(-1, today)
verify(screen).showIntroScreen()
}
@Test
fun testOnStartup_notFirstLaunch() {
Mockito.`when`(prefs!!.isFirstRun).thenReturn(false)
behavior!!.onStartup()
Mockito.verify(prefs).incrementLaunchCount()
whenever(prefs.isFirstRun).thenReturn(false)
behavior.onStartup()
verify(prefs).incrementLaunchCount()
}
@Test
fun testOnToggle() {
assertTrue(habit1!!.isCompletedToday())
behavior!!.onToggle(habit1!!, getToday(), Entry.NO)
assertFalse(habit1!!.isCompletedToday())
assertTrue(habit1.isCompletedToday())
behavior.onToggle(habit1, getToday(), Entry.NO)
assertFalse(habit1.isCompletedToday())
}
}

@ -18,7 +18,16 @@
*/
package org.isoron.uhabits.core.ui.screens.habits.list
import junit.framework.TestCase
import com.nhaarman.mockitokotlin2.KArgumentCaptor
import com.nhaarman.mockitokotlin2.argumentCaptor
import com.nhaarman.mockitokotlin2.clearInvocations
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.never
import com.nhaarman.mockitokotlin2.verify
import com.nhaarman.mockitokotlin2.verifyNoMoreInteractions
import com.nhaarman.mockitokotlin2.whenever
import junit.framework.Assert.assertFalse
import junit.framework.Assert.assertTrue
import org.hamcrest.MatcherAssert.assertThat
import org.hamcrest.Matchers.equalTo
import org.isoron.uhabits.core.BaseUnitTest
@ -27,196 +36,144 @@ import org.isoron.uhabits.core.models.HabitMatcher
import org.isoron.uhabits.core.preferences.Preferences
import org.isoron.uhabits.core.ui.ThemeSwitcher
import org.junit.Test
import org.mockito.ArgumentCaptor
import org.mockito.ArgumentMatchers
import org.mockito.Captor
import org.mockito.Mock
import org.mockito.Mockito
class ListHabitsMenuBehaviorTest : BaseUnitTest() {
private var behavior: ListHabitsMenuBehavior? = null
private lateinit var behavior: ListHabitsMenuBehavior
@Mock
private val screen: ListHabitsMenuBehavior.Screen? = null
private val screen: ListHabitsMenuBehavior.Screen = mock()
@Mock
private val adapter: ListHabitsMenuBehavior.Adapter? = null
private val adapter: ListHabitsMenuBehavior.Adapter = mock()
@Mock
private val prefs: Preferences? = null
private val prefs: Preferences = mock()
@Mock
private val themeSwitcher: ThemeSwitcher? = null
private val themeSwitcher: ThemeSwitcher = mock()
@Captor
private val matcherCaptor: ArgumentCaptor<HabitMatcher>? = null
private val matcherCaptor: KArgumentCaptor<HabitMatcher> = argumentCaptor()
@Captor
private val orderCaptor: ArgumentCaptor<HabitList.Order>? = null
private val orderCaptor: KArgumentCaptor<HabitList.Order> = argumentCaptor()
@Captor
private val secondaryOrderCaptor: ArgumentCaptor<HabitList.Order>? = null
private val secondaryOrderCaptor: KArgumentCaptor<HabitList.Order> = argumentCaptor()
@Throws(Exception::class)
override fun setUp() {
super.setUp()
behavior = ListHabitsMenuBehavior(screen!!, adapter!!, prefs!!, themeSwitcher!!)
Mockito.clearInvocations(adapter)
behavior = ListHabitsMenuBehavior(screen, adapter, prefs, themeSwitcher)
clearInvocations(adapter)
}
@Test
fun testInitialFilter() {
Mockito.`when`(prefs!!.showArchived).thenReturn(true)
Mockito.`when`(prefs.showCompleted).thenReturn(true)
behavior = ListHabitsMenuBehavior(screen!!, adapter!!, prefs, themeSwitcher!!)
Mockito.verify(adapter).setFilter(
matcherCaptor!!.capture()
)
Mockito.verify(adapter).refresh()
Mockito.verifyNoMoreInteractions(adapter)
Mockito.clearInvocations(adapter)
TestCase.assertTrue(matcherCaptor.value.isArchivedAllowed)
TestCase.assertTrue(matcherCaptor.value.isCompletedAllowed)
Mockito.`when`(prefs.showArchived).thenReturn(false)
Mockito.`when`(prefs.showCompleted).thenReturn(false)
whenever(prefs.showArchived).thenReturn(true)
whenever(prefs.showCompleted).thenReturn(true)
behavior = ListHabitsMenuBehavior(screen, adapter, prefs, themeSwitcher)
verify(adapter).setFilter(matcherCaptor.capture())
verify(adapter).refresh()
verifyNoMoreInteractions(adapter)
clearInvocations(adapter)
assertTrue(matcherCaptor.lastValue.isArchivedAllowed)
assertTrue(matcherCaptor.lastValue.isCompletedAllowed)
whenever(prefs.showArchived).thenReturn(false)
whenever(prefs.showCompleted).thenReturn(false)
behavior = ListHabitsMenuBehavior(screen, adapter, prefs, themeSwitcher)
Mockito.verify(adapter).setFilter(
matcherCaptor.capture()
)
Mockito.verify(adapter).refresh()
Mockito.verifyNoMoreInteractions(adapter)
TestCase.assertFalse(matcherCaptor.value.isArchivedAllowed)
TestCase.assertFalse(matcherCaptor.value.isCompletedAllowed)
verify(adapter).setFilter(matcherCaptor.capture())
verify(adapter).refresh()
verifyNoMoreInteractions(adapter)
assertFalse(matcherCaptor.lastValue.isArchivedAllowed)
assertFalse(matcherCaptor.lastValue.isCompletedAllowed)
}
// @Test
// public void testOnCreateHabit()
// {
// behavior.onCreateHabit();
// verify(screen).showCreateHabitScreen();
// }
@Test
fun testOnSortByColor() {
behavior!!.onSortByColor()
Mockito.verify(adapter)!!.primaryOrder = orderCaptor!!.capture()
assertThat(
orderCaptor.value,
equalTo(HabitList.Order.BY_COLOR_ASC)
)
behavior.onSortByColor()
verify(adapter).primaryOrder = orderCaptor.capture()
assertThat(orderCaptor.lastValue, equalTo(HabitList.Order.BY_COLOR_ASC))
}
@Test
fun testOnSortManually() {
behavior!!.onSortByManually()
Mockito.verify(adapter)!!.primaryOrder = orderCaptor!!.capture()
assertThat(
orderCaptor.value,
equalTo(HabitList.Order.BY_POSITION)
)
behavior.onSortByManually()
verify(adapter).primaryOrder = orderCaptor.capture()
assertThat(orderCaptor.lastValue, equalTo(HabitList.Order.BY_POSITION))
}
@Test
fun testOnSortScore() {
behavior!!.onSortByScore()
Mockito.verify(adapter)!!.primaryOrder = orderCaptor!!.capture()
assertThat(
orderCaptor.value,
equalTo(HabitList.Order.BY_SCORE_DESC)
)
behavior.onSortByScore()
verify(adapter).primaryOrder = orderCaptor.capture()
assertThat(orderCaptor.lastValue, equalTo(HabitList.Order.BY_SCORE_DESC))
}
@Test
fun testOnSortName() {
behavior!!.onSortByName()
Mockito.verify(adapter)!!.primaryOrder = orderCaptor!!.capture()
assertThat(
orderCaptor.value,
equalTo(HabitList.Order.BY_NAME_ASC)
)
behavior.onSortByName()
verify(adapter).primaryOrder = orderCaptor.capture()
assertThat(orderCaptor.lastValue, equalTo(HabitList.Order.BY_NAME_ASC))
}
@Test
fun testOnSortStatus() {
Mockito.`when`(adapter!!.primaryOrder).thenReturn(HabitList.Order.BY_NAME_ASC)
behavior!!.onSortByStatus()
Mockito.verify(adapter).primaryOrder = orderCaptor!!.capture()
Mockito.verify(adapter).setSecondaryOrder(
secondaryOrderCaptor!!.capture()
)
assertThat(
orderCaptor.value,
equalTo(HabitList.Order.BY_STATUS_ASC)
)
assertThat(
secondaryOrderCaptor.value,
equalTo(HabitList.Order.BY_NAME_ASC)
)
whenever(adapter.primaryOrder).thenReturn(HabitList.Order.BY_NAME_ASC)
behavior.onSortByStatus()
verify(adapter).primaryOrder = orderCaptor.capture()
verify(adapter).setSecondaryOrder(secondaryOrderCaptor.capture())
assertThat(orderCaptor.lastValue, equalTo(HabitList.Order.BY_STATUS_ASC))
assertThat(secondaryOrderCaptor.lastValue, equalTo(HabitList.Order.BY_NAME_ASC))
}
@Test
fun testOnSortStatusToggle() {
Mockito.`when`(adapter!!.primaryOrder).thenReturn(HabitList.Order.BY_STATUS_ASC)
behavior!!.onSortByStatus()
Mockito.verify(adapter).primaryOrder = orderCaptor!!.capture()
Mockito.verify(adapter, Mockito.never()).setSecondaryOrder(ArgumentMatchers.any())
assertThat(
orderCaptor.value,
equalTo(HabitList.Order.BY_STATUS_DESC)
)
whenever(adapter.primaryOrder).thenReturn(HabitList.Order.BY_STATUS_ASC)
behavior.onSortByStatus()
verify(adapter).primaryOrder = orderCaptor.capture()
verify(adapter, never()).setSecondaryOrder(ArgumentMatchers.any())
assertThat(orderCaptor.lastValue, equalTo(HabitList.Order.BY_STATUS_DESC))
}
@Test
fun testOnToggleShowArchived() {
behavior!!.onToggleShowArchived()
Mockito.verify(adapter)!!.setFilter(
matcherCaptor!!.capture()
)
TestCase.assertTrue(matcherCaptor.value.isArchivedAllowed)
Mockito.clearInvocations(adapter)
behavior!!.onToggleShowArchived()
Mockito.verify(adapter)!!.setFilter(
matcherCaptor.capture()
)
TestCase.assertFalse(matcherCaptor.value.isArchivedAllowed)
behavior.onToggleShowArchived()
verify(adapter).setFilter(matcherCaptor.capture())
assertTrue(matcherCaptor.lastValue.isArchivedAllowed)
clearInvocations(adapter)
behavior.onToggleShowArchived()
verify(adapter).setFilter(matcherCaptor.capture())
assertFalse(matcherCaptor.lastValue.isArchivedAllowed)
}
@Test
fun testOnToggleShowCompleted() {
behavior!!.onToggleShowCompleted()
Mockito.verify(adapter)!!.setFilter(
matcherCaptor!!.capture()
)
TestCase.assertTrue(matcherCaptor.value.isCompletedAllowed)
Mockito.clearInvocations(adapter)
behavior!!.onToggleShowCompleted()
Mockito.verify(adapter)!!.setFilter(
matcherCaptor.capture()
)
TestCase.assertFalse(matcherCaptor.value.isCompletedAllowed)
behavior.onToggleShowCompleted()
verify(adapter).setFilter(matcherCaptor.capture())
assertTrue(matcherCaptor.lastValue.isCompletedAllowed)
clearInvocations(adapter)
behavior.onToggleShowCompleted()
verify(adapter).setFilter(matcherCaptor.capture())
assertFalse(matcherCaptor.lastValue.isCompletedAllowed)
}
@Test
fun testOnViewAbout() {
behavior!!.onViewAbout()
Mockito.verify(screen)!!.showAboutScreen()
behavior.onViewAbout()
verify(screen).showAboutScreen()
}
@Test
fun testOnViewFAQ() {
behavior!!.onViewFAQ()
Mockito.verify(screen)!!.showFAQScreen()
behavior.onViewFAQ()
verify(screen).showFAQScreen()
}
@Test
fun testOnViewSettings() {
behavior!!.onViewSettings()
Mockito.verify(screen)!!.showSettingsScreen()
behavior.onViewSettings()
verify(screen).showSettingsScreen()
}
@Test
fun testOnToggleNightMode() {
behavior!!.onToggleNightMode()
Mockito.verify(themeSwitcher)!!.toggleNightMode()
Mockito.verify(screen)!!.applyTheme()
behavior.onToggleNightMode()
verify(themeSwitcher).toggleNightMode()
verify(screen).applyTheme()
}
}

@ -18,7 +18,15 @@
*/
package org.isoron.uhabits.core.ui.screens.habits.list
import junit.framework.TestCase
import com.nhaarman.mockitokotlin2.KArgumentCaptor
import com.nhaarman.mockitokotlin2.argumentCaptor
import com.nhaarman.mockitokotlin2.eq
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.verify
import com.nhaarman.mockitokotlin2.whenever
import junit.framework.Assert.assertFalse
import junit.framework.Assert.assertNull
import junit.framework.Assert.assertTrue
import org.hamcrest.MatcherAssert.assertThat
import org.hamcrest.Matchers.equalTo
import org.isoron.uhabits.core.BaseUnitTest
@ -27,126 +35,113 @@ import org.isoron.uhabits.core.models.PaletteColor
import org.isoron.uhabits.core.ui.callbacks.OnColorPickedCallback
import org.isoron.uhabits.core.ui.callbacks.OnConfirmedCallback
import org.junit.Test
import org.mockito.ArgumentCaptor
import org.mockito.ArgumentMatchers
import org.mockito.Captor
import org.mockito.Mock
import org.mockito.Mockito
class ListHabitsSelectionMenuBehaviorTest : BaseUnitTest() {
@Mock
private val screen: ListHabitsSelectionMenuBehavior.Screen? = null
private val screen: ListHabitsSelectionMenuBehavior.Screen = mock()
@Mock
private val adapter: ListHabitsSelectionMenuBehavior.Adapter? = null
private var behavior: ListHabitsSelectionMenuBehavior? = null
private var habit1: Habit? = null
private var habit2: Habit? = null
private var habit3: Habit? = null
private val adapter: ListHabitsSelectionMenuBehavior.Adapter = mock()
private lateinit var behavior: ListHabitsSelectionMenuBehavior
private lateinit var habit1: Habit
private lateinit var habit2: Habit
private lateinit var habit3: Habit
@Captor
private val colorPickerCallback: ArgumentCaptor<OnColorPickedCallback>? = null
private val colorPickerCallback: KArgumentCaptor<OnColorPickedCallback> = argumentCaptor()
@Captor
private val deleteCallback: ArgumentCaptor<OnConfirmedCallback>? = null
private val deleteCallback: KArgumentCaptor<OnConfirmedCallback> = argumentCaptor()
@Test
@Throws(Exception::class)
fun canArchive() {
Mockito.`when`(adapter!!.selected).thenReturn(listOf(habit1, habit2))
TestCase.assertFalse(behavior!!.canArchive())
Mockito.`when`(adapter.selected).thenReturn(listOf(habit2, habit3))
TestCase.assertTrue(behavior!!.canArchive())
whenever(adapter.selected).thenReturn(listOf(habit1, habit2))
assertFalse(behavior.canArchive())
whenever(adapter.selected).thenReturn(listOf(habit2, habit3))
assertTrue(behavior.canArchive())
}
@Test
@Throws(Exception::class)
fun canEdit() {
Mockito.`when`(adapter!!.selected).thenReturn(listOf(habit1))
TestCase.assertTrue(behavior!!.canEdit())
Mockito.`when`(adapter.selected).thenReturn(listOf(habit1, habit2))
TestCase.assertFalse(behavior!!.canEdit())
whenever(adapter.selected).thenReturn(listOf(habit1))
assertTrue(behavior.canEdit())
whenever(adapter.selected).thenReturn(listOf(habit1, habit2))
assertFalse(behavior.canEdit())
}
@Test
@Throws(Exception::class)
fun canUnarchive() {
Mockito.`when`(adapter!!.selected).thenReturn(listOf(habit1, habit2))
TestCase.assertFalse(behavior!!.canUnarchive())
Mockito.`when`(adapter.selected).thenReturn(listOf(habit1))
TestCase.assertTrue(behavior!!.canUnarchive())
whenever(adapter.selected).thenReturn(listOf(habit1, habit2))
assertFalse(behavior.canUnarchive())
whenever(adapter.selected).thenReturn(listOf(habit1))
assertTrue(behavior.canUnarchive())
}
@Test
@Throws(Exception::class)
fun onArchiveHabits() {
TestCase.assertFalse(habit2!!.isArchived)
Mockito.`when`(adapter!!.selected).thenReturn(listOf(habit2))
behavior!!.onArchiveHabits()
TestCase.assertTrue(habit2!!.isArchived)
assertFalse(habit2.isArchived)
whenever(adapter.selected).thenReturn(listOf(habit2))
behavior.onArchiveHabits()
assertTrue(habit2.isArchived)
}
@Test
@Throws(Exception::class)
fun onChangeColor() {
assertThat(habit1!!.color, equalTo(PaletteColor(8)))
assertThat(habit2!!.color, equalTo(PaletteColor(8)))
Mockito.`when`(adapter!!.selected).thenReturn(listOf(habit1, habit2))
behavior!!.onChangeColor()
Mockito.verify(screen)!!
.showColorPicker(ArgumentMatchers.eq(PaletteColor(8)), colorPickerCallback!!.capture())
colorPickerCallback.value.onColorPicked(PaletteColor(30))
assertThat(habit1!!.color, equalTo(PaletteColor(30)))
assertThat(habit1.color, equalTo(PaletteColor(8)))
assertThat(habit2.color, equalTo(PaletteColor(8)))
whenever(adapter.selected).thenReturn(listOf(habit1, habit2))
behavior.onChangeColor()
verify(screen)
.showColorPicker(eq(PaletteColor(8)), colorPickerCallback.capture())
colorPickerCallback.lastValue.onColorPicked(PaletteColor(30))
assertThat(habit1.color, equalTo(PaletteColor(30)))
}
@Test
@Throws(Exception::class)
fun onDeleteHabits() {
val id = habit1!!.id
TestCase.assertNotNull(id)
TestCase.assertNotNull(habitList.getById(id!!))
Mockito.`when`(adapter!!.selected).thenReturn(listOf(habit1))
behavior!!.onDeleteHabits()
Mockito.verify(screen)!!.showDeleteConfirmationScreen(
deleteCallback!!.capture(),
ArgumentMatchers.eq(1)
)
deleteCallback.value.onConfirmed()
TestCase.assertNull(habitList.getById(id))
val id = habit1.id!!
habitList.getById(id)!!
whenever(adapter.selected).thenReturn(listOf(habit1))
behavior.onDeleteHabits()
verify(screen).showDeleteConfirmationScreen(deleteCallback.capture(), eq(1))
deleteCallback.lastValue.onConfirmed()
assertNull(habitList.getById(id))
}
@Test
@Throws(Exception::class)
fun onEditHabits() {
val selected: List<Habit> = listOf(habit1!!, habit2!!)
Mockito.`when`(adapter!!.selected).thenReturn(selected)
behavior!!.onEditHabits()
Mockito.verify(screen)!!.showEditHabitsScreen(selected)
val selected: List<Habit> = listOf(habit1, habit2)
whenever(adapter.selected).thenReturn(selected)
behavior.onEditHabits()
verify(screen).showEditHabitsScreen(selected)
}
@Test
@Throws(Exception::class)
fun onUnarchiveHabits() {
TestCase.assertTrue(habit1!!.isArchived)
Mockito.`when`(adapter!!.selected).thenReturn(listOf(habit1))
behavior!!.onUnarchiveHabits()
TestCase.assertFalse(habit1!!.isArchived)
assertTrue(habit1.isArchived)
whenever(adapter.selected).thenReturn(listOf(habit1))
behavior.onUnarchiveHabits()
assertFalse(habit1.isArchived)
}
@Throws(Exception::class)
override fun setUp() {
super.setUp()
habit1 = fixtures.createShortHabit()
habit1!!.isArchived = true
habit1.isArchived = true
habit2 = fixtures.createShortHabit()
habit3 = fixtures.createShortHabit()
habitList.add(habit1!!)
habitList.add(habit2!!)
habitList.add(habit3!!)
habitList.add(habit1)
habitList.add(habit2)
habitList.add(habit3)
behavior = ListHabitsSelectionMenuBehavior(
habitList,
screen!!,
adapter!!,
screen,
adapter,
commandRunner
)
}

@ -18,13 +18,15 @@
*/
package org.isoron.uhabits.core.ui.screens.habits.show
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.verify
import com.nhaarman.mockitokotlin2.whenever
import org.apache.commons.io.FileUtils
import org.hamcrest.CoreMatchers
import org.hamcrest.CoreMatchers.equalTo
import org.hamcrest.MatcherAssert.assertThat
import org.isoron.uhabits.core.BaseUnitTest
import org.isoron.uhabits.core.models.Habit
import org.junit.Test
import org.mockito.Mockito
import java.nio.file.Files
class ShowHabitMenuPresenterTest : BaseUnitTest() {
@ -32,11 +34,12 @@ class ShowHabitMenuPresenterTest : BaseUnitTest() {
private lateinit var screen: ShowHabitMenuPresenter.Screen
private lateinit var habit: Habit
private lateinit var menu: ShowHabitMenuPresenter
@Throws(Exception::class)
override fun setUp() {
super.setUp()
system = Mockito.mock(ShowHabitMenuPresenter.System::class.java)
screen = Mockito.mock(ShowHabitMenuPresenter.Screen::class.java)
system = mock()
screen = mock()
habit = fixtures.createShortHabit()
menu = ShowHabitMenuPresenter(
commandRunner,
@ -51,16 +54,16 @@ class ShowHabitMenuPresenterTest : BaseUnitTest() {
@Test
fun testOnEditHabit() {
menu.onEditHabit()
Mockito.verify(screen)!!.showEditHabitScreen(habit)
verify(screen).showEditHabitScreen(habit)
}
@Test
@Throws(Exception::class)
fun testOnExport() {
val outputDir = Files.createTempDirectory("CSV").toFile()
Mockito.`when`(system.getCSVOutputDir()).thenReturn(outputDir)
whenever(system.getCSVOutputDir()).thenReturn(outputDir)
menu.onExportCSV()
assertThat(FileUtils.listFiles(outputDir, null, false).size, CoreMatchers.equalTo(1))
assertThat(FileUtils.listFiles(outputDir, null, false).size, equalTo(1))
FileUtils.deleteDirectory(outputDir)
}
}

@ -18,8 +18,12 @@
*/
package org.isoron.uhabits.core.ui.widgets
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.reset
import com.nhaarman.mockitokotlin2.verify
import com.nhaarman.mockitokotlin2.verifyZeroInteractions
import com.nhaarman.mockitokotlin2.whenever
import org.isoron.uhabits.core.BaseUnitTest
import org.isoron.uhabits.core.commands.CommandRunner
import org.isoron.uhabits.core.commands.CreateRepetitionCommand
import org.isoron.uhabits.core.models.Entry
import org.isoron.uhabits.core.models.Entry.Companion.nextToggleValueWithSkip
@ -31,44 +35,43 @@ import org.isoron.uhabits.core.ui.NotificationTray
import org.isoron.uhabits.core.utils.DateUtils.Companion.getTodayWithOffset
import org.junit.Before
import org.junit.Test
import org.mockito.Mockito
class WidgetBehaviorTest : BaseUnitTest() {
private lateinit var notificationTray: NotificationTray
private lateinit var preferences: Preferences
private lateinit var behavior: WidgetBehavior
private var habit: Habit? = null
private var today: Timestamp? = null
private lateinit var habit: Habit
private lateinit var today: Timestamp
@Before
@Throws(Exception::class)
override fun setUp() {
super.setUp()
habit = fixtures.createEmptyHabit()
commandRunner = Mockito.mock(CommandRunner::class.java)
notificationTray = Mockito.mock(NotificationTray::class.java)
preferences = Mockito.mock(Preferences::class.java)
commandRunner = mock()
notificationTray = mock()
preferences = mock()
behavior = WidgetBehavior(habitList, commandRunner, notificationTray, preferences)
today = getTodayWithOffset()
}
@Test
fun testOnAddRepetition() {
behavior.onAddRepetition(habit!!, today)
Mockito.verify(commandRunner)!!.run(
CreateRepetitionCommand(habitList, habit!!, today!!, Entry.YES_MANUAL)
behavior.onAddRepetition(habit, today)
verify(commandRunner).run(
CreateRepetitionCommand(habitList, habit, today, Entry.YES_MANUAL)
)
Mockito.verify(notificationTray)!!.cancel(habit!!)
Mockito.verifyZeroInteractions(preferences)
verify(notificationTray).cancel(habit)
verifyZeroInteractions(preferences)
}
@Test
fun testOnRemoveRepetition() {
behavior.onRemoveRepetition(habit!!, today)
Mockito.verify(commandRunner)!!.run(
CreateRepetitionCommand(habitList, habit!!, today!!, Entry.NO)
behavior.onRemoveRepetition(habit, today)
verify(commandRunner).run(
CreateRepetitionCommand(habitList, habit, today, Entry.NO)
)
Mockito.verify(notificationTray)!!.cancel(habit!!)
Mockito.verifyZeroInteractions(preferences)
verify(notificationTray).cancel(habit)
verifyZeroInteractions(preferences)
}
@Test
@ -81,46 +84,46 @@ class WidgetBehaviorTest : BaseUnitTest() {
Entry.SKIP
)
) {
Mockito.`when`(preferences.isSkipEnabled).thenReturn(skipEnabled)
whenever(preferences.isSkipEnabled).thenReturn(skipEnabled)
val nextValue: Int = if (skipEnabled) nextToggleValueWithSkip(currentValue) else nextToggleValueWithoutSkip(
currentValue
)
habit!!.originalEntries.add(Entry(today!!, currentValue))
behavior.onToggleRepetition(habit!!, today)
Mockito.verify(preferences)!!.isSkipEnabled
Mockito.verify(commandRunner)!!.run(
CreateRepetitionCommand(habitList, habit!!, today!!, nextValue)
habit.originalEntries.add(Entry(today, currentValue))
behavior.onToggleRepetition(habit, today)
verify(preferences).isSkipEnabled
verify(commandRunner).run(
CreateRepetitionCommand(habitList, habit, today, nextValue)
)
Mockito.verify(notificationTray)!!.cancel(
habit!!
verify(notificationTray).cancel(
habit
)
Mockito.reset(preferences, commandRunner, notificationTray)
reset(preferences, commandRunner, notificationTray)
}
}
@Test
fun testOnIncrement() {
habit = fixtures.createNumericalHabit()
habit!!.originalEntries.add(Entry(today!!, 500))
habit!!.recompute()
behavior.onIncrement(habit!!, today!!, 100)
Mockito.verify(commandRunner)!!.run(
CreateRepetitionCommand(habitList, habit!!, today!!, 600)
habit.originalEntries.add(Entry(today, 500))
habit.recompute()
behavior.onIncrement(habit, today, 100)
verify(commandRunner).run(
CreateRepetitionCommand(habitList, habit, today, 600)
)
Mockito.verify(notificationTray)!!.cancel(habit!!)
Mockito.verifyZeroInteractions(preferences)
verify(notificationTray).cancel(habit)
verifyZeroInteractions(preferences)
}
@Test
fun testOnDecrement() {
habit = fixtures.createNumericalHabit()
habit!!.originalEntries.add(Entry(today!!, 500))
habit!!.recompute()
behavior.onDecrement(habit!!, today!!, 100)
Mockito.verify(commandRunner)!!.run(
CreateRepetitionCommand(habitList, habit!!, today!!, 400)
habit.originalEntries.add(Entry(today, 500))
habit.recompute()
behavior.onDecrement(habit, today, 100)
verify(commandRunner).run(
CreateRepetitionCommand(habitList, habit, today, 400)
)
Mockito.verify(notificationTray)!!.cancel(habit!!)
Mockito.verifyZeroInteractions(preferences)
verify(notificationTray).cancel(habit)
verifyZeroInteractions(preferences)
}
}

@ -19,8 +19,8 @@
package org.isoron.uhabits.core.utils
import junit.framework.Assert.assertEquals
import org.hamcrest.CoreMatchers
import org.hamcrest.MatcherAssert.assertThat
import org.hamcrest.core.IsEqual.equalTo
import org.isoron.uhabits.core.BaseUnitTest
import org.isoron.uhabits.core.models.Timestamp
import org.isoron.uhabits.core.utils.DateUtils.Companion.applyTimezone
@ -42,6 +42,7 @@ import java.util.TimeZone
class DateUtilsTest : BaseUnitTest() {
var firstWeekday = Calendar.SUNDAY
@Before
@Throws(Exception::class)
override fun setUp() {
@ -54,7 +55,7 @@ class DateUtilsTest : BaseUnitTest() {
val timestamp = unixTime(2015, Calendar.DECEMBER, 31)
val date = Timestamp(timestamp).toCalendar()
val formatted = formatHeaderDate(date)
assertThat(formatted, CoreMatchers.equalTo("Thu\n31"))
assertThat(formatted, equalTo("Thu\n31"))
}
@Test
@ -64,24 +65,24 @@ class DateUtilsTest : BaseUnitTest() {
var t0 = unixTime(2015, Calendar.JANUARY, 11)
var t1 = unixTime(2015, Calendar.JANUARY, 16)
var t2 = unixTime(2015, Calendar.JANUARY, 17)
assertThat(truncate(field, t0, firstWeekday), CoreMatchers.equalTo(expected))
assertThat(truncate(field, t1, firstWeekday), CoreMatchers.equalTo(expected))
assertThat(truncate(field, t2, firstWeekday), CoreMatchers.equalTo(expected))
assertThat(truncate(field, t0, firstWeekday), equalTo(expected))
assertThat(truncate(field, t1, firstWeekday), equalTo(expected))
assertThat(truncate(field, t2, firstWeekday), equalTo(expected))
expected = unixTime(2015, Calendar.JANUARY, 18)
t0 = unixTime(2015, Calendar.JANUARY, 18)
t1 = unixTime(2015, Calendar.JANUARY, 19)
t2 = unixTime(2015, Calendar.JANUARY, 24)
assertThat(truncate(field, t0, firstWeekday), CoreMatchers.equalTo(expected))
assertThat(truncate(field, t1, firstWeekday), CoreMatchers.equalTo(expected))
assertThat(truncate(field, t2, firstWeekday), CoreMatchers.equalTo(expected))
assertThat(truncate(field, t0, firstWeekday), equalTo(expected))
assertThat(truncate(field, t1, firstWeekday), equalTo(expected))
assertThat(truncate(field, t2, firstWeekday), equalTo(expected))
firstWeekday = Calendar.WEDNESDAY
expected = unixTime(2015, Calendar.JANUARY, 7)
t0 = unixTime(2015, Calendar.JANUARY, 7)
t1 = unixTime(2015, Calendar.JANUARY, 9)
t2 = unixTime(2015, Calendar.JANUARY, 13)
assertThat(truncate(field, t0, firstWeekday), CoreMatchers.equalTo(expected))
assertThat(truncate(field, t1, firstWeekday), CoreMatchers.equalTo(expected))
assertThat(truncate(field, t2, firstWeekday), CoreMatchers.equalTo(expected))
assertThat(truncate(field, t0, firstWeekday), equalTo(expected))
assertThat(truncate(field, t1, firstWeekday), equalTo(expected))
assertThat(truncate(field, t2, firstWeekday), equalTo(expected))
}
@Test
@ -91,16 +92,16 @@ class DateUtilsTest : BaseUnitTest() {
var t1 = unixTime(2016, Calendar.JUNE, 15)
var t2 = unixTime(2016, Calendar.JUNE, 20)
val field = DateUtils.TruncateField.MONTH
assertThat(truncate(field, t0, firstWeekday), CoreMatchers.equalTo(expected))
assertThat(truncate(field, t1, firstWeekday), CoreMatchers.equalTo(expected))
assertThat(truncate(field, t2, firstWeekday), CoreMatchers.equalTo(expected))
assertThat(truncate(field, t0, firstWeekday), equalTo(expected))
assertThat(truncate(field, t1, firstWeekday), equalTo(expected))
assertThat(truncate(field, t2, firstWeekday), equalTo(expected))
expected = unixTime(2016, Calendar.DECEMBER, 1)
t0 = unixTime(2016, Calendar.DECEMBER, 1)
t1 = unixTime(2016, Calendar.DECEMBER, 15)
t2 = unixTime(2016, Calendar.DECEMBER, 31)
assertThat(truncate(field, t0, firstWeekday), CoreMatchers.equalTo(expected))
assertThat(truncate(field, t1, firstWeekday), CoreMatchers.equalTo(expected))
assertThat(truncate(field, t2, firstWeekday), CoreMatchers.equalTo(expected))
assertThat(truncate(field, t0, firstWeekday), equalTo(expected))
assertThat(truncate(field, t1, firstWeekday), equalTo(expected))
assertThat(truncate(field, t2, firstWeekday), equalTo(expected))
}
@Test
@ -110,16 +111,16 @@ class DateUtilsTest : BaseUnitTest() {
var t0 = unixTime(2016, Calendar.JANUARY, 20)
var t1 = unixTime(2016, Calendar.FEBRUARY, 15)
var t2 = unixTime(2016, Calendar.MARCH, 30)
assertThat(truncate(field, t0, firstWeekday), CoreMatchers.equalTo(expected))
assertThat(truncate(field, t1, firstWeekday), CoreMatchers.equalTo(expected))
assertThat(truncate(field, t2, firstWeekday), CoreMatchers.equalTo(expected))
assertThat(truncate(field, t0, firstWeekday), equalTo(expected))
assertThat(truncate(field, t1, firstWeekday), equalTo(expected))
assertThat(truncate(field, t2, firstWeekday), equalTo(expected))
expected = unixTime(2016, Calendar.APRIL, 1)
t0 = unixTime(2016, Calendar.APRIL, 1)
t1 = unixTime(2016, Calendar.MAY, 30)
t2 = unixTime(2016, Calendar.JUNE, 20)
assertThat(truncate(field, t0, firstWeekday), CoreMatchers.equalTo(expected))
assertThat(truncate(field, t1, firstWeekday), CoreMatchers.equalTo(expected))
assertThat(truncate(field, t2, firstWeekday), CoreMatchers.equalTo(expected))
assertThat(truncate(field, t0, firstWeekday), equalTo(expected))
assertThat(truncate(field, t1, firstWeekday), equalTo(expected))
assertThat(truncate(field, t2, firstWeekday), equalTo(expected))
}
@Test
@ -129,16 +130,16 @@ class DateUtilsTest : BaseUnitTest() {
var t0 = unixTime(2016, Calendar.JANUARY, 1)
var t1 = unixTime(2016, Calendar.FEBRUARY, 25)
var t2 = unixTime(2016, Calendar.DECEMBER, 31)
assertThat(truncate(field, t0, firstWeekday), CoreMatchers.equalTo(expected))
assertThat(truncate(field, t1, firstWeekday), CoreMatchers.equalTo(expected))
assertThat(truncate(field, t2, firstWeekday), CoreMatchers.equalTo(expected))
assertThat(truncate(field, t0, firstWeekday), equalTo(expected))
assertThat(truncate(field, t1, firstWeekday), equalTo(expected))
assertThat(truncate(field, t2, firstWeekday), equalTo(expected))
expected = unixTime(2017, Calendar.JANUARY, 1)
t0 = unixTime(2017, Calendar.JANUARY, 1)
t1 = unixTime(2017, Calendar.MAY, 30)
t2 = unixTime(2017, Calendar.DECEMBER, 31)
assertThat(truncate(field, t0, firstWeekday), CoreMatchers.equalTo(expected))
assertThat(truncate(field, t1, firstWeekday), CoreMatchers.equalTo(expected))
assertThat(truncate(field, t2, firstWeekday), CoreMatchers.equalTo(expected))
assertThat(truncate(field, t0, firstWeekday), equalTo(expected))
assertThat(truncate(field, t1, firstWeekday), equalTo(expected))
assertThat(truncate(field, t2, firstWeekday), equalTo(expected))
}
@Test
@ -146,41 +147,33 @@ class DateUtilsTest : BaseUnitTest() {
fun testMillisecondsUntilTomorrow() {
setFixedTimeZone(TimeZone.getTimeZone("GMT"))
setFixedLocalTime(unixTime(2017, Calendar.JANUARY, 1, 23, 59))
assertThat(
millisecondsUntilTomorrowWithOffset(),
CoreMatchers.equalTo(
DateUtils.MINUTE_LENGTH
)
)
assertThat(millisecondsUntilTomorrowWithOffset(), equalTo(DateUtils.MINUTE_LENGTH))
setFixedLocalTime(unixTime(2017, Calendar.JANUARY, 1, 20, 0))
assertThat(
millisecondsUntilTomorrowWithOffset(),
CoreMatchers.equalTo(4 * DateUtils.HOUR_LENGTH)
equalTo(4 * DateUtils.HOUR_LENGTH)
)
setStartDayOffset(3, 30)
setFixedLocalTime(unixTime(2017, Calendar.JANUARY, 1, 23, 59))
assertThat(
millisecondsUntilTomorrowWithOffset(),
CoreMatchers.equalTo(3 * DateUtils.HOUR_LENGTH + 31 * DateUtils.MINUTE_LENGTH)
equalTo(3 * DateUtils.HOUR_LENGTH + 31 * DateUtils.MINUTE_LENGTH)
)
setFixedLocalTime(unixTime(2017, Calendar.JANUARY, 2, 1, 0))
assertThat(
millisecondsUntilTomorrowWithOffset(),
CoreMatchers.equalTo(2 * DateUtils.HOUR_LENGTH + 30 * DateUtils.MINUTE_LENGTH)
equalTo(2 * DateUtils.HOUR_LENGTH + 30 * DateUtils.MINUTE_LENGTH)
)
}
@Test
@Throws(Exception::class)
fun testGetTodayWithOffset() {
assertThat(
getTodayWithOffset(),
CoreMatchers.equalTo(Timestamp(FIXED_LOCAL_TIME))
)
assertThat(getTodayWithOffset(), equalTo(Timestamp(FIXED_LOCAL_TIME)))
setStartDayOffset(9, 0)
assertThat(
getTodayWithOffset(),
CoreMatchers.equalTo(Timestamp(FIXED_LOCAL_TIME - DateUtils.DAY_LENGTH))
equalTo(Timestamp(FIXED_LOCAL_TIME - DateUtils.DAY_LENGTH))
)
}
@ -190,12 +183,12 @@ class DateUtilsTest : BaseUnitTest() {
val timestamp = unixTime(2020, Calendar.SEPTEMBER, 3)
assertThat(
getStartOfDayWithOffset(timestamp + DateUtils.HOUR_LENGTH),
CoreMatchers.equalTo(timestamp)
equalTo(timestamp)
)
setStartDayOffset(3, 30)
assertThat(
getStartOfDayWithOffset(timestamp + 3 * DateUtils.HOUR_LENGTH + 29 * DateUtils.MINUTE_LENGTH),
CoreMatchers.equalTo(timestamp - DateUtils.DAY_LENGTH)
equalTo(timestamp - DateUtils.DAY_LENGTH)
)
}

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save