-
Notifications
You must be signed in to change notification settings - Fork 0
Add test rule to compare screenshots #1
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -147,7 +147,8 @@ class LoggerazziPlugin @Inject constructor( | |
| file.delete() | ||
| } | ||
| } | ||
| lastFile?.renameTo(File(this, "$key.txt")) | ||
|
|
||
| lastFile?.renameTo(File(this, key)) | ||
|
Comment on lines
-150
to
+151
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I'm including the extension in the original file so no need to include it here |
||
| } | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -36,10 +36,18 @@ android { | |
| } | ||
| } | ||
|
|
||
| kotlin { | ||
| explicitApi() | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Added to force the classes to define their visibility. |
||
| } | ||
|
|
||
| dependencies { | ||
| api(libs.differ) | ||
|
|
||
| implementation(libs.core.ktx) | ||
| implementation(libs.junit) | ||
| implementation(libs.androidx.test.monitor) | ||
| implementation(libs.androidx.test.runner) | ||
| implementation(libs.androidx.ui.test.junit4.android) | ||
| } | ||
|
|
||
| apply("${rootProject.projectDir}/mavencentral.gradle") | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,18 @@ | ||
| package com.telefonica.loggerazzi | ||
|
|
||
| import android.graphics.Bitmap | ||
| import com.dropbox.differ.Color | ||
| import com.dropbox.differ.Image | ||
| import androidx.core.graphics.get | ||
|
|
||
| internal class BitmapImage(private val src: Bitmap) : Image { | ||
| override val width: Int get() = src.width | ||
| override val height: Int get() = src.height | ||
| override fun getPixel(x: Int, y: Int): Color { | ||
| try { | ||
| return Color(src[x, y]) | ||
| } catch (e: IllegalArgumentException) { | ||
| throw IllegalArgumentException("Can't request pixel {x = $x, y = $y} from image {width = $width, height = $height}", e) | ||
| } | ||
| } | ||
| } |
This file was deleted.
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,10 @@ | ||
| package com.telefonica.loggerazzi | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I've created a new annotation to ignore the screenshots checks and rename the logs one |
||
|
|
||
|
|
||
| @Retention(AnnotationRetention.RUNTIME) | ||
| @Target(AnnotationTarget.FUNCTION) | ||
| public annotation class IgnoreLogs | ||
|
|
||
| @Retention(AnnotationRetention.RUNTIME) | ||
| @Target(AnnotationTarget.FUNCTION) | ||
| public annotation class IgnoreScreenshots | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,6 +1,6 @@ | ||
| package com.telefonica.loggerazzi | ||
|
|
||
| interface LogsRecorder<LogType> { | ||
| fun clear() | ||
| fun getRecordedLogs(): List<LogType> | ||
| public interface LogsRecorder<LogType> { | ||
| public fun clear() | ||
| public fun getRecordedLogs(): List<LogType> | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,33 @@ | ||
| package com.telefonica.loggerazzi | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Copy from dropshots, it allows you to customize the threshold |
||
|
|
||
| import com.dropbox.differ.ImageComparator | ||
| import kotlin.math.roundToInt | ||
|
|
||
| /** | ||
| * A function used to validate the comparison result. | ||
| */ | ||
| public typealias ResultValidator = (result: ImageComparator.ComparisonResult) -> Boolean | ||
|
|
||
| /** | ||
| * Fails validation if there are more than `count` pixel differences. | ||
| */ | ||
| @Suppress("FunctionName") | ||
| public fun CountValidator(count: Int) : ResultValidator { | ||
| require(count >= 0) { "count must be greater than or equal to 0." } | ||
| return { result -> | ||
| result.pixelDifferences <= count | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Fails validation if more than `threshold` percent of pixels are different. | ||
| */ | ||
| @Suppress("FunctionName") | ||
| public fun ThresholdValidator(threshold: Float) : ResultValidator { | ||
| require(threshold in 0f..1f) { "threshold must be in range 0.0..1.0"} | ||
| return { result -> | ||
| result.pixelDifferences <= (result.pixelCount * threshold).roundToInt() | ||
| } | ||
| } | ||
|
|
||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,149 @@ | ||
| package com.telefonica.loggerazzi | ||
|
|
||
| import android.app.Activity | ||
| import android.graphics.Bitmap | ||
| import android.graphics.BitmapFactory | ||
| import android.os.Build | ||
| import android.os.Environment | ||
| import androidx.annotation.RequiresApi | ||
| import androidx.compose.ui.graphics.asAndroidBitmap | ||
| import androidx.compose.ui.test.captureToImage | ||
| import androidx.compose.ui.test.junit4.ComposeTestRule | ||
| import androidx.compose.ui.test.onRoot | ||
| import androidx.test.platform.app.InstrumentationRegistry | ||
| import androidx.test.runner.screenshot.Screenshot | ||
| import com.dropbox.differ.ImageComparator | ||
| import com.dropbox.differ.Mask | ||
| import com.dropbox.differ.SimpleImageComparator | ||
| import org.junit.rules.TestRule | ||
| import org.junit.runner.Description | ||
| import org.junit.runners.model.Statement | ||
| import java.io.File | ||
| import java.io.FileNotFoundException | ||
|
|
||
| public class ScreenshotsRule( | ||
| private val imageComparator: ImageComparator = SimpleImageComparator(maxDistance = 0.004f), | ||
| private val resultValidator: ResultValidator = CountValidator(0), | ||
| ) : TestRule { | ||
|
|
||
| private var className: String = "" | ||
| private var testName: String = "" | ||
| private var isTestIgnored: Boolean = false | ||
| private val writeDiffImage = WriteDiffImage() | ||
|
|
||
| private val context = InstrumentationRegistry.getInstrumentation().context | ||
| private val downloadDir = File( | ||
| Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).absolutePath | ||
| ) | ||
| private val loggerazziDir = File(downloadDir, "loggerazzi-logs/${context.packageName}") | ||
| private val failuresDir = File(loggerazziDir, "failures") | ||
| private val recordedDir = File(loggerazziDir, "recorded") | ||
|
Comment on lines
+38
to
+40
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I though we was going to stop using loggerazzi. I'm seeing it in many places (package, class names, etc), is there a renaming task in the roadmap or aren't we going to stop using that name?
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Yes, the rename is pending, I will do it after this |
||
|
|
||
| override fun apply(base: Statement, description: Description): Statement { | ||
| className = description.className | ||
| testName = description.methodName | ||
| isTestIgnored = description.getAnnotation(IgnoreScreenshots::class.java) != null | ||
|
|
||
| if (!failuresDir.exists()) { | ||
| failuresDir.mkdirs() | ||
| } | ||
| if (!recordedDir.exists()) { | ||
| recordedDir.mkdirs() | ||
| } | ||
| return base | ||
| } | ||
|
|
||
| @RequiresApi(Build.VERSION_CODES.O) | ||
| public fun compareScreenshot( | ||
| rule: ComposeTestRule, | ||
| name: String?, | ||
| ) { | ||
| rule.waitForIdle() | ||
| val bitmap = rule.onRoot().captureToImage().asAndroidBitmap() | ||
| compareScreenshot(bitmap, name) | ||
| } | ||
|
|
||
| public fun compareScreenshot( | ||
| activity: Activity, | ||
| name: String?, | ||
| ) { | ||
| val bitmap = Screenshot.capture(activity).bitmap | ||
| compareScreenshot(bitmap, name) | ||
| } | ||
|
|
||
| @Suppress("MemberVisibilityCanBePrivate") | ||
| public fun compareScreenshot( | ||
| bitmap: Bitmap, | ||
| name: String? | ||
| ) { | ||
|
Comment on lines
+56
to
+78
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I've copied the same API that Shot has |
||
| val resourceName = "${className}_${name ?: testName}.png" | ||
| val fileName = "$resourceName.${System.nanoTime()}" | ||
| saveScreenshot(fileName, bitmap) | ||
|
|
||
| if (InstrumentationRegistry.getArguments().getString("record") != "true" && !isTestIgnored) { | ||
| val goldenBitmap = getGoldenBitmap(resourceName) | ||
| compareImagesSize(bitmap, goldenBitmap, fileName, name) | ||
| compareImages(bitmap, goldenBitmap, fileName, resourceName) | ||
| } | ||
|
Comment on lines
+83
to
+87
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. If we are not recording the baseline or this test is ignored, we compare the screenshot. |
||
| } | ||
|
|
||
| private fun saveScreenshot(fileName: String, bitmap: Bitmap) { | ||
| val testFile = File(recordedDir, fileName) | ||
| testFile.createNewFile() | ||
| testFile.outputStream().use { | ||
| bitmap.compress(Bitmap.CompressFormat.PNG, 100, it) | ||
| } | ||
| } | ||
|
|
||
| private fun getGoldenBitmap(resourceName: String): Bitmap { | ||
| val goldenBitmap = try { | ||
| context.assets.open("loggerazzi-golden-files/$resourceName").use { | ||
| BitmapFactory.decodeStream(it) | ||
| } | ||
| } catch (e: FileNotFoundException) { | ||
| throw IllegalStateException( | ||
| "Failed to find golden image named $resourceName. If this is a new test, you may need to record screenshots", | ||
| e | ||
| ) | ||
| } | ||
| return goldenBitmap | ||
| } | ||
|
|
||
| private fun compareImagesSize( | ||
| bitmap: Bitmap, | ||
| goldenBitmap: Bitmap, | ||
| fileName: String, | ||
| name: String? | ||
| ) { | ||
| if (bitmap.width != goldenBitmap.width || bitmap.height != goldenBitmap.height) { | ||
| writeDiffImage(failuresDir, fileName, bitmap, goldenBitmap, null) | ||
| throw AssertionError( | ||
| "$name: Test image (w=${bitmap.width}, h=${bitmap.height}) differs in size" + | ||
| " from reference image (w=${goldenBitmap.width}, h=${goldenBitmap.height}).\n", | ||
| ) | ||
| } | ||
| } | ||
|
|
||
| private fun compareImages( | ||
| bitmap: Bitmap, | ||
| goldenBitmap: Bitmap, | ||
| fileName: String, | ||
| resourceName: String | ||
| ) { | ||
| val mask = Mask(bitmap.width, bitmap.height) | ||
| val result = try { | ||
| imageComparator.compare(BitmapImage(goldenBitmap), BitmapImage(bitmap), mask) | ||
| } catch (e: IllegalArgumentException) { | ||
| writeDiffImage(failuresDir, fileName, bitmap, goldenBitmap, mask) | ||
| throw AssertionError("Failed to compare images", e) | ||
| } | ||
|
|
||
| if (!resultValidator(result)) { | ||
| writeDiffImage(failuresDir, fileName, bitmap, goldenBitmap, mask) | ||
| throw AssertionError( | ||
| "\"$resourceName\" failed to match reference image. ${result.pixelDifferences} pixels differ " + | ||
| "(${(result.pixelDifferences / result.pixelCount.toFloat()) * 100} %)" | ||
| ) | ||
| } | ||
| } | ||
| } | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
New test to check a basic screenshot