Java Code Examples for org.testng.Assert

The following examples show how to use org.testng.Assert. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: submarine   Source File: dataIT.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void dataNavigation() throws Exception {
  // Login
  LOG.info("Login");
  pollingWait(By.cssSelector("input[ng-reflect-name='userName']"), MAX_BROWSER_TIMEOUT_SEC).sendKeys("admin");
  pollingWait(By.cssSelector("input[ng-reflect-name='password']"), MAX_BROWSER_TIMEOUT_SEC).sendKeys("admin");
  clickAndWait(By.cssSelector("button[class='login-form-button ant-btn ant-btn-primary']"));
  pollingWait(By.cssSelector("a[routerlink='/workbench/dashboard']"), MAX_BROWSER_TIMEOUT_SEC);

  // Routing to data page
  pollingWait(By.xpath("//span[contains(text(), \"Data\")]"), MAX_BROWSER_TIMEOUT_SEC).click();
  Assert.assertEquals(driver.getCurrentUrl(), "http://localhost:8080/workbench/data");

  // Test create new Table
  pollingWait(By.xpath("//button[@id='createBtn']"), MAX_BROWSER_TIMEOUT_SEC).click();
  Assert.assertEquals(pollingWait(By.xpath("//form"), MAX_BROWSER_TIMEOUT_SEC).isDisplayed(), true);

  pollingWait(By.xpath("//button[@id='firstNextBtn']"), MAX_BROWSER_TIMEOUT_SEC).click();
  pollingWait(By.xpath("//input[@id='tableName']"), MAX_BROWSER_TIMEOUT_SEC).sendKeys("e2e test Table");
  pollingWait(By.xpath("//button[@id='secondNextBtn']"), MAX_BROWSER_TIMEOUT_SEC).click();

  pollingWait(By.xpath("//button[@id='submit']"), MAX_BROWSER_TIMEOUT_SEC).click();
  Assert.assertEquals(pollingWait(By.xpath("//thead"), MAX_BROWSER_TIMEOUT_SEC).isDisplayed(), true);
}
 
Example 2
Source Project: carbon-device-mgt   Source File: BSTAuthenticatorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test(description = "This test case tests the canHandle method of the BSTAuthenticator under faulty conditions")
public void testCanHandleWithFalseConditions() throws IllegalAccessException {
    Request request = new Request();
    org.apache.coyote.Request coyoteRequest = new org.apache.coyote.Request();
    request.setCoyoteRequest(coyoteRequest);
    Assert.assertFalse(bstAuthenticator.canHandle(request),
            "BST Authenticator can handle a request without content type");

    MimeHeaders mimeHeaders = new MimeHeaders();
    MessageBytes bytes = mimeHeaders.addValue("content-type");
    bytes.setString("test");
    headersField.set(coyoteRequest, mimeHeaders);
    request.setCoyoteRequest(coyoteRequest);
    Assert.assertFalse(bstAuthenticator.canHandle(request),
            "BST Authenticator can handle a request with content type test");
}
 
Example 3
@RunAsClient
@Test(groups = TEST_GROUP_CONFIG,
    description = "Validate specifying the mp.jwt.decrypt.key.location as resource path to a JWK key")
public void testKeyAsLocation() throws Exception {
    Reporter.log("testKeyAsLocation, expect HTTP_OK");

    PublicKey publicKey = TokenUtils.readJwkPublicKey("/encryptorPublicKey.jwk");
    String kid = "mp-jwt";
    String token = TokenUtils.encryptClaims(publicKey, kid, "/Token1.json");

    String uri = baseURL.toExternalForm() + "jwks/endp/verifyKeyLocationAsJWKResource";
    WebTarget echoEndpointTarget = ClientBuilder.newClient()
        .target(uri)
        .queryParam("kid", kid);
    Response response = echoEndpointTarget.request(APPLICATION_JSON).header(HttpHeaders.AUTHORIZATION, "Bearer "+token).get();
    Assert.assertEquals(response.getStatus(), HttpURLConnection.HTTP_OK);
    String replyString = response.readEntity(String.class);
    JsonReader jsonReader = Json.createReader(new StringReader(replyString));
    JsonObject reply = jsonReader.readObject();
    Reporter.log(reply.toString());
    Assert.assertTrue(reply.getBoolean("pass"), reply.getString("msg"));
}
 
Example 4
Source Project: helix   Source File: TestRoutingDataCache.java    License: Apache License 2.0 6 votes vote down vote up
@Test()
public void testUpdateOnNotification() throws Exception {
  MockZkHelixDataAccessor accessor =
      new MockZkHelixDataAccessor(CLUSTER_NAME, new ZkBaseDataAccessor<ZNRecord>(_gZkClient));

  RoutingDataCache cache =
      new RoutingDataCache("CLUSTER_" + TestHelper.getTestClassName(), PropertyType.EXTERNALVIEW);
  cache.refresh(accessor);
  Assert.assertEquals(accessor.getReadCount(PropertyType.EXTERNALVIEW), 1);

  accessor.clearReadCounters();

  // refresh again should read nothing
  cache.refresh(accessor);
  Assert.assertEquals(accessor.getReadCount(PropertyType.EXTERNALVIEW), 0);

  accessor.clearReadCounters();
  // refresh again should read nothing as ideal state is same
  cache.notifyDataChange(HelixConstants.ChangeType.EXTERNAL_VIEW);
  cache.refresh(accessor);
  Assert.assertEquals(accessor.getReadCount(PropertyType.EXTERNALVIEW), 0);
}
 
Example 5
Source Project: openjdk-jdk8u   Source File: Main.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Test(dataProvider="callHandlerDataProvider")
public void runTest(boolean callGetMessageInHandler) throws Exception {
    CountDownLatch serverInitSignal = new CountDownLatch(1);
    CountDownLatch testDoneSignal = new CountDownLatch(1);

    WebserviceRunner serverThread = new WebserviceRunner(serverInitSignal, testDoneSignal);
    (new Thread(serverThread)).start();

    serverInitSignal.await();

    boolean paramModified = runClientCode(serverThread.getPort(), callGetMessageInHandler);

    testDoneSignal.countDown();

    Assert.assertEquals(callGetMessageInHandler, paramModified,
        "WS parameter has not been processed as expected");
}
 
Example 6
Source Project: curator   Source File: TestTreeCache.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testFromRootWithDepth() throws Exception
{
    client.create().forPath("/test");
    client.create().forPath("/test/one", "hey there".getBytes());

    cache = buildWithListeners(TreeCache.newBuilder(client, "/").setMaxDepth(1));
    cache.start();
    assertEvent(TreeCacheEvent.Type.NODE_ADDED, "/");
    assertEvent(TreeCacheEvent.Type.NODE_ADDED, "/test");
    assertEvent(TreeCacheEvent.Type.INITIALIZED);
    assertNoMoreEvents();

    Assert.assertTrue(cache.getCurrentChildren("/").keySet().contains("test"));
    Assert.assertEquals(cache.getCurrentChildren("/test").keySet(), ImmutableSet.of());
    Assert.assertNull(cache.getCurrentData("/test/one"));
    Assert.assertNull(cache.getCurrentChildren("/test/one"));
}
 
Example 7
Source Project: djl   Source File: PaddingStackBatchifierTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testUnbatchify() {
    try (NDManager manager = NDManager.newBaseManager()) {
        NDList input =
                new NDList(manager.zeros(new Shape(10, 11)), manager.zeros(new Shape(10)));
        Batchifier batchifier =
                PaddingStackBatchifier.builder()
                        .optIncludeValidLengths(false)
                        .addPad(0, 1, (mngr) -> mngr.zeros(new Shape(10, 1)))
                        .build();
        NDList[] actual = batchifier.unbatchify(input);

        Assert.assertEquals(actual.length, 10);
        for (NDList arrays : actual) {
            Assert.assertEquals(arrays.size(), 2);
            Assert.assertEquals(arrays.get(0).getShape(), new Shape(11));
            Assert.assertEquals(arrays.get(1).getShape(), new Shape());
        }
    }
}
 
Example 8
Source Project: jenetics   Source File: MultiPointCrossoverTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test(dataProvider = "crossoverParameters")
public void crossover(
	final String stringA,
	final String stringB,
	final Seq<Integer> points,
	final String expectedA,
	final String expectedB
) {
	final ISeq<Character> a = CharSeq.toISeq(stringA);
	final ISeq<Character> b = CharSeq.toISeq(stringB);

	final MSeq<Character> ma = a.copy();
	final MSeq<Character> mb = b.copy();

	final int[] intPoints = points.stream()
		.mapToInt(Integer::intValue)
		.toArray();

	MultiPointCrossover.crossover(ma, mb, intPoints);
	Assert.assertEquals(toString(ma), expectedA);
	Assert.assertEquals(toString(mb), expectedB);
}
 
Example 9
@Test(dataProvider = "bindingData")
public void testCreateBinding(String queueName, String bindingPattern) throws IOException, TimeoutException {

    Channel channel = amqpConnection.createChannel();
    channel.queueDeclare(queueName, false, false, false, new HashMap<>());
    String exchangeName = "amq.direct";
    HttpPost httpPost = new HttpPost(apiBasePath + "/queues/" + queueName + "/bindings");
    ClientHelper.setAuthHeader(httpPost, username, password);
    BindingCreateRequest createRequest = new BindingCreateRequest().bindingPattern(bindingPattern)
                                                                   .exchangeName(exchangeName);

    String payloadString = objectMapper.writeValueAsString(createRequest);
    StringEntity stringEntity = new StringEntity(payloadString, ContentType.APPLICATION_JSON);
    httpPost.setEntity(stringEntity);

    CloseableHttpResponse response = client.execute(httpPost);

    Assert.assertEquals(response.getStatusLine().getStatusCode(), HttpStatus.SC_CREATED);

    BindingCreateResponse responseMessage = HttpClientHelper.getResponseMessage(response,
                                                                                BindingCreateResponse.class);
    Assert.assertEquals(responseMessage.getMessage(), "Binding created.");

    channel.queueUnbind(queueName, exchangeName, bindingPattern);
    channel.close();
}
 
Example 10
Source Project: micro-integrator   Source File: IterateClient.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * This is used to send a request which contains several getquote elements
 *
 * @param address service address
 * @param symbol  stock quote symbol
 * @return
 * @throws IOException
 */
public String getGetQuotesResponse(String address, String symbol, int iterations) throws IOException {

    AxisOperationClient operationClient = new AxisOperationClient();
    OMElement response = null;
    try {
        response = operationClient
                .send(address, null, createGetQuotesRequestBody(symbol, iterations), "urn:getQuote");
    } finally {
        operationClient.destroy();
    }
    Assert.assertNotNull(response, "Response null");

    return response.toString();

}
 
Example 11
Source Project: jenetics   Source File: FitnessConvergenceLimitTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void stream() {
	final long seed = 0xdeadbeef;
	final int capacity = 10;

	final Random random = new Random(seed);
	final Buffer buffer = new Buffer(capacity);

	for (int i = 0; i < buffer.capacity(); ++i) {
		final double value = random.nextDouble();
		buffer.accept(value);
	}

	random.setSeed(seed);
	buffer.stream().forEach(d -> Assert.assertEquals(d, random.nextDouble()));

	random.setSeed(seed);
	for (int i = 0; i < 5; ++i) random.nextDouble();
	buffer.stream(5).forEach(d -> Assert.assertEquals(d, random.nextDouble()));
}
 
Example 12
Source Project: microprofile-config   Source File: ArrayConverterTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testOptionalInstantArrayLookupProgrammatically() {
    Optional<Instant[]> optionalValue = config.getOptionalValue("tck.config.test.javaconfig.converter.instantvalues",
           Instant[].class);
    Assert.assertTrue(optionalValue.isPresent());
    Instant[] value = optionalValue.get();
    Assert.assertNotNull(value);
    Assert.assertEquals(value.length, 2);
    Assert.assertEquals(value,  new Instant[]{
        Instant.parse("2015-06-02T21:34:33.616Z"),
        Instant.parse("2017-06-02T21:34:33.616Z")});
    Optional<Instant[]> optionalSingle = config.getOptionalValue("tck.config.test.javaconfig.converter.instantvalue",
           Instant[].class);
    Assert.assertTrue(optionalSingle.isPresent());
    Instant[] single = optionalSingle.get();
    Assert.assertNotNull(single);
    Assert.assertEquals(single.length, 1);
    Assert.assertEquals(single,  new Instant[]{ Instant.parse("2015-06-02T21:34:33.616Z") });
}
 
Example 13
Source Project: djl   Source File: NDIndexTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testSetNumber() {
    try (NDManager manager = NDManager.newBaseManager()) {
        NDArray original = manager.create(new float[] {1, 2, 3, 4}, new Shape(2, 2));
        NDArray expected = manager.create(new float[] {9, 9, 3, 4}, new Shape(2, 2));
        original.set(new NDIndex(0), 9);
        Assert.assertEquals(original, expected);

        original = manager.arange(4f).reshape(2, 2);
        expected = manager.ones(new Shape(2, 2));
        original.set(new NDIndex("..."), 1);
        Assert.assertEquals(original, expected);

        original = manager.arange(4f).reshape(2, 2);
        expected = manager.create(new float[] {1, 1, 1, 3}).reshape(2, 2);
        original.set(new NDIndex("..., 0"), 1);
        Assert.assertEquals(original, expected);
    }
}
 
Example 14
@Test
public void testSatisfySuperTemplateRequirements() throws Exception {
  TestTemplate template1 = new TestTemplate(new URI("template1"), Lists.<JobTemplate>newArrayList(), ImmutableMap.of("key1", "value1"),
      Lists.newArrayList("required"));
  TestTemplate template2 = new TestTemplate(new URI("template2"), Lists.<JobTemplate>newArrayList(template1), ImmutableMap.of("required", "r1"),
      Lists.newArrayList("required2"));

  Collection<String> required = template2.getRequiredConfigList();
  Assert.assertEquals(required.size(), 1);
  Assert.assertTrue(required.contains("required2"));

  Config rawTemplate = template2.getRawTemplateConfig();
  Assert.assertEquals(rawTemplate.getString("key1"), "value1");
  Assert.assertEquals(rawTemplate.getString("required"), "r1");

  Config resolved = template2.getResolvedConfig(ConfigFactory.parseMap(ImmutableMap.of("required2", "r2")));
  Assert.assertEquals(resolved.getString("key1"), "value1");
  Assert.assertEquals(resolved.getString("required"), "r1");
  Assert.assertEquals(resolved.getString("required2"), "r2");
}
 
Example 15
Source Project: tasmo   Source File: JsonNodeMarshallerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test(dataProviderClass = ObjectIdTestDataProvider.class, dataProvider = "createObjectId")
public void testMarshaller(String className, long longId) throws Exception {
    JsonNodeMarshaller jsonNodeMarshaller = new JsonNodeMarshaller();

    ObjectId objectId1 = new ObjectId(className, new Id(longId));
    ObjectMapper mapper = new ObjectMapper();
    String json = mapper.writeValueAsString(objectId1);
    JsonNode jsonNode = mapper.readTree(json);

    //    JsonNode node = objectMapper.valueToTree(map);
    //    JsonNode node = mapper.convertValue(object, JsonNode.class);

    byte[] bytes = jsonNodeMarshaller.toBytes(jsonNode);
    JsonNode jsonNode1 = jsonNodeMarshaller.fromBytes(bytes);

    ObjectId objectId2 = mapper.convertValue(jsonNode1, ObjectId.class);

    System.out.println("before JsonNodeMarshaller: objectId=" + objectId1.toStringForm());
    System.out.println("after JsonNodeMarshaller : objectId=" + objectId2.toStringForm());

    Assert.assertTrue(objectId1.equals(objectId2), " marshalled object should be equal to the original");
}
 
Example 16
Source Project: jdk8u_jdk   Source File: CheckArrayTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Test SharedSecrets checkArray with unmodified ObjectInputStream.
 */
@Test(dataProvider = "Patterns")
public void normalOIS(String pattern, int arraySize, Object[] array) throws IOException {
    ObjectInputFilter filter = ObjectInputFilter.Config.createFilter(pattern);
    byte[] bytes = SerialFilterTest.writeObjects(array);
    try (ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
         ObjectInputStream ois = new ObjectInputStream(bais)) {
        // Check the arraysize against the filter
        try {
            ObjectInputFilter.Config.setObjectInputFilter(ois, filter);
            SharedSecrets.getJavaOISAccess()
                    .checkArray(ois, array.getClass(), arraySize);
            Assert.assertTrue(array.length >= arraySize,
                    "Should have thrown InvalidClassException due to array size");
        } catch (InvalidClassException ice) {
            Assert.assertFalse(array.length > arraySize,
                    "Should NOT have thrown InvalidClassException due to array size");
        }
    }
}
 
Example 17
@Test
public void testSslConsumerProperties() {
  Properties overrides = new Properties();
  String groupId = "groupId";
  KafkaConnectionString connectionString = KafkaConnectionString.valueOf("kafkassl://MyBroker:10251/MyTopic");
  Properties actual = KafkaConnectorTask.getKafkaConsumerProperties(overrides, groupId, connectionString);

  Properties expected = new Properties();
  expected.put("auto.offset.reset", "none");
  expected.put("bootstrap.servers", "MyBroker:10251");
  expected.put("enable.auto.commit", "false");
  expected.put("group.id", "groupId");
  expected.put("security.protocol", "SSL");

  Assert.assertEquals(actual, expected);
}
 
Example 18
@Test
public void unionEstimationMode() {
  int key = 0;
  UpdatableSketch<Double, DoubleSummary> sketch1 =
      new UpdatableSketchBuilder<>(new DoubleSummaryFactory(mode)).build();
  for (int i = 0; i < 8192; i++) {
    sketch1.update(key++, 1.0);
  }

  key -= 4096; // overlap half of the entries
  UpdatableSketch<Double, DoubleSummary> sketch2 =
      new UpdatableSketchBuilder<>(new DoubleSummaryFactory(mode)).build();
  for (int i = 0; i < 8192; i++) {
    sketch2.update(key++, 1.0);
  }

  Union<DoubleSummary> union = new Union<>(4096, new DoubleSummarySetOperations(mode, mode));
  union.update(sketch1);
  union.update(sketch2);
  CompactSketch<DoubleSummary> result = union.getResult();
  Assert.assertEquals(result.getEstimate(), 12288.0, 12288 * 0.01);
  Assert.assertTrue(result.getLowerBound(1) <= result.getEstimate());
  Assert.assertTrue(result.getUpperBound(1) > result.getEstimate());
}
 
Example 19
Source Project: bullet-core   Source File: MetricCollectorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testCounting() {
    MetricCollector collector = new MetricCollector();
    collector.add("foo", 4);
    collector.increment("foo");
    collector.increment("bar");

    Map<String, Number> metrics = collector.extractMetrics();
    Assert.assertEquals(metrics.size(), 2);
    Assert.assertEquals(metrics.get("foo"), 5L);
    Assert.assertEquals(metrics.get("bar"), 1L);
    Assert.assertNull(metrics.get("baz"));

    metrics = collector.extractMetrics();
    Assert.assertEquals(metrics.size(), 2);
    Assert.assertEquals(metrics.get("foo"), 0L);
    Assert.assertEquals(metrics.get("bar"), 0L);
    Assert.assertNull(metrics.get("baz"));
}
 
Example 20
Source Project: FHIR   Source File: ExtractParameterValuesTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * run test
 *
 * @param file
 * @param cls
 * @param debug
 * @param validator
 * @param skip
 * @throws Exception
 */
public static void runTest(String file, Class<? extends Resource> cls, boolean debug, ExtractorValidator validator, boolean skip) throws Exception {
    try (InputStream stream = ExtractParameterValuesTest.class.getResourceAsStream("/testdata/" + file)) {
        Resource res = FHIRParser.parser(Format.JSON).parse(stream);

        Map<SearchParameter, List<FHIRPathNode>> output;
        if (skip) {
            output = SearchUtil.extractParameterValues(res, false);
        } else {
            output = SearchUtil.extractParameterValues(res);
        }
        validator.validate(output);
    } catch (Exception e) {
        Assert.fail("Failed to process the test", e);
    }
}
 
Example 21
@Test
// NOTE, the gene list file was not generated with GATK3 due to different gene list merging behavior
public void testGeneListDataPartallylCovered() throws IOException {
    final File baseOutputFile = createTempDir("testNoCoverageDueToFiltering");
    final File output = IOUtils.createTempFileInDirectory( "testNoCoverageDueToFiltering", ".csv", baseOutputFile);

    String[] cmd = new String[]{ "-R",hg38Reference,
            "-I",largeFileTestDir+"multiSampleSubsetted.bam",
            "-L", "chr1:1656275-1677440", // this should only completely span two of the genes in the list
            "--calculate-coverage-over-genes",getTestFile("refGene_CDK11B.refseq").getAbsolutePath(),
            "--min-base-quality","0","--include-deletions","-pt","sample","--output-format","CSV","--omit-depth-output-at-each-base","--omit-per-sample-statistics","--omit-genes-not-entirely-covered-by-traversal",
            "-O",output.getAbsolutePath()};
    runCommandLine(cmd);

    try (final CSVReader actualParser = new CSVReader(new FileReader(output.getAbsolutePath()+".sample_gene_summary"))) {
        actualParser.readNext(); // Skip header line
        List<String[]> lines = actualParser.readAll();
        Assert.assertEquals(lines.size(), 2);
        // The only two genes completely encompassed by this interval span
        Assert.assertEquals(lines.get(0)[0], "SLC35E2");
        Assert.assertEquals(lines.get(1)[0], "SLC35E2");
        Assert.assertNotEquals(lines.get(0), lines.get(1));
    }
}
 
Example 22
Source Project: module-ballerina-kubernetes   Source File: Sample10Test.java    License: Apache License 2.0 5 votes vote down vote up
@Test(groups = {"integration"})
public void deploySample() throws IOException, InterruptedException {
    Assert.assertEquals(0, loadImage(BURGER_DOCKER_IMAGE));
    Assert.assertEquals(0, loadImage(PIZZA_DOCKER_IMAGE));
    Assert.assertEquals(0, deployK8s(BURGER_PKG_K8S_TARGET_PATH));
    Assert.assertEquals(0, deployK8s(PIZZA_PKG_K8S_TARGET_PATH));
    Assert.assertTrue(validateService("http://pizza.com/pizzastore/pizza/menu", "Pizza menu"));
    Assert.assertTrue(validateService("http://burger.com/menu", "Burger menu"));
    deleteK8s(BURGER_PKG_K8S_TARGET_PATH);
    deleteK8s(PIZZA_PKG_K8S_TARGET_PATH);
}
 
Example 23
Source Project: openapi-generator   Source File: DartModelTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test(description = "convert a model with a map property")
public void mapPropertyTest() {
    final Schema model = new Schema()
            .description("a sample model")
            .addProperties("translations", new MapSchema()
                    .additionalProperties(new StringSchema()))
            .addRequiredItem("id");
    final DefaultCodegen codegen = new DartClientCodegen();
    OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", model);
    codegen.setOpenAPI(openAPI);
    final CodegenModel cm = codegen.fromModel("sample", model);

    Assert.assertEquals(cm.name, "sample");
    Assert.assertEquals(cm.classname, "Sample");
    Assert.assertEquals(cm.description, "a sample model");
    Assert.assertEquals(cm.vars.size(), 1);

    final CodegenProperty property1 = cm.vars.get(0);
    Assert.assertEquals(property1.baseName, "translations");
    Assert.assertEquals(property1.dataType, "Map<String, String>");
    Assert.assertEquals(property1.name, "translations");
    Assert.assertEquals(property1.baseType, "Map");
    Assert.assertEquals(property1.containerType, "map");
    Assert.assertFalse(property1.required);
    Assert.assertTrue(property1.isContainer);
    Assert.assertTrue(property1.isPrimitiveType);
}
 
Example 24
@Override
protected void assertTestDisconnectUnidirectionalArrayReferenceFromClassType(
        List<ITypedReferenceableInstance> columns, String columnGuid) {
    Assert.assertEquals(columns.size(), 5);
    for (ITypedReferenceableInstance column : columns) {
        if (column.getId()._getId().equals(columnGuid)) {
            assertEquals(column.getId().getState(), Id.EntityState.DELETED);
        } else {
            assertEquals(column.getId().getState(), Id.EntityState.ACTIVE);
        }
    }

}
 
Example 25
Source Project: cql_engine   Source File: CqlTypeOperatorsTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
     * {@link org.opencds.cqf.cql.elm.execution.ToTimeEvaluator#evaluate(Context)}
     */
    @Test
    public void testToTime() throws JAXBException {
        // TODO: fix timezone tests
        Context context = new Context(library);

        BigDecimal offset = TemporalHelper.getDefaultOffset();
        Object result = context.resolveExpressionRef("ToTime1").getExpression().evaluate(context);
        Assert.assertTrue(EquivalentEvaluator.equivalent(result, new Time(offset, 14, 30, 0, 0)));
        // assertThat(((Time)result).getTimezoneOffset(), is(new BigDecimal("-7")));

        result = context.resolveExpressionRef("ToTime2").getExpression().evaluate(context);
        Assert.assertTrue(EquivalentEvaluator.equivalent(result, new Time(new BigDecimal("5.5"), 14, 30, 0, 0)));
        // assertThat(((Time)result).getTimezoneOffset(), is(new BigDecimal("5.5")));

        result = context.resolveExpressionRef("ToTime3").getExpression().evaluate(context);
        Assert.assertTrue(EquivalentEvaluator.equivalent(result, new Time(new BigDecimal("-5.75"), 14, 30, 0, 0)));
        // assertThat(((Time)result).getTimezoneOffset(), is(new BigDecimal("-5.75")));

        result = context.resolveExpressionRef("ToTime4").getExpression().evaluate(context);
        Assert.assertTrue(EquivalentEvaluator.equivalent(result, new Time(new BigDecimal(0), 14, 30, 0, 0)));
        // assertThat(((Time)result).getTimezoneOffset(), is(new BigDecimal("-7")));

//        try {
//            context.resolveExpressionRef("ToTimeMalformed").getExpression().evaluate(context);
//            Assert.fail();
//        } catch (DateTimeParseException iae) {
//            // pass
//        }
    }
 
Example 26
Source Project: micro-integrator   Source File: IterateClient.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @param address
 * @param symbol
 * @return
 * @throws IOException
 */
public String getResponse(String address, String symbol) throws IOException {
    AxisOperationClient operationClient = new AxisOperationClient();
    OMElement response = null;
    try {
        response = operationClient.send(address, null, createSimpleQuoteRequestBody(symbol), "urn:getQuote");
    } finally {
        operationClient.destroy();
    }
    Assert.assertNotNull(response, "Response null");
    return response.toString();

}
 
Example 27
Source Project: incubator-gobblin   Source File: CouchbaseTestServer.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public static void testServer()
    throws InterruptedException, IOException {
  CouchbaseTestServer couchbaseTestServer = new CouchbaseTestServer(TestUtils.findFreePort());
  couchbaseTestServer.start();

  int port = couchbaseTestServer.getPort();
  int serverPort = couchbaseTestServer.getServerPort();



  try {
    CouchbaseEnvironment cbEnv = DefaultCouchbaseEnvironment.builder().bootstrapHttpEnabled(true)
        .bootstrapHttpDirectPort(port)
        .bootstrapCarrierDirectPort(serverPort)
        .connectTimeout(TimeUnit.SECONDS.toMillis(15))
        .bootstrapCarrierEnabled(true).build();
    CouchbaseCluster cbCluster = CouchbaseCluster.create(cbEnv, "localhost");
    Bucket bucket = cbCluster.openBucket("default","");
    try {
      JsonObject content = JsonObject.empty().put("name", "Michael");
      JsonDocument doc = JsonDocument.create("docId", content);
      JsonDocument inserted = bucket.insert(doc);
    }
    catch (Exception e)
    {
      Assert.fail("Should not throw exception on insert", e);
    }
  }
  finally
  {
    couchbaseTestServer.stop();
  }
}
 
Example 28
@Test
public void schemaWithRecordIsNullable()
    throws Exception {
  String testName = "schemaWithRecordIsNullable";
  JsonObject schema = getSchemaData(testName).getAsJsonObject();
  JsonArray expected = getExpectedSchema(testName).getAsJsonArray();

  RecordConverter converter = new RecordConverter(new JsonSchema(schema), state,
      buildNamespace(state.getExtract().getNamespace(), "something"));

  Assert.assertEquals(avroSchemaToJsonElement(converter), expected);
}
 
Example 29
Source Project: scheduler   Source File: IssuesTest.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * A helper to check that an instance has a solution.
 *
 * @param file the serialised instance. Must be in 'src/test/resources/'
 */
private static void computable(String file) {
    Instance i = JSON.readInstance(new File("src/test/resources/" + file));
    ChocoScheduler s = new DefaultChocoScheduler();
    ReconfigurationPlan p = s.solve(i);
    System.out.println(s.getStatistics());
    Assert.assertNotNull(p);
    System.out.println(p.getSize() + " action(s)");
}
 
Example 30
Source Project: bullet-core   Source File: RegionDistributionTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testRegionDistributionAggregation() {
    RegionDistribution aggregation = new RegionDistribution("foo", DistributionType.QUANTILE, 500, 0.0, 1.0, 0.2);
    aggregation.configure(config);

    Assert.assertEquals(aggregation.getType(), AggregationType.DISTRIBUTION);
    Assert.assertEquals(aggregation.getDistributionType(), DistributionType.QUANTILE);
    Assert.assertEquals(aggregation.getStart(), 0.0);
    Assert.assertEquals(aggregation.getEnd(), 1.0);
    Assert.assertEquals(aggregation.getIncrement(), 0.2);
    Assert.assertTrue(aggregation.getStrategy(config) instanceof QuantileSketchingStrategy);
}