Java Code Examples for org.skyscreamer.jsonassert.JSONAssert

The following examples show how to use org.skyscreamer.jsonassert.JSONAssert. 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 check out the related API usage on the sidebar.
Example 1
@Test
public void simpleSubqueryAliasGroup_WhereProjectGroupSort() throws ParseException, JSONException, IOException {
	QueryConverter queryConverter = new QueryConverter.Builder().sqlString("select c.cuisine, sum(c.c) as c  from(select borough, cuisine, count(*) as c from "+COLLECTION+" group by borough, cuisine) as c where c.c > 500 group by c.cuisine order by cuisine desc ").build();
    QueryResultIterator<Document> distinctIterable = queryConverter.run(mongoDatabase);
    List<Document> results = Lists.newArrayList(distinctIterable);
    assertEquals(4, results.size());
    JSONAssert.assertEquals("[{\n" + 
    		"	\"c\": 621,\n" + 
    		"	\"cuisine\": \"Italian\"\n" + 
    		"},{\n" + 
    		"	\"c\": 2001,\n" + 
    		"	\"cuisine\": \"Chinese\"\n" + 
    		"},{\n" + 
    		"	\"c\": 680,\n" + 
    		"	\"cuisine\": \"Café/Coffee/Tea\"\n" + 
    		"},{\n" + 
    		"	\"c\": 5518,\n" + 
    		"	\"cuisine\": \"American \"\n" + 
    		"}]",toJson(results),false);
}
 
Example 2
@Test
public void testJsonValueForSubjectWithMultipleValues() throws Exception {
    TestFactory.makeTimedValue(subject.getSubjectType(), "E01000001", attribute, "2011-01-01T00:00", 100d);
    TestFactory.makeTimedValue(subject.getSubjectType(), "E01000001", attribute, "2011-01-02T00:00", 200d);
    String jsonString = field.jsonValueForSubject(subject, true).toJSONString();
    JSONAssert.assertEquals("{" +
            "  aLabel: [" +
            "    {" +
            "      value: 100," +
            "      timestamp: '2011-01-01T00:00:00'" +
            "    }," +
            "    {" +
            "      value: 200," +
            "      timestamp: '2011-01-02T00:00:00'" +
            "    }" +
            "  ]," +
            "  aLabel Mean: 150" +
            "}", jsonString, false);
}
 
Example 3
@Test
@SuppressWarnings("unchecked")
public void writeParameterizedBaseType() throws Exception {
	ParameterizedTypeReference<List<MyBean>> beansList = new ParameterizedTypeReference<List<MyBean>>() {};
	ParameterizedTypeReference<List<MyBase>> baseList = new ParameterizedTypeReference<List<MyBase>>() {};

	String body = "[{\"bytes\":[1,2],\"array\":[\"Foo\",\"Bar\"]," +
			"\"number\":42,\"string\":\"Foo\",\"bool\":true,\"fraction\":42.0}]";
	MockHttpInputMessage inputMessage = new MockHttpInputMessage(body.getBytes(StandardCharsets.UTF_8));
	inputMessage.getHeaders().setContentType(new MediaType("application", "json"));

	List<MyBean> results = (List<MyBean>) converter.read(beansList.getType(), null, inputMessage);
	assertEquals(1, results.size());
	MyBean result = results.get(0);
	assertEquals("Foo", result.getString());
	assertEquals(42, result.getNumber());
	assertEquals(42F, result.getFraction(), 0F);
	assertArrayEquals(new String[] {"Foo", "Bar"}, result.getArray());
	assertTrue(result.isBool());
	assertArrayEquals(new byte[] {0x1, 0x2}, result.getBytes());

	MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();
	converter.write(results, baseList.getType(), new MediaType("application", "json"), outputMessage);
	JSONAssert.assertEquals(body, outputMessage.getBodyAsString(StandardCharsets.UTF_8), true);
}
 
Example 4
Source Project: data-prep   Source File: TransformationServiceTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void noAction() throws Exception {
    // given
    String dataSetId = createDataset("input_dataset.csv", "uppercase", "text/csv");
    String preparationId = createEmptyPreparationFromDataset(dataSetId, "uppercase prep");

    // when
    String transformedContent = given() //
            .when() //
            .get("/apply/preparation/{preparationId}/dataset/{datasetId}/{format}", preparationId, dataSetId,
                    "JSON") //
            .asString();

    // then
    String expectedContent =
            IOUtils.toString(this.getClass().getResourceAsStream("no_action_expected.json"), UTF_8);
    JSONAssert.assertEquals(expectedContent, transformedContent, false);
}
 
Example 5
Source Project: FHIR   Source File: BulkExportJobRestTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testBulkExportJobInstanceRequestEmpty() throws Exception {
    String jsonString = "{}";
    String expected = "{}";

    try (InputStream in = new ByteArrayInputStream(jsonString.getBytes())) {
        JobInstanceRequest parsedObj = JobInstanceRequest.Parser.parse(in);

        String str = JobInstanceRequest.Writer.generate(parsedObj, false);

        JSONAssert.assertEquals(expected, str, false);
    } catch (Exception e) {

        fail("failed to parse", e);
    }
}
 
Example 6
@Test
public void shouldValidateGitHubEnterpriseUrl() throws Exception {
    when(request.requestBody()).thenReturn("{\n" +
            "  \"ClientId\": \"client-id\",\n" +
            "  \"AllowedOrganizations\": \"example-1,example-2\",\n" +
            "  \"AuthenticateWith\": \"GitHubEnterprise\",\n" +
            "  \"ClientSecret\": \"client-secret\",\n" +
            "  \"PersonalAccessToken\": \"Foobar\"\n" +
            "}");

    GoPluginApiResponse response = AuthConfigValidateRequest.from(request).execute();

    String expectedJSON = "[\n" +
            "  {\n" +
            "    \"key\": \"GitHubEnterpriseUrl\",\n" +
            "    \"message\": \"GitHubEnterpriseUrl must not be blank.\"\n" +
            "  }\n" +
            "]";

    JSONAssert.assertEquals(expectedJSON, response.responseBody(), JSONCompareMode.NON_EXTENSIBLE);
}
 
Example 7
@Test
public void shouldGetStatusReport() throws Exception {
    StatusReport statusReport = aStatusReport();
    when(clusterStatusReportRequest.getClusterProfile()).thenReturn(clusterProfile);
    when(dockerContainers.getStatusReport(clusterProfile)).thenReturn(statusReport);
    when(viewBuilder.getTemplate("status-report.template.ftlh")).thenReturn(template);
    when(viewBuilder.build(template, statusReport)).thenReturn("statusReportView");
    ClusterStatusReportExecutor statusReportExecutor = new ClusterStatusReportExecutor(clusterStatusReportRequest, dockerContainers, viewBuilder);

    GoPluginApiResponse goPluginApiResponse = statusReportExecutor.execute();

    JsonObject expectedResponseBody = new JsonObject();
    expectedResponseBody.addProperty("view", "statusReportView");
    assertThat(goPluginApiResponse.responseCode(), is(200));
    JSONAssert.assertEquals(expectedResponseBody.toString(), goPluginApiResponse.responseBody(), true);
}
 
Example 8
@Test
public void countGroupByQueryHavingByCountAlias() throws ParseException, IOException, JSONException {
    QueryConverter queryConverter = new QueryConverter.Builder().sqlString("select cuisine, count(cuisine) as cc from "+COLLECTION+" WHERE borough = 'Manhattan' GROUP BY cuisine HAVING cc > 500").build();
    QueryResultIterator<Document> distinctIterable = queryConverter.run(mongoDatabase);
    queryConverter.write(System.out);
    List<Document> results = Lists.newArrayList(distinctIterable);
    assertEquals(4, results.size());
    JSONAssert.assertEquals("[{\n" + 
    		"	\"cuisine\": \"Chinese\",\n" + 
    		"	\"cc\": 510\n" +  
    		"}," +
    		"{\n" + 
    		"	\"cuisine\": \"Italian\",\n" + 
    		"	\"cc\": 621\n" +  
    		"}," +
    		"{\n" + 
    		"	\"cuisine\": \"Café/Coffee/Tea\",\n" + 
    		"	\"cc\": 680\n" +
    		"}," +
    		"{\n" + 
    		"	\"cuisine\": \"American \",\n" + 
    		"	\"cc\": 3205\n" +
    		"}]",toJson(results),false);
}
 
Example 9
Source Project: jsonschema-generator   Source File: IntegrationTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Test
 *
 * @throws Exception
 */
@Test
public void testIntegration() throws Exception {
    // active all optional modules
    JavaxValidationModule module = new JavaxValidationModule(
            JavaxValidationOption.NOT_NULLABLE_FIELD_IS_REQUIRED,
            JavaxValidationOption.NOT_NULLABLE_METHOD_IS_REQUIRED,
            JavaxValidationOption.INCLUDE_PATTERN_EXPRESSIONS);
    SchemaGeneratorConfig config = new SchemaGeneratorConfigBuilder(new ObjectMapper(), SchemaVersion.DRAFT_2019_09)
            .with(module)
            .build();
    SchemaGenerator generator = new SchemaGenerator(config);
    JsonNode result = generator.generateSchema(TestClass.class);

    String rawJsonSchema = result.toString();
    JSONAssert.assertEquals('\n' + rawJsonSchema + '\n',
            loadResource("integration-test-result.json"), rawJsonSchema, JSONCompareMode.STRICT);
}
 
Example 10
Source Project: bdt   Source File: CommonGTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void modifyDataAddToJsonNumberTest_3() throws Exception {
    ThreadProperty.set("class", this.getClass().getCanonicalName());
    CommonG commong = new CommonG();

    JSONObject jsonObject = new JSONObject();
    jsonObject.put("key1", new JSONArray(Arrays.asList("value1")));
    String data = jsonObject.toString();
    String expectedData = "{\"key1\":[\"value1\",0]}";
    String type = "json";
    List<List<String>> rawData = Arrays.asList(Arrays.asList("key1", "ADDTO", "0", "number"));
    DataTable modifications = DataTable.create(rawData);

    String modifiedData = commong.modifyData(data, type, modifications);
    JSONAssert.assertEquals(expectedData, modifiedData, false);
}
 
Example 11
@Test
@Parameters(source = SchemaVersion.class)
public void testGenerateSchema_CircularCustomStandardDefinition(SchemaVersion schemaVersion) throws Exception {
    String accessProperty = "get(0)";
    CustomDefinitionProviderV2 customDefinitionProvider = (javaType, context) -> {
        if (!javaType.isInstanceOf(List.class)) {
            return null;
        }
        ResolvedType generic = context.getTypeContext().getContainerItemType(javaType);
        SchemaGeneratorConfig config = context.getGeneratorConfig();
        return new CustomDefinition(config.createObjectNode()
                .put(config.getKeyword(SchemaKeyword.TAG_TYPE), config.getKeyword(SchemaKeyword.TAG_TYPE_OBJECT))
                .set(config.getKeyword(SchemaKeyword.TAG_PROPERTIES), config.createObjectNode()
                        .set(accessProperty, context.createDefinitionReference(generic))));
    };
    SchemaGeneratorConfigBuilder configBuilder = new SchemaGeneratorConfigBuilder(schemaVersion);
    configBuilder.forTypesInGeneral()
            .withCustomDefinitionProvider(customDefinitionProvider);
    SchemaGenerator generator = new SchemaGenerator(configBuilder.build());
    JsonNode result = generator.generateSchema(TestCircularClass1.class);
    JSONAssert.assertEquals('\n' + result.toString() + '\n',
            TestUtils.loadResource(this.getClass(), "circular-custom-definition-" + schemaVersion.name() + ".json"),
            result.toString(), JSONCompareMode.STRICT);
}
 
Example 12
@SuppressWarnings("GrazieInspection")
private DynamicTest testResource(final Path resource) {
    return dynamicTest(resource.getFileName().toString(), () -> {
        final FileInputStream fileInputStream = new FileInputStream(resource.toFile());

        final String json = copyToString(fileInputStream, StandardCharsets.UTF_8);
        log.debug("JSON                : {}", json);

        final FlexContainer flexContainer = mapper.readValue(json, FlexContainer.class);
        log.debug("Deserialized        : {}", flexContainer);

        final String jsonReconstructed = mapper.writeValueAsString(flexContainer);
        log.debug("Re-Serialized JSON  : {}", jsonReconstructed);

        JSONAssert.assertEquals(json, jsonReconstructed, true);
    });
}
 
Example 13
@Test
@SuppressWarnings("unchecked")
public void readAndWriteGenerics() throws Exception {
	Field beansList = ListHolder.class.getField("listField");

	String body = "[{\"bytes\":[1,2],\"array\":[\"Foo\",\"Bar\"]," +
			"\"number\":42,\"string\":\"Foo\",\"bool\":true,\"fraction\":42.0}]";
	MockHttpInputMessage inputMessage = new MockHttpInputMessage(body.getBytes(StandardCharsets.UTF_8));
	inputMessage.getHeaders().setContentType(new MediaType("application", "json"));

	Type genericType = beansList.getGenericType();
	List<MyBean> results = (List<MyBean>) converter.read(genericType, MyBeanListHolder.class, inputMessage);
	assertEquals(1, results.size());
	MyBean result = results.get(0);
	assertEquals("Foo", result.getString());
	assertEquals(42, result.getNumber());
	assertEquals(42F, result.getFraction(), 0F);
	assertArrayEquals(new String[] {"Foo", "Bar"}, result.getArray());
	assertTrue(result.isBool());
	assertArrayEquals(new byte[] {0x1, 0x2}, result.getBytes());

	MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();
	converter.write(results, genericType, new MediaType("application", "json"), outputMessage);
	JSONAssert.assertEquals(body, outputMessage.getBodyAsString(StandardCharsets.UTF_8), true);
}
 
Example 14
@Test
public void shouldGetTypedJson() throws JSONException {
  // given
  engineRule.startProcessInstance(processDefinition.getId(), VARIABLE_NAME_JSON, VARIABLE_VALUE_JSON_VALUE);

  // when
  client.subscribe(EXTERNAL_TASK_TOPIC_FOO)
    .handler(handler)
    .open();

  // then
  clientRule.waitForFetchAndLockUntil(() -> !handler.getHandledTasks().isEmpty());

  ExternalTask task = handler.getHandledTasks().get(0);

  JsonValue typedValue = task.getVariableTyped(VARIABLE_NAME_JSON);
  assertThat(typedValue.getType()).isEqualTo(JSON);
  JSONAssert.assertEquals(VARIABLE_VALUE_JSON_SERIALIZED, typedValue.getValue(), true);
}
 
Example 15
Source Project: camunda-bpm-platform   Source File: JsonValueTest.java    License: Apache License 2.0 6 votes vote down vote up
@Deployment(resources = ONE_TASK_PROCESS)
public void testGetTypedJsonValue() throws JSONException {
  // given
  JsonValue jsonValue = jsonValue(jsonString).create();
  VariableMap variables = Variables.createVariables().putValueTyped(variableName, jsonValue);

  String processInstanceId = runtimeService.startProcessInstanceByKey(ONE_TASK_PROCESS_KEY, variables).getId();

  // when
  JsonValue typedValue = runtimeService.getVariableTyped(processInstanceId, variableName);

  // then
  SpinJsonNode value = typedValue.getValue();
  JSONAssert.assertEquals(jsonString, value.toString(), true);

  assertTrue(typedValue.isDeserialized());
  assertEquals(JSON, typedValue.getType());
  assertEquals(JSON_FORMAT_NAME, typedValue.getSerializationDataFormat());
  JSONAssert.assertEquals(jsonString, typedValue.getValueSerialized(), true);
}
 
Example 16
@Test
public void shouldGetAgentStatusReportWithJobIdentifier() throws Exception {
    JobIdentifier jobIdentifier = new JobIdentifier("up42", 2L, "label", "stage1", "1", "job", 1L);
    AgentStatusReportRequest agentStatusReportRequest = new AgentStatusReportRequest(null, jobIdentifier, clusterProfileConfigurations);
    AgentStatusReport agentStatusReport = new AgentStatusReport(jobIdentifier, "elastic-agent-id", null, null, null, null, null, new HashMap<>(), new ArrayList<>());

    DockerContainer dockerContainer = new DockerContainer("id", "name", jobIdentifier, new Date(), new HashMap<>(), null);
    when(dockerContainers.find(jobIdentifier)).thenReturn(Optional.ofNullable(dockerContainer));
    when(dockerContainers.getAgentStatusReport(clusterProfile, dockerContainer)).thenReturn(agentStatusReport);
    when(viewBuilder.getTemplate("agent-status-report.template.ftlh")).thenReturn(template);
    when(viewBuilder.build(template, agentStatusReport)).thenReturn("agentStatusReportView");

    GoPluginApiResponse goPluginApiResponse = new AgentStatusReportExecutor(agentStatusReportRequest, pluginRequest, dockerContainers, viewBuilder)
            .execute();

    JsonObject expectedResponseBody = new JsonObject();
    expectedResponseBody.addProperty("view", "agentStatusReportView");
    assertThat(goPluginApiResponse.responseCode(), is(200));
    JSONAssert.assertEquals(expectedResponseBody.toString(), goPluginApiResponse.responseBody(), true);
}
 
Example 17
Source Project: moip-sdk-java-le   Source File: PaymentRequestTest.java    License: MIT License 6 votes vote down vote up
@Test
public void testPaymentWithOnlineDebit() throws JSONException {
    PaymentRequest payment = new PaymentRequest()
        .orderId("ORD-VN1DD41V9G45")
        .installmentCount(1)
        .fundingInstrument(
            new FundingInstrumentRequest()
                .onlineBankDebit(new OnlineBankDebitRequest()
                    .bankNumber("341")
                    .expirationDate(new ApiDateRequest().date(new GregorianCalendar(2020, Calendar.AUGUST, 10).getTime()))
                    .returnUri("https://moip.com.br/")
                )
        );

    String paymentJSON = new Gson().toJson(payment);
    JsonObject expectedJSON = getJsonFileAsJsonObject("payment/create_online_debit.json");

    JSONAssert.assertEquals(expectedJSON.toString(), paymentJSON, false);
}
 
Example 18
@Test
@Deployment(resources = ONE_TASK_PROCESS)
public void testSerializationAsJson() throws JSONException {
  ProcessInstance instance = runtimeService.startProcessInstanceByKey("oneTaskProcess");

  JsonSerializable bean = new JsonSerializable("a String", 42, true);
  // request object to be serialized as JSON
  runtimeService.setVariable(instance.getId(), "simpleBean", objectValue(bean).serializationDataFormat(JSON_FORMAT_NAME).create());

  // validate untyped value
  Object value = runtimeService.getVariable(instance.getId(), "simpleBean");
  assertEquals(bean, value);

  // validate typed value
  ObjectValue typedValue = runtimeService.getVariableTyped(instance.getId(), "simpleBean");
  assertEquals(ValueType.OBJECT, typedValue.getType());

  assertTrue(typedValue.isDeserialized());

  assertEquals(bean, typedValue.getValue());
  assertEquals(bean, typedValue.getValue(JsonSerializable.class));
  assertEquals(JsonSerializable.class, typedValue.getObjectType());

  assertEquals(JSON_FORMAT_NAME, typedValue.getSerializationDataFormat());
  assertEquals(JsonSerializable.class.getName(), typedValue.getObjectTypeName());
  JSONAssert.assertEquals(bean.toExpectedJsonString(), new String(typedValue.getValueSerialized()), true);
}
 
Example 19
Source Project: bdt   Source File: CommonGTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void modifyDataReplaceJsonBooleanTest_2() throws Exception {
    ThreadProperty.set("class", this.getClass().getCanonicalName());
    CommonG commong = new CommonG();
    String data = jsonObject1.toString();
    String expectedData = jsonObject12.toString();
    String type = "json";
    List<List<String>> rawData = Arrays.asList(Arrays.asList("key2.key3", "REPLACE", "false", "boolean"));
    DataTable modifications = DataTable.create(rawData);
    String modifiedData = commong.modifyData(data, type, modifications);
    JSONAssert.assertEquals(expectedData, modifiedData, false);
}
 
Example 20
Source Project: TomboloDigitalConnector   Source File: TimeseriesFieldTest.java    License: MIT License 5 votes vote down vote up
@Test
public void testJsonValueForSubject() throws Exception {
    TestFactory.makeTimedValue(subject.getSubjectType(), "E01000001", attribute, "2011-01-01T00:00", 100d);
    String jsonString = field.jsonValueForSubject(subject, null).toJSONString();
    JSONAssert.assertEquals("{" +
            "  aLabel: [" +
            "    {" +
            "      value: 100," +
            "      timestamp: '2011-01-01T00:00:00'" +
            "    }" +
            "  ]" +
            "}", jsonString, false);
}
 
Example 21
Source Project: messenger4j   Source File: SendTest.java    License: MIT License 5 votes vote down vote up
@Test
void shouldSendTextMessageWithMetadata() throws Exception {
  // tag::send-TextMessageMetadata[]
  final IdRecipient recipient = IdRecipient.create("USER_ID");
  final NotificationType notificationType = NotificationType.SILENT_PUSH;
  final String text = "Hello Messenger Platform";
  final String metadata = "DEVELOPER_DEFINED_METADATA";

  final TextMessage textMessage = TextMessage.create(text, empty(), of(metadata));
  final MessagePayload payload =
      MessagePayload.create(
          recipient, MessagingType.RESPONSE, textMessage, of(notificationType), empty());

  messenger.send(payload);
  // end::send-TextMessageMetadata[]

  final ArgumentCaptor<String> payloadCaptor = ArgumentCaptor.forClass(String.class);
  final String expectedJsonBody =
      "{\"recipient\":{\"id\":\"USER_ID\"},"
          + "\"notification_type\":\"SILENT_PUSH\","
          + "\"messaging_type\":\"RESPONSE\","
          + "\"message\":{"
          + "\"text\":\"Hello Messenger Platform\","
          + "\"metadata\":\"DEVELOPER_DEFINED_METADATA\""
          + "}}";
  verify(mockHttpClient).execute(eq(POST), endsWith(PAGE_ACCESS_TOKEN), payloadCaptor.capture());
  JSONAssert.assertEquals(expectedJsonBody, payloadCaptor.getValue(), true);
}
 
Example 22
Source Project: prebid-server-java   Source File: CpmStarTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void openrtb2AuctionShouldRespondWithBidsFromCPMStar() throws IOException, JSONException {
    // given
    // Cpmstar bid response
    WIRE_MOCK_RULE.stubFor(post(urlPathEqualTo("/cpmstar-exchange"))
            .withHeader("Accept", equalTo("application/json"))
            .withHeader("Content-Type", equalTo("application/json;charset=UTF-8"))
            .withRequestBody(equalToJson(jsonFrom("openrtb2/cpmstar/test-cpmstar-bid-request-1.json")))
            .willReturn(aResponse().withBody(jsonFrom("openrtb2/cpmstar/test-cpmstar-bid-response-1.json"))));

    // pre-bid cache
    WIRE_MOCK_RULE.stubFor(post(urlPathEqualTo("/cache"))
            .withRequestBody(equalToJson(jsonFrom("openrtb2/cpmstar/test-cache-cpmstar-request.json")))
            .willReturn(aResponse().withBody(jsonFrom("openrtb2/cpmstar/test-cache-cpmstar-response.json"))));

    // when
    final Response response = given(SPEC)
            .header("Referer", "http://www.example.com")
            .header("X-Forwarded-For", "193.168.244.1")
            .header("User-Agent", "userAgent")
            .header("Origin", "http://www.example.com")
            .cookie("uids", "eyJ1aWRzIjp7ImNwbXN0YXIiOiJDUy1VSUQifX0=")
            .body(jsonFrom("openrtb2/cpmstar/test-auction-cpmstar-request.json"))
            .post("/openrtb2/auction");

    // then
    final String expectedAuctionResponse = openrtbAuctionResponseFrom(
            "openrtb2/cpmstar/test-auction-cpmstar-response.json",
            response, singletonList("cpmstar"));

    JSONAssert.assertEquals(expectedAuctionResponse, response.asString(), JSONCompareMode.NON_EXTENSIBLE);
}
 
Example 23
Source Project: android-perftracking   Source File: EventWriterSpec.java    License: MIT License 5 votes vote down vote up
@Test public void shouldHandleMalformedURLData() throws IOException, JSONException {
  Measurement measurement = new Measurement();
  measurement.type = Measurement.URL;
  measurement.a = new URL("http://example.com:80/page1\".html");
  measurement.startTime = 0L;
  measurement.endTime = 999;

  writer.begin();
  writer.write(measurement, "test-metric");
  measurement.a = new URL("http://example.com:80/page1\"[.html");
  writer.write(measurement, "test-metric");
  measurement.a = new URL("http://example.com:80/page1\"{.html");
  writer.write(measurement, "test-metric");
  measurement.a = new URL("http://example.com:80/page1\",.html");
  writer.write(measurement, "test-metric");
  measurement.a = new URL("http://example.com:80/page1'}'.html");
  writer.write(measurement, "test-metric");
  //For URL as String.
  measurement.a = "http://example.com:80/page1\".html";
  writer.write(measurement, "test-metric");
  measurement.a = "http://example.com:80/page1\"[.html";
  writer.write(measurement, "test-metric");
  measurement.a = "http://example.com:80/page1\"{.html";
  writer.write(measurement, "test-metric");
  measurement.a = "http://example.com:80/page1\",.html";
  writer.write(measurement, "test-metric");
  measurement.a = "http://example.com:80/page1'}'.html";
  writer.write(measurement, "test-metric");
  writer.end();

  String writtenString = trimAppMemDetails(extractWrittenString(outputStream));
  JSONAssert.assertEquals(escapedJson.content, writtenString, true);
}
 
Example 24
Source Project: ambiverse-nlu   Source File: ResultProcessorTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test public void test() throws Exception {
  Document.Builder docbuilder = new Document.Builder();
  docbuilder.withId("testPageKashmir1");
  docbuilder.withText("Page played Kashmir at Knebworth.");

  DocumentAnnotations annotations = new DocumentAnnotations();
  annotations.addMention(0, 4);
  annotations.addMention(12, 7);
  annotations.addMention(23, 9);
  docbuilder.withAnnotations(annotations);

  DisambiguationSettings settings = new CocktailPartyLangaugeModelDefaultDisambiguationSettings();
  settings.getGraphSettings().setAlpha(DEFAULT_ALPHA);
  settings.getGraphSettings().setCohRobustnessThresholdNE(DEFAULT_COH_ROBUSTNESS);
  settings.getGraphSettings().setEntitiesPerMentionConstraint(DEFAULT_SIZE);
  settings.setIncludeNullAsEntityCandidate(false);
  settings.setDisambiguationMethod(DisambiguationSettings.DISAMBIGUATION_METHOD.LM_COHERENCE);

  docbuilder.withDisambiguationSettings(settings);

  DocumentProcessor dp = DocumentProcessor.getInstance(PipelineType.DISAMBIGUATION_STANFORD);
  AnalyzeOutput ao = OutputUtils.generateAnalyzeOutputfromProcessedDocument(dp.process(docbuilder.build()));

  // TODO: test ao directly (as in DisambiguationPipelinesHolderTest)

  String result = OutputUtils.generateJSONStringfromAnalyzeOutput(ao);

  JSONAssert.assertEquals(
      "{\"docId\":\"testPageKashmir1\",\"language\":\"en\",\"matches\":[{\"charLength\":4,\"charOffset\":0,\"text\":\"Page\",\"entity\":{\"id\":\"http://www.wikidata.org/entity/TESTING:Jimmy_Page\",\"confidence\":1.0}},{\"charLength\":7,\"charOffset\":12,\"text\":\"Kashmir\",\"entity\":{\"id\":\"http://www.wikidata.org/entity/TESTING:Kashmir_(song)\",\"confidence\":1.0}},{\"charLength\":9,\"charOffset\":23,\"text\":\"Knebworth\",\"entity\":{\"id\":\"http://www.wikidata.org/entity/TESTING:Knebworth_Festival\",\"confidence\":1.0}}],\"entities\":[{\"id\":\"http://www.wikidata.org/entity/TESTING:Knebworth_Festival\",\"name\":\"Knebworth_Festival\",\"url\":\"http://Knebworth_Festival\",\"salience\":0.0},{\"id\":\"http://www.wikidata.org/entity/TESTING:Jimmy_Page\",\"name\":\"Jimmy_Page\",\"url\":\"http://Jimmy_Page\",\"salience\":0.0},{\"id\":\"http://www.wikidata.org/entity/TESTING:Kashmir_(song)\",\"name\":\"Kashmir_(song)\",\"url\":\"http://Kashmir_(song)\",\"salience\":0.0}]}",
      result,
      false);
}
 
Example 25
Source Project: app-runner   Source File: BuildStatusTest.java    License: MIT License 5 votes vote down vote up
@Test
public void inProgressWorks() {
    Instant now = Instant.now();
    JSONObject s = BuildStatus.inProgress(now, aCommit(), "maven").toJSON();
    JSONAssert.assertEquals("{" +
        "runnerId: 'maven', status: 'building', startTime: '" + now.toString() + "', description: 'Building now...', commit: {}" +
        "}", s, JSONCompareMode.LENIENT);
}
 
Example 26
@Test
public void testJsonValueForSubject() throws Exception {
    nearbySubject.setShape(TestFactory.makePointGeometry(0.09d, 0d)); // Just inside the given radius
    SubjectUtils.save(Collections.singletonList(nearbySubject));

    String jsonString = mapToNearestSubjectField.jsonValueForSubject(subject, true).toJSONString();
    JSONAssert.assertEquals("{" +
            "  aLabel: 100.0" +
            "}", jsonString,false);
}
 
Example 27
Source Project: spring-analysis-note   Source File: Jackson2TokenizerTests.java    License: MIT License 5 votes vote down vote up
@Override
public void accept(String s) {
	try {
		JSONAssert.assertEquals(this.expected, s, true);
	}
	catch (JSONException ex) {
		throw new RuntimeException(ex);
	}
}
 
Example 28
@Test
public void shouldSupportAgentAndPluginStatusReport() throws Exception {
    GoPluginApiResponse response = new GetCapabilitiesExecutor().execute();

    String expectedJSON = "{\n" +
            "    \"supports_plugin_status_report\":false\n," +
            "    \"supports_cluster_status_report\":true\n," +
            "    \"supports_agent_status_report\":true\n" +
            "}";

    JSONAssert.assertEquals(expectedJSON, response.responseBody(), true);
}
 
Example 29
@Test
public void shouldReturnResponse() throws Exception {
    GoPluginApiResponse response = new GetCapabilitiesExecutor().execute();

    assertThat(response.responseCode(), is(200));
    JSONObject expected = new JSONObject().put("supports_plugin_status_report", false);
    expected.put("supports_agent_status_report", true);
    expected.put("supports_cluster_status_report", true);
    JSONAssert.assertEquals(expected, new JSONObject(response.responseBody()), true);
}
 
Example 30
Source Project: bdt   Source File: CommonGTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void modifyDataReplaceJsonTest() throws Exception {
    ThreadProperty.set("class", this.getClass().getCanonicalName());
    CommonG commong = new CommonG();
    String data = jsonObject1.toString();
    String expectedData = jsonObject10.toString();
    String type = "json";
    List<List<String>> rawData = Arrays.asList(Arrays.asList("key2.key3", "REPLACE", "lu->REPLACE"));
    DataTable modifications = DataTable.create(rawData);

    String modifiedData = commong.modifyData(data, type, modifications);
    JSONAssert.assertEquals(expectedData, modifiedData, false);
}