com.google.common.truth.Correspondence Java Examples

The following examples show how to use com.google.common.truth.Correspondence. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DependencyGraphBuilderTest.java    From cloud-opensource-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testBuildLinkageCheckDependencyGraph_grpcProtobufExclusion() {
  // Grpc-protobuf depends on grpc-protobuf-lite with protobuf-lite exclusion.
  // https://github.com/GoogleCloudPlatform/cloud-opensource-java/issues/1056
  Artifact grpcProtobuf = new DefaultArtifact("io.grpc:grpc-protobuf:1.25.0");

  DependencyGraph dependencyGraph = dependencyGraphBuilder
          .buildFullDependencyGraph(ImmutableList.of(grpcProtobuf));

  Correspondence<DependencyPath, String> pathToArtifactKey =
      Correspondence.transforming(
          dependencyPath -> Artifacts.makeKey(dependencyPath.getLeaf()),
          "has a leaf with groupID and artifactID");
  Truth.assertThat(dependencyGraph.list())
      .comparingElementsUsing(pathToArtifactKey)
      .doesNotContain("com.google.protobuf:protobuf-lite");
}
 
Example #2
Source File: DependencyGraphBuilderTest.java    From cloud-opensource-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testBuildLinkageCheckDependencyGraph_catchRootException() {
  // This should not throw exception
  DependencyGraph result =
      dependencyGraphBuilder.buildFullDependencyGraph(
          ImmutableList.of(new DefaultArtifact("ant:ant:jar:1.6.2")));

  Set<UnresolvableArtifactProblem> problems = result.getUnresolvedArtifacts();

  Truth.assertThat(problems)
      .comparingElementsUsing(problemOnArtifact)
      .containsAtLeast("xerces:xerces-impl:2.6.2", "xml-apis:xml-apis:2.6.2");

  Truth.assertThat(problems).hasSize(2);
  Truth.assertThat(problems)
      .comparingElementsUsing(
          Correspondence.transforming(UnresolvableArtifactProblem::toString, "has description"))
      .containsExactly(
          "xerces:xerces-impl:jar:2.6.2 was not resolved. Dependency path: ant:ant:jar:1.6.2"
              + " (compile) > xerces:xerces-impl:jar:2.6.2 (compile?)",
          "xml-apis:xml-apis:jar:2.6.2 was not resolved. Dependency path: ant:ant:jar:1.6.2"
              + " (compile) > xml-apis:xml-apis:jar:2.6.2 (compile?)");
}
 
Example #3
Source File: LinkageCheckerTest.java    From cloud-opensource-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testGenerateInputClasspathFromLinkageCheckOption_recordMissingDependency()
    throws ParseException, RepositoryException, IOException {
  // tomcat-jasper has missing dependency (not optional):
  //   org.apache.tomcat:tomcat-jasper:jar:8.0.9
  //     org.eclipse.jdt.core.compiler:ecj:jar:4.4RC4 (not found in Maven central)
  LinkageCheckerArguments parsedArguments =
      LinkageCheckerArguments.readCommandLine(
          "--artifacts", "org.apache.tomcat:tomcat-jasper:8.0.9");

  ImmutableList<UnresolvableArtifactProblem> artifactProblems =
      classPathBuilder.resolve(parsedArguments.getArtifacts()).getArtifactProblems();
  Truth.assertThat(artifactProblems)
      .comparingElementsUsing(
          Correspondence.transforming(
              (UnresolvableArtifactProblem problem) -> problem.getArtifact().toString(),
              "problem with Maven coordinate"))
      .contains("org.eclipse.jdt.core.compiler:ecj:jar:4.4RC4");
}
 
Example #4
Source File: ClassDumperTest.java    From cloud-opensource-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testListClasses_unexpectedNonClassFile() throws IOException {
  // com.amazonaws:amazon-kinesis-client:1.13.0 contains an unexpected lock file
  // /unison/com/e007f77498fd27177e2ea931a06dcf50/unison/tmp/amazonaws/services/kinesis/leases/impl/LeaseTaker.class
  // https://github.com/awslabs/amazon-kinesis-client/issues/654
  List<ClassPathEntry> classPath = resolvePaths("com.amazonaws:amazon-kinesis-client:1.13.0");
  ClassDumper classDumper = ClassDumper.create(classPath);
  ClassPathEntry kinesisJar = classPath.get(0);

  // This should not raise IOException
  SymbolReferences symbolReferences = classDumper.findSymbolReferences();

  Truth.assertWithMessage("Invalid files should not stop loading valid class files")
      .that(symbolReferences.getClassFiles())
      .comparingElementsUsing(
          Correspondence.transforming(
              (ClassFile classFile) -> classFile.getClassPathEntry(), "is in the JAR file"))
      .contains(kinesisJar);
}
 
Example #5
Source File: IntentCorrespondences.java    From android-test with Apache License 2.0 6 votes vote down vote up
@Beta
public static Correspondence<Intent, Intent> all(
    final Correspondence<Intent, Intent>... correspondences) {
  StringBuilder combinedString = new StringBuilder();
  for (int i = 0; i < correspondences.length; i++) {
    combinedString.append(correspondences[i]);
    if ((i + 1) < correspondences.length) {
      combinedString.append(" and ");
    }
  }
  return Correspondence.from(
      (actual, expected) -> {
        for (Correspondence<Intent, Intent> innerCorrespondence : correspondences) {
          if (!innerCorrespondence.compare(actual, expected)) {
            return false;
          }
        }
        return true;
      },
      combinedString.toString());
}
 
Example #6
Source File: BasicAnnotationProcessorTest.java    From auto with Apache License 2.0 5 votes vote down vote up
private static <K, V>
    Correspondence<SetMultimap<K, V>, SetMultimap<K, String>> setMultimapValuesByString() {
  return Correspondence.from(
      (actual, expected) ->
          ImmutableSetMultimap.copyOf(transformValues(actual, Object::toString)).equals(expected),
      "is equivalent comparing multimap values by `toString()` to");
}
 
Example #7
Source File: DashboardTest.java    From cloud-opensource-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testLinkageReports() {
  Nodes reports = details.query("//p[@class='jar-linkage-report']");
  // appengine-api-sdk, shown as first item in linkage errors, has these errors
  Truth.assertThat(trimAndCollapseWhiteSpace(reports.get(0).getValue()))
      .isEqualTo(
          "91 target classes causing linkage errors referenced from 501 source classes.");

  Nodes dependencyPaths = details.query("//p[@class='linkage-check-dependency-paths']");
  Node dependencyPathMessageOnProblem = dependencyPaths.get(dependencyPaths.size() - 4);
  Assert.assertEquals(
      "The following paths contain com.google.guava:guava-jdk5:13.0:",
      trimAndCollapseWhiteSpace(dependencyPathMessageOnProblem.getValue()));

  Node dependencyPathMessageOnSource = dependencyPaths.get(dependencyPaths.size() - 3);
  Assert.assertEquals(
      "The following paths contain com.google.guava:guava:27.1-android:",
      trimAndCollapseWhiteSpace(dependencyPathMessageOnSource.getValue()));

  Nodes nodesWithPathsSummary = details.query("//p[@class='linkage-check-dependency-paths']");
  Truth.assertWithMessage("The dashboard should not show repetitive dependency paths")
      .that(nodesWithPathsSummary)
      .comparingElementsUsing(
          Correspondence.<Node, String>transforming(
              node -> trimAndCollapseWhiteSpace(node.getValue()), "has text"))
      .contains(
          "Dependency path 'commons-logging:commons-logging > javax.servlet:servlet-api' exists"
              + " in all 1337 dependency paths. Example path:"
              + " com.google.http-client:google-http-client:1.29.1 (compile) /"
              + " org.apache.httpcomponents:httpclient:4.5.5 (compile) /"
              + " commons-logging:commons-logging:1.2 (compile) / javax.servlet:servlet-api:2.3"
              + " (provided, optional)");
}
 
Example #8
Source File: AnnotationValuesTest.java    From auto with Apache License 2.0 5 votes vote down vote up
@Test
public void getAnnotationValues() {
  AnnotationValue value = AnnotationMirrors.getAnnotationValue(annotationMirror, "intValues");
  ImmutableList<AnnotationValue> values = AnnotationValues.getAnnotationValues(value);
  assertThat(values)
      .comparingElementsUsing(Correspondence.transforming(AnnotationValue::getValue, "has value"))
      .containsExactly(1, 2)
      .inOrder();
}
 
Example #9
Source File: AnnotationValuesTest.java    From auto with Apache License 2.0 5 votes vote down vote up
@Test
public void getTypeMirrors() {
  TypeMirror insideClassA = getTypeElement(InsideClassA.class).asType();
  TypeMirror insideClassB = getTypeElement(InsideClassB.class).asType();
  AnnotationValue value = AnnotationMirrors.getAnnotationValue(annotationMirror, "classValues");
  ImmutableList<DeclaredType> valueElements = AnnotationValues.getTypeMirrors(value);
  assertThat(valueElements)
      .comparingElementsUsing(Correspondence.from(types::isSameType, "has Same Type"))
      .containsExactly(insideClassA, insideClassB)
      .inOrder();
}
 
Example #10
Source File: FileInfoTest.java    From hadoop-connectors with Apache License 2.0 5 votes vote down vote up
@Test
public void fromItemInfo() throws Exception {
  GoogleCloudStorageItemInfo itemInfo =
      new GoogleCloudStorageItemInfo(
          new StorageResourceId("foo-test-bucket", "bar/test/object"),
          /* creationTime= */ 10L,
          /* modificationTime= */ 15L,
          /* size= */ 200L,
          "us-east1",
          "nearline",
          "text/plain",
          /* contentEncoding= */ "lzma",
          /* metadata= */ ImmutableMap.of("foo-meta", new byte[] {5, 66, 56}),
          /* contentGeneration= */ 312432L,
          /* metaGeneration= */ 2L);

  FileInfo fileInfo = FileInfo.fromItemInfo(itemInfo);

  assertThat(fileInfo.getPath()).isEqualTo(new URI("gs://foo-test-bucket/bar/test/object"));
  assertThat(fileInfo.getCreationTime()).isEqualTo(10L);
  assertThat(fileInfo.getModificationTime()).isEqualTo(15L);
  assertThat(fileInfo.getSize()).isEqualTo(200);
  assertThat(fileInfo.getAttributes())
      .<byte[], byte[]>comparingValuesUsing(Correspondence.from(Arrays::equals, "Arrays.equals"))
      .containsExactly("foo-meta", new byte[] {5, 66, 56});
  assertThat(fileInfo.getItemInfo()).isEqualTo(itemInfo);
}
 
Example #11
Source File: LocationCorrespondences.java    From android-test with Apache License 2.0 5 votes vote down vote up
public static Correspondence<Location, Location> at() {
  return Correspondence.from(
      (actual, expected) ->
          actual.getLatitude() == expected.getLatitude()
              && actual.getLongitude() == expected.getLongitude(),
      "has lat/lon at");
}
 
Example #12
Source File: LinkageCheckerArgumentsTest.java    From cloud-opensource-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testReadCommandLine_jarFileList_relativePath() throws ParseException, IOException {

  LinkageCheckerArguments parsedArguments =
      LinkageCheckerArguments.readCommandLine("--jars", "dir1/foo.jar,dir2/bar.jar,baz.jar");
  List<ClassPathEntry> inputClasspath = parsedArguments.getJarFiles();

  Truth.assertThat(inputClasspath)
      .comparingElementsUsing(
          Correspondence.transforming(ClassPathEntry::getJar, "has path equals to"))
      .containsExactly(
          Paths.get("dir1/foo.jar").toAbsolutePath(),
          Paths.get("dir2/bar.jar").toAbsolutePath(),
          Paths.get("baz.jar").toAbsolutePath());
}
 
Example #13
Source File: LinkageCheckerArgumentsTest.java    From cloud-opensource-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testReadCommandLine_jarFileList_absolutePath() throws ParseException, IOException {
  LinkageCheckerArguments parsedArguments =
      LinkageCheckerArguments.readCommandLine(
          "-j", "/foo/bar/A.jar,/foo/bar/B.jar,/foo/bar/C.jar");

  Truth.assertThat(parsedArguments.getJarFiles())
      .comparingElementsUsing(
          Correspondence.transforming(ClassPathEntry::getJar, "has path equals to"))
      // Using Path::toString to work in Windows
      .containsExactly(
          Paths.get("/foo/bar/A.jar").toAbsolutePath(),
          Paths.get("/foo/bar/B.jar").toAbsolutePath(),
          Paths.get("/foo/bar/C.jar").toAbsolutePath());
}
 
Example #14
Source File: ClassDumperTest.java    From cloud-opensource-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testFindSymbolReferences_catchClassFormatException() throws IOException {
  List<ClassPathEntry> classPath = resolvePaths("com.ibm.icu:icu4j:2.6.1");
  ClassDumper classDumper = ClassDumper.create(classPath);

  // This should not throw ClassFormatException
  SymbolReferences symbolReferences = classDumper.findSymbolReferences();
  Truth.assertThat(symbolReferences.getClassFiles())
      .comparingElementsUsing(
          Correspondence.transforming(
              (ClassFile classFile) -> classFile.getBinaryName(), "has class name"))
      .contains("com.ibm.icu.util.DateRule");
}
 
Example #15
Source File: LinkageCheckerTest.java    From cloud-opensource-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testFindSymbolProblems_grpcAndGuava() throws IOException {
  // This pair of the library generates NoSuchMethodError at runtime.
  // https://github.com/GoogleCloudPlatform/cloud-opensource-java/tree/master/example-problems/no-such-method-error-signature-mismatch
  ImmutableList<ClassPathEntry> jars =
      resolvePaths("io.grpc:grpc-core:1.17.0", "com.google.guava:guava:20.0");

  LinkageChecker linkageChecker = LinkageChecker.create(jars);
  ImmutableSetMultimap<SymbolProblem, ClassFile> problems = linkageChecker.findSymbolProblems();

  Truth.assertThat(problems.values())
      .comparingElementsUsing(
          Correspondence.transforming(ClassFile::getBinaryName, "has class binary name"))
      .contains("io.grpc.internal.DnsNameResolver");
}
 
Example #16
Source File: LinkageCheckerTest.java    From cloud-opensource-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testFindSymbolProblems_blockHoundClasses() throws IOException {
  // BlockHound is a tool to detect blocking method calls in nonblocking frameworks.
  // In our BOM dashboard, it appears in dependency path io.grpc:grpc-netty:1.28.0 (compile)
  //   / io.netty:netty-codec-http2:4.1.45.Final (compile)
  //   / io.netty:netty-common:4.1.45.Final (compile)
  //   / io.projectreactor.tools:blockhound:1.0.1.RELEASE (compile, optional)
  ImmutableList<ClassPathEntry> jars =
      resolvePaths("io.projectreactor.tools:blockhound:1.0.1.RELEASE");

  LinkageChecker linkageChecker = LinkageChecker.create(jars);

  ImmutableSetMultimap<SymbolProblem, ClassFile> symbolProblems =
      linkageChecker.findSymbolProblems();

  // BlockHound integrates with Reactor and RxJava if their classes are available in class path by
  // checking ClassNotFoundException. Therefore LinkageMonitor should not report the references to
  // missing classes from the integration classes.
  ImmutableList<String> unexpectedClasses =
      ImmutableList.of(
          // The following two catch ClassNotFoundException
          "reactor.blockhound.integration.RxJava2Integration",
          "reactor.blockhound.integration.ReactorIntegration",
          // This class is in exclusion rule
          "reactor.blockhound.shaded.net.bytebuddy.agent.VirtualMachine");

  for (String unexpectedSourceClass : unexpectedClasses) {
    Truth.assertThat(symbolProblems.values())
        .comparingElementsUsing(
            Correspondence.transforming(
                (ClassFile sourceClass) -> sourceClass.getBinaryName(), "has source class name"))
        .doesNotContain(unexpectedSourceClass);
  }
}
 
Example #17
Source File: LinkageCheckerTest.java    From cloud-opensource-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testFindSymbolProblems_unimplementedAbstractMethod() throws IOException {
  // Non-abstract NioEventLoopGroup class extends MultithreadEventLoopGroup.
  // Abstract MultithreadEventLoopGroup class extends MultithreadEventExecutorGroup
  // Abstract MultithreadEventExecutorGroup class has abstract newChild method.
  // Netty version discrepancy between 4.0 and 4.1 causes AbstractMethodError.
  // https://github.com/netty/netty/issues/7675
  ImmutableList<ClassPathEntry> nettyTransportJars4_0 =
      resolvePaths("io.netty:netty-transport:jar:4.0.37.Final");
  ImmutableList<ClassPathEntry> nettyCommonJars4_1 =
      resolvePaths("io.netty:netty-common:jar:4.1.16.Final");

  ImmutableList<ClassPathEntry> jars =
      ImmutableList.<ClassPathEntry>builder()
          .addAll(nettyCommonJars4_1)
          .addAll(nettyTransportJars4_0)
          .build();
  LinkageChecker linkageChecker = LinkageChecker.create(jars);

  ImmutableSetMultimap<SymbolProblem, ClassFile> symbolProblems =
      linkageChecker.findSymbolProblems();

  MethodSymbol expectedMethodSymbol =
      new MethodSymbol(
          "io.netty.channel.nio.NioEventLoopGroup",
          "newChild",
          "(Ljava/util/concurrent/Executor;[Ljava/lang/Object;)Lio/netty/util/concurrent/EventExecutor;",
          false);

  Truth.assertThat(symbolProblems.keySet())
      .comparingElementsUsing(Correspondence.transforming(SymbolProblem::getSymbol, "has symbol"))
      .contains(expectedMethodSymbol);
}
 
Example #18
Source File: DependencyGraphIntegrationTest.java    From cloud-opensource-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testFindUpdates() {

  DefaultArtifact core =
      new DefaultArtifact("com.google.cloud:google-cloud-core:1.37.1");

  DependencyGraph graph =
      dependencyGraphBuilder
          .buildFullDependencyGraph(ImmutableList.of(core));
  List<Update> updates = graph.findUpdates();

  // Order of updates are not important
  Truth.assertThat(updates)
      .comparingElementsUsing(Correspondence.transforming(Update::toString, "has message"))
      .containsExactly(
          "com.google.api.grpc:proto-google-iam-v1:0.12.0 needs to "
              + "upgrade com.google.api.grpc:proto-google-common-protos:1.11.0 to 1.12.0",
          "com.google.api.grpc:proto-google-iam-v1:0.12.0 needs to "
              + "upgrade com.google.api:api-common:1.5.0 to 1.6.0",
          "com.google.guava:guava:20.0 needs to "
              + "upgrade com.google.code.findbugs:jsr305:1.3.9 to 3.0.2",
          "com.google.api:api-common:1.6.0 needs to "
              + "upgrade com.google.code.findbugs:jsr305:3.0.0 to 3.0.2",
          "com.google.api:api-common:1.6.0 needs to "
              + "upgrade com.google.guava:guava:19.0 to 20.0",
          "com.google.protobuf:protobuf-java-util:3.6.0 needs to "
              + "upgrade com.google.guava:guava:19.0 to 20.0",
          "com.google.auth:google-auth-library-oauth2-http:0.9.1 needs to "
              + "upgrade com.google.guava:guava:19.0 to 20.0",
          "com.google.auth:google-auth-library-oauth2-http:0.9.1 needs to "
              + "upgrade com.google.http-client:google-http-client:1.19.0 to 1.23.0",
          "com.google.http-client:google-http-client-jackson2:1.19.0 needs to "
              + "upgrade com.google.http-client:google-http-client:1.19.0 to 1.23.0",
          "com.google.api.grpc:proto-google-common-protos:1.12.0 needs to "
              + "upgrade com.google.protobuf:protobuf-java:3.5.1 to 3.6.0",
          "com.google.api.grpc:proto-google-iam-v1:0.12.0 needs to "
              + "upgrade com.google.protobuf:protobuf-java:3.5.1 to 3.6.0",
          "org.apache.httpcomponents:httpclient:4.0.1 needs to "
              + "upgrade commons-codec:commons-codec:1.3 to 1.6");
}
 
Example #19
Source File: DependencyGraphBuilderTest.java    From cloud-opensource-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testAlts_exclusionElements() {
  Correspondence<DependencyPath, String> dependencyPathToString =
      Correspondence.transforming(DependencyPath::toString, "has string representation");

  DefaultArtifact artifact = new DefaultArtifact("io.grpc:grpc-alts:jar:1.27.0");
  DependencyGraph graph =
      dependencyGraphBuilder
          .buildFullDependencyGraph(ImmutableList.of(artifact));
  List<DependencyPath> dependencyPaths = graph.list();

  String expectedDependencyPathForOpencensusContribHttpUtil =
      "io.grpc:grpc-alts:jar:1.27.0 " // this has exclusion of Guava
          + "/ com.google.auth:google-auth-library-oauth2-http:0.19.0 (compile) "
          + "/ com.google.http-client:google-http-client:1.33.0 (compile) "
          + "/ io.opencensus:opencensus-contrib-http-util:0.24.0 (compile)";

  Truth.assertThat(dependencyPaths)
      .comparingElementsUsing(dependencyPathToString)
      .contains(expectedDependencyPathForOpencensusContribHttpUtil);

  String unexpectedDependencyPathForGuava =
      expectedDependencyPathForOpencensusContribHttpUtil
          + " / com.google.guava:guava:jar:26.0-android (compile)";
  Truth.assertThat(dependencyPaths)
      .comparingElementsUsing(dependencyPathToString)
      .doesNotContain(unexpectedDependencyPathForGuava);
}
 
Example #20
Source File: BundleModuleMergerTest.java    From bundletool with Apache License 2.0 4 votes vote down vote up
private static Correspondence<BundleModuleName, String> equalsBundleModuleName() {
  return Correspondence.from(
      (BundleModuleName bundleModuleName, String moduleName) ->
          bundleModuleName.getName().equals(moduleName),
      "equals");
}
 
Example #21
Source File: TranspilerTester.java    From j2cl with Apache License 2.0 4 votes vote down vote up
public TranspileResult assertErrorsContainsSnippets(String... snippets) {
  assertThat(getProblems().getErrors())
      .comparingElementsUsing(Correspondence.from(String::contains, "contained within"))
      .containsAtLeastElementsIn(Arrays.asList(snippets));
  return this;
}
 
Example #22
Source File: IntentCorrespondences.java    From android-test with Apache License 2.0 4 votes vote down vote up
public static Correspondence<Intent, Intent> action() {
  return Correspondence.from(
      (actual, expected) -> Objects.equal(actual.getAction(), expected.getAction()),
      "has getAction() equal to");
}
 
Example #23
Source File: IntentCorrespondences.java    From android-test with Apache License 2.0 4 votes vote down vote up
public static Correspondence<Intent, Intent> data() {
  return Correspondence.from(
      (actual, expected) -> Objects.equal(actual.getData(), expected.getData()),
      "has getData() equal to");
}
 
Example #24
Source File: LocationCorrespondences.java    From android-test with Apache License 2.0 4 votes vote down vote up
public static Correspondence<Location, Location> equality() {
  return Correspondence.from(
      (actual, expected) -> {
        if (actual == expected) {
          return true;
        }
        if (actual == null || expected == null) {
          return false;
        }
        if (!Objects.equal(actual.getProvider(), expected.getProvider())) {
          return false;
        }
        if (actual.getTime() != expected.getTime()) {
          return false;
        }
        if (Build.VERSION.SDK_INT >= VERSION_CODES.JELLY_BEAN_MR1) {
          if (actual.getElapsedRealtimeNanos() != expected.getElapsedRealtimeNanos()) {
            return false;
          }
        }
        if (actual.getLatitude() != expected.getLatitude()) {
          return false;
        }
        if (actual.getLongitude() != expected.getLongitude()) {
          return false;
        }
        if (actual.getAltitude() != expected.getAltitude()) {
          return false;
        }
        if (actual.getSpeed() != expected.getSpeed()) {
          return false;
        }
        if (actual.getBearing() != expected.getBearing()) {
          return false;
        }
        if (actual.getAccuracy() != expected.getAccuracy()) {
          return false;
        }
        if (Build.VERSION.SDK_INT >= VERSION_CODES.O) {
          if (actual.getVerticalAccuracyMeters() != expected.getVerticalAccuracyMeters()) {
            return false;
          }
          if (actual.getSpeedAccuracyMetersPerSecond()
              != expected.getSpeedAccuracyMetersPerSecond()) {
            return false;
          }
          if (actual.getBearingAccuracyDegrees() != expected.getBearingAccuracyDegrees()) {
            return false;
          }
        }
        return true;
      },
      "is equal to");
}
 
Example #25
Source File: LocationCorrespondences.java    From android-test with Apache License 2.0 4 votes vote down vote up
public static Correspondence<Location, Location> nearby(float distanceM) {
  return Correspondence.from(
      (actual, expected) -> actual.distanceTo(expected) <= distanceM, "has lat/lon near");
}
 
Example #26
Source File: OptionsDataTest.java    From bazel with Apache License 2.0 4 votes vote down vote up
@Test
public void optionsDefinitionsAreSharedBetweenOptionsBases() throws Exception {
  Class<FieldNamesDifferOptions> class1 = FieldNamesDifferOptions.class;
  Class<EndOfAlphabetOptions> class2 = EndOfAlphabetOptions.class;
  Class<ReverseOrderedOptions> class3 = ReverseOrderedOptions.class;

  // Construct the definitions once and accumulate them so we can test that these are not
  // recomputed during the construction of the options data.
  ImmutableList<OptionDefinition> optionDefinitions =
      new ImmutableList.Builder<OptionDefinition>()
          .addAll(OptionsData.getAllOptionDefinitionsForClass(class1))
          .addAll(OptionsData.getAllOptionDefinitionsForClass(class2))
          .addAll(OptionsData.getAllOptionDefinitionsForClass(class3))
          .build();

  // Construct the data all together.
  IsolatedOptionsData data = construct(class1, class2, class3);
  ArrayList<OptionDefinition> optionDefinitionsFromData =
      new ArrayList<>(optionDefinitions.size());
  data.getAllOptionDefinitions()
      .forEach(entry -> optionDefinitionsFromData.add(entry.getValue()));

  Correspondence<Object, Object> referenceEquality =
      Correspondence.from((obj1, obj2) -> obj1 == obj2, "is the same object as");
  assertThat(optionDefinitionsFromData)
      .comparingElementsUsing(referenceEquality)
      .containsAtLeastElementsIn(optionDefinitions);

  // Construct options data for each class separately, and check again.
  IsolatedOptionsData data1 = construct(class1);
  IsolatedOptionsData data2 = construct(class2);
  IsolatedOptionsData data3 = construct(class3);
  ArrayList<OptionDefinition> optionDefinitionsFromGroupedData =
      new ArrayList<>(optionDefinitions.size());
  data1
      .getAllOptionDefinitions()
      .forEach(entry -> optionDefinitionsFromGroupedData.add(entry.getValue()));
  data2
      .getAllOptionDefinitions()
      .forEach(entry -> optionDefinitionsFromGroupedData.add(entry.getValue()));
  data3
      .getAllOptionDefinitions()
      .forEach(entry -> optionDefinitionsFromGroupedData.add(entry.getValue()));

  assertThat(optionDefinitionsFromGroupedData)
      .comparingElementsUsing(referenceEquality)
      .containsAtLeastElementsIn(optionDefinitions);
}
 
Example #27
Source File: StarlarkIntegrationTest.java    From bazel with Apache License 2.0 4 votes vote down vote up
@Test
public void testTransitiveAnalysisFailureInfo() throws Exception {
  scratch.file(
      "test/extension.bzl",
      "def custom_rule_impl(ctx):",
      "   fail('This Is My Failure Message')",
      "",
      "custom_rule = rule(implementation = custom_rule_impl)",
      "",
      "def depending_rule_impl(ctx):",
      "   return []",
      "",
      "depending_rule = rule(implementation = depending_rule_impl,",
      "     attrs = {'deps' : attr.label_list()})");

  scratch.file(
      "test/BUILD",
      "load('//test:extension.bzl', 'custom_rule', 'depending_rule')",
      "",
      "custom_rule(name = 'one')",
      "custom_rule(name = 'two')",
      "depending_rule(name = 'failures_are_direct_deps',",
      "    deps = [':one', ':two'])",
      "depending_rule(name = 'failures_are_indirect_deps',",
      "    deps = [':failures_are_direct_deps'])");

  useConfiguration("--allow_analysis_failures=true");

  ConfiguredTarget target = getConfiguredTarget("//test:failures_are_indirect_deps");
  AnalysisFailureInfo info =
      (AnalysisFailureInfo) target.get(AnalysisFailureInfo.STARLARK_CONSTRUCTOR.getKey());

  Correspondence<AnalysisFailure, AnalysisFailure> correspondence =
      Correspondence.from(
          (actual, expected) ->
              actual.getLabel().equals(expected.getLabel())
                  && actual.getMessage().contains(expected.getMessage()),
          "is equivalent to");

  AnalysisFailure expectedOne =
      new AnalysisFailure(
          Label.parseAbsoluteUnchecked("//test:one"), "This Is My Failure Message");
  AnalysisFailure expectedTwo =
      new AnalysisFailure(
          Label.parseAbsoluteUnchecked("//test:two"), "This Is My Failure Message");

  assertThat(info.getCauses().getSet(AnalysisFailure.class).toList())
      .comparingElementsUsing(correspondence)
      .containsExactly(expectedOne, expectedTwo);
}