/**
   * Test the deployment operation. This will add and remove a given set of deployment using a
   * composite operation and attaching the streams necessary to the http post message.
   *
   * @param quantity the amount of deployments
   * @param encoded whether to send the operation in the dmr encoded format or not
   * @throws IOException
   */
  private void testDeploymentOperations(final int quantity, final boolean encoded)
      throws IOException {

    // Create the deployment
    final File temp = createTempDeploymentZip();
    try {
      final ModelNode deployment = createCompositeDeploymentOperation(quantity);
      final ContentBody operation = getOperationBody(deployment, encoded);
      final List<ContentBody> streams = new ArrayList<ContentBody>();
      for (int i = 0; i < quantity; i++) {
        streams.add(new FileBody(temp));
      }

      final ModelNode response = executePost(operation, encoded, streams);
      Assert.assertEquals(response.toString(), SUCCESS, response.get(OUTCOME).asString());

    } finally {
      temp.delete();
    }

    // And remove the deployments again
    final ModelNode remove = removeDeploymentsOperation(quantity);
    final ContentBody operation = getOperationBody(remove, encoded);
    final ModelNode response = executePost(operation, encoded);
    Assert.assertEquals(response.toString(), SUCCESS, response.get(OUTCOME).asString());
  }
  @Test
  public void testResetOriginalValues() throws Exception {
    CalendarResource newCalendarResource = addCalendarResource();

    _persistence.clearCache();

    CalendarResource existingCalendarResource =
        _persistence.findByPrimaryKey(newCalendarResource.getPrimaryKey());

    Assert.assertTrue(
        Validator.equals(
            existingCalendarResource.getUuid(),
            ReflectionTestUtil.invoke(
                existingCalendarResource, "getOriginalUuid", new Class<?>[0])));
    Assert.assertEquals(
        Long.valueOf(existingCalendarResource.getGroupId()),
        ReflectionTestUtil.<Long>invoke(
            existingCalendarResource, "getOriginalGroupId", new Class<?>[0]));

    Assert.assertEquals(
        Long.valueOf(existingCalendarResource.getClassNameId()),
        ReflectionTestUtil.<Long>invoke(
            existingCalendarResource, "getOriginalClassNameId", new Class<?>[0]));
    Assert.assertEquals(
        Long.valueOf(existingCalendarResource.getClassPK()),
        ReflectionTestUtil.<Long>invoke(
            existingCalendarResource, "getOriginalClassPK", new Class<?>[0]));
  }
  @org.junit.Ignore("This fails for some mysterious reason - but this isn't a critical test")
  @Test
  @BMRule(
      name = "Test remove rollback operation",
      targetClass = "org.jboss.as.clustering.jgroups.subsystem.StackRemoveHandler",
      targetMethod = "performRuntime",
      targetLocation = "AT EXIT",
      action = "traceln(\"Injecting rollback fault via Byteman\");$1.setRollbackOnly()")
  public void testProtocolStackRemoveRollback() throws Exception {

    KernelServices services = buildKernelServices();

    ModelNode operation =
        Operations.createCompositeOperation(addStackOp, addTransportOp, addProtocolOp);

    // add a protocol stack
    ModelNode result = services.executeOperation(operation);
    Assert.assertEquals(SUCCESS, result.get(OUTCOME).asString());

    // remove the protocol stack
    // the remove has OperationContext.setRollbackOnly() injected
    // and so is expected to fail
    result = services.executeOperation(removeStackOp);
    Assert.assertEquals(FAILED, result.get(OUTCOME).asString());

    // need to check that all services are correctly re-installed
    ServiceName channelFactoryServiceName =
        ProtocolStackServiceName.CHANNEL_FACTORY.getServiceName("maximal2");
    Assert.assertNotNull(
        "channel factory service not installed",
        services.getContainer().getService(channelFactoryServiceName));
  }
  @Test
  public void testRunWindupTiny() throws Exception {
    try (GraphContext context = createGraphContext()) {
      super.runTest(
          context, "../test-files/jee-example-app-1.0.0.ear", false, Arrays.asList("com.acme"));

      Path graphDirectory = context.getGraphDirectory();
      Path reportsDirectory = graphDirectory.resolve("reports");
      Path indexPath = graphDirectory.resolve(Paths.get("index.html"));

      Path appReportPath =
          resolveChildPath(
              reportsDirectory,
              "ApplicationDetails_JEE_Example_App__org_windup_example_jee_example_app_1_0_0_\\.html");
      Path appNonClassifiedReportPath =
          resolveChildPath(
              reportsDirectory,
              "compatiblefiles_JEE_Example_App__org_windup_example_jee_example_app_1_0_0_\\.html");
      Path productCatalogBeanPath =
          resolveChildPath(reportsDirectory, "ProductCatalogBean_java\\.html");

      Assert.assertTrue(indexPath.toFile().exists());
      Assert.assertTrue(appReportPath.toFile().exists());
      Assert.assertTrue(appNonClassifiedReportPath.toFile().exists());
      Assert.assertTrue(productCatalogBeanPath.toFile().exists());

      String appReportContent = new String(Files.readAllBytes(appReportPath));

      Assert.assertTrue(appReportContent.contains("Used only to support migration activities."));
      allDecompiledFilesAreLinked(context);
    }
  }
  @Test
  public void JDBCExecutionContextRead() throws Exception {
    if (loadSQLite() == null) {
      return;
    }
    String[] args = new String[] {"-e", "jdbc:sqlite:"};
    CommandLineOptions options = CliFactory.parseArguments(CommandLineOptions.class, args);

    ExecutionContext testContext = new JDBCExecutionContext(options);
    MedicalLogicModule mlm =
        ActionTests.parseTemplate(
            "varA := read {drop table if exists person};\n"
                + "varB := read {create table person (id integer, name string)};\n"
                + "varC := read {insert into person values (1, 'A')};\n"
                + "varD := read {insert into person values (2, 'B')};\n"
                + "(varE, varF) := read {select * from person};\n",
            "conclude true;",
            "return (varE, varF);");
    ArdenValue[] result = mlm.run(testContext, null);
    Assert.assertEquals(1, result.length);

    ArdenValue[] expected = {
      new ArdenNumber(1), new ArdenNumber(2), new ArdenString("A"), new ArdenString("B")
    };
    ArdenValue[] resultList = ((ArdenList) (result[0])).values;

    Assert.assertArrayEquals(expected, resultList);
  }
Example #6
0
  public void testForUpdate() {
    ResetBasicData.reset();

    Query<Order> query =
        Ebean.find(Order.class)
            .setAutofetch(false)
            .setForUpdate(false)
            .setMaxRows(1)
            .order()
            .asc("orderDate")
            .order()
            .desc("id");

    int rc = query.findList().size();
    Assert.assertTrue(rc > 0);
    Assert.assertTrue(!query.getGeneratedSql().toLowerCase().contains("for update"));

    query =
        Ebean.find(Order.class)
            .setAutofetch(false)
            .setForUpdate(true)
            .setMaxRows(1)
            .order()
            .asc("orderDate")
            .order()
            .desc("id");

    rc = query.findList().size();
    Assert.assertTrue(rc > 0);
    Assert.assertTrue(query.getGeneratedSql().toLowerCase().contains("for update"));
  }
  @Test
  public void testRenewLeaseFailed() throws Exception {
    long id = CorrelationIdGenerator.generateCorrelationId() + 1;

    ConsumerNotifier notifier = lookup(ConsumerNotifier.class);

    metaProxyActions4LeaseOperation(LeaseAnswer.SUCCESS, LeaseAnswer.SUCCESS);
    brokerActions4PollMessageCmd(
        PullMessageAnswer.BASIC.channel(m_channel).creator(SIMPLE_CREATOR));

    TestMessageListener listener = new TestMessageListener().receiveCount(1);
    ConsumerHolder holder = Consumer.getInstance().start(TEST_TOPIC, TEST_GROUP, listener);
    waitUntilConsumerStarted(holder);
    listener.waitUntilReceivedAllMessage();
    Assert.assertEquals(1, listener.getReceivedMessages().size());
    holder.close();
    listener.countDownAll();

    metaProxyActions4LeaseOperation(LeaseAnswer.SUCCESS, LeaseAnswer.FAILED);
    brokerActions4PollMessageCmd(
        PullMessageAnswer.BASIC.channel(m_channel).creator(SIMPLE_CREATOR));

    listener = new TestMessageListener().receiveCount(1);
    ConsumerHolder holder_failed = Consumer.getInstance().start(TEST_TOPIC, TEST_GROUP, listener);
    waitUntilConsumerStarted(holder_failed);
    listener.waitUntilReceivedAllMessage();
    Assert.assertNull(notifier.find(id));
    holder_failed.close();
    listener.countDownAll();
  }
 @Test
 public void testCSVTable() throws IOException {
   CSVDataReference inMemory = referenceTable;
   CSVDataReference urlCon = new CSVDataLocation(url, null, true, null, true);
   try (CSVDataConnection refCon = inMemory.openConnection();
       CSVDataConnection testCon = urlCon.openConnection()) {
     int count = 0;
     do {
       CSVRecord reference = refCon.readNext();
       CSVRecord test = testCon.readNext();
       if (reference == null) {
         Assert.assertNull(test);
         break;
       } else if (test == null) {
         Assert.assertNull(reference);
         break;
       } else {
         count++;
         Assert.assertNotSame(reference, test);
         Assert.assertEquals(reference, test);
       }
     } while (true);
     Assert.assertEquals(37, count);
   }
 }
  @Test
  public void buttonIsAddedToLeftNavigation() {
    Navbar navbar = new Navbar("id");
    navbar.addComponents(
        new INavbarComponent() {
          @Override
          public Component create(String markupId) {
            return new NavbarButton<Page>(Page.class, Model.of("Link Name"));
          }

          @Override
          public Navbar.ComponentPosition getPosition() {
            return Navbar.ComponentPosition.LEFT;
          }
        });

    tester().startComponentInPage(navbar);
    TagTester tagTester = tester().getTagByWicketId("navLeftList");

    Assert.assertThat(tagTester.hasChildTag("a"), is(equalTo(true)));
    Assert.assertThat(
        tester().getTagByWicketId(Navbar.componentId()).hasAttribute("href"), is(equalTo(true)));
    Assert.assertThat(
        tester().getTagByWicketId(Navbar.componentId()).getValue(), containsString("Link Name"));
  }
Example #10
0
 @Test
 public void testBoolean() {
   Response response = client.target(generateURL("/boolean")).request().post(Entity.text("true"));
   Assert.assertEquals(response.getStatus(), 200);
   Assert.assertEquals(response.readEntity(String.class), "true");
   response.close();
 }
Example #11
0
  /** 先增加,再查找,再删除,再查找 */
  @Test
  public void operateUser() {
    // 先新增一个对象
    User user = new User(username, password, cellphone, levelId, userStatus);

    // 1. 保存
    User userNew = userService.saveUser(user);

    // 更新属性
    // 2. 更新
    String newCellphone = "13999999999";
    userNew.setCellphone(newCellphone);
    userService.updateUser(userNew);

    // 3. 查找
    // 3.1 通过用户ID查找
    User userDB = userService.findUserByUsernameAndPassword(username, password);
    Assert.assertNotNull(userDB);

    // 3.2 查找(通过手机号码查找用户)
    userDB = userService.findUserByCellphone(newCellphone);
    Assert.assertNotNull(userDB);
    Assert.assertEquals(newCellphone, userDB.getCellphone());

    // 3.3 通过用户名查找用户
    userDB = userService.findUserByUserName(userNew.getUsername());
    Assert.assertNotNull(userDB);

    // 4. 删除
    userService.removeUser(userDB.getUserId());

    // 5.通过用户名密码查找用户
    userDB = userService.loadUser(userNew.getUserId());
    Assert.assertNull(userDB);
  }
  @Test
  public void testProductCRUD() {

    // create local product object
    Product product = SolrTestUtils.createProduct(PRODUCT_ID);

    // save product to Solr Index and confirm index count increased by 1
    repo.save(product);
    Assert.assertEquals(INITIAL_RECORD_COUNT + 1, repo.count());

    // find single product from Solr
    Product loaded = repo.findOne(Integer.toString(PRODUCT_ID));
    Assert.assertEquals(product.getName(), loaded.getName());

    // update product name in Solr and confirm index count not changed
    loaded.setName("changed named");
    repo.save(loaded);
    Assert.assertEquals(INITIAL_RECORD_COUNT + 1, repo.count());

    // retrieve product from Solr and confirm name change
    loaded = repo.findOne(Integer.toString(PRODUCT_ID));
    Assert.assertEquals("changed named", loaded.getName());

    // delete the test product in Solr and confirm index count equal to initial count
    repo.delete(loaded);
    Assert.assertEquals(INITIAL_RECORD_COUNT, repo.count());
  }
  @Test
  public void testKafkaLog4jConfigs() {
    // host missing
    Properties props = new Properties();
    props.put("log4j.rootLogger", "INFO");
    props.put("log4j.appender.KAFKA", "org.apache.kafka.log4jappender.KafkaLog4jAppender");
    props.put("log4j.appender.KAFKA.layout", "org.apache.log4j.PatternLayout");
    props.put("log4j.appender.KAFKA.layout.ConversionPattern", "%-5p: %c - %m%n");
    props.put("log4j.appender.KAFKA.Topic", "test-topic");
    props.put("log4j.logger.kafka.log4j", "INFO, KAFKA");

    try {
      PropertyConfigurator.configure(props);
      Assert.fail("Missing properties exception was expected !");
    } catch (ConfigException ex) {
      // It's OK!
    }

    // topic missing
    props = new Properties();
    props.put("log4j.rootLogger", "INFO");
    props.put("log4j.appender.KAFKA", "org.apache.kafka.log4jappender.KafkaLog4jAppender");
    props.put("log4j.appender.KAFKA.layout", "org.apache.log4j.PatternLayout");
    props.put("log4j.appender.KAFKA.layout.ConversionPattern", "%-5p: %c - %m%n");
    props.put("log4j.appender.KAFKA.brokerList", "127.0.0.1:9093");
    props.put("log4j.logger.kafka.log4j", "INFO, KAFKA");

    try {
      PropertyConfigurator.configure(props);
      Assert.fail("Missing properties exception was expected !");
    } catch (ConfigException ex) {
      // It's OK!
    }
  }
Example #14
0
  @org.junit.Test
  public void testCreateUnsignedJWT() throws Exception {
    TokenProvider jwtTokenProvider = new JWTTokenProvider();
    ((JWTTokenProvider) jwtTokenProvider).setSignToken(false);

    TokenProviderParameters providerParameters = createProviderParameters();

    assertTrue(jwtTokenProvider.canHandleToken(JWTTokenProvider.JWT_TOKEN_TYPE));
    TokenProviderResponse providerResponse = jwtTokenProvider.createToken(providerParameters);
    assertTrue(providerResponse != null);
    assertTrue(providerResponse.getToken() != null && providerResponse.getTokenId() != null);

    String token = (String) providerResponse.getToken();
    assertNotNull(token);
    assertTrue(token.split("\\.").length == 2);

    // Validate the token
    JwsJwtCompactConsumer jwtConsumer = new JwsJwtCompactConsumer(token);
    JwtToken jwt = jwtConsumer.getJwtToken();
    Assert.assertEquals("alice", jwt.getClaim(JwtConstants.CLAIM_SUBJECT));
    Assert.assertEquals(providerResponse.getTokenId(), jwt.getClaim(JwtConstants.CLAIM_JWT_ID));
    Assert.assertEquals(
        providerResponse.getCreated().getTime() / 1000L,
        jwt.getClaim(JwtConstants.CLAIM_ISSUED_AT));
    Assert.assertEquals(
        providerResponse.getExpires().getTime() / 1000L, jwt.getClaim(JwtConstants.CLAIM_EXPIRY));
  }
  @Test
  public void testClusterModeHadoopDbFileAbsPath() {
    List<GeolocationFieldConfig> configs = new ArrayList<>();
    GeolocationFieldConfig config;
    config = new GeolocationFieldConfig();
    config.inputFieldName = "/ipAsInt";
    config.outputFieldName = "/intIpCountry";
    config.targetType = GeolocationField.COUNTRY_NAME;
    configs.add(config);

    ProcessorRunner runner =
        new ProcessorRunner.Builder(GeolocationDProcessor.class)
            .setOnRecordError(OnRecordError.STOP_PIPELINE)
            .addConfiguration("geoIP2DBFile", databaseFile.getAbsolutePath())
            .addConfiguration("fieldTypeConverterConfigs", configs)
            .setExecutionMode(ExecutionMode.CLUSTER_BATCH)
            .addOutputLane("a")
            .build();
    try {
      runner.runInit();
      Assert.fail(
          Utils.format(
              "Expected StageException as absolute database file path '{}' is specified in cluster mode",
              databaseFile.getAbsolutePath()));
    } catch (StageException e) {
      Assert.assertTrue(e.getMessage().contains("GEOIP_10"));
    }
  }
 @Test
 public void testValidateEmailId() {
   String email = "jitendra.sonkar@freestoneinfotech.com";
   boolean value = stringUtil.validateEmail(email);
   Assert.assertTrue(email.length() < 128);
   Assert.assertTrue(value);
 }
Example #17
0
  @Test
  public void testCachedPut() throws Exception {
    HttpFields header = new HttpFields();

    header.put("Connection", "Keep-Alive");
    header.put("tRansfer-EncOding", "CHUNKED");
    header.put("CONTENT-ENCODING", "gZIP");

    ByteBuffer buffer = BufferUtil.allocate(1024);
    BufferUtil.flipToFill(buffer);
    HttpGenerator.putTo(header, buffer);
    BufferUtil.flipToFlush(buffer, 0);
    String out = BufferUtil.toString(buffer).toLowerCase();

    Assert.assertThat(
        out,
        Matchers.containsString(
            (HttpHeader.CONNECTION + ": " + HttpHeaderValue.KEEP_ALIVE).toLowerCase()));
    Assert.assertThat(
        out,
        Matchers.containsString(
            (HttpHeader.TRANSFER_ENCODING + ": " + HttpHeaderValue.CHUNKED).toLowerCase()));
    Assert.assertThat(
        out,
        Matchers.containsString(
            (HttpHeader.CONTENT_ENCODING + ": " + HttpHeaderValue.GZIP).toLowerCase()));
  }
Example #18
0
  @Test
  public void buttonWithIconIsAddedToLeftNavigation() {
    Navbar navbar = new Navbar("id");
    navbar.addComponents(
        new INavbarComponent() {
          @Override
          public Component create(String markupId) {
            return new NavbarButton<Page>(Page.class, Model.of("Link Name"))
                .setIconType(IconType.aligncenter);
          }

          @Override
          public Navbar.ComponentPosition getPosition() {
            return Navbar.ComponentPosition.LEFT;
          }
        });

    tester().startComponentInPage(navbar);

    Assert.assertThat(
        tester().getTagByWicketId(Navbar.componentId()).hasChildTag("i"), is(equalTo(true)));
    Assert.assertThat(
        tester().getTagByWicketId("icon").getAttribute("class"),
        containsString("icon-align-center"));
  }
 @Test
 public void testExtendedVersion() throws Exception {
   String version = "0.9.2-dart";
   SemVer semVer = SemVer.parseFromText(version);
   Assert.assertNotNull(semVer);
   Assert.assertEquals(new SemVer(version, 0, 9, 2), semVer);
 }
  @Test
  public void testAutoSend() throws Exception {
    ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
    TelnetOutputStream out = new TelnetOutputStream(byteOut);
    out.autoSend();
    out.flush();
    byte[] message = byteOut.toByteArray();

    Assert.assertNotNull("Auto message not sent", message);
    Assert.assertFalse("Auto message not sent", message.length == 0);
    Assert.assertTrue(
        "Error sending auto message. Expected length: "
            + TelnetOutputStream.autoMessage.length
            + ", actual length: "
            + message.length,
        message.length == TelnetOutputStream.autoMessage.length);

    for (int i = 0; i < message.length; i++) {
      Assert.assertEquals(
          "Wrong char in auto message. Position: "
              + i
              + ", expected: "
              + TelnetOutputStream.autoMessage[i]
              + ", read: "
              + message[i],
          TelnetOutputStream.autoMessage[i],
          message[i]);
    }
  }
Example #21
0
  private void verifyOutboundQueues(Session session) throws Exception {
    int countJca = receiveUntilEmpty(session, _outboundQueueJca);
    Assert.assertEquals("JCA queue should contains 3 messages", 3, countJca);

    int countCamel = receiveUntilEmpty(session, _outboundQueue);
    Assert.assertEquals("Camel queue should contains 3 messages", 3, countCamel);
  }
  @Test
  public void testTelemetryModulesWithoutParameters() {
    MockTelemetryModule module = generateTelemetryModules(false);

    Assert.assertNotNull(module);
    Assert.assertNull(module.getParam1());
  }
  @Test(timeout = 1000)
  public void testGenerator() throws Exception {
    // load the resource
    ResourceSet set = this.resourceSetProvider.get();
    URI uri = URI.createURI("res/Test0139_LineBreakInString.c");
    Resource resource = set.getResource(uri, true);
    // validate the resource
    List<Issue> list = this.validator.validate(resource, CheckMode.ALL, CancelIndicator.NullImpl);
    Assert.assertTrue(list.isEmpty());

    // configure and start the generator
    this.fileAccessSystem.setOutputPath("bin");
    final Class<?> clazz = this.generator.getClass();
    try {
      final Method method = clazz.getMethod("setFileName", String.class);
      if (method != null) {
        method.invoke(this.generator, "Test0139_LineBreakInString.c.i");
      }
    } catch (NoSuchMethodException
        | SecurityException
        | IllegalAccessException
        | IllegalArgumentException
        | InvocationTargetException e) {
      // do nothing
    }
    this.generator.doGenerate(resource, this.fileAccessSystem);
    final String actual = this.getTextFromFile("bin/Test0139_LineBreakInString.c.i");
    final String expected = this.getTextFromFile("expected/Test0139_LineBreakInString.c");
    Assert.assertEquals(preprocess(expected), preprocess(actual));
  }
  @Test
  public void testTelemetryModulesWithParameters() {
    MockTelemetryModule module = generateTelemetryModules(true);

    Assert.assertNotNull(module);
    Assert.assertEquals("value1", module.getParam1());
  }
    @Override
    public void join(
        IntPair rec1, Tuple2<Integer, String> rec2, Collector<Tuple2<Integer, String>> out)
        throws Exception {
      final int k = rec1.getKey();
      final int v = rec1.getValue();

      final Integer key = rec2.f0;
      final String value = rec2.f1;

      Assert.assertTrue("Key does not match for matching IntPair Tuple combination.", k == key);

      Collection<TupleIntPairMatch> matches = this.toRemoveFrom.get(key);
      if (matches == null) {
        Assert.fail("Match " + key + " - " + v + ":" + value + " is unexpected.");
      }

      Assert.assertTrue(
          "Produced match was not contained: " + key + " - " + v + ":" + value,
          matches.remove(new TupleIntPairMatch(v, value)));

      if (matches.isEmpty()) {
        this.toRemoveFrom.remove(key);
      }
    }
 @Test
 public void testOldFormatContent() throws OrekitException, ParseException {
   setRoot("regular-data");
   IERSConventions.NutationCorrectionConverter converter =
       IERSConventions.IERS_2010.getNutationCorrectionConverter();
   SortedSet<EOPEntry> data = new TreeSet<EOPEntry>(new ChronologicalComparator());
   new BulletinBFilesLoader(FramesFactory.BULLETINB_2000_FILENAME).fillHistory(converter, data);
   EOPHistory history = new EOPHistory(IERSConventions.IERS_2010, data, true);
   AbsoluteDate date = new AbsoluteDate(2006, 1, 11, 12, 0, 0, TimeScalesFactory.getUTC());
   Assert.assertEquals(
       msToS((-3 * 0.073 + 27 * -0.130 + 27 * -0.244 - 3 * -0.264) / 48),
       history.getLOD(date),
       1.0e-10);
   Assert.assertEquals(
       (-3 * 0.333275 + 27 * 0.333310 + 27 * 0.333506 - 3 * 0.333768) / 48,
       history.getUT1MinusUTC(date),
       1.0e-10);
   Assert.assertEquals(
       asToRad((-3 * 0.04958 + 27 * 0.04927 + 27 * 0.04876 - 3 * 0.04854) / 48),
       history.getPoleCorrection(date).getXp(),
       1.0e-10);
   Assert.assertEquals(
       asToRad((-3 * 0.38117 + 27 * 0.38105 + 27 * 0.38071 - 3 * 0.38036) / 48),
       history.getPoleCorrection(date).getYp(),
       1.0e-10);
 }
Example #27
0
  /** Tests the method to fill the Reserved Expansion Field with a velocity value. */
  @Test
  public void testPrepareREForCat062() throws Exception {

    TrackVelocity trackVelocity = new TrackVelocity((short) 1, (short) 5, 5.5);
    REForCat062 re = new REForCat062((short) 62, 5, "description", new ArrayList<DataItem>());

    ByteBuffer buffer =
        REForCat062Container.getDefaultBuffer(re.getSubTypeDescriptor(), trackVelocity);

    byte[] bytes =
        new byte[] {
          0x6, // length
          0x20, // item indicator 00100000 (only the 3rd item is present)
          0x0, 0x1, 0x0, 0x5
        }; // values of the velocity

    Assert.assertEquals(ByteBuffer.wrap(bytes), buffer);

    // another test
    trackVelocity = new TrackVelocity((short) 2, (short) 7, 5.5);
    buffer = REForCat062Container.getDefaultBuffer(re.getSubTypeDescriptor(), trackVelocity);
    bytes[3] = 0x2;
    bytes[5] = 0x7;

    Assert.assertEquals(ByteBuffer.wrap(bytes), buffer);
  }
 @Test
 public void testNormalizeEmailIdNull() {
   String email = null;
   String lowercase = stringUtil.normalizeEmail(email);
   Assert.assertEquals(lowercase, email);
   Assert.assertNull(lowercase);
 }
Example #29
0
  @Test
  public void testLargeMeanCumulativeProbability() {
    double mean = 1.0;
    while (mean <= 10000000.0) {
      PoissonDistribution dist = new PoissonDistribution(mean);

      double x = mean * 2.0;
      double dx = x / 10.0;
      double p = Double.NaN;
      double sigma = FastMath.sqrt(mean);
      while (x >= 0) {
        try {
          p = dist.cumulativeProbability((int) x);
          Assert.assertFalse(
              "NaN cumulative probability returned for mean = " + mean + " x = " + x,
              Double.isNaN(p));
          if (x > mean - 2 * sigma) {
            Assert.assertTrue(
                "Zero cum probaility returned for mean = " + mean + " x = " + x, p > 0);
          }
        } catch (Exception ex) {
          Assert.fail("mean of " + mean + " and x of " + x + " caused " + ex.getMessage());
        }
        x -= dx;
      }

      mean *= 10.0;
    }
  }
Example #30
0
 @Test
 public void testOptional() {
   Optional<String> fullName = Optional.ofNullable(null);
   Assert.assertEquals("Optional.empty", fullName.toString());
   Assert.assertEquals("[none]", fullName.orElseGet(() -> "[none]"));
   Assert.assertEquals("[none2]", fullName.orElse("[none2]"));
 }