类org.testng.Assert源码实例Demo

下面列出了怎么用org.testng.Assert的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: submarine   文件: dataIT.java
@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);
}
 
源代码2 项目: carbon-device-mgt   文件: BSTAuthenticatorTest.java
@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");
}
 
@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"));
}
 
源代码4 项目: helix   文件: TestRoutingDataCache.java
@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);
}
 
源代码5 项目: openjdk-jdk8u   文件: Main.java
@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");
}
 
源代码6 项目: curator   文件: TestTreeCache.java
@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"));
}
 
源代码7 项目: djl   文件: PaddingStackBatchifierTest.java
@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());
        }
    }
}
 
源代码8 项目: jenetics   文件: MultiPointCrossoverTest.java
@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);
}
 
@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();
}
 
源代码10 项目: micro-integrator   文件: IterateClient.java
/**
 * 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();

}
 
源代码11 项目: jenetics   文件: FitnessConvergenceLimitTest.java
@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()));
}
 
源代码12 项目: microprofile-config   文件: ArrayConverterTest.java
@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") });
}
 
源代码13 项目: djl   文件: NDIndexTest.java
@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);
    }
}
 
@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");
}
 
源代码15 项目: tasmo   文件: JsonNodeMarshallerTest.java
@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");
}
 
源代码16 项目: jdk8u_jdk   文件: CheckArrayTest.java
/**
 * 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");
        }
    }
}
 
源代码17 项目: brooklin   文件: TestKafkaConnectorTask.java
@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);
}
 
@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());
}
 
源代码19 项目: bullet-core   文件: MetricCollectorTest.java
@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"));
}
 
源代码20 项目: FHIR   文件: ExtractParameterValuesTest.java
/**
 * 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);
    }
}
 
源代码21 项目: gatk   文件: DepthOfCoverageIntegrationTest.java
@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));
    }
}
 
源代码22 项目: module-ballerina-kubernetes   文件: Sample10Test.java
@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);
}
 
源代码23 项目: openapi-generator   文件: DartModelTest.java
@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);
}
 
@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);
        }
    }

}
 
源代码25 项目: cql_engine   文件: CqlTypeOperatorsTest.java
/**
     * {@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
//        }
    }
 
源代码26 项目: micro-integrator   文件: IterateClient.java
/**
 * @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();

}
 
源代码27 项目: incubator-gobblin   文件: CouchbaseTestServer.java
@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();
  }
}
 
@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);
}
 
源代码29 项目: scheduler   文件: IssuesTest.java
/**
 * 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)");
}
 
源代码30 项目: bullet-core   文件: RegionDistributionTest.java
@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);
}
 
 类所在包
 同包方法