Skip to content

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 3 commits into from
Sep 30, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions firebase-common/firebase-common.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ dependencies {

annotationProcessor 'com.google.auto.value:auto-value:1.6.5'

androidTestImplementation project(':integ-testing')
androidTestImplementation 'junit:junit:4.13'
androidTestImplementation 'androidx.test:runner:1.3.0'
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,38 +14,21 @@

package com.google.firebase;

import android.os.StrictMode;
import android.os.StrictMode.ThreadPolicy;
import android.os.StrictMode.VmPolicy;
import androidx.test.core.app.ApplicationProvider;
import com.google.firebase.FirebaseOptions.Builder;
import com.google.firebase.testing.integ.StrictModeRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;

@RunWith(androidx.test.ext.junit.runners.AndroidJUnit4.class)
public class StrictModeTest {

interface Fn<E extends Throwable> {
void call() throws E;
}

static <E extends Throwable> void withStrictMode(Fn<E> fn) throws E {
ThreadPolicy threadPolicy = StrictMode.getThreadPolicy();
VmPolicy vmPolicy = StrictMode.getVmPolicy();

StrictMode.setThreadPolicy(new ThreadPolicy.Builder().detectAll().penaltyDeath().build());
StrictMode.setVmPolicy(new VmPolicy.Builder().detectAll().penaltyDeath().build());
try {
fn.call();
} finally {
StrictMode.setThreadPolicy(threadPolicy);
StrictMode.setVmPolicy(vmPolicy);
}
}
@Rule public StrictModeRule strictMode = new StrictModeRule();

@Test
public void initializingFirebaseApp_shouldNotViolateStrictMode() {
withStrictMode(
strictMode.runOnMainThread(
() -> {
FirebaseApp app =
FirebaseApp.initializeApp(
Expand All @@ -56,7 +39,6 @@ public void initializingFirebaseApp_shouldNotViolateStrictMode() {
.setApplicationId("appId")
.build(),
"hello");

app.initializeAllComponents();
});
}
Expand Down
Empty file added integ-testing/gradle.properties
Empty file.
35 changes: 35 additions & 0 deletions integ-testing/integ-testing.gradle
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'
}
21 changes: 21 additions & 0 deletions integ-testing/src/main/AndroidManifest.xml
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>
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;
}
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;
}
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();
}
}
2 changes: 2 additions & 0 deletions subprojects.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@ encoders:firebase-encoders-processor
encoders:firebase-encoders-reflective
encoders:firebase-decoders-json

integ-testing

tools:errorprone
tools:lint

Expand Down