-
Notifications
You must be signed in to change notification settings - Fork 627
Add StrictModeRule for use by SDKs. #2023
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
Merged
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Empty file.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
// Copyright 2018 Google LLC | ||
// | ||
// Licensed under the Apache License, Version 2.0 (the "License"); | ||
// you may not use this file except in compliance with the License. | ||
// You may obtain a copy of the License at | ||
// | ||
// http://www.apache.org/licenses/LICENSE-2.0 | ||
// | ||
// Unless required by applicable law or agreed to in writing, software | ||
// distributed under the License is distributed on an "AS IS" BASIS, | ||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
// See the License for the specific language governing permissions and | ||
// limitations under the License. | ||
|
||
plugins { | ||
id 'com.android.library' | ||
} | ||
|
||
android { | ||
compileSdkVersion project.targetSdkVersion | ||
defaultConfig { | ||
minSdkVersion project.minSdkVersion | ||
targetSdkVersion project.targetSdkVersion | ||
} | ||
|
||
compileOptions { | ||
sourceCompatibility JavaVersion.VERSION_1_8 | ||
targetCompatibility JavaVersion.VERSION_1_8 | ||
} | ||
} | ||
|
||
dependencies { | ||
implementation 'junit:junit:4.13' | ||
implementation 'androidx.test:runner:1.3.0' | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
<?xml version="1.0" encoding="utf-8"?> | ||
<!-- Copyright 2020 Google LLC --> | ||
<!-- --> | ||
<!-- Licensed under the Apache License, Version 2.0 (the "License"); --> | ||
<!-- you may not use this file except in compliance with the License. --> | ||
<!-- You may obtain a copy of the License at --> | ||
<!-- --> | ||
<!-- http://www.apache.org/licenses/LICENSE-2.0 --> | ||
<!-- --> | ||
<!-- Unless required by applicable law or agreed to in writing, software --> | ||
<!-- distributed under the License is distributed on an "AS IS" BASIS, --> | ||
<!-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. --> | ||
<!-- See the License for the specific language governing permissions and --> | ||
<!-- limitations under the License. --> | ||
|
||
<manifest xmlns:android="http://schemas.android.com/apk/res/android" | ||
xmlns:tools="http://schemas.android.com/tools" | ||
package="com.google.firebase.testing.integ"> | ||
<!--Although the *SdkVersion is captured in gradle build files, this is required for non gradle builds--> | ||
<!--<uses-sdk android:minSdkVersion="14"/>--> | ||
</manifest> |
19 changes: 19 additions & 0 deletions
19
integ-testing/src/main/java/com/google/firebase/testing/integ/MaybeThrowingCallable.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,19 @@ | ||
// Copyright 2020 Google LLC | ||
// | ||
// Licensed under the Apache License, Version 2.0 (the "License"); | ||
// you may not use this file except in compliance with the License. | ||
// You may obtain a copy of the License at | ||
// | ||
// http://www.apache.org/licenses/LICENSE-2.0 | ||
// | ||
// Unless required by applicable law or agreed to in writing, software | ||
// distributed under the License is distributed on an "AS IS" BASIS, | ||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
// See the License for the specific language governing permissions and | ||
// limitations under the License. | ||
|
||
package com.google.firebase.testing.integ; | ||
|
||
public interface MaybeThrowingCallable<T, E extends Throwable> { | ||
T call() throws E; | ||
} |
19 changes: 19 additions & 0 deletions
19
integ-testing/src/main/java/com/google/firebase/testing/integ/MaybeThrowingRunnable.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,19 @@ | ||
// Copyright 2020 Google LLC | ||
// | ||
// Licensed under the Apache License, Version 2.0 (the "License"); | ||
// you may not use this file except in compliance with the License. | ||
// You may obtain a copy of the License at | ||
// | ||
// http://www.apache.org/licenses/LICENSE-2.0 | ||
// | ||
// Unless required by applicable law or agreed to in writing, software | ||
// distributed under the License is distributed on an "AS IS" BASIS, | ||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
// See the License for the specific language governing permissions and | ||
// limitations under the License. | ||
|
||
package com.google.firebase.testing.integ; | ||
|
||
public interface MaybeThrowingRunnable<E extends Throwable> { | ||
void run() throws E; | ||
} |
167 changes: 167 additions & 0 deletions
167
integ-testing/src/main/java/com/google/firebase/testing/integ/StrictModeRule.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,167 @@ | ||
// Copyright 2020 Google LLC | ||
// | ||
// Licensed under the Apache License, Version 2.0 (the "License"); | ||
// you may not use this file except in compliance with the License. | ||
// You may obtain a copy of the License at | ||
// | ||
// http://www.apache.org/licenses/LICENSE-2.0 | ||
// | ||
// Unless required by applicable law or agreed to in writing, software | ||
// distributed under the License is distributed on an "AS IS" BASIS, | ||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
// See the License for the specific language governing permissions and | ||
// limitations under the License. | ||
|
||
package com.google.firebase.testing.integ; | ||
|
||
import android.os.Build; | ||
import android.os.StrictMode; | ||
import android.os.StrictMode.ThreadPolicy; | ||
import android.os.StrictMode.VmPolicy; | ||
import androidx.test.internal.runner.junit4.statement.UiThreadStatement; | ||
import androidx.test.platform.app.InstrumentationRegistry; | ||
import java.util.ArrayList; | ||
import java.util.Collection; | ||
import java.util.concurrent.ConcurrentLinkedQueue; | ||
import java.util.concurrent.Executor; | ||
import java.util.concurrent.atomic.AtomicReference; | ||
import org.junit.rules.TestRule; | ||
import org.junit.runner.Description; | ||
import org.junit.runners.model.MultipleFailureException; | ||
import org.junit.runners.model.Statement; | ||
|
||
/** | ||
* This rule enables {@link StrictMode} on the <a | ||
* href="https://developer.android.com/guide/components/processes-and-threads#Threads">Main | ||
* thread</a>. | ||
* | ||
* <p>Just adding it as a {@link @Rule} to your test is enough to enable it. | ||
* | ||
* <p>Note however that the tests don't run on the Main thread by default, so if you expect the code | ||
* under test to run in the Main thread in production, please use the provided {@link | ||
* #runOnMainThread(MaybeThrowingRunnable)} to execute it on the Main thread. | ||
* | ||
* <p>Example use: | ||
* | ||
* <pre>{@code | ||
* @Test | ||
* public class MyTests { | ||
* @Rule public StrictModeRule strictMode = new StrictModeRule(); | ||
* | ||
* @Test public void myTest() { | ||
* // runs on the instrumentation thread | ||
* runMyCode(); | ||
* | ||
* // runs on Main thread. | ||
* strictMode.runOnMainThread(() -> { | ||
* runCodeOnMainThread(); | ||
* }); | ||
* } | ||
* } | ||
* }</pre> | ||
*/ | ||
public class StrictModeRule implements TestRule { | ||
|
||
private static final Executor penaltyListenerExecutor = Runnable::run; | ||
|
||
/** Runs {@code runnable} on Main thread. */ | ||
public <E extends Throwable> void runOnMainThread(MaybeThrowingRunnable<E> runnable) throws E { | ||
try { | ||
new UiThreadStatement( | ||
new Statement() { | ||
@Override | ||
public void evaluate() throws E { | ||
runnable.run(); | ||
} | ||
}, | ||
true) | ||
.evaluate(); | ||
} catch (Throwable throwable) { | ||
@SuppressWarnings("unchecked") | ||
E e = (E) throwable; | ||
throw e; | ||
} | ||
} | ||
|
||
/** Runs {@code callable} on Main thread and returns it result. */ | ||
public <T, E extends Throwable> T runOnMainThread(MaybeThrowingCallable<T, E> callable) throws E { | ||
try { | ||
AtomicReference<T> result = new AtomicReference<>(); | ||
new UiThreadStatement( | ||
new Statement() { | ||
@Override | ||
public void evaluate() throws E { | ||
result.set(callable.call()); | ||
} | ||
}, | ||
true) | ||
.evaluate(); | ||
return result.get(); | ||
} catch (Throwable throwable) { | ||
@SuppressWarnings("unchecked") | ||
E e = (E) throwable; | ||
throw e; | ||
} | ||
} | ||
|
||
@Override | ||
public Statement apply(Statement base, Description description) { | ||
return new Statement() { | ||
@Override | ||
public void evaluate() throws Throwable { | ||
AtomicReference<ThreadPolicy> originalThreadPolicy = new AtomicReference<>(); | ||
VmPolicy originalVmPolicy = StrictMode.getVmPolicy(); | ||
|
||
ConcurrentLinkedQueue<Throwable> violations = new ConcurrentLinkedQueue<>(); | ||
|
||
InstrumentationRegistry.getInstrumentation() | ||
.runOnMainSync( | ||
() -> { | ||
originalThreadPolicy.set(StrictMode.getThreadPolicy()); | ||
|
||
StrictMode.setThreadPolicy(createThreadPolicy(violations)); | ||
StrictMode.setVmPolicy(createVmPolicy(violations)); | ||
}); | ||
try { | ||
base.evaluate(); | ||
} catch (Throwable e) { | ||
violations.add(e); | ||
} finally { | ||
InstrumentationRegistry.getInstrumentation() | ||
.runOnMainSync(() -> StrictMode.setThreadPolicy(originalThreadPolicy.get())); | ||
// Make sure GC happens, so that the VM policy can detect unclosed resources. | ||
runGc(); | ||
StrictMode.setVmPolicy(originalVmPolicy); | ||
} | ||
MultipleFailureException.assertEmpty(new ArrayList<>(violations)); | ||
} | ||
}; | ||
} | ||
|
||
private static ThreadPolicy createThreadPolicy(Collection<Throwable> violations) { | ||
ThreadPolicy.Builder builder = new ThreadPolicy.Builder().detectAll(); | ||
if (Build.VERSION.SDK_INT >= 28) { | ||
builder.penaltyListener(penaltyListenerExecutor, violations::add); | ||
} else { | ||
builder.penaltyDeath(); | ||
} | ||
return builder.build(); | ||
} | ||
|
||
private static VmPolicy createVmPolicy(Collection<Throwable> violations) { | ||
VmPolicy.Builder builder = new VmPolicy.Builder().detectAll(); | ||
if (Build.VERSION.SDK_INT >= 28) { | ||
builder.penaltyListener(penaltyListenerExecutor, violations::add); | ||
} else { | ||
builder.penaltyDeath(); | ||
} | ||
return builder.build(); | ||
} | ||
|
||
private static void runGc() { | ||
Runtime.getRuntime().gc(); | ||
Runtime.getRuntime().runFinalization(); | ||
Runtime.getRuntime().gc(); | ||
Runtime.getRuntime().runFinalization(); | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.