You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
iceraven-browser/app/src/androidTest/java/org/mozilla/fenix/perf/StartupExcessiveResourceUse...

152 lines
6.8 KiB
Kotlin

/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.fenix.perf
import android.util.Log
import android.view.View
import android.view.ViewGroup
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.view.children
import androidx.recyclerview.widget.RecyclerView
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.uiautomator.UiDevice
import kotlinx.android.synthetic.main.activity_home.*
import org.junit.Assert.assertEquals
import org.junit.Rule
import org.junit.Test
import org.mozilla.fenix.ext.components
import org.mozilla.fenix.helpers.HomeActivityTestRule
// BEFORE INCREASING THESE VALUES, PLEASE CONSULT WITH THE PERF TEAM.
private const val EXPECTED_SUPPRESSION_COUNT = 11
16900 make navgraph inflation asynchronous (#18889) * For #16900: implement async navgraph inflation For #16900: removed nav graph from xml For #16900: inflate navGraph programatically For #16900: Made NavGraph inflation asynchronous For #16900: Changed to block with runBlocking For #16900: Refactored blocking call into a function For 16900: NavGraph inflation is now async We now attach the nav graph (or check if its attached) on every nav call ( an extension function for NavController). This is done by checking the value of the job stored in PerfNavController.map which keeps track of the job with the NavController as a Key. If the job hasn't been completed, it will block the main thread until the job is done. The job itself is responsible for attaching the navgraph to the navcontroller (and the inflation of the latter too) For 16900: rebased upstream master For 16900: Rebase on master For #16900: Fixed Async Navgraph navigation per review comments. 1)The Asynchronous method is now found in NavGraphProvider.kt. It creates a job on the IO dispatcher 2)The Job is tracked through a WeakHashMap from Controller --> NavGraph 3)The Coroutine scope doesn't use MainScope() anymore 4)The Coroutine is cancelled if the Activity is destroyed 5)The tests mockk the blockForNavGraphInflation method through the FenixReoboelectricTestApplication instead of calling the mock every setup() For #16900: inflateNavGraphAsync now takes navController For #16900: Pass lifecycleScope to NavGraphProvider For #16900: removed unused mock For #16900: Added linter rules for navigate calls We need linting rules to make sure no one calls the NavController.navigate() methods For #16900: Added TestRule to help abstract the mocks in the code For 16900: Fix linting problems For #16900: Cleaned duplicated code in tests For #16900: cleaned up NavGraphTestRule for finished test For #16900: had to revert an accidentally edited file For #16900: rebased master * For #16900: Review nits for async navgraph This is composed of squash commits, the original messages can be found below: -> DisableNavGraphProviderAssertionRule + kdoc. Use test rule in RobolectricApplication. Fix failing CrashReporterControllerTest Fix blame by -> navigate in tests. This commit was generated by the following commands only: ``` find app/src/test -type f -exec sed -i '' "/import org.mozilla.fenix.ext.navigateBlockingForAsyncNavGraph/d" {} \; find app/src/test -type f -exec sed -i "" "s/navigateBlockingForAsyncNavGraph/navigate/g" {} \; git checkout app/src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker ``` Fix various blame This is expected to be squashed into the first commit so, if so, it'd fix the blame. Move test rule to helpers pkg. add missing license header Add import change I missed fix unused imports Replace robolectricTestrunner with test rule. Improve navGraphProvider docs Remove unnecessary rule as defined by robolectric. add clarifying comment to robolectric remove unnecessary space * For #16900: nit fixes for MozillaNavigateCheck and lint fixes 3 squash commits: *Changed violation message and fixed the lint rule for MozillaNavigateCheck *Added suppression to NavController.kt *Fixed detekt violations * For 16900: Fixed failing tests Co-authored-by: Michael Comella <michael.l.comella@gmail.com>
3 years ago
private const val EXPECTED_RUNBLOCKING_COUNT = 3
private const val EXPECTED_COMPONENT_INIT_COUNT = 42
private const val EXPECTED_VIEW_HIERARCHY_DEPTH = 12
private const val EXPECTED_RECYCLER_VIEW_CONSTRAINT_LAYOUT_CHILDREN = 4
16373 Count the # of inflations done on startup (#16778) * For #16373: Added performance Inflater to counter # of inflations This class is quite straight forward. The only thing that I have to point out is the onCreateView method. It usually calls its super if you don't override it. The problem with that is that the super.onCreateView actually uses android.view. as a prefix for the XML element it tries to inflate. So if we have an element that isn't part of that package, it'll crash. As I said in the code, a good example is ImageButton. Calling android.view.ImageButton will make the app crash. The method is implemented the same way that PhoneLayoutInflater does (Another example is the AsyncLayoutInflater) * For #16373: Added test for PerformanceInflater This test got quite awkward / complicated fast. I wanted to test the to make sure we don't break *any* of our layouts and to do so, I decided to just retrieve all our XML in our /res/layout folder. However, this gets quite a bit outside of a unit test scope. The point was to get every layouts and get their LayoutID through the resources using the testContext we have. It gets even weirder, since some of the XML tags have special implementation in android. One of them is the <fragment> tag. That tag actually is inflated by the OS using the Factory2 that the Activity.java implements. In order to get around the fragment issue, we just return a basic FrameLayout since the system LayoutInflater doesn't deal won't ever get a <fragment> tag to inflate. Another issue was the <merge> tag. In order to inflate those, you need 1) a root view and 2) attach your view to it. In order to be able to test those layouts file, I had to create an empty FrameLayout and use it as the root view for testing. Again, I know this is beyond the spirit of a unit test but if we use this inflater, I think it should make sure that no layouts are broken by it. * For #16373: Overrode getSystemService to return PerformanceInflater This allows PerformanceInflater to be called in every inflation to keep track of the number of inflations we do. * For #16373: Added UI test for # of inflations * For #16373: Lint fix * For #167373: Changed the LayoutInflater cloneInContext to take this instead of inflater The inflater parameter is set on the first call from the OS from the Window object. However, the activity itself sets multiple factories on the inflater during its creation (usually through AppCompatDelegateImpl.java). This means that, once we initially set the inflater with a null check, we pass an inflater that has no factory initially. However, since we keep a reference to it, when cloneInContext was called, it cloned the inflater with the original inflater which didn't have any factories set up. This meant that the app would crash on either browserFragment creation or any thing that required appCompat (such as ImageView and ImageButton). Now, passing itself with a cloneInContext means we keep all the factories initially set by the activity or the fragment. * For #16373: Fixed code issues for PR. No behavior change * For #16373: fixed some code nits
3 years ago
private const val EXPECTED_NUMBER_OF_INFLATION = 12
private val failureMsgStrictMode = getErrorMessage(
shortName = "StrictMode suppression",
implications = "suppressing a StrictMode violation can introduce performance regressions?"
)
private val failureMsgRunBlocking = getErrorMessage(
shortName = "runBlockingIncrement",
implications = "using runBlocking may block the main thread and have other negative performance implications?"
)
private val failureMsgComponentInit = getErrorMessage(
shortName = "Component init",
implications = "initializing new components on start up may be an indication that we're doing more work than necessary on start up?"
)
private val failureMsgViewHierarchyDepth = getErrorMessage(
shortName = "view hierarchy depth",
implications = "having a deep view hierarchy can slow down measure/layout performance?"
) + "Please note that we're not sure if this is a useful metric to assert: with your feedback, " +
"we'll find out over time if it is or is not."
private val failureMsgRecyclerViewConstraintLayoutChildren = getErrorMessage(
shortName = "ConstraintLayout being a common direct descendant of a RecyclerView",
implications = "ConstraintLayouts are slow to inflate and are primarily used to flatten deep " +
"view hierarchies so can be under-performant as a common RecyclerView child?"
) + "Please note that we're not sure if this is a useful metric to assert: with your feedback, " +
"we'll find out over time if it is or is not."
16373 Count the # of inflations done on startup (#16778) * For #16373: Added performance Inflater to counter # of inflations This class is quite straight forward. The only thing that I have to point out is the onCreateView method. It usually calls its super if you don't override it. The problem with that is that the super.onCreateView actually uses android.view. as a prefix for the XML element it tries to inflate. So if we have an element that isn't part of that package, it'll crash. As I said in the code, a good example is ImageButton. Calling android.view.ImageButton will make the app crash. The method is implemented the same way that PhoneLayoutInflater does (Another example is the AsyncLayoutInflater) * For #16373: Added test for PerformanceInflater This test got quite awkward / complicated fast. I wanted to test the to make sure we don't break *any* of our layouts and to do so, I decided to just retrieve all our XML in our /res/layout folder. However, this gets quite a bit outside of a unit test scope. The point was to get every layouts and get their LayoutID through the resources using the testContext we have. It gets even weirder, since some of the XML tags have special implementation in android. One of them is the <fragment> tag. That tag actually is inflated by the OS using the Factory2 that the Activity.java implements. In order to get around the fragment issue, we just return a basic FrameLayout since the system LayoutInflater doesn't deal won't ever get a <fragment> tag to inflate. Another issue was the <merge> tag. In order to inflate those, you need 1) a root view and 2) attach your view to it. In order to be able to test those layouts file, I had to create an empty FrameLayout and use it as the root view for testing. Again, I know this is beyond the spirit of a unit test but if we use this inflater, I think it should make sure that no layouts are broken by it. * For #16373: Overrode getSystemService to return PerformanceInflater This allows PerformanceInflater to be called in every inflation to keep track of the number of inflations we do. * For #16373: Added UI test for # of inflations * For #16373: Lint fix * For #167373: Changed the LayoutInflater cloneInContext to take this instead of inflater The inflater parameter is set on the first call from the OS from the Window object. However, the activity itself sets multiple factories on the inflater during its creation (usually through AppCompatDelegateImpl.java). This means that, once we initially set the inflater with a null check, we pass an inflater that has no factory initially. However, since we keep a reference to it, when cloneInContext was called, it cloned the inflater with the original inflater which didn't have any factories set up. This meant that the app would crash on either browserFragment creation or any thing that required appCompat (such as ImageView and ImageButton). Now, passing itself with a cloneInContext means we keep all the factories initially set by the activity or the fragment. * For #16373: Fixed code issues for PR. No behavior change * For #16373: fixed some code nits
3 years ago
private val failureMsgNumberOfInflation = getErrorMessage(
shortName = "Number of inflation on start up doesn't match expected count",
implications = "The number of inflation can negatively impact start up time. Having more inflations" +
"will most likely mean we're adding extra work on the UI thread."
16373 Count the # of inflations done on startup (#16778) * For #16373: Added performance Inflater to counter # of inflations This class is quite straight forward. The only thing that I have to point out is the onCreateView method. It usually calls its super if you don't override it. The problem with that is that the super.onCreateView actually uses android.view. as a prefix for the XML element it tries to inflate. So if we have an element that isn't part of that package, it'll crash. As I said in the code, a good example is ImageButton. Calling android.view.ImageButton will make the app crash. The method is implemented the same way that PhoneLayoutInflater does (Another example is the AsyncLayoutInflater) * For #16373: Added test for PerformanceInflater This test got quite awkward / complicated fast. I wanted to test the to make sure we don't break *any* of our layouts and to do so, I decided to just retrieve all our XML in our /res/layout folder. However, this gets quite a bit outside of a unit test scope. The point was to get every layouts and get their LayoutID through the resources using the testContext we have. It gets even weirder, since some of the XML tags have special implementation in android. One of them is the <fragment> tag. That tag actually is inflated by the OS using the Factory2 that the Activity.java implements. In order to get around the fragment issue, we just return a basic FrameLayout since the system LayoutInflater doesn't deal won't ever get a <fragment> tag to inflate. Another issue was the <merge> tag. In order to inflate those, you need 1) a root view and 2) attach your view to it. In order to be able to test those layouts file, I had to create an empty FrameLayout and use it as the root view for testing. Again, I know this is beyond the spirit of a unit test but if we use this inflater, I think it should make sure that no layouts are broken by it. * For #16373: Overrode getSystemService to return PerformanceInflater This allows PerformanceInflater to be called in every inflation to keep track of the number of inflations we do. * For #16373: Added UI test for # of inflations * For #16373: Lint fix * For #167373: Changed the LayoutInflater cloneInContext to take this instead of inflater The inflater parameter is set on the first call from the OS from the Window object. However, the activity itself sets multiple factories on the inflater during its creation (usually through AppCompatDelegateImpl.java). This means that, once we initially set the inflater with a null check, we pass an inflater that has no factory initially. However, since we keep a reference to it, when cloneInContext was called, it cloned the inflater with the original inflater which didn't have any factories set up. This meant that the app would crash on either browserFragment creation or any thing that required appCompat (such as ImageView and ImageButton). Now, passing itself with a cloneInContext means we keep all the factories initially set by the activity or the fragment. * For #16373: Fixed code issues for PR. No behavior change * For #16373: fixed some code nits
3 years ago
)
/**
* A performance test to limit the number of StrictMode suppressions and number of runBlocking used
* on startup.
*
* This test was written by the perf team.
*
* StrictMode detects main thread IO, which is often indicative of a performance issue.
* It's easy to suppress StrictMode so we wrote a test to ensure we have a discussion
* if the StrictMode count changes.
*
* RunBlocking is mostly used to return values to a thread from a coroutine. However, if that
* coroutine takes too long, it can lead that thread to block every other operations.
*
* The perf team is code owners for this package so they should be notified when the counts are modified.
*/
class StartupExcessiveResourceUseTest {
@get:Rule
val activityTestRule = HomeActivityTestRule(skipOnboarding = true)
private val uiDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation())
@Test
fun verifyRunBlockingAndStrictModeSuppresionCount() {
uiDevice.waitForIdle() // wait for async UI to load.
// This might cause intermittents: at an arbitrary point after start up (such as the visual
// completeness queue), we might run code on the main thread that suppresses StrictMode,
// causing this number to fluctuate depending on device speed. We'll deal with it if it occurs.
val actualSuppresionCount = activityTestRule.activity.components.strictMode.suppressionCount.get().toInt()
val actualRunBlocking = RunBlockingCounter.count.get()
val actualComponentInitCount = ComponentInitCount.count.get()
val rootView = activityTestRule.activity.rootContainer
val actualViewHierarchyDepth = countAndLogViewHierarchyDepth(rootView, 1)
val actualRecyclerViewConstraintLayoutChildren = countRecyclerViewConstraintLayoutChildren(rootView, null)
16373 Count the # of inflations done on startup (#16778) * For #16373: Added performance Inflater to counter # of inflations This class is quite straight forward. The only thing that I have to point out is the onCreateView method. It usually calls its super if you don't override it. The problem with that is that the super.onCreateView actually uses android.view. as a prefix for the XML element it tries to inflate. So if we have an element that isn't part of that package, it'll crash. As I said in the code, a good example is ImageButton. Calling android.view.ImageButton will make the app crash. The method is implemented the same way that PhoneLayoutInflater does (Another example is the AsyncLayoutInflater) * For #16373: Added test for PerformanceInflater This test got quite awkward / complicated fast. I wanted to test the to make sure we don't break *any* of our layouts and to do so, I decided to just retrieve all our XML in our /res/layout folder. However, this gets quite a bit outside of a unit test scope. The point was to get every layouts and get their LayoutID through the resources using the testContext we have. It gets even weirder, since some of the XML tags have special implementation in android. One of them is the <fragment> tag. That tag actually is inflated by the OS using the Factory2 that the Activity.java implements. In order to get around the fragment issue, we just return a basic FrameLayout since the system LayoutInflater doesn't deal won't ever get a <fragment> tag to inflate. Another issue was the <merge> tag. In order to inflate those, you need 1) a root view and 2) attach your view to it. In order to be able to test those layouts file, I had to create an empty FrameLayout and use it as the root view for testing. Again, I know this is beyond the spirit of a unit test but if we use this inflater, I think it should make sure that no layouts are broken by it. * For #16373: Overrode getSystemService to return PerformanceInflater This allows PerformanceInflater to be called in every inflation to keep track of the number of inflations we do. * For #16373: Added UI test for # of inflations * For #16373: Lint fix * For #167373: Changed the LayoutInflater cloneInContext to take this instead of inflater The inflater parameter is set on the first call from the OS from the Window object. However, the activity itself sets multiple factories on the inflater during its creation (usually through AppCompatDelegateImpl.java). This means that, once we initially set the inflater with a null check, we pass an inflater that has no factory initially. However, since we keep a reference to it, when cloneInContext was called, it cloned the inflater with the original inflater which didn't have any factories set up. This meant that the app would crash on either browserFragment creation or any thing that required appCompat (such as ImageView and ImageButton). Now, passing itself with a cloneInContext means we keep all the factories initially set by the activity or the fragment. * For #16373: Fixed code issues for PR. No behavior change * For #16373: fixed some code nits
3 years ago
val actualNumberOfInflations = InflationCounter.inflationCount.get()
assertEquals(failureMsgStrictMode, EXPECTED_SUPPRESSION_COUNT, actualSuppresionCount)
assertEquals(failureMsgRunBlocking, EXPECTED_RUNBLOCKING_COUNT, actualRunBlocking)
assertEquals(failureMsgComponentInit, EXPECTED_COMPONENT_INIT_COUNT, actualComponentInitCount)
assertEquals(failureMsgViewHierarchyDepth, EXPECTED_VIEW_HIERARCHY_DEPTH, actualViewHierarchyDepth)
assertEquals(
failureMsgRecyclerViewConstraintLayoutChildren,
EXPECTED_RECYCLER_VIEW_CONSTRAINT_LAYOUT_CHILDREN,
actualRecyclerViewConstraintLayoutChildren
)
16373 Count the # of inflations done on startup (#16778) * For #16373: Added performance Inflater to counter # of inflations This class is quite straight forward. The only thing that I have to point out is the onCreateView method. It usually calls its super if you don't override it. The problem with that is that the super.onCreateView actually uses android.view. as a prefix for the XML element it tries to inflate. So if we have an element that isn't part of that package, it'll crash. As I said in the code, a good example is ImageButton. Calling android.view.ImageButton will make the app crash. The method is implemented the same way that PhoneLayoutInflater does (Another example is the AsyncLayoutInflater) * For #16373: Added test for PerformanceInflater This test got quite awkward / complicated fast. I wanted to test the to make sure we don't break *any* of our layouts and to do so, I decided to just retrieve all our XML in our /res/layout folder. However, this gets quite a bit outside of a unit test scope. The point was to get every layouts and get their LayoutID through the resources using the testContext we have. It gets even weirder, since some of the XML tags have special implementation in android. One of them is the <fragment> tag. That tag actually is inflated by the OS using the Factory2 that the Activity.java implements. In order to get around the fragment issue, we just return a basic FrameLayout since the system LayoutInflater doesn't deal won't ever get a <fragment> tag to inflate. Another issue was the <merge> tag. In order to inflate those, you need 1) a root view and 2) attach your view to it. In order to be able to test those layouts file, I had to create an empty FrameLayout and use it as the root view for testing. Again, I know this is beyond the spirit of a unit test but if we use this inflater, I think it should make sure that no layouts are broken by it. * For #16373: Overrode getSystemService to return PerformanceInflater This allows PerformanceInflater to be called in every inflation to keep track of the number of inflations we do. * For #16373: Added UI test for # of inflations * For #16373: Lint fix * For #167373: Changed the LayoutInflater cloneInContext to take this instead of inflater The inflater parameter is set on the first call from the OS from the Window object. However, the activity itself sets multiple factories on the inflater during its creation (usually through AppCompatDelegateImpl.java). This means that, once we initially set the inflater with a null check, we pass an inflater that has no factory initially. However, since we keep a reference to it, when cloneInContext was called, it cloned the inflater with the original inflater which didn't have any factories set up. This meant that the app would crash on either browserFragment creation or any thing that required appCompat (such as ImageView and ImageButton). Now, passing itself with a cloneInContext means we keep all the factories initially set by the activity or the fragment. * For #16373: Fixed code issues for PR. No behavior change * For #16373: fixed some code nits
3 years ago
assertEquals(failureMsgNumberOfInflation, EXPECTED_NUMBER_OF_INFLATION, actualNumberOfInflations)
}
}
private fun countAndLogViewHierarchyDepth(view: View, level: Int): Int {
// Log for debugging purposes: not sure if this is actually helpful.
val indent = "| ".repeat(level - 1)
Log.d("Startup...Test", "${indent}$view")
return if (view !is ViewGroup) {
level
} else {
val maxDepth = view.children.map { countAndLogViewHierarchyDepth(it, level + 1) }.maxOrNull()
maxDepth ?: level
}
}
private fun countRecyclerViewConstraintLayoutChildren(view: View, parent: View?): Int {
val viewValue = if (parent is RecyclerView && view is ConstraintLayout) {
1
} else {
0
}
return if (view !is ViewGroup) {
viewValue
} else {
viewValue + view.children.sumOf { countRecyclerViewConstraintLayoutChildren(it, view) }
}
}
private fun getErrorMessage(shortName: String, implications: String) = """$shortName count does not match expected count.
If this PR removed a $shortName call, great! Please decrease the count.
Did this PR add or call code that increases the $shortName count?
Did you know that $implications
Please do your best to implement a solution without adding $shortName calls.
Please consult the perf team if you have questions or believe that having this call
is the optimal solution.
"""