com.google.common.base.VerifyException Java Examples

The following examples show how to use com.google.common.base.VerifyException. 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: DnsUpdateWriterTest.java    From nomulus with Apache License 2.0 7 votes vote down vote up
@Test
@SuppressWarnings("AssertThrowsMultipleStatements")
public void testPublishDomainFails_whenDnsUpdateReturnsError() throws Exception {
  DomainBase domain =
      persistActiveDomain("example.tld")
          .asBuilder()
          .setNameservers(ImmutableSet.of(persistActiveHost("ns1.example.tld").createVKey()))
          .build();
  persistResource(domain);
  when(mockResolver.send(any(Message.class))).thenReturn(messageWithResponseCode(Rcode.SERVFAIL));
  VerifyException thrown =
      assertThrows(
          VerifyException.class,
          () -> {
            writer.publishDomain("example.tld");
            writer.commit();
          });
  assertThat(thrown).hasMessageThat().contains("SERVFAIL");
}
 
Example #2
Source File: PgpHelper.java    From nomulus with Apache License 2.0 6 votes vote down vote up
/**
 * Same as {@link #lookupPublicKey} but also retrieves the associated private key.
 *
 * @throws VerifyException if either keys couldn't be found.
 * @see #lookupPublicKey
 */
public static PGPKeyPair lookupKeyPair(
    PGPPublicKeyRingCollection publics,
    PGPSecretKeyRingCollection privates,
    String query,
    KeyRequirement want) {
  PGPPublicKey publicKey = lookupPublicKey(publics, query, want);
  PGPPrivateKey privateKey;
  try {
    PGPSecretKey secret = verifyNotNull(privates.getSecretKey(publicKey.getKeyID()),
        "Keyring missing private key associated with public key id: %x (query '%s')",
        publicKey.getKeyID(), query);
    // We do not support putting a password on the private key so we're just going to
    // put char[0] here.
    privateKey = secret.extractPrivateKey(
        new BcPBESecretKeyDecryptorBuilder(new BcPGPDigestCalculatorProvider())
            .build(new char[0]));
  } catch (PGPException e) {
    throw new VerifyException(String.format("Could not load PGP private key for: %s", query), e);
  }
  return new PGPKeyPair(publicKey, privateKey);
}
 
Example #3
Source File: ReflectionWindowFunctionSupplier.java    From presto with Apache License 2.0 6 votes vote down vote up
@Override
protected T newWindowFunction(List<Integer> inputs, boolean ignoreNulls, List<LambdaProvider> lambdaProviders)
{
    try {
        switch (constructorType) {
            case NO_INPUTS:
                return constructor.newInstance();
            case INPUTS:
                return constructor.newInstance(inputs);
            case INPUTS_IGNORE_NULLS:
                return constructor.newInstance(inputs, ignoreNulls);
            default:
                throw new VerifyException("Unhandled constructor type: " + constructorType);
        }
    }
    catch (ReflectiveOperationException e) {
        throw new RuntimeException(e);
    }
}
 
Example #4
Source File: FilterStatsCalculator.java    From presto with Apache License 2.0 6 votes vote down vote up
private Type getType(Expression expression)
{
    if (expression instanceof SymbolReference) {
        Symbol symbol = Symbol.from(expression);
        return requireNonNull(types.get(symbol), () -> format("No type for symbol %s", symbol));
    }

    ExpressionAnalyzer expressionAnalyzer = ExpressionAnalyzer.createWithoutSubqueries(
            metadata,
            new AllowAllAccessControl(),
            session,
            types,
            ImmutableMap.of(),
            // At this stage, there should be no subqueries in the plan.
            node -> new VerifyException("Unexpected subquery"),
            WarningCollector.NOOP,
            false);
    return expressionAnalyzer.analyze(expression, Scope.create());
}
 
Example #5
Source File: VersionUniverseVersionSelector.java    From buck with Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
protected Optional<Map.Entry<String, VersionUniverse>> getVersionUniverse(TargetNode<?> root) {
  Optional<String> universeName = getVersionUniverseName(root);
  if (!universeName.isPresent() && !universes.isEmpty()) {
    return Optional.of(Iterables.get(universes.entrySet(), 0));
  }
  if (!universeName.isPresent()) {
    return Optional.empty();
  }
  VersionUniverse universe = universes.get(universeName.get());
  if (universe == null) {
    throw new VerifyException(
        String.format(
            "%s: unknown version universe \"%s\"", root.getBuildTarget(), universeName.get()));
  }
  return Optional.of(new AbstractMap.SimpleEntry<>(universeName.get(), universe));
}
 
Example #6
Source File: RowExpressionCompiler.java    From presto with Apache License 2.0 6 votes vote down vote up
@Override
public BytecodeNode visitLambda(LambdaDefinitionExpression lambda, Context context)
{
    checkState(compiledLambdaMap.containsKey(lambda), "lambda expressions map does not contain this lambda definition");
    if (!context.lambdaInterface.get().isAnnotationPresent(FunctionalInterface.class)) {
        // lambdaInterface is checked to be annotated with FunctionalInterface when generating ScalarFunctionImplementation
        throw new VerifyException("lambda should be generated as class annotated with FunctionalInterface");
    }

    BytecodeGeneratorContext generatorContext = new BytecodeGeneratorContext(
            RowExpressionCompiler.this,
            context.getScope(),
            callSiteBinder,
            cachedInstanceBinder,
            metadata);

    return generateLambda(
            generatorContext,
            ImmutableList.of(),
            compiledLambdaMap.get(lambda),
            context.getLambdaInterface().get());
}
 
Example #7
Source File: ServiceConfigUtil.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
private static Set<Status.Code> getStatusCodesFromList(List<?> statuses) {
  EnumSet<Status.Code> codes = EnumSet.noneOf(Status.Code.class);
  for (Object status : statuses) {
    Status.Code code;
    if (status instanceof Double) {
      Double statusD = (Double) status;
      int codeValue = statusD.intValue();
      verify((double) codeValue == statusD, "Status code %s is not integral", status);
      code = Status.fromCodeValue(codeValue).getCode();
      verify(code.value() == statusD.intValue(), "Status code %s is not valid", status);
    } else if (status instanceof String) {
      try {
        code = Status.Code.valueOf((String) status);
      } catch (IllegalArgumentException iae) {
        throw new VerifyException("Status code " + status + " is not valid", iae);
      }
    } else {
      throw new VerifyException(
          "Can not convert status code " + status + " to Status.Code, because its type is "
              + status.getClass());
    }
    codes.add(code);
  }
  return Collections.unmodifiableSet(codes);
}
 
Example #8
Source File: TestDynamicFiltersChecker.java    From presto with Apache License 2.0 6 votes vote down vote up
@Test(expectedExceptions = VerifyException.class, expectedExceptionsMessageRegExp = "Dynamic filters \\[DF\\] present in join were not fully consumed by it's probe side.")
public void testUnconsumedDynamicFilterInJoin()
{
    PlanNode root = builder.join(
            INNER,
            builder.filter(expression("ORDERS_OK > 0"), ordersTableScanNode),
            lineitemTableScanNode,
            ImmutableList.of(new JoinNode.EquiJoinClause(ordersOrderKeySymbol, lineitemOrderKeySymbol)),
            ImmutableList.of(ordersOrderKeySymbol),
            ImmutableList.of(),
            Optional.empty(),
            Optional.empty(),
            Optional.empty(),
            ImmutableMap.of(new DynamicFilterId("DF"), lineitemOrderKeySymbol));
    validatePlan(root);
}
 
Example #9
Source File: TestDynamicFiltersChecker.java    From presto with Apache License 2.0 6 votes vote down vote up
@Test(expectedExceptions = VerifyException.class, expectedExceptionsMessageRegExp = "Dynamic filters \\[DF\\] present in join were consumed by it's build side.")
public void testDynamicFilterConsumedOnBuildSide()
{
    PlanNode root = builder.join(
            INNER,
            builder.filter(
                    createDynamicFilterExpression(metadata, new DynamicFilterId("DF"), BIGINT, ordersOrderKeySymbol.toSymbolReference()),
                    ordersTableScanNode),
            builder.filter(
                    createDynamicFilterExpression(metadata, new DynamicFilterId("DF"), BIGINT, ordersOrderKeySymbol.toSymbolReference()),
                    lineitemTableScanNode),
            ImmutableList.of(new JoinNode.EquiJoinClause(ordersOrderKeySymbol, lineitemOrderKeySymbol)),
            ImmutableList.of(ordersOrderKeySymbol),
            ImmutableList.of(),
            Optional.empty(),
            Optional.empty(),
            Optional.empty(),
            ImmutableMap.of(new DynamicFilterId("DF"), lineitemOrderKeySymbol));
    validatePlan(root);
}
 
Example #10
Source File: TestDynamicFiltersChecker.java    From presto with Apache License 2.0 6 votes vote down vote up
@Test(expectedExceptions = VerifyException.class, expectedExceptionsMessageRegExp = "All consumed dynamic filters could not be matched with a join.")
public void testUnmatchedDynamicFilter()
{
    PlanNode root = builder.output(
            ImmutableList.of(),
            ImmutableList.of(),
            builder.join(
                    INNER,
                    ordersTableScanNode,
                    builder.filter(
                            combineConjuncts(
                                    metadata,
                                    expression("LINEITEM_OK > 0"),
                                    createDynamicFilterExpression(metadata, new DynamicFilterId("DF"), BIGINT, lineitemOrderKeySymbol.toSymbolReference())),
                            lineitemTableScanNode),
                    ImmutableList.of(new JoinNode.EquiJoinClause(ordersOrderKeySymbol, lineitemOrderKeySymbol)),
                    ImmutableList.of(ordersOrderKeySymbol),
                    ImmutableList.of(),
                    Optional.empty(),
                    Optional.empty(),
                    Optional.empty(),
                    ImmutableMap.of()));
    validatePlan(root);
}
 
Example #11
Source File: TestDynamicFiltersChecker.java    From presto with Apache License 2.0 6 votes vote down vote up
@Test(expectedExceptions = VerifyException.class, expectedExceptionsMessageRegExp = "Dynamic filters \\[Descriptor\\{id=DF, input=\"ORDERS_OK\"\\}\\] present in filter predicate whose source is not a table scan.")
public void testDynamicFilterNotAboveTableScan()
{
    PlanNode root = builder.output(
            ImmutableList.of(),
            ImmutableList.of(),
            builder.join(
                    INNER,
                    builder.filter(
                            combineConjuncts(
                                    metadata,
                                    expression("LINEITEM_OK > 0"),
                                    createDynamicFilterExpression(metadata, new DynamicFilterId("DF"), BIGINT, ordersOrderKeySymbol.toSymbolReference())),
                            builder.values(lineitemOrderKeySymbol)),
                    ordersTableScanNode,
                    ImmutableList.of(new JoinNode.EquiJoinClause(lineitemOrderKeySymbol, ordersOrderKeySymbol)),
                    ImmutableList.of(),
                    ImmutableList.of(),
                    Optional.empty(),
                    Optional.empty(),
                    Optional.empty(),
                    ImmutableMap.of(new DynamicFilterId("DF"), ordersOrderKeySymbol)));
    validatePlan(root);
}
 
Example #12
Source File: HivePartitionManager.java    From presto with Apache License 2.0 6 votes vote down vote up
public HivePartitionResult getPartitions(ConnectorTableHandle tableHandle, List<List<String>> partitionValuesList)
{
    HiveTableHandle hiveTableHandle = (HiveTableHandle) tableHandle;
    SchemaTableName tableName = hiveTableHandle.getSchemaTableName();
    List<HiveColumnHandle> partitionColumns = hiveTableHandle.getPartitionColumns();
    Optional<HiveBucketHandle> bucketHandle = hiveTableHandle.getBucketHandle();

    List<String> partitionColumnNames = partitionColumns.stream()
            .map(HiveColumnHandle::getName)
            .collect(toImmutableList());

    List<Type> partitionColumnTypes = partitionColumns.stream()
            .map(HiveColumnHandle::getType)
            .collect(toImmutableList());

    List<HivePartition> partitionList = partitionValuesList.stream()
            .map(partitionValues -> toPartitionName(partitionColumnNames, partitionValues))
            .map(partitionName -> parseValuesAndFilterPartition(tableName, partitionName, partitionColumns, partitionColumnTypes, TupleDomain.all(), value -> true))
            .map(partition -> partition.orElseThrow(() -> new VerifyException("partition must exist")))
            .collect(toImmutableList());

    return new HivePartitionResult(partitionColumns, partitionList, TupleDomain.all(), TupleDomain.all(), TupleDomain.all(), bucketHandle, Optional.empty());
}
 
Example #13
Source File: ClassDumperTest.java    From cloud-opensource-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testIsUnusedClassSymbolReference_classSymbolReferenceNotFound()
    throws IOException, URISyntaxException {
  ClassDumper classDumper =
      ClassDumper.create(
          ImmutableList.of(
              classPathEntryOfResource("testdata/conscrypt-openjdk-uber-1.4.2.jar")));

  try {
    classDumper.isUnusedClassSymbolReference(
        "org.conscrypt.Conscrypt", new ClassSymbol("dummy.NoSuchClass"));

    Assert.fail("It should throw VerifyException when it cannot find a class symbol reference");
  } catch (VerifyException ex) {
    // pass
    Truth.assertThat(ex)
        .hasMessageThat()
        .isEqualTo(
            "When checking a class reference from org.conscrypt.Conscrypt to dummy.NoSuchClass,"
                + " the reference to the target class is no longer found in the source class's"
                + " constant pool.");
  }
}
 
Example #14
Source File: JaxenTest.java    From yangtools with Eclipse Public License 1.0 6 votes vote down vote up
@Test(expected = UnresolvableException.class)
public void testYangFunctionContext() throws UnresolvableException, FunctionCallException {
    final YangFunctionContext yangFun = YangFunctionContext.getInstance();
    assertNotNull(yangFun);
    final Function function = yangFun.getFunction("urn:opendaylight.test2", null, "current");
    assertNotNull(function);

    try {
        final Context context = mock(Context.class);
        final ArrayList<Object> list = new ArrayList<>();
        function.call(context, list);
        fail();
    } catch (VerifyException e) {
        // Expected
    }

    yangFun.getFunction("urn:opendaylight.test2", "test2", "root");
}
 
Example #15
Source File: PreferenceEntityAnnotatedClass.java    From PreferenceRoom with Apache License 2.0 6 votes vote down vote up
private void checkOverrideMethods() {
  annotatedElement.getEnclosedElements().stream()
      .filter(element -> element instanceof ExecutableElement)
      .map(element -> (ExecutableElement) element)
      .forEach(
          method -> {
            if (keyNameFields.contains(
                method.getSimpleName().toString().replace(SETTER_PREFIX, "")))
              throw new VerifyException(
                  getMethodNameVerifyErrorMessage(method.getSimpleName().toString()));
            else if (keyNameFields.contains(
                method.getSimpleName().toString().replace(GETTER_PREFIX, "")))
              throw new VerifyException(
                  getMethodNameVerifyErrorMessage(method.getSimpleName().toString()));
            else if (keyNameFields.contains(
                method.getSimpleName().toString().replace(HAS_PREFIX, "")))
              throw new VerifyException(
                  getMethodNameVerifyErrorMessage(method.getSimpleName().toString()));
            else if (keyNameFields.contains(
                method.getSimpleName().toString().replace(REMOVE_PREFIX, "")))
              throw new VerifyException(
                  getMethodNameVerifyErrorMessage(method.getSimpleName().toString()));
          });
}
 
Example #16
Source File: DnsUpdateWriterTest.java    From nomulus with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("AssertThrowsMultipleStatements")
public void testPublishHostFails_whenDnsUpdateReturnsError() throws Exception {
  HostResource host =
      persistActiveSubordinateHost("ns1.example.tld", persistActiveDomain("example.tld"))
          .asBuilder()
          .setInetAddresses(ImmutableSet.of(InetAddresses.forString("10.0.0.1")))
          .build();
  persistResource(host);
  when(mockResolver.send(any(Message.class))).thenReturn(messageWithResponseCode(Rcode.SERVFAIL));
  VerifyException thrown =
      assertThrows(
          VerifyException.class,
          () -> {
            writer.publishHost("ns1.example.tld");
            writer.commit();
          });
  assertThat(thrown).hasMessageThat().contains("SERVFAIL");
}
 
Example #17
Source File: PreferenceRoomProcessor.java    From PreferenceRoom with Apache License 2.0 6 votes vote down vote up
private void processInjector(PreferenceComponentAnnotatedClass annotatedClass)
    throws VerifyException {
  try {
    annotatedClass.annotatedElement.getEnclosedElements().stream()
        .filter(element -> element instanceof ExecutableElement)
        .map(element -> (ExecutableElement) element)
        .filter(method -> method.getParameters().size() == 1)
        .forEach(
            method -> {
              MethodSpec methodSpec = MethodSpec.overriding(method).build();
              ParameterSpec parameterSpec = methodSpec.parameters.get(0);
              TypeElement injectedElement =
                  processingEnv.getElementUtils().getTypeElement(parameterSpec.type.toString());
              generateProcessInjector(annotatedClass, injectedElement);
            });
  } catch (VerifyException e) {
    showErrorLog(e.getMessage(), annotatedClass.annotatedElement);
    e.printStackTrace();
  }
}
 
Example #18
Source File: RequestModule.java    From nomulus with Apache License 2.0 6 votes vote down vote up
@Provides
@JsonPayload
@SuppressWarnings("unchecked")
static Map<String, Object> provideJsonPayload(
    @Header("Content-Type") MediaType contentType,
    @Payload String payload) {
  if (!JSON_UTF_8.is(contentType.withCharset(UTF_8))) {
    throw new UnsupportedMediaTypeException(
        String.format("Expected %s Content-Type", JSON_UTF_8.withoutParameters()));
  }
  try {
    return (Map<String, Object>) JSONValue.parseWithException(payload);
  } catch (ParseException e) {
    throw new BadRequestException(
        "Malformed JSON", new VerifyException("Malformed JSON:\n" + payload, e));
  }
}
 
Example #19
Source File: PgpHelper.java    From nomulus with Apache License 2.0 6 votes vote down vote up
/**
 * Search for public key on keyring based on a substring (like an email address).
 *
 * @throws VerifyException if the key couldn't be found.
 * @see #lookupKeyPair
 */
public static PGPPublicKey lookupPublicKey(
    PGPPublicKeyRingCollection keyring, String query, KeyRequirement want) {
  try {
    Iterator<PGPPublicKeyRing> results =
        keyring.getKeyRings(checkNotNull(query, "query"), true, true);
    verify(results.hasNext(), "No public key found matching substring: %s", query);
    while (results.hasNext()) {
      Optional<PGPPublicKey> result = lookupPublicSubkey(results.next(), want);
      if (result.isPresent()) {
        return result.get();
      }
    }
    throw new VerifyException(String.format(
        "No public key (%s) found matching substring: %s", want, query));
  } catch (PGPException e) {
    throw new VerifyException(String.format("Public key lookup failed for query: %s", query), e);
  }
}
 
Example #20
Source File: ArgumentContextUtils.java    From yangtools with Eclipse Public License 1.0 6 votes vote down vote up
final @NonNull String stringFromStringContext(final ArgumentContext context, final StatementSourceReference ref) {
    // Get first child, which we fully expect to exist and be a lexer token
    final ParseTree firstChild = context.getChild(0);
    verify(firstChild instanceof TerminalNode, "Unexpected shape of %s", context);
    final TerminalNode firstNode = (TerminalNode) firstChild;
    final int firstType = firstNode.getSymbol().getType();
    switch (firstType) {
        case YangStatementParser.IDENTIFIER:
            // Simple case, there is a simple string, which cannot contain anything that we would need to process.
            return firstNode.getText();
        case YangStatementParser.STRING:
            // Complex case, defer to a separate method
            return concatStrings(context, ref);
        default:
            throw new VerifyException("Unexpected first symbol in " + context);
    }
}
 
Example #21
Source File: RdeRevisionTest.java    From nomulus with Apache License 2.0 5 votes vote down vote up
@Test
public void testSaveRevision_objectDoesntExist_newRevisionIsOne_throwsVe() {
  VerifyException thrown =
      assertThrows(
          VerifyException.class,
          () ->
              tm()
                  .transact(
                      () ->
                          saveRevision("despondency", DateTime.parse("1984-12-18TZ"), FULL, 1)));
  assertThat(thrown).hasMessageThat().contains("object missing");
}
 
Example #22
Source File: RdeRevisionTest.java    From nomulus with Apache License 2.0 5 votes vote down vote up
@Test
public void testSaveRevision_objectExistsAtZero_newRevisionIsTwo_throwsVe() {
  save("melancholy", DateTime.parse("1984-12-18TZ"), FULL, 0);
  VerifyException thrown =
      assertThrows(
          VerifyException.class,
          () ->
              tm()
                  .transact(
                      () -> saveRevision("melancholy", DateTime.parse("1984-12-18TZ"), FULL, 2)));
  assertThat(thrown).hasMessageThat().contains("should be at 1 ");
}
 
Example #23
Source File: NordnUploadActionTest.java    From nomulus with Apache License 2.0 5 votes vote down vote up
@Test
public void testFailure_nullRegistryUser() {
  persistClaimsModeDomain();
  persistResource(Registry.get("tld").asBuilder().setLordnUsername(null).build());
  VerifyException thrown = assertThrows(VerifyException.class, action::run);
  assertThat(thrown).hasMessageThat().contains("lordnUsername is not set for tld.");
}
 
Example #24
Source File: DepAttributeTest.java    From buck with Apache License 2.0 5 votes vote down vote up
@Test
public void failsTransformIfInvalidElementProvided() {

  thrown.expect(VerifyException.class);

  attr.getPostCoercionTransform()
      .postCoercionTransform("invalid", new FakeRuleAnalysisContextImpl(ImmutableMap.of()));
}
 
Example #25
Source File: DepAttributeTest.java    From buck with Apache License 2.0 5 votes vote down vote up
@Test
public void failsTransformIfInvalidCoercedTypeProvided() {

  thrown.expect(VerifyException.class);

  attr.getPostCoercionTransform()
      .postCoercionTransform(1, new FakeRuleAnalysisContextImpl(ImmutableMap.of()));
}
 
Example #26
Source File: DepListAttributeTest.java    From buck with Apache License 2.0 5 votes vote down vote up
@Test
public void failsTransformIfMissingRequiredProvider() throws CoerceFailedException {
  FakeBuiltInProvider expectedProvider = new FakeBuiltInProvider("expected");
  DepListAttribute attr =
      ImmutableDepListAttribute.of(
          ImmutableList.of(), "", true, true, ImmutableList.of(expectedProvider));
  FakeBuiltInProvider presentProvider = new FakeBuiltInProvider("present");

  FakeInfo info = new FakeInfo(presentProvider);

  ImmutableList<BuildTarget> coerced =
      attr.getValue(
          cellNameResolver,
          filesystem,
          ForwardRelativePath.of(""),
          UnconfiguredTargetConfiguration.INSTANCE,
          UnconfiguredTargetConfiguration.INSTANCE,
          ImmutableList.of("//foo:bar"));

  thrown.expect(VerifyException.class);
  attr.getPostCoercionTransform()
      .postCoercionTransform(
          coerced,
          new FakeRuleAnalysisContextImpl(
              ImmutableMap.of(
                  BuildTargetFactory.newInstance("//foo:bar"),
                  TestProviderInfoCollectionImpl.builder().put(info).build())));
}
 
Example #27
Source File: DepListAttributeTest.java    From buck with Apache License 2.0 5 votes vote down vote up
@Test
public void failsTransformIfInvalidElementInList() {

  thrown.expect(VerifyException.class);

  attr.getPostCoercionTransform()
      .postCoercionTransform(
          ImmutableList.of("invalid"), new FakeRuleAnalysisContextImpl(ImmutableMap.of()));
}
 
Example #28
Source File: DnsMessageTransportTest.java    From nomulus with Apache License 2.0 5 votes vote down vote up
@Test
public void testResponseIdMismatchThrowsExeption() throws Exception {
  expectedResponse.getHeader().setID(1 + simpleQuery.getHeader().getID());
  when(mockSocket.getInputStream())
      .thenReturn(new ByteArrayInputStream(messageToBytesWithLength(expectedResponse)));
  when(mockSocket.getOutputStream()).thenReturn(new ByteArrayOutputStream());
  VerifyException thrown = assertThrows(VerifyException.class, () -> resolver.send(simpleQuery));
  assertThat(thrown)
      .hasMessageThat()
      .contains(
          "response ID "
              + expectedResponse.getHeader().getID()
              + " does not match query ID "
              + simpleQuery.getHeader().getID());
}
 
Example #29
Source File: DepAttributeTest.java    From buck with Apache License 2.0 5 votes vote down vote up
@Test
public void failsTransformIfMissingRequiredProvider() throws CoerceFailedException {
  FakeBuiltInProvider expectedProvider = new FakeBuiltInProvider("expected");
  DepAttribute attr =
      ImmutableDepAttribute.of(Runtime.NONE, "", true, ImmutableList.of(expectedProvider));
  FakeBuiltInProvider presentProvider = new FakeBuiltInProvider("present");

  FakeInfo info = new FakeInfo(presentProvider);

  BuildTarget coerced =
      attr.getValue(
          cellRoots,
          filesystem,
          ForwardRelativePath.of(""),
          UnconfiguredTargetConfiguration.INSTANCE,
          UnconfiguredTargetConfiguration.INSTANCE,
          "//foo:bar");

  thrown.expect(VerifyException.class);
  attr.getPostCoercionTransform()
      .postCoercionTransform(
          coerced,
          new FakeRuleAnalysisContextImpl(
              ImmutableMap.of(
                  BuildTargetFactory.newInstance("//foo:bar"),
                  TestProviderInfoCollectionImpl.builder().put(info).build())));
}
 
Example #30
Source File: DnsMessageTransportTest.java    From nomulus with Apache License 2.0 5 votes vote down vote up
@Test
public void testResponseOpcodeMismatchThrowsException() throws Exception {
  simpleQuery.getHeader().setOpcode(Opcode.QUERY);
  expectedResponse.getHeader().setOpcode(Opcode.STATUS);
  when(mockSocket.getInputStream())
      .thenReturn(new ByteArrayInputStream(messageToBytesWithLength(expectedResponse)));
  when(mockSocket.getOutputStream()).thenReturn(new ByteArrayOutputStream());
  VerifyException thrown = assertThrows(VerifyException.class, () -> resolver.send(simpleQuery));
  assertThat(thrown)
      .hasMessageThat()
      .contains("response opcode 'STATUS' does not match query opcode 'QUERY'");
}