[ApiModel] Add test for outlining and stubbing

Change-Id: I71e8b43a6ae97f2ef87c75dc5660e44fb6c791b4
diff --git a/src/test/java/com/android/tools/r8/apimodel/ApiModelOutlineMethodAndStubClassTest.java b/src/test/java/com/android/tools/r8/apimodel/ApiModelOutlineMethodAndStubClassTest.java
new file mode 100644
index 0000000..aaa64ba
--- /dev/null
+++ b/src/test/java/com/android/tools/r8/apimodel/ApiModelOutlineMethodAndStubClassTest.java
@@ -0,0 +1,105 @@
+// Copyright (c) 2021, the R8 project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+package com.android.tools.r8.apimodel;
+
+import static com.android.tools.r8.apimodel.ApiModelingTestHelper.setMockApiLevelForClass;
+import static com.android.tools.r8.apimodel.ApiModelingTestHelper.setMockApiLevelForDefaultInstanceInitializer;
+import static com.android.tools.r8.apimodel.ApiModelingTestHelper.setMockApiLevelForMethod;
+import static com.android.tools.r8.apimodel.ApiModelingTestHelper.verifyThat;
+import static org.junit.Assume.assumeFalse;
+
+import com.android.tools.r8.TestBase;
+import com.android.tools.r8.TestParameters;
+import com.android.tools.r8.TestParametersCollection;
+import com.android.tools.r8.ToolHelper.DexVm.Version;
+import com.android.tools.r8.apimodel.ApiModelMockClassTest.TestClass;
+import com.android.tools.r8.testing.AndroidBuildVersion;
+import com.android.tools.r8.utils.AndroidApiLevel;
+import java.lang.reflect.Method;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+import org.junit.runners.Parameterized.Parameter;
+import org.junit.runners.Parameterized.Parameters;
+
+@RunWith(Parameterized.class)
+public class ApiModelOutlineMethodAndStubClassTest extends TestBase {
+
+  private final AndroidApiLevel libraryClassLevel = AndroidApiLevel.M;
+  private final AndroidApiLevel libraryMethodLevel = AndroidApiLevel.Q;
+
+  @Parameter public TestParameters parameters;
+
+  @Parameters(name = "{0}")
+  public static TestParametersCollection data() {
+    return getTestParameters().withAllRuntimesAndApiLevels().build();
+  }
+
+  @Test
+  public void testR8() throws Exception {
+    // TODO(b/197078995): Make this work on 12.
+    assumeFalse(
+        parameters.isDexRuntime() && parameters.getDexRuntimeVersion().isEqualTo(Version.V12_0_0));
+    boolean libraryClassNotStubbed =
+        parameters.isDexRuntime()
+            && parameters.getApiLevel().isGreaterThanOrEqualTo(libraryClassLevel);
+    Method apiMethod = LibraryClass.class.getDeclaredMethod("foo");
+    testForR8(parameters.getBackend())
+        .addProgramClasses(Main.class, TestClass.class)
+        .addLibraryClasses(LibraryClass.class)
+        .addDefaultRuntimeLibrary(parameters)
+        .setMinApi(parameters.getApiLevel())
+        .addKeepMainRule(Main.class)
+        .addAndroidBuildVersion()
+        .apply(ApiModelingTestHelper::enableStubbingOfClasses)
+        .apply(ApiModelingTestHelper::enableOutliningOfMethods)
+        .apply(setMockApiLevelForClass(LibraryClass.class, libraryClassLevel))
+        .apply(setMockApiLevelForDefaultInstanceInitializer(LibraryClass.class, libraryClassLevel))
+        .apply(setMockApiLevelForMethod(apiMethod, libraryMethodLevel))
+        .compile()
+        .applyIf(
+            parameters.isDexRuntime()
+                && parameters
+                    .getRuntime()
+                    .maxSupportedApiLevel()
+                    .isGreaterThanOrEqualTo(libraryClassLevel),
+            b -> b.addBootClasspathClasses(LibraryClass.class))
+        .run(parameters.getRuntime(), Main.class)
+        .assertSuccessWithOutputLinesIf(libraryClassNotStubbed, "LibraryClass::foo")
+        .assertSuccessWithOutputLinesIf(!libraryClassNotStubbed, "Hello World")
+        .inspect(verifyThat(parameters, LibraryClass.class).stubbedUntil(libraryClassLevel))
+        // TODO(b/210823526): We should always outline the call if min-api < libraryMethodLevel
+        .applyIf(
+            libraryClassNotStubbed && parameters.getApiLevel().isLessThan(libraryMethodLevel),
+            b ->
+                b.inspect(
+                    verifyThat(parameters, apiMethod)
+                        .isOutlinedFrom(Main.class.getDeclaredMethod("main", String[].class))),
+            b ->
+                b.inspect(
+                    verifyThat(parameters, apiMethod)
+                        .isNotOutlinedFrom(Main.class.getDeclaredMethod("main", String[].class))));
+  }
+
+  // Only present from api level 23.
+  public static class LibraryClass {
+
+    // Only present from api level 30
+    public void foo() {
+      System.out.println("LibraryClass::foo");
+    }
+  }
+
+  public static class Main {
+
+    public static void main(String[] args) {
+      if (AndroidBuildVersion.VERSION >= 23) {
+        new LibraryClass().foo();
+      } else {
+        System.out.println("Hello World");
+      }
+    }
+  }
+}
diff --git a/src/test/java/com/android/tools/r8/apimodel/ApiModelingTestHelper.java b/src/test/java/com/android/tools/r8/apimodel/ApiModelingTestHelper.java
index c109def..70d4f36 100644
--- a/src/test/java/com/android/tools/r8/apimodel/ApiModelingTestHelper.java
+++ b/src/test/java/com/android/tools/r8/apimodel/ApiModelingTestHelper.java
@@ -4,10 +4,13 @@
 
 package com.android.tools.r8.apimodel;
 
+import static com.android.tools.r8.utils.codeinspector.CodeMatchers.invokesMethod;
+import static com.android.tools.r8.utils.codeinspector.CodeMatchers.invokesMethodWithName;
 import static com.android.tools.r8.utils.codeinspector.Matchers.isPresent;
 import static com.android.tools.r8.utils.codeinspector.Matchers.notIf;
 import static org.hamcrest.CoreMatchers.not;
 import static org.hamcrest.MatcherAssert.assertThat;
+import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertTrue;
 
 import com.android.tools.r8.TestCompilerBuilder;
@@ -20,12 +23,15 @@
 import com.android.tools.r8.utils.codeinspector.CodeInspector;
 import com.android.tools.r8.utils.codeinspector.CodeMatchers;
 import com.android.tools.r8.utils.codeinspector.FoundClassSubject;
+import com.android.tools.r8.utils.codeinspector.FoundMethodSubject;
 import com.android.tools.r8.utils.codeinspector.MethodSubject;
 import com.google.common.collect.ImmutableList;
 import java.lang.reflect.Constructor;
 import java.lang.reflect.Field;
 import java.lang.reflect.Method;
+import java.util.List;
 import java.util.function.BiConsumer;
+import java.util.stream.Collectors;
 
 public abstract class ApiModelingTestHelper {
 
@@ -223,5 +229,40 @@
         assertThat(target, not(CodeMatchers.invokesMethod(candidate)));
       };
     }
+
+    ThrowingConsumer<CodeInspector, Exception> isOutlinedFromUntil(
+        Method method, AndroidApiLevel apiLevel) {
+      return parameters.isDexRuntime() && parameters.getApiLevel().isLessThan(apiLevel)
+          ? isOutlinedFrom(method)
+          : isNotOutlinedFrom(method);
+    }
+
+    ThrowingConsumer<CodeInspector, Exception> isOutlinedFrom(Method method) {
+      return inspector -> {
+        // Check that the call is in a synthetic class.
+        List<FoundMethodSubject> outlinedMethod =
+            inspector.allClasses().stream()
+                .flatMap(clazz -> clazz.allMethods().stream())
+                .filter(
+                    methodSubject ->
+                        methodSubject.isSynthetic()
+                            && invokesMethodWithName(methodOfInterest.getMethodName())
+                                .matches(methodSubject))
+                .collect(Collectors.toList());
+        assertEquals(1, outlinedMethod.size());
+        // Assert that method invokes the outline
+        MethodSubject caller = inspector.method(method);
+        assertThat(caller, isPresent());
+        assertThat(caller, invokesMethod(outlinedMethod.get(0)));
+      };
+    }
+
+    ThrowingConsumer<CodeInspector, Exception> isNotOutlinedFrom(Method method) {
+      return inspector -> {
+        MethodSubject caller = inspector.method(method);
+        assertThat(caller, isPresent());
+        assertThat(caller, invokesMethodWithName(methodOfInterest.getMethodName()));
+      };
+    }
   }
 }