Skip to content

Commit

Permalink
Rearrange test base classes for more reusable code (Azure#55)
Browse files Browse the repository at this point in the history
- General refactoring and rearrangements for tests.
- Adding readJsonFileToList() to JsonApi
  • Loading branch information
rabee333 authored Sep 8, 2019
1 parent 8229595 commit 71211e6
Show file tree
Hide file tree
Showing 60 changed files with 1,143 additions and 1,485 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,16 @@ public interface JsonApi {
*/
<T> List<T> readStringToList(String json, Type<List<T>> type);

/**
* Reads a json from file in the project's resources folder, and converts it to a list of objects.
* The json file must include a list of jsons (objects), that correspond to the type's class structure.
* @param fileName The json file name in resources folder
* @param type type to deserialize to
* @param <T> type to deserialize to
* @return list of objects of type T
*/
<T> List<T> readJsonFileToList(String fileName, Type<List<T>> type);

/**
* Convert an Object to instance of class T
* @param source source Object
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@
import com.fasterxml.jackson.databind.type.TypeFactory;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
Expand All @@ -29,6 +31,7 @@
public class JacksonDeserializer implements JsonApi {

private static final Map<Config, DeserializationFeature> CONFIG_MAP;

static {
CONFIG_MAP = new HashMap<>();

Expand Down Expand Up @@ -62,7 +65,8 @@ public <T> void registerCustomDeserializer(final Deserializer<T> deserializer) {
module.addDeserializer(deserializer.getRawType(), new com.fasterxml.jackson.databind.JsonDeserializer() {

@Override
public Object deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
public Object deserialize(JsonParser jsonParser, DeserializationContext deserializationContext)
throws IOException, JsonProcessingException {
ObjectCodec codec = jsonParser.getCodec();
JsonNode node = codec.readTree(jsonParser);
return deserializer.deserialize(new JacksonNode(node));
Expand All @@ -74,6 +78,7 @@ public Object deserialize(JsonParser jsonParser, DeserializationContext deserial

/**
* read json string convert to class type
*
* @param json input string
* @param cls class type
* @param <T> type
Expand Down Expand Up @@ -115,6 +120,22 @@ public <T> List<T> readStringToList(String json, Type<List<T>> type) {
return null;
}

@Override
public <T> List<T> readJsonFileToList(String fileName, Type<List<T>> type) {
assert type.isParameterizedType();

try {
Reader reader = new InputStreamReader(
getClass().getClassLoader().getResourceAsStream(fileName));

return objectMapper.readValue(reader, listTypeReference(type));
} catch (IOException e) {
e.printStackTrace();
}

return null;
}

private <T> CollectionType listTypeReference(Type<T> type) {
return typeFactory.constructCollectionType(List.class, typeFactory.constructType(type.getListType()));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,10 @@
package com.azure.search.data.customization.models;

import com.azure.core.implementation.annotation.Fluent;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Fluent
Expand All @@ -23,6 +20,11 @@ public class GeoPoint {
@JsonProperty("crs")
private CoordinateSystem coordinateSystem;

@JsonProperty
public String getType(){
return TYPE;
}

public List<Double> coordinates() {
return this.coordinates;
}
Expand All @@ -49,14 +51,6 @@ public static GeoPoint createWithDefaultCrs(double latitude, double longitude) {
return create(latitude, longitude).coordinateSystem(CoordinateSystem.create());
}

public Map createObjectMap() {
Map geoPointMap = new ObjectMapper()
.setSerializationInclusion(JsonInclude.Include.NON_NULL)
.convertValue(this, Map.class);
geoPointMap.put("type", TYPE);
return geoPointMap;
}

/**
* Ensures that the GeoPoint values are valid for the Geography Point type in Search Service.
*
Expand Down
1 change: 0 additions & 1 deletion sdk/search/azure-search-data/src/test/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,6 @@ Before running the tests on PLAYBACK mode, you need to run them on RECORD mode t
* AZURE_DOMAIN_ID: *Azure domain ID*
* AZURE_SUBSCRIPTION_ID: *Azure subscription ID*
* AZURE_TEST_MODE: **RECORD** *for recording* (**PLAYBACK** *for playback mode*)
* INDEX_FILE_NAME: *The json filename where the index configuration is stored (in the resources folder)*

2. Run the tests.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -104,8 +104,7 @@ public void canDeserializeGeoPoint() throws Exception {

@Test
public void canSerializeGeoPoint() {
Map geoPointMap = GeoPoint.create(100.0, 1.0).createObjectMap();
Map indexObjectMap = createGeoPointIndexMap("1", "test", geoPointMap);
Map indexObjectMap = createGeoPointIndexMap("1", "test", GeoPoint.create(100.0, 1.0));
DocumentIndexResult indexResult = client.setIndexName(INDEX_NAME_GEO_POINTS)
.index(new IndexBatch()
.actions(Collections.singletonList(new IndexAction()
Expand All @@ -127,11 +126,11 @@ private List<Map<String, Object>> getSearchResults(PagedIterable<SearchResult> r
return searchResults;
}

private Map<String, Object> createGeoPointIndexMap(String id, String name, Map geoPointMap) {
private Map<String, Object> createGeoPointIndexMap(String id, String name, GeoPoint geoPoint) {
Map<String, Object> indexObjectMap = new HashMap<>();
indexObjectMap.put("Id", id);
indexObjectMap.put("Name", name);
indexObjectMap.put("Location", geoPointMap);
indexObjectMap.put("Location", geoPoint);

return indexObjectMap;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,6 @@
import org.junit.Test;

import java.util.Collections;
import java.util.List;
import java.util.Map;

public class GeoPointUnitTests {
@Test
Expand Down Expand Up @@ -39,23 +37,6 @@ public void canCreateWithCrs() {
Assert.assertTrue(geoPoint.coordinateSystem().properties().get("name").startsWith("EPSG"));
}

@Test
public void canCreateMap() {
GeoPoint geoPoint = GeoPoint.create(100.0, 1.0);
Map geoPointMap = geoPoint.createObjectMap();

Assert.assertNotNull(geoPointMap);
Assert.assertTrue(geoPointMap.containsKey("type"));
Assert.assertEquals("Point", geoPointMap.get("type"));

Assert.assertTrue(geoPointMap.containsKey("coordinates"));
Assert.assertTrue(geoPointMap.get("coordinates") instanceof List);
List<Double> coordinates = (List) geoPointMap.get("coordinates");
Assert.assertEquals(2, coordinates.size());
Assert.assertEquals(100.0, coordinates.get(0), 0.0);
Assert.assertEquals(1.0, coordinates.get(1), 0.0);
}

@Test
public void canValidateWithCrs() {
GeoPoint geoPoint = GeoPoint.createWithDefaultCrs(100.0, 1.0);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,17 @@
import com.azure.core.exception.HttpResponseException;
import com.azure.core.exception.ResourceNotFoundException;
import com.azure.search.data.SearchIndexAsyncClient;
import com.azure.search.data.common.jsonwrapper.JsonWrapper;
import com.azure.search.data.common.jsonwrapper.api.JsonApi;
import com.azure.search.data.common.jsonwrapper.jacksonwrapper.JacksonDeserializer;
import com.azure.search.data.customization.models.GeoPoint;
import com.azure.search.data.env.SearchIndexClientTestBase;
import io.netty.handler.codec.http.HttpResponseStatus;
import org.junit.Assert;
import org.junit.Test;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
Expand All @@ -21,9 +25,10 @@

public class SearchIndexAsyncClientImplTest extends SearchIndexClientTestBase {

private SearchIndexAsyncClient asyncClient;

private static final CharSequence ERROR_MESSAGE_INVALID_FIELDS_REQUEST =
"Invalid expression: Could not find a property named 'ThisFieldDoesNotExist' on type 'search.document'.";
private static final String INDEX_NAME = "hotels";
private SearchIndexAsyncClient asyncClient;

@Override
protected void beforeTest() {
Expand All @@ -33,7 +38,7 @@ protected void beforeTest() {

@Test
public void canGetDynamicDocument() {

JsonApi jsonApi = JsonWrapper.newInstance(JacksonDeserializer.class);
Map<String, Object> addressDoc = new HashMap<String, Object>();
addressDoc.put("StreetAddress", "677 5th Ave");
addressDoc.put("City", "New York");
Expand Down Expand Up @@ -72,7 +77,6 @@ public void canGetDynamicDocument() {
rooms.add(room1Doc);
rooms.add(room2Doc);


ArrayList<String> tags = new ArrayList<String>();
tags.add("pool");
tags.add("air conditioning");
Expand All @@ -81,8 +85,17 @@ public void canGetDynamicDocument() {
HashMap<String, Object> expectedDoc = new HashMap<String, Object>();
expectedDoc.put("HotelId", "1");
expectedDoc.put("HotelName", "Secret Point Motel");
expectedDoc.put("Description", "The hotel is ideally located on the main commercial artery of the city in the heart of New York. A few minutes away is Time's Square and the historic centre of the city, as well as other places of interest that make New York one of America's most attractive and cosmopolitan cities.");
expectedDoc.put("Description_fr", "L'hôtel est idéalement situé sur la principale artère commerciale de la ville en plein cœur de New York. A quelques minutes se trouve la place du temps et le centre historique de la ville, ainsi que d'autres lieux d'intérêt qui font de New York l'une des villes les plus attractives et cosmopolites de l'Amérique.");
expectedDoc.put(
"Description",
"The hotel is ideally located on the main commercial artery of the city in the heart of New York. A few "
+ "minutes away is Time's Square and the historic centre of the city, as well as other places of "
+ "interest that make New York one of America's most attractive and cosmopolitan cities.");
expectedDoc.put(
"Description_fr",
"L'hôtel est idéalement situé sur la principale artère commerciale de la ville en plein cœur de New York."
+ " A quelques minutes se trouve la place du temps et le centre historique de la ville, ainsi que "
+ "d'autres lieux d'intérêt qui font de New York l'une des villes les plus attractives et cosmopolites "
+ "de l'Amérique.");
expectedDoc.put("Category", "Boutique");
expectedDoc.put("Tags", tags);
expectedDoc.put("ParkingIncluded", false);
Expand All @@ -91,22 +104,17 @@ public void canGetDynamicDocument() {
expectedDoc.put("Rating", 3);
expectedDoc.put("Address", addressDoc);
expectedDoc.put("Rooms", rooms);
expectedDoc.put("Location", GeoPoint.createWithDefaultCrs(40.760586, -73.975403).createObjectMap());
expectedDoc.put(
"Location",
jsonApi.convertObjectToType(GeoPoint.createWithDefaultCrs(40.760586, -73.975403), Map.class));

try {
super.indexDocument(asyncClient, expectedDoc);

} catch (Exception e) {
e.printStackTrace();
}
uploadDocuments(asyncClient, INDEX_NAME, expectedDoc);

Mono<Document> futureDoc = asyncClient.getDocument("1");

StepVerifier
.create(futureDoc)
.assertNext(result -> {
Assert.assertEquals(expectedDoc, result);
})
.assertNext(result -> Assert.assertEquals(expectedDoc, result))
.verifyComplete();
}

Expand All @@ -129,12 +137,7 @@ public void getDocumentThrowsWhenRequestIsMalformed() {
selectedFields.add("HotelId");
selectedFields.add("ThisFieldDoesNotExist");

try {
super.indexDocument(asyncClient, hotelDoc);

} catch (Exception e) {
e.printStackTrace();
}
uploadDocuments(asyncClient, INDEX_NAME, hotelDoc);

Mono futureDoc = asyncClient.getDocument("2", selectedFields, null);

Expand All @@ -143,8 +146,7 @@ public void getDocumentThrowsWhenRequestIsMalformed() {
.verifyErrorSatisfies(error -> {
assertEquals(HttpResponseException.class, error.getClass());
assertEquals(HttpResponseStatus.BAD_REQUEST.code(), ((HttpResponseException) error).response().statusCode());
assertTrue(error.getMessage().contains("Invalid expression: Could not find a property named 'ThisFieldDoesNotExist' on type 'search.document'."));
//TODO: Create Enum for messages
assertTrue(error.getMessage().contains(ERROR_MESSAGE_INVALID_FIELDS_REQUEST));
});
}
}

This file was deleted.

Loading

0 comments on commit 71211e6

Please sign in to comment.