org.testng.Assert Java Examples

The following examples show how to use org.testng.Assert. 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: AdoubleUnionTest.java    From incubator-datasketches-java with Apache License 2.0 6 votes vote down vote up
@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 #2
Source File: TestRoutingDataCache.java    From helix with 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 #3
Source File: Main.java    From openjdk-jdk8u with 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 #4
Source File: PrivateKeyAsJWKClasspathTest.java    From microprofile-jwt-auth with Apache License 2.0 6 votes vote down vote up
@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 #5
Source File: TestTreeCache.java    From curator with 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 #6
Source File: BSTAuthenticatorTest.java    From carbon-device-mgt with 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 #7
Source File: PaddingStackBatchifierTest.java    From djl with 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 File: MultiPointCrossoverTest.java    From jenetics with 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
Source File: DepthOfCoverageIntegrationTest.java    From gatk with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@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 #10
Source File: BindingsRestApiTest.java    From ballerina-message-broker with Apache License 2.0 6 votes vote down vote up
@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 #11
Source File: ExtractParameterValuesTest.java    From FHIR with 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 #12
Source File: FitnessConvergenceLimitTest.java    From jenetics with 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 #13
Source File: dataIT.java    From submarine with 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 #14
Source File: TestKafkaConnectorTask.java    From brooklin with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@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 #15
Source File: CheckArrayTest.java    From jdk8u_jdk with 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 #16
Source File: JsonNodeMarshallerTest.java    From tasmo with 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 #17
Source File: InheritingJobTemplateTest.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
@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 #18
Source File: NDIndexTest.java    From djl with 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 #19
Source File: MetricCollectorTest.java    From bullet-core with 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 File: ArrayConverterTest.java    From microprofile-config with 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 #21
Source File: IterateClient.java    From micro-integrator with 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 #22
Source File: RegionDistributionTest.java    From bullet-core with 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);
}
 
Example #23
Source File: GraphBackedRepositorySoftDeleteTest.java    From incubator-atlas with Apache License 2.0 5 votes vote down vote up
@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 #24
Source File: MetricEventPublisherTest.java    From bullet-core with Apache License 2.0 5 votes vote down vote up
@Test
public void testGroup() {
    MetricEventPublisher publisher = new NullMetricEventPublisher();
    MetricEvent event = publisher.convert(null, null);
    Assert.assertEquals(event.getGroup(), MetricEventPublisher.DEFAULT_GROUP);
    Assert.assertNull(event.getDimensions());
    Assert.assertNull(event.getMetrics());
}
 
Example #25
Source File: DartModelTest.java    From openapi-generator with 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 #26
Source File: SequenceStatisticsTest.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
@Test(groups = {"wso2.esb"}, description = "Sequence statistics message count check.")
public void statisticsCollectionCountTestForNestedSequence() throws Exception {
    thriftServer.resetMsgCount();
    thriftServer.resetPreservedEventList();
    for (int i = 0; i < 100; i++) {
        axis2Client.sendSimpleStockQuoteRequest(getProxyServiceURLHttp("ReferencingProxyStatisticDisableProxy"), null,
                "WSO2");
    }
    thriftServer.waitToReceiveEvents(20000, 100); //wait to esb for asynchronously send statistics events to the
    // backend
    Assert.assertEquals(thriftServer.getMsgCount(), 100, "Hundred statistics events are required, but different "
                                                        + "number is found");
}
 
Example #27
Source File: Sample10Test.java    From module-ballerina-kubernetes with 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 #28
Source File: TypeSystemTest.java    From incubator-atlas with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetTraitsNames() throws Exception {
    HierarchicalTypeDefinition<TraitType> classificationTraitDefinition = TypesUtil
            .createTraitTypeDef("Classification", ImmutableSet.<String>of(),
                    TypesUtil.createRequiredAttrDef("tag", DataTypes.STRING_TYPE));
    HierarchicalTypeDefinition<TraitType> piiTrait =
            TypesUtil.createTraitTypeDef("PII", ImmutableSet.<String>of());
    HierarchicalTypeDefinition<TraitType> phiTrait =
            TypesUtil.createTraitTypeDef("PHI", ImmutableSet.<String>of());
    HierarchicalTypeDefinition<TraitType> pciTrait =
            TypesUtil.createTraitTypeDef("PCI", ImmutableSet.<String>of());
    HierarchicalTypeDefinition<TraitType> soxTrait =
            TypesUtil.createTraitTypeDef("SOX", ImmutableSet.<String>of());
    HierarchicalTypeDefinition<TraitType> secTrait =
            TypesUtil.createTraitTypeDef("SEC", ImmutableSet.<String>of());
    HierarchicalTypeDefinition<TraitType> financeTrait =
            TypesUtil.createTraitTypeDef("Finance", ImmutableSet.<String>of());

    getTypeSystem().defineTypes(ImmutableList.<EnumTypeDefinition>of(),
            ImmutableList.<StructTypeDefinition>of(),
            ImmutableList.of(classificationTraitDefinition, piiTrait, phiTrait, pciTrait, soxTrait, secTrait,
                    financeTrait), ImmutableList.<HierarchicalTypeDefinition<ClassType>>of());

    final ImmutableList<String> traitsNames = getTypeSystem().getTypeNamesByCategory(DataTypes.TypeCategory.TRAIT);
    Assert.assertEquals(traitsNames.size(), 7);
    List traits = Arrays.asList(new String[]{"Classification", "PII", "PHI", "PCI", "SOX", "SEC", "Finance",});

    Assert.assertFalse(Collections.disjoint(traitsNames, traits));
}
 
Example #29
Source File: AddressEndpointTestCase.java    From product-ei with Apache License 2.0 5 votes vote down vote up
@Test(groups = {"wso2.esb"}, description = "Sending a Message to a Address endpoint in Config Reg")
public void testSendingToAddressEndpoint_ConfigReg()
        throws Exception {
    OMElement response = axis2Client.sendSimpleStockQuoteRequest(getProxyServiceURLHttp("addressEndPointRegistryConfigProxy"),
                                                                 getBackEndServiceUrl(ESBTestConstant.SIMPLE_STOCK_QUOTE_SERVICE), "WSO2");
    Assert.assertNotNull(response);
    Assert.assertTrue(response.toString().contains("WSO2 Company"));

}
 
Example #30
Source File: JideCheckBoxListTest.java    From marathonv5 with Apache License 2.0 5 votes vote down vote up
@Test
public void selectCheckboxUnselectedSelected() throws Throwable {
    driver = new JavaAgent();
    IJavaElement listItem = driver.findElementByCssSelector("list::nth-item(3)::editor");
    listItem.marathon_select("false");
    CheckBoxList listComponent = (CheckBoxList) ComponentUtils.findComponent(CheckBoxList.class, frame);
    Assert.assertFalse(listComponent.getCheckBoxListSelectionModel().isSelectedIndex(2));
}