67 lines · 2.9 KB · KotlinRaw
package com.cottondb.messages.chatimport android.app.Applicationimport android.graphics.Bitmapimport android.graphics.BitmapFactoryimport android.graphics.Canvasimport android.graphics.LinearGradientimport android.graphics.Paintimport android.graphics.Shaderimport android.util.Base64import org.junit.Assert.assertEqualsimport org.junit.Assert.assertNotNullimport org.junit.Assert.assertNullimport org.junit.Assert.assertTrueimport org.junit.Ruleimport org.junit.Testimport org.junit.rules.TemporaryFolderimport org.junit.runner.RunWithimport org.robolectric.RobolectricTestRunnerimport org.robolectric.annotation.Configimport org.robolectric.annotation.GraphicsMode/** * A PICTURE'S PREVIEW as the sending phone makes it (CONTRACT.md "Pictures at once", 23 Nov 2026: pictures took 1 to * 2 s to appear, blank boxes meanwhile, because a Cotton picture carried no preview): at most 32 px a side, a JPEG of * at most 2,000 bytes, base64 with no line breaks, which the core takes as `payload::preview_of` does. */@RunWith(RobolectricTestRunner::class)@GraphicsMode(GraphicsMode.Mode.NATIVE)@Config(sdk = [35], application = Application::class)class PicturePreviewTest { @get:Rule val tmp = TemporaryFolder() /** An invented photograph the size of the walk's (2016 x 1512), a busy wash so it does not compress to nothing. */ private fun photo(w: Int = 2016, h: Int = 1512): java.io.File { val b = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888) Canvas(b).drawRect(0f, 0f, w.toFloat(), h.toFloat(), Paint().apply { shader = LinearGradient(0f, 0f, w.toFloat(), h.toFloat(), 0xFF3F7A9C.toInt(), 0xFFA6D80F.toInt(), Shader.TileMode.MIRROR) }) return tmp.newFile("invented.jpg").apply { outputStream().use { b.compress(Bitmap.CompressFormat.JPEG, 92, it) } } } @Test fun a_photo_gives_a_small_jpeg_at_its_own_shape() { val preview = PicturePreview.of(photo()) assertNotNull(preview) assertTrue("no line breaks", '\n' !in preview!!) val bytes = Base64.decode(preview, Base64.NO_WRAP) assertTrue("at most 2,000 bytes, was ${bytes.size}", bytes.size <= PicturePreview.MAX_BYTES) assertTrue("a JPEG", bytes[0] == 0xFF.toByte() && bytes[1] == 0xD8.toByte()) assertTrue("within the core's 2,800 characters", preview.length <= 2_800) val drawn = BitmapFactory.decodeByteArray(bytes, 0, bytes.size) assertEquals(32, drawn.width) assertEquals(24, drawn.height) } @Test fun a_tall_photo_keeps_its_shape() { val drawn = PicturePreview.bitmap(PicturePreview.of(photo(900, 1600))!!)!! assertEquals(32, drawn.height) assertEquals(18, drawn.width) } @Test fun what_is_not_a_picture_gives_none() { assertNull(PicturePreview.of(tmp.newFile("notes.txt").apply { writeText("invented words") })) assertNull(PicturePreview.of(java.io.File(tmp.root, "missing.jpg"))) }}