Java Code Examples for org.junit.Assert#assertNull()

The following examples show how to use org.junit.Assert#assertNull() . 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: LaunchCommandTest.java    From sofa-ark with Apache License 2.0 6 votes vote down vote up
@Test
public void testCommandParser() {
    try {
        List<String> args = new ArrayList<>();
        args.addAll(arkCommand);
        args.add("p1");
        args.add("p2");
        LaunchCommand launchCommand = LaunchCommand.parse(args.toArray(new String[] {}));

        Assert.assertTrue(launchCommand.getEntryClassName().equals(
            method.getDeclaringClass().getName()));
        Assert.assertTrue(launchCommand.getEntryMethodName().equals(method.getName()));
        Assert.assertTrue(launchCommand.getExecutableArkBizJar().equals(fatJarUrl));
        Assert.assertTrue(launchCommand.getClasspath().length == classpath
            .split(CommandArgument.CLASSPATH_SPLIT).length);
        for (URL url : launchCommand.getClasspath()) {
            Assert.assertTrue(classpath.contains(url.toExternalForm()));
        }
        Assert.assertTrue(2 == launchCommand.getLaunchArgs().length);
    } catch (Exception ex) {
        Assert.assertNull(ex);
    }
}
 
Example 2
Source File: AbsoluteReferenceResolverTest.java    From apicurio-studio with Apache License 2.0 6 votes vote down vote up
/**
 * Test method for {@link io.apicurio.hub.api.content.AbsoluteReferenceResolver#resolveRef(java.lang.String, io.apicurio.datamodels.core.models.Node)}.
 */
@Test
public void testResolveRef_AsyncAPI2() {
    Aai20NodeFactory factory = new Aai20NodeFactory();
    Aai20Document doc = (Aai20Document) Library.createDocument(DocumentType.asyncapi2);
    
    AaiMessage message = factory.createMessage(doc.createComponents(), "foo");
    message.$ref = "#/components/Message1";

    Node actual = resolver.resolveRef(message.$ref, message);
    Assert.assertNull(actual);
    
    message.$ref = "http://localhost:8111/aai20-streetlights.json#/components/messages/lightMeasured";
    actual = resolver.resolveRef(message.$ref, message);
    Assert.assertNotNull(actual);
    Assert.assertEquals("Inform about environmental lighting conditions of a particular streetlight.", ((AaiMessage) actual).summary);

    AaiParameter param = factory.createParameter(doc.createComponents(), "foo-param");
    param._ownerDocument = doc;
    param.$ref = "http://localhost:8111/aai20-streetlights.json#/components/parameters/streetlightId";
    actual = resolver.resolveRef(param.$ref, param);
    Assert.assertNotNull(actual);
    Assert.assertEquals("The ID of the streetlight.", ((AaiParameter) actual).description);
}
 
Example 3
Source File: AbstractCloudSpannerConnectionTest.java    From spanner-jdbc with MIT License 5 votes vote down vote up
@Test
public void testGetSchema() throws Exception {
  AbstractCloudSpannerConnection testSubject = createTestSubject();
  Assert.assertNull(testSubject.getSchema());
  testSubject.setReportDefaultSchemaAsNull(false);
  Assert.assertEquals("", testSubject.getSchema());
}
 
Example 4
Source File: TestMetricsTruncation.java    From iceberg with Apache License 2.0 5 votes vote down vote up
@Test
public void testTruncateBinaryMax() {
  ByteBuffer test1 = ByteBuffer.wrap(new byte[] {1, 1, 2});
  ByteBuffer test2 = ByteBuffer.wrap(new byte[] {1, 1, (byte) 0xFF, 2});
  ByteBuffer test3 = ByteBuffer.wrap(new byte[] {(byte) 0xFF, (byte) 0xFF, (byte) 0xFF, 2});
  ByteBuffer test4 = ByteBuffer.wrap(new byte[] {1, 1, 0});
  ByteBuffer expectedOutput = ByteBuffer.wrap(new byte[] {1, 2});

  Comparator<ByteBuffer> cmp = Literal.of(test1).comparator();
  Assert.assertTrue("Truncated upper bound should be greater than or equal to the actual upper bound",
      cmp.compare(truncateBinaryMax(Literal.of(test1), 2).value(), test1) >= 0);
  Assert.assertTrue("Output must have two bytes and the second byte of the input must be incremented",
      cmp.compare(truncateBinaryMax(Literal.of(test1), 2).value(), expectedOutput) == 0);
  Assert.assertTrue("Truncated upper bound should be greater than or equal to the actual upper bound",
      cmp.compare(truncateBinaryMax(Literal.of(test2), 2).value(), test2) >= 0);
  Assert.assertTrue("Since the third byte is already the max value, output must have two bytes " +
      "with the second byte incremented ", cmp.compare(
      truncateBinaryMax(Literal.of(test2), 3).value(), expectedOutput) == 0);
  Assert.assertTrue("No truncation required as truncate length is greater than the input size",
      cmp.compare(truncateBinaryMax(Literal.of(test3), 5).value(), test3) == 0);
  Assert.assertNull("An upper bound doesn't exist since the first two bytes are the max value",
      truncateBinaryMax(Literal.of(test3), 2));
  Assert.assertTrue("Truncated upper bound should be greater than or equal to the actual upper bound",
      cmp.compare(truncateBinaryMax(Literal.of(test4), 2).value(), test4) >= 0);
  Assert.assertTrue("Since a shorter sequence is considered smaller, output must have two bytes " +
          "and the second byte of the input must be incremented",
      cmp.compare(truncateBinaryMax(Literal.of(test4), 2).value(), expectedOutput) == 0);
}
 
Example 5
Source File: KsqlGenericRowAvroDeserializerTest.java    From ksql-fork-with-deep-learning-function with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldDeserializeWithMissingFields() {
  String schemaStr1 = "{"
                      + "\"namespace\": \"kql\","
                      + " \"name\": \"orders\","
                      + " \"type\": \"record\","
                      + " \"fields\": ["
                      + "     {\"name\": \"orderTime\", \"type\": \"long\"},"
                      + "     {\"name\": \"orderId\",  \"type\": \"long\"},"
                      + "     {\"name\": \"itemId\", \"type\": \"string\"},"
                      + "     {\"name\": \"orderUnits\", \"type\": \"double\"}"
                      + " ]"
                      + "}";
  Schema.Parser parser = new Schema.Parser();
  Schema avroSchema1 = parser.parse(schemaStr1);
  SchemaRegistryClient schemaRegistryClient = new MockSchemaRegistryClient();
  List columns = Arrays.asList(1511897796092L, 1L, "item_1", 10.0);

  GenericRow genericRow = new GenericRow(columns);
  byte[] serializedRow = getSerializedRow("t1", schemaRegistryClient, avroSchema1, genericRow);

  KsqlGenericRowAvroDeserializer ksqlGenericRowAvroDeserializer = new
      KsqlGenericRowAvroDeserializer(schema, schemaRegistryClient, false);

  GenericRow row = ksqlGenericRowAvroDeserializer.deserialize("t1", serializedRow);
  assertThat("Incorrect deserializarion", row.getColumns().size(), equalTo(6));
  assertThat("Incorrect deserializarion", (Long)row.getColumns().get(0), equalTo(1511897796092L));
  assertThat("Incorrect deserializarion", (Long)row.getColumns().get(1), equalTo
      (1L));
  assertThat("Incorrect deserializarion", (String)row.getColumns().get(2), equalTo
      ( "item_1"));
  Assert.assertNull(row.getColumns().get(4));
  Assert.assertNull(row.getColumns().get(5));
}
 
Example 6
Source File: ArrayTest.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
@Test
public void testEntries() {
    final Entry theEntry = new Entry();
    Assert.assertNull(entries[0]);
    theEntry.test = 10;
    entries[4] = theEntry;
    Assert.assertEquals(10, entries[4].test, 0);

    final Object[] theEmpty = new Object[100];

    final Object theEntry0 = theEmpty[12];
    Assert.assertNull(theEntry0);
}
 
Example 7
Source File: TestReadProjection.java    From iceberg with Apache License 2.0 5 votes vote down vote up
@Test
public void testRenamedAddedField() throws Exception {
  Schema schema = new Schema(
      Types.NestedField.required(1, "a", Types.LongType.get()),
      Types.NestedField.required(2, "b", Types.LongType.get()),
      Types.NestedField.required(3, "d", Types.LongType.get())
  );

  Record record = GenericRecord.create(schema.asStruct());
  record.setField("a", 100L);
  record.setField("b", 200L);
  record.setField("d", 300L);

  Schema renamedAdded = new Schema(
      Types.NestedField.optional(1, "a", Types.LongType.get()),
      Types.NestedField.optional(2, "b", Types.LongType.get()),
      Types.NestedField.optional(3, "c", Types.LongType.get()),
      Types.NestedField.optional(4, "d", Types.LongType.get())
  );

  Record projected = writeAndRead("rename_and_add_column_projection", schema, renamedAdded, record);
  Assert.assertEquals("Should contain the correct value in column 1", projected.get(0), 100L);
  Assert.assertEquals("Should contain the correct value in column a", projected.getField("a"), 100L);
  Assert.assertEquals("Should contain the correct value in column 2", projected.get(1), 200L);
  Assert.assertEquals("Should contain the correct value in column b", projected.getField("b"), 200L);
  Assert.assertEquals("Should contain the correct value in column 3", projected.get(2), 300L);
  Assert.assertEquals("Should contain the correct value in column c", projected.getField("c"), 300L);
  Assert.assertNull("Should contain empty value on new column 4", projected.get(3));
  Assert.assertNull("Should contain the correct value in column d", projected.getField("d"));
}
 
Example 8
Source File: ReflectCacheTest.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
@Test
public void testMethodSigs() {
    final String key = TestInterface.class.getCanonicalName();
    final Method method = ReflectUtils.getMethod(TestInterface.class, "invoke", SofaRequest.class);
    Assert.assertNull(ReflectCache.getMethodSigsCache(key, "invoke"));

    ReflectCache.putMethodSigsCache(key, method.getName(),
        ClassTypeUtils.getTypeStrs(method.getParameterTypes(), true));
    Assert.assertArrayEquals(new String[] { SofaRequest.class.getCanonicalName() },
        ReflectCache.getMethodSigsCache(key, "invoke"));

    ReflectCache.invalidateMethodSigsCache(key);
    Assert.assertNull(ReflectCache.NOT_OVERLOAD_METHOD_CACHE.get(key));
}
 
Example 9
Source File: Neo4JEdgeWhileCreatingInsertCommandTest.java    From neo4j-gremlin-bolt with Apache License 2.0 5 votes vote down vote up
@Test
public void givenNoIdGenerationProviderShouldCreateInsertCommand() {
    // arrange
    Mockito.when(graph.tx()).thenAnswer(invocation -> transaction);
    Mockito.when(outVertex.matchPattern(Mockito.any())).thenAnswer(invocation -> "(o)");
    Mockito.when(outVertex.matchPredicate(Mockito.any(), Mockito.any())).thenAnswer(invocation -> "ID(o) = $oid");
    Mockito.when(outVertex.id()).thenAnswer(invocation -> 1L);
    Mockito.when(outVertex.matchStatement(Mockito.anyString(), Mockito.anyString())).thenAnswer(invocation -> "MATCH (o) WHERE ID(o) = $oid");
    Mockito.when(inVertex.matchPattern(Mockito.any())).thenAnswer(invocation -> "(i)");
    Mockito.when(inVertex.matchPredicate(Mockito.any(), Mockito.any())).thenAnswer(invocation -> "ID(i) = $iid");
    Mockito.when(inVertex.id()).thenAnswer(invocation -> 2L);
    Mockito.when(inVertex.matchStatement(Mockito.anyString(), Mockito.anyString())).thenAnswer(invocation -> "MATCH (i) WHERE ID(i) = $iid");
    Mockito.when(edgeIdProvider.processIdentifier(Mockito.any())).thenAnswer(invocation -> 3L);
    Mockito.when(edgeIdProvider.fieldName()).thenAnswer(invocation -> "id");
    Mockito.when(edgeIdProvider.matchPredicateOperand(Mockito.anyString())).thenAnswer(invocation -> "ID(r)");
    Mockito.when(statementResult.hasNext()).thenAnswer(invocation -> true);
    Mockito.when(statementResult.next()).thenAnswer(invocation -> record);
    Mockito.when(record.get(Mockito.eq(0))).thenAnswer(invocation -> value);
    Mockito.when(value.asEntity()).thenAnswer(invocation -> entity);
    Neo4JEdge edge = new Neo4JEdge(graph, session, edgeIdProvider, "L1", outVertex, inVertex);
    // act
    Neo4JDatabaseCommand command = edge.insertCommand();
    // assert
    Assert.assertNull("Failed get node identifier", edge.id());
    Assert.assertNotNull("Failed to create insert command", command);
    Assert.assertNotNull("Failed to create insert command statement", command.getStatement());
    Assert.assertEquals("Invalid insert command statement", command.getStatement(), "MATCH (o) WHERE ID(o) = $oid MATCH (i) WHERE ID(i) = $iid CREATE (o)-[r:`L1`$ep]->(i) RETURN ID(r)");
    Assert.assertEquals("Invalid insert command statement", command.getParameters(), ParameterUtils.createParameters("oid", 1L, "iid", 2L, "ep", Collections.emptyMap()));
    Assert.assertNotNull("Failed to create insert command callback", command.getCallback());
    // invoke callback
    command.getCallback().accept(statementResult);
    // assert
    Assert.assertNotNull("Failed get node identifier", edge.id());
}
 
Example 10
Source File: FeaturePackLocationStringTestCase.java    From galleon with Apache License 2.0 5 votes vote down vote up
@Test
public void testFeaturePackIdWithUniverseLocationFromString() throws Exception {
    final FeaturePackLocation parsedCoords = FeaturePackLocation.fromString("producer@factory(location):channel#build");
    Assert.assertNotNull(parsedCoords);
    Assert.assertEquals("factory", parsedCoords.getUniverse().getFactory());
    Assert.assertEquals("location", parsedCoords.getUniverse().getLocation());
    Assert.assertEquals("producer", parsedCoords.getProducerName());
    Assert.assertEquals("channel", parsedCoords.getChannelName());
    Assert.assertNull(parsedCoords.getFrequency());
    Assert.assertEquals("build", parsedCoords.getBuild());
}
 
Example 11
Source File: AuthenticatorTestCase.java    From hadoop with Apache License 2.0 5 votes vote down vote up
protected void _testAuthentication(Authenticator authenticator, boolean doPost) throws Exception {
  start();
  try {
    URL url = new URL(getBaseURL());
    AuthenticatedURL.Token token = new AuthenticatedURL.Token();
    Assert.assertFalse(token.isSet());
    TestConnectionConfigurator connConf = new TestConnectionConfigurator();
    AuthenticatedURL aUrl = new AuthenticatedURL(authenticator, connConf);
    HttpURLConnection conn = aUrl.openConnection(url, token);
    Assert.assertTrue(connConf.invoked);
    String tokenStr = token.toString();
    if (doPost) {
      conn.setRequestMethod("POST");
      conn.setDoOutput(true);
    }
    conn.connect();
    if (doPost) {
      Writer writer = new OutputStreamWriter(conn.getOutputStream());
      writer.write(POST);
      writer.close();
    }
    Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());
    if (doPost) {
      BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
      String echo = reader.readLine();
      Assert.assertEquals(POST, echo);
      Assert.assertNull(reader.readLine());
    }
    aUrl = new AuthenticatedURL();
    conn = aUrl.openConnection(url, token);
    conn.connect();
    Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());
    Assert.assertEquals(tokenStr, token.toString());
  } finally {
    stop();
  }
}
 
Example 12
Source File: GreetingDecoderTest.java    From garmadon with Apache License 2.0 5 votes vote down vote up
@Test
public void GreetingDecoder_should_read_4_bytes_at_once() {
    byte[] bytes = new byte[]{1, 2, 3, 4};
    ByteBuf byteBuf = Unpooled.wrappedBuffer(bytes);
    Assert.assertTrue(channel.get().writeInbound(byteBuf));
    Assert.assertTrue(channel.get().finish());

    Assert.assertEquals(Unpooled.wrappedBuffer(bytes), channel.get().readInbound());
    //check there is nothing more
    Assert.assertNull(channel.get().readInbound());
}
 
Example 13
Source File: TransactionRetStoreTest.java    From gsc-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void put() {
  TransactionInfoWrapper transactionInfoWrapper = new TransactionInfoWrapper();
  transactionInfoWrapper.setId(transactionId);
  transactionInfoWrapper.setFee(1000L);
  transactionInfoWrapper.setBlockNumber(100L);
  transactionInfoWrapper.setBlockTimeStamp(200L);

  TransactionRetWrapper transactionRetWrapper = new TransactionRetWrapper();
  transactionRetWrapper.addTransactionInfo(transactionInfoWrapper.getInstance());
  Assert.assertNull("put transaction info error", transactionRetStore.getUnchecked(transactionInfoWrapper.getId()));
  transactionRetStore.put(transactionInfoWrapper.getId(), transactionRetWrapper);
  Assert.assertNotNull("get transaction info error", transactionRetStore.getUnchecked(transactionInfoWrapper.getId()));
}
 
Example 14
Source File: TestCorsFilter.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
@Test
public void testDoFilterPreflightWithoutCredentialsAndSpecificOrigin()
        throws IOException,
        ServletException {
    TesterHttpServletRequest request = new TesterHttpServletRequest();
    request.setHeader(CorsFilter.REQUEST_HEADER_ORIGIN,
            TesterFilterConfigs.HTTPS_WWW_APACHE_ORG);
    request.setHeader(
            CorsFilter.REQUEST_HEADER_ACCESS_CONTROL_REQUEST_METHOD, "PUT");
    request.setHeader(
            CorsFilter.REQUEST_HEADER_ACCESS_CONTROL_REQUEST_HEADERS,
            "Content-Type");
    request.setMethod("OPTIONS");
    TesterHttpServletResponse response = new TesterHttpServletResponse();

    CorsFilter corsFilter = new CorsFilter();
    corsFilter.init(TesterFilterConfigs
            .getFilterConfigSpecificOriginAndSupportsCredentialsDisabled());
    corsFilter.doFilter(request, response, filterChain);

    Assert.assertTrue(response.getHeader(
            CorsFilter.RESPONSE_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN).equals(
            TesterFilterConfigs.HTTPS_WWW_APACHE_ORG));
    Assert.assertNull(response.getHeader(
            CorsFilter.RESPONSE_HEADER_ACCESS_CONTROL_ALLOW_CREDENTIALS));
    Assert.assertTrue(((Boolean) request.getAttribute(
            CorsFilter.HTTP_REQUEST_ATTRIBUTE_IS_CORS_REQUEST)).booleanValue());
    Assert.assertTrue(request.getAttribute(
            CorsFilter.HTTP_REQUEST_ATTRIBUTE_ORIGIN).equals(
            TesterFilterConfigs.HTTPS_WWW_APACHE_ORG));
    Assert.assertTrue(request.getAttribute(
            CorsFilter.HTTP_REQUEST_ATTRIBUTE_REQUEST_TYPE).equals(
            CorsFilter.CORSRequestType.PRE_FLIGHT.name().toLowerCase(Locale.ENGLISH)));
    Assert.assertTrue(request.getAttribute(
            CorsFilter.HTTP_REQUEST_ATTRIBUTE_REQUEST_HEADERS).equals(
            "Content-Type"));
}
 
Example 15
Source File: BackwardsCompatibilityTest.java    From eet-client with MIT License 5 votes vote down vote up
@Test
public void realCommunicationPlayground() throws Exception {
    final TrzbaDataType data = getData();
    final SubmitResult result = eetService.submitReceipt(data, CommunicationMode.REAL, EndpointType.PLAYGROUND, SubmissionType.FIRST_ATTEMPT);
    Assert.assertNull(result.getChyba());
    Assert.assertNotNull(result.getFik());
    final String bkpFromRequest = result.getBKP();
    final String bkpFromResponse = result.getHlavicka().getBkp();
    Assert.assertEquals(bkpFromRequest, bkpFromResponse);
}
 
Example 16
Source File: EventDecoderTest.java    From garmadon with Apache License 2.0 5 votes vote down vote up
@Test
public void EventDecoder_should_read_event_sent_as_chunks() throws TypeMarkerException, SerializationException {
    Header header = Header.newBuilder()
            .withHostname("hostname")
            .withApplicationID("app_id")
            .withAttemptID("app_attempt_id")
            .withApplicationName("app_name")
            .withContainerID("container_id")
            .withUser("user")
            .withPid("pid")
            .build();


    byte[] raw = ProtocolMessage.create(System.currentTimeMillis(), header.serialize(), new TestEvent(100));

    ByteBuf input = Unpooled.wrappedBuffer(raw);

    Assert.assertFalse(channel.get().writeInbound(input.readBytes(2)));
    Assert.assertFalse(channel.get().writeInbound(input.readBytes(20)));
    Assert.assertTrue(channel.get().writeInbound(input.readBytes(raw.length - 22)));
    Assert.assertTrue(channel.get().finish());

    //check that the event is read as one piece
    Assert.assertEquals(Unpooled.wrappedBuffer(raw), channel.get().readInbound());
    //check there is nothing more
    Assert.assertNull(channel.get().readInbound());
}
 
Example 17
Source File: TransformParamContainingTest.java    From spring-native-query with MIT License 4 votes vote down vote up
@Test
public void applyEmpty() {
    Object result = transform.apply("");
    Assert.assertNull(result);
}
 
Example 18
Source File: SpringAnnotationProcessorTest.java    From servicecomb-toolkit with Apache License 2.0 4 votes vote down vote up
@Test
public void parseParameter() throws NoSuchMethodException {
  Class<ParamAnnotationResource> paramAnnotationResourceClass = ParamAnnotationResource.class;
  OasContext oasContext = new OasContext(null);
  OperationContext operationContext;
  ParameterContext parameterContext;

  RequestParamAnnotationProcessor requestParamAnnotationProcessor = new RequestParamAnnotationProcessor();
  Method requestParamMethod = paramAnnotationResourceClass.getMethod("requestParam", String.class);
  Parameter requestParamMethodParam = requestParamMethod.getParameters()[0];
  RequestParam requestParamAnnotation = requestParamMethodParam
      .getAnnotation(RequestParam.class);
  operationContext = new OperationContext(requestParamMethod, oasContext);
  parameterContext = new ParameterContext(operationContext, requestParamMethodParam);
  requestParamAnnotationProcessor.process(requestParamAnnotation, parameterContext);
  io.swagger.v3.oas.models.parameters.Parameter oasParameter = parameterContext.toParameter();
  Assert.assertNull(parameterContext.getDefaultValue());
  Assert.assertNull(oasParameter.getSchema().getDefault());

  PathVariableAnnotationProcessor pathVariableAnnotationProcessor = new PathVariableAnnotationProcessor();
  Method pathVariableMethod = paramAnnotationResourceClass.getMethod("pathVariable", String.class);
  Parameter pathVariableMethodParam = pathVariableMethod.getParameters()[0];
  PathVariable pathVariableAnnotation = pathVariableMethodParam
      .getAnnotation(PathVariable.class);
  operationContext = new OperationContext(pathVariableMethod, oasContext);
  parameterContext = new ParameterContext(operationContext, pathVariableMethodParam);
  pathVariableAnnotationProcessor.process(pathVariableAnnotation, parameterContext);
  parameterContext.toParameter();
  Assert.assertTrue(parameterContext.isRequired());

  RequestPartAnnotationProcessor requestPartAnnotationProcessor = new RequestPartAnnotationProcessor();
  Method requestPartMethod = paramAnnotationResourceClass.getMethod("requestPart", MultipartFile.class);
  Parameter requestPartMethodParam = requestPartMethod.getParameters()[0];
  RequestPart requestPartParamAnnotation = requestPartMethodParam
      .getAnnotation(RequestPart.class);
  operationContext = new OperationContext(requestPartMethod, oasContext);
  parameterContext = new ParameterContext(operationContext, requestPartMethodParam);
  requestPartAnnotationProcessor.process(requestPartParamAnnotation, parameterContext);
  oasParameter = parameterContext.toParameter();
  Assert.assertNull(parameterContext.getDefaultValue());
  Assert.assertEquals(FileSchema.class, oasParameter.getSchema().getClass());

  RequestHeaderAnnotationProcessor requestHeaderAnnotationProcessor = new RequestHeaderAnnotationProcessor();
  Method requestHeaderMethod = paramAnnotationResourceClass.getMethod("requestHeader", String.class);
  Parameter requestHeaderMethodParam = requestHeaderMethod.getParameters()[0];
  RequestHeader requestHeaderParamAnnotation = requestHeaderMethodParam
      .getAnnotation(RequestHeader.class);
  operationContext = new OperationContext(requestPartMethod, oasContext);
  parameterContext = new ParameterContext(operationContext, requestHeaderMethodParam);
  requestHeaderAnnotationProcessor.process(requestHeaderParamAnnotation, parameterContext);
  oasParameter = parameterContext.toParameter();
  Assert.assertNull(parameterContext.getDefaultValue());
  Assert.assertNull(oasParameter.getSchema().getDefault());

  RequestBodyAnnotationProcessor requestBodyAnnotationProcessor = new RequestBodyAnnotationProcessor();
  Method requestBodyMethod = paramAnnotationResourceClass.getMethod("requestBody", String.class);
  Parameter requestBodyMethodParam = requestBodyMethod.getParameters()[0];
  RequestBody requestBodyParamAnnotation = requestBodyMethodParam
      .getAnnotation(RequestBody.class);
  operationContext = new OperationContext(requestBodyMethod, oasContext);
  parameterContext = new ParameterContext(operationContext, requestBodyMethodParam);
  requestBodyAnnotationProcessor.process(requestBodyParamAnnotation, parameterContext);
  parameterContext.toParameter();
  Assert.assertTrue(parameterContext.isRequired());
}
 
Example 19
Source File: TestBlockOutputStreamWithFailures.java    From hadoop-ozone with Apache License 2.0 4 votes vote down vote up
@Test
public void testExceptionDuringClose() throws Exception {
  String keyName = getKeyName();
  OzoneOutputStream key = createKey(keyName, ReplicationType.RATIS, 0);
  int dataLength = 167;
  // write data more than 1 chunk
  byte[] data1 =
      ContainerTestHelper.getFixedLengthString(keyString, dataLength)
          .getBytes(UTF_8);
  key.write(data1);

  Assert.assertTrue(key.getOutputStream() instanceof KeyOutputStream);
  KeyOutputStream keyOutputStream = (KeyOutputStream) key.getOutputStream();

  Assert.assertTrue(keyOutputStream.getStreamEntries().size() == 1);
  OutputStream stream =
      keyOutputStream.getStreamEntries().get(0).getOutputStream();
  Assert.assertTrue(stream instanceof BlockOutputStream);
  BlockOutputStream blockOutputStream = (BlockOutputStream) stream;

  Assert.assertEquals(2, blockOutputStream.getBufferPool().getSize());
  Assert.assertEquals(dataLength, blockOutputStream.getWrittenDataLength());

  Assert.assertEquals(0, blockOutputStream.getTotalDataFlushedLength());

  Assert.assertTrue(blockOutputStream.getTotalAckDataLength() == 0);

  Assert.assertTrue(
      blockOutputStream.getCommitIndex2flushedDataMap().size() == 0);
  // Now do a flush. This will flush the data and update the flush length and
  // the map.
  key.flush();
  // Since the data in the buffer is already flushed, flush here will have
  // no impact on the counters and data structures

  Assert.assertEquals(2, blockOutputStream.getBufferPool().getSize());
  Assert.assertEquals(dataLength, blockOutputStream.getWrittenDataLength());

  Assert.assertEquals(dataLength,
      blockOutputStream.getTotalDataFlushedLength());
  // flush will make sure one more entry gets updated in the map
  Assert.assertTrue(
      blockOutputStream.getCommitIndex2flushedDataMap().size() == 0);

  XceiverClientRatis raftClient =
      (XceiverClientRatis) blockOutputStream.getXceiverClient();
  Assert.assertEquals(3, raftClient.getCommitInfoMap().size());
  // Close the containers on the Datanode and write more data
  TestHelper.waitForContainerClose(key, cluster);
  key.write(data1);

  // commitInfoMap will remain intact as there is no server failure
  Assert.assertEquals(3, raftClient.getCommitInfoMap().size());
  // now close the stream, It will hit exception
  key.close();

  Assert.assertTrue(HddsClientUtils.checkForException(blockOutputStream
      .getIoException()) instanceof ContainerNotOpenException);
  // Make sure the retryCount is reset after the exception is handled
  Assert.assertTrue(keyOutputStream.getRetryCount() == 0);
  // make sure the bufferPool is empty
  Assert
      .assertEquals(0, blockOutputStream.getBufferPool().computeBufferData());
  Assert.assertEquals(dataLength, blockOutputStream.getTotalAckDataLength());
  Assert.assertNull(blockOutputStream.getCommitIndex2flushedDataMap());
  Assert.assertTrue(keyOutputStream.getStreamEntries().size() == 0);
  // Written the same data twice
  String dataString = new String(data1, UTF_8);
  validateData(keyName, dataString.concat(dataString).getBytes());
}
 
Example 20
Source File: WebTestCase.java    From htmlunit with Apache License 2.0 2 votes vote down vote up
/**
 * Assert that the specified object is null.
 * @param object the object to check
 */
public static void assertNull(final Object object) {
    Assert.assertNull("Expected null but found [" + object + "]", object);
}