From 15af66b115f3e8046b2d0f2634fb77b3d835f730 Mon Sep 17 00:00:00 2001 From: "mark.j.leonard" Date: Fri, 21 Sep 2018 16:16:04 +0100 Subject: Format Java code to ONAP standard Use the Eclipse formatter to automatically format the code to adhere to the defined standards. Change-Id: I42a8c90c5b272facc4cc2a0c85233061ed64ba3f Issue-ID: AAI-1650 Signed-off-by: mark.j.leonard --- .../onap/aai/sa/auth/SearchDbServiceAuthTest.java | 46 +- .../java/org/onap/aai/sa/rest/ApiUtilsTest.java | 20 +- .../java/org/onap/aai/sa/rest/BulkApiTest.java | 26 +- .../java/org/onap/aai/sa/rest/BulkRequestTest.java | 25 +- .../java/org/onap/aai/sa/rest/DocumentApiTest.java | 350 ++++++------ .../org/onap/aai/sa/rest/DocumentSchemaTest.java | 131 ++--- .../java/org/onap/aai/sa/rest/DocumentTest.java | 128 +++-- .../java/org/onap/aai/sa/rest/IndexApiTest.java | 449 ++++++++------- .../onap/aai/sa/rest/SearchServiceApiHarness.java | 286 ++++------ .../org/onap/aai/sa/rest/StubEsController.java | 373 ++++++------ src/test/java/org/onap/aai/sa/rest/TestUtils.java | 55 +- .../config/ElasticSearchConfigTest.java | 7 +- .../dao/AggregationResponseParsingTest.java | 108 ++-- .../dao/ElasticSearchResultItemTest.java | 12 +- .../searchapi/AggregationStatementTest.java | 175 +++--- .../searchapi/AggregationTest.java | 35 +- .../searchapi/DateHistogramAggregationTest.java | 75 ++- .../searchapi/DateRangeAggregationTest.java | 52 +- .../searchapi/DateRangeTest.java | 69 +-- .../searchdbabstraction/searchapi/FilterTest.java | 23 +- .../searchapi/GroupByAggregationTest.java | 46 +- .../searchdbabstraction/searchapi/QueryTest.java | 624 +++++++++++---------- .../searchapi/RangeQueryTest.java | 22 +- .../searchapi/SearchStatementTest.java | 392 ++++++------- .../sa/searchdbabstraction/searchapi/SortTest.java | 24 +- .../util/ElasticSearchPayloadTranslatorTest.java | 42 +- 26 files changed, 1752 insertions(+), 1843 deletions(-) (limited to 'src/test/java') diff --git a/src/test/java/org/onap/aai/sa/auth/SearchDbServiceAuthTest.java b/src/test/java/org/onap/aai/sa/auth/SearchDbServiceAuthTest.java index 3ffb422..a4b5395 100644 --- a/src/test/java/org/onap/aai/sa/auth/SearchDbServiceAuthTest.java +++ b/src/test/java/org/onap/aai/sa/auth/SearchDbServiceAuthTest.java @@ -39,47 +39,47 @@ public class SearchDbServiceAuthTest { @Mock HttpHeaders headers; -// @Mock -// Cookie mockedCookie; + // @Mock + // Cookie mockedCookie; @Before public void setUp() throws NoSuchFieldException, IllegalAccessException, IOException { MockitoAnnotations.initMocks(this); System.setProperty("AJSC_HOME", new File(".").getCanonicalPath().replace('\\', '/')); - setFinalStatic(System.getProperty("AJSC_HOME")+"/src/test/resources/json/search_policy.json"); + setFinalStatic(System.getProperty("AJSC_HOME") + "/src/test/resources/json/search_policy.json"); } @Test - public void testAuthUser(){ + public void testAuthUser() { SearchDbServiceAuth aaiAuth = new SearchDbServiceAuth(); String auth = aaiAuth.authUser(headers, "user-1", "function-1"); Assert.assertEquals(auth, "AAI_9101"); } -// @Test -// public void testAuthCookie_NullCookie(){ -// SearchDbServiceAuth aaiAuth = new SearchDbServiceAuth(); -// Cookie cookie = null; -// Assert.assertFalse(aaiAuth.authCookie(cookie, "function-1", new StringBuilder("user-1"))); -// } + // @Test + // public void testAuthCookie_NullCookie(){ + // SearchDbServiceAuth aaiAuth = new SearchDbServiceAuth(); + // Cookie cookie = null; + // Assert.assertFalse(aaiAuth.authCookie(cookie, "function-1", new StringBuilder("user-1"))); + // } -// @Test -// public void testAuthCookie_NotNullCookie(){ -// SearchDbServiceAuth aaiAuth = new SearchDbServiceAuth(); -// Cookie cookie = new Cookie ( "TestCookie", "TestValue"); -// // Cookie cookie = new Cookie ( "TestCookie", "TestValue" ); -// boolean retValue = aaiAuth.authCookie(cookie, "GET:testFunction", new StringBuilder("testuser")); -// Assert.assertTrue(retValue); -// } + // @Test + // public void testAuthCookie_NotNullCookie(){ + // SearchDbServiceAuth aaiAuth = new SearchDbServiceAuth(); + // Cookie cookie = new Cookie ( "TestCookie", "TestValue"); + // // Cookie cookie = new Cookie ( "TestCookie", "TestValue" ); + // boolean retValue = aaiAuth.authCookie(cookie, "GET:testFunction", new StringBuilder("testuser")); + // Assert.assertTrue(retValue); + // } - static void setFinalStatic(String fieldValue) throws NoSuchFieldException, SecurityException, - IllegalArgumentException, IllegalAccessException { + static void setFinalStatic(String fieldValue) + throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { Field configField = SearchDbConstants.class.getDeclaredField("SDB_AUTH_CONFIG_FILENAME"); configField.setAccessible(true); - Field modifiersField = Field.class.getDeclaredField( "modifiers" ); - modifiersField.setAccessible( true ); - modifiersField.setInt( configField, configField.getModifiers() & ~Modifier.FINAL ); + Field modifiersField = Field.class.getDeclaredField("modifiers"); + modifiersField.setAccessible(true); + modifiersField.setInt(configField, configField.getModifiers() & ~Modifier.FINAL); configField.set(null, fieldValue); } diff --git a/src/test/java/org/onap/aai/sa/rest/ApiUtilsTest.java b/src/test/java/org/onap/aai/sa/rest/ApiUtilsTest.java index 457dbdd..593ec92 100644 --- a/src/test/java/org/onap/aai/sa/rest/ApiUtilsTest.java +++ b/src/test/java/org/onap/aai/sa/rest/ApiUtilsTest.java @@ -27,16 +27,16 @@ import org.junit.Test; public class ApiUtilsTest { - @Test - public void testHTTPStatusConversion() { - String statusString; - statusString = ApiUtils.getHttpStatusString(201); - assertEquals(0, statusString.compareToIgnoreCase("Created")); + @Test + public void testHTTPStatusConversion() { + String statusString; + statusString = ApiUtils.getHttpStatusString(201); + assertEquals(0, statusString.compareToIgnoreCase("Created")); - statusString = ApiUtils.getHttpStatusString(207); - assertEquals(0, statusString.compareToIgnoreCase("Multi-Status")); + statusString = ApiUtils.getHttpStatusString(207); + assertEquals(0, statusString.compareToIgnoreCase("Multi-Status")); - statusString = ApiUtils.getHttpStatusString(9999); - assertEquals(0, statusString.compareToIgnoreCase("Unknown")); - } + statusString = ApiUtils.getHttpStatusString(9999); + assertEquals(0, statusString.compareToIgnoreCase("Unknown")); + } } diff --git a/src/test/java/org/onap/aai/sa/rest/BulkApiTest.java b/src/test/java/org/onap/aai/sa/rest/BulkApiTest.java index a1c255c..eff4efc 100644 --- a/src/test/java/org/onap/aai/sa/rest/BulkApiTest.java +++ b/src/test/java/org/onap/aai/sa/rest/BulkApiTest.java @@ -38,8 +38,7 @@ import org.springframework.test.web.servlet.ResultActions; /** - * This suite of tests validates the behaviour of the bulk operations REST - * end point. + * This suite of tests validates the behaviour of the bulk operations REST end point. */ @RunWith(SpringRunner.class) @SpringBootTest(classes = org.onap.aai.sa.Application.class) @@ -54,16 +53,16 @@ public class BulkApiTest { @Test public void authenticationFailureTest() throws Exception { - this.mockMvc.perform ( post ( TOP_URI) .contentType( MediaType.APPLICATION_JSON) - .content ( SearchServiceApiHarness.FAIL_AUTHENTICATION_TRIGGER )).andExpect ( status ().isForbidden () ); + this.mockMvc + .perform(post(TOP_URI).contentType(MediaType.APPLICATION_JSON) + .content(SearchServiceApiHarness.FAIL_AUTHENTICATION_TRIGGER)) + .andExpect(status().isForbidden()); } /** - * This test validates that properly constructed json payloads are - * correctly validated and that improperly contructed payloads will - * be rejected with the appropriate response code returned to the - * client. + * This test validates that properly constructed json payloads are correctly validated and that improperly + * contructed payloads will be rejected with the appropriate response code returned to the client. * * @throws IOException */ @@ -72,19 +71,20 @@ public class BulkApiTest { // Post a request to the bulk operations endpoint with a valid // operations list payload. - File validBulkOpsFile = new File ("src/test/resources/json/bulk-ops-valid.json"); + File validBulkOpsFile = new File("src/test/resources/json/bulk-ops-valid.json"); String validPayloadStr = TestUtils.readFileToString(validBulkOpsFile); // Validate that the payload is accepted as expected. - this.mockMvc.perform ( post ( TOP_URI ).contentType ( MediaType.APPLICATION_JSON ) - .content ( validPayloadStr ) ).andExpect ( status ().isOk () ); + this.mockMvc.perform(post(TOP_URI).contentType(MediaType.APPLICATION_JSON).content(validPayloadStr)) + .andExpect(status().isOk()); // Post a request to the bulk operations endpoint with an invalid // operations list payload. File inValidBulkOpsFile = new File("src/test/resources/json/bulk-ops-invalid.json"); String inValidPayloadStr = TestUtils.readFileToString(inValidBulkOpsFile); - ResultActions invalid = this.mockMvc.perform ( post ( TOP_URI ).contentType ( MediaType.APPLICATION_JSON ) - .content ( inValidPayloadStr ) ).andExpect ( status ().isBadRequest ()); + ResultActions invalid = + this.mockMvc.perform(post(TOP_URI).contentType(MediaType.APPLICATION_JSON).content(inValidPayloadStr)) + .andExpect(status().isBadRequest()); } } diff --git a/src/test/java/org/onap/aai/sa/rest/BulkRequestTest.java b/src/test/java/org/onap/aai/sa/rest/BulkRequestTest.java index d085d04..d5999b8 100644 --- a/src/test/java/org/onap/aai/sa/rest/BulkRequestTest.java +++ b/src/test/java/org/onap/aai/sa/rest/BulkRequestTest.java @@ -33,7 +33,7 @@ import org.springframework.test.context.junit4.SpringRunner; public class BulkRequestTest { @Test - public void testBulkRequest_Delete(){ + public void testBulkRequest_Delete() { BulkRequest request = new BulkRequest(); BulkOperation operation = new BulkOperation(); Document document = new Document(); @@ -54,7 +54,7 @@ public class BulkRequestTest { } @Test - public void testBulkRequest_Update(){ + public void testBulkRequest_Update() { BulkRequest request = new BulkRequest(); BulkOperation operation = new BulkOperation(); Document document = new Document(); @@ -74,7 +74,7 @@ public class BulkRequestTest { } @Test - public void testBulkRequest_Create(){ + public void testBulkRequest_Create() { BulkRequest request = new BulkRequest(); BulkOperation operation = new BulkOperation(); Document document = new Document(); @@ -94,7 +94,7 @@ public class BulkRequestTest { } @Test - public void testBulkRequest_Undefined(){ + public void testBulkRequest_Undefined() { BulkRequest request = new BulkRequest(); Assert.assertNull(request.getOperation()); Assert.assertNull(request.getOperationType()); @@ -102,7 +102,7 @@ public class BulkRequestTest { } @Test - public void testGetIndex(){ + public void testGetIndex() { BulkRequest request = new BulkRequest(); BulkOperation operation = new BulkOperation(); BulkMetaData metaData = new BulkMetaData(); @@ -114,7 +114,7 @@ public class BulkRequestTest { } @Test - public void testGetId(){ + public void testGetId() { BulkRequest request = new BulkRequest(); BulkOperation operation = new BulkOperation(); BulkMetaData metaData = new BulkMetaData(); @@ -126,16 +126,15 @@ public class BulkRequestTest { } @Test - public void testApiUtils(){ - Assert.assertEquals("services/search-data-service/v1/search/indexes/index1", - ApiUtils.buildIndexUri("index1")); + public void testApiUtils() { + Assert.assertEquals("services/search-data-service/v1/search/indexes/index1", ApiUtils.buildIndexUri("index1")); Assert.assertEquals("services/search-data-service/v1/search/indexes/index1/documents/document1", ApiUtils.buildDocumentUri("index1", "document1")); Assert.assertTrue(ApiUtils.validateIndexUri("services/search-data-service/v1/search/indexes/index1")); - Assert.assertTrue(ApiUtils.validateDocumentUri - ("services/search-data-service/v1/search/indexes/index1/documents/document1", true)); - Assert.assertTrue(ApiUtils.validateDocumentUri - ("services/search-data-service/v1/search/indexes/index1/documents/document1", false)); + Assert.assertTrue(ApiUtils.validateDocumentUri( + "services/search-data-service/v1/search/indexes/index1/documents/document1", true)); + Assert.assertTrue(ApiUtils.validateDocumentUri( + "services/search-data-service/v1/search/indexes/index1/documents/document1", false)); } private BulkMetaData getMetaData() { diff --git a/src/test/java/org/onap/aai/sa/rest/DocumentApiTest.java b/src/test/java/org/onap/aai/sa/rest/DocumentApiTest.java index 78fec3e..4276f3d 100644 --- a/src/test/java/org/onap/aai/sa/rest/DocumentApiTest.java +++ b/src/test/java/org/onap/aai/sa/rest/DocumentApiTest.java @@ -46,186 +46,182 @@ import org.springframework.test.web.servlet.MvcResult; @RunWith(SpringRunner.class) @SpringBootTest @AutoConfigureMockMvc -public class DocumentApiTest { - - private static final String INDEXES_URI = "/test/indexes/"; - private static final String DOCUMENT_URI = "documents/"; - - private static final String SEARCH_URI = "query/"; - private static final String INDEX_NAME = "test-index"; - private static final String DOC_ID = "test-1"; - private static final String SIMPLE_QUERY = "\"parsed-query\": {\"my-field\": \"something\", \"query-string\": \"string\"}"; - private static final String COMPLEX_QUERY = - "{" - + "\"filter\": {" - + "\"all\": [" - + "{\"match\": {\"field\": \"searchTags\", \"value\": \"a\"}}" - + "]" - + "}," - + "\"queries\": [" - + "{\"may\": {\"parsed-query\": {\"field\": \"searchTags\", \"query-string\": \"b\"}}}" - + "]" - + "}"; - - private static final String CREATE_JSON_CONTENT = "creation content"; +public class DocumentApiTest { + + private static final String INDEXES_URI = "/test/indexes/"; + private static final String DOCUMENT_URI = "documents/"; + + private static final String SEARCH_URI = "query/"; + private static final String INDEX_NAME = "test-index"; + private static final String DOC_ID = "test-1"; + private static final String SIMPLE_QUERY = + "\"parsed-query\": {\"my-field\": \"something\", \"query-string\": \"string\"}"; + private static final String COMPLEX_QUERY = "{" + "\"filter\": {" + "\"all\": [" + + "{\"match\": {\"field\": \"searchTags\", \"value\": \"a\"}}" + "]" + "}," + "\"queries\": [" + + "{\"may\": {\"parsed-query\": {\"field\": \"searchTags\", \"query-string\": \"b\"}}}" + "]" + "}"; + + private static final String CREATE_JSON_CONTENT = "creation content"; @Autowired private MockMvc mockMvc; - /** - * This test validates the behaviour of the 'Create Document' POST request - * endpoint. - * - * @throws IOException - * @throws ParseException - */ - @Test - public void createDocumentTest() throws Exception { - - MvcResult result = this.mockMvc.perform ( post ( INDEXES_URI + INDEX_NAME + "/" + DOCUMENT_URI ).contentType ( MediaType.APPLICATION_JSON ) - .content ( CREATE_JSON_CONTENT ) ).andReturn ( ); - - // Our stub document store DAO returns the parameters that it was - // passed as the result string, so now we can validate that our - // endpoint invoked it with the correct parameters. - - JSONParser parser = new JSONParser(); - JSONObject json = (JSONObject) parser.parse(result.getResponse ().getContentAsString ()); - - assertTrue("Unexpected Result ", !json.get("etag").toString().isEmpty()); - } - - /** - * This test validates the behaviour of the 'Create Document' PUT request - * endpoint. - * - * @throws IOException - * @throws ParseException - */ - @Test - public void updateDocumentTest() throws Exception { - // WebTarget target = target(INDEXES_URI + INDEX_NAME + "/" + DOCUMENT_URI + DOC_ID); - // Builder request = target.request().header("If-Match", "1"); - // String result = request.put(Entity.json(CREATE_JSON_CONTENT), String.class); - - MvcResult result = this.mockMvc.perform ( put ( INDEXES_URI + INDEX_NAME + "/" + DOCUMENT_URI + DOC_ID ).contentType ( MediaType.APPLICATION_JSON ) - .header ( "If-Match", "1" ).content ( CREATE_JSON_CONTENT ) ).andReturn ( ); - - // Our stub document store DAO returns the parameters that it was - // passed as the result string, so now we can validate that our - // endpoint invoked it with the correct parameters. - JSONParser parser = new JSONParser(); - JSONObject json = (JSONObject) parser.parse(result.getResponse ().getContentAsString ()); - - assertTrue("Unexpected Result ", !json.get("etag").toString().isEmpty()); - } - - /** - * This test validates the behaviour of the 'Get Document' GET request - * endpoint. - * - * @throws IOException - * @throws ParseException - */ - @Test - public void getDocumentTest() throws Exception { - // String result = target(INDEXES_URI + INDEX_NAME + "/" + DOCUMENT_URI + DOC_ID).request().get(String.class); - - // MvcResult result = this.mockMvc.perform ( get ( INDEXES_URI + INDEX_NAME + "/" + DOCUMENT_URI + DOC_ID ) ).andReturn (); - MvcResult result = this.mockMvc.perform ( get ( INDEXES_URI + INDEX_NAME + "/" + DOCUMENT_URI + DOC_ID ) - .contentType ( MediaType.APPLICATION_JSON ) - .header ( "If-Match", "1" ) - .content ( CREATE_JSON_CONTENT ) ).andReturn ( ); - - - // Our stub document store DAO returns the parameters that it was - // passed as the result string, so now we can validate that our - // endpoint invoked it with the correct parameters. - JSONParser parser = new JSONParser(); - JSONObject json = (JSONObject) parser.parse(result.getResponse ().getContentAsString ()); - - assertTrue("Unexpected Result ", !json.get("etag").toString().isEmpty()); - - } -// -// /** -// * This test validates the behaviour of the 'Delete Document' DELETE request -// * endpoint. -// * -// * @throws IOException -// * @throws ParseException -// */ - @Test - public void deleteDocumentTest() throws Exception { -// WebTarget target = target(INDEXES_URI + INDEX_NAME + "/" + DOCUMENT_URI + DOC_ID); -// Builder request = target.request().header("If-Match", "1"); -// String result = request.delete(String.class); - MvcResult result = this.mockMvc.perform ( delete ( INDEXES_URI + INDEX_NAME + "/" + DOCUMENT_URI + DOC_ID ) - .contentType ( MediaType.APPLICATION_JSON ) - .header ( "If-Match", "1" ) - .content ( CREATE_JSON_CONTENT ) ).andReturn ( ); - - - - // Our stub document store DAO returns the parameters that it was - // passed as the result string, so now we can validate that our - // endpoint invoked it with the correct parameters. - assertTrue("Unexpected Result ", result.getResponse ().getContentAsString ().isEmpty ()); - - } -// -// /** -// * This test validates the behaviour of the 'Search Documents' GET request -// * endpoint. -// * -// * @throws IOException -// * @throws ParseException -// */ - @Ignore - @Test - public void searchDocumentTest1() throws Exception { - // String result = target(INDEXES_URI + INDEX_NAME + "/" + SEARCH_URI + SIMPLE_QUERY).request().get(String.class); - - MvcResult result = this.mockMvc.perform ( get ( INDEXES_URI + INDEX_NAME + "/" + SEARCH_URI + SIMPLE_QUERY ) - .contentType ( MediaType.APPLICATION_JSON ) - .header ( "If-Match", "1" ) - .content ( CREATE_JSON_CONTENT ) ).andReturn ( ); - - // Our stub document store DAO returns the parameters that it was - // passed as the result string, so now we can validate that our - // endpoint invoked it with the correct parameters. - JSONParser parser = new JSONParser(); - JSONObject json = (JSONObject) parser.parse(result.getResponse ().getContentAsString ()); - - assertTrue("Unexpected Result ", json.get("totalHits").toString().equals("1")); - - - } -// - /** - * This test validates the behaviour of the 'Search Documents' GET request - * endpoint. - * - * @throws IOException - * @throws ParseException - */ - @Test - public void searchDocumentTest2() throws Exception { - // String result = target(INDEXES_URI + INDEX_NAME + "/" + SEARCH_URI).request().post(Entity.json(COMPLEX_QUERY), String.class); - - MvcResult result = this.mockMvc.perform ( get ( INDEXES_URI + INDEX_NAME + "/" + SEARCH_URI) - .contentType ( MediaType.APPLICATION_JSON ) - .content ( COMPLEX_QUERY ) ).andReturn ( ); - - // Our stub document store DAO returns the parameters that it was - // passed as the result string, so now we can validate that our - // endpoint invoked it with the correct parameters. - JSONParser parser = new JSONParser(); - JSONObject json = (JSONObject) parser.parse(result.getResponse ().getContentAsString ()); - JSONObject resultJson = (JSONObject) json.get("searchResult"); - - assertTrue("Unexpected Result ", resultJson.get("totalHits").toString().equals("1")); - - } + /** + * This test validates the behaviour of the 'Create Document' POST request endpoint. + * + * @throws IOException + * @throws ParseException + */ + @Test + public void createDocumentTest() throws Exception { + + MvcResult result = this.mockMvc.perform(post(INDEXES_URI + INDEX_NAME + "/" + DOCUMENT_URI) + .contentType(MediaType.APPLICATION_JSON).content(CREATE_JSON_CONTENT)).andReturn(); + + // Our stub document store DAO returns the parameters that it was + // passed as the result string, so now we can validate that our + // endpoint invoked it with the correct parameters. + + JSONParser parser = new JSONParser(); + JSONObject json = (JSONObject) parser.parse(result.getResponse().getContentAsString()); + + assertTrue("Unexpected Result ", !json.get("etag").toString().isEmpty()); + } + + /** + * This test validates the behaviour of the 'Create Document' PUT request endpoint. + * + * @throws IOException + * @throws ParseException + */ + @Test + public void updateDocumentTest() throws Exception { + // WebTarget target = target(INDEXES_URI + INDEX_NAME + "/" + DOCUMENT_URI + DOC_ID); + // Builder request = target.request().header("If-Match", "1"); + // String result = request.put(Entity.json(CREATE_JSON_CONTENT), String.class); + + MvcResult result = this.mockMvc + .perform(put(INDEXES_URI + INDEX_NAME + "/" + DOCUMENT_URI + DOC_ID) + .contentType(MediaType.APPLICATION_JSON).header("If-Match", "1").content(CREATE_JSON_CONTENT)) + .andReturn(); + + // Our stub document store DAO returns the parameters that it was + // passed as the result string, so now we can validate that our + // endpoint invoked it with the correct parameters. + JSONParser parser = new JSONParser(); + JSONObject json = (JSONObject) parser.parse(result.getResponse().getContentAsString()); + + assertTrue("Unexpected Result ", !json.get("etag").toString().isEmpty()); + } + + /** + * This test validates the behaviour of the 'Get Document' GET request endpoint. + * + * @throws IOException + * @throws ParseException + */ + @Test + public void getDocumentTest() throws Exception { + // String result = target(INDEXES_URI + INDEX_NAME + "/" + DOCUMENT_URI + DOC_ID).request().get(String.class); + + // MvcResult result = this.mockMvc.perform ( get ( INDEXES_URI + INDEX_NAME + "/" + DOCUMENT_URI + DOC_ID ) + // ).andReturn (); + MvcResult result = this.mockMvc + .perform(get(INDEXES_URI + INDEX_NAME + "/" + DOCUMENT_URI + DOC_ID) + .contentType(MediaType.APPLICATION_JSON).header("If-Match", "1").content(CREATE_JSON_CONTENT)) + .andReturn(); + + + // Our stub document store DAO returns the parameters that it was + // passed as the result string, so now we can validate that our + // endpoint invoked it with the correct parameters. + JSONParser parser = new JSONParser(); + JSONObject json = (JSONObject) parser.parse(result.getResponse().getContentAsString()); + + assertTrue("Unexpected Result ", !json.get("etag").toString().isEmpty()); + + } + + // + // /** + // * This test validates the behaviour of the 'Delete Document' DELETE request + // * endpoint. + // * + // * @throws IOException + // * @throws ParseException + // */ + @Test + public void deleteDocumentTest() throws Exception { + // WebTarget target = target(INDEXES_URI + INDEX_NAME + "/" + DOCUMENT_URI + DOC_ID); + // Builder request = target.request().header("If-Match", "1"); + // String result = request.delete(String.class); + MvcResult result = this.mockMvc + .perform(delete(INDEXES_URI + INDEX_NAME + "/" + DOCUMENT_URI + DOC_ID) + .contentType(MediaType.APPLICATION_JSON).header("If-Match", "1").content(CREATE_JSON_CONTENT)) + .andReturn(); + + + + // Our stub document store DAO returns the parameters that it was + // passed as the result string, so now we can validate that our + // endpoint invoked it with the correct parameters. + assertTrue("Unexpected Result ", result.getResponse().getContentAsString().isEmpty()); + + } + + // + // /** + // * This test validates the behaviour of the 'Search Documents' GET request + // * endpoint. + // * + // * @throws IOException + // * @throws ParseException + // */ + @Ignore + @Test + public void searchDocumentTest1() throws Exception { + // String result = target(INDEXES_URI + INDEX_NAME + "/" + SEARCH_URI + + // SIMPLE_QUERY).request().get(String.class); + + MvcResult result = this.mockMvc + .perform(get(INDEXES_URI + INDEX_NAME + "/" + SEARCH_URI + SIMPLE_QUERY) + .contentType(MediaType.APPLICATION_JSON).header("If-Match", "1").content(CREATE_JSON_CONTENT)) + .andReturn(); + + // Our stub document store DAO returns the parameters that it was + // passed as the result string, so now we can validate that our + // endpoint invoked it with the correct parameters. + JSONParser parser = new JSONParser(); + JSONObject json = (JSONObject) parser.parse(result.getResponse().getContentAsString()); + + assertTrue("Unexpected Result ", json.get("totalHits").toString().equals("1")); + + + } + + // + /** + * This test validates the behaviour of the 'Search Documents' GET request endpoint. + * + * @throws IOException + * @throws ParseException + */ + @Test + public void searchDocumentTest2() throws Exception { + // String result = target(INDEXES_URI + INDEX_NAME + "/" + + // SEARCH_URI).request().post(Entity.json(COMPLEX_QUERY), String.class); + + MvcResult result = this.mockMvc.perform(get(INDEXES_URI + INDEX_NAME + "/" + SEARCH_URI) + .contentType(MediaType.APPLICATION_JSON).content(COMPLEX_QUERY)).andReturn(); + + // Our stub document store DAO returns the parameters that it was + // passed as the result string, so now we can validate that our + // endpoint invoked it with the correct parameters. + JSONParser parser = new JSONParser(); + JSONObject json = (JSONObject) parser.parse(result.getResponse().getContentAsString()); + JSONObject resultJson = (JSONObject) json.get("searchResult"); + + assertTrue("Unexpected Result ", resultJson.get("totalHits").toString().equals("1")); + + } } diff --git a/src/test/java/org/onap/aai/sa/rest/DocumentSchemaTest.java b/src/test/java/org/onap/aai/sa/rest/DocumentSchemaTest.java index 44ed60c..b18928d 100644 --- a/src/test/java/org/onap/aai/sa/rest/DocumentSchemaTest.java +++ b/src/test/java/org/onap/aai/sa/rest/DocumentSchemaTest.java @@ -32,68 +32,69 @@ import org.junit.Test; public class DocumentSchemaTest { - private final String SIMPLE_DOC_SCHEMA_JSON = "src/test/resources/json/simpleDocument.json"; - private final String NESTED_DOC_SCHEMA_JSON = "src/test/resources/json/nested-document.json"; - - - /** - * This test validates that we convert document definitions back and - * forth between json strings and POJOs without any loss of data. - * - * @throws com.fasterxml.jackson.core.JsonParseException - * @throws com.fasterxml.jackson.databind.JsonMappingException - * @throws IOException - */ - @Test - public void simpleDocSchemaFromJsonFileTest() throws com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException, IOException { - - // Import our json format document schema from a file. - File schemaFile = new File(SIMPLE_DOC_SCHEMA_JSON); - String fileString = TestUtils.readFileToString(schemaFile); - - // Unmarshall that to a Java POJO - ObjectMapper mapper = new ObjectMapper(); - DocumentSchema docSchema = mapper.readValue(schemaFile, DocumentSchema.class); - - // Now, for the purposes of comparison, produce a JSON string from - // our Java object. - String jsonString = mapper.writeValueAsString(docSchema); - - // Assert that the raw JSON that we read from the file matches the marshalled - // JSON we generated from our Java object (ie: validate that we didn't lose - // anything going in either direction). - assertTrue("Marshalled object does not match the original json source that produced it", - fileString.equals(jsonString)); - } - -// -// /** -// * This test validates that we convert document definitions back and -// * forth between json strings and POJOs without any loss of data in -// * the case of document schemas which contain nested fields. -// * -// * @throws com.fasterxml.jackson.core.JsonParseException -// * @throws com.fasterxml.jackson.databind.JsonMappingException -// * @throws IOException -// */ - - @Test - public void nestedDocSchemaFromJsonFileTest() throws JsonParseException, JsonMappingException, IOException { - - // Import our json format document schema from a file. - File schemaFile = new File(NESTED_DOC_SCHEMA_JSON); - String fileString = TestUtils.readFileToString(schemaFile); - - // Unmarshall that to a Java POJO - ObjectMapper mapper = new ObjectMapper(); - DocumentSchema docSchema = mapper.readValue(schemaFile, DocumentSchema.class); - - String jsonString = mapper.writeValueAsString(docSchema); - - // Assert that the raw JSON that we read from the file matches the marshalled - // JSON we generated from our Java object (ie: validate that we didn't lose - // anything going in either direction). - assertTrue("Marshalled object does not match the original json source that produced it", - fileString.equals(jsonString)); - } -} \ No newline at end of file + private final String SIMPLE_DOC_SCHEMA_JSON = "src/test/resources/json/simpleDocument.json"; + private final String NESTED_DOC_SCHEMA_JSON = "src/test/resources/json/nested-document.json"; + + + /** + * This test validates that we convert document definitions back and forth between json strings and POJOs without + * any loss of data. + * + * @throws com.fasterxml.jackson.core.JsonParseException + * @throws com.fasterxml.jackson.databind.JsonMappingException + * @throws IOException + */ + @Test + public void simpleDocSchemaFromJsonFileTest() throws com.fasterxml.jackson.core.JsonParseException, + com.fasterxml.jackson.databind.JsonMappingException, IOException { + + // Import our json format document schema from a file. + File schemaFile = new File(SIMPLE_DOC_SCHEMA_JSON); + String fileString = TestUtils.readFileToString(schemaFile); + + // Unmarshall that to a Java POJO + ObjectMapper mapper = new ObjectMapper(); + DocumentSchema docSchema = mapper.readValue(schemaFile, DocumentSchema.class); + + // Now, for the purposes of comparison, produce a JSON string from + // our Java object. + String jsonString = mapper.writeValueAsString(docSchema); + + // Assert that the raw JSON that we read from the file matches the marshalled + // JSON we generated from our Java object (ie: validate that we didn't lose + // anything going in either direction). + assertTrue("Marshalled object does not match the original json source that produced it", + fileString.equals(jsonString)); + } + + // + // /** + // * This test validates that we convert document definitions back and + // * forth between json strings and POJOs without any loss of data in + // * the case of document schemas which contain nested fields. + // * + // * @throws com.fasterxml.jackson.core.JsonParseException + // * @throws com.fasterxml.jackson.databind.JsonMappingException + // * @throws IOException + // */ + + @Test + public void nestedDocSchemaFromJsonFileTest() throws JsonParseException, JsonMappingException, IOException { + + // Import our json format document schema from a file. + File schemaFile = new File(NESTED_DOC_SCHEMA_JSON); + String fileString = TestUtils.readFileToString(schemaFile); + + // Unmarshall that to a Java POJO + ObjectMapper mapper = new ObjectMapper(); + DocumentSchema docSchema = mapper.readValue(schemaFile, DocumentSchema.class); + + String jsonString = mapper.writeValueAsString(docSchema); + + // Assert that the raw JSON that we read from the file matches the marshalled + // JSON we generated from our Java object (ie: validate that we didn't lose + // anything going in either direction). + assertTrue("Marshalled object does not match the original json source that produced it", + fileString.equals(jsonString)); + } +} diff --git a/src/test/java/org/onap/aai/sa/rest/DocumentTest.java b/src/test/java/org/onap/aai/sa/rest/DocumentTest.java index efff07b..9fa5fe1 100644 --- a/src/test/java/org/onap/aai/sa/rest/DocumentTest.java +++ b/src/test/java/org/onap/aai/sa/rest/DocumentTest.java @@ -71,7 +71,7 @@ public class DocumentTest { DocumentApi documentApi; @Before - public void setUp(){ + public void setUp() { MockitoAnnotations.initMocks(this); documentApi = new DocumentApi(searchServiceApi); } @@ -80,14 +80,14 @@ public class DocumentTest { public void testDocumentClass_AllMethods() throws JsonProcessingException { Document doc = new Document(); doc.setField("name-1", "value-1"); - Assert.assertTrue(doc.getFields().size()==1); + Assert.assertTrue(doc.getFields().size() == 1); Assert.assertTrue(doc.toJson().contains("value-1")); Assert.assertNotNull(doc.toString()); Assert.assertTrue(doc.toString().contains("name-1")); } @Test - public void testProcessPost_NullContent(){ + public void testProcessPost_NullContent() { String transactionId = "transactionId-1"; String remoteAddr = "http://127.0.0.1"; String content = null; @@ -97,10 +97,10 @@ public class DocumentTest { Mockito.when(request.getMethod()).thenReturn("testMethod"); Mockito.when(request.getRequestURL()).thenReturn(new StringBuffer("http://127.0.0.1")); Mockito.when(request.getRemoteHost()).thenReturn("localhost"); - ResponseEntity response = documentApi.processPost(content, request, headers, httpResponse, "index", - documentStore); + ResponseEntity response = + documentApi.processPost(content, request, headers, httpResponse, "index", documentStore); Assert.assertNotNull(response); - Assert.assertTrue( HttpStatus.BAD_REQUEST.value () == response.getStatusCodeValue ()); + Assert.assertTrue(HttpStatus.BAD_REQUEST.value() == response.getStatusCodeValue()); } @Test @@ -117,12 +117,13 @@ public class DocumentTest { Mockito.when(searchServiceApi.validateRequest(Mockito.any(HttpHeaders.class), Mockito.any(HttpServletRequest.class), Mockito.any(ApiUtils.Action.class), Mockito.anyString())) .thenThrow(IllegalArgumentException.class); - ResponseEntity response = documentApi.processPost(content, request, headers, httpResponse, "index", - documentStore); + ResponseEntity response = + documentApi.processPost(content, request, headers, httpResponse, "index", documentStore); Assert.assertNotNull(response); - Assert.assertTrue(HttpStatus.FORBIDDEN.value () == response.getStatusCodeValue ()); + Assert.assertTrue(HttpStatus.FORBIDDEN.value() == response.getStatusCodeValue()); } -// + + // @Test public void testProcessPost_ValidRequest() throws Exception { String transactionId = "transactionId-1"; @@ -144,12 +145,13 @@ public class DocumentTest { Mockito.when(documentStore.createDocument(Mockito.anyString(), Mockito.any(DocumentStoreDataEntity.class), Mockito.anyBoolean())).thenReturn(result); Mockito.doNothing().when(httpResponse).setHeader(Mockito.anyString(), Mockito.anyString()); - ResponseEntity response = documentApi.processPost(content, request, headers, httpResponse, "index", - documentStore); + ResponseEntity response = + documentApi.processPost(content, request, headers, httpResponse, "index", documentStore); Assert.assertNotNull(response); - Assert.assertTrue(HttpStatus.INTERNAL_SERVER_ERROR.value () == response.getStatusCodeValue ()); + Assert.assertTrue(HttpStatus.INTERNAL_SERVER_ERROR.value() == response.getStatusCodeValue()); } -// + + // @Test public void testProcessSearchWithGet_Created() throws Exception { String transactionId = "transactionId-1"; @@ -170,13 +172,14 @@ public class DocumentTest { Mockito.any(HttpServletRequest.class), Mockito.any(ApiUtils.Action.class), Mockito.anyString())) .thenReturn(true); Mockito.when(documentStore.search(Mockito.anyString(), Mockito.anyString())).thenReturn(result); - ResponseEntityresponse = documentApi.processSearchWithGet(content, request, headers, "index-1", - "query-text", documentStore); + ResponseEntity response = + documentApi.processSearchWithGet(content, request, headers, "index-1", "query-text", documentStore); Assert.assertNotNull(response); Assert.assertTrue(HttpStatus.CREATED.value() == response.getStatusCodeValue()); } -// + + // @Test public void testProcessSearchWithGet_ValidateThrowsException() throws Exception { String transactionId = "transactionId-1"; @@ -197,13 +200,14 @@ public class DocumentTest { Mockito.any(HttpServletRequest.class), Mockito.any(ApiUtils.Action.class), Mockito.anyString())) .thenThrow(IllegalArgumentException.class); Mockito.when(documentStore.search(Mockito.anyString(), Mockito.anyString())).thenReturn(result); - ResponseEntityresponse = documentApi.processSearchWithGet(content, request, headers, "index-1", - "query-text", documentStore); + ResponseEntity response = + documentApi.processSearchWithGet(content, request, headers, "index-1", "query-text", documentStore); Assert.assertNotNull(response); Assert.assertTrue(HttpStatus.FORBIDDEN.value() == response.getStatusCodeValue()); } -// + + // @Test public void testProcessSearchWithGet_ValidateIsFalse() throws Exception { String transactionId = "transactionId-1"; @@ -224,8 +228,8 @@ public class DocumentTest { Mockito.any(HttpServletRequest.class), Mockito.any(ApiUtils.Action.class), Mockito.anyString())) .thenReturn(false); Mockito.when(documentStore.search(Mockito.anyString(), Mockito.anyString())).thenReturn(result); - ResponseEntityresponse = documentApi.processSearchWithGet(content, request, headers, "index-1", - "query-text", documentStore); + ResponseEntity response = + documentApi.processSearchWithGet(content, request, headers, "index-1", "query-text", documentStore); Assert.assertNotNull(response); Assert.assertTrue(HttpStatus.FORBIDDEN.value() == response.getStatusCodeValue()); @@ -251,15 +255,15 @@ public class DocumentTest { Mockito.any(HttpServletRequest.class), Mockito.any(ApiUtils.Action.class), Mockito.anyString())) .thenReturn(true); Mockito.when(documentStore.search(Mockito.anyString(), Mockito.anyString())).thenReturn(result); - ResponseEntityresponse = documentApi.processSearchWithGet(content, request, headers, "index-1", - "query-text", documentStore); + ResponseEntity response = + documentApi.processSearchWithGet(content, request, headers, "index-1", "query-text", documentStore); Assert.assertNotNull(response); Assert.assertTrue(HttpStatus.FOUND.value() == response.getStatusCodeValue()); } @Test - public void testProcessPut_NullContent(){ + public void testProcessPut_NullContent() { String transactionId = "transactionId-1"; String remoteAddr = "http://127.0.0.1"; String content = null; @@ -269,8 +273,8 @@ public class DocumentTest { Mockito.when(request.getMethod()).thenReturn("testMethod"); Mockito.when(request.getRequestURL()).thenReturn(new StringBuffer("http://127.0.0.1")); Mockito.when(request.getRemoteHost()).thenReturn("localhost"); - ResponseEntityresponse = documentApi.processPut(content, request, headers, httpResponse, "index","id-1", - documentStore); + ResponseEntity response = + documentApi.processPut(content, request, headers, httpResponse, "index", "id-1", documentStore); Assert.assertNotNull(response); Assert.assertTrue(HttpStatus.BAD_REQUEST.value() == response.getStatusCodeValue()); } @@ -289,8 +293,8 @@ public class DocumentTest { Mockito.when(searchServiceApi.validateRequest(Mockito.any(HttpHeaders.class), Mockito.any(HttpServletRequest.class), Mockito.any(ApiUtils.Action.class), Mockito.anyString())) .thenThrow(IllegalArgumentException.class); - ResponseEntityresponse = documentApi.processPut(content, request, headers, httpResponse, "index","id-1", - documentStore); + ResponseEntity response = + documentApi.processPut(content, request, headers, httpResponse, "index", "id-1", documentStore); Assert.assertNotNull(response); Assert.assertTrue(HttpStatus.FORBIDDEN.value() == response.getStatusCodeValue()); } @@ -309,8 +313,8 @@ public class DocumentTest { Mockito.when(searchServiceApi.validateRequest(Mockito.any(HttpHeaders.class), Mockito.any(HttpServletRequest.class), Mockito.any(ApiUtils.Action.class), Mockito.anyString())) .thenReturn(false); - ResponseEntityresponse = documentApi.processPut(content, request, headers, httpResponse, "index","id-1", - documentStore); + ResponseEntity response = + documentApi.processPut(content, request, headers, httpResponse, "index", "id-1", documentStore); Assert.assertNotNull(response); Assert.assertTrue(HttpStatus.FORBIDDEN.value() == response.getStatusCodeValue()); } @@ -336,8 +340,8 @@ public class DocumentTest { .thenReturn(true); Mockito.when(documentStore.updateDocument(Mockito.anyString(), Mockito.any(DocumentStoreDataEntity.class), Mockito.anyBoolean())).thenReturn(result); - ResponseEntityresponse = documentApi.processPut(content, request, headers, httpResponse, "index","id-1", - documentStore); + ResponseEntity response = + documentApi.processPut(content, request, headers, httpResponse, "index", "id-1", documentStore); Assert.assertNotNull(response); Assert.assertTrue(HttpStatus.FOUND.value() == response.getStatusCodeValue()); } @@ -356,8 +360,8 @@ public class DocumentTest { Mockito.when(searchServiceApi.validateRequest(Mockito.any(HttpHeaders.class), Mockito.any(HttpServletRequest.class), Mockito.any(ApiUtils.Action.class), Mockito.anyString())) .thenThrow(IllegalArgumentException.class); - ResponseEntityresponse = documentApi.processDelete(content, request, headers, httpResponse, "index","id-1", - documentStore); + ResponseEntity response = + documentApi.processDelete(content, request, headers, httpResponse, "index", "id-1", documentStore); Assert.assertNotNull(response); Assert.assertTrue(HttpStatus.FORBIDDEN.value() == response.getStatusCodeValue()); } @@ -376,8 +380,8 @@ public class DocumentTest { Mockito.when(searchServiceApi.validateRequest(Mockito.any(HttpHeaders.class), Mockito.any(HttpServletRequest.class), Mockito.any(ApiUtils.Action.class), Mockito.anyString())) .thenReturn(false); - ResponseEntityresponse = documentApi.processDelete(content, request, headers, httpResponse, "index","id-1", - documentStore); + ResponseEntity response = + documentApi.processDelete(content, request, headers, httpResponse, "index", "id-1", documentStore); Assert.assertNotNull(response); Assert.assertTrue(HttpStatus.FORBIDDEN.value() == response.getStatusCodeValue()); } @@ -403,8 +407,8 @@ public class DocumentTest { .thenReturn(true); Mockito.when(documentStore.deleteDocument(Mockito.anyString(), Mockito.any(DocumentStoreDataEntity.class))) .thenReturn(result); - ResponseEntityresponse = documentApi.processDelete(content, request, headers, httpResponse, "index","id-1", - documentStore); + ResponseEntity response = + documentApi.processDelete(content, request, headers, httpResponse, "index", "id-1", documentStore); Assert.assertNotNull(response); Assert.assertTrue(HttpStatus.FOUND.value() == response.getStatusCodeValue()); } @@ -423,8 +427,8 @@ public class DocumentTest { Mockito.when(searchServiceApi.validateRequest(Mockito.any(HttpHeaders.class), Mockito.any(HttpServletRequest.class), Mockito.any(ApiUtils.Action.class), Mockito.anyString())) .thenThrow(IllegalArgumentException.class); - ResponseEntityresponse = documentApi.processGet(content, request, headers, httpResponse, "index","id-1", - documentStore); + ResponseEntity response = + documentApi.processGet(content, request, headers, httpResponse, "index", "id-1", documentStore); Assert.assertNotNull(response); Assert.assertTrue(HttpStatus.FORBIDDEN.value() == response.getStatusCodeValue()); } @@ -443,8 +447,8 @@ public class DocumentTest { Mockito.when(searchServiceApi.validateRequest(Mockito.any(HttpHeaders.class), Mockito.any(HttpServletRequest.class), Mockito.any(ApiUtils.Action.class), Mockito.anyString())) .thenReturn(false); - ResponseEntityresponse = documentApi.processGet(content, request, headers, httpResponse, "index","id-1", - documentStore); + ResponseEntity response = + documentApi.processGet(content, request, headers, httpResponse, "index", "id-1", documentStore); Assert.assertNotNull(response); Assert.assertTrue(HttpStatus.FORBIDDEN.value() == response.getStatusCodeValue()); } @@ -469,14 +473,14 @@ public class DocumentTest { .thenReturn(true); Mockito.when(documentStore.getDocument(Mockito.anyString(), Mockito.any(DocumentStoreDataEntity.class))) .thenReturn(result); - ResponseEntityresponse = documentApi.processGet(content, request, headers, httpResponse, "index","id-1", - documentStore); + ResponseEntity response = + documentApi.processGet(content, request, headers, httpResponse, "index", "id-1", documentStore); Assert.assertNotNull(response); Assert.assertTrue(HttpStatus.FOUND.value() == response.getStatusCodeValue()); } @Test - public void testQueryWithGetWithPayload_NullContent(){ + public void testQueryWithGetWithPayload_NullContent() { String transactionId = "transactionId-1"; String remoteAddr = "http://127.0.0.1"; String content = null; @@ -486,8 +490,8 @@ public class DocumentTest { Mockito.when(request.getMethod()).thenReturn("testMethod"); Mockito.when(request.getRequestURL()).thenReturn(new StringBuffer("http://127.0.0.1")); Mockito.when(request.getRemoteHost()).thenReturn("localhost"); - ResponseEntityresponse = documentApi.queryWithGetWithPayload(content, request, headers, "index-1", - documentStore); + ResponseEntity response = + documentApi.queryWithGetWithPayload(content, request, headers, "index-1", documentStore); Assert.assertNotNull(response); Assert.assertTrue(HttpStatus.BAD_REQUEST.value() == response.getStatusCodeValue()); } @@ -506,8 +510,8 @@ public class DocumentTest { Mockito.when(searchServiceApi.validateRequest(Mockito.any(HttpHeaders.class), Mockito.any(HttpServletRequest.class), Mockito.any(ApiUtils.Action.class), Mockito.anyString())) .thenThrow(IllegalArgumentException.class); - ResponseEntityresponse = documentApi.queryWithGetWithPayload(content, request, headers, "index-1", - documentStore); + ResponseEntity response = + documentApi.queryWithGetWithPayload(content, request, headers, "index-1", documentStore); Assert.assertNotNull(response); Assert.assertTrue(HttpStatus.FORBIDDEN.value() == response.getStatusCodeValue()); } @@ -526,8 +530,8 @@ public class DocumentTest { Mockito.when(searchServiceApi.validateRequest(Mockito.any(HttpHeaders.class), Mockito.any(HttpServletRequest.class), Mockito.any(ApiUtils.Action.class), Mockito.anyString())) .thenReturn(false); - ResponseEntityresponse = documentApi.queryWithGetWithPayload(content, request, headers, "index-1", - documentStore); + ResponseEntity response = + documentApi.queryWithGetWithPayload(content, request, headers, "index-1", documentStore); Assert.assertNotNull(response); Assert.assertTrue(HttpStatus.FORBIDDEN.value() == response.getStatusCodeValue()); } @@ -545,8 +549,8 @@ public class DocumentTest { Mockito.when(searchServiceApi.validateRequest(Mockito.any(HttpHeaders.class), Mockito.any(HttpServletRequest.class), Mockito.any(ApiUtils.Action.class), Mockito.anyString())) .thenReturn(false); - ResponseEntityresponse = indexApi.processCreateIndex("document-1", request, headers, "index-1", - documentStore); + ResponseEntity response = + indexApi.processCreateIndex("document-1", request, headers, "index-1", documentStore); Assert.assertNotNull(response); Assert.assertTrue(HttpStatus.FORBIDDEN.value() == response.getStatusCodeValue()); } @@ -564,8 +568,8 @@ public class DocumentTest { Mockito.when(searchServiceApi.validateRequest(Mockito.any(HttpHeaders.class), Mockito.any(HttpServletRequest.class), Mockito.any(ApiUtils.Action.class), Mockito.anyString())) .thenThrow(IllegalArgumentException.class); - ResponseEntityresponse = indexApi.processCreateIndex("document-1", request, headers, "index-1", - documentStore); + ResponseEntity response = + indexApi.processCreateIndex("document-1", request, headers, "index-1", documentStore); Assert.assertNotNull(response); Assert.assertTrue(HttpStatus.FORBIDDEN.value() == response.getStatusCodeValue()); } @@ -574,7 +578,7 @@ public class DocumentTest { public void testCreateProcessIndex_IndexApi_NullDocument() throws Exception { String transactionId = "transactionId-1"; String remoteAddr = "http://127.0.0.1"; - String documentSchema= null; + String documentSchema = null; // Mockito.when(headers.getRequestHeaders()).thenReturn(multivaluedMap);; Mockito.when(multivaluedMap.getFirst(Mockito.anyString())).thenReturn(transactionId); Mockito.when(request.getRemoteAddr()).thenReturn(remoteAddr); @@ -584,8 +588,8 @@ public class DocumentTest { Mockito.when(searchServiceApi.validateRequest(Mockito.any(HttpHeaders.class), Mockito.any(HttpServletRequest.class), Mockito.any(ApiUtils.Action.class), Mockito.anyString())) .thenReturn(true); - ResponseEntityresponse = indexApi.processCreateIndex(documentSchema, request, headers, "index-1", - documentStore); + ResponseEntity response = + indexApi.processCreateIndex(documentSchema, request, headers, "index-1", documentStore); Assert.assertNotNull(response); Assert.assertTrue(HttpStatus.INTERNAL_SERVER_ERROR.value() == response.getStatusCodeValue()); } @@ -603,7 +607,7 @@ public class DocumentTest { Mockito.when(searchServiceApi.validateRequest(Mockito.any(HttpHeaders.class), Mockito.any(HttpServletRequest.class), Mockito.any(ApiUtils.Action.class), Mockito.anyString())) .thenReturn(false); - ResponseEntityresponse = indexApi.processDelete("document-1", request, headers, documentStore); + ResponseEntity response = indexApi.processDelete("document-1", request, headers, documentStore); Assert.assertNotNull(response); Assert.assertTrue(HttpStatus.FORBIDDEN.value() == response.getStatusCodeValue()); } @@ -621,7 +625,7 @@ public class DocumentTest { Mockito.when(searchServiceApi.validateRequest(Mockito.any(HttpHeaders.class), Mockito.any(HttpServletRequest.class), Mockito.any(ApiUtils.Action.class), Mockito.anyString())) .thenThrow(IllegalArgumentException.class); - ResponseEntityresponse = indexApi.processDelete("document-1", request, headers, documentStore); + ResponseEntity response = indexApi.processDelete("document-1", request, headers, documentStore); Assert.assertNotNull(response); Assert.assertTrue(HttpStatus.FORBIDDEN.value() == response.getStatusCodeValue()); } @@ -640,7 +644,7 @@ public class DocumentTest { Mockito.any(HttpServletRequest.class), Mockito.any(ApiUtils.Action.class), Mockito.anyString())) .thenReturn(true); Mockito.when(documentStore.deleteIndex(Mockito.anyString())).thenThrow(DocumentStoreOperationException.class); - ResponseEntityresponse = indexApi.processDelete("document-1", request, headers, documentStore); + ResponseEntity response = indexApi.processDelete("document-1", request, headers, documentStore); Assert.assertNotNull(response); Assert.assertTrue(HttpStatus.INTERNAL_SERVER_ERROR.value() == response.getStatusCodeValue()); } diff --git a/src/test/java/org/onap/aai/sa/rest/IndexApiTest.java b/src/test/java/org/onap/aai/sa/rest/IndexApiTest.java index 0f5932b..cd33edd 100644 --- a/src/test/java/org/onap/aai/sa/rest/IndexApiTest.java +++ b/src/test/java/org/onap/aai/sa/rest/IndexApiTest.java @@ -50,238 +50,231 @@ import org.springframework.test.web.servlet.MvcResult; /** - * This suite of tests is intended to exercise the set of REST endpoints - * associated with manipulating Indexes in the document store. + * This suite of tests is intended to exercise the set of REST endpoints associated with manipulating Indexes in the + * document store. */ @RunWith(SpringRunner.class) @SpringBootTest @AutoConfigureMockMvc public class IndexApiTest { - private final String TOP_URI = "/test/indexes/"; - private final String SIMPLE_DOC_SCHEMA_JSON = "src/test/resources/json/simpleDocument.json"; - private final String DYNAMIC_INDEX_PAYLOAD = "src/test/resources/json/dynamicIndex.json"; - - @Autowired - private MockMvc mockMvc; - -// -// @Override -// protected Application configure() { -// -// // Make sure that our test endpoint is on the resource path -// // for Jersey Test. -// return new ResourceConfig(SearchServiceApiHarness.class); -// } -// -// - - @Before - public void setup() throws Exception { - System.setProperty("CONFIG_HOME", System.getProperty("user.dir")+ File.separator + "src/test/resources/json"); - } - - /** - * Tests the dynamic shcema creation flow that send the request - * JSON to the data store without any JSON validation against a schema - * - * @throws IOException - */ - @Test - public void createDynamicIndexTest() throws Exception { - String indexName = "super-ultra-dynamic-mega-index"; - String dynamicUri = TOP_URI + "dynamic/"; - File indexFile = new File(DYNAMIC_INDEX_PAYLOAD); - String indexPayload = TestUtils.readFileToString(indexFile); - -// String result = target(dynamicUri + indexName).request().put(Entity.json(indexPayload), String.class); - MvcResult result = this.mockMvc.perform ( put (dynamicUri + indexName) - .contentType ( MediaType.APPLICATION_JSON ).content ( indexPayload )).andReturn (); - - assertEquals(indexPayload, result.getResponse ().getContentAsString ()); - } - - - /** - * This test validates that the {@link IndexApi} is able to convert {@link OperationResult} - * obects to standard REST {@link ResponseEntity} objects. - * - * @throws FileNotFoundException - * @throws IOException - * @throws DocumentStoreOperationException - */ - @Test - public void responseFromOperationResultTest() throws FileNotFoundException, IOException, DocumentStoreOperationException { - - int SUCCESS_RESULT_CODE = 200; - String SUCCESS_RESULT_STRING = "Everything is ay-okay!"; - int FAILURE_RESULT_CODE = 500; - String FAILURE_CAUSE_STRING = "Something went wrong!"; - - - // Create an instance of the index API endpoint that we will test against. - // We will override the init() method because we don't want it to try to - // connect to a real document store. - IndexApi indexApi = new IndexApi(new SearchServiceApiHarness()) { - @Override - public void init() { /* do nothing */ } - }; -// - //Construct an OperationResult instance with a success code and string. - OperationResult successResult = new OperationResult(); - successResult.setResultCode(SUCCESS_RESULT_CODE); - successResult.setResult(SUCCESS_RESULT_STRING); - - // Convert our success OperationResult to a standard REST Response... - ResponseEntity successResponse = indexApi.responseFromOperationResult(successResult); - - // ...and validate that the Response is correctly populated. - assertEquals("Unexpected result code", SUCCESS_RESULT_CODE, successResponse.getStatusCodeValue ()); - assertTrue("Incorrect result string", ((String) successResponse.getBody ()).equals(SUCCESS_RESULT_STRING)); - - // Construct an OperationResult instance with an error code and failure - // cause. - OperationResult failureResult = new OperationResult(); - failureResult.setResultCode(FAILURE_RESULT_CODE); - failureResult.setFailureCause(FAILURE_CAUSE_STRING); - - // Convert our failure OperationResult to a standard REST Response... - ResponseEntity failureResponse = indexApi.responseFromOperationResult(failureResult); - - // ...and validate that the Response is correctly populated. - assertEquals("Unexpected result code", FAILURE_RESULT_CODE, failureResponse.getStatusCodeValue ()); - assertTrue("Incorrect result string", ((String) failureResponse.getBody ()).equals(FAILURE_CAUSE_STRING)); - } -// -// -// /** -// * This test validates the behaviour of the 'Create Index' POST request -// * endpoint. -// * -// * @throws IOException -// */ - @Test - public void createIndexTest() throws Exception { - - String INDEX_NAME = "test-index"; - String EXPECTED_SETTINGS = - "{\"analysis\": " - + "{\"filter\": " - + "{\"nGram_filter\": { " - + "\"type\": \"nGram\", " - + "\"min_gram\": 1, " - + "\"max_gram\": 50, " - + "\"token_chars\": [ \"letter\", \"digit\", \"punctuation\", \"symbol\" ]}}," - + "\"analyzer\": {" - + "\"nGram_analyzer\": " - + "{\"type\": \"custom\"," - + "\"tokenizer\": \"whitespace\"," - + "\"filter\": [\"lowercase\",\"asciifolding\",\"nGram_filter\"]}," - + "\"whitespace_analyzer\": " - + "{\"type\": \"custom\"," - + "\"tokenizer\": \"whitespace\"," - + "\"filter\": [\"lowercase\",\"asciifolding\"]}}}}"; - String EXPECTED_MAPPINGS = - "{\"dynamic_templates\":[{\"strings\":{\"match_mapping_type\":\"string\",\"match\":\"*\",\"mapping\":{\"type\":\"text\",\"fielddata\":true}}}]" - + ",\"properties\": {" - + "\"serverName\": {" - + "\"type\": \"string\", " - + "\"index\": \"analyzed\", " - + "\"search_analyzer\": \"whitespace\"}, " - + "\"serverComplex\": {" - + "\"type\": \"string\", " - + "\"search_analyzer\": \"whitespace\"}}}"; - - // Read a valid document schema from a json file. - File schemaFile = new File(SIMPLE_DOC_SCHEMA_JSON); - String documentJson = TestUtils.readFileToString(schemaFile); - - // Send a request to our 'create index' endpoint, using the schema - // which we just read. - // String result = target(TOP_URI + INDEX_NAME).request().put(Entity.json(documentJson), String.class); - MvcResult result = this.mockMvc.perform ( put ( TOP_URI + INDEX_NAME ).contentType ( MediaType.APPLICATION_JSON ) - .content ( documentJson) ).andReturn (); - - - // Our stub document store DAO returns the parameters that it was - // passed as the result string, so now we can validate that our - // endpoint invoked it with the correct parameters. - String[] tokenizedResult = result.getResponse ().getContentAsString ().split("@"); - assertTrue("Unexpected Index Name '" + tokenizedResult[0] + "' passed to doc store DAO", - tokenizedResult[0].equals(INDEX_NAME)); - assertTrue("Unexpected settings string '" + tokenizedResult[1] + "' passed to doc store DAO", - tokenizedResult[1].equals(EXPECTED_SETTINGS)); - assertTrue("Unexpected mappings string '" + tokenizedResult[2] + "' passed to doc store DAO", - tokenizedResult[2].equals(EXPECTED_MAPPINGS)); - } -// -// - /** - * This test validates that a 'create index' request with an improperly - * formatted document schema as the payload will result in an - * appropriate error being returned from the endpoint. - */ - @Test - public void createIndexWithMangledSchemaTest() throws Exception { - - String INDEX_NAME = "test-index"; - int BAD_REQUEST_CODE = 400; - - String invalidSchemaString = "this is definitely not json!"; - - // ResponseEntity result = target(TOP_URI + INDEX_NAME).request().put(Entity.json(invalidSchemaString), ResponseEntity.class); - MvcResult result = this.mockMvc.perform ( put ( TOP_URI + INDEX_NAME ).contentType ( MediaType.APPLICATION_JSON ) - .content ( invalidSchemaString) ).andReturn (); - - assertEquals("Invalid document schema should result in a 400 error", - BAD_REQUEST_CODE, result.getResponse ().getStatus ()); - } -// -// - /** - * This test validates the behaviour of the 'Delete Index' end point. - */ - @Test - public void deleteIndexTest() throws Exception { - - String INDEX_NAME = "test-index"; - - // Send a request to the 'delete index' endpoint. - // String result = target(TOP_URI + INDEX_NAME).request().delete(String.class); - - MvcResult result = this.mockMvc.perform ( delete ( TOP_URI + INDEX_NAME ) - .contentType ( MediaType.APPLICATION_JSON ) - .header ( "If-Match", "1" ) - .content ( "Some Json" ) ).andReturn ( ); - - // Validate that the expected parameters were passed to the document - // store DAO. - assertTrue("Unexpected index name '" + result.getResponse ().getContentAsString () + "' passed to doc store DAO", - result.getResponse ().getContentAsString ().equals(INDEX_NAME)); - } -// -// -// /** -// * This test validates that attempting to delete an index which does not -// * exist results in a 404 error. -// */ - @Test - public void deleteIndexDoesNotExistTest() throws Exception { - - int NOT_FOUND_CODE = 404; - - // Send a request to the 'delete index' endpoint, specifying a - // non-existent index. - // ResponseEntity result = target(TOP_URI + StubEsController.DOES_NOT_EXIST_INDEX).request().delete(ResponseEntity.class); - - MvcResult result = this.mockMvc.perform ( delete ( TOP_URI + StubEsController.DOES_NOT_EXIST_INDEX ) - .contentType ( MediaType.APPLICATION_JSON ) - .header ( "If-Match", "1" ) - .content ( "Some Json" ) ).andReturn ( ); - - - // Validate that a 404 error code is returned from the end point. - assertEquals("Deleting an index which does not exist should result in a 404 error", - NOT_FOUND_CODE, result.getResponse ().getStatus ()); - } + private final String TOP_URI = "/test/indexes/"; + private final String SIMPLE_DOC_SCHEMA_JSON = "src/test/resources/json/simpleDocument.json"; + private final String DYNAMIC_INDEX_PAYLOAD = "src/test/resources/json/dynamicIndex.json"; + + @Autowired + private MockMvc mockMvc; + + // + // @Override + // protected Application configure() { + // + // // Make sure that our test endpoint is on the resource path + // // for Jersey Test. + // return new ResourceConfig(SearchServiceApiHarness.class); + // } + // + // + + @Before + public void setup() throws Exception { + System.setProperty("CONFIG_HOME", System.getProperty("user.dir") + File.separator + "src/test/resources/json"); + } + + /** + * Tests the dynamic shcema creation flow that send the request JSON to the data store without any JSON validation + * against a schema + * + * @throws IOException + */ + @Test + public void createDynamicIndexTest() throws Exception { + String indexName = "super-ultra-dynamic-mega-index"; + String dynamicUri = TOP_URI + "dynamic/"; + File indexFile = new File(DYNAMIC_INDEX_PAYLOAD); + String indexPayload = TestUtils.readFileToString(indexFile); + + // String result = target(dynamicUri + indexName).request().put(Entity.json(indexPayload), String.class); + MvcResult result = this.mockMvc + .perform(put(dynamicUri + indexName).contentType(MediaType.APPLICATION_JSON).content(indexPayload)) + .andReturn(); + + assertEquals(indexPayload, result.getResponse().getContentAsString()); + } + + + /** + * This test validates that the {@link IndexApi} is able to convert {@link OperationResult} obects to standard REST + * {@link ResponseEntity} objects. + * + * @throws FileNotFoundException + * @throws IOException + * @throws DocumentStoreOperationException + */ + @Test + public void responseFromOperationResultTest() + throws FileNotFoundException, IOException, DocumentStoreOperationException { + + int SUCCESS_RESULT_CODE = 200; + String SUCCESS_RESULT_STRING = "Everything is ay-okay!"; + int FAILURE_RESULT_CODE = 500; + String FAILURE_CAUSE_STRING = "Something went wrong!"; + + + // Create an instance of the index API endpoint that we will test against. + // We will override the init() method because we don't want it to try to + // connect to a real document store. + IndexApi indexApi = new IndexApi(new SearchServiceApiHarness()) { + @Override + public void init() { /* do nothing */ } + }; + // + // Construct an OperationResult instance with a success code and string. + OperationResult successResult = new OperationResult(); + successResult.setResultCode(SUCCESS_RESULT_CODE); + successResult.setResult(SUCCESS_RESULT_STRING); + + // Convert our success OperationResult to a standard REST Response... + ResponseEntity successResponse = indexApi.responseFromOperationResult(successResult); + + // ...and validate that the Response is correctly populated. + assertEquals("Unexpected result code", SUCCESS_RESULT_CODE, successResponse.getStatusCodeValue()); + assertTrue("Incorrect result string", ((String) successResponse.getBody()).equals(SUCCESS_RESULT_STRING)); + + // Construct an OperationResult instance with an error code and failure + // cause. + OperationResult failureResult = new OperationResult(); + failureResult.setResultCode(FAILURE_RESULT_CODE); + failureResult.setFailureCause(FAILURE_CAUSE_STRING); + + // Convert our failure OperationResult to a standard REST Response... + ResponseEntity failureResponse = indexApi.responseFromOperationResult(failureResult); + + // ...and validate that the Response is correctly populated. + assertEquals("Unexpected result code", FAILURE_RESULT_CODE, failureResponse.getStatusCodeValue()); + assertTrue("Incorrect result string", ((String) failureResponse.getBody()).equals(FAILURE_CAUSE_STRING)); + } + + // + // + // /** + // * This test validates the behaviour of the 'Create Index' POST request + // * endpoint. + // * + // * @throws IOException + // */ + @Test + public void createIndexTest() throws Exception { + + String INDEX_NAME = "test-index"; + String EXPECTED_SETTINGS = "{\"analysis\": " + "{\"filter\": " + "{\"nGram_filter\": { " + + "\"type\": \"nGram\", " + "\"min_gram\": 1, " + "\"max_gram\": 50, " + + "\"token_chars\": [ \"letter\", \"digit\", \"punctuation\", \"symbol\" ]}}," + "\"analyzer\": {" + + "\"nGram_analyzer\": " + "{\"type\": \"custom\"," + "\"tokenizer\": \"whitespace\"," + + "\"filter\": [\"lowercase\",\"asciifolding\",\"nGram_filter\"]}," + "\"whitespace_analyzer\": " + + "{\"type\": \"custom\"," + "\"tokenizer\": \"whitespace\"," + + "\"filter\": [\"lowercase\",\"asciifolding\"]}}}}"; + String EXPECTED_MAPPINGS = + "{\"dynamic_templates\":[{\"strings\":{\"match_mapping_type\":\"string\",\"match\":\"*\",\"mapping\":{\"type\":\"text\",\"fielddata\":true}}}]" + + ",\"properties\": {" + "\"serverName\": {" + "\"type\": \"string\", " + + "\"index\": \"analyzed\", " + "\"search_analyzer\": \"whitespace\"}, " + + "\"serverComplex\": {" + "\"type\": \"string\", " + "\"search_analyzer\": \"whitespace\"}}}"; + + // Read a valid document schema from a json file. + File schemaFile = new File(SIMPLE_DOC_SCHEMA_JSON); + String documentJson = TestUtils.readFileToString(schemaFile); + + // Send a request to our 'create index' endpoint, using the schema + // which we just read. + // String result = target(TOP_URI + INDEX_NAME).request().put(Entity.json(documentJson), String.class); + MvcResult result = this.mockMvc + .perform(put(TOP_URI + INDEX_NAME).contentType(MediaType.APPLICATION_JSON).content(documentJson)) + .andReturn(); + + + // Our stub document store DAO returns the parameters that it was + // passed as the result string, so now we can validate that our + // endpoint invoked it with the correct parameters. + String[] tokenizedResult = result.getResponse().getContentAsString().split("@"); + assertTrue("Unexpected Index Name '" + tokenizedResult[0] + "' passed to doc store DAO", + tokenizedResult[0].equals(INDEX_NAME)); + assertTrue("Unexpected settings string '" + tokenizedResult[1] + "' passed to doc store DAO", + tokenizedResult[1].equals(EXPECTED_SETTINGS)); + assertTrue("Unexpected mappings string '" + tokenizedResult[2] + "' passed to doc store DAO", + tokenizedResult[2].equals(EXPECTED_MAPPINGS)); + } + + // + // + /** + * This test validates that a 'create index' request with an improperly formatted document schema as the payload + * will result in an appropriate error being returned from the endpoint. + */ + @Test + public void createIndexWithMangledSchemaTest() throws Exception { + + String INDEX_NAME = "test-index"; + int BAD_REQUEST_CODE = 400; + + String invalidSchemaString = "this is definitely not json!"; + + // ResponseEntity result = target(TOP_URI + INDEX_NAME).request().put(Entity.json(invalidSchemaString), + // ResponseEntity.class); + MvcResult result = this.mockMvc + .perform(put(TOP_URI + INDEX_NAME).contentType(MediaType.APPLICATION_JSON).content(invalidSchemaString)) + .andReturn(); + + assertEquals("Invalid document schema should result in a 400 error", BAD_REQUEST_CODE, + result.getResponse().getStatus()); + } + + // + // + /** + * This test validates the behaviour of the 'Delete Index' end point. + */ + @Test + public void deleteIndexTest() throws Exception { + + String INDEX_NAME = "test-index"; + + // Send a request to the 'delete index' endpoint. + // String result = target(TOP_URI + INDEX_NAME).request().delete(String.class); + + MvcResult result = this.mockMvc.perform(delete(TOP_URI + INDEX_NAME).contentType(MediaType.APPLICATION_JSON) + .header("If-Match", "1").content("Some Json")).andReturn(); + + // Validate that the expected parameters were passed to the document + // store DAO. + assertTrue("Unexpected index name '" + result.getResponse().getContentAsString() + "' passed to doc store DAO", + result.getResponse().getContentAsString().equals(INDEX_NAME)); + } + + // + // + // /** + // * This test validates that attempting to delete an index which does not + // * exist results in a 404 error. + // */ + @Test + public void deleteIndexDoesNotExistTest() throws Exception { + + int NOT_FOUND_CODE = 404; + + // Send a request to the 'delete index' endpoint, specifying a + // non-existent index. + // ResponseEntity result = target(TOP_URI + + // StubEsController.DOES_NOT_EXIST_INDEX).request().delete(ResponseEntity.class); + + MvcResult result = + this.mockMvc + .perform(delete(TOP_URI + StubEsController.DOES_NOT_EXIST_INDEX) + .contentType(MediaType.APPLICATION_JSON).header("If-Match", "1").content("Some Json")) + .andReturn(); + + + // Validate that a 404 error code is returned from the end point. + assertEquals("Deleting an index which does not exist should result in a 404 error", NOT_FOUND_CODE, + result.getResponse().getStatus()); + } } diff --git a/src/test/java/org/onap/aai/sa/rest/SearchServiceApiHarness.java b/src/test/java/org/onap/aai/sa/rest/SearchServiceApiHarness.java index 0621cd8..072b090 100644 --- a/src/test/java/org/onap/aai/sa/rest/SearchServiceApiHarness.java +++ b/src/test/java/org/onap/aai/sa/rest/SearchServiceApiHarness.java @@ -20,7 +20,7 @@ */ package org.onap.aai.sa.rest; - import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.http.HttpHeaders; import org.springframework.http.ResponseEntity; @@ -38,172 +38,128 @@ import org.springframework.web.bind.annotation.RestController; public class SearchServiceApiHarness extends SearchServiceApi { - public static final String FAIL_AUTHENTICATION_TRIGGER = "FAIL AUTHENTICATION"; - - private boolean authenticationShouldSucceed = true; - - - /** - * Performs all one-time initialization required for the end point. - */ - @Override - public void init() { - - // Instantiate our Document Store DAO. - documentStore = new StubEsController(); - } - - @Override - @RequestMapping (value="/indexes/dynamic/{index}", - method = RequestMethod.PUT, - consumes = { "application/json"}) - public ResponseEntity processCreateDynamicIndex(@RequestBody String requestBody, - HttpServletRequest request, - @RequestHeader HttpHeaders headers, - @PathVariable("index") String index) { - - return super.processCreateDynamicIndex(requestBody, request, headers, index); - } - - - @Override - @RequestMapping (value="/indexes/{index}", - method = RequestMethod.PUT, - consumes = { "application/json"}) - public ResponseEntity processCreateIndex(@RequestBody String requestBody, - HttpServletRequest request, - @RequestHeader HttpHeaders headers, - @PathVariable("index") String index) { - - return super.processCreateIndex(requestBody, request, headers, index); - } - - @Override - @RequestMapping (value="/indexes/{index}", - method = RequestMethod.DELETE, - consumes = { "application/json"}) - public ResponseEntity processDeleteIndex(HttpServletRequest request, - @RequestHeader HttpHeaders headers, - @PathVariable("index") String index) { - - return super.processDeleteIndex(request, headers, index); - } - - @Override - @RequestMapping (value="/indexes/{index}/documents/{id}", - method = RequestMethod.GET) - public ResponseEntity processGetDocument( - HttpServletRequest request, - HttpServletResponse httpResponse, - @RequestHeader HttpHeaders headers, - @PathVariable("index") String index, - @PathVariable("id") String id) { - - return super.processGetDocument(request, httpResponse, headers, index, id); - } - - @Override - @RequestMapping (value="/indexes/{index}/documents", - method = RequestMethod.POST, - consumes = { "application/json", "application/xml" }) - public ResponseEntity processCreateDocWithoutId(@RequestBody String requestBody, - HttpServletRequest request, - HttpServletResponse httpResponse, - @RequestHeader HttpHeaders headers, - @PathVariable("index") String index) { - - return super.processCreateDocWithoutId(requestBody, request, httpResponse, headers, index); - } - - @Override - @RequestMapping (value="/indexes/{index}/documents/{id}", - method = RequestMethod.PUT, - consumes = { "application/json", "application/xml" }) - public ResponseEntity processUpsertDoc(@RequestBody String requestBody, - HttpServletRequest request, - HttpServletResponse httpResponse, - @RequestHeader HttpHeaders headers, - @PathVariable("index") String index, - @PathVariable("id") String id) { - - return super.processUpsertDoc(requestBody, request, httpResponse, headers, index, id); - } - - @Override - @RequestMapping(value = "/indexes/{index}/documents/{id}", - method = RequestMethod.DELETE, - consumes = { "application/json"}) - public ResponseEntity processDeleteDoc(HttpServletRequest request, - HttpServletResponse httpResponse, - @RequestHeader HttpHeaders headers, - @PathVariable("index") String index, - @PathVariable("id") String id) { - - return super.processDeleteDoc(request, httpResponse, headers, index, id); - } - - @Override - @RequestMapping(value = "/indexes/{index}/query/{queryText}", - method = RequestMethod.GET) - public ResponseEntity processInlineQuery(HttpServletRequest request, - @RequestHeader HttpHeaders headers, - @PathVariable("index") String index, - @PathVariable("queryText") String queryText) { - - return super.processInlineQuery(request, headers, index, queryText); - } - - @Override - @RequestMapping(value = "/indexes/{index}/query", - method = RequestMethod.GET, - consumes = { "application/json"}) - public ResponseEntity processQueryWithGet(@RequestBody String requestBody, - HttpServletRequest request, - @RequestHeader HttpHeaders headers, - @PathVariable("index") String index) { - - return super.processQueryWithGet(requestBody, request, headers, index); - } - - @Override - @RequestMapping(value = "/indexes/{index}/query", - method = RequestMethod.POST, - consumes = { "application/json"}) - public ResponseEntity processQuery(@RequestBody String requestBody, - HttpServletRequest request, - @RequestHeader HttpHeaders headers, - @PathVariable("index") String index) { - - return super.processQuery(requestBody, request, headers, index); - } - - @Override - @RequestMapping(value = "/bulk", - method = RequestMethod.POST, - consumes = { "application/json"}, - produces = { "application/json"}) - public ResponseEntity processBulkRequest(@RequestBody String requestBody, - HttpServletRequest request, - @RequestHeader HttpHeaders headers) { - - // If the operations string contains a special keyword, set the - // harness to fail the authentication validation. - if (requestBody.contains(FAIL_AUTHENTICATION_TRIGGER)) { - authenticationShouldSucceed = false; + public static final String FAIL_AUTHENTICATION_TRIGGER = "FAIL AUTHENTICATION"; + + private boolean authenticationShouldSucceed = true; + + + /** + * Performs all one-time initialization required for the end point. + */ + @Override + public void init() { + + // Instantiate our Document Store DAO. + documentStore = new StubEsController(); + } + + @Override + @RequestMapping(value = "/indexes/dynamic/{index}", method = RequestMethod.PUT, consumes = {"application/json"}) + public ResponseEntity processCreateDynamicIndex(@RequestBody String requestBody, HttpServletRequest request, + @RequestHeader HttpHeaders headers, @PathVariable("index") String index) { + + return super.processCreateDynamicIndex(requestBody, request, headers, index); } - // Just pass the request up to the parent, since that is the code - // that we really want to test. - //return super.processPost(operations, request, headers, index); - return super.processBulkRequest(requestBody, request, headers); - } - @Override - protected boolean validateRequest(HttpHeaders headers, - HttpServletRequest req, - ApiUtils.Action action, - String authPolicyFunctionName) throws Exception { + @Override + @RequestMapping(value = "/indexes/{index}", method = RequestMethod.PUT, consumes = {"application/json"}) + public ResponseEntity processCreateIndex(@RequestBody String requestBody, HttpServletRequest request, + @RequestHeader HttpHeaders headers, @PathVariable("index") String index) { + + return super.processCreateIndex(requestBody, request, headers, index); + } + + @Override + @RequestMapping(value = "/indexes/{index}", method = RequestMethod.DELETE, consumes = {"application/json"}) + public ResponseEntity processDeleteIndex(HttpServletRequest request, @RequestHeader HttpHeaders headers, + @PathVariable("index") String index) { + + return super.processDeleteIndex(request, headers, index); + } + + @Override + @RequestMapping(value = "/indexes/{index}/documents/{id}", method = RequestMethod.GET) + public ResponseEntity processGetDocument(HttpServletRequest request, HttpServletResponse httpResponse, + @RequestHeader HttpHeaders headers, @PathVariable("index") String index, @PathVariable("id") String id) { + + return super.processGetDocument(request, httpResponse, headers, index, id); + } + + @Override + @RequestMapping(value = "/indexes/{index}/documents", method = RequestMethod.POST, + consumes = {"application/json", "application/xml"}) + public ResponseEntity processCreateDocWithoutId(@RequestBody String requestBody, HttpServletRequest request, + HttpServletResponse httpResponse, @RequestHeader HttpHeaders headers, @PathVariable("index") String index) { + + return super.processCreateDocWithoutId(requestBody, request, httpResponse, headers, index); + } + + @Override + @RequestMapping(value = "/indexes/{index}/documents/{id}", method = RequestMethod.PUT, + consumes = {"application/json", "application/xml"}) + public ResponseEntity processUpsertDoc(@RequestBody String requestBody, HttpServletRequest request, + HttpServletResponse httpResponse, @RequestHeader HttpHeaders headers, @PathVariable("index") String index, + @PathVariable("id") String id) { - return authenticationShouldSucceed; - } + return super.processUpsertDoc(requestBody, request, httpResponse, headers, index, id); + } + + @Override + @RequestMapping(value = "/indexes/{index}/documents/{id}", method = RequestMethod.DELETE, + consumes = {"application/json"}) + public ResponseEntity processDeleteDoc(HttpServletRequest request, HttpServletResponse httpResponse, + @RequestHeader HttpHeaders headers, @PathVariable("index") String index, @PathVariable("id") String id) { + + return super.processDeleteDoc(request, httpResponse, headers, index, id); + } + + @Override + @RequestMapping(value = "/indexes/{index}/query/{queryText}", method = RequestMethod.GET) + public ResponseEntity processInlineQuery(HttpServletRequest request, @RequestHeader HttpHeaders headers, + @PathVariable("index") String index, @PathVariable("queryText") String queryText) { + + return super.processInlineQuery(request, headers, index, queryText); + } + + @Override + @RequestMapping(value = "/indexes/{index}/query", method = RequestMethod.GET, consumes = {"application/json"}) + public ResponseEntity processQueryWithGet(@RequestBody String requestBody, HttpServletRequest request, + @RequestHeader HttpHeaders headers, @PathVariable("index") String index) { + + return super.processQueryWithGet(requestBody, request, headers, index); + } + + @Override + @RequestMapping(value = "/indexes/{index}/query", method = RequestMethod.POST, consumes = {"application/json"}) + public ResponseEntity processQuery(@RequestBody String requestBody, HttpServletRequest request, + @RequestHeader HttpHeaders headers, @PathVariable("index") String index) { + + return super.processQuery(requestBody, request, headers, index); + } + + @Override + @RequestMapping(value = "/bulk", method = RequestMethod.POST, consumes = {"application/json"}, + produces = {"application/json"}) + public ResponseEntity processBulkRequest(@RequestBody String requestBody, HttpServletRequest request, + @RequestHeader HttpHeaders headers) { + + // If the operations string contains a special keyword, set the + // harness to fail the authentication validation. + if (requestBody.contains(FAIL_AUTHENTICATION_TRIGGER)) { + authenticationShouldSucceed = false; + } + + // Just pass the request up to the parent, since that is the code + // that we really want to test. + // return super.processPost(operations, request, headers, index); + return super.processBulkRequest(requestBody, request, headers); + } + + @Override + protected boolean validateRequest(HttpHeaders headers, HttpServletRequest req, ApiUtils.Action action, + String authPolicyFunctionName) throws Exception { + + return authenticationShouldSucceed; + } } diff --git a/src/test/java/org/onap/aai/sa/rest/StubEsController.java b/src/test/java/org/onap/aai/sa/rest/StubEsController.java index 0472283..14a7534 100644 --- a/src/test/java/org/onap/aai/sa/rest/StubEsController.java +++ b/src/test/java/org/onap/aai/sa/rest/StubEsController.java @@ -36,242 +36,235 @@ import org.onap.aai.sa.searchdbabstraction.entity.SearchOperationResult; import org.onap.aai.sa.searchdbabstraction.util.DocumentSchemaUtil; /** - * This class implements a stubbed version of the document store DAO so - * that we can run unit tests without trying to connect to a real - * document store. + * This class implements a stubbed version of the document store DAO so that we can run unit tests without trying to + * connect to a real document store. */ public class StubEsController implements DocumentStoreInterface { - public static final String DOES_NOT_EXIST_INDEX = "index-does-not-exist"; + public static final String DOES_NOT_EXIST_INDEX = "index-does-not-exist"; - private AnalysisConfiguration analysisConfig = null; + private AnalysisConfiguration analysisConfig = null; - /** - * - */ - //private IndexAPIHarness indexAPIHarness; + /** + * + */ + // private IndexAPIHarness indexAPIHarness; + + StubEsController() { + analysisConfig = new AnalysisConfiguration(); + analysisConfig.init("src/test/resources/json/filter-config.json", + "src/test/resources/json/analysis-config.json"); + } - StubEsController() { - analysisConfig = new AnalysisConfiguration(); - analysisConfig.init("src/test/resources/json/filter-config.json", - "src/test/resources/json/analysis-config.json"); - } + @Override + public OperationResult createIndex(String index, DocumentSchema documentSchema) { - @Override - public OperationResult createIndex(String index, - DocumentSchema documentSchema) { + // Just return an OK result, with the parameters that we were passed + // bundled in the response string. This allows unit tests to validate + // that those parameters match what they expected to be passed. + OperationResult opResult = new OperationResult(); + opResult.setResultCode(200); - // Just return an OK result, with the parameters that we were passed - // bundled in the response string. This allows unit tests to validate - // that those parameters match what they expected to be passed. - OperationResult opResult = new OperationResult(); - opResult.setResultCode(200); + try { + opResult.setResult(index + "@" + analysisConfig.getEsIndexSettings() + "@" + + DocumentSchemaUtil.generateDocumentMappings(documentSchema)); + } catch (IOException e) { + e.printStackTrace(); + } - try { - opResult.setResult(index + "@" + analysisConfig.getEsIndexSettings() + "@" - + DocumentSchemaUtil.generateDocumentMappings(documentSchema)); - } catch (IOException e) { - e.printStackTrace(); - } + return opResult; + } - return opResult; - } + @Override + public OperationResult createDynamicIndex(String index, String dynamicSchema) { + OperationResult opResult = new OperationResult(); + opResult.setResultCode(200); + // Directly return the json as this flow should not edit the json in any way + opResult.setResult(dynamicSchema); + return opResult; + } - @Override - public OperationResult createDynamicIndex(String index, String dynamicSchema) { - OperationResult opResult = new OperationResult(); - opResult.setResultCode(200); - // Directly return the json as this flow should not edit the json in any way - opResult.setResult(dynamicSchema); - return opResult; - } + @Override + public OperationResult deleteIndex(String indexName) throws DocumentStoreOperationException { - @Override - public OperationResult deleteIndex(String indexName) throws DocumentStoreOperationException { + OperationResult opResult = new OperationResult(); - OperationResult opResult = new OperationResult(); + if (indexName.equals(DOES_NOT_EXIST_INDEX)) { + opResult.setResultCode(404); + } else { + opResult.setResultCode(200); + opResult.setResult(indexName); + } - if (indexName.equals(DOES_NOT_EXIST_INDEX)) { - opResult.setResultCode(404); - } else { - opResult.setResultCode(200); - opResult.setResult(indexName); + return opResult; } - return opResult; - } - - @Override - public DocumentOperationResult createDocument(String indexName, - DocumentStoreDataEntity document, - boolean allowImplicitIndexCreation) - throws DocumentStoreOperationException { - - DocumentOperationResult opResult = buildSampleDocumentOperationResult(); - - if (indexName.equals(DOES_NOT_EXIST_INDEX)) { - opResult.setResultCode(404); - } else { - opResult.setResultCode(200); - String id = "dummy"; - if (document.getId() != null) { - id = document.getId(); - } - opResult.setResultVersion("1"); + @Override + public DocumentOperationResult createDocument(String indexName, DocumentStoreDataEntity document, + boolean allowImplicitIndexCreation) throws DocumentStoreOperationException { + + DocumentOperationResult opResult = buildSampleDocumentOperationResult(); + + if (indexName.equals(DOES_NOT_EXIST_INDEX)) { + opResult.setResultCode(404); + } else { + opResult.setResultCode(200); + String id = "dummy"; + if (document.getId() != null) { + id = document.getId(); + } + opResult.setResultVersion("1"); + } + + return opResult; } - return opResult; - } - - @Override - public DocumentOperationResult updateDocument(String indexName, - DocumentStoreDataEntity document, - boolean allowImplicitIndexCreation) - throws DocumentStoreOperationException { - - DocumentOperationResult opResult = buildSampleDocumentOperationResult(); - - if (indexName.equals(DOES_NOT_EXIST_INDEX)) { - opResult.setResultCode(404); - } else { - opResult.setResultCode(200); - String version = "1"; - if (document.getVersion() != null) { - version = String.valueOf(Integer.parseInt(document.getVersion()) + 1); - } - opResult.setResultVersion(version); + @Override + public DocumentOperationResult updateDocument(String indexName, DocumentStoreDataEntity document, + boolean allowImplicitIndexCreation) throws DocumentStoreOperationException { + + DocumentOperationResult opResult = buildSampleDocumentOperationResult(); + + if (indexName.equals(DOES_NOT_EXIST_INDEX)) { + opResult.setResultCode(404); + } else { + opResult.setResultCode(200); + String version = "1"; + if (document.getVersion() != null) { + version = String.valueOf(Integer.parseInt(document.getVersion()) + 1); + } + opResult.setResultVersion(version); + } + + return opResult; } - return opResult; - } - - @Override - public DocumentOperationResult deleteDocument(String indexName, - DocumentStoreDataEntity document) throws DocumentStoreOperationException { - DocumentOperationResult opResult = buildSampleDocumentOperationResult(); - - - if (indexName.equals(DOES_NOT_EXIST_INDEX)) { - opResult.setResultCode(404); - } else { - if (opResult.getDocument() != null) { - opResult.getDocument().setEtag(null); - opResult.getDocument().setUrl(null); - opResult.setResultVersion("1"); - } - opResult.setResultCode(200); - opResult.setResult(indexName + "@" + document.getId()); - opResult.setResultVersion("1"); + @Override + public DocumentOperationResult deleteDocument(String indexName, DocumentStoreDataEntity document) + throws DocumentStoreOperationException { + DocumentOperationResult opResult = buildSampleDocumentOperationResult(); + + + if (indexName.equals(DOES_NOT_EXIST_INDEX)) { + opResult.setResultCode(404); + } else { + if (opResult.getDocument() != null) { + opResult.getDocument().setEtag(null); + opResult.getDocument().setUrl(null); + opResult.setResultVersion("1"); + } + opResult.setResultCode(200); + opResult.setResult(indexName + "@" + document.getId()); + opResult.setResultVersion("1"); + } + + return opResult; } - return opResult; - } - - @Override - public DocumentOperationResult getDocument(String indexName, - DocumentStoreDataEntity document) throws DocumentStoreOperationException { - DocumentOperationResult opResult = buildSampleDocumentOperationResult(); - - if (indexName.equals(DOES_NOT_EXIST_INDEX)) { - opResult.setResultCode(404); - // Adding it to make the tests pass. - opResult.setResultVersion ("1"); - } else { - opResult.setResultCode(200); - // Adding it to make the tests pass. - opResult.setResultVersion ("1"); + @Override + public DocumentOperationResult getDocument(String indexName, DocumentStoreDataEntity document) + throws DocumentStoreOperationException { + DocumentOperationResult opResult = buildSampleDocumentOperationResult(); + + if (indexName.equals(DOES_NOT_EXIST_INDEX)) { + opResult.setResultCode(404); + // Adding it to make the tests pass. + opResult.setResultVersion("1"); + } else { + opResult.setResultCode(200); + // Adding it to make the tests pass. + opResult.setResultVersion("1"); + } + + return opResult; } - return opResult; - } + @Override + public SearchOperationResult search(String indexName, String queryText) throws DocumentStoreOperationException { - @Override - public SearchOperationResult search(String indexName, - String queryText) throws DocumentStoreOperationException { + SearchOperationResult opResult = buildSampleSearchOperationResult(); - SearchOperationResult opResult = buildSampleSearchOperationResult(); + if (indexName.equals(DOES_NOT_EXIST_INDEX)) { + opResult.setResultCode(404); + } else { + opResult.setResultCode(200); + opResult.setResult(indexName + "@" + queryText); + } - if (indexName.equals(DOES_NOT_EXIST_INDEX)) { - opResult.setResultCode(404); - } else { - opResult.setResultCode(200); - opResult.setResult(indexName + "@" + queryText); + return opResult; } - return opResult; - } + @Override + public SearchOperationResult searchWithPayload(String indexName, String query) + throws DocumentStoreOperationException { + SearchOperationResult opResult = buildSampleSearchOperationResult(); - @Override - public SearchOperationResult searchWithPayload(String indexName, - String query) throws DocumentStoreOperationException { - SearchOperationResult opResult = buildSampleSearchOperationResult(); + if (indexName.equals(DOES_NOT_EXIST_INDEX)) { + opResult.setResultCode(404); + } else { + opResult.setResultCode(200); + opResult.setResult(indexName + "@" + query); + } - if (indexName.equals(DOES_NOT_EXIST_INDEX)) { - opResult.setResultCode(404); - } else { - opResult.setResultCode(200); - opResult.setResult(indexName + "@" + query); + return opResult; } - return opResult; - } + @Override + public SearchOperationResult suggestionQueryWithPayload(String indexName, String query) + throws DocumentStoreOperationException { + SearchOperationResult opResult = new SearchOperationResult(); - @Override - public SearchOperationResult suggestionQueryWithPayload(String indexName, String query) - throws DocumentStoreOperationException { - SearchOperationResult opResult = new SearchOperationResult(); + if (indexName.equals(DOES_NOT_EXIST_INDEX)) { + opResult.setResultCode(404); + } else { + opResult.setResultCode(200); + opResult.setResult(indexName + "@" + query); + } - if (indexName.equals(DOES_NOT_EXIST_INDEX)) { - opResult.setResultCode(404); - } else { - opResult.setResultCode(200); - opResult.setResult(indexName + "@" + query); + return opResult; } - return opResult; - } - - @Override - public OperationResult performBulkOperations(BulkRequest[] requests) throws DocumentStoreOperationException { + @Override + public OperationResult performBulkOperations(BulkRequest[] requests) throws DocumentStoreOperationException { - OperationResult opResult = new OperationResult(); - opResult.setResultCode(200); + OperationResult opResult = new OperationResult(); + opResult.setResultCode(200); - return opResult; - } + return opResult; + } - private DocumentOperationResult buildSampleDocumentOperationResult() { - DocumentOperationResult result = new DocumentOperationResult(); - Document doc = new Document(); - doc.setEtag("etag1"); + private DocumentOperationResult buildSampleDocumentOperationResult() { + DocumentOperationResult result = new DocumentOperationResult(); + Document doc = new Document(); + doc.setEtag("etag1"); - doc.setContent(new JSONObject()); - result.setDocument(doc); - return result; - } + doc.setContent(new JSONObject()); + result.setDocument(doc); + return result; + } - private SearchOperationResult buildSampleSearchOperationResult() { - SearchOperationResult result = new SearchOperationResult(); + private SearchOperationResult buildSampleSearchOperationResult() { + SearchOperationResult result = new SearchOperationResult(); - SearchHits searchHits = new SearchHits(); - SearchHit[] searchHitArray = new SearchHit[1]; - SearchHit searchHit = new SearchHit(); - Document doc = new Document(); - doc.setEtag("etag1"); - Map content = new HashMap(); - content.put("key1", "value1"); - doc.setContent(new JSONObject()); - searchHit.setDocument(doc); - searchHitArray[0] = searchHit; + SearchHits searchHits = new SearchHits(); + SearchHit[] searchHitArray = new SearchHit[1]; + SearchHit searchHit = new SearchHit(); + Document doc = new Document(); + doc.setEtag("etag1"); + Map content = new HashMap(); + content.put("key1", "value1"); + doc.setContent(new JSONObject()); + searchHit.setDocument(doc); + searchHitArray[0] = searchHit; - searchHits.setHits(searchHitArray); - searchHits.setTotalHits("1"); - result.setSearchResult(searchHits); + searchHits.setHits(searchHitArray); + searchHits.setTotalHits("1"); + result.setSearchResult(searchHits); - return result; + return result; - } + } -} \ No newline at end of file +} diff --git a/src/test/java/org/onap/aai/sa/rest/TestUtils.java b/src/test/java/org/onap/aai/sa/rest/TestUtils.java index 503e808..e990438 100644 --- a/src/test/java/org/onap/aai/sa/rest/TestUtils.java +++ b/src/test/java/org/onap/aai/sa/rest/TestUtils.java @@ -29,35 +29,34 @@ import java.io.IOException; public class TestUtils { - /** - * This helper method reads the contents of a file into a - * simple string. - * - * @param aFile - The file to be imported. - * - * @return - The file contents expressed as a simple string. - * - * @throws IOException - */ - public static String readFileToString(File aFile) throws IOException { + /** + * This helper method reads the contents of a file into a simple string. + * + * @param aFile - The file to be imported. + * + * @return - The file contents expressed as a simple string. + * + * @throws IOException + */ + public static String readFileToString(File aFile) throws IOException { - BufferedReader br = new BufferedReader(new FileReader(aFile)); - try { - StringBuilder sb = new StringBuilder(); - String line = br.readLine(); + BufferedReader br = new BufferedReader(new FileReader(aFile)); + try { + StringBuilder sb = new StringBuilder(); + String line = br.readLine(); - while (line != null) { - sb.append(line); - line = br.readLine(); - } + while (line != null) { + sb.append(line); + line = br.readLine(); + } - return sb.toString().replaceAll("\\s+", ""); - } finally { - try { - br.close(); - } catch (IOException e) { - fail("Unexpected IOException: " + e.getMessage()); - } + return sb.toString().replaceAll("\\s+", ""); + } finally { + try { + br.close(); + } catch (IOException e) { + fail("Unexpected IOException: " + e.getMessage()); + } + } } - } -} \ No newline at end of file +} diff --git a/src/test/java/org/onap/aai/sa/searchdbabstraction/elasticsearch/config/ElasticSearchConfigTest.java b/src/test/java/org/onap/aai/sa/searchdbabstraction/elasticsearch/config/ElasticSearchConfigTest.java index 8c4de81..b976f17 100644 --- a/src/test/java/org/onap/aai/sa/searchdbabstraction/elasticsearch/config/ElasticSearchConfigTest.java +++ b/src/test/java/org/onap/aai/sa/searchdbabstraction/elasticsearch/config/ElasticSearchConfigTest.java @@ -26,23 +26,24 @@ import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; + public class ElasticSearchConfigTest { @Autowired ElasticSearchConfig elasticSearchConfig; @Before - public void setUp(){ + public void setUp() { Properties prop = new Properties(); prop.put("es.cluster-name", "cluster-1"); prop.put("es.ip-address", "127.0.0.1"); prop.put("es.http-port", "9001"); -// elasticSearchConfig = new ElasticSearchConfig(prop); + // elasticSearchConfig = new ElasticSearchConfig(prop); } @Ignore @Test - public void testAllGetMethods(){ + public void testAllGetMethods() { Assert.assertEquals(elasticSearchConfig.getClusterName(), "cluster-1"); Assert.assertEquals(elasticSearchConfig.getIpAddress(), "127.0.0.1"); Assert.assertEquals(elasticSearchConfig.getHttpPort(), "9001"); diff --git a/src/test/java/org/onap/aai/sa/searchdbabstraction/elasticsearch/dao/AggregationResponseParsingTest.java b/src/test/java/org/onap/aai/sa/searchdbabstraction/elasticsearch/dao/AggregationResponseParsingTest.java index 61e64f5..fbc077d 100644 --- a/src/test/java/org/onap/aai/sa/searchdbabstraction/elasticsearch/dao/AggregationResponseParsingTest.java +++ b/src/test/java/org/onap/aai/sa/searchdbabstraction/elasticsearch/dao/AggregationResponseParsingTest.java @@ -31,69 +31,69 @@ import org.onap.aai.sa.searchdbabstraction.util.AggregationParsingUtil; public class AggregationResponseParsingTest { - @Test - public void testParseAggregationResponse() { - JSONParser parser = new JSONParser(); - JSONObject root; + @Test + public void testParseAggregationResponse() { + JSONParser parser = new JSONParser(); + JSONObject root; - String input = - "{\r\n \"aggregations\": {\r\n \"violations\": {\r\n \"doc_count\": 2,\r\n \"by_Timestamp\": {\r\n \"doc_count_error_upper_bound\": 0,\r\n \"sum_other_doc_count\": 0,\r\n \"buckets\": [\r\n {\r\n \"key\": 7199992,\r\n \"key_as_string\": \"Jan 1 1970 01:59:59\",\r\n \"doc_count\": 2\r\n }\r\n ]\r\n }\r\n }\r\n }\r\n}"; + String input = + "{\r\n \"aggregations\": {\r\n \"violations\": {\r\n \"doc_count\": 2,\r\n \"by_Timestamp\": {\r\n \"doc_count_error_upper_bound\": 0,\r\n \"sum_other_doc_count\": 0,\r\n \"buckets\": [\r\n {\r\n \"key\": 7199992,\r\n \"key_as_string\": \"Jan 1 1970 01:59:59\",\r\n \"doc_count\": 2\r\n }\r\n ]\r\n }\r\n }\r\n }\r\n}"; - try { - root = (JSONObject) parser.parse(input); - JSONObject aggregations = (JSONObject) root.get("aggregations"); - AggregationResult[] results = AggregationParsingUtil.parseAggregationResults(aggregations); - AggregationResults aggs = new AggregationResults(); - ObjectMapper mapper = new ObjectMapper(); - aggs.setAggregations(results); - System.out.println(mapper.setSerializationInclusion(Include.NON_NULL) - .writerWithDefaultPrettyPrinter().writeValueAsString(aggs)); - } catch (Exception e) { - e.printStackTrace(); + try { + root = (JSONObject) parser.parse(input); + JSONObject aggregations = (JSONObject) root.get("aggregations"); + AggregationResult[] results = AggregationParsingUtil.parseAggregationResults(aggregations); + AggregationResults aggs = new AggregationResults(); + ObjectMapper mapper = new ObjectMapper(); + aggs.setAggregations(results); + System.out.println(mapper.setSerializationInclusion(Include.NON_NULL).writerWithDefaultPrettyPrinter() + .writeValueAsString(aggs)); + } catch (Exception e) { + e.printStackTrace(); + } } - } - @Test - public void testParseAggregationResponse2() { - JSONParser parser = new JSONParser(); - JSONObject root; + @Test + public void testParseAggregationResponse2() { + JSONParser parser = new JSONParser(); + JSONObject root; - String input = - "{\r\n \"aggregations\": {\r\n \"entityType\": {\r\n \"doc_count_error_upper_bound\": 0,\r\n \"sum_other_doc_count\": 0,\r\n \"buckets\": [\r\n {\r\n \"key\": \"entity1\",\r\n \"doc_count\": 5,\r\n \"byVersion\": {\r\n \"doc_count_error_upper_bound\": 0,\r\n \"sum_other_doc_count\": 0,\r\n \"buckets\": [\r\n {\r\n \"key\": \"0\",\r\n \"doc_count\": 5\r\n }\r\n ]\r\n }\r\n }\r\n ]\r\n }\r\n }\r\n}"; + String input = + "{\r\n \"aggregations\": {\r\n \"entityType\": {\r\n \"doc_count_error_upper_bound\": 0,\r\n \"sum_other_doc_count\": 0,\r\n \"buckets\": [\r\n {\r\n \"key\": \"entity1\",\r\n \"doc_count\": 5,\r\n \"byVersion\": {\r\n \"doc_count_error_upper_bound\": 0,\r\n \"sum_other_doc_count\": 0,\r\n \"buckets\": [\r\n {\r\n \"key\": \"0\",\r\n \"doc_count\": 5\r\n }\r\n ]\r\n }\r\n }\r\n ]\r\n }\r\n }\r\n}"; - try { - root = (JSONObject) parser.parse(input); - JSONObject aggregations = (JSONObject) root.get("aggregations"); - AggregationResult[] results = AggregationParsingUtil.parseAggregationResults(aggregations); - AggregationResults aggs = new AggregationResults(); - ObjectMapper mapper = new ObjectMapper(); - aggs.setAggregations(results); - System.out.println(mapper.setSerializationInclusion(Include.NON_NULL) - .writerWithDefaultPrettyPrinter().writeValueAsString(aggs)); - } catch (Exception e) { - e.printStackTrace(); + try { + root = (JSONObject) parser.parse(input); + JSONObject aggregations = (JSONObject) root.get("aggregations"); + AggregationResult[] results = AggregationParsingUtil.parseAggregationResults(aggregations); + AggregationResults aggs = new AggregationResults(); + ObjectMapper mapper = new ObjectMapper(); + aggs.setAggregations(results); + System.out.println(mapper.setSerializationInclusion(Include.NON_NULL).writerWithDefaultPrettyPrinter() + .writeValueAsString(aggs)); + } catch (Exception e) { + e.printStackTrace(); + } } - } - @Test - public void testParseAggregationResponse3() { - JSONParser parser = new JSONParser(); - JSONObject root; + @Test + public void testParseAggregationResponse3() { + JSONParser parser = new JSONParser(); + JSONObject root; - String input = - "{\r\n \"aggregations\": {\r\n \"validateTimes\": {\r\n \"buckets\": [\r\n {\r\n \"key\": \"Jan 10 2017 21:6:6-Jan 24 2017 13:43:5\",\r\n \"from\": 1484082366000,\r\n \"from_as_string\": \"Jan 10 2017 21:6:6\",\r\n \"to\": 1485265385000,\r\n \"to_as_string\": \"Jan 24 2017 13:43:5\",\r\n \"doc_count\": 95\r\n },\r\n {\r\n \"key\": \"Feb 3 2017 18:27:39-*\",\r\n \"from\": 1486146459000,\r\n \"from_as_string\": \"Feb 3 2017 18:27:39\",\r\n \"doc_count\": 2\r\n }\r\n ]\r\n }\r\n }\r\n}"; + String input = + "{\r\n \"aggregations\": {\r\n \"validateTimes\": {\r\n \"buckets\": [\r\n {\r\n \"key\": \"Jan 10 2017 21:6:6-Jan 24 2017 13:43:5\",\r\n \"from\": 1484082366000,\r\n \"from_as_string\": \"Jan 10 2017 21:6:6\",\r\n \"to\": 1485265385000,\r\n \"to_as_string\": \"Jan 24 2017 13:43:5\",\r\n \"doc_count\": 95\r\n },\r\n {\r\n \"key\": \"Feb 3 2017 18:27:39-*\",\r\n \"from\": 1486146459000,\r\n \"from_as_string\": \"Feb 3 2017 18:27:39\",\r\n \"doc_count\": 2\r\n }\r\n ]\r\n }\r\n }\r\n}"; - try { - root = (JSONObject) parser.parse(input); - JSONObject aggregations = (JSONObject) root.get("aggregations"); - AggregationResult[] results = AggregationParsingUtil.parseAggregationResults(aggregations); - AggregationResults aggs = new AggregationResults(); - ObjectMapper mapper = new ObjectMapper(); - aggs.setAggregations(results); - System.out.println(mapper.setSerializationInclusion(Include.NON_NULL) - .writerWithDefaultPrettyPrinter().writeValueAsString(aggs)); - } catch (Exception e) { - e.printStackTrace(); + try { + root = (JSONObject) parser.parse(input); + JSONObject aggregations = (JSONObject) root.get("aggregations"); + AggregationResult[] results = AggregationParsingUtil.parseAggregationResults(aggregations); + AggregationResults aggs = new AggregationResults(); + ObjectMapper mapper = new ObjectMapper(); + aggs.setAggregations(results); + System.out.println(mapper.setSerializationInclusion(Include.NON_NULL).writerWithDefaultPrettyPrinter() + .writeValueAsString(aggs)); + } catch (Exception e) { + e.printStackTrace(); + } } - } } diff --git a/src/test/java/org/onap/aai/sa/searchdbabstraction/elasticsearch/dao/ElasticSearchResultItemTest.java b/src/test/java/org/onap/aai/sa/searchdbabstraction/elasticsearch/dao/ElasticSearchResultItemTest.java index 89e75cd..43203c9 100644 --- a/src/test/java/org/onap/aai/sa/searchdbabstraction/elasticsearch/dao/ElasticSearchResultItemTest.java +++ b/src/test/java/org/onap/aai/sa/searchdbabstraction/elasticsearch/dao/ElasticSearchResultItemTest.java @@ -26,7 +26,7 @@ import org.junit.Test; public class ElasticSearchResultItemTest { @Test - public void testAllMethods(){ + public void testAllMethods() { ElasticSearchShardStatus shardStatus = new ElasticSearchShardStatus(); shardStatus.setTotal(10); shardStatus.setSuccessful(0); @@ -51,7 +51,7 @@ public class ElasticSearchResultItemTest { error.setAdditionalProperties("name-1", "value-1"); Assert.assertNotNull(error.getAdditionalProperties()); - //Create Status + // Create Status ElasticSearchResultItem resultItem1 = new ElasticSearchResultItem(); resultItem1.setCreate(getStatus(shardStatus, error)); Assert.assertNotNull(resultItem1.getCreate()); @@ -60,7 +60,7 @@ public class ElasticSearchResultItemTest { Assert.assertTrue(resultItem1.toString().contains("create")); Assert.assertNotNull(resultItem1.toJson()); - //Index Status + // Index Status ElasticSearchResultItem resultItem2 = new ElasticSearchResultItem(); resultItem2.setIndex(getStatus(shardStatus, error)); Assert.assertNotNull(resultItem2.getIndex()); @@ -69,7 +69,7 @@ public class ElasticSearchResultItemTest { Assert.assertTrue(resultItem2.toString().contains("index")); Assert.assertNotNull(resultItem2.toJson()); - //Delete Status + // Delete Status ElasticSearchResultItem resultItem3 = new ElasticSearchResultItem(); resultItem3.setDelete(getStatus(shardStatus, error)); Assert.assertNotNull(resultItem3.getDelete()); @@ -78,12 +78,12 @@ public class ElasticSearchResultItemTest { Assert.assertTrue(resultItem3.toString().contains("delete")); Assert.assertNotNull(resultItem3.toJson()); - //Unknown Status + // Unknown Status ElasticSearchResultItem resultItem4 = new ElasticSearchResultItem(); Assert.assertEquals(resultItem4.operationType(), "unknown"); Assert.assertNull(resultItem4.operationStatus()); - //ElasticSearchBulkOperationResult + // ElasticSearchBulkOperationResult ElasticSearchResultItem[] resultItems = {resultItem1, resultItem2, resultItem3}; ElasticSearchBulkOperationResult result = new ElasticSearchBulkOperationResult(); result.setErrors(true); diff --git a/src/test/java/org/onap/aai/sa/searchdbabstraction/searchapi/AggregationStatementTest.java b/src/test/java/org/onap/aai/sa/searchdbabstraction/searchapi/AggregationStatementTest.java index 495a456..bff0f4f 100644 --- a/src/test/java/org/onap/aai/sa/searchdbabstraction/searchapi/AggregationStatementTest.java +++ b/src/test/java/org/onap/aai/sa/searchdbabstraction/searchapi/AggregationStatementTest.java @@ -28,116 +28,127 @@ import org.junit.Test; public class AggregationStatementTest { - private static ObjectMapper mapper = new ObjectMapper(); + private static ObjectMapper mapper = new ObjectMapper(); - @Test - public void testGroupBy() { - String input = "{\r\n \"group-by\": {\r\n \"field\": \"entityType\"\r\n }\r\n }"; + @Test + public void testGroupBy() { + String input = "{\r\n \"group-by\": {\r\n \"field\": \"entityType\"\r\n }\r\n }"; - String expected = "{\"terms\": {\"field\": \"entityType\"}}"; + String expected = "{\"terms\": {\"field\": \"entityType\"}}"; + + AggregationStatement actual; + try { + actual = mapper.readValue(input, AggregationStatement.class); + assertEquals(expected, actual.toElasticSearch()); + } catch (Exception e) { + fail("Exception occurred: " + e.getMessage()); + } - AggregationStatement actual; - try { - actual = mapper.readValue(input, AggregationStatement.class); - assertEquals(expected, actual.toElasticSearch()); - } catch (Exception e) { - fail("Exception occurred: " + e.getMessage()); } - } + @Test + public void testDateRange() { + String input = + "{\r\n \"date-range\": {\r\n \"field\": \"mydate\",\r\n \"ranges\": [\r\n {\r\n \"from\": \"2016-12-19T00:00:00.738-05:00\",\r\n \"to\": \"2016-12-23T23:59:59.738-05:00\"\r\n }\r\n ],\r\n \"format\": \"MM-yyy\",\r\n \"size\": \"5\"\r\n }\r\n}"; - @Test - public void testDateRange() { - String input = "{\r\n \"date-range\": {\r\n \"field\": \"mydate\",\r\n \"ranges\": [\r\n {\r\n \"from\": \"2016-12-19T00:00:00.738-05:00\",\r\n \"to\": \"2016-12-23T23:59:59.738-05:00\"\r\n }\r\n ],\r\n \"format\": \"MM-yyy\",\r\n \"size\": \"5\"\r\n }\r\n}"; + String expected = + "{\"date_range\": {\"field\": \"mydate\", \"format\": \"MM-yyy\", \"ranges\": [{\"from\": \"2016-12-19T00:00:00.738-05:00\", \"to\": \"2016-12-23T23:59:59.738-05:00\"}], \"size\": 5}}"; - String expected = "{\"date_range\": {\"field\": \"mydate\", \"format\": \"MM-yyy\", \"ranges\": [{\"from\": \"2016-12-19T00:00:00.738-05:00\", \"to\": \"2016-12-23T23:59:59.738-05:00\"}], \"size\": 5}}"; + AggregationStatement actual; + try { + actual = mapper.readValue(input, AggregationStatement.class); + assertEquals(expected, actual.toElasticSearch()); + } catch (Exception e) { + fail("Exception occurred: " + e.getMessage()); + } - AggregationStatement actual; - try { - actual = mapper.readValue(input, AggregationStatement.class); - assertEquals(expected, actual.toElasticSearch()); - } catch (Exception e) { - fail("Exception occurred: " + e.getMessage()); } - } + @Test + public void testDateHistogram() { + String input = + "{\r\n \"date-histogram\": {\r\n \"field\": \"mydate\",\r\n \"interval\": \"day\"\r\n }\r\n}"; - @Test - public void testDateHistogram() { - String input = "{\r\n \"date-histogram\": {\r\n \"field\": \"mydate\",\r\n \"interval\": \"day\"\r\n }\r\n}"; + String expected = "{\"date_histogram\": {\"field\": \"mydate\", \"interval\": \"day\"}}"; - String expected = "{\"date_histogram\": {\"field\": \"mydate\", \"interval\": \"day\"}}"; + AggregationStatement actual; + try { + actual = mapper.readValue(input, AggregationStatement.class); + assertEquals(expected, actual.toElasticSearch()); + } catch (Exception e) { + fail("Exception occurred: " + e.getMessage()); + } - AggregationStatement actual; - try { - actual = mapper.readValue(input, AggregationStatement.class); - assertEquals(expected, actual.toElasticSearch()); - } catch (Exception e) { - fail("Exception occurred: " + e.getMessage()); } - } - - @Test - public void testSubAggregation1() { - String input = "{\r\n \"group-by\": {\r\n \"field\": \"severity\"\r\n },\r\n \"sub-aggregations\": [\r\n {\r\n \"name\": \"byType\",\r\n \"aggregation\": {\r\n \"group-by\": {\r\n \"field\": \"entityType\"\r\n }\r\n }\r\n }\r\n ]\r\n}"; - String expected = "{\"terms\": {\"field\": \"severity\"}, \"aggs\": {\"byType\": {\"terms\": {\"field\": \"entityType\"}}}}"; + @Test + public void testSubAggregation1() { + String input = + "{\r\n \"group-by\": {\r\n \"field\": \"severity\"\r\n },\r\n \"sub-aggregations\": [\r\n {\r\n \"name\": \"byType\",\r\n \"aggregation\": {\r\n \"group-by\": {\r\n \"field\": \"entityType\"\r\n }\r\n }\r\n }\r\n ]\r\n}"; + String expected = + "{\"terms\": {\"field\": \"severity\"}, \"aggs\": {\"byType\": {\"terms\": {\"field\": \"entityType\"}}}}"; + + AggregationStatement actual; + try { + actual = mapper.readValue(input, AggregationStatement.class); + assertEquals(expected, actual.toElasticSearch()); + } catch (Exception e) { + fail("Exception occurred: " + e.getMessage()); + } - AggregationStatement actual; - try { - actual = mapper.readValue(input, AggregationStatement.class); - assertEquals(expected, actual.toElasticSearch()); - } catch (Exception e) { - fail("Exception occurred: " + e.getMessage()); } - } - - @Test - public void testSubAggregation2() { - String input = "{\r\n \"group-by\": {\r\n \"field\": \"severity\"\r\n },\r\n \"sub-aggregations\": [\r\n {\r\n \"name\": \"byType\",\r\n \"aggregation\": {\r\n \"group-by\": {\r\n \"field\": \"violationType\"\r\n }\r\n }\r\n },\r\n {\r\n \"name\": \"byRule\",\r\n \"aggregation\": {\r\n \"group-by\": {\r\n \"field\": \"validationRule\"\r\n }\r\n }\r\n }\r\n ]\r\n}"; - String expected = "{\"terms\": {\"field\": \"severity\"}, \"aggs\": {\"byType\": {\"terms\": {\"field\": \"violationType\"}},\"byRule\": {\"terms\": {\"field\": \"validationRule\"}}}}"; + @Test + public void testSubAggregation2() { + String input = + "{\r\n \"group-by\": {\r\n \"field\": \"severity\"\r\n },\r\n \"sub-aggregations\": [\r\n {\r\n \"name\": \"byType\",\r\n \"aggregation\": {\r\n \"group-by\": {\r\n \"field\": \"violationType\"\r\n }\r\n }\r\n },\r\n {\r\n \"name\": \"byRule\",\r\n \"aggregation\": {\r\n \"group-by\": {\r\n \"field\": \"validationRule\"\r\n }\r\n }\r\n }\r\n ]\r\n}"; + String expected = + "{\"terms\": {\"field\": \"severity\"}, \"aggs\": {\"byType\": {\"terms\": {\"field\": \"violationType\"}},\"byRule\": {\"terms\": {\"field\": \"validationRule\"}}}}"; + + AggregationStatement actual; + try { + actual = mapper.readValue(input, AggregationStatement.class); + assertEquals(expected, actual.toElasticSearch()); + } catch (Exception e) { + fail("Exception occurred: " + e.getMessage()); + } - AggregationStatement actual; - try { - actual = mapper.readValue(input, AggregationStatement.class); - assertEquals(expected, actual.toElasticSearch()); - } catch (Exception e) { - fail("Exception occurred: " + e.getMessage()); } - } + @Test + public void testNestedAggregation1() { + String input = + "{\r\n \"nested\": [{\r\n \"name\": \"by_severity\",\r\n \"aggregation\": {\r\n \"group-by\": {\r\n \"field\": \"violations.severity\"\r\n }\r\n }\r\n }]\r\n}"; + String expected = + "{\"nested\": {\"path\": \"violations\"}, \"aggs\": {\"by_severity\": {\"terms\": {\"field\": \"violations.severity\"}}}}"; - @Test - public void testNestedAggregation1() { - String input = "{\r\n \"nested\": [{\r\n \"name\": \"by_severity\",\r\n \"aggregation\": {\r\n \"group-by\": {\r\n \"field\": \"violations.severity\"\r\n }\r\n }\r\n }]\r\n}"; - String expected = "{\"nested\": {\"path\": \"violations\"}, \"aggs\": {\"by_severity\": {\"terms\": {\"field\": \"violations.severity\"}}}}"; + AggregationStatement actual; + try { + actual = mapper.readValue(input, AggregationStatement.class); + assertEquals(expected, actual.toElasticSearch()); + } catch (Exception e) { + fail("Exception occurred: " + e.getMessage()); + } - AggregationStatement actual; - try { - actual = mapper.readValue(input, AggregationStatement.class); - assertEquals(expected, actual.toElasticSearch()); - } catch (Exception e) { - fail("Exception occurred: " + e.getMessage()); } - } + @Test + public void testNestedAggregation2() { + String input = + "{\r\n \"nested\": [\r\n {\r\n \"name\": \"by_severity\",\r\n \"aggregation\": {\r\n \"group-by\": {\r\n \"field\": \"violations.severity\"\r\n }\r\n }\r\n },\r\n {\r\n \"name\": \"by_type\",\r\n \"aggregation\": {\r\n \"group-by\": {\r\n \"field\": \"violations.violationType\"\r\n }\r\n }\r\n }\r\n ]\r\n}"; + String expected = + "{\"nested\": {\"path\": \"violations\"}, \"aggs\": {\"by_severity\": {\"terms\": {\"field\": \"violations.severity\"}},\"by_type\": {\"terms\": {\"field\": \"violations.violationType\"}}}}"; + + AggregationStatement actual; + try { + actual = mapper.readValue(input, AggregationStatement.class); + assertEquals(expected, actual.toElasticSearch()); + } catch (Exception e) { + fail("Exception occurred: " + e.getMessage()); + } - @Test - public void testNestedAggregation2() { - String input = "{\r\n \"nested\": [\r\n {\r\n \"name\": \"by_severity\",\r\n \"aggregation\": {\r\n \"group-by\": {\r\n \"field\": \"violations.severity\"\r\n }\r\n }\r\n },\r\n {\r\n \"name\": \"by_type\",\r\n \"aggregation\": {\r\n \"group-by\": {\r\n \"field\": \"violations.violationType\"\r\n }\r\n }\r\n }\r\n ]\r\n}"; - String expected = "{\"nested\": {\"path\": \"violations\"}, \"aggs\": {\"by_severity\": {\"terms\": {\"field\": \"violations.severity\"}},\"by_type\": {\"terms\": {\"field\": \"violations.violationType\"}}}}"; - - AggregationStatement actual; - try { - actual = mapper.readValue(input, AggregationStatement.class); - assertEquals(expected, actual.toElasticSearch()); - } catch (Exception e) { - fail("Exception occurred: " + e.getMessage()); } - } - } diff --git a/src/test/java/org/onap/aai/sa/searchdbabstraction/searchapi/AggregationTest.java b/src/test/java/org/onap/aai/sa/searchdbabstraction/searchapi/AggregationTest.java index d85e075..12b18d1 100644 --- a/src/test/java/org/onap/aai/sa/searchdbabstraction/searchapi/AggregationTest.java +++ b/src/test/java/org/onap/aai/sa/searchdbabstraction/searchapi/AggregationTest.java @@ -27,22 +27,25 @@ import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; public class AggregationTest { - private static ObjectMapper mapper = new ObjectMapper(); -// - @Test - public void test() { - String input = "{\r\n \"name\": \"byDate\",\r\n \"aggregation\": {\r\n \"date-range\": {\r\n \"field\": \"mydate\",\r\n \"ranges\": [\r\n {\r\n \"from\": \"2016-12-19T00:00:00.738-05:00\",\r\n \"to\": \"2016-12-23T23:59:59.738-05:00\"\r\n }\r\n ]\r\n },\r\n \"sub-aggregations\": [{\r\n \"name\": \"byTerm\",\r\n \"aggregation\": {\r\n \"group-by\": {\r\n \"field\": \"myterm\"\r\n }\r\n }\r\n }]\r\n }\r\n}"; - - String expected = "\"byDate\": {\"date_range\": {\"field\": \"mydate\", \"ranges\": [{\"from\": \"2016-12-19T00:00:00.738-05:00\", \"to\": \"2016-12-23T23:59:59.738-05:00\"}]}, \"aggs\": {\"byTerm\": {\"terms\": {\"field\": \"myterm\"}}}}"; - - Aggregation actual; - try { - actual = mapper.readValue(input, Aggregation.class); - assertEquals(expected, actual.toElasticSearch()); - } catch (Exception e) { - fail("Exception occurred: " + e.getMessage()); - } + private static ObjectMapper mapper = new ObjectMapper(); + + // + @Test + public void test() { + String input = + "{\r\n \"name\": \"byDate\",\r\n \"aggregation\": {\r\n \"date-range\": {\r\n \"field\": \"mydate\",\r\n \"ranges\": [\r\n {\r\n \"from\": \"2016-12-19T00:00:00.738-05:00\",\r\n \"to\": \"2016-12-23T23:59:59.738-05:00\"\r\n }\r\n ]\r\n },\r\n \"sub-aggregations\": [{\r\n \"name\": \"byTerm\",\r\n \"aggregation\": {\r\n \"group-by\": {\r\n \"field\": \"myterm\"\r\n }\r\n }\r\n }]\r\n }\r\n}"; + + String expected = + "\"byDate\": {\"date_range\": {\"field\": \"mydate\", \"ranges\": [{\"from\": \"2016-12-19T00:00:00.738-05:00\", \"to\": \"2016-12-23T23:59:59.738-05:00\"}]}, \"aggs\": {\"byTerm\": {\"terms\": {\"field\": \"myterm\"}}}}"; - } + Aggregation actual; + try { + actual = mapper.readValue(input, Aggregation.class); + assertEquals(expected, actual.toElasticSearch()); + } catch (Exception e) { + fail("Exception occurred: " + e.getMessage()); + } + + } } diff --git a/src/test/java/org/onap/aai/sa/searchdbabstraction/searchapi/DateHistogramAggregationTest.java b/src/test/java/org/onap/aai/sa/searchdbabstraction/searchapi/DateHistogramAggregationTest.java index 6a3ecf7..005cb76 100644 --- a/src/test/java/org/onap/aai/sa/searchdbabstraction/searchapi/DateHistogramAggregationTest.java +++ b/src/test/java/org/onap/aai/sa/searchdbabstraction/searchapi/DateHistogramAggregationTest.java @@ -27,57 +27,52 @@ import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; public class DateHistogramAggregationTest { - ObjectMapper mapper = new ObjectMapper(); + ObjectMapper mapper = new ObjectMapper(); - @Test - public void testFullSet() { - String input = - "{\r\n \"field\": \"mydate\",\r\n \"interval\": \"day\",\r\n \"time-zone\": \"-01:00\"\r\n}"; + @Test + public void testFullSet() { + String input = "{\r\n \"field\": \"mydate\",\r\n \"interval\": \"day\",\r\n \"time-zone\": \"-01:00\"\r\n}"; - String expected = - "\"date_histogram\": {\"field\": \"mydate\", \"interval\": \"day\", \"time_zone\": \"-01:00\"}"; + String expected = + "\"date_histogram\": {\"field\": \"mydate\", \"interval\": \"day\", \"time_zone\": \"-01:00\"}"; - DateHistogramAggregation actual; - try { - actual = mapper.readValue(input, DateHistogramAggregation.class); - assertEquals(expected, actual.toElasticSearch()); - } catch (Exception e) { - fail("Exception occurred: " + e.getMessage()); + DateHistogramAggregation actual; + try { + actual = mapper.readValue(input, DateHistogramAggregation.class); + assertEquals(expected, actual.toElasticSearch()); + } catch (Exception e) { + fail("Exception occurred: " + e.getMessage()); + } } - } - @Test - public void test2() { - String input = - "{\r\n \"field\": \"mydate\",\r\n \"interval\": \"day\"\r\n}"; + @Test + public void test2() { + String input = "{\r\n \"field\": \"mydate\",\r\n \"interval\": \"day\"\r\n}"; - String expected = - "\"date_histogram\": {\"field\": \"mydate\", \"interval\": \"day\"}"; + String expected = "\"date_histogram\": {\"field\": \"mydate\", \"interval\": \"day\"}"; - DateHistogramAggregation actual; - try { - actual = mapper.readValue(input, DateHistogramAggregation.class); - assertEquals(expected, actual.toElasticSearch()); - } catch (Exception e) { - fail("Exception occurred: " + e.getMessage()); + DateHistogramAggregation actual; + try { + actual = mapper.readValue(input, DateHistogramAggregation.class); + assertEquals(expected, actual.toElasticSearch()); + } catch (Exception e) { + fail("Exception occurred: " + e.getMessage()); + } } - } - @Test - public void test3() { - String input = - "{\r\n \"field\": \"mydate\"\r\n}"; + @Test + public void test3() { + String input = "{\r\n \"field\": \"mydate\"\r\n}"; - String expected = - "\"date_histogram\": {\"field\": \"mydate\"}"; + String expected = "\"date_histogram\": {\"field\": \"mydate\"}"; - DateHistogramAggregation actual; - try { - actual = mapper.readValue(input, DateHistogramAggregation.class); - assertEquals(expected, actual.toElasticSearch()); - } catch (Exception e) { - fail("Exception occurred: " + e.getMessage()); + DateHistogramAggregation actual; + try { + actual = mapper.readValue(input, DateHistogramAggregation.class); + assertEquals(expected, actual.toElasticSearch()); + } catch (Exception e) { + fail("Exception occurred: " + e.getMessage()); + } } - } } diff --git a/src/test/java/org/onap/aai/sa/searchdbabstraction/searchapi/DateRangeAggregationTest.java b/src/test/java/org/onap/aai/sa/searchdbabstraction/searchapi/DateRangeAggregationTest.java index 3183687..45e7c51 100644 --- a/src/test/java/org/onap/aai/sa/searchdbabstraction/searchapi/DateRangeAggregationTest.java +++ b/src/test/java/org/onap/aai/sa/searchdbabstraction/searchapi/DateRangeAggregationTest.java @@ -28,40 +28,42 @@ import org.junit.Test; public class DateRangeAggregationTest { - private static ObjectMapper mapper = new ObjectMapper(); + private static ObjectMapper mapper = new ObjectMapper(); - @Test - public void test() { + @Test + public void test() { - String input = - "{\r\n \"field\": \"mydate\",\r\n \"ranges\": [\r\n {\r\n \"from\": \"2016-12-19T00:00:00.738-05:00\",\r\n \"to\": \"2016-12-23T23:59:59.738-05:00\"\r\n },\r\n {\r\n \"to\": \"2016-12-23T23:59:59.738-05:00\"\r\n },\r\n {\r\n \"from\": \"2016-12-19T00:00:00.738-05:00\"\r\n }\r\n ],\r\n \"format\": \"MM-yyy\",\r\n \"size\": \"5\"\r\n}"; - String expected = "\"date_range\": {\"field\": \"mydate\", \"format\": \"MM-yyy\", \"ranges\": [{\"from\": \"2016-12-19T00:00:00.738-05:00\", \"to\": \"2016-12-23T23:59:59.738-05:00\"},{\"to\": \"2016-12-23T23:59:59.738-05:00\"},{\"from\": \"2016-12-19T00:00:00.738-05:00\"}], \"size\": 5}"; + String input = + "{\r\n \"field\": \"mydate\",\r\n \"ranges\": [\r\n {\r\n \"from\": \"2016-12-19T00:00:00.738-05:00\",\r\n \"to\": \"2016-12-23T23:59:59.738-05:00\"\r\n },\r\n {\r\n \"to\": \"2016-12-23T23:59:59.738-05:00\"\r\n },\r\n {\r\n \"from\": \"2016-12-19T00:00:00.738-05:00\"\r\n }\r\n ],\r\n \"format\": \"MM-yyy\",\r\n \"size\": \"5\"\r\n}"; + String expected = + "\"date_range\": {\"field\": \"mydate\", \"format\": \"MM-yyy\", \"ranges\": [{\"from\": \"2016-12-19T00:00:00.738-05:00\", \"to\": \"2016-12-23T23:59:59.738-05:00\"},{\"to\": \"2016-12-23T23:59:59.738-05:00\"},{\"from\": \"2016-12-19T00:00:00.738-05:00\"}], \"size\": 5}"; - DateRangeAggregation actual; - try { - actual = mapper.readValue(input, DateRangeAggregation.class); - assertEquals(expected, actual.toElasticSearch()); - } catch (Exception e) { - fail("Exception occurred: " + e.getMessage()); + DateRangeAggregation actual; + try { + actual = mapper.readValue(input, DateRangeAggregation.class); + assertEquals(expected, actual.toElasticSearch()); + } catch (Exception e) { + fail("Exception occurred: " + e.getMessage()); + } } - } - @Test - public void testNoFormatNoSize() { + @Test + public void testNoFormatNoSize() { - String input = - "{\r\n \"field\": \"mydate\",\r\n \"ranges\": [\r\n {\r\n \"from\": \"2016-12-19T00:00:00.738-05:00\",\r\n \"to\": \"2016-12-23T23:59:59.738-05:00\"\r\n },\r\n {\r\n \"to\": \"2016-12-23T23:59:59.738-05:00\"\r\n },\r\n {\r\n \"from\": \"2016-12-19T00:00:00.738-05:00\"\r\n }\r\n ]\r\n}"; - String expected = "\"date_range\": {\"field\": \"mydate\", \"ranges\": [{\"from\": \"2016-12-19T00:00:00.738-05:00\", \"to\": \"2016-12-23T23:59:59.738-05:00\"},{\"to\": \"2016-12-23T23:59:59.738-05:00\"},{\"from\": \"2016-12-19T00:00:00.738-05:00\"}]}"; + String input = + "{\r\n \"field\": \"mydate\",\r\n \"ranges\": [\r\n {\r\n \"from\": \"2016-12-19T00:00:00.738-05:00\",\r\n \"to\": \"2016-12-23T23:59:59.738-05:00\"\r\n },\r\n {\r\n \"to\": \"2016-12-23T23:59:59.738-05:00\"\r\n },\r\n {\r\n \"from\": \"2016-12-19T00:00:00.738-05:00\"\r\n }\r\n ]\r\n}"; + String expected = + "\"date_range\": {\"field\": \"mydate\", \"ranges\": [{\"from\": \"2016-12-19T00:00:00.738-05:00\", \"to\": \"2016-12-23T23:59:59.738-05:00\"},{\"to\": \"2016-12-23T23:59:59.738-05:00\"},{\"from\": \"2016-12-19T00:00:00.738-05:00\"}]}"; - DateRangeAggregation actual; - try { - actual = mapper.readValue(input, DateRangeAggregation.class); - assertEquals(expected, actual.toElasticSearch()); - } catch (Exception e) { - fail("Exception occurred: " + e.getMessage()); + DateRangeAggregation actual; + try { + actual = mapper.readValue(input, DateRangeAggregation.class); + assertEquals(expected, actual.toElasticSearch()); + } catch (Exception e) { + fail("Exception occurred: " + e.getMessage()); + } } - } } diff --git a/src/test/java/org/onap/aai/sa/searchdbabstraction/searchapi/DateRangeTest.java b/src/test/java/org/onap/aai/sa/searchdbabstraction/searchapi/DateRangeTest.java index 52880c0..ef7325e 100644 --- a/src/test/java/org/onap/aai/sa/searchdbabstraction/searchapi/DateRangeTest.java +++ b/src/test/java/org/onap/aai/sa/searchdbabstraction/searchapi/DateRangeTest.java @@ -27,48 +27,49 @@ import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; public class DateRangeTest { - private static ObjectMapper mapper = new ObjectMapper(); + private static ObjectMapper mapper = new ObjectMapper(); - @Test - public void testBoth() { - String input = "{\r\n \"from\": \"2016-12-19T00:00:00.738-05:00\",\r\n \"to\": \"2016-12-23T23:59:59.738-05:00\"\r\n}"; - String expected = "{\"from\": \"2016-12-19T00:00:00.738-05:00\", \"to\": \"2016-12-23T23:59:59.738-05:00\"}"; + @Test + public void testBoth() { + String input = + "{\r\n \"from\": \"2016-12-19T00:00:00.738-05:00\",\r\n \"to\": \"2016-12-23T23:59:59.738-05:00\"\r\n}"; + String expected = "{\"from\": \"2016-12-19T00:00:00.738-05:00\", \"to\": \"2016-12-23T23:59:59.738-05:00\"}"; - DateRange actual; - try { - actual = mapper.readValue(input, DateRange.class); - assertEquals(expected, actual.toElasticSearch()); - } catch (Exception e) { - fail("Exception occurred: " + e.getMessage()); + DateRange actual; + try { + actual = mapper.readValue(input, DateRange.class); + assertEquals(expected, actual.toElasticSearch()); + } catch (Exception e) { + fail("Exception occurred: " + e.getMessage()); + } } - } - @Test - public void testFrom() { - String input = "{\"from\": \"2016-12-19T00:00:00.738-05:00\"}"; - String expected = "{\"from\": \"2016-12-19T00:00:00.738-05:00\"}"; + @Test + public void testFrom() { + String input = "{\"from\": \"2016-12-19T00:00:00.738-05:00\"}"; + String expected = "{\"from\": \"2016-12-19T00:00:00.738-05:00\"}"; - DateRange actual; - try { - actual = mapper.readValue(input, DateRange.class); - assertEquals(expected, actual.toElasticSearch()); - } catch (Exception e) { - fail("Exception occurred: " + e.getMessage()); + DateRange actual; + try { + actual = mapper.readValue(input, DateRange.class); + assertEquals(expected, actual.toElasticSearch()); + } catch (Exception e) { + fail("Exception occurred: " + e.getMessage()); + } } - } - @Test - public void testTo() { - String input = "{\r\n \"to\": \"2016-12-23T23:59:59.738-05:00\"\r\n}"; - String expected = "{\"to\": \"2016-12-23T23:59:59.738-05:00\"}"; + @Test + public void testTo() { + String input = "{\r\n \"to\": \"2016-12-23T23:59:59.738-05:00\"\r\n}"; + String expected = "{\"to\": \"2016-12-23T23:59:59.738-05:00\"}"; - DateRange actual; - try { - actual = mapper.readValue(input, DateRange.class); - assertEquals(expected, actual.toElasticSearch()); - } catch (Exception e) { - fail("Exception occurred: " + e.getMessage()); + DateRange actual; + try { + actual = mapper.readValue(input, DateRange.class); + assertEquals(expected, actual.toElasticSearch()); + } catch (Exception e) { + fail("Exception occurred: " + e.getMessage()); + } } - } } diff --git a/src/test/java/org/onap/aai/sa/searchdbabstraction/searchapi/FilterTest.java b/src/test/java/org/onap/aai/sa/searchdbabstraction/searchapi/FilterTest.java index 7b7abd0..81fa07f 100644 --- a/src/test/java/org/onap/aai/sa/searchdbabstraction/searchapi/FilterTest.java +++ b/src/test/java/org/onap/aai/sa/searchdbabstraction/searchapi/FilterTest.java @@ -28,21 +28,16 @@ import org.junit.Test; public class FilterTest { - @Test - public void test() throws JsonParseException, JsonMappingException, IOException { + @Test + public void test() throws JsonParseException, JsonMappingException, IOException { - String json = "{ \"any\": [ " - + "{\"match\": {\"field\": \"searchTags\", \"value\": \"a\"}}," - + "{\"match\": {\"field\": \"searchTags\", \"value\": \"b\"}}" - + "]," - + "\"all\": [" - + "{\"parsed-query\": {\"field\": \"fieldname\", \"query-string\": \"string\"}}" - + "]" - + "}"; + String json = "{ \"any\": [ " + "{\"match\": {\"field\": \"searchTags\", \"value\": \"a\"}}," + + "{\"match\": {\"field\": \"searchTags\", \"value\": \"b\"}}" + "]," + "\"all\": [" + + "{\"parsed-query\": {\"field\": \"fieldname\", \"query-string\": \"string\"}}" + "]" + "}"; - ObjectMapper mapper = new ObjectMapper(); - Filter filter = mapper.readValue(json, Filter.class); - System.out.println("GDF: filter = " + filter); - } + ObjectMapper mapper = new ObjectMapper(); + Filter filter = mapper.readValue(json, Filter.class); + System.out.println("GDF: filter = " + filter); + } } diff --git a/src/test/java/org/onap/aai/sa/searchdbabstraction/searchapi/GroupByAggregationTest.java b/src/test/java/org/onap/aai/sa/searchdbabstraction/searchapi/GroupByAggregationTest.java index be50243..1ebed91 100644 --- a/src/test/java/org/onap/aai/sa/searchdbabstraction/searchapi/GroupByAggregationTest.java +++ b/src/test/java/org/onap/aai/sa/searchdbabstraction/searchapi/GroupByAggregationTest.java @@ -27,36 +27,36 @@ import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; public class GroupByAggregationTest { - private static ObjectMapper mapper = new ObjectMapper(); + private static ObjectMapper mapper = new ObjectMapper(); - @Test - public void test() { - String input = "{\"field\" : \"entityType\", \"size\": 20}\r\n"; + @Test + public void test() { + String input = "{\"field\" : \"entityType\", \"size\": 20}\r\n"; - String expected = "\"terms\": {\"field\": \"entityType\", \"size\": 20}"; + String expected = "\"terms\": {\"field\": \"entityType\", \"size\": 20}"; - GroupByAggregation actual; - try { - actual = mapper.readValue(input, GroupByAggregation.class); - assertEquals(expected, actual.toElasticSearch()); - } catch (Exception e) { - fail("Exception occurred: " + e.getMessage()); + GroupByAggregation actual; + try { + actual = mapper.readValue(input, GroupByAggregation.class); + assertEquals(expected, actual.toElasticSearch()); + } catch (Exception e) { + fail("Exception occurred: " + e.getMessage()); + } } - } - @Test - public void testNoSize() { - String input = "{\"field\" : \"entityType\"}\r\n"; + @Test + public void testNoSize() { + String input = "{\"field\" : \"entityType\"}\r\n"; - String expected = "\"terms\": {\"field\": \"entityType\"}"; + String expected = "\"terms\": {\"field\": \"entityType\"}"; - GroupByAggregation actual; - try { - actual = mapper.readValue(input, GroupByAggregation.class); - assertEquals(expected, actual.toElasticSearch()); - } catch (Exception e) { - fail("Exception occurred: " + e.getMessage()); + GroupByAggregation actual; + try { + actual = mapper.readValue(input, GroupByAggregation.class); + assertEquals(expected, actual.toElasticSearch()); + } catch (Exception e) { + fail("Exception occurred: " + e.getMessage()); + } } - } } diff --git a/src/test/java/org/onap/aai/sa/searchdbabstraction/searchapi/QueryTest.java b/src/test/java/org/onap/aai/sa/searchdbabstraction/searchapi/QueryTest.java index 0e60649..2f22605 100644 --- a/src/test/java/org/onap/aai/sa/searchdbabstraction/searchapi/QueryTest.java +++ b/src/test/java/org/onap/aai/sa/searchdbabstraction/searchapi/QueryTest.java @@ -32,320 +32,338 @@ import org.junit.Test; public class QueryTest { - /** - * This test validates that we are able to marshal json structures - * representing term queries into POJOs and that we can then - * unmarshal those POJOs into ElasticSearch syntax. - * - * @throws JsonParseException - * @throws JsonMappingException - * @throws IOException - */ - @Test - public void termQueryTest() throws JsonParseException, JsonMappingException, IOException { - - Integer intValue = 1; - String field = "searchTags"; - String termQueryWithIntegerValueJson = "{\"field\": \"" + field + "\", \"value\": " + intValue + "}"; - String termQueryWithIntegerValueExpectedES = "{\"term\": {\"" + field + "\" : " + intValue + "}}"; - - Double doubleValue = 5.7; - String termQueryWithDoubleValueJson = "{\"field\": \"" + field + "\", \"value\": " + doubleValue + "}"; - String termQueryWithDoubleValueExpectedES = "{\"term\": {\"" + field + "\" : " + doubleValue + "}}"; - - String stringValue = "theValue"; - String termQueryWithStringValueJson = "{\"field\": \"" + field + "\", \"value\": \"" + stringValue + "\"}"; - String termQueryWithStringValueExpectedES = "{\"term\": {\"" + field + "\" : \"" + stringValue + "\"}}"; - - ObjectMapper mapper = new ObjectMapper(); - - - // Validate that we can marshal a term query where the supplied value - // is an Integer. - TermQuery integerTermQuery = mapper.readValue(termQueryWithIntegerValueJson, TermQuery.class); - assertTrue("Expected value to be of type Integer, but was type " + integerTermQuery.getValue().getClass().getName(), - integerTermQuery.getValue() instanceof Integer); - assertEquals(intValue, integerTermQuery.getValue()); - - assertTrue("ElasticSearch term query translation does not match the expected result", - termQueryWithIntegerValueExpectedES.equals(integerTermQuery.toElasticSearch())); - - // Validate that we can marshal a term query where the supplied value - // is a Double. - TermQuery doubleTermQuery = mapper.readValue(termQueryWithDoubleValueJson, TermQuery.class); - assertTrue("Expected value to be of type Double, but was type " + doubleTermQuery.getValue().getClass().getName(), - doubleTermQuery.getValue() instanceof Double); - assertEquals(doubleValue, doubleTermQuery.getValue()); - assertTrue("ElasticSearch term query translation does not match the expected result", - termQueryWithDoubleValueExpectedES.equals(doubleTermQuery.toElasticSearch())); - - // Validate that we can marshal a term query where the supplied value - // is a String literal. - TermQuery stringTermQuery = mapper.readValue(termQueryWithStringValueJson, TermQuery.class); - assertTrue("Expected value to be of type String, but was type " + stringTermQuery.getValue().getClass().getName(), - stringTermQuery.getValue() instanceof String); - assertEquals(stringValue, stringTermQuery.getValue()); - assertTrue("ElasticSearch term query translation does not match the expected result", - termQueryWithStringValueExpectedES.equals(stringTermQuery.toElasticSearch())); - - - } - - - /** - * This test validates that we are able to marshal json structures - * representing parsed queries into POJOs and that we can then - * unmarshal those POJOs into ElasticSearch syntax. - * - * @throws JsonParseException - * @throws JsonMappingException - * @throws IOException - */ - @Test - public void parsedQueryTest() throws JsonParseException, JsonMappingException, IOException { - - String field = "fieldname"; - String queryString = "The query string"; - - String queryJson = "{\"field\": \"" + field + "\", \"query-string\": \"" + queryString + "\"}"; - String queryExpectedES = "{\"query_string\": {\"default_field\": \"" + field + "\", \"query\": \"" + queryString + "\"}}"; - - ObjectMapper mapper = new ObjectMapper(); - ParsedQuery pq = mapper.readValue(queryJson, ParsedQuery.class); - - assertTrue("Unexpected marshalled value for 'field' - expected: " + field + " actual: " + pq.getField(), - field.equals(pq.getField())); - assertTrue("Unexpected marshalled value for 'query-string' - expected: " + queryString + " actual: " + pq.getQueryString(), - queryString.equals(pq.getQueryString())); - assertTrue("Unexpected ElasticSearch syntax. Expected: " + queryExpectedES + " Actual: " + pq.toElasticSearch(), - queryExpectedES.equals(pq.toElasticSearch())); - } - - - /** - * This test validates that a ranged query cannot be parsed with values - * for both the 'gte' and 'gt' fields or the 'lte' and 'lt' fields, and - * that we do not allow mixing of numeric and date types in the same - * query. - * - * @throws JsonParseException - * @throws IOException - */ - @Test - public void rangeQueryConflictingBoundsTest() throws JsonParseException, IOException { - - String invalidGTAndGTE = "{ \"field\": \"timestamp\", \"gte\": \"2016-10-06T00:00:00.558+03:00\", \"gt\": \"2016-10-06T23:59:59.558+03:00\"}"; - String invalidLTAndLTE = "{ \"field\": \"timestamp\", \"lte\": \"2016-10-06T00:00:00.558+03:00\", \"lt\": \"2016-10-06T23:59:59.558+03:00\"}"; - String invalidTypes = "{ \"field\": \"timestamp\", \"lte\": 5, \"gte\": \"2016-10-06T23:59:59.558+03:00\"}"; - - ObjectMapper mapper = new ObjectMapper(); - - // Attempt to parse a query where we are setting values for both the - // 'greater than' and 'greater than and equal to' operators. - boolean gotExpectedException = false; - try { - RangeQuery badRangeQuery = mapper.readValue(invalidGTAndGTE, RangeQuery.class); - } catch (JsonMappingException e) { - gotExpectedException = true; - } - assertTrue("Attempting to set both a 'gt' and 'gte' value on the same query should not have been allowed", - gotExpectedException); - - // Attempt to parse a query where we are setting values for both the - // 'less than' and 'less than and equal to' operators. - gotExpectedException = false; - try { - RangeQuery badRangeQuery = mapper.readValue(invalidLTAndLTE, RangeQuery.class); - } catch (JsonMappingException e) { - gotExpectedException = true; - } - assertTrue("Attempting to set both a 'lt' and 'lte' value on the same query should not have been allowed", - gotExpectedException); - - // Attempt to parse a query where we are mixing numeric and date values - // in the same query. - gotExpectedException = false; - try { - RangeQuery badRangeQuery = mapper.readValue(invalidTypes, RangeQuery.class); - } catch (JsonMappingException e) { - gotExpectedException = true; - } - assertTrue("Attempting to mix numeric and date values in the same query should not have been allowed", - gotExpectedException); - - - } - + /** + * This test validates that we are able to marshal json structures representing term queries into POJOs and that we + * can then unmarshal those POJOs into ElasticSearch syntax. + * + * @throws JsonParseException + * @throws JsonMappingException + * @throws IOException + */ + @Test + public void termQueryTest() throws JsonParseException, JsonMappingException, IOException { + + Integer intValue = 1; + String field = "searchTags"; + String termQueryWithIntegerValueJson = "{\"field\": \"" + field + "\", \"value\": " + intValue + "}"; + String termQueryWithIntegerValueExpectedES = "{\"term\": {\"" + field + "\" : " + intValue + "}}"; + + Double doubleValue = 5.7; + String termQueryWithDoubleValueJson = "{\"field\": \"" + field + "\", \"value\": " + doubleValue + "}"; + String termQueryWithDoubleValueExpectedES = "{\"term\": {\"" + field + "\" : " + doubleValue + "}}"; + + String stringValue = "theValue"; + String termQueryWithStringValueJson = "{\"field\": \"" + field + "\", \"value\": \"" + stringValue + "\"}"; + String termQueryWithStringValueExpectedES = "{\"term\": {\"" + field + "\" : \"" + stringValue + "\"}}"; + + ObjectMapper mapper = new ObjectMapper(); + + + // Validate that we can marshal a term query where the supplied value + // is an Integer. + TermQuery integerTermQuery = mapper.readValue(termQueryWithIntegerValueJson, TermQuery.class); + assertTrue( + "Expected value to be of type Integer, but was type " + + integerTermQuery.getValue().getClass().getName(), + integerTermQuery.getValue() instanceof Integer); + assertEquals(intValue, integerTermQuery.getValue()); + + assertTrue("ElasticSearch term query translation does not match the expected result", + termQueryWithIntegerValueExpectedES.equals(integerTermQuery.toElasticSearch())); + + // Validate that we can marshal a term query where the supplied value + // is a Double. + TermQuery doubleTermQuery = mapper.readValue(termQueryWithDoubleValueJson, TermQuery.class); + assertTrue( + "Expected value to be of type Double, but was type " + doubleTermQuery.getValue().getClass().getName(), + doubleTermQuery.getValue() instanceof Double); + assertEquals(doubleValue, doubleTermQuery.getValue()); + assertTrue("ElasticSearch term query translation does not match the expected result", + termQueryWithDoubleValueExpectedES.equals(doubleTermQuery.toElasticSearch())); + + // Validate that we can marshal a term query where the supplied value + // is a String literal. + TermQuery stringTermQuery = mapper.readValue(termQueryWithStringValueJson, TermQuery.class); + assertTrue( + "Expected value to be of type String, but was type " + stringTermQuery.getValue().getClass().getName(), + stringTermQuery.getValue() instanceof String); + assertEquals(stringValue, stringTermQuery.getValue()); + assertTrue("ElasticSearch term query translation does not match the expected result", + termQueryWithStringValueExpectedES.equals(stringTermQuery.toElasticSearch())); - /** - * This test validates that date range queries can be marshalled to a Java - * POJO and unmarshalled to ElasticSearch syntax. - * - * @throws JsonParseException - * @throws JsonMappingException - * @throws IOException - */ - @Test - public void dateRangeQueryTest() throws JsonParseException, JsonMappingException, IOException { - String field = "timestamp"; - String greaterThanDate = "2016-10-06T00:00:00.558+03:00"; - String lessThanDate = "2016-10-06T23:59:59.558+03:00"; - - ObjectMapper mapper = new ObjectMapper(); - - // Generate a date range query using 'greater than or equal' and 'less - // than or equal' operations. - String dateRangeJson = - "{ \"field\": \"" + field + "\", \"gte\": \"" + greaterThanDate + "\", \"lte\": \"" + lessThanDate + "\"}"; - String dateRangeExpectedES = - "{\"range\": {\"timestamp\": {\"gte\": \"2016-10-06T00:00:00.558+03:00\", \"lte\": \"2016-10-06T23:59:59.558+03:00\"}}}"; + } - // Validate that the query is marshalled correctly to the POJO and that - // the generated ElasticSearch syntax looks as expected. - RangeQuery dateRangeQuery = mapper.readValue(dateRangeJson, RangeQuery.class); - - assertTrue("Unexpected marshalled value for 'field'. Expected: " + field + " Actual: " + dateRangeQuery.getField(), - field.equals(dateRangeQuery.getField())); - assertTrue("Unexpected type for 'gte' value. Expected: String Actual: " + dateRangeQuery.getGte().getClass().getName(), - dateRangeQuery.getGte() instanceof String); - assertTrue("Unexpected type for 'lte' value. Expected: String Actual: " + dateRangeQuery.getLte().getClass().getName(), - dateRangeQuery.getLte() instanceof String); - assertTrue("Unexpected marshalled value for 'gte'. Expected: " + greaterThanDate + " Actual: " + dateRangeQuery.getGte(), - greaterThanDate.equals(dateRangeQuery.getGte())); - assertTrue("Unexpected marshalled value for 'lte'. Expected: " + lessThanDate + " Actual: " + dateRangeQuery.getLte(), - lessThanDate.equals(dateRangeQuery.getLte())); - assertTrue("Unexpected ElasticSearch syntax. Expected: " + dateRangeExpectedES + " Actual: " + dateRangeQuery.toElasticSearch(), - dateRangeExpectedES.equals(dateRangeQuery.toElasticSearch())); - - - // Generate a date range query using 'greater than' and 'less than or - // equal' operations. - dateRangeJson = - "{ \"field\": \"" + field + "\", \"gt\": \"" + greaterThanDate + "\", \"lte\": \"" + lessThanDate + "\"}"; - dateRangeExpectedES = - "{\"range\": {\"timestamp\": {\"gt\": \"2016-10-06T00:00:00.558+03:00\", \"lte\": \"2016-10-06T23:59:59.558+03:00\"}}}"; - - // Validate that the query is marshalled correctly to the POJO and that - // the generated ElasticSearch syntax looks as expected. - dateRangeQuery = mapper.readValue(dateRangeJson, RangeQuery.class); - - assertTrue("Unexpected marshalled value for 'field'. Expected: " + field + " Actual: " + dateRangeQuery.getField(), - field.equals(dateRangeQuery.getField())); - - assertTrue("Unexpected type for 'gt' value. Expected: String Actual: " + dateRangeQuery.getGt().getClass().getName(), - dateRangeQuery.getGt() instanceof String); - - assertTrue("Unexpected type for 'lte' value. Expected: String Actual: " + dateRangeQuery.getLte().getClass().getName(), - dateRangeQuery.getLte() instanceof String); - - assertTrue("Unexpected marshalled value for 'gt'. Expected: " + greaterThanDate + " Actual: " + dateRangeQuery.getGt(), - greaterThanDate.equals(dateRangeQuery.getGt())); - - assertTrue("Unexpected marshalled value for 'lte'. Expected: " + lessThanDate + " Actual: " + dateRangeQuery.getLte(), - lessThanDate.equals(dateRangeQuery.getLte())); - - assertTrue("Unexpected ElasticSearch syntax. Expected: " + dateRangeExpectedES + " Actual: " + dateRangeQuery.toElasticSearch(), - dateRangeExpectedES.equals(dateRangeQuery.toElasticSearch())); - - - // Generate a date range query using only a 'greater than' operation. - dateRangeJson = - "{ \"field\": \"" + field + "\", \"gt\": \"" + greaterThanDate + "\"}"; - dateRangeExpectedES = - "{\"range\": {\"timestamp\": {\"gt\": \"2016-10-06T00:00:00.558+03:00\"}}}"; - - // Validate that the query is marshalled correctly to the POJO and that - // the generated ElasticSearch syntax looks as expected. - dateRangeQuery = mapper.readValue(dateRangeJson, RangeQuery.class); - - assertTrue("Unexpected marshalled value for 'field'. Expected: " + field + " Actual: " + dateRangeQuery.getField(), - field.equals(dateRangeQuery.getField())); - - assertTrue("Unexpected type for 'gt' value. Expected: String Actual: " + dateRangeQuery.getGt().getClass().getName(), - dateRangeQuery.getGt() instanceof String); - - assertTrue("Unexpected marshalled value for 'gt'. Expected: " + greaterThanDate + " Actual: " + dateRangeQuery.getGt(), - greaterThanDate.equals(dateRangeQuery.getGt())); - - assertTrue("Unexpected ElasticSearch syntax. Expected: " + dateRangeExpectedES + " Actual: " + dateRangeQuery.toElasticSearch(), - dateRangeExpectedES.equals(dateRangeQuery.toElasticSearch())); - - } - - /** - * This test validates that numeric range queries can be marshalled to a Java - * POJO and unmarshalled to ElasticSearch syntax. - * - * @throws JsonParseException - * @throws JsonMappingException - * @throws IOException - */ - @Test - public void numericRangeQueryTest() throws JsonParseException, JsonMappingException, IOException { - - String field = "version"; - Integer greaterThanInt = 5; - Integer lessThanInt = 100; - - ObjectMapper mapper = new ObjectMapper(); - - // Generate a numeric range query using 'greater than or equal' and 'less - // than or equal' operations. - String numericRangeJson = - "{ \"field\": \"" + field + "\", \"gte\": " + greaterThanInt + ", \"lte\": " + lessThanInt + "}"; - String numericRangeExpectedES = - "{\"range\": {\"" + field + "\": {\"gte\": " + greaterThanInt + ", \"lte\": " + lessThanInt + "}}}"; - - // Validate that the query is marshalled correctly to the POJO and that - // the generated ElasticSearch syntax looks as expected. - RangeQuery numericRangeQuery = mapper.readValue(numericRangeJson, RangeQuery.class); - - assertTrue("Unexpected marshalled value for 'field'. Expected: " + field + " Actual: " + numericRangeQuery.getField(), - field.equals(numericRangeQuery.getField())); - assertTrue("Unexpected type for 'gte' value. Expected: Integer Actual: " + numericRangeQuery.getGte().getClass().getName(), - numericRangeQuery.getGte() instanceof Integer); - assertTrue("Unexpected type for 'lte' value. Expected: Integer Actual: " + numericRangeQuery.getLte().getClass().getName(), - numericRangeQuery.getLte() instanceof Integer); - assertEquals("Unexpected marshalled value for 'gte'. Expected: " + greaterThanInt + " Actual: " + numericRangeQuery.getGte(), - greaterThanInt, numericRangeQuery.getGte()); - assertEquals("Unexpected marshalled value for 'lte'. Expected: " + lessThanInt + " Actual: " + numericRangeQuery.getLte(), - lessThanInt, numericRangeQuery.getLte()); - assertTrue("Unexpected ElasticSearch syntax. Expected: " + numericRangeExpectedES + " Actual: " + numericRangeQuery.toElasticSearch(), - numericRangeExpectedES.equals(numericRangeQuery.toElasticSearch())); + /** + * This test validates that we are able to marshal json structures representing parsed queries into POJOs and that + * we can then unmarshal those POJOs into ElasticSearch syntax. + * + * @throws JsonParseException + * @throws JsonMappingException + * @throws IOException + */ + @Test + public void parsedQueryTest() throws JsonParseException, JsonMappingException, IOException { + + String field = "fieldname"; + String queryString = "The query string"; + + String queryJson = "{\"field\": \"" + field + "\", \"query-string\": \"" + queryString + "\"}"; + String queryExpectedES = + "{\"query_string\": {\"default_field\": \"" + field + "\", \"query\": \"" + queryString + "\"}}"; + + ObjectMapper mapper = new ObjectMapper(); + ParsedQuery pq = mapper.readValue(queryJson, ParsedQuery.class); + + assertTrue("Unexpected marshalled value for 'field' - expected: " + field + " actual: " + pq.getField(), + field.equals(pq.getField())); + assertTrue("Unexpected marshalled value for 'query-string' - expected: " + queryString + " actual: " + + pq.getQueryString(), queryString.equals(pq.getQueryString())); + assertTrue( + "Unexpected ElasticSearch syntax. Expected: " + queryExpectedES + " Actual: " + pq.toElasticSearch(), + queryExpectedES.equals(pq.toElasticSearch())); + } - Double greaterThanDouble = 5.0; - Double lessThanDouble = 100.0; - // Generate a date range query using 'greater than' and 'less than or - // equal' operations. - numericRangeJson = - "{ \"field\": \"" + field + "\", \"gt\": " + greaterThanDouble + ", \"lte\": " + lessThanDouble + "}"; - numericRangeExpectedES = - "{\"range\": {\"" + field + "\": {\"gt\": " + greaterThanDouble + ", \"lte\": " + lessThanDouble + "}}}"; + /** + * This test validates that a ranged query cannot be parsed with values for both the 'gte' and 'gt' fields or the + * 'lte' and 'lt' fields, and that we do not allow mixing of numeric and date types in the same query. + * + * @throws JsonParseException + * @throws IOException + */ + @Test + public void rangeQueryConflictingBoundsTest() throws JsonParseException, IOException { + + String invalidGTAndGTE = + "{ \"field\": \"timestamp\", \"gte\": \"2016-10-06T00:00:00.558+03:00\", \"gt\": \"2016-10-06T23:59:59.558+03:00\"}"; + String invalidLTAndLTE = + "{ \"field\": \"timestamp\", \"lte\": \"2016-10-06T00:00:00.558+03:00\", \"lt\": \"2016-10-06T23:59:59.558+03:00\"}"; + String invalidTypes = "{ \"field\": \"timestamp\", \"lte\": 5, \"gte\": \"2016-10-06T23:59:59.558+03:00\"}"; + + ObjectMapper mapper = new ObjectMapper(); + + // Attempt to parse a query where we are setting values for both the + // 'greater than' and 'greater than and equal to' operators. + boolean gotExpectedException = false; + try { + RangeQuery badRangeQuery = mapper.readValue(invalidGTAndGTE, RangeQuery.class); + } catch (JsonMappingException e) { + gotExpectedException = true; + } + assertTrue("Attempting to set both a 'gt' and 'gte' value on the same query should not have been allowed", + gotExpectedException); + + // Attempt to parse a query where we are setting values for both the + // 'less than' and 'less than and equal to' operators. + gotExpectedException = false; + try { + RangeQuery badRangeQuery = mapper.readValue(invalidLTAndLTE, RangeQuery.class); + } catch (JsonMappingException e) { + gotExpectedException = true; + } + assertTrue("Attempting to set both a 'lt' and 'lte' value on the same query should not have been allowed", + gotExpectedException); + + // Attempt to parse a query where we are mixing numeric and date values + // in the same query. + gotExpectedException = false; + try { + RangeQuery badRangeQuery = mapper.readValue(invalidTypes, RangeQuery.class); + } catch (JsonMappingException e) { + gotExpectedException = true; + } + assertTrue("Attempting to mix numeric and date values in the same query should not have been allowed", + gotExpectedException); - // Validate that the query is marshalled correctly to the POJO and that - // the generated ElasticSearch syntax looks as expected. - numericRangeQuery = mapper.readValue(numericRangeJson, RangeQuery.class); - assertTrue("Unexpected marshalled value for 'field'. Expected: " + field + " Actual: " + numericRangeQuery.getField(), - field.equals(numericRangeQuery.getField())); + } - assertTrue("Unexpected type for 'gt' value. Expected: Double Actual: " + numericRangeQuery.getGt().getClass().getName(), - numericRangeQuery.getGt() instanceof Double); - assertTrue("Unexpected type for 'lte' value. Expected: Double Actual: " + numericRangeQuery.getLte().getClass().getName(), - numericRangeQuery.getLte() instanceof Double); + /** + * This test validates that date range queries can be marshalled to a Java POJO and unmarshalled to ElasticSearch + * syntax. + * + * @throws JsonParseException + * @throws JsonMappingException + * @throws IOException + */ + @Test + public void dateRangeQueryTest() throws JsonParseException, JsonMappingException, IOException { + + String field = "timestamp"; + String greaterThanDate = "2016-10-06T00:00:00.558+03:00"; + String lessThanDate = "2016-10-06T23:59:59.558+03:00"; + + ObjectMapper mapper = new ObjectMapper(); + + // Generate a date range query using 'greater than or equal' and 'less + // than or equal' operations. + String dateRangeJson = "{ \"field\": \"" + field + "\", \"gte\": \"" + greaterThanDate + "\", \"lte\": \"" + + lessThanDate + "\"}"; + String dateRangeExpectedES = + "{\"range\": {\"timestamp\": {\"gte\": \"2016-10-06T00:00:00.558+03:00\", \"lte\": \"2016-10-06T23:59:59.558+03:00\"}}}"; + + // Validate that the query is marshalled correctly to the POJO and that + // the generated ElasticSearch syntax looks as expected. + RangeQuery dateRangeQuery = mapper.readValue(dateRangeJson, RangeQuery.class); + + assertTrue("Unexpected marshalled value for 'field'. Expected: " + field + " Actual: " + + dateRangeQuery.getField(), field.equals(dateRangeQuery.getField())); + assertTrue("Unexpected type for 'gte' value. Expected: String Actual: " + + dateRangeQuery.getGte().getClass().getName(), dateRangeQuery.getGte() instanceof String); + assertTrue("Unexpected type for 'lte' value. Expected: String Actual: " + + dateRangeQuery.getLte().getClass().getName(), dateRangeQuery.getLte() instanceof String); + assertTrue("Unexpected marshalled value for 'gte'. Expected: " + greaterThanDate + " Actual: " + + dateRangeQuery.getGte(), greaterThanDate.equals(dateRangeQuery.getGte())); + assertTrue("Unexpected marshalled value for 'lte'. Expected: " + lessThanDate + " Actual: " + + dateRangeQuery.getLte(), lessThanDate.equals(dateRangeQuery.getLte())); + assertTrue( + "Unexpected ElasticSearch syntax. Expected: " + dateRangeExpectedES + " Actual: " + + dateRangeQuery.toElasticSearch(), + dateRangeExpectedES.equals(dateRangeQuery.toElasticSearch())); + + + // Generate a date range query using 'greater than' and 'less than or + // equal' operations. + dateRangeJson = "{ \"field\": \"" + field + "\", \"gt\": \"" + greaterThanDate + "\", \"lte\": \"" + + lessThanDate + "\"}"; + dateRangeExpectedES = + "{\"range\": {\"timestamp\": {\"gt\": \"2016-10-06T00:00:00.558+03:00\", \"lte\": \"2016-10-06T23:59:59.558+03:00\"}}}"; + + // Validate that the query is marshalled correctly to the POJO and that + // the generated ElasticSearch syntax looks as expected. + dateRangeQuery = mapper.readValue(dateRangeJson, RangeQuery.class); + + assertTrue("Unexpected marshalled value for 'field'. Expected: " + field + " Actual: " + + dateRangeQuery.getField(), field.equals(dateRangeQuery.getField())); + + assertTrue("Unexpected type for 'gt' value. Expected: String Actual: " + + dateRangeQuery.getGt().getClass().getName(), dateRangeQuery.getGt() instanceof String); + + assertTrue("Unexpected type for 'lte' value. Expected: String Actual: " + + dateRangeQuery.getLte().getClass().getName(), dateRangeQuery.getLte() instanceof String); + + assertTrue("Unexpected marshalled value for 'gt'. Expected: " + greaterThanDate + " Actual: " + + dateRangeQuery.getGt(), greaterThanDate.equals(dateRangeQuery.getGt())); + + assertTrue("Unexpected marshalled value for 'lte'. Expected: " + lessThanDate + " Actual: " + + dateRangeQuery.getLte(), lessThanDate.equals(dateRangeQuery.getLte())); + + assertTrue( + "Unexpected ElasticSearch syntax. Expected: " + dateRangeExpectedES + " Actual: " + + dateRangeQuery.toElasticSearch(), + dateRangeExpectedES.equals(dateRangeQuery.toElasticSearch())); + + + // Generate a date range query using only a 'greater than' operation. + dateRangeJson = "{ \"field\": \"" + field + "\", \"gt\": \"" + greaterThanDate + "\"}"; + dateRangeExpectedES = "{\"range\": {\"timestamp\": {\"gt\": \"2016-10-06T00:00:00.558+03:00\"}}}"; + + // Validate that the query is marshalled correctly to the POJO and that + // the generated ElasticSearch syntax looks as expected. + dateRangeQuery = mapper.readValue(dateRangeJson, RangeQuery.class); + + assertTrue("Unexpected marshalled value for 'field'. Expected: " + field + " Actual: " + + dateRangeQuery.getField(), field.equals(dateRangeQuery.getField())); + + assertTrue("Unexpected type for 'gt' value. Expected: String Actual: " + + dateRangeQuery.getGt().getClass().getName(), dateRangeQuery.getGt() instanceof String); + + assertTrue("Unexpected marshalled value for 'gt'. Expected: " + greaterThanDate + " Actual: " + + dateRangeQuery.getGt(), greaterThanDate.equals(dateRangeQuery.getGt())); + + assertTrue( + "Unexpected ElasticSearch syntax. Expected: " + dateRangeExpectedES + " Actual: " + + dateRangeQuery.toElasticSearch(), + dateRangeExpectedES.equals(dateRangeQuery.toElasticSearch())); - assertEquals("Unexpected marshalled value for 'gt'. Expected: " + greaterThanDouble + " Actual: " + numericRangeQuery.getGt(), - greaterThanDouble, numericRangeQuery.getGt()); + } - assertEquals("Unexpected marshalled value for 'lte'. Expected: " + lessThanDouble + " Actual: " + numericRangeQuery.getLte(), - lessThanDouble, numericRangeQuery.getLte()); - - assertTrue("Unexpected ElasticSearch syntax. Expected: " + numericRangeExpectedES + " Actual: " + numericRangeQuery.toElasticSearch(), - numericRangeExpectedES.equals(numericRangeQuery.toElasticSearch())); - } + /** + * This test validates that numeric range queries can be marshalled to a Java POJO and unmarshalled to ElasticSearch + * syntax. + * + * @throws JsonParseException + * @throws JsonMappingException + * @throws IOException + */ + @Test + public void numericRangeQueryTest() throws JsonParseException, JsonMappingException, IOException { + + String field = "version"; + Integer greaterThanInt = 5; + Integer lessThanInt = 100; + + ObjectMapper mapper = new ObjectMapper(); + + // Generate a numeric range query using 'greater than or equal' and 'less + // than or equal' operations. + String numericRangeJson = + "{ \"field\": \"" + field + "\", \"gte\": " + greaterThanInt + ", \"lte\": " + lessThanInt + "}"; + String numericRangeExpectedES = + "{\"range\": {\"" + field + "\": {\"gte\": " + greaterThanInt + ", \"lte\": " + lessThanInt + "}}}"; + + // Validate that the query is marshalled correctly to the POJO and that + // the generated ElasticSearch syntax looks as expected. + RangeQuery numericRangeQuery = mapper.readValue(numericRangeJson, RangeQuery.class); + + assertTrue("Unexpected marshalled value for 'field'. Expected: " + field + " Actual: " + + numericRangeQuery.getField(), field.equals(numericRangeQuery.getField())); + assertTrue( + "Unexpected type for 'gte' value. Expected: Integer Actual: " + + numericRangeQuery.getGte().getClass().getName(), + numericRangeQuery.getGte() instanceof Integer); + assertTrue( + "Unexpected type for 'lte' value. Expected: Integer Actual: " + + numericRangeQuery.getLte().getClass().getName(), + numericRangeQuery.getLte() instanceof Integer); + assertEquals("Unexpected marshalled value for 'gte'. Expected: " + greaterThanInt + " Actual: " + + numericRangeQuery.getGte(), greaterThanInt, numericRangeQuery.getGte()); + assertEquals("Unexpected marshalled value for 'lte'. Expected: " + lessThanInt + " Actual: " + + numericRangeQuery.getLte(), lessThanInt, numericRangeQuery.getLte()); + assertTrue( + "Unexpected ElasticSearch syntax. Expected: " + numericRangeExpectedES + " Actual: " + + numericRangeQuery.toElasticSearch(), + numericRangeExpectedES.equals(numericRangeQuery.toElasticSearch())); + + + Double greaterThanDouble = 5.0; + Double lessThanDouble = 100.0; + + // Generate a date range query using 'greater than' and 'less than or + // equal' operations. + numericRangeJson = + "{ \"field\": \"" + field + "\", \"gt\": " + greaterThanDouble + ", \"lte\": " + lessThanDouble + "}"; + numericRangeExpectedES = "{\"range\": {\"" + field + "\": {\"gt\": " + greaterThanDouble + ", \"lte\": " + + lessThanDouble + "}}}"; + + // Validate that the query is marshalled correctly to the POJO and that + // the generated ElasticSearch syntax looks as expected. + numericRangeQuery = mapper.readValue(numericRangeJson, RangeQuery.class); + + assertTrue("Unexpected marshalled value for 'field'. Expected: " + field + " Actual: " + + numericRangeQuery.getField(), field.equals(numericRangeQuery.getField())); + + assertTrue("Unexpected type for 'gt' value. Expected: Double Actual: " + + numericRangeQuery.getGt().getClass().getName(), numericRangeQuery.getGt() instanceof Double); + + assertTrue( + "Unexpected type for 'lte' value. Expected: Double Actual: " + + numericRangeQuery.getLte().getClass().getName(), + numericRangeQuery.getLte() instanceof Double); + + assertEquals("Unexpected marshalled value for 'gt'. Expected: " + greaterThanDouble + " Actual: " + + numericRangeQuery.getGt(), greaterThanDouble, numericRangeQuery.getGt()); + + assertEquals("Unexpected marshalled value for 'lte'. Expected: " + lessThanDouble + " Actual: " + + numericRangeQuery.getLte(), lessThanDouble, numericRangeQuery.getLte()); + + assertTrue( + "Unexpected ElasticSearch syntax. Expected: " + numericRangeExpectedES + " Actual: " + + numericRangeQuery.toElasticSearch(), + numericRangeExpectedES.equals(numericRangeQuery.toElasticSearch())); + } } diff --git a/src/test/java/org/onap/aai/sa/searchdbabstraction/searchapi/RangeQueryTest.java b/src/test/java/org/onap/aai/sa/searchdbabstraction/searchapi/RangeQueryTest.java index a06a2a0..e8ca844 100644 --- a/src/test/java/org/onap/aai/sa/searchdbabstraction/searchapi/RangeQueryTest.java +++ b/src/test/java/org/onap/aai/sa/searchdbabstraction/searchapi/RangeQueryTest.java @@ -29,8 +29,8 @@ import org.onap.aai.sa.rest.TestUtils; public class RangeQueryTest { - @Test(expected=IllegalArgumentException.class) - public void testSetGt(){ + @Test(expected = IllegalArgumentException.class) + public void testSetGt() { RangeQuery rq = new RangeQuery(); rq.setLt(new String("2x")); @@ -40,8 +40,8 @@ public class RangeQueryTest { rq.setGt(new Integer(1)); } - @Test(expected=IllegalArgumentException.class) - public void testSetGte(){ + @Test(expected = IllegalArgumentException.class) + public void testSetGte() { RangeQuery rq = new RangeQuery(); rq.setGt(new Integer(1)); @@ -50,8 +50,8 @@ public class RangeQueryTest { rq.setGte(new Integer(1)); } - @Test(expected=IllegalArgumentException.class) - public void testSetLt(){ + @Test(expected = IllegalArgumentException.class) + public void testSetLt() { RangeQuery rq = new RangeQuery(); rq.setLt(new Integer(1)); @@ -66,8 +66,8 @@ public class RangeQueryTest { rq.setLt(new String("10")); } - @Test(expected=IllegalArgumentException.class) - public void testSetLte(){ + @Test(expected = IllegalArgumentException.class) + public void testSetLte() { RangeQuery rq = new RangeQuery(); rq.setGt(new Integer(1)); rq.setTimeZone("CT"); @@ -88,12 +88,12 @@ public class RangeQueryTest { Aggregation a1 = getAggregationObject(); Aggregation a2 = getAggregationObject(); - Aggregation[] aggs= new Aggregation[] {a1, a2}; + Aggregation[] aggs = new Aggregation[] {a1, a2}; ss.setAggregations(aggs); Assert.assertNotNull(ss.toString()); } - private Aggregation getAggregationObject(){ + private Aggregation getAggregationObject() { Aggregation a = new Aggregation(); AggregationStatement as = new AggregationStatement(); @@ -126,7 +126,7 @@ public class RangeQueryTest { Assert.assertEquals(dr.getToDate(), "21-12-2017"); DateRange[] drs = {dr}; dra.setDateRanges(drs); - Assert.assertTrue(dra.getDateRanges().length==1); + Assert.assertTrue(dra.getDateRanges().length == 1); Assert.assertNotNull(dra.toElasticSearch()); Assert.assertNotNull(dra.toString()); as.setDateRange(dra); diff --git a/src/test/java/org/onap/aai/sa/searchdbabstraction/searchapi/SearchStatementTest.java b/src/test/java/org/onap/aai/sa/searchdbabstraction/searchapi/SearchStatementTest.java index 03cf238..45ad666 100644 --- a/src/test/java/org/onap/aai/sa/searchdbabstraction/searchapi/SearchStatementTest.java +++ b/src/test/java/org/onap/aai/sa/searchdbabstraction/searchapi/SearchStatementTest.java @@ -36,234 +36,176 @@ import org.onap.aai.sa.rest.TestUtils; public class SearchStatementTest { - @Test - public void simpleQueryTest() throws JsonParseException, JsonMappingException, IOException { - - String field = "searchTags"; - String queryString = "aai3255"; - String queryJson = - "{" - + "\"queries\": [" - + "{\"may\": {\"parsed-query\": {" - + "\"field\": \"" + field + "\"," - + "\"query-string\": \"" + queryString + "\"}}}" - + "]" - + "}" - + "}"; - - String queryES = - "{" - + "\"version\": true," - + "\"query\": {" - + "\"bool\": {" - + "\"must\": [], " - + "\"should\": [" - + "{\"query_string\": {\"default_field\": \"searchTags\", \"query\": \"aai3255\"}}" - + "]," - + "\"must_not\": []}" - + "}" - + "}"; - - // Marshal our simple query JSON to a SearchStatement object. - ObjectMapper mapper = new ObjectMapper(); - SearchStatement ss = mapper.readValue(queryJson, SearchStatement.class); - - // We expect to have a search statement with one query. - assertEquals("Unexpected number of queries in marshalled result", - 1, ss.getQueries().length); - - // Validate that the query is of the expected type and contains the - // expected values. - QueryStatement query = ss.getQueries()[0].getQueryStatement(); - assertNotNull("Expected marshalled statement to contain a 'parsed query'", - query.getParsedQuery()); - assertTrue("Unexpected field name in marshalled query. Expected: " + field + " Actual: " + query.getParsedQuery().getField(), - field.equals(query.getParsedQuery().getField())); - assertTrue("Unexpected query string in marshalled query. Expected: " + queryString + " Actual: " + query.getParsedQuery().getQueryString(), - queryString.equals(query.getParsedQuery().getQueryString())); - - // Validate that we are able to produce the expected ElasticSearch - // query syntax from the search statement. - assertTrue("Unexpected ElasticSearch syntax. Expected: " + queryES + " Actual: " + ss.toElasticSearch(), - queryES.equals(ss.toElasticSearch())); - } - - - @Test - public void simpleSortedQueryTest() throws JsonParseException, JsonMappingException, IOException { - - String field = "searchTags"; - String queryString = "aai3255"; - String queryJson = - "{" - + "\"queries\": [" - + "{\"may\": {\"parsed-query\": {" - + "\"field\": \"" + field + "\"," - + "\"query-string\": \"" + queryString + "\"}}}" - + "]," - + "\"sort\": { \"field\": \"date\", \"order\": \"ascending\" }" - + "}"; - - - String queryES = - "{" - + "\"version\": true," - + "\"query\": {" - + "\"bool\": {" - + "\"must\": [], " - + "\"should\": [" - + "{\"query_string\": {\"default_field\": \"searchTags\", \"query\": \"aai3255\"}}" - + "]," - + "\"must_not\": []" - + "}" - + "}, " - + "\"sort\": { \"date\": { \"order\": \"asc\"}}" - + "}"; - - // Marshal our simple query JSON to a SearchStatement object. - ObjectMapper mapper = new ObjectMapper(); - SearchStatement ss = mapper.readValue(queryJson, SearchStatement.class); - - // We expect to have a search statement with one query. - assertEquals("Unexpected number of queries in marshalled result", - 1, ss.getQueries().length); - - // Validate that the query is of the expected type and contains the - // expected values. - QueryStatement query = ss.getQueries()[0].getQueryStatement(); - assertNotNull("Expected marshalled statement to contain a 'parsed query'", - query.getParsedQuery()); - assertTrue("Unexpected field name in marshalled query. Expected: " + field + " Actual: " + query.getParsedQuery().getField(), - field.equals(query.getParsedQuery().getField())); - assertTrue("Unexpected query string in marshalled query. Expected: " + queryString + " Actual: " + query.getParsedQuery().getQueryString(), - queryString.equals(query.getParsedQuery().getQueryString())); - System.out.println("GDF: ES = " + ss.toElasticSearch()); - // Validate that we are able to produce the expected ElasticSearch - // query syntax from the search statement. - assertTrue("Unexpected ElasticSearch syntax. Expected: " + queryES + " Actual: " + ss.toElasticSearch(), - queryES.equals(ss.toElasticSearch())); - assertNull(ss.getAggregations()); - } - - @Test - public void filteredQueryTest() throws JsonParseException, JsonMappingException, IOException { - - String filterField1 = "field1"; - String filterField2 = "field2"; - String filterField3 = "field3"; - String filterValue1 = "a"; - String filterValue2 = "b"; - String filterValue3 = "string"; - String filterJson = "{ \"any\": [ " - + "{\"match\": {\"field\": \"" + filterField1 + "\", \"value\": \"" + filterValue1 + "\"}}," - + "{\"match\": {\"field\": \"" + filterField2 + "\", \"value\": \"" + filterValue2 + "\"}}" - + "]," - + "\"all\": [" - + "{\"parsed-query\": {\"field\": \"" + filterField3 + "\", \"query-string\": \"" + filterValue3 + "\"}}" - + "]" - + "}"; - - String filterStanzaJson = "\"filter\": " + filterJson; - - String queryStanzaJson = "\"queries\": [ " - + "{\"may\": {\"match\": {\"field\": \"searchTags\", \"value\": \"a\"}}}," - + "{\"may\": {\"match\": {\"field\": \"searchTags\", \"value\": \"b\"}}}," - + "{\"may\": {\"parsed-query\": {\"field\": \"fieldname\", \"query-string\": \"string\"}}}" - + "]"; - - String queryES = - "{" - + "\"version\": true," - + "\"query\": {" - + "\"bool\": {" - + "\"must\": [], " - + "\"should\": [" - + "{\"term\": {\"searchTags\" : \"a\"}}, " - + "{\"term\": {\"searchTags\" : \"b\"}}, " - + "{\"query_string\": {\"default_field\": \"fieldname\", \"query\": \"string\"}}" - + "]," - + "\"must_not\": [], " - + "\"filter\": {" - + "\"bool\": {" - + "\"must\": [" - + "{\"query_string\": {\"default_field\": \"field3\", \"query\": \"string\"}}" - + "]," - + "\"must_not\": []," - + "\"should\": [" - + "{\"term\": {\"field1\" : \"a\"}}, " - + "{\"term\": {\"field2\" : \"b\"}}" - + "]," - + "\"must_not\": []" - + "}" - + "}" - + "}" - + "}" - + "}"; - - StringBuilder sb = new StringBuilder(); - sb.append("{"); - sb.append(filterStanzaJson).append(", "); - sb.append(queryStanzaJson); - sb.append("}"); - - ObjectMapper mapper = new ObjectMapper(); - SearchStatement ss = mapper.readValue(sb.toString(), SearchStatement.class); - - assertEquals("Unexpected number of queries in the 'any' list for this statement's filter", - 2, ss.getFilter().getAny().length); - assertEquals("Unexpected number of queries in the 'all' list for this statement's filter", - 1, ss.getFilter().getAll().length); - - assertTrue("Unexpected ElasticSearch syntax. Expected: " + queryES + " Actual: " + ss.toElasticSearch(), - queryES.equals(ss.toElasticSearch())); - - assertNull(ss.getAggregations()); - } - - @Test - public void aggregationTest() { - String input = "{\r\n \"queries\": [\r\n {\r\n \"must\": {\r\n \"match\": {\r\n \"field\": \"searchTags\",\r\n \"value\": \"a\"\r\n }\r\n }\r\n }\r\n ],\r\n \"aggregations\": [\r\n {\r\n \"name\": \"byDate\",\r\n \"aggregation\": {\r\n \"date-range\": {\r\n \"field\": \"mydate\",\r\n \"ranges\": [\r\n {\r\n \"from\": \"2016-12-19T00:00:00.738-05:00\",\r\n \"to\": \"2016-12-23T23:59:59.738-05:00\"\r\n }\r\n ]\r\n },\r\n \"sub-aggregations\": [\r\n {\r\n \"name\": \"byTerm\",\r\n \"aggregation\": {\r\n \"group-by\": {\r\n \"field\": \"myterm\"\r\n }\r\n }\r\n },\r\n {\r\n \"name\": \"byDate\",\r\n \"aggregation\": {\r\n \"date-histogram\": {\r\n \"field\": \"myDate\",\r\n \"interval\": \"myInterval\"\r\n }\r\n }\r\n }\r\n ]\r\n }\r\n },\r\n {\r\n \"name\": \"2nd\",\r\n \"aggregation\": {\r\n \"group-by\": {\r\n \"field\": \"anotherTerm\"\r\n }\r\n }\r\n }\r\n ]\r\n}"; - - ObjectMapper mapper = new ObjectMapper(); - try { - SearchStatement ss = mapper.readValue(input, SearchStatement.class); - Aggregation[] aggs = ss.getAggregations(); - assertNotNull(aggs); - assertEquals("Unexpected number aggregations", 2, aggs.length); - assertEquals("byDate", aggs[0].getName()); - assertNotNull(aggs[0].getStatement().getDateRange()); - assertEquals("mydate", aggs[0].getStatement().getDateRange().getField()); - assertNotNull(aggs[0].getStatement().getSubAggregations()); - assertEquals(2, aggs[0].getStatement().getSubAggregations().length); - assertEquals("byTerm", aggs[0].getStatement().getSubAggregations()[0].getName()); - assertEquals("byDate", aggs[0].getStatement().getSubAggregations()[1].getName()); - assertNull(aggs[0].getStatement().getGroupBy()); - assertEquals("2nd", aggs[1].getName()); - assertNotNull(aggs[1].getStatement().getGroupBy()); - assertEquals("anotherTerm", aggs[1].getStatement().getGroupBy().getField()); - assertNull(aggs[1].getStatement().getDateRange()); - assertNull(aggs[1].getStatement().getSubAggregations()); - - } catch (Exception e) { - fail("Encountered exception: " + e.getMessage()); + @Test + public void simpleQueryTest() throws JsonParseException, JsonMappingException, IOException { + + String field = "searchTags"; + String queryString = "aai3255"; + String queryJson = "{" + "\"queries\": [" + "{\"may\": {\"parsed-query\": {" + "\"field\": \"" + field + "\"," + + "\"query-string\": \"" + queryString + "\"}}}" + "]" + "}" + "}"; + + String queryES = "{" + "\"version\": true," + "\"query\": {" + "\"bool\": {" + "\"must\": [], " + + "\"should\": [" + "{\"query_string\": {\"default_field\": \"searchTags\", \"query\": \"aai3255\"}}" + + "]," + "\"must_not\": []}" + "}" + "}"; + + // Marshal our simple query JSON to a SearchStatement object. + ObjectMapper mapper = new ObjectMapper(); + SearchStatement ss = mapper.readValue(queryJson, SearchStatement.class); + + // We expect to have a search statement with one query. + assertEquals("Unexpected number of queries in marshalled result", 1, ss.getQueries().length); + + // Validate that the query is of the expected type and contains the + // expected values. + QueryStatement query = ss.getQueries()[0].getQueryStatement(); + assertNotNull("Expected marshalled statement to contain a 'parsed query'", query.getParsedQuery()); + assertTrue("Unexpected field name in marshalled query. Expected: " + field + " Actual: " + + query.getParsedQuery().getField(), field.equals(query.getParsedQuery().getField())); + assertTrue( + "Unexpected query string in marshalled query. Expected: " + queryString + " Actual: " + + query.getParsedQuery().getQueryString(), + queryString.equals(query.getParsedQuery().getQueryString())); + + // Validate that we are able to produce the expected ElasticSearch + // query syntax from the search statement. + assertTrue("Unexpected ElasticSearch syntax. Expected: " + queryES + " Actual: " + ss.toElasticSearch(), + queryES.equals(ss.toElasticSearch())); } - } - @Test - public void resultSetRangeTest() throws IOException { - // Simple query with a result set subrange specified. - File queryWithSubrangeFile = new File("src/test/resources/json/queries/query-with-subrange.json"); - String queryWithSubrangeStr = TestUtils.readFileToString(queryWithSubrangeFile); - String queryWithSubrangeExpectedESString = - "{\"version\": true,\"from\": 0, \"size\": 10, \"query\": {\"bool\": {\"must\": [{\"term\": {\"field1\" : \"Bob\"}}], \"should\": [],\"must_not\": []}}}"; + @Test + public void simpleSortedQueryTest() throws JsonParseException, JsonMappingException, IOException { + + String field = "searchTags"; + String queryString = "aai3255"; + String queryJson = "{" + "\"queries\": [" + "{\"may\": {\"parsed-query\": {" + "\"field\": \"" + field + "\"," + + "\"query-string\": \"" + queryString + "\"}}}" + "]," + + "\"sort\": { \"field\": \"date\", \"order\": \"ascending\" }" + "}"; + + + String queryES = "{" + "\"version\": true," + "\"query\": {" + "\"bool\": {" + "\"must\": [], " + + "\"should\": [" + "{\"query_string\": {\"default_field\": \"searchTags\", \"query\": \"aai3255\"}}" + + "]," + "\"must_not\": []" + "}" + "}, " + "\"sort\": { \"date\": { \"order\": \"asc\"}}" + "}"; + + // Marshal our simple query JSON to a SearchStatement object. + ObjectMapper mapper = new ObjectMapper(); + SearchStatement ss = mapper.readValue(queryJson, SearchStatement.class); + + // We expect to have a search statement with one query. + assertEquals("Unexpected number of queries in marshalled result", 1, ss.getQueries().length); + + // Validate that the query is of the expected type and contains the + // expected values. + QueryStatement query = ss.getQueries()[0].getQueryStatement(); + assertNotNull("Expected marshalled statement to contain a 'parsed query'", query.getParsedQuery()); + assertTrue("Unexpected field name in marshalled query. Expected: " + field + " Actual: " + + query.getParsedQuery().getField(), field.equals(query.getParsedQuery().getField())); + assertTrue( + "Unexpected query string in marshalled query. Expected: " + queryString + " Actual: " + + query.getParsedQuery().getQueryString(), + queryString.equals(query.getParsedQuery().getQueryString())); + System.out.println("GDF: ES = " + ss.toElasticSearch()); + // Validate that we are able to produce the expected ElasticSearch + // query syntax from the search statement. + assertTrue("Unexpected ElasticSearch syntax. Expected: " + queryES + " Actual: " + ss.toElasticSearch(), + queryES.equals(ss.toElasticSearch())); + assertNull(ss.getAggregations()); + } + + @Test + public void filteredQueryTest() throws JsonParseException, JsonMappingException, IOException { + + String filterField1 = "field1"; + String filterField2 = "field2"; + String filterField3 = "field3"; + String filterValue1 = "a"; + String filterValue2 = "b"; + String filterValue3 = "string"; + String filterJson = "{ \"any\": [ " + "{\"match\": {\"field\": \"" + filterField1 + "\", \"value\": \"" + + filterValue1 + "\"}}," + "{\"match\": {\"field\": \"" + filterField2 + "\", \"value\": \"" + + filterValue2 + "\"}}" + "]," + "\"all\": [" + "{\"parsed-query\": {\"field\": \"" + filterField3 + + "\", \"query-string\": \"" + filterValue3 + "\"}}" + "]" + "}"; + + String filterStanzaJson = "\"filter\": " + filterJson; + + String queryStanzaJson = "\"queries\": [ " + + "{\"may\": {\"match\": {\"field\": \"searchTags\", \"value\": \"a\"}}}," + + "{\"may\": {\"match\": {\"field\": \"searchTags\", \"value\": \"b\"}}}," + + "{\"may\": {\"parsed-query\": {\"field\": \"fieldname\", \"query-string\": \"string\"}}}" + "]"; + + String queryES = "{" + "\"version\": true," + "\"query\": {" + "\"bool\": {" + "\"must\": [], " + + "\"should\": [" + "{\"term\": {\"searchTags\" : \"a\"}}, " + "{\"term\": {\"searchTags\" : \"b\"}}, " + + "{\"query_string\": {\"default_field\": \"fieldname\", \"query\": \"string\"}}" + "]," + + "\"must_not\": [], " + "\"filter\": {" + "\"bool\": {" + "\"must\": [" + + "{\"query_string\": {\"default_field\": \"field3\", \"query\": \"string\"}}" + "]," + + "\"must_not\": []," + "\"should\": [" + "{\"term\": {\"field1\" : \"a\"}}, " + + "{\"term\": {\"field2\" : \"b\"}}" + "]," + "\"must_not\": []" + "}" + "}" + "}" + "}" + "}"; + + StringBuilder sb = new StringBuilder(); + sb.append("{"); + sb.append(filterStanzaJson).append(", "); + sb.append(queryStanzaJson); + sb.append("}"); + + ObjectMapper mapper = new ObjectMapper(); + SearchStatement ss = mapper.readValue(sb.toString(), SearchStatement.class); + + assertEquals("Unexpected number of queries in the 'any' list for this statement's filter", 2, + ss.getFilter().getAny().length); + assertEquals("Unexpected number of queries in the 'all' list for this statement's filter", 1, + ss.getFilter().getAll().length); + + assertTrue("Unexpected ElasticSearch syntax. Expected: " + queryES + " Actual: " + ss.toElasticSearch(), + queryES.equals(ss.toElasticSearch())); + + assertNull(ss.getAggregations()); + } + + @Test + public void aggregationTest() { + String input = + "{\r\n \"queries\": [\r\n {\r\n \"must\": {\r\n \"match\": {\r\n \"field\": \"searchTags\",\r\n \"value\": \"a\"\r\n }\r\n }\r\n }\r\n ],\r\n \"aggregations\": [\r\n {\r\n \"name\": \"byDate\",\r\n \"aggregation\": {\r\n \"date-range\": {\r\n \"field\": \"mydate\",\r\n \"ranges\": [\r\n {\r\n \"from\": \"2016-12-19T00:00:00.738-05:00\",\r\n \"to\": \"2016-12-23T23:59:59.738-05:00\"\r\n }\r\n ]\r\n },\r\n \"sub-aggregations\": [\r\n {\r\n \"name\": \"byTerm\",\r\n \"aggregation\": {\r\n \"group-by\": {\r\n \"field\": \"myterm\"\r\n }\r\n }\r\n },\r\n {\r\n \"name\": \"byDate\",\r\n \"aggregation\": {\r\n \"date-histogram\": {\r\n \"field\": \"myDate\",\r\n \"interval\": \"myInterval\"\r\n }\r\n }\r\n }\r\n ]\r\n }\r\n },\r\n {\r\n \"name\": \"2nd\",\r\n \"aggregation\": {\r\n \"group-by\": {\r\n \"field\": \"anotherTerm\"\r\n }\r\n }\r\n }\r\n ]\r\n}"; + + ObjectMapper mapper = new ObjectMapper(); + try { + SearchStatement ss = mapper.readValue(input, SearchStatement.class); + Aggregation[] aggs = ss.getAggregations(); + assertNotNull(aggs); + assertEquals("Unexpected number aggregations", 2, aggs.length); + assertEquals("byDate", aggs[0].getName()); + assertNotNull(aggs[0].getStatement().getDateRange()); + assertEquals("mydate", aggs[0].getStatement().getDateRange().getField()); + assertNotNull(aggs[0].getStatement().getSubAggregations()); + assertEquals(2, aggs[0].getStatement().getSubAggregations().length); + assertEquals("byTerm", aggs[0].getStatement().getSubAggregations()[0].getName()); + assertEquals("byDate", aggs[0].getStatement().getSubAggregations()[1].getName()); + assertNull(aggs[0].getStatement().getGroupBy()); + assertEquals("2nd", aggs[1].getName()); + assertNotNull(aggs[1].getStatement().getGroupBy()); + assertEquals("anotherTerm", aggs[1].getStatement().getGroupBy().getField()); + assertNull(aggs[1].getStatement().getDateRange()); + assertNull(aggs[1].getStatement().getSubAggregations()); + + } catch (Exception e) { + fail("Encountered exception: " + e.getMessage()); + } + } + + @Test + public void resultSetRangeTest() throws IOException { - ObjectMapper mapper = new ObjectMapper(); - SearchStatement ss = mapper.readValue(queryWithSubrangeStr, SearchStatement.class); + // Simple query with a result set subrange specified. + File queryWithSubrangeFile = new File("src/test/resources/json/queries/query-with-subrange.json"); + String queryWithSubrangeStr = TestUtils.readFileToString(queryWithSubrangeFile); + String queryWithSubrangeExpectedESString = + "{\"version\": true,\"from\": 0, \"size\": 10, \"query\": {\"bool\": {\"must\": [{\"term\": {\"field1\" : \"Bob\"}}], \"should\": [],\"must_not\": []}}}"; - assertEquals("Unexpected index for result set start", ss.getFrom(), (Integer) 0); - assertEquals("Unexpected value for result set size", ss.getSize(), (Integer) 10); - assertTrue("Unexpected elastic search query generated from search statement", - ss.toElasticSearch().equals(queryWithSubrangeExpectedESString)); - } + ObjectMapper mapper = new ObjectMapper(); + SearchStatement ss = mapper.readValue(queryWithSubrangeStr, SearchStatement.class); + + assertEquals("Unexpected index for result set start", ss.getFrom(), (Integer) 0); + assertEquals("Unexpected value for result set size", ss.getSize(), (Integer) 10); + assertTrue("Unexpected elastic search query generated from search statement", + ss.toElasticSearch().equals(queryWithSubrangeExpectedESString)); + } } diff --git a/src/test/java/org/onap/aai/sa/searchdbabstraction/searchapi/SortTest.java b/src/test/java/org/onap/aai/sa/searchdbabstraction/searchapi/SortTest.java index 9b93a25..832fa98 100644 --- a/src/test/java/org/onap/aai/sa/searchdbabstraction/searchapi/SortTest.java +++ b/src/test/java/org/onap/aai/sa/searchdbabstraction/searchapi/SortTest.java @@ -30,20 +30,20 @@ import org.junit.Test; public class SortTest { - @Test - public void sortFieldTest() throws JsonParseException, JsonMappingException, IOException { + @Test + public void sortFieldTest() throws JsonParseException, JsonMappingException, IOException { - String field = "fieldname"; - String order = "ascending"; - String json = "{\"field\": \"" + field + "\", \"order\": \"" + order + "\"}"; + String field = "fieldname"; + String order = "ascending"; + String json = "{\"field\": \"" + field + "\", \"order\": \"" + order + "\"}"; - ObjectMapper mapper = new ObjectMapper(); - Sort sort = mapper.readValue(json, Sort.class); + ObjectMapper mapper = new ObjectMapper(); + Sort sort = mapper.readValue(json, Sort.class); - assertTrue("Unexpected field name in marshalled object. Expected: " + field + " Actual: " + sort.getField(), - field.equals(sort.getField())); - assertTrue("Unexpected order field in marshalled object. Expected: " + order + " Actual: " + sort.getOrder(), - order.equals(sort.getOrder().toString())); + assertTrue("Unexpected field name in marshalled object. Expected: " + field + " Actual: " + sort.getField(), + field.equals(sort.getField())); + assertTrue("Unexpected order field in marshalled object. Expected: " + order + " Actual: " + sort.getOrder(), + order.equals(sort.getOrder().toString())); - } + } } diff --git a/src/test/java/org/onap/aai/sa/searchdbabstraction/util/ElasticSearchPayloadTranslatorTest.java b/src/test/java/org/onap/aai/sa/searchdbabstraction/util/ElasticSearchPayloadTranslatorTest.java index 40209d6..877b64f 100644 --- a/src/test/java/org/onap/aai/sa/searchdbabstraction/util/ElasticSearchPayloadTranslatorTest.java +++ b/src/test/java/org/onap/aai/sa/searchdbabstraction/util/ElasticSearchPayloadTranslatorTest.java @@ -30,26 +30,26 @@ import org.junit.Before; import org.junit.Test; public class ElasticSearchPayloadTranslatorTest { - - private final String SIMPLE_DOC_SCHEMA_JSON = "src/test/resources/json/index-mapping.json"; - @Before - public void setup() throws Exception { - System.setProperty("CONFIG_HOME", System.getProperty("user.dir")+ File.separator + "src/test/resources/json"); - } - - @Test - public void testPayloadTranslation() throws Exception { - String expectedErrMsg = "Sample error message for whitespace check"; - File schemaFile = new File(SIMPLE_DOC_SCHEMA_JSON); - String documentJson = IOUtils.toString(new FileInputStream(schemaFile), "UTF-8"); - assertTrue(documentJson.contains("\"type\": \"string\"")); - assertTrue(documentJson.contains("\"index\": \"analyzed\"")); - String translatedPayload = ElasticSearchPayloadTranslator.translateESPayload(documentJson); - assertTrue(translatedPayload.contains("\"type\":\"text\"")); - assertTrue(translatedPayload.contains("\"index\":true")); - assertTrue(translatedPayload.contains("\"fielddata\":true")); - assertFalse(documentJson.contains("\"index\":\"analyzed\"")); - assertTrue(translatedPayload.contains("\"errMsg\":\""+expectedErrMsg+"\"")); - } + private final String SIMPLE_DOC_SCHEMA_JSON = "src/test/resources/json/index-mapping.json"; + + @Before + public void setup() throws Exception { + System.setProperty("CONFIG_HOME", System.getProperty("user.dir") + File.separator + "src/test/resources/json"); + } + + @Test + public void testPayloadTranslation() throws Exception { + String expectedErrMsg = "Sample error message for whitespace check"; + File schemaFile = new File(SIMPLE_DOC_SCHEMA_JSON); + String documentJson = IOUtils.toString(new FileInputStream(schemaFile), "UTF-8"); + assertTrue(documentJson.contains("\"type\": \"string\"")); + assertTrue(documentJson.contains("\"index\": \"analyzed\"")); + String translatedPayload = ElasticSearchPayloadTranslator.translateESPayload(documentJson); + assertTrue(translatedPayload.contains("\"type\":\"text\"")); + assertTrue(translatedPayload.contains("\"index\":true")); + assertTrue(translatedPayload.contains("\"fielddata\":true")); + assertFalse(documentJson.contains("\"index\":\"analyzed\"")); + assertTrue(translatedPayload.contains("\"errMsg\":\"" + expectedErrMsg + "\"")); + } } -- cgit 1.2.3-korg