Clean up kotlin code

* static imports
* less nullable types
* format
This commit is contained in:
Quentin Hibon
2021-01-18 16:11:52 +01:00
parent 9d0fbb9ea9
commit dedeb13f46
106 changed files with 982 additions and 1287 deletions

View File

@@ -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.

View File

@@ -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"
}
}

View File

@@ -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

View File

@@ -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
)
}
}
}

View File

@@ -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 {

View File

@@ -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 <= ' ' })

View File

@@ -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() {

View File

@@ -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)

View File

@@ -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>,

View File

@@ -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

View File

@@ -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

View File

@@ -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)
}
}

View File

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

View File

@@ -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

View File

@@ -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()

View File

@@ -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
}
}

View File

@@ -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)

View File

@@ -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)
}
}

View File

@@ -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)
}

View File

@@ -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()

View File

@@ -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
}
}
}

View File

@@ -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)
}

View File

@@ -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)
}
}

View File

@@ -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)))
}
}

View File

@@ -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))
}
}

View File

@@ -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())
}
}

View File

@@ -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"))
}
}

View File

@@ -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)")
}
}

View File

@@ -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) {

View File

@@ -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))

View File

@@ -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

View File

@@ -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"))
}
}

View File

@@ -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 {

View File

@@ -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))
}
}

View File

@@ -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

View File

@@ -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

View File

@@ -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(),

View File

@@ -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))
}
}

View File

@@ -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()))
}
}

View File

@@ -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))
}
}

View File

@@ -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

View File

@@ -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))
}
}

View File

@@ -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

View File

@@ -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()

View File

@@ -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)
}
}

View File

@@ -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())
}
}

View File

@@ -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())
}
}

View File

@@ -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)
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)
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)
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()
}
}

View File

@@ -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
)
}

View File

@@ -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)
}
}

View File

@@ -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)
}
}

View File

@@ -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)
)
}