Switch assertions to assertk

This commit is contained in:
cketti 2023-05-14 03:25:03 +02:00
parent 4f0ee47d12
commit 5498567bf2
35 changed files with 601 additions and 489 deletions

View file

@ -1,36 +1,46 @@
package com.fsck.k9 package com.fsck.k9
import org.junit.Assert import assertk.assertThat
import assertk.assertions.isFalse
import assertk.assertions.isTrue
import org.junit.Test import org.junit.Test
class EmailAddressValidatorTest { class EmailAddressValidatorTest {
private val validator = EmailAddressValidator()
@Test @Test
fun testEmailValidation() { fun testEmailValidation() {
// Most of the tests based on https://en.wikipedia.org/wiki/Email_address#Examples // Most of the tests based on https://en.wikipedia.org/wiki/Email_address#Examples
val validator = EmailAddressValidator() assertValidAddress("simple@example.com")
Assert.assertTrue(validator.isValidAddressOnly("simple@example.com")) assertValidAddress("very.common@example.com")
Assert.assertTrue(validator.isValidAddressOnly("very.common@example.com")) assertValidAddress("disposable.style.email.with+symbol@example.com")
Assert.assertTrue(validator.isValidAddressOnly("disposable.style.email.with+symbol@example.com")) assertValidAddress("other.email-with-hyphen@example.com")
Assert.assertTrue(validator.isValidAddressOnly("other.email-with-hyphen@example.com")) assertValidAddress("fully-qualified-domain@example.com")
Assert.assertTrue(validator.isValidAddressOnly("fully-qualified-domain@example.com")) assertValidAddress("user.name+tag+sorting@example.com")
Assert.assertTrue(validator.isValidAddressOnly("user.name+tag+sorting@example.com")) assertValidAddress("example-indeed@strange-example.com")
Assert.assertTrue(validator.isValidAddressOnly("example-indeed@strange-example.com")) assertValidAddress("example-indeed@strange_example.com")
Assert.assertTrue(validator.isValidAddressOnly("example-indeed@strange_example.com")) assertValidAddress("example@1.com")
Assert.assertTrue(validator.isValidAddressOnly("example@1.com")) assertValidAddress("admin@mailserver1")
Assert.assertTrue(validator.isValidAddressOnly("admin@mailserver1")) assertValidAddress("user@localserver")
Assert.assertTrue(validator.isValidAddressOnly("user@localserver")) assertValidAddress("\"very.(),:;<>[]\\\".VERY.\\\"very@\\\\ \\\"very\\\".unusual\"@strange.example.com")
Assert.assertTrue(validator.isValidAddressOnly("\"very.(),:;<>[]\\\".VERY.\\\"very@\\\\ \\\"very\\\".unusual\"@strange.example.com")) assertValidAddress("\"()<>[]:,;@\\\\\\\"!#$%&'-/=?^_`{}| ~.a\"@example.org")
Assert.assertTrue(validator.isValidAddressOnly("\"()<>[]:,;@\\\\\\\"!#$%&'-/=?^_`{}| ~.a\"@example.org")) assertValidAddress("\" \"@example.org")
Assert.assertTrue(validator.isValidAddressOnly("\" \"@example.org")) assertValidAddress("x@example.com")
Assert.assertTrue(validator.isValidAddressOnly("x@example.com"))
Assert.assertFalse(validator.isValidAddressOnly("Abc.example.com")) assertInvalidAddress("Abc.example.com")
Assert.assertFalse(validator.isValidAddressOnly("\"not\"right@example.com")) assertInvalidAddress("\"not\"right@example.com")
Assert.assertFalse(validator.isValidAddressOnly("john.doe@example..com")) assertInvalidAddress("john.doe@example..com")
Assert.assertFalse(validator.isValidAddressOnly("example@c.2")) assertInvalidAddress("example@c.2")
Assert.assertFalse(validator.isValidAddressOnly("this\\ still\\\"not\\\\allowed@example.com")) assertInvalidAddress("this\\ still\\\"not\\\\allowed@example.com")
Assert.assertFalse(validator.isValidAddressOnly("john..doe@example.com")) assertInvalidAddress("john..doe@example.com")
Assert.assertFalse(validator.isValidAddressOnly("invalidperiod.@example.com")) assertInvalidAddress("invalidperiod.@example.com")
}
private fun assertValidAddress(input: String) {
assertThat(input).transform { validator.isValidAddressOnly(it) }.isTrue()
}
private fun assertInvalidAddress(input: String) {
assertThat(input).transform { validator.isValidAddressOnly(it) }.isFalse()
} }
} }

View file

@ -1,10 +1,11 @@
package com.fsck.k9 package com.fsck.k9
import app.k9mail.core.testing.TestClock import app.k9mail.core.testing.TestClock
import assertk.assertThat
import assertk.assertions.isFalse
import assertk.assertions.isTrue
import java.util.Calendar import java.util.Calendar
import kotlinx.datetime.Instant import kotlinx.datetime.Instant
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test import org.junit.Test
class QuietTimeCheckerTest { class QuietTimeCheckerTest {
@ -15,7 +16,7 @@ class QuietTimeCheckerTest {
setClockTo("02:00") setClockTo("02:00")
val quietTimeChecker = QuietTimeChecker(clock, "22:30", "06:45") val quietTimeChecker = QuietTimeChecker(clock, "22:30", "06:45")
assertTrue(quietTimeChecker.isQuietTime) assertThat(quietTimeChecker.isQuietTime).isTrue()
} }
@Test @Test
@ -23,7 +24,7 @@ class QuietTimeCheckerTest {
setClockTo("10:00") setClockTo("10:00")
val quietTimeChecker = QuietTimeChecker(clock, "22:30", "06:45") val quietTimeChecker = QuietTimeChecker(clock, "22:30", "06:45")
assertFalse(quietTimeChecker.isQuietTime) assertThat(quietTimeChecker.isQuietTime).isFalse()
} }
@Test @Test
@ -31,7 +32,7 @@ class QuietTimeCheckerTest {
setClockTo("23:00") setClockTo("23:00")
val quietTimeChecker = QuietTimeChecker(clock, "22:30", "06:45") val quietTimeChecker = QuietTimeChecker(clock, "22:30", "06:45")
assertTrue(quietTimeChecker.isQuietTime) assertThat(quietTimeChecker.isQuietTime).isTrue()
} }
@Test @Test
@ -39,7 +40,7 @@ class QuietTimeCheckerTest {
setClockTo("22:30") setClockTo("22:30")
val quietTimeChecker = QuietTimeChecker(clock, "22:30", "06:45") val quietTimeChecker = QuietTimeChecker(clock, "22:30", "06:45")
assertTrue(quietTimeChecker.isQuietTime) assertThat(quietTimeChecker.isQuietTime).isTrue()
} }
@Test @Test
@ -47,7 +48,7 @@ class QuietTimeCheckerTest {
setClockTo("06:45") setClockTo("06:45")
val quietTimeChecker = QuietTimeChecker(clock, "22:30", "06:45") val quietTimeChecker = QuietTimeChecker(clock, "22:30", "06:45")
assertTrue(quietTimeChecker.isQuietTime) assertThat(quietTimeChecker.isQuietTime).isTrue()
} }
@Test @Test
@ -55,7 +56,7 @@ class QuietTimeCheckerTest {
setClockTo("02:00") setClockTo("02:00")
val quietTimeChecker = QuietTimeChecker(clock, "09:00", "17:00") val quietTimeChecker = QuietTimeChecker(clock, "09:00", "17:00")
assertFalse(quietTimeChecker.isQuietTime) assertThat(quietTimeChecker.isQuietTime).isFalse()
} }
@Test @Test
@ -63,7 +64,7 @@ class QuietTimeCheckerTest {
setClockTo("10:00") setClockTo("10:00")
val quietTimeChecker = QuietTimeChecker(clock, "09:00", "17:00") val quietTimeChecker = QuietTimeChecker(clock, "09:00", "17:00")
assertTrue(quietTimeChecker.isQuietTime) assertThat(quietTimeChecker.isQuietTime).isTrue()
} }
@Test @Test
@ -71,7 +72,7 @@ class QuietTimeCheckerTest {
setClockTo("20:00") setClockTo("20:00")
val quietTimeChecker = QuietTimeChecker(clock, "09:00", "17:00") val quietTimeChecker = QuietTimeChecker(clock, "09:00", "17:00")
assertFalse(quietTimeChecker.isQuietTime) assertThat(quietTimeChecker.isQuietTime).isFalse()
} }
@Test @Test
@ -79,7 +80,7 @@ class QuietTimeCheckerTest {
setClockTo("09:00") setClockTo("09:00")
val quietTimeChecker = QuietTimeChecker(clock, "09:00", "17:00") val quietTimeChecker = QuietTimeChecker(clock, "09:00", "17:00")
assertTrue(quietTimeChecker.isQuietTime) assertThat(quietTimeChecker.isQuietTime).isTrue()
} }
@Test @Test
@ -87,7 +88,7 @@ class QuietTimeCheckerTest {
setClockTo("17:00") setClockTo("17:00")
val quietTimeChecker = QuietTimeChecker(clock, "09:00", "17:00") val quietTimeChecker = QuietTimeChecker(clock, "09:00", "17:00")
assertTrue(quietTimeChecker.isQuietTime) assertThat(quietTimeChecker.isQuietTime).isTrue()
} }
@Test @Test
@ -95,7 +96,7 @@ class QuietTimeCheckerTest {
setClockTo("10:00") setClockTo("10:00")
val quietTimeChecker = QuietTimeChecker(clock, "06:00", "06:00") val quietTimeChecker = QuietTimeChecker(clock, "06:00", "06:00")
assertFalse(quietTimeChecker.isQuietTime) assertThat(quietTimeChecker.isQuietTime).isFalse()
} }
@Test @Test
@ -103,7 +104,7 @@ class QuietTimeCheckerTest {
setClockTo("06:00") setClockTo("06:00")
val quietTimeChecker = QuietTimeChecker(clock, "06:00", "06:00") val quietTimeChecker = QuietTimeChecker(clock, "06:00", "06:00")
assertFalse(quietTimeChecker.isQuietTime) assertThat(quietTimeChecker.isQuietTime).isFalse()
} }
private fun setClockTo(time: String) { private fun setClockTo(time: String) {

View file

@ -1,12 +1,16 @@
package com.fsck.k9.autocrypt package com.fsck.k9.autocrypt
import assertk.all
import assertk.assertThat
import assertk.assertions.containsExactly
import assertk.assertions.extracting
import assertk.assertions.index
import assertk.assertions.isEqualTo
import assertk.assertions.isNotNull
import assertk.assertions.isNull
import com.fsck.k9.mail.crlf import com.fsck.k9.mail.crlf
import com.fsck.k9.mail.filter.Base64 import com.fsck.k9.mail.filter.Base64
import com.fsck.k9.mailstore.MimePartStreamParser import com.fsck.k9.mailstore.MimePartStreamParser
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Test import org.junit.Test
class AutocryptGossipHeaderParserTest { class AutocryptGossipHeaderParserTest {
@ -56,20 +60,24 @@ class AutocryptGossipHeaderParserTest {
val gossipPart = MimePartStreamParser.parse(null, GOSSIP_PART.byteInputStream()) val gossipPart = MimePartStreamParser.parse(null, GOSSIP_PART.byteInputStream())
val allAutocryptGossipHeaders = autocryptGossipHeaderParser.getAllAutocryptGossipHeaders(gossipPart) val allAutocryptGossipHeaders = autocryptGossipHeaderParser.getAllAutocryptGossipHeaders(gossipPart)
assertEquals("text/plain", gossipPart.mimeType) assertThat(gossipPart.mimeType).isEqualTo("text/plain")
assertEquals(2, allAutocryptGossipHeaders.size) assertThat(allAutocryptGossipHeaders).all {
assertEquals("bob@autocrypt.example", allAutocryptGossipHeaders[0].addr) extracting { it.addr }.containsExactly(
assertEquals("carol@autocrypt.example", allAutocryptGossipHeaders[1].addr) "bob@autocrypt.example",
assertArrayEquals(GOSSIP_DATA_BOB, allAutocryptGossipHeaders[0].keyData) "carol@autocrypt.example",
)
index(0).transform { it.keyData }.isEqualTo(GOSSIP_DATA_BOB)
}
} }
@Test @Test
fun parseString() { fun parseString() {
val gossipHeader = autocryptGossipHeaderParser.parseAutocryptGossipHeader(GOSSIP_HEADER_BOB) val gossipHeader = autocryptGossipHeaderParser.parseAutocryptGossipHeader(GOSSIP_HEADER_BOB)
gossipHeader!! assertThat(gossipHeader).isNotNull().all {
assertArrayEquals(GOSSIP_DATA_BOB, gossipHeader.keyData) transform { it.keyData }.isEqualTo(GOSSIP_DATA_BOB)
assertEquals(GOSSIP_RAW_HEADER_BOB, gossipHeader.toRawHeaderString()) transform { it.toRawHeaderString() }.isEqualTo(GOSSIP_RAW_HEADER_BOB)
}
} }
@Test @Test
@ -78,7 +86,7 @@ class AutocryptGossipHeaderParserTest {
"addr=CDEF", "addr=CDEF",
) )
assertNull(gossipHeader) assertThat(gossipHeader).isNull()
} }
@Test @Test
@ -87,7 +95,7 @@ class AutocryptGossipHeaderParserTest {
"addr=bawb; somecritical=value; keydata=aGk", "addr=bawb; somecritical=value; keydata=aGk",
) )
assertNull(gossipHeader) assertThat(gossipHeader).isNull()
} }
@Test @Test
@ -96,7 +104,7 @@ class AutocryptGossipHeaderParserTest {
"addr=bawb; _somenoncritical=value; keydata=aGk", "addr=bawb; _somenoncritical=value; keydata=aGk",
) )
assertNotNull(gossipHeader) assertThat(gossipHeader).isNotNull()
} }
@Test @Test
@ -105,6 +113,6 @@ class AutocryptGossipHeaderParserTest {
"addr=bawb; _somenoncritical=value; keydata=X", "addr=bawb; _somenoncritical=value; keydata=X",
) )
assertNull(gossipHeader) assertThat(gossipHeader).isNull()
} }
} }

View file

@ -1,7 +1,8 @@
package com.fsck.k9.crypto package com.fsck.k9.crypto
import assertk.assertThat
import assertk.assertions.isEqualTo
import com.fsck.k9.Identity import com.fsck.k9.Identity
import org.junit.Assert.assertEquals
import org.junit.Test import org.junit.Test
class OpenPgpApiHelperTest { class OpenPgpApiHelperTest {
@ -15,7 +16,7 @@ class OpenPgpApiHelperTest {
val result = OpenPgpApiHelper.buildUserId(identity) val result = OpenPgpApiHelper.buildUserId(identity)
assertEquals("Name <user@domain.com>", result) assertThat(result).isEqualTo("Name <user@domain.com>")
} }
@Test @Test
@ -26,6 +27,6 @@ class OpenPgpApiHelperTest {
val result = OpenPgpApiHelper.buildUserId(identity) val result = OpenPgpApiHelper.buildUserId(identity)
assertEquals("<user@domain.com>", result) assertThat(result).isEqualTo("<user@domain.com>")
} }
} }

View file

@ -3,9 +3,9 @@ package com.fsck.k9.helper
import androidx.core.net.toUri import androidx.core.net.toUri
import assertk.assertThat import assertk.assertThat
import assertk.assertions.isEqualTo import assertk.assertions.isEqualTo
import assertk.assertions.isNull
import com.fsck.k9.RobolectricTest import com.fsck.k9.RobolectricTest
import com.fsck.k9.mail.internet.MimeMessage import com.fsck.k9.mail.internet.MimeMessage
import kotlin.test.assertNull
import org.junit.Test import org.junit.Test
class ListUnsubscribeHelperTest : RobolectricTest() { class ListUnsubscribeHelperTest : RobolectricTest() {
@ -60,7 +60,7 @@ class ListUnsubscribeHelperTest : RobolectricTest() {
"<http://example.com/unsubscribe>", "<http://example.com/unsubscribe>",
) )
val result = ListUnsubscribeHelper.getPreferredListUnsubscribeUri(message) val result = ListUnsubscribeHelper.getPreferredListUnsubscribeUri(message)
assertNull(result) assertThat(result).isNull()
} }
@Test @Test
@ -78,14 +78,14 @@ class ListUnsubscribeHelperTest : RobolectricTest() {
"", "",
) )
val result = ListUnsubscribeHelper.getPreferredListUnsubscribeUri(message) val result = ListUnsubscribeHelper.getPreferredListUnsubscribeUri(message)
assertNull(result) assertThat(result).isNull()
} }
@Test @Test
fun `get list unsubscribe url - should ignore missing header`() { fun `get list unsubscribe url - should ignore missing header`() {
val message = MimeMessage() val message = MimeMessage()
val result = ListUnsubscribeHelper.getPreferredListUnsubscribeUri(message) val result = ListUnsubscribeHelper.getPreferredListUnsubscribeUri(message)
assertNull(result) assertThat(result).isNull()
} }
private fun buildMimeMessageWithListUnsubscribeValue(value: String): MimeMessage { private fun buildMimeMessageWithListUnsubscribeValue(value: String): MimeMessage {

View file

@ -2,6 +2,13 @@ package com.fsck.k9.mailstore
import android.database.sqlite.SQLiteDatabase import android.database.sqlite.SQLiteDatabase
import androidx.core.content.contentValuesOf import androidx.core.content.contentValuesOf
import assertk.assertThat
import assertk.assertions.contains
import assertk.assertions.hasMessage
import assertk.assertions.isEqualTo
import assertk.assertions.isFailure
import assertk.assertions.isInstanceOf
import assertk.assertions.isTrue
import com.fsck.k9.Account import com.fsck.k9.Account
import com.fsck.k9.K9RobolectricTest import com.fsck.k9.K9RobolectricTest
import com.fsck.k9.Preferences import com.fsck.k9.Preferences
@ -17,9 +24,6 @@ import com.fsck.k9.mail.internet.MimeMessage
import com.fsck.k9.mail.internet.MimeMessageHelper import com.fsck.k9.mail.internet.MimeMessageHelper
import com.fsck.k9.mail.internet.TextBody import com.fsck.k9.mail.internet.TextBody
import org.junit.After import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Assert.fail
import org.junit.Test import org.junit.Test
import org.koin.core.component.inject import org.koin.core.component.inject
@ -45,7 +49,7 @@ class K9BackendFolderTest : K9RobolectricTest() {
val messageFlags = backendFolder.getMessageFlags(MESSAGE_SERVER_ID) val messageFlags = backendFolder.getMessageFlags(MESSAGE_SERVER_ID)
assertEquals(flags, messageFlags) assertThat(messageFlags).isEqualTo(flags)
} }
@Test @Test
@ -55,7 +59,7 @@ class K9BackendFolderTest : K9RobolectricTest() {
val messageFlags = backendFolder.getMessageFlags(MESSAGE_SERVER_ID) val messageFlags = backendFolder.getMessageFlags(MESSAGE_SERVER_ID)
assertTrue(messageFlags.isEmpty()) assertThat(messageFlags.isEmpty()).isTrue()
} }
@Test @Test
@ -66,29 +70,29 @@ class K9BackendFolderTest : K9RobolectricTest() {
val messageFlags = backendFolder.getMessageFlags(MESSAGE_SERVER_ID) val messageFlags = backendFolder.getMessageFlags(MESSAGE_SERVER_ID)
assertEquals(flags, messageFlags) assertThat(messageFlags).isEqualTo(flags)
} }
@Test @Test
fun saveCompleteMessage_withoutServerId_shouldThrow() { fun saveCompleteMessage_withoutServerId_shouldThrow() {
val message = createMessage(messageServerId = null) val message = createMessage(messageServerId = null)
try { assertThat {
backendFolder.saveMessage(message, MessageDownloadState.FULL) backendFolder.saveMessage(message, MessageDownloadState.FULL)
fail("Expected exception") }.isFailure()
} catch (e: IllegalStateException) { .isInstanceOf(IllegalStateException::class)
} .hasMessage("Message requires a server ID to be set")
} }
@Test @Test
fun savePartialMessage_withoutServerId_shouldThrow() { fun savePartialMessage_withoutServerId_shouldThrow() {
val message = createMessage(messageServerId = null) val message = createMessage(messageServerId = null)
try { assertThat {
backendFolder.saveMessage(message, MessageDownloadState.PARTIAL) backendFolder.saveMessage(message, MessageDownloadState.PARTIAL)
fail("Expected exception") }.isFailure()
} catch (e: IllegalStateException) { .isInstanceOf(IllegalStateException::class)
} .hasMessage("Message requires a server ID to be set")
} }
fun createAccount(): Account { fun createAccount(): Account {
@ -111,7 +115,7 @@ class K9BackendFolderTest : K9RobolectricTest() {
} }
val folderServerIds = backendStorage.getFolderServerIds() val folderServerIds = backendStorage.getFolderServerIds()
assertTrue(FOLDER_SERVER_ID in folderServerIds) assertThat(folderServerIds).contains(FOLDER_SERVER_ID)
return K9BackendFolder(messageStore, saveMessageDataCreator, FOLDER_SERVER_ID) return K9BackendFolder(messageStore, saveMessageDataCreator, FOLDER_SERVER_ID)
} }
@ -121,7 +125,7 @@ class K9BackendFolderTest : K9RobolectricTest() {
backendFolder.saveMessage(message, MessageDownloadState.FULL) backendFolder.saveMessage(message, MessageDownloadState.FULL)
val messageServerIds = backendFolder.getMessageServerIds() val messageServerIds = backendFolder.getMessageServerIds()
assertTrue(messageServerId in messageServerIds) assertThat(messageServerIds).contains(messageServerId)
} }
private fun createMessage(messageServerId: String?, flags: Set<Flag> = emptySet()): Message { private fun createMessage(messageServerId: String?, flags: Set<Flag> = emptySet()): Message {
@ -144,7 +148,7 @@ class K9BackendFolderTest : K9RobolectricTest() {
"uid = ?", "uid = ?",
arrayOf(MESSAGE_SERVER_ID), arrayOf(MESSAGE_SERVER_ID),
) )
assertEquals(1, numberOfUpdatedRows) assertThat(numberOfUpdatedRows).isEqualTo(1)
} }
} }

View file

@ -1,12 +1,13 @@
package com.fsck.k9.mailstore package com.fsck.k9.mailstore
import assertk.assertThat
import assertk.assertions.isEqualTo
import com.fsck.k9.Account import com.fsck.k9.Account
import com.fsck.k9.K9RobolectricTest import com.fsck.k9.K9RobolectricTest
import com.fsck.k9.Preferences import com.fsck.k9.Preferences
import com.fsck.k9.backend.api.BackendStorage import com.fsck.k9.backend.api.BackendStorage
import com.fsck.k9.mail.FolderClass import com.fsck.k9.mail.FolderClass
import org.junit.After import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Test import org.junit.Test
import org.koin.core.component.inject import org.koin.core.component.inject
import org.mockito.kotlin.any import org.mockito.kotlin.any
@ -15,12 +16,10 @@ import org.mockito.kotlin.mock
class K9BackendStorageTest : K9RobolectricTest() { class K9BackendStorageTest : K9RobolectricTest() {
val preferences: Preferences by inject() val preferences: Preferences by inject()
val localStoreProvider: LocalStoreProvider by inject()
val messageStoreManager: MessageStoreManager by inject() val messageStoreManager: MessageStoreManager by inject()
val saveMessageDataCreator: SaveMessageDataCreator by inject() val saveMessageDataCreator: SaveMessageDataCreator by inject()
val account: Account = createAccount() val account: Account = createAccount()
val database: LockableDatabase = localStoreProvider.getInstance(account).database
val backendStorage = createBackendStorage() val backendStorage = createBackendStorage()
@After @After
@ -33,7 +32,7 @@ class K9BackendStorageTest : K9RobolectricTest() {
backendStorage.setExtraString("testString", "someValue") backendStorage.setExtraString("testString", "someValue")
val value = backendStorage.getExtraString("testString") val value = backendStorage.getExtraString("testString")
assertEquals("someValue", value) assertThat(value).isEqualTo("someValue")
} }
@Test @Test
@ -42,7 +41,7 @@ class K9BackendStorageTest : K9RobolectricTest() {
backendStorage.setExtraString("testString", "newValue") backendStorage.setExtraString("testString", "newValue")
val value = backendStorage.getExtraString("testString") val value = backendStorage.getExtraString("testString")
assertEquals("newValue", value) assertThat(value).isEqualTo("newValue")
} }
@Test @Test
@ -50,7 +49,7 @@ class K9BackendStorageTest : K9RobolectricTest() {
backendStorage.setExtraNumber("testNumber", 42) backendStorage.setExtraNumber("testNumber", 42)
val value = backendStorage.getExtraNumber("testNumber") val value = backendStorage.getExtraNumber("testNumber")
assertEquals(42L, value) assertThat(value).isEqualTo(42L)
} }
@Test @Test
@ -59,7 +58,7 @@ class K9BackendStorageTest : K9RobolectricTest() {
backendStorage.setExtraNumber("testNumber", 23) backendStorage.setExtraNumber("testNumber", 23)
val value = backendStorage.getExtraNumber("testNumber") val value = backendStorage.getExtraNumber("testNumber")
assertEquals(23L, value) assertThat(value).isEqualTo(23L)
} }
fun createAccount(): Account { fun createAccount(): Account {

View file

@ -1,12 +1,18 @@
package com.fsck.k9.mailstore package com.fsck.k9.mailstore
import assertk.all
import assertk.assertThat
import assertk.assertions.hasSize
import assertk.assertions.isEqualTo
import assertk.assertions.isInstanceOf
import com.fsck.k9.mail.assertk.body
import com.fsck.k9.mail.assertk.bodyPart
import com.fsck.k9.mail.assertk.bodyParts
import com.fsck.k9.mail.assertk.mimeType
import com.fsck.k9.mail.crlf import com.fsck.k9.mail.crlf
import com.fsck.k9.mail.internet.MimeBodyPart
import com.fsck.k9.mail.internet.MimeMessage import com.fsck.k9.mail.internet.MimeMessage
import com.fsck.k9.mail.internet.MimeMultipart import com.fsck.k9.mail.internet.MimeMultipart
import java.io.ByteArrayInputStream import java.io.ByteArrayInputStream
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test import org.junit.Test
class MimePartStreamParserTest { class MimePartStreamParserTest {
@ -35,14 +41,15 @@ class MimePartStreamParserTest {
--1-- --1--
""".trimIndent().crlf() """.trimIndent().crlf()
val msg = MimePartStreamParser.parse(null, ByteArrayInputStream(messageContent.toByteArray())) val bodyPart = MimePartStreamParser.parse(null, ByteArrayInputStream(messageContent.toByteArray()))
val body = msg.body as MimeMultipart assertThat(bodyPart.body).isInstanceOf(MimeMultipart::class).all {
assertEquals(2, body.count.toLong()) bodyParts().hasSize(2)
bodyPart(1).all {
val messagePart = body.getBodyPart(1) as MimeBodyPart mimeType().isEqualTo("message/rfc822")
assertEquals("message/rfc822", messagePart.mimeType) body().isInstanceOf(MimeMessage::class)
assertTrue(messagePart.body is MimeMessage) }
}
} }
@Test @Test
@ -71,13 +78,14 @@ class MimePartStreamParserTest {
--1-- --1--
""".trimIndent().crlf() """.trimIndent().crlf()
val msg = MimePartStreamParser.parse(null, ByteArrayInputStream(messageContent.toByteArray())) val bodyPart = MimePartStreamParser.parse(null, ByteArrayInputStream(messageContent.toByteArray()))
val body = msg.body as MimeMultipart assertThat(bodyPart.body).isInstanceOf(MimeMultipart::class).all {
assertEquals(2, body.count) bodyParts().hasSize(2)
bodyPart(1).all {
val messagePart = body.getBodyPart(1) as MimeBodyPart mimeType().isEqualTo("message/rfc822")
assertEquals("message/rfc822", messagePart.mimeType) body().isInstanceOf(DeferredFileBody::class)
assertTrue(messagePart.body is DeferredFileBody) }
}
} }
} }

View file

@ -1,7 +1,10 @@
package com.fsck.k9.message.html package com.fsck.k9.message.html
import assertk.Assert
import assertk.assertThat
import assertk.assertions.hasSize
import assertk.assertions.isEqualTo
import org.jsoup.Jsoup import org.jsoup.Jsoup
import org.junit.Assert.assertEquals
import org.junit.Test import org.junit.Test
class DisplayHtmlTest { class DisplayHtmlTest {
@ -11,21 +14,21 @@ class DisplayHtmlTest {
fun wrapMessageContent_addsViewportMetaElement() { fun wrapMessageContent_addsViewportMetaElement() {
val html = displayHtml.wrapMessageContent("Some text") val html = displayHtml.wrapMessageContent("Some text")
assertHtmlContainsElement(html, "head > meta[name=viewport]") assertThat(html).containsHtmlElement("head > meta[name=viewport]")
} }
@Test @Test
fun wrapMessageContent_setsDirToAuto() { fun wrapMessageContent_setsDirToAuto() {
val html = displayHtml.wrapMessageContent("Some text") val html = displayHtml.wrapMessageContent("Some text")
assertHtmlContainsElement(html, "html[dir=auto]") assertThat(html).containsHtmlElement("html[dir=auto]")
} }
@Test @Test
fun wrapMessageContent_addsPreCSS() { fun wrapMessageContent_addsPreCSS() {
val html = displayHtml.wrapMessageContent("Some text") val html = displayHtml.wrapMessageContent("Some text")
assertHtmlContainsElement(html, "head > style") assertThat(html).containsHtmlElement("head > style")
} }
@Test @Test
@ -34,7 +37,7 @@ class DisplayHtmlTest {
val html = darkModeDisplayHtml.wrapMessageContent("Some text") val html = darkModeDisplayHtml.wrapMessageContent("Some text")
assertHtmlContainsElement(html, "head > style", 2) assertThat(html).htmlElements("head > style").hasSize(2)
} }
@Test @Test
@ -43,16 +46,18 @@ class DisplayHtmlTest {
val html = displayHtml.wrapMessageContent(content) val html = displayHtml.wrapMessageContent(content)
assertEquals(content, Jsoup.parse(html).body().text()) assertThat(html).bodyText().isEqualTo(content)
} }
private fun assertHtmlContainsElement(html: String, cssQuery: String, numberOfExpectedOccurrences: Int = 1) { private fun Assert<String>.containsHtmlElement(cssQuery: String) = given { actual ->
val document = Jsoup.parse(html) assertThat(actual).htmlElements(cssQuery).hasSize(1)
val numberOfFoundElements = document.select(cssQuery).size }
assertEquals(
"Expected to find '$cssQuery' $numberOfExpectedOccurrences time(s) in:\n$html", private fun Assert<String>.htmlElements(cssQuery: String) = transform { html ->
numberOfExpectedOccurrences, Jsoup.parse(html).select(cssQuery)
numberOfFoundElements, }
)
private fun Assert<String>.bodyText() = transform { html ->
Jsoup.parse(html).body().text()
} }
} }

View file

@ -5,7 +5,8 @@ import assertk.assertions.hasMessage
import assertk.assertions.isEqualTo import assertk.assertions.isEqualTo
import assertk.assertions.isFailure import assertk.assertions.isFailure
import assertk.assertions.isInstanceOf import assertk.assertions.isInstanceOf
import kotlin.test.assertNotNull import assertk.assertions.isNotNull
import assertk.assertions.prop
import org.junit.Test import org.junit.Test
class GenericUriParserTest { class GenericUriParserTest {
@ -86,8 +87,7 @@ class GenericUriParserTest {
private fun assertUriValid(input: String) { private fun assertUriValid(input: String) {
val result = parser.parseUri(input, 0) val result = parser.parseUri(input, 0)
assertNotNull(result) { uriMatch -> assertThat(result).isNotNull()
assertThat(uriMatch.uri).isEqualTo(input) .prop(UriMatch::uri).isEqualTo(input)
}
} }
} }

View file

@ -1,14 +1,15 @@
package com.fsck.k9.preferences package com.fsck.k9.preferences
import assertk.assertThat
import assertk.assertions.isEqualTo
import assertk.assertions.isNotNull
import assertk.assertions.isNull
import com.fsck.k9.K9RobolectricTest import com.fsck.k9.K9RobolectricTest
import com.fsck.k9.Preferences import com.fsck.k9.Preferences
import com.fsck.k9.mailstore.FolderRepository import com.fsck.k9.mailstore.FolderRepository
import java.io.ByteArrayOutputStream import java.io.ByteArrayOutputStream
import org.jdom2.Document import org.jdom2.Document
import org.jdom2.input.SAXBuilder import org.jdom2.input.SAXBuilder
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Test import org.junit.Test
import org.koin.core.component.inject import org.koin.core.component.inject
import org.mockito.kotlin.mock import org.mockito.kotlin.mock
@ -31,35 +32,35 @@ class SettingsExporterTest : K9RobolectricTest() {
fun exportPreferences_producesXML() { fun exportPreferences_producesXML() {
val document = exportPreferences(false, emptySet()) val document = exportPreferences(false, emptySet())
assertEquals("k9settings", document.rootElement.name) assertThat(document.rootElement.name).isEqualTo("k9settings")
} }
@Test @Test
fun exportPreferences_setsVersionToLatest() { fun exportPreferences_setsVersionToLatest() {
val document = exportPreferences(false, emptySet()) val document = exportPreferences(false, emptySet())
assertEquals(Settings.VERSION.toString(), document.rootElement.getAttributeValue("version")) assertThat(document.rootElement.getAttributeValue("version")).isEqualTo(Settings.VERSION.toString())
} }
@Test @Test
fun exportPreferences_setsFormatTo1() { fun exportPreferences_setsFormatTo1() {
val document = exportPreferences(false, emptySet()) val document = exportPreferences(false, emptySet())
assertEquals("1", document.rootElement.getAttributeValue("format")) assertThat(document.rootElement.getAttributeValue("format")).isEqualTo("1")
} }
@Test @Test
fun exportPreferences_exportsGlobalSettingsWhenRequested() { fun exportPreferences_exportsGlobalSettingsWhenRequested() {
val document = exportPreferences(true, emptySet()) val document = exportPreferences(true, emptySet())
assertNotNull(document.rootElement.getChild("global")) assertThat(document.rootElement.getChild("global")).isNotNull()
} }
@Test @Test
fun exportPreferences_ignoresGlobalSettingsWhenRequested() { fun exportPreferences_ignoresGlobalSettingsWhenRequested() {
val document = exportPreferences(false, emptySet()) val document = exportPreferences(false, emptySet())
assertNull(document.rootElement.getChild("global")) assertThat(document.rootElement.getChild("global")).isNull()
} }
private fun exportPreferences(globalSettings: Boolean, accounts: Set<String>): Document { private fun exportPreferences(globalSettings: Boolean, accounts: Set<String>): Document {

View file

@ -1,13 +1,16 @@
package com.fsck.k9.preferences package com.fsck.k9.preferences
import android.content.Context import android.content.Context
import assertk.assertThat
import assertk.assertions.contains
import assertk.assertions.containsOnly
import assertk.assertions.isEmpty
import assertk.assertions.isFailure
import assertk.assertions.isSameAs
import assertk.assertions.isTrue
import com.fsck.k9.preferences.K9StoragePersister.StoragePersistOperationCallback import com.fsck.k9.preferences.K9StoragePersister.StoragePersistOperationCallback
import com.fsck.k9.preferences.K9StoragePersister.StoragePersistOperations import com.fsck.k9.preferences.K9StoragePersister.StoragePersistOperations
import com.fsck.k9.storage.K9RobolectricTest import com.fsck.k9.storage.K9RobolectricTest
import org.junit.Assert.assertEquals
import org.junit.Assert.assertSame
import org.junit.Assert.assertTrue
import org.junit.Assert.fail
import org.junit.Test import org.junit.Test
import org.mockito.kotlin.any import org.mockito.kotlin.any
import org.mockito.kotlin.inOrder import org.mockito.kotlin.inOrder
@ -39,16 +42,15 @@ class StoragePersisterTest : K9RobolectricTest() {
val operationCallback = prepareCallback( val operationCallback = prepareCallback(
persistOp = { ops -> ops.put("x", "y") }, persistOp = { ops -> ops.put("x", "y") },
onSuccess = { map -> onSuccess = { map ->
assertEquals(1, map.size) assertThat(map).containsOnly("x" to "y")
assertEquals("y", map["x"])
}, },
) )
storagePersister.doInTransaction(operationCallback) storagePersister.doInTransaction(operationCallback)
val values = storagePersister.loadValues().all val values = storagePersister.loadValues().all
assertEquals(1, values.size)
assertEquals("y", values["x"]) assertThat(values).containsOnly("x" to "y")
} }
@Test @Test
@ -61,15 +63,14 @@ class StoragePersisterTest : K9RobolectricTest() {
}, },
) )
try { assertThat {
storagePersister.doInTransaction(operationCallback) storagePersister.doInTransaction(operationCallback)
fail("expected exception") }.isFailure()
} catch (e: Exception) { .isSameAs(exception)
assertSame(exception, e)
}
val values = storagePersister.loadValues() val values = storagePersister.loadValues()
assertTrue(values.isEmpty())
assertThat(values.isEmpty).isTrue()
verify(operationCallback, never()).onPersistTransactionSuccess(any()) verify(operationCallback, never()).onPersistTransactionSuccess(any())
} }
@ -78,26 +79,32 @@ class StoragePersisterTest : K9RobolectricTest() {
val operationCallback = prepareCallback( val operationCallback = prepareCallback(
before = { map -> map["x"] = "y" }, before = { map -> map["x"] = "y" },
persistOp = { ops -> ops.remove("x") }, persistOp = { ops -> ops.remove("x") },
onSuccess = { map -> assertTrue(map.isEmpty()) }, onSuccess = { map ->
assertThat(map).isEmpty()
},
) )
storagePersister.doInTransaction(operationCallback) storagePersister.doInTransaction(operationCallback)
val values = storagePersister.loadValues() val values = storagePersister.loadValues()
assertTrue(values.isEmpty())
assertThat(values.isEmpty).isTrue()
} }
@Test @Test
fun doInTransaction_before_preserveButNotPersist() { fun doInTransaction_before_preserveButNotPersist() {
val operationCallback = prepareCallback( val operationCallback = prepareCallback(
before = { map -> map["x"] = "y" }, before = { map -> map["x"] = "y" },
onSuccess = { map -> assertEquals("y", map["x"]) }, onSuccess = { map ->
assertThat(map).contains(key = "x", value = "y")
},
) )
storagePersister.doInTransaction(operationCallback) storagePersister.doInTransaction(operationCallback)
val values = storagePersister.loadValues() val values = storagePersister.loadValues()
assertTrue(values.isEmpty())
assertThat(values.isEmpty).isTrue()
} }
private fun prepareCallback( private fun prepareCallback(

View file

@ -3,7 +3,7 @@ package com.fsck.k9.storage.messages
import assertk.assertThat import assertk.assertThat
import assertk.assertions.hasSize import assertk.assertions.hasSize
import assertk.assertions.isEqualTo import assertk.assertions.isEqualTo
import org.junit.Assert.fail import assertk.fail
import org.junit.Test import org.junit.Test
class ChunkedDatabaseOperationsTest { class ChunkedDatabaseOperationsTest {

View file

@ -9,7 +9,6 @@ import assertk.assertions.startsWith
import com.fsck.k9.K9 import com.fsck.k9.K9
import com.fsck.k9.storage.RobolectricTest import com.fsck.k9.storage.RobolectricTest
import org.junit.Test import org.junit.Test
import org.junit.Assert.fail as junitFail
private const val SOURCE_FOLDER_ID = 3L private const val SOURCE_FOLDER_ID = 3L
private const val DESTINATION_FOLDER_ID = 23L private const val DESTINATION_FOLDER_ID = 23L
@ -211,6 +210,4 @@ class MoveMessageOperationsTest : RobolectricTest() {
assertThat(message.messagePartId).isNull() assertThat(message.messagePartId).isNull()
assertThat(message.encryptionType).isNull() assertThat(message.encryptionType).isNull()
} }
private fun fail(message: String): Nothing = junitFail(message) as Nothing
} }

View file

@ -1,8 +1,9 @@
package com.fsck.k9.contacts package com.fsck.k9.contacts
import assertk.assertThat
import assertk.assertions.isEqualTo
import com.fsck.k9.RobolectricTest import com.fsck.k9.RobolectricTest
import com.fsck.k9.mail.Address import com.fsck.k9.mail.Address
import org.junit.Assert.assertEquals
import org.junit.Test import org.junit.Test
class ContactLetterExtractorTest : RobolectricTest() { class ContactLetterExtractorTest : RobolectricTest() {
@ -54,6 +55,6 @@ class ContactLetterExtractorTest : RobolectricTest() {
} }
private fun assertExtractedLetterEquals(expected: String, address: String) { private fun assertExtractedLetterEquals(expected: String, address: String) {
assertEquals(expected, letterExtractor.extractContactLetter(Address(address))) assertThat(letterExtractor.extractContactLetter(Address(address))).isEqualTo(expected)
} }
} }

View file

@ -4,6 +4,17 @@ import android.app.Activity
import android.app.PendingIntent import android.app.PendingIntent
import android.content.Intent import android.content.Intent
import android.os.Parcelable import android.os.Parcelable
import assertk.Assert
import assertk.all
import assertk.assertThat
import assertk.assertions.containsExactly
import assertk.assertions.hasSize
import assertk.assertions.isEmpty
import assertk.assertions.isEqualTo
import assertk.assertions.isInstanceOf
import assertk.assertions.isNotNull
import assertk.assertions.isNull
import assertk.assertions.isSameAs
import com.fsck.k9.Account.QuoteStyle import com.fsck.k9.Account.QuoteStyle
import com.fsck.k9.CoreResourceProvider import com.fsck.k9.CoreResourceProvider
import com.fsck.k9.Identity import com.fsck.k9.Identity
@ -15,29 +26,29 @@ import com.fsck.k9.autocrypt.AutocryptOpenPgpApiInteractor
import com.fsck.k9.autocrypt.AutocryptOperations import com.fsck.k9.autocrypt.AutocryptOperations
import com.fsck.k9.autocrypt.AutocryptOperationsHelper.assertMessageHasAutocryptHeader import com.fsck.k9.autocrypt.AutocryptOperationsHelper.assertMessageHasAutocryptHeader
import com.fsck.k9.mail.Address import com.fsck.k9.mail.Address
import com.fsck.k9.mail.BodyPart
import com.fsck.k9.mail.BoundaryGenerator import com.fsck.k9.mail.BoundaryGenerator
import com.fsck.k9.mail.MessagingException import com.fsck.k9.mail.MessagingException
import com.fsck.k9.mail.assertk.asBytes
import com.fsck.k9.mail.assertk.asText
import com.fsck.k9.mail.assertk.body
import com.fsck.k9.mail.assertk.bodyPart
import com.fsck.k9.mail.assertk.bodyParts
import com.fsck.k9.mail.assertk.contentTransferEncoding
import com.fsck.k9.mail.assertk.contentType
import com.fsck.k9.mail.assertk.mimeType
import com.fsck.k9.mail.assertk.parameter
import com.fsck.k9.mail.assertk.value
import com.fsck.k9.mail.internet.BinaryTempFileBody import com.fsck.k9.mail.internet.BinaryTempFileBody
import com.fsck.k9.mail.internet.MessageIdGenerator import com.fsck.k9.mail.internet.MessageIdGenerator
import com.fsck.k9.mail.internet.MimeMessage import com.fsck.k9.mail.internet.MimeMessage
import com.fsck.k9.mail.internet.MimeMultipart import com.fsck.k9.mail.internet.MimeMultipart
import com.fsck.k9.mail.internet.MimeUtility
import com.fsck.k9.mail.internet.TextBody import com.fsck.k9.mail.internet.TextBody
import com.fsck.k9.message.MessageBuilder.Callback import com.fsck.k9.message.MessageBuilder.Callback
import com.fsck.k9.message.quote.InsertableHtmlContent import com.fsck.k9.message.quote.InsertableHtmlContent
import com.fsck.k9.view.RecipientSelectView import com.fsck.k9.view.RecipientSelectView
import java.io.ByteArrayOutputStream
import java.io.IOException
import java.io.OutputStream import java.io.OutputStream
import java.util.Date import java.util.Date
import org.apache.commons.io.Charsets
import org.apache.commons.io.IOUtils
import org.apache.james.mime4j.util.MimeUtil import org.apache.james.mime4j.util.MimeUtil
import org.junit.Assert
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertTrue
import org.junit.Before import org.junit.Before
import org.junit.Test import org.junit.Test
import org.koin.core.component.inject import org.koin.core.component.inject
@ -143,7 +154,7 @@ class PgpMessageBuilderTest : K9RobolectricTest() {
verifyNoMoreInteractions(mockCallback) verifyNoMoreInteractions(mockCallback)
val message = captor.value val message = captor.value
assertEquals("text/plain", message.mimeType) assertThat(message.mimeType).isEqualTo("text/plain")
} }
@Test @Test
@ -159,7 +170,7 @@ class PgpMessageBuilderTest : K9RobolectricTest() {
val message = captor.value val message = captor.value
assertMessageHasAutocryptHeader(message, SENDER_EMAIL, false, AUTOCRYPT_KEY_MATERIAL) assertMessageHasAutocryptHeader(message, SENDER_EMAIL, false, AUTOCRYPT_KEY_MATERIAL)
assertEquals(0, message.getHeader("Autocrypt-Draft-State").size) assertThat(message.getHeader("Autocrypt-Draft-State")).isEmpty()
} }
@Test @Test
@ -206,45 +217,32 @@ class PgpMessageBuilderTest : K9RobolectricTest() {
val expectedIntent = Intent(OpenPgpApi.ACTION_DETACHED_SIGN) val expectedIntent = Intent(OpenPgpApi.ACTION_DETACHED_SIGN)
expectedIntent.putExtra(OpenPgpApi.EXTRA_SIGN_KEY_ID, TEST_KEY_ID) expectedIntent.putExtra(OpenPgpApi.EXTRA_SIGN_KEY_ID, TEST_KEY_ID)
expectedIntent.putExtra(OpenPgpApi.EXTRA_REQUEST_ASCII_ARMOR, true) expectedIntent.putExtra(OpenPgpApi.EXTRA_REQUEST_ASCII_ARMOR, true)
assertIntentEqualsActionAndExtras(expectedIntent, capturedApiIntent.value) assertThat(capturedApiIntent.value).matches(expectedIntent)
val captor = ArgumentCaptor.forClass(MimeMessage::class.java) val captor = ArgumentCaptor.forClass(MimeMessage::class.java)
verify(mockCallback).onMessageBuildSuccess(captor.capture(), eq(false)) verify(mockCallback).onMessageBuildSuccess(captor.capture(), eq(false))
verifyNoMoreInteractions(mockCallback) verifyNoMoreInteractions(mockCallback)
val message = captor.value val message = captor.value
Assert.assertEquals("message must be multipart/signed", "multipart/signed", message.mimeType) assertThat(message.mimeType).isEqualTo("multipart/signed")
val multipart = message.body as MimeMultipart assertThat(message.body).isInstanceOf(MimeMultipart::class).all {
Assert.assertEquals("multipart/signed must consist of two parts", 2, multipart.count.toLong()) bodyParts().hasSize(2)
bodyPart(0).all {
val contentBodyPart = multipart.getBodyPart(0) contentType().value().isEqualTo("text/plain")
Assert.assertEquals( body().isInstanceOf(TextBody::class).all {
"first part must have content type text/plain", contentTransferEncoding().isEqualTo(MimeUtil.ENC_QUOTED_PRINTABLE)
"text/plain", asText().isEqualTo(TEST_MESSAGE_TEXT)
MimeUtility.getHeaderParameter(contentBodyPart.contentType, null), }
) }
assertTrue("signed message body must be TextBody", contentBodyPart.body is TextBody) bodyPart(1).all {
Assert.assertEquals(MimeUtil.ENC_QUOTED_PRINTABLE, (contentBodyPart.body as TextBody).encoding) contentType().all {
assertContentOfBodyPartEquals("content must match the message text", contentBodyPart, TEST_MESSAGE_TEXT) value().isEqualTo("application/pgp-signature")
parameter("name").isEqualTo("signature.asc")
val signatureBodyPart = multipart.getBodyPart(1) }
val contentType = signatureBodyPart.contentType body().asBytes().isEqualTo(byteArrayOf(1, 2, 3))
Assert.assertEquals( }
"second part must be pgp signature", }
"application/pgp-signature",
MimeUtility.getHeaderParameter(contentType, null),
)
Assert.assertEquals(
"second part must be called signature.asc",
"signature.asc",
MimeUtility.getHeaderParameter(contentType, "name"),
)
assertContentOfBodyPartEquals(
"content must match the supplied detached signature",
signatureBodyPart,
byteArrayOf(1, 2, 3),
)
assertMessageHasAutocryptHeader(message, SENDER_EMAIL, false, AUTOCRYPT_KEY_MATERIAL) assertMessageHasAutocryptHeader(message, SENDER_EMAIL, false, AUTOCRYPT_KEY_MATERIAL)
} }
@ -274,7 +272,7 @@ class PgpMessageBuilderTest : K9RobolectricTest() {
verifyNoMoreInteractions(mockCallback) verifyNoMoreInteractions(mockCallback)
val pendingIntent = captor.value val pendingIntent = captor.value
Assert.assertSame(pendingIntent, mockPendingIntent) assertThat(pendingIntent).isSameAs(mockPendingIntent)
} }
@Test @Test
@ -306,7 +304,7 @@ class PgpMessageBuilderTest : K9RobolectricTest() {
verifyNoMoreInteractions(mockCallback) verifyNoMoreInteractions(mockCallback)
returnedRequestCode = rcCaptor.value returnedRequestCode = rcCaptor.value
Assert.assertSame(mockPendingIntent, piCaptor.value) assertThat(piCaptor.value).isEqualTo(mockPendingIntent)
} }
run { run {
@ -367,7 +365,7 @@ class PgpMessageBuilderTest : K9RobolectricTest() {
val mimeMessage = buildMessage() val mimeMessage = buildMessage()
assertEquals("encrypt=no; ", mimeMessage.getHeader("Autocrypt-Draft-State").get(0)) assertThat(mimeMessage.getHeader("Autocrypt-Draft-State")).containsExactly("encrypt=no; ")
} }
@Test @Test
@ -382,7 +380,8 @@ class PgpMessageBuilderTest : K9RobolectricTest() {
val mimeMessage = buildMessage() val mimeMessage = buildMessage()
assertEquals("encrypt=yes; _is-reply-to-encrypted=yes; ", mimeMessage.getHeader("Autocrypt-Draft-State").get(0)) assertThat(mimeMessage.getHeader("Autocrypt-Draft-State"))
.containsExactly("encrypt=yes; _is-reply-to-encrypted=yes; ")
} }
@Test @Test
@ -394,7 +393,7 @@ class PgpMessageBuilderTest : K9RobolectricTest() {
val mimeMessage = buildMessage() val mimeMessage = buildMessage()
assertEquals("encrypt=yes; _by-choice=yes; ", mimeMessage.getHeader("Autocrypt-Draft-State").get(0)) assertThat(mimeMessage.getHeader("Autocrypt-Draft-State")).containsExactly("encrypt=yes; _by-choice=yes; ")
} }
@Test @Test
@ -406,10 +405,8 @@ class PgpMessageBuilderTest : K9RobolectricTest() {
val mimeMessage = buildMessage() val mimeMessage = buildMessage()
assertEquals( assertThat(mimeMessage.getHeader("Autocrypt-Draft-State"))
"encrypt=no; _sign-only=yes; _by-choice=yes; ", .containsExactly("encrypt=no; _sign-only=yes; _by-choice=yes; ")
mimeMessage.getHeader("Autocrypt-Draft-State").get(0),
)
} }
private fun buildMessage(): MimeMessage { private fun buildMessage(): MimeMessage {
@ -431,7 +428,7 @@ class PgpMessageBuilderTest : K9RobolectricTest() {
verify(mockCallback).onMessageBuildSuccess(mimeMessageCaptor.capture(), eq(true)) verify(mockCallback).onMessageBuildSuccess(mimeMessageCaptor.capture(), eq(true))
verifyNoMoreInteractions(mockCallback) verifyNoMoreInteractions(mockCallback)
assertNotNull(mimeMessageCaptor.value) assertThat(mimeMessageCaptor.value).isNotNull()
return mimeMessageCaptor.value return mimeMessageCaptor.value
} }
@ -552,7 +549,7 @@ class PgpMessageBuilderTest : K9RobolectricTest() {
expectedApiIntent.putExtra(OpenPgpApi.EXTRA_KEY_IDS, longArrayOf(TEST_KEY_ID)) expectedApiIntent.putExtra(OpenPgpApi.EXTRA_KEY_IDS, longArrayOf(TEST_KEY_ID))
expectedApiIntent.putExtra(OpenPgpApi.EXTRA_REQUEST_ASCII_ARMOR, true) expectedApiIntent.putExtra(OpenPgpApi.EXTRA_REQUEST_ASCII_ARMOR, true)
expectedApiIntent.putExtra(OpenPgpApi.EXTRA_USER_IDS, cryptoStatus.recipientAddressesAsArray) expectedApiIntent.putExtra(OpenPgpApi.EXTRA_USER_IDS, cryptoStatus.recipientAddressesAsArray)
assertIntentEqualsActionAndExtras(expectedApiIntent, capturedApiIntent.value) assertThat(capturedApiIntent.value).matches(expectedApiIntent)
val captor = ArgumentCaptor.forClass(MimeMessage::class.java) val captor = ArgumentCaptor.forClass(MimeMessage::class.java)
verify(mockCallback).onMessageBuildSuccess(captor.capture(), eq(false)) verify(mockCallback).onMessageBuildSuccess(captor.capture(), eq(false))
@ -560,34 +557,24 @@ class PgpMessageBuilderTest : K9RobolectricTest() {
val message = captor.value val message = captor.value
Assert.assertEquals("message must be multipart/encrypted", "multipart/encrypted", message.mimeType) assertThat(message).all {
mimeType().isEqualTo("multipart/encrypted")
val multipart = message.body as MimeMultipart body().isInstanceOf(MimeMultipart::class).all {
Assert.assertEquals("multipart/encrypted must consist of two parts", 2, multipart.count.toLong()) bodyParts().hasSize(2)
bodyPart(0).all {
val dummyBodyPart = multipart.getBodyPart(0) contentType().value().isEqualTo("application/pgp-encrypted")
Assert.assertEquals( body().asText().isEqualTo("Version: 1")
"first part must be pgp encrypted dummy part", }
"application/pgp-encrypted", bodyPart(1).all {
dummyBodyPart.contentType, contentType().all {
) value().isEqualTo("application/octet-stream")
assertContentOfBodyPartEquals( parameter("name").isEqualTo("encrypted.asc")
"content must match the supplied detached signature", }
dummyBodyPart, body().isInstanceOf(BinaryTempFileBody::class)
"Version: 1", .contentTransferEncoding().isEqualTo(MimeUtil.ENC_7BIT)
) }
}
val encryptedBodyPart = multipart.getBodyPart(1) }
Assert.assertEquals(
"second part must be octet-stream of encrypted data",
"application/octet-stream; name=\"encrypted.asc\"",
encryptedBodyPart.contentType,
)
assertTrue(
"message body must be BinaryTempFileBody",
encryptedBodyPart.body is BinaryTempFileBody,
)
Assert.assertEquals(MimeUtil.ENC_7BIT, (encryptedBodyPart.body as BinaryTempFileBody).encoding)
assertMessageHasAutocryptHeader(message, SENDER_EMAIL, false, AUTOCRYPT_KEY_MATERIAL) assertMessageHasAutocryptHeader(message, SENDER_EMAIL, false, AUTOCRYPT_KEY_MATERIAL)
} }
@ -623,16 +610,18 @@ class PgpMessageBuilderTest : K9RobolectricTest() {
expectedApiIntent.putExtra(OpenPgpApi.EXTRA_KEY_IDS, longArrayOf(TEST_KEY_ID)) expectedApiIntent.putExtra(OpenPgpApi.EXTRA_KEY_IDS, longArrayOf(TEST_KEY_ID))
expectedApiIntent.putExtra(OpenPgpApi.EXTRA_REQUEST_ASCII_ARMOR, true) expectedApiIntent.putExtra(OpenPgpApi.EXTRA_REQUEST_ASCII_ARMOR, true)
expectedApiIntent.putExtra(OpenPgpApi.EXTRA_USER_IDS, cryptoStatus.recipientAddressesAsArray) expectedApiIntent.putExtra(OpenPgpApi.EXTRA_USER_IDS, cryptoStatus.recipientAddressesAsArray)
assertIntentEqualsActionAndExtras(expectedApiIntent, capturedApiIntent.value) assertThat(capturedApiIntent.value).matches(expectedApiIntent)
val captor = ArgumentCaptor.forClass(MimeMessage::class.java) val captor = ArgumentCaptor.forClass(MimeMessage::class.java)
verify(mockCallback).onMessageBuildSuccess(captor.capture(), eq(false)) verify(mockCallback).onMessageBuildSuccess(captor.capture(), eq(false))
verifyNoMoreInteractions(mockCallback) verifyNoMoreInteractions(mockCallback)
val message = captor.value val message = captor.value
Assert.assertEquals("text/plain", message.mimeType) assertThat(message).all {
assertTrue("message body must be BinaryTempFileBody", message.body is BinaryTempFileBody) mimeType().isEqualTo("text/plain")
Assert.assertEquals(MimeUtil.ENC_7BIT, (message.body as BinaryTempFileBody).encoding) body().isInstanceOf(BinaryTempFileBody::class)
.contentTransferEncoding().isEqualTo(MimeUtil.ENC_7BIT)
}
assertMessageHasAutocryptHeader(message, SENDER_EMAIL, false, AUTOCRYPT_KEY_MATERIAL) assertMessageHasAutocryptHeader(message, SENDER_EMAIL, false, AUTOCRYPT_KEY_MATERIAL)
} }
@ -667,14 +656,14 @@ class PgpMessageBuilderTest : K9RobolectricTest() {
val expectedApiIntent = Intent(OpenPgpApi.ACTION_SIGN) val expectedApiIntent = Intent(OpenPgpApi.ACTION_SIGN)
expectedApiIntent.putExtra(OpenPgpApi.EXTRA_SIGN_KEY_ID, TEST_KEY_ID) expectedApiIntent.putExtra(OpenPgpApi.EXTRA_SIGN_KEY_ID, TEST_KEY_ID)
expectedApiIntent.putExtra(OpenPgpApi.EXTRA_REQUEST_ASCII_ARMOR, true) expectedApiIntent.putExtra(OpenPgpApi.EXTRA_REQUEST_ASCII_ARMOR, true)
assertIntentEqualsActionAndExtras(expectedApiIntent, capturedApiIntent.value) assertThat(capturedApiIntent.value).matches(expectedApiIntent)
val captor = ArgumentCaptor.forClass(MimeMessage::class.java) val captor = ArgumentCaptor.forClass(MimeMessage::class.java)
verify(mockCallback).onMessageBuildSuccess(captor.capture(), eq(false)) verify(mockCallback).onMessageBuildSuccess(captor.capture(), eq(false))
verifyNoMoreInteractions(mockCallback) verifyNoMoreInteractions(mockCallback)
val message = captor.value val message = captor.value
Assert.assertEquals("message must be text/plain", "text/plain", message.mimeType) assertThat(message.mimeType).isEqualTo("text/plain")
assertMessageHasAutocryptHeader(message, SENDER_EMAIL, false, AUTOCRYPT_KEY_MATERIAL) assertMessageHasAutocryptHeader(message, SENDER_EMAIL, false, AUTOCRYPT_KEY_MATERIAL)
} }
@ -742,7 +731,7 @@ class PgpMessageBuilderTest : K9RobolectricTest() {
verifyNoMoreInteractions(mockCallback) verifyNoMoreInteractions(mockCallback)
val message = captor.value val message = captor.value
Assert.assertEquals("text/plain", message.mimeType) assertThat(message.mimeType).isEqualTo("text/plain")
} }
@Test @Test
@ -820,58 +809,28 @@ class PgpMessageBuilderTest : K9RobolectricTest() {
return builder return builder
} }
private fun assertContentOfBodyPartEquals(reason: String, signatureBodyPart: BodyPart, expected: ByteArray) { private fun Assert<Intent>.matches(expected: Intent) = given { actual ->
try { assertThat(actual.action).isEqualTo(expected.action)
val bos = ByteArrayOutputStream()
signatureBodyPart.body.writeTo(bos)
Assert.assertArrayEquals(reason, expected, bos.toByteArray())
} catch (e: IOException) {
Assert.fail()
} catch (e: MessagingException) {
Assert.fail()
}
}
private fun assertContentOfBodyPartEquals(reason: String, signatureBodyPart: BodyPart, expected: String) { val expectedExtras = checkNotNull(expected.extras)
try { val intentExtras = checkNotNull(actual.extras)
val bos = ByteArrayOutputStream() assertThat(intentExtras.size()).isEqualTo(expectedExtras.size())
val inputStream = MimeUtility.decodeBody(signatureBodyPart.body)
IOUtils.copy(inputStream, bos)
Assert.assertEquals(reason, expected, String(bos.toByteArray(), Charsets.UTF_8))
} catch (e: IOException) {
Assert.fail()
} catch (e: MessagingException) {
Assert.fail()
}
}
private fun assertIntentEqualsActionAndExtras(expected: Intent, actual: Intent) {
Assert.assertEquals(expected.action, actual.action)
val expectedExtras = expected.extras
val intentExtras = actual.extras
if (expectedExtras!!.size() != intentExtras!!.size()) {
Assert.assertEquals(expectedExtras.size().toLong(), intentExtras.size().toLong())
}
for (key in expectedExtras.keySet()) { for (key in expectedExtras.keySet()) {
val name = "extra[$key]"
val intentExtra = intentExtras.get(key) val intentExtra = intentExtras.get(key)
val expectedExtra = expectedExtras.get(key) val expectedExtra = expectedExtras.get(key)
if (intentExtra == null) {
if (expectedExtra == null) { if (expectedExtra == null) {
continue assertThat(intentExtra, name).isNull()
}
Assert.fail("found null for an expected non-null extra: $key")
}
if (intentExtra is LongArray) {
Assert.assertArrayEquals("error in $key", expectedExtra as LongArray, intentExtra)
} else if (intentExtra is Array<*>) {
Assert.assertArrayEquals("error in $key", expectedExtra as Array<*>, intentExtra)
} else { } else {
if (intentExtra != expectedExtra) { assertThat(intentExtra, name).isNotNull()
Assert.assertEquals("error in $key", expectedExtra, intentExtra) }
}
when (intentExtra) {
is LongArray -> assertThat(intentExtra, name).isEqualTo(expectedExtra as LongArray)
is Array<*> -> assertThat(intentExtra as Array<Any?>, name).isEqualTo(expectedExtra as Array<Any?>)
else -> assertThat(intentExtra, name).isEqualTo(expectedExtra)
} }
} }
} }

View file

@ -1,8 +1,10 @@
package com.fsck.k9.ui package com.fsck.k9.ui
import assertk.assertThat
import assertk.assertions.isEqualTo
import assertk.assertions.size
import com.fsck.k9.RobolectricTest import com.fsck.k9.RobolectricTest
import com.fsck.k9.core.R import com.fsck.k9.core.R
import org.junit.Assert.assertEquals
import org.junit.Test import org.junit.Test
import org.robolectric.RuntimeEnvironment import org.robolectric.RuntimeEnvironment
@ -14,6 +16,6 @@ class K9DrawerTest : RobolectricTest() {
val lightColors = resources.getIntArray(R.array.account_colors) val lightColors = resources.getIntArray(R.array.account_colors)
val darkColors = resources.getIntArray(R.array.drawer_account_accent_color_dark_theme) val darkColors = resources.getIntArray(R.array.drawer_account_accent_color_dark_theme)
assertEquals(lightColors.size, darkColors.size) assertThat(darkColors).size().isEqualTo(lightColors.size)
} }
} }

View file

@ -3,13 +3,14 @@ package com.fsck.k9.ui.helper
import android.os.Build import android.os.Build
import android.os.SystemClock import android.os.SystemClock
import app.k9mail.core.testing.TestClock import app.k9mail.core.testing.TestClock
import assertk.assertThat
import assertk.assertions.isEqualTo
import com.fsck.k9.RobolectricTest import com.fsck.k9.RobolectricTest
import java.time.LocalDate import java.time.LocalDate
import java.time.LocalDateTime import java.time.LocalDateTime
import java.time.ZoneId import java.time.ZoneId
import java.util.TimeZone import java.util.TimeZone
import kotlinx.datetime.Instant import kotlinx.datetime.Instant
import org.junit.Assert.assertEquals
import org.junit.Before import org.junit.Before
import org.junit.Test import org.junit.Test
import org.robolectric.RuntimeEnvironment import org.robolectric.RuntimeEnvironment
@ -39,7 +40,7 @@ class RelativeDateTimeFormatterTest : RobolectricTest() {
val displayDate = dateTimeFormatter.formatDate(date) val displayDate = dateTimeFormatter.formatDate(date)
assertEquals("May 18", displayDate) assertThat(displayDate).isEqualTo("May 18")
} }
@Test @Test
@ -49,7 +50,7 @@ class RelativeDateTimeFormatterTest : RobolectricTest() {
val displayDate = dateTimeFormatter.formatDate(date) val displayDate = dateTimeFormatter.formatDate(date)
assertEquals("3:41 PM", displayDate) assertThat(displayDate).isEqualTo("3:41 PM")
} }
@Test @Test
@ -59,7 +60,7 @@ class RelativeDateTimeFormatterTest : RobolectricTest() {
val displayDate = dateTimeFormatter.formatDate(date) val displayDate = dateTimeFormatter.formatDate(date)
assertEquals("9:42 AM", displayDate) assertThat(displayDate).isEqualTo("9:42 AM")
} }
@Test @Test
@ -69,7 +70,7 @@ class RelativeDateTimeFormatterTest : RobolectricTest() {
val displayDate = dateTimeFormatter.formatDate(date) val displayDate = dateTimeFormatter.formatDate(date)
assertEquals("Sat", displayDate) assertThat(displayDate).isEqualTo("Sat")
} }
@Test @Test
@ -79,7 +80,7 @@ class RelativeDateTimeFormatterTest : RobolectricTest() {
val displayDate = dateTimeFormatter.formatDate(date) val displayDate = dateTimeFormatter.formatDate(date)
assertEquals("Mon", displayDate) assertThat(displayDate).isEqualTo("Mon")
} }
@Test @Test
@ -89,7 +90,7 @@ class RelativeDateTimeFormatterTest : RobolectricTest() {
val displayDate = dateTimeFormatter.formatDate(date) val displayDate = dateTimeFormatter.formatDate(date)
assertEquals("May 10", displayDate) assertThat(displayDate).isEqualTo("May 10")
} }
@Test @Test
@ -99,7 +100,7 @@ class RelativeDateTimeFormatterTest : RobolectricTest() {
val displayDate = dateTimeFormatter.formatDate(date) val displayDate = dateTimeFormatter.formatDate(date)
assertEquals("May 10", displayDate) assertThat(displayDate).isEqualTo("May 10")
} }
@Test @Test
@ -109,7 +110,7 @@ class RelativeDateTimeFormatterTest : RobolectricTest() {
val displayDate = dateTimeFormatter.formatDate(date) val displayDate = dateTimeFormatter.formatDate(date)
assertEquals("Jan 1", displayDate) assertThat(displayDate).isEqualTo("Jan 1")
} }
@Test @Test
@ -119,7 +120,7 @@ class RelativeDateTimeFormatterTest : RobolectricTest() {
val displayDate = dateTimeFormatter.formatDate(date) val displayDate = dateTimeFormatter.formatDate(date)
assertEquals("12/31/2019", displayDate) assertThat(displayDate).isEqualTo("12/31/2019")
} }
private fun setClockTo(time: String) { private fun setClockTo(time: String) {

View file

@ -1,7 +1,8 @@
package com.fsck.k9.ui.helper package com.fsck.k9.ui.helper
import assertk.assertThat
import assertk.assertions.isEqualTo
import com.fsck.k9.RobolectricTest import com.fsck.k9.RobolectricTest
import org.junit.Assert.assertEquals
import org.junit.Test import org.junit.Test
import org.robolectric.RuntimeEnvironment import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config import org.robolectric.annotation.Config
@ -12,46 +13,46 @@ class SizeFormatterTest : RobolectricTest() {
@Test @Test
fun bytes_lower_bound() { fun bytes_lower_bound() {
assertEquals("0 B", sizeFormatter.formatSize(0)) assertThat(sizeFormatter.formatSize(0)).isEqualTo("0 B")
} }
@Test @Test
fun bytes_upper_bound() { fun bytes_upper_bound() {
assertEquals("999 B", sizeFormatter.formatSize(999)) assertThat(sizeFormatter.formatSize(999)).isEqualTo("999 B")
} }
@Test @Test
fun kilobytes_lower_bound() { fun kilobytes_lower_bound() {
assertEquals("1.0 kB", sizeFormatter.formatSize(1000)) assertThat(sizeFormatter.formatSize(1000)).isEqualTo("1.0 kB")
} }
@Test @Test
fun kilobytes_upper_bound() { fun kilobytes_upper_bound() {
assertEquals("999.9 kB", sizeFormatter.formatSize(999_949)) assertThat(sizeFormatter.formatSize(999_949)).isEqualTo("999.9 kB")
} }
@Test @Test
fun megabytes_lower_bound() { fun megabytes_lower_bound() {
assertEquals("1.0 MB", sizeFormatter.formatSize(999_950)) assertThat(sizeFormatter.formatSize(999_950)).isEqualTo("1.0 MB")
} }
@Test @Test
fun megabytes_upper_bound() { fun megabytes_upper_bound() {
assertEquals("999.9 MB", sizeFormatter.formatSize(999_949_999)) assertThat(sizeFormatter.formatSize(999_949_999)).isEqualTo("999.9 MB")
} }
@Test @Test
fun gigabytes_lower_bound() { fun gigabytes_lower_bound() {
assertEquals("1.0 GB", sizeFormatter.formatSize(999_950_000)) assertThat(sizeFormatter.formatSize(999_950_000)).isEqualTo("1.0 GB")
} }
@Test @Test
fun gigabytes_2() { fun gigabytes_2() {
assertEquals("2.0 GB", sizeFormatter.formatSize(2_000_000_000L)) assertThat(sizeFormatter.formatSize(2_000_000_000L)).isEqualTo("2.0 GB")
} }
@Test @Test
fun gigabytes_2000() { fun gigabytes_2000() {
assertEquals("2000.0 GB", sizeFormatter.formatSize(2_000_000_000_000L)) assertThat(sizeFormatter.formatSize(2_000_000_000_000L)).isEqualTo("2000.0 GB")
} }
} }

View file

@ -12,6 +12,11 @@ import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.isGone import androidx.core.view.isGone
import androidx.core.view.isVisible import androidx.core.view.isVisible
import app.k9mail.core.testing.TestClock import app.k9mail.core.testing.TestClock
import assertk.Assert
import assertk.assertThat
import assertk.assertions.isEqualTo
import assertk.assertions.isNull
import assertk.assertions.support.expected
import com.fsck.k9.Account import com.fsck.k9.Account
import com.fsck.k9.FontSizes import com.fsck.k9.FontSizes
import com.fsck.k9.FontSizes.FONT_DEFAULT import com.fsck.k9.FontSizes.FONT_DEFAULT
@ -23,10 +28,6 @@ import com.fsck.k9.mail.Address
import com.fsck.k9.textString import com.fsck.k9.textString
import com.fsck.k9.ui.R import com.fsck.k9.ui.R
import com.fsck.k9.ui.helper.RelativeDateTimeFormatter import com.fsck.k9.ui.helper.RelativeDateTimeFormatter
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test import org.junit.Test
import org.mockito.kotlin.mock import org.mockito.kotlin.mock
import org.robolectric.Robolectric import org.robolectric.Robolectric
@ -49,7 +50,7 @@ class MessageListAdapterTest : RobolectricTest() {
val view = adapter.createAndBindView() val view = adapter.createAndBindView()
assertTrue(view.accountChipView.isVisible) assertThat(view.accountChipView).isVisible()
} }
@Test @Test
@ -58,7 +59,7 @@ class MessageListAdapterTest : RobolectricTest() {
val view = adapter.createAndBindView() val view = adapter.createAndBindView()
assertTrue(view.accountChipView.isGone) assertThat(view.accountChipView).isGone()
} }
@Test @Test
@ -67,7 +68,7 @@ class MessageListAdapterTest : RobolectricTest() {
val view = adapter.createAndBindView() val view = adapter.createAndBindView()
assertTrue(view.starView.isGone) assertThat(view.starView).isGone()
} }
@Test @Test
@ -76,7 +77,7 @@ class MessageListAdapterTest : RobolectricTest() {
val view = adapter.createAndBindView() val view = adapter.createAndBindView()
assertTrue(view.starView.isVisible) assertThat(view.starView).isVisible()
} }
@Test @Test
@ -86,7 +87,7 @@ class MessageListAdapterTest : RobolectricTest() {
val view = adapter.createAndBindView(messageListItem) val view = adapter.createAndBindView(messageListItem)
assertTrue(view.starView.isSelected) assertThat(view.starView).isSelected()
} }
@Test @Test
@ -96,7 +97,7 @@ class MessageListAdapterTest : RobolectricTest() {
val view = adapter.createAndBindView(messageListItem) val view = adapter.createAndBindView(messageListItem)
assertFalse(view.starView.isSelected) assertThat(view.starView).isNotSelected()
} }
@Test @Test
@ -105,7 +106,7 @@ class MessageListAdapterTest : RobolectricTest() {
val view = adapter.createAndBindView() val view = adapter.createAndBindView()
assertTrue(view.contactPictureContainerView.isGone) assertThat(view.contactPictureContainerView).isGone()
} }
@Test @Test
@ -114,7 +115,7 @@ class MessageListAdapterTest : RobolectricTest() {
val view = adapter.createAndBindView() val view = adapter.createAndBindView()
assertTrue(view.contactPictureContainerView.isVisible) assertThat(view.contactPictureContainerView).isVisible()
} }
@Test @Test
@ -124,7 +125,7 @@ class MessageListAdapterTest : RobolectricTest() {
val view = adapter.createAndBindView(messageListItem) val view = adapter.createAndBindView(messageListItem)
assertTrue(view.threadCountView.isGone) assertThat(view.threadCountView).isGone()
} }
@Test @Test
@ -134,8 +135,8 @@ class MessageListAdapterTest : RobolectricTest() {
val view = adapter.createAndBindView(messageListItem) val view = adapter.createAndBindView(messageListItem)
assertTrue(view.threadCountView.isVisible) assertThat(view.threadCountView).isVisible()
assertEquals("13", view.threadCountView.textString) assertThat(view.threadCountView.textString).isEqualTo("13")
} }
@Test @Test
@ -145,7 +146,7 @@ class MessageListAdapterTest : RobolectricTest() {
val view = adapter.createAndBindView(messageListItem) val view = adapter.createAndBindView(messageListItem)
assertEquals("Subject", view.firstLineView.textString) assertThat(view.firstLineView.textString).isEqualTo("Subject")
} }
@Test @Test
@ -155,7 +156,7 @@ class MessageListAdapterTest : RobolectricTest() {
val view = adapter.createAndBindView(messageListItem) val view = adapter.createAndBindView(messageListItem)
assertEquals("Display Name", view.firstLineView.textString) assertThat(view.firstLineView.textString).isEqualTo("Display Name")
} }
@Test @Test
@ -165,7 +166,7 @@ class MessageListAdapterTest : RobolectricTest() {
val view = adapter.createAndBindView(messageListItem) val view = adapter.createAndBindView(messageListItem)
assertEquals("Display Name", view.secondLineView.textString) assertThat(view.secondLineView.textString).isEqualTo("Display Name")
} }
@Test @Test
@ -175,7 +176,7 @@ class MessageListAdapterTest : RobolectricTest() {
val view = adapter.createAndBindView(messageListItem) val view = adapter.createAndBindView(messageListItem)
assertEquals(secondLine("Display Name", "Preview"), view.secondLineView.textString) assertThat(view.secondLineView.textString).isEqualTo(secondLine("Display Name", "Preview"))
} }
@Test @Test
@ -185,7 +186,7 @@ class MessageListAdapterTest : RobolectricTest() {
val view = adapter.createAndBindView(messageListItem) val view = adapter.createAndBindView(messageListItem)
assertEquals("Subject", view.secondLineView.textString) assertThat(view.secondLineView.textString).isEqualTo("Subject")
} }
@Test @Test
@ -195,7 +196,7 @@ class MessageListAdapterTest : RobolectricTest() {
val view = adapter.createAndBindView(messageListItem) val view = adapter.createAndBindView(messageListItem)
assertEquals(secondLine("Subject", "Preview"), view.secondLineView.textString) assertThat(view.secondLineView.textString).isEqualTo(secondLine("Subject", "Preview"))
} }
@Test @Test
@ -205,7 +206,7 @@ class MessageListAdapterTest : RobolectricTest() {
val view = adapter.createAndBindView(messageListItem) val view = adapter.createAndBindView(messageListItem)
assertTrue(view.firstLineView.containsNoSubjectIndicator()) assertThat(view.firstLineView.textString).isMissingSubjectText()
} }
@Test @Test
@ -215,7 +216,7 @@ class MessageListAdapterTest : RobolectricTest() {
val view = adapter.createAndBindView(messageListItem) val view = adapter.createAndBindView(messageListItem)
assertTrue(view.firstLineView.containsNoSubjectIndicator()) assertThat(view.firstLineView.textString).isMissingSubjectText()
} }
@Test @Test
@ -225,7 +226,7 @@ class MessageListAdapterTest : RobolectricTest() {
val view = adapter.createAndBindView(messageListItem) val view = adapter.createAndBindView(messageListItem)
assertTrue(view.attachmentCountView.isGone) assertThat(view.attachmentCountView).isGone()
} }
@Test @Test
@ -235,7 +236,7 @@ class MessageListAdapterTest : RobolectricTest() {
val view = adapter.createAndBindView(messageListItem) val view = adapter.createAndBindView(messageListItem)
assertTrue(view.attachmentCountView.isVisible) assertThat(view.attachmentCountView).isVisible()
} }
@Test @Test
@ -247,7 +248,7 @@ class MessageListAdapterTest : RobolectricTest() {
val view = adapter.createAndBindView() val view = adapter.createAndBindView()
assertEquals(FIRST_LINE_DEFAULT_FONT_SIZE, view.firstLineView.textSize) assertThat(view.firstLineView.textSize).isEqualTo(FIRST_LINE_DEFAULT_FONT_SIZE)
} }
@Test @Test
@ -259,7 +260,7 @@ class MessageListAdapterTest : RobolectricTest() {
val view = adapter.createAndBindView() val view = adapter.createAndBindView()
assertEquals(22f, view.firstLineView.textSize) assertThat(view.firstLineView.textSize).isEqualTo(22f)
} }
@Test @Test
@ -271,7 +272,7 @@ class MessageListAdapterTest : RobolectricTest() {
val view = adapter.createAndBindView() val view = adapter.createAndBindView()
assertEquals(FIRST_LINE_DEFAULT_FONT_SIZE, view.firstLineView.textSize) assertThat(view.firstLineView.textSize).isEqualTo(FIRST_LINE_DEFAULT_FONT_SIZE)
} }
@Test @Test
@ -283,7 +284,7 @@ class MessageListAdapterTest : RobolectricTest() {
val view = adapter.createAndBindView() val view = adapter.createAndBindView()
assertEquals(22f, view.firstLineView.textSize) assertThat(view.firstLineView.textSize).isEqualTo(22f)
} }
@Test @Test
@ -295,7 +296,7 @@ class MessageListAdapterTest : RobolectricTest() {
val view = adapter.createAndBindView() val view = adapter.createAndBindView()
assertNull(view.secondLineView.getFirstAbsoluteSizeSpanValueOrNull()) assertThat(view.secondLineView.text).firstAbsoluteSizeSpanValue().isNull()
} }
@Test @Test
@ -307,7 +308,7 @@ class MessageListAdapterTest : RobolectricTest() {
val view = adapter.createAndBindView() val view = adapter.createAndBindView()
assertEquals(22, view.secondLineView.getFirstAbsoluteSizeSpanValueOrNull()) assertThat(view.secondLineView.text).firstAbsoluteSizeSpanValue().isEqualTo(22)
} }
@Test @Test
@ -319,7 +320,7 @@ class MessageListAdapterTest : RobolectricTest() {
val view = adapter.createAndBindView() val view = adapter.createAndBindView()
assertNull(view.secondLineView.getFirstAbsoluteSizeSpanValueOrNull()) assertThat(view.secondLineView.text).firstAbsoluteSizeSpanValue().isNull()
} }
@Test @Test
@ -331,7 +332,7 @@ class MessageListAdapterTest : RobolectricTest() {
val view = adapter.createAndBindView() val view = adapter.createAndBindView()
assertEquals(22, view.secondLineView.getFirstAbsoluteSizeSpanValueOrNull()) assertThat(view.secondLineView.text).firstAbsoluteSizeSpanValue().isEqualTo(22)
} }
@Test @Test
@ -340,7 +341,7 @@ class MessageListAdapterTest : RobolectricTest() {
val view = adapter.createAndBindView() val view = adapter.createAndBindView()
assertEquals(DATE_DEFAULT_FONT_SIZE, view.dateView.textSize) assertThat(view.dateView.textSize).isEqualTo(DATE_DEFAULT_FONT_SIZE)
} }
@Test @Test
@ -349,7 +350,7 @@ class MessageListAdapterTest : RobolectricTest() {
val view = adapter.createAndBindView() val view = adapter.createAndBindView()
assertEquals(22f, view.dateView.textSize) assertThat(view.dateView.textSize).isEqualTo(22f)
} }
@Test @Test
@ -361,7 +362,7 @@ class MessageListAdapterTest : RobolectricTest() {
val view = adapter.createAndBindView() val view = adapter.createAndBindView()
assertEquals(SECOND_LINE_DEFAULT_FONT_SIZE, view.secondLineView.textSize) assertThat(view.secondLineView.textSize).isEqualTo(SECOND_LINE_DEFAULT_FONT_SIZE)
} }
@Test @Test
@ -373,7 +374,7 @@ class MessageListAdapterTest : RobolectricTest() {
val view = adapter.createAndBindView() val view = adapter.createAndBindView()
assertEquals(22f, view.secondLineView.textSize) assertThat(view.secondLineView.textSize).isEqualTo(22f)
} }
fun createFontSizes( fun createFontSizes(
@ -486,10 +487,36 @@ class MessageListAdapterTest : RobolectricTest() {
val View.attachmentCountView: View get() = findViewById(R.id.attachment) val View.attachmentCountView: View get() = findViewById(R.id.attachment)
val View.dateView: TextView get() = findViewById(R.id.date) val View.dateView: TextView get() = findViewById(R.id.date)
fun TextView.containsNoSubjectIndicator() = textString.contains(context.getString(R.string.general_no_subject)) private fun Assert<View>.isVisible() = given { actual ->
if (!actual.isVisible) {
expected("View to be visible ($actual)")
}
}
fun TextView.getFirstAbsoluteSizeSpanValueOrNull(): Int? { private fun Assert<View>.isGone() = given { actual ->
if (!actual.isGone) {
expected("View to be gone ($actual)")
}
}
private fun Assert<View>.isSelected() = given { actual ->
if (!actual.isSelected) {
expected("View to be selected ($actual)")
}
}
private fun Assert<View>.isNotSelected() = given { actual ->
if (actual.isSelected) {
expected("View to not be selected ($actual)")
}
}
private fun Assert<CharSequence>.isMissingSubjectText() {
isEqualTo(context.getString(R.string.general_no_subject))
}
private fun Assert<CharSequence>.firstAbsoluteSizeSpanValue() = transform { text ->
val spans = (text as Spannable).getSpans(0, text.length, AbsoluteSizeSpan::class.java) val spans = (text as Spannable).getSpans(0, text.length, AbsoluteSizeSpan::class.java)
return spans.firstOrNull()?.size spans.firstOrNull()?.size
} }
} }

View file

@ -1,18 +1,21 @@
package com.fsck.k9.backend.jmap package com.fsck.k9.backend.jmap
import app.k9mail.backend.testing.InMemoryBackendStorage import app.k9mail.backend.testing.InMemoryBackendStorage
import assertk.assertThat
import assertk.assertions.containsExactlyInAnyOrder
import assertk.assertions.isEqualTo
import assertk.assertions.isFailure
import assertk.assertions.isInstanceOf
import assertk.assertions.isTrue
import assertk.fail
import com.fsck.k9.backend.api.BackendFolderUpdater import com.fsck.k9.backend.api.BackendFolderUpdater
import com.fsck.k9.backend.api.FolderInfo import com.fsck.k9.backend.api.FolderInfo
import com.fsck.k9.backend.api.updateFolders import com.fsck.k9.backend.api.updateFolders
import com.fsck.k9.mail.AuthenticationFailedException import com.fsck.k9.mail.AuthenticationFailedException
import com.fsck.k9.mail.FolderType import com.fsck.k9.mail.FolderType
import com.fsck.k9.mail.MessagingException import com.fsck.k9.mail.MessagingException
import junit.framework.AssertionFailedError
import okhttp3.HttpUrl import okhttp3.HttpUrl
import okhttp3.mockwebserver.MockResponse import okhttp3.mockwebserver.MockResponse
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Assert.fail
import org.junit.Test import org.junit.Test
import rs.ltt.jmap.client.JmapClient import rs.ltt.jmap.client.JmapClient
@ -25,11 +28,10 @@ class CommandRefreshFolderListTest {
MockResponse().setResponseCode(401), MockResponse().setResponseCode(401),
) )
try { assertThat {
command.refreshFolderList() command.refreshFolderList()
fail("Expected exception") }.isFailure()
} catch (e: AuthenticationFailedException) { .isInstanceOf(AuthenticationFailedException::class)
}
} }
@Test @Test
@ -38,12 +40,11 @@ class CommandRefreshFolderListTest {
MockResponse().setBody("invalid"), MockResponse().setBody("invalid"),
) )
try { assertThat {
command.refreshFolderList() command.refreshFolderList()
fail("Expected exception") }.isFailure()
} catch (e: MessagingException) { .isInstanceOf(MessagingException::class)
assertTrue(e.isPermanentFailure) .transform { it.isPermanentFailure }.isTrue()
}
} }
@Test @Test
@ -162,18 +163,17 @@ class CommandRefreshFolderListTest {
} }
private fun assertFolderList(vararg folderServerIds: String) { private fun assertFolderList(vararg folderServerIds: String) {
assertEquals(folderServerIds.toSet(), backendStorage.getFolderServerIds().toSet()) assertThat(backendStorage.getFolderServerIds()).containsExactlyInAnyOrder(*folderServerIds)
} }
private fun assertFolderPresent(serverId: String, name: String, type: FolderType) { private fun assertFolderPresent(serverId: String, name: String, type: FolderType) {
val folder = backendStorage.folders[serverId] val folder = backendStorage.folders[serverId] ?: fail("Expected folder '$serverId' in BackendStorage")
?: throw AssertionFailedError("Expected folder '$serverId' in BackendStorage")
assertEquals(name, folder.name) assertThat(folder.name).isEqualTo(name)
assertEquals(type, folder.type) assertThat(folder.type).isEqualTo(type)
} }
private fun assertMailboxState(expected: String) { private fun assertMailboxState(expected: String) {
assertEquals(expected, backendStorage.getExtraString("jmapState")) assertThat(backendStorage.getExtraString("jmapState")).isEqualTo(expected)
} }
} }

View file

@ -2,6 +2,12 @@ package com.fsck.k9.backend.jmap
import app.k9mail.backend.testing.InMemoryBackendFolder import app.k9mail.backend.testing.InMemoryBackendFolder
import app.k9mail.backend.testing.InMemoryBackendStorage import app.k9mail.backend.testing.InMemoryBackendStorage
import assertk.assertThat
import assertk.assertions.containsOnly
import assertk.assertions.isEmpty
import assertk.assertions.isEqualTo
import assertk.assertions.isInstanceOf
import assertk.assertions.isNotNull
import com.fsck.k9.backend.api.FolderInfo import com.fsck.k9.backend.api.FolderInfo
import com.fsck.k9.backend.api.SyncConfig import com.fsck.k9.backend.api.SyncConfig
import com.fsck.k9.backend.api.SyncConfig.ExpungePolicy import com.fsck.k9.backend.api.SyncConfig.ExpungePolicy
@ -16,7 +22,6 @@ import okhttp3.HttpUrl
import okhttp3.OkHttpClient import okhttp3.OkHttpClient
import okhttp3.mockwebserver.MockResponse import okhttp3.mockwebserver.MockResponse
import okhttp3.mockwebserver.MockWebServer import okhttp3.mockwebserver.MockWebServer
import org.junit.Assert.assertEquals
import org.junit.Before import org.junit.Before
import org.junit.Test import org.junit.Test
import rs.ltt.jmap.client.JmapClient import rs.ltt.jmap.client.JmapClient
@ -49,9 +54,9 @@ class CommandSyncTest {
command.sync(FOLDER_SERVER_ID, syncConfig, syncListener) command.sync(FOLDER_SERVER_ID, syncConfig, syncListener)
assertEquals(SyncListenerEvent.SyncStarted(FOLDER_SERVER_ID), syncListener.getNextEvent()) assertThat(syncListener.getNextEvent()).isEqualTo(SyncListenerEvent.SyncStarted(FOLDER_SERVER_ID))
val failedEvent = syncListener.getNextEvent() as SyncListenerEvent.SyncFailed val failedEvent = syncListener.getNextEvent() as SyncListenerEvent.SyncFailed
assertEquals(AuthenticationFailedException::class.java, failedEvent.exception!!.javaClass) assertThat(failedEvent.exception).isNotNull().isInstanceOf(AuthenticationFailedException::class)
} }
@Test @Test
@ -103,7 +108,13 @@ class CommandSyncTest {
command.sync(FOLDER_SERVER_ID, syncConfig, syncListener) command.sync(FOLDER_SERVER_ID, syncConfig, syncListener)
val backendFolder = backendStorage.getFolder(FOLDER_SERVER_ID) val backendFolder = backendStorage.getFolder(FOLDER_SERVER_ID)
assertEquals(setOf("M001", "M002", "M003", "M004", "M005"), backendFolder.getMessageServerIds()) assertThat(backendFolder.getMessageServerIds()).containsOnly(
"M001",
"M002",
"M003",
"M004",
"M005",
)
syncListener.assertSyncSuccess() syncListener.assertSyncSuccess()
} }
@ -145,7 +156,7 @@ class CommandSyncTest {
command.sync(FOLDER_SERVER_ID, syncConfig, syncListener) command.sync(FOLDER_SERVER_ID, syncConfig, syncListener)
assertEquals(emptySet<String>(), backendFolder.getMessageServerIds()) assertThat(backendFolder.getMessageServerIds()).isEmpty()
syncListener.assertSyncEvents( syncListener.assertSyncEvents(
SyncListenerEvent.SyncStarted(FOLDER_SERVER_ID), SyncListenerEvent.SyncStarted(FOLDER_SERVER_ID),
SyncListenerEvent.SyncFinished(FOLDER_SERVER_ID), SyncListenerEvent.SyncFinished(FOLDER_SERVER_ID),
@ -168,9 +179,9 @@ class CommandSyncTest {
command.sync(FOLDER_SERVER_ID, syncConfig, syncListener) command.sync(FOLDER_SERVER_ID, syncConfig, syncListener)
assertEquals(setOf("M001", "M002"), backendFolder.getMessageServerIds()) assertThat(backendFolder.getMessageServerIds()).containsOnly("M001", "M002")
assertEquals(emptySet<Flag>(), backendFolder.getMessageFlags("M001")) assertThat(backendFolder.getMessageFlags("M001")).isEmpty()
assertEquals(setOf(Flag.SEEN), backendFolder.getMessageFlags("M002")) assertThat(backendFolder.getMessageFlags("M002")).containsOnly(Flag.SEEN)
backendFolder.assertQueryState("50:0") backendFolder.assertQueryState("50:0")
syncListener.assertSyncEvents( syncListener.assertSyncEvents(
SyncListenerEvent.SyncStarted(FOLDER_SERVER_ID), SyncListenerEvent.SyncStarted(FOLDER_SERVER_ID),
@ -196,7 +207,7 @@ class CommandSyncTest {
command.sync(FOLDER_SERVER_ID, syncConfig, syncListener) command.sync(FOLDER_SERVER_ID, syncConfig, syncListener)
assertEquals(setOf("M002", "M003"), backendFolder.getMessageServerIds()) assertThat(backendFolder.getMessageServerIds()).containsOnly("M002", "M003")
backendFolder.assertQueryState("51:0") backendFolder.assertQueryState("51:0")
syncListener.assertSyncSuccess() syncListener.assertSyncSuccess()
} }
@ -220,7 +231,7 @@ class CommandSyncTest {
command.sync(FOLDER_SERVER_ID, syncConfig, syncListener) command.sync(FOLDER_SERVER_ID, syncConfig, syncListener)
assertEquals(setOf("M002", "M003"), backendFolder.getMessageServerIds()) assertThat(backendFolder.getMessageServerIds()).containsOnly("M002", "M003")
backendFolder.assertQueryState("50:0") backendFolder.assertQueryState("50:0")
syncListener.assertSyncSuccess() syncListener.assertSyncSuccess()
} }
@ -246,11 +257,11 @@ class CommandSyncTest {
val request = takeRequest() val request = takeRequest()
val requestUrl = request.requestUrl ?: error("No request URL") val requestUrl = request.requestUrl ?: error("No request URL")
val requestUrlPath = requestUrl.encodedPath + "?" + requestUrl.encodedQuery val requestUrlPath = requestUrl.encodedPath + "?" + requestUrl.encodedQuery
assertEquals(expected, requestUrlPath) assertThat(requestUrlPath).isEqualTo(expected)
} }
private fun InMemoryBackendFolder.assertQueryState(expected: String) { private fun InMemoryBackendFolder.assertQueryState(expected: String) {
assertEquals(expected, getFolderExtraString("jmapQueryState")) assertThat(getFolderExtraString("jmapQueryState")).isEqualTo(expected)
} }
private fun InMemoryBackendFolder.setQueryState(queryState: String) { private fun InMemoryBackendFolder.setQueryState(queryState: String) {

View file

@ -1,9 +1,10 @@
package com.fsck.k9.backend.jmap package com.fsck.k9.backend.jmap
import assertk.assertThat
import assertk.assertions.isEmpty
import assertk.assertions.isEqualTo
import assertk.fail
import com.fsck.k9.backend.api.SyncListener import com.fsck.k9.backend.api.SyncListener
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Assert.fail
class LoggingSyncListener : SyncListener { class LoggingSyncListener : SyncListener {
private val events = mutableListOf<SyncListenerEvent>() private val events = mutableListOf<SyncListenerEvent>()
@ -20,9 +21,10 @@ class LoggingSyncListener : SyncListener {
fun assertSyncEvents(vararg events: SyncListenerEvent) { fun assertSyncEvents(vararg events: SyncListenerEvent) {
for (event in events) { for (event in events) {
assertEquals(event, getNextEvent()) assertThat(getNextEvent()).isEqualTo(event)
} }
assertNoMoreEventsLeft()
assertThat(this.events).isEmpty()
} }
fun getNextEvent(): SyncListenerEvent { fun getNextEvent(): SyncListenerEvent {
@ -30,10 +32,6 @@ class LoggingSyncListener : SyncListener {
return events.removeAt(0) return events.removeAt(0)
} }
private fun assertNoMoreEventsLeft() {
assertTrue("Expected no more events; but still have: $events", events.isEmpty())
}
override fun syncStarted(folderServerId: String) { override fun syncStarted(folderServerId: String) {
events.add(SyncListenerEvent.SyncStarted(folderServerId)) events.add(SyncListenerEvent.SyncStarted(folderServerId))
} }

View file

@ -8,4 +8,5 @@ dependencies {
implementation(libs.okio) implementation(libs.okio)
implementation(libs.junit) implementation(libs.junit)
implementation(libs.assertk)
} }

View file

@ -1,5 +1,7 @@
package app.k9mail.backend.testing package app.k9mail.backend.testing
import assertk.assertThat
import assertk.assertions.isEqualTo
import com.fsck.k9.backend.api.BackendFolder import com.fsck.k9.backend.api.BackendFolder
import com.fsck.k9.backend.api.BackendFolder.MoreMessages import com.fsck.k9.backend.api.BackendFolder.MoreMessages
import com.fsck.k9.mail.Flag import com.fsck.k9.mail.Flag
@ -11,7 +13,6 @@ import java.util.Date
import okio.Buffer import okio.Buffer
import okio.buffer import okio.buffer
import okio.source import okio.source
import org.junit.Assert.assertEquals
class InMemoryBackendFolder(override var name: String, var type: FolderType) : BackendFolder { class InMemoryBackendFolder(override var name: String, var type: FolderType) : BackendFolder {
val extraStrings: MutableMap<String, String> = mutableMapOf() val extraStrings: MutableMap<String, String> = mutableMapOf()
@ -29,12 +30,12 @@ class InMemoryBackendFolder(override var name: String, var type: FolderType) : B
assertMessageContents(messageServerId, resourceName) assertMessageContents(messageServerId, resourceName)
} }
val messageServerIds = messagePairs.map { it.first }.toSet() val messageServerIds = messagePairs.map { it.first }.toSet()
assertEquals(messageServerIds, messages.keys) assertThat(messages.keys).isEqualTo(messageServerIds)
} }
private fun assertMessageContents(messageServerId: String, resourceName: String) { private fun assertMessageContents(messageServerId: String, resourceName: String) {
val message = messages[messageServerId] ?: error("Message $messageServerId not found") val message = messages[messageServerId] ?: error("Message $messageServerId not found")
assertEquals(loadResource(resourceName), getMessageContents(message)) assertThat(getMessageContents(message)).isEqualTo(loadResource(resourceName))
} }
fun createMessages(vararg messagePairs: Pair<String, String>) { fun createMessages(vararg messagePairs: Pair<String, String>) {

View file

@ -1,17 +1,21 @@
package app.k9mail.core.common.mail package app.k9mail.core.common.mail
import assertk.assertThat import assertk.assertThat
import assertk.assertions.hasMessage
import assertk.assertions.isEqualTo import assertk.assertions.isEqualTo
import assertk.assertions.isFailure
import assertk.assertions.isInstanceOf
import kotlin.test.Test import kotlin.test.Test
import kotlin.test.assertFails
internal class EmailAddressTest { internal class EmailAddressTest {
@Test @Test
fun `should reject blank email address`() { fun `should reject blank email address`() {
assertFails("Email address must not be blank") { assertThat {
EmailAddress("") EmailAddress("")
} }.isFailure()
.isInstanceOf(IllegalArgumentException::class)
.hasMessage("Email address must not be blank")
} }
@Test @Test

View file

@ -1,8 +1,15 @@
package app.k9mail.autodiscovery.srvrecords package app.k9mail.autodiscovery.srvrecords
import app.k9mail.autodiscovery.api.DiscoveryResults import app.k9mail.autodiscovery.api.DiscoveryResults
import assertk.all
import assertk.assertThat
import assertk.assertions.containsExactly
import assertk.assertions.extracting
import assertk.assertions.hasSize
import assertk.assertions.isEqualTo
import assertk.assertions.isNotNull
import assertk.assertions.prop
import com.fsck.k9.mail.ConnectionSecurity import com.fsck.k9.mail.ConnectionSecurity
import org.junit.Assert.assertEquals
import org.junit.Test import org.junit.Test
import org.mockito.kotlin.doReturn import org.mockito.kotlin.doReturn
import org.mockito.kotlin.mock import org.mockito.kotlin.mock
@ -16,7 +23,7 @@ class SrvServiceDiscoveryTest {
val srvServiceDiscovery = SrvServiceDiscovery(srvResolver) val srvServiceDiscovery = SrvServiceDiscovery(srvResolver)
val result = srvServiceDiscovery.discover("test@example.com") val result = srvServiceDiscovery.discover("test@example.com")
assertEquals(DiscoveryResults(listOf(), listOf()), result) assertThat(result).isEqualTo(DiscoveryResults(incoming = listOf(), outgoing = listOf()))
} }
@Test @Test
@ -31,8 +38,10 @@ class SrvServiceDiscoveryTest {
val srvServiceDiscovery = SrvServiceDiscovery(srvResolver) val srvServiceDiscovery = SrvServiceDiscovery(srvResolver)
val result = srvServiceDiscovery.discover("test@example.com") val result = srvServiceDiscovery.discover("test@example.com")
assertEquals(2, result!!.incoming.size) assertThat(result).isNotNull().all {
assertEquals(0, result.outgoing.size) prop(DiscoveryResults::incoming).hasSize(2)
prop(DiscoveryResults::outgoing).hasSize(0)
}
} }
@Test @Test
@ -55,8 +64,10 @@ class SrvServiceDiscoveryTest {
val srvServiceDiscovery = SrvServiceDiscovery(srvResolver) val srvServiceDiscovery = SrvServiceDiscovery(srvResolver)
val result = srvServiceDiscovery.discover("test@example.com") val result = srvServiceDiscovery.discover("test@example.com")
assertEquals(0, result!!.incoming.size) assertThat(result).isNotNull().all {
assertEquals(2, result.outgoing.size) prop(DiscoveryResults::incoming).hasSize(0)
prop(DiscoveryResults::outgoing).hasSize(2)
}
} }
@Test @Test
@ -131,24 +142,20 @@ class SrvServiceDiscoveryTest {
val srvServiceDiscovery = SrvServiceDiscovery(srvResolver) val srvServiceDiscovery = SrvServiceDiscovery(srvResolver)
val result = srvServiceDiscovery.discover("test@example.com") val result = srvServiceDiscovery.discover("test@example.com")
assertEquals( assertThat(result).isNotNull().all {
listOf( prop(DiscoveryResults::outgoing).extracting { it.host }.containsExactly(
"smtp3.example.com", "smtp3.example.com",
"smtp1.example.com", "smtp1.example.com",
"smtp4.example.com", "smtp4.example.com",
"smtp2.example.com", "smtp2.example.com",
), )
result?.outgoing?.map { it.host }, prop(DiscoveryResults::incoming).extracting { it.host }.containsExactly(
)
assertEquals(
listOf(
"imaps1.example.com", "imaps1.example.com",
"imap1.example.com", "imap1.example.com",
"imaps2.example.com", "imaps2.example.com",
"imap2.example.com", "imap2.example.com",
), )
result?.incoming?.map { it.host }, }
)
} }
private fun newMailService( private fun newMailService(

View file

@ -1,8 +1,12 @@
package com.fsck.k9.mail.internet package com.fsck.k9.mail.internet
import assertk.assertThat
import assertk.assertions.hasMessage
import assertk.assertions.isEqualTo
import assertk.assertions.isFailure
import assertk.assertions.isInstanceOf
import com.fsck.k9.mail.Address import com.fsck.k9.mail.Address
import com.fsck.k9.mail.crlf import com.fsck.k9.mail.crlf
import org.junit.Assert.assertEquals
import org.junit.Test import org.junit.Test
class AddressHeaderBuilderTest { class AddressHeaderBuilderTest {
@ -13,7 +17,7 @@ class AddressHeaderBuilderTest {
val headerValue = AddressHeaderBuilder.createHeaderValue(addresses) val headerValue = AddressHeaderBuilder.createHeaderValue(addresses)
assertEquals("test@domain.example", headerValue) assertThat(headerValue).isEqualTo("test@domain.example")
} }
@Test @Test
@ -25,7 +29,7 @@ class AddressHeaderBuilderTest {
val headerValue = AddressHeaderBuilder.createHeaderValue(addresses) val headerValue = AddressHeaderBuilder.createHeaderValue(addresses)
assertEquals("one@domain.example, two@domain.example", headerValue) assertThat(headerValue).isEqualTo("one@domain.example, two@domain.example")
} }
@Test @Test
@ -40,19 +44,22 @@ class AddressHeaderBuilderTest {
val headerValue = AddressHeaderBuilder.createHeaderValue(addresses) val headerValue = AddressHeaderBuilder.createHeaderValue(addresses)
assertEquals( assertThat(headerValue).isEqualTo(
""" """
|Person One <one@domain.example>, |Person One <one@domain.example>,
| "Person \"Long Email Address\" Two" <two+because.i.can@this.is.quite.some.domain.example>, | "Person \"Long Email Address\" Two" <two+because.i.can@this.is.quite.some.domain.example>,
| Person Three <three@domain.example>, Person Four <four@domain.example>, | Person Three <three@domain.example>, Person Four <four@domain.example>,
| Person Five <five@domain.example> | Person Five <five@domain.example>
""".trimMargin().crlf(), """.trimMargin().crlf(),
headerValue,
) )
} }
@Test(expected = IllegalArgumentException::class) @Test
fun createHeaderValue_withoutAddresses_shouldThrow() { fun createHeaderValue_withoutAddresses_shouldThrow() {
AddressHeaderBuilder.createHeaderValue(emptyArray()) assertThat {
AddressHeaderBuilder.createHeaderValue(emptyArray())
}.isFailure()
.isInstanceOf(IllegalArgumentException::class)
.hasMessage("addresses must not be empty")
} }
} }

View file

@ -1,33 +1,36 @@
package com.fsck.k9.mail.internet package com.fsck.k9.mail.internet
import org.junit.Assert.assertEquals import assertk.assertThat
import assertk.assertions.isEqualTo
import org.junit.Test import org.junit.Test
class EncoderUtilTest { class EncoderUtilTest {
@Test @Test
fun singleNonAsciiCharacter() { fun singleNonAsciiCharacter() {
assertInputEncodesToExpected("123456789Ä", "=?UTF-8?Q?123456789=C3=84?=") val result = EncoderUtil.encodeEncodedWord("123456789Ä")
assertThat(result).isEqualTo("=?UTF-8?Q?123456789=C3=84?=")
} }
@Test @Test
fun onlyNonAsciiCharacters() { fun onlyNonAsciiCharacters() {
assertInputEncodesToExpected("ÄÖÜÄÖÜÄÖÜÄ", "=?UTF-8?B?w4TDlsOcw4TDlsOcw4TDlsOcw4Q=?=") val result = EncoderUtil.encodeEncodedWord("ÄÖÜÄÖÜÄÖÜÄ")
assertThat(result).isEqualTo("=?UTF-8?B?w4TDlsOcw4TDlsOcw4TDlsOcw4Q=?=")
} }
@Test @Test
fun nonAsciiCharactersThatNeedToBeEncodedAsMultipleEncodedWords() { fun nonAsciiCharactersThatNeedToBeEncodedAsMultipleEncodedWords() {
assertInputEncodesToExpected( val result = EncoderUtil.encodeEncodedWord(
"Re: \uD83D\uDC15\uD83D\uDC36\uD83D\uDC29\uD83D\uDC08\uD83D\uDC31\uD83D\uDC00\uD83D\uDC01\uD83D\uDC2D" + "Re: \uD83D\uDC15\uD83D\uDC36\uD83D\uDC29\uD83D\uDC08\uD83D\uDC31\uD83D\uDC00\uD83D\uDC01\uD83D\uDC2D" +
"\uD83D\uDC39\uD83D\uDC22\uD83D\uDC07\uD83D\uDC30\uD83D\uDC13\uD83D\uDC14\uD83D\uDC23\uD83D\uDC24" + "\uD83D\uDC39\uD83D\uDC22\uD83D\uDC07\uD83D\uDC30\uD83D\uDC13\uD83D\uDC14\uD83D\uDC23\uD83D\uDC24" +
"\uD83D\uDC25\uD83D\uDC26\uD83D\uDC0F\uD83D\uDC11\uD83D\uDC10", "\uD83D\uDC25\uD83D\uDC26\uD83D\uDC0F\uD83D\uDC11\uD83D\uDC10",
)
assertThat(result).isEqualTo(
"=?UTF-8?B?UmU6IPCfkJXwn5C28J+QqfCfkIjwn5Cx8J+QgPCfkIHwn5Ct8J+QuQ==?= " + "=?UTF-8?B?UmU6IPCfkJXwn5C28J+QqfCfkIjwn5Cx8J+QgPCfkIHwn5Ct8J+QuQ==?= " +
"=?UTF-8?B?8J+QovCfkIfwn5Cw8J+Qk/CfkJTwn5Cj?= " + "=?UTF-8?B?8J+QovCfkIfwn5Cw8J+Qk/CfkJTwn5Cj?= " +
"=?UTF-8?B?8J+QpPCfkKXwn5Cm8J+Qj/CfkJHwn5CQ?=", "=?UTF-8?B?8J+QpPCfkKXwn5Cm8J+Qj/CfkJHwn5CQ?=",
) )
} }
private fun assertInputEncodesToExpected(input: String, expected: String) {
val encodedText = EncoderUtil.encodeEncodedWord(input)
assertEquals(expected, encodedText)
}
} }

View file

@ -1,7 +1,8 @@
package com.fsck.k9.mail.internet package com.fsck.k9.mail.internet
import assertk.assertThat
import assertk.assertions.isEqualTo
import com.fsck.k9.mail.Address import com.fsck.k9.mail.Address
import org.junit.Assert.assertEquals
import org.junit.Test import org.junit.Test
class MessageIdGeneratorTest { class MessageIdGeneratorTest {
@ -20,7 +21,7 @@ class MessageIdGeneratorTest {
val result = messageIdGenerator.generateMessageId(message) val result = messageIdGenerator.generateMessageId(message)
assertEquals("<00000000-0000-4000-0000-000000000000@example.org>", result) assertThat(result).isEqualTo("<00000000-0000-4000-0000-000000000000@example.org>")
} }
@Test @Test
@ -31,7 +32,7 @@ class MessageIdGeneratorTest {
val result = messageIdGenerator.generateMessageId(message) val result = messageIdGenerator.generateMessageId(message)
assertEquals("<00000000-0000-4000-0000-000000000000@example.com>", result) assertThat(result).isEqualTo("<00000000-0000-4000-0000-000000000000@example.com>")
} }
@Test @Test
@ -40,6 +41,6 @@ class MessageIdGeneratorTest {
val result = messageIdGenerator.generateMessageId(message) val result = messageIdGenerator.generateMessageId(message)
assertEquals("<00000000-0000-4000-0000-000000000000@fallback.k9mail.app>", result) assertThat(result).isEqualTo("<00000000-0000-4000-0000-000000000000@fallback.k9mail.app>")
} }
} }

View file

@ -1,6 +1,9 @@
package com.fsck.k9.mail.internet package com.fsck.k9.mail.internet
import org.junit.Assert.fail import assertk.assertThat
import assertk.assertions.isFailure
import assertk.assertions.isInstanceOf
import assertk.assertions.isSuccess
import org.junit.Test import org.junit.Test
class MimeHeaderCheckerTest { class MimeHeaderCheckerTest {
@ -196,15 +199,18 @@ class MimeHeaderCheckerTest {
private fun assertValidHeader(header: String) { private fun assertValidHeader(header: String) {
val (name, value) = header.split(": ", limit = 2) val (name, value) = header.split(": ", limit = 2)
MimeHeaderChecker.checkHeader(name, value)
assertThat {
MimeHeaderChecker.checkHeader(name, value)
}.isSuccess()
} }
private fun assertInvalidHeader(header: String) { private fun assertInvalidHeader(header: String) {
val (name, value) = header.split(": ", limit = 2) val (name, value) = header.split(": ", limit = 2)
try {
assertThat {
MimeHeaderChecker.checkHeader(name, value) MimeHeaderChecker.checkHeader(name, value)
fail("Expected exception") }.isFailure()
} catch (expected: MimeHeaderParserException) { .isInstanceOf(MimeHeaderParserException::class)
}
} }
} }

View file

@ -4,11 +4,17 @@ import assertk.all
import assertk.assertThat import assertk.assertThat
import assertk.assertions.cause import assertk.assertions.cause
import assertk.assertions.containsExactly import assertk.assertions.containsExactly
import assertk.assertions.containsOnly
import assertk.assertions.extracting
import assertk.assertions.hasMessage import assertk.assertions.hasMessage
import assertk.assertions.isEqualTo import assertk.assertions.isEqualTo
import assertk.assertions.isFailure import assertk.assertions.isFailure
import assertk.assertions.isFalse
import assertk.assertions.isInstanceOf import assertk.assertions.isInstanceOf
import assertk.assertions.isNotNull import assertk.assertions.isNotNull
import assertk.assertions.isNull
import assertk.assertions.isTrue
import assertk.fail
import com.fsck.k9.mail.Body import com.fsck.k9.mail.Body
import com.fsck.k9.mail.DefaultBodyFactory import com.fsck.k9.mail.DefaultBodyFactory
import com.fsck.k9.mail.FetchProfile import com.fsck.k9.mail.FetchProfile
@ -27,12 +33,6 @@ import java.util.TimeZone
import okio.Buffer import okio.Buffer
import org.apache.james.mime4j.util.MimeUtil import org.apache.james.mime4j.util.MimeUtil
import org.junit.After import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Assert.fail
import org.junit.Before import org.junit.Before
import org.junit.Test import org.junit.Test
import org.mockito.ArgumentMatchers.anySet import org.mockito.ArgumentMatchers.anySet
@ -79,7 +79,7 @@ class RealImapFolderTest {
imapFolder.open(OpenMode.READ_WRITE) imapFolder.open(OpenMode.READ_WRITE)
assertTrue(imapFolder.isOpen) assertThat(imapFolder.isOpen).isTrue()
} }
@Test @Test
@ -89,7 +89,7 @@ class RealImapFolderTest {
imapFolder.open(OpenMode.READ_ONLY) imapFolder.open(OpenMode.READ_ONLY)
assertTrue(imapFolder.isOpen) assertThat(imapFolder.isOpen).isTrue()
} }
@Test @Test
@ -99,7 +99,7 @@ class RealImapFolderTest {
imapFolder.open(OpenMode.READ_WRITE) imapFolder.open(OpenMode.READ_WRITE)
assertEquals(23, imapFolder.messageCount) assertThat(imapFolder.messageCount).isEqualTo(23)
} }
@Test @Test
@ -109,7 +109,7 @@ class RealImapFolderTest {
imapFolder.open(OpenMode.READ_WRITE) imapFolder.open(OpenMode.READ_WRITE)
assertEquals(OpenMode.READ_WRITE, imapFolder.mode) assertThat(imapFolder.mode).isEqualTo(OpenMode.READ_WRITE)
} }
@Test @Test
@ -119,7 +119,7 @@ class RealImapFolderTest {
imapFolder.open(OpenMode.READ_ONLY) imapFolder.open(OpenMode.READ_ONLY)
assertEquals(OpenMode.READ_ONLY, imapFolder.mode) assertThat(imapFolder.mode).isEqualTo(OpenMode.READ_ONLY)
} }
@Test @Test
@ -129,7 +129,7 @@ class RealImapFolderTest {
imapFolder.open(OpenMode.READ_WRITE) imapFolder.open(OpenMode.READ_WRITE)
assertTrue(imapFolder.exists()) assertThat(imapFolder.exists()).isTrue()
verify(imapConnection, times(1)).executeSimpleCommand(anyString()) verify(imapConnection, times(1)).executeSimpleCommand(anyString())
} }
@ -202,7 +202,7 @@ class RealImapFolderTest {
imapFolder.close() imapFolder.close()
assertFalse(imapFolder.isOpen) assertThat(imapFolder.isOpen).isFalse()
} }
@Test @Test
@ -220,7 +220,7 @@ class RealImapFolderTest {
val folderExists = imapFolder.exists() val folderExists = imapFolder.exists()
assertTrue(folderExists) assertThat(folderExists).isTrue()
} }
@Test @Test
@ -231,7 +231,7 @@ class RealImapFolderTest {
val folderExists = imapFolder.exists() val folderExists = imapFolder.exists()
assertFalse(folderExists) assertThat(folderExists).isFalse()
} }
@Test @Test
@ -249,7 +249,7 @@ class RealImapFolderTest {
val success = imapFolder.create() val success = imapFolder.create()
assertTrue(success) assertThat(success).isTrue()
} }
@Test @Test
@ -259,7 +259,7 @@ class RealImapFolderTest {
val success = imapFolder.create() val success = imapFolder.create()
assertFalse(success) assertThat(success).isFalse()
} }
@Test @Test
@ -270,7 +270,7 @@ class RealImapFolderTest {
val uidMapping = sourceFolder.copyMessages(messages, destinationFolder) val uidMapping = sourceFolder.copyMessages(messages, destinationFolder)
assertNull(uidMapping) assertThat(uidMapping).isNull()
} }
@Test @Test
@ -297,8 +297,7 @@ class RealImapFolderTest {
val uidMapping = sourceFolder.copyMessages(messages, destinationFolder) val uidMapping = sourceFolder.copyMessages(messages, destinationFolder)
assertNotNull(uidMapping) assertThat(uidMapping).isNotNull().containsOnly("1" to "101")
assertEquals("101", uidMapping!!["1"])
} }
@Test @Test
@ -312,8 +311,7 @@ class RealImapFolderTest {
val uidMapping = sourceFolder.moveMessages(messages, destinationFolder) val uidMapping = sourceFolder.moveMessages(messages, destinationFolder)
assertNotNull(uidMapping) assertThat(uidMapping).isNotNull().containsOnly("1" to "101")
assertEquals("101", uidMapping!!["1"])
} }
@Test @Test
@ -337,7 +335,7 @@ class RealImapFolderTest {
val uidMapping = sourceFolder.moveMessages(messages, destinationFolder) val uidMapping = sourceFolder.moveMessages(messages, destinationFolder)
assertNull(uidMapping) assertThat(uidMapping).isNull()
} }
@Test @Test
@ -375,7 +373,7 @@ class RealImapFolderTest {
val unreadMessageCount = folder.unreadMessageCount val unreadMessageCount = folder.unreadMessageCount
assertEquals(3, unreadMessageCount) assertThat(unreadMessageCount).isEqualTo(3)
} }
@Test @Test
@ -402,7 +400,7 @@ class RealImapFolderTest {
val flaggedMessageCount = folder.flaggedMessageCount val flaggedMessageCount = folder.flaggedMessageCount
assertEquals(4, flaggedMessageCount) assertThat(flaggedMessageCount).isEqualTo(4)
} }
@Test @Test
@ -414,7 +412,7 @@ class RealImapFolderTest {
val highestUid = folder.highestUid val highestUid = folder.highestUid
assertEquals(42L, highestUid) assertThat(highestUid).isEqualTo(42L)
} }
@Test @Test
@ -426,7 +424,7 @@ class RealImapFolderTest {
val highestUid = folder.highestUid val highestUid = folder.highestUid
assertEquals(-1L, highestUid) assertThat(highestUid).isEqualTo(-1L)
} }
@Test @Test
@ -452,8 +450,8 @@ class RealImapFolderTest {
val messages = folder.getMessages(1, 10, null, null) val messages = folder.getMessages(1, 10, null, null)
assertNotNull(messages) assertThat(messages).isNotNull()
assertEquals(setOf("3", "5", "6"), extractMessageUids(messages)) .extracting { it.uid }.containsOnly("3", "5", "6")
} }
@Test @Test
@ -466,8 +464,8 @@ class RealImapFolderTest {
val messages = folder.getMessages(1, 10, Date(1454719826000L), null) val messages = folder.getMessages(1, 10, Date(1454719826000L), null)
assertNotNull(messages) assertThat(messages).isNotNull()
assertEquals(setOf("18", "47"), extractMessageUids(messages)) .extracting { it.uid }.containsOnly("18", "47")
} }
@Test @Test
@ -548,8 +546,8 @@ class RealImapFolderTest {
val messages = folder.getMessages(setOf(1L, 2L, 5L), false, null) val messages = folder.getMessages(setOf(1L, 2L, 5L), false, null)
assertNotNull(messages) assertThat(messages).isNotNull()
assertEquals(setOf("17", "18", "49"), extractMessageUids(messages)) .extracting { it.uid }.containsOnly("17", "18", "49")
} }
@Test @Test
@ -586,8 +584,8 @@ class RealImapFolderTest {
val messages = folder.getMessagesFromUids(listOf("11", "22", "25")) val messages = folder.getMessagesFromUids(listOf("11", "22", "25"))
assertNotNull(messages) assertThat(messages).isNotNull()
assertEquals(setOf("11", "22", "25"), extractMessageUids(messages)) .extracting { it.uid }.containsOnly("11", "22", "25")
} }
@Test @Test
@ -610,7 +608,7 @@ class RealImapFolderTest {
val areMoreMessagesAvailable = folder.areMoreMessagesAvailable(10, null) val areMoreMessagesAvailable = folder.areMoreMessagesAvailable(10, null)
assertTrue(areMoreMessagesAvailable) assertThat(areMoreMessagesAvailable).isTrue()
} }
@Test @Test
@ -622,7 +620,7 @@ class RealImapFolderTest {
val areMoreMessagesAvailable = folder.areMoreMessagesAvailable(600, null) val areMoreMessagesAvailable = folder.areMoreMessagesAvailable(600, null)
assertFalse(areMoreMessagesAvailable) assertThat(areMoreMessagesAvailable).isFalse()
} }
@Test @Test
@ -633,7 +631,7 @@ class RealImapFolderTest {
val areMoreMessagesAvailable = folder.areMoreMessagesAvailable(1, null) val areMoreMessagesAvailable = folder.areMoreMessagesAvailable(1, null)
assertFalse(areMoreMessagesAvailable) assertThat(areMoreMessagesAvailable).isFalse()
// SELECT during OPEN and no more // SELECT during OPEN and no more
verify(imapConnection, times(1)).executeSimpleCommand(anyString()) verify(imapConnection, times(1)).executeSimpleCommand(anyString())
} }
@ -922,7 +920,7 @@ class RealImapFolderTest {
val body = bodyArgumentCaptor.firstValue val body = bodyArgumentCaptor.firstValue
val buffer = Buffer() val buffer = Buffer()
body.writeTo(buffer.outputStream()) body.writeTo(buffer.outputStream())
assertEquals("text", buffer.readUtf8()) assertThat(buffer.readUtf8()).isEqualTo("text")
} }
@Test @Test
@ -993,7 +991,7 @@ class RealImapFolderTest {
val uid = folder.getUidFromMessageId("<00000000.0000000@example.org>") val uid = folder.getUidFromMessageId("<00000000.0000000@example.org>")
assertEquals("23", uid) assertThat(uid).isEqualTo("23")
} }
@Test @Test
@ -1066,7 +1064,7 @@ class RealImapFolderTest {
val message = folder.getMessage("uid") val message = folder.getMessage("uid")
assertEquals("uid", message.uid) assertThat(message.uid).isEqualTo("uid")
} }
@Suppress("SameParameterValue") @Suppress("SameParameterValue")
@ -1103,8 +1101,6 @@ class RealImapFolderTest {
return response return response
} }
private fun extractMessageUids(messages: List<ImapMessage>) = messages.map { it.uid }.toSet()
private fun createFolder(folderName: String): RealImapFolder { private fun createFolder(folderName: String): RealImapFolder {
return RealImapFolder(internalImapStore, testConnectionManager, folderName, FolderNameCodec()) return RealImapFolder(internalImapStore, testConnectionManager, folderName, FolderNameCodec())
} }

View file

@ -1,8 +1,10 @@
package com.fsck.k9.mail.store.imap package com.fsck.k9.mail.store.imap
import org.junit.Assert.assertEquals import assertk.assertThat
import org.junit.Assert.assertNotNull import assertk.assertions.isEqualTo
import org.junit.Assert.assertNull import assertk.assertions.isNotNull
import assertk.assertions.isNull
import assertk.assertions.prop
import org.junit.Test import org.junit.Test
class UidValidityResponseTest { class UidValidityResponseTest {
@ -12,8 +14,8 @@ class UidValidityResponseTest {
val result = UidValidityResponse.parse(response) val result = UidValidityResponse.parse(response)
assertNotNull(result) assertThat(result).isNotNull()
assertEquals(23, result!!.uidValidity) .prop(UidValidityResponse::uidValidity).isEqualTo(23)
} }
@Test @Test
@ -22,8 +24,8 @@ class UidValidityResponseTest {
val result = UidValidityResponse.parse(response) val result = UidValidityResponse.parse(response)
assertNotNull(result) assertThat(result).isNotNull()
assertEquals(42, result!!.uidValidity) .prop(UidValidityResponse::uidValidity).isEqualTo(42)
} }
@Test @Test
@ -58,6 +60,7 @@ class UidValidityResponseTest {
private fun assertNotValid(response: String) { private fun assertNotValid(response: String) {
val result = UidValidityResponse.parse(ImapResponseHelper.createImapResponse(response)) val result = UidValidityResponse.parse(ImapResponseHelper.createImapResponse(response))
assertNull(result)
assertThat(result).isNull()
} }
} }

View file

@ -13,4 +13,5 @@ dependencies {
api(libs.okio) api(libs.okio)
api(libs.junit) api(libs.junit)
api(libs.assertk)
} }

View file

@ -0,0 +1,41 @@
@file:Suppress("TooManyFunctions")
package com.fsck.k9.mail.assertk
import assertk.Assert
import assertk.assertions.prop
import com.fsck.k9.mail.Body
import com.fsck.k9.mail.BodyPart
import com.fsck.k9.mail.Part
import com.fsck.k9.mail.internet.MimeMultipart
import com.fsck.k9.mail.internet.MimeParameterDecoder
import com.fsck.k9.mail.internet.MimeUtility
import com.fsck.k9.mail.internet.MimeValue
import com.fsck.k9.mail.internet.RawDataBody
import com.fsck.k9.mail.internet.TextBody
fun Assert<Part>.body() = prop(Part::getBody)
@JvmName("textBodyEncoding")
fun Assert<TextBody>.contentTransferEncoding() = prop(TextBody::getEncoding)
@JvmName("rawDataBodyEncoding")
fun Assert<RawDataBody>.contentTransferEncoding() = prop(RawDataBody::getEncoding)
fun Assert<Body>.asBytes() = transform { it.inputStream.readBytes() }
fun Assert<Body>.asText() = transform {
String(MimeUtility.decodeBody(it).readBytes())
}
fun Assert<MimeMultipart>.bodyParts() = transform { it.bodyParts }
fun Assert<MimeMultipart>.bodyPart(index: Int): Assert<BodyPart> = transform { it.getBodyPart(index) }
fun Assert<Part>.mimeType() = transform { it.mimeType }
fun Assert<Part>.contentType() = transform { MimeParameterDecoder.decode(it.contentType) }
fun Assert<MimeValue>.value() = transform { it.value }
fun Assert<MimeValue>.parameter(name: String): Assert<String?> = transform { it.parameters[name] }