[Android]Expand schema test, modify performance event (#14535)

* expand schema test, modify performance event

* enclose java doc

* revert int to long
This commit is contained in:
Kevin Li
2019-05-02 16:55:20 +08:00
committed by GitHub
parent 3e4afbc788
commit 386b013c5e
8 changed files with 287 additions and 336 deletions

View File

@@ -9,7 +9,7 @@ import com.mapbox.android.telemetry.Event;
* Base event class for telemetry events.
*/
@SuppressLint("ParcelCreator")
public abstract class MapBaseEvent extends Event {
abstract class MapBaseEvent extends Event {
private final String event;
private final String created;
@@ -20,11 +20,11 @@ public abstract class MapBaseEvent extends Event {
abstract String getEventName();
public String getEvent() {
String getEvent() {
return event;
}
public String getCreated() {
String getCreated() {
return created;
}

View File

@@ -1,5 +1,6 @@
package com.mapbox.mapboxsdk.module.telemetry;
import android.os.Bundle;
import android.support.annotation.FloatRange;
import android.support.annotation.NonNull;
@@ -35,8 +36,8 @@ class MapEventFactory {
@FloatRange(from = MapboxConstants.MINIMUM_ZOOM,
to = MapboxConstants.MAXIMUM_ZOOM) Double maxZoom,
String styleURL,
Long sizeOfResourcesCompleted,
Long numberOfTilesCompleted,
long sizeOfResourcesCompleted,
long numberOfTilesCompleted,
@OfflineRegion.DownloadState int state) {
OfflineDownloadEndEvent offlineEvent =
@@ -56,4 +57,9 @@ class MapEventFactory {
return new MapDragendEvent(phoneState, mapState);
}
static PerformanceEvent buildPerformanceEvent(@NonNull PhoneState phoneState, @NonNull String sessionId,
@NonNull Bundle data) {
return new PerformanceEvent(phoneState, sessionId, data);
}
}

View File

@@ -16,9 +16,9 @@ public class OfflineDownloadEndEvent extends MapBaseEvent {
private final Double maxZoom;
private final String shapeForOfflineRegion;
private String styleURL;
private String state;
private long sizeOfResourcesCompleted;
private long numberOfTilesCompleted;
private int state;
OfflineDownloadEndEvent(PhoneState phoneState, String shapeForOfflineRegion,
@FloatRange(from = MapboxConstants.MINIMUM_ZOOM,
@@ -72,12 +72,12 @@ public class OfflineDownloadEndEvent extends MapBaseEvent {
this.numberOfTilesCompleted = numberOfTilesCompleted;
}
int getState() {
String getState() {
return state;
}
void setState(@OfflineRegion.DownloadState int state) {
this.state = state;
this.state = String.valueOf(state);
}
@Override
@@ -97,20 +97,20 @@ public class OfflineDownloadEndEvent extends MapBaseEvent {
if (numberOfTilesCompleted != that.numberOfTilesCompleted) {
return false;
}
if (state != that.state) {
return false;
}
if (minZoom != null ? !minZoom.equals(that.minZoom) : that.minZoom != null) {
return false;
}
if (maxZoom != null ? !maxZoom.equals(that.maxZoom) : that.maxZoom != null) {
return false;
}
if (shapeForOfflineRegion != null ? !shapeForOfflineRegion.equals(that.shapeForOfflineRegion) :
that.shapeForOfflineRegion != null) {
if (shapeForOfflineRegion != null ? !shapeForOfflineRegion.equals(that.shapeForOfflineRegion)
: that.shapeForOfflineRegion != null) {
return false;
}
return styleURL != null ? styleURL.equals(that.styleURL) : that.styleURL == null;
if (styleURL != null ? !styleURL.equals(that.styleURL) : that.styleURL != null) {
return false;
}
return state != null ? state.equals(that.state) : that.state == null;
}
@Override
@@ -119,9 +119,9 @@ public class OfflineDownloadEndEvent extends MapBaseEvent {
result = 31 * result + (maxZoom != null ? maxZoom.hashCode() : 0);
result = 31 * result + (shapeForOfflineRegion != null ? shapeForOfflineRegion.hashCode() : 0);
result = 31 * result + (styleURL != null ? styleURL.hashCode() : 0);
result = 31 * result + (state != null ? state.hashCode() : 0);
result = 31 * result + (int) (sizeOfResourcesCompleted ^ (sizeOfResourcesCompleted >>> 32));
result = 31 * result + (int) (numberOfTilesCompleted ^ (numberOfTilesCompleted >>> 32));
result = 31 * result + state;
return result;
}

View File

@@ -1,116 +1,71 @@
package com.mapbox.mapboxsdk.module.telemetry;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.mapbox.android.telemetry.Event;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Parcel;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
/**
* Generic Performance Event that can be used for performance measurements.
* Customer measurements can be added to the bundle.
*
* <p>
* Bundle is expected to have following properties:
* "attributes", "counters", and "metadata" with String values.
*
* </p>
* <p>
* Attributes: a string representing an array of name/string value pair objects.
* Counters: a string representing an array of name/number value pair objects.
* Metadata is a string representation of a JsonObject with string values.
*
* Here is an example of a Performance event bundle data:
*
* </p>
* <p>
* Here is an example of a Performance event bundle data:
* </p>
* <p>
* "attributes": [{ "name": "style_id", "value": "mapbox://styles/mapbox/streets-v10"}]
*
* </p>
* <p>
* "counters": [{"name": "fps_average", "value": 90.7655486547093},
* {"name": "fps_deviation", "value": 29.301809631465574}]
* {"name": "fps_deviation", "value": 29.301809631465574}]
* “metadata”: {
* “version”: “9”,
* “screenSize”: “1080x1794”,
* “country”: “US”,
* “device”: “Pixel 2”,
* “abi”: “arm64-v8a”,
* “brand”: “google”,
* “ram”: “3834167296”,
* “os”: “android”,
* “gpu”: “Qualcomm, Adreno (TM) 540, OpenGL ES 3.2 V@313.0 (GIT@7bf2852, Ie32bfa6f6f)“,
* “manufacturer”: “Google”
* }
* “version”: “9”,
* “screenSize”: “1080x1794”,
* “country”: “US”,
* “device”: “Pixel 2”,
* “abi”: “arm64-v8a”,
* “brand”: “google”,
* “ram”: “3834167296”,
* “os”: “android”,
* “gpu”: “Qualcomm, Adreno (TM) 540, OpenGL ES 3.2 V@313.0 (GIT@7bf2852, Ie32bfa6f6f)“,
* “manufacturer”: “Google”
* }
* </p>
*/
public class PerformanceEvent extends Event {
@SuppressLint("ParcelCreator")
class PerformanceEvent extends MapBaseEvent {
private static final String PERFORMANCE_TRACE = "mobile.performance_trace";
private final String event;
private final String created;
private final String sessionId;
private final List<Attribute<String>> attributes;
private final List<Attribute<Double>> counters;
private final List<PerformanceAttribute<String>> attributes;
private final List<PerformanceAttribute<Double>> counters;
private final JsonObject metadata;
private static final SimpleDateFormat DATE_FORMAT =
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ", Locale.US);
PerformanceEvent(String sessionId, Bundle bundle) {
this.event = PERFORMANCE_TRACE;
this.created = DATE_FORMAT.format(new Date());
PerformanceEvent(PhoneState phoneState, String sessionId, Bundle bundle) {
super(phoneState);
this.sessionId = sessionId;
this.attributes = initList(bundle.getString("attributes"),
new TypeToken<ArrayList<Attribute<String>>>() {});
new TypeToken<ArrayList<PerformanceAttribute<String>>>() {
});
this.counters = initList(bundle.getString("counters"),
new TypeToken<ArrayList<Attribute<Double>>>() {});
new TypeToken<ArrayList<PerformanceAttribute<Double>>>() {
});
this.metadata = initMetaData(bundle.getString("metadata"));
}
private PerformanceEvent(Parcel in) {
this.event = in.readString();
this.created = in.readString();
this.sessionId = in.readString();
this.attributes = initList(in.readString(), new TypeToken<ArrayList<Attribute<String>>>() {});
this.counters = initList(in.readString(), new TypeToken<ArrayList<Attribute<Double>>>() {});
this.metadata = initMetaData(in.readString());
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(event);
parcel.writeString(created);
parcel.writeString(sessionId);
Gson gson = new Gson();
parcel.writeString(gson.toJson(attributes));
parcel.writeString(gson.toJson(counters));
if (metadata != null) {
parcel.writeString(metadata.toString());
}
}
private <T> ArrayList<Attribute<T>> initList(String fromString, TypeToken typeToken) {
private <T> ArrayList<PerformanceAttribute<T>> initList(String fromString, TypeToken typeToken) {
if (fromString == null || fromString.isEmpty()) {
return new ArrayList<>();
}
@@ -125,26 +80,100 @@ public class PerformanceEvent extends Event {
}
}
public static final Creator<PerformanceEvent> CREATOR = new Creator<PerformanceEvent>() {
@Override
public PerformanceEvent createFromParcel(Parcel in) {
return new PerformanceEvent(in);
@Override
String getEventName() {
return PERFORMANCE_TRACE;
}
String getSessionId() {
return sessionId;
}
List<PerformanceAttribute<String>> getAttributes() {
return attributes;
}
List<PerformanceAttribute<Double>> getCounters() {
return counters;
}
JsonObject getMetadata() {
return metadata;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
@Override
public PerformanceEvent[] newArray(int size) {
return new PerformanceEvent[size];
PerformanceEvent that = (PerformanceEvent) o;
if (sessionId != null ? !sessionId.equals(that.sessionId) : that.sessionId != null) {
return false;
}
};
if (attributes != null ? !attributes.equals(that.attributes) : that.attributes != null) {
return false;
}
if (counters != null ? !counters.equals(that.counters) : that.counters != null) {
return false;
}
return metadata != null ? metadata.equals(that.metadata) : that.metadata == null;
}
@Override
public int hashCode() {
int result = sessionId != null ? sessionId.hashCode() : 0;
result = 31 * result + (attributes != null ? attributes.hashCode() : 0);
result = 31 * result + (counters != null ? counters.hashCode() : 0);
result = 31 * result + (metadata != null ? metadata.hashCode() : 0);
return result;
}
private class Attribute<T> {
@Override
public String toString() {
return "PerformanceEvent{"
+ "sessionId='" + sessionId + '\''
+ ", attributes=" + attributes
+ ", counters=" + counters
+ ", metadata=" + metadata
+ '}';
}
static class PerformanceAttribute<T> {
private final String name;
private final T value;
Attribute(String name, T value) {
PerformanceAttribute(String name, T value) {
this.name = name;
this.value = value;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
PerformanceAttribute<?> that = (PerformanceAttribute<?>) o;
if (name != null ? !name.equals(that.name) : that.name != null) {
return false;
}
return value != null ? value.equals(that.value) : that.value == null;
}
@Override
public int hashCode() {
int result = name != null ? name.hashCode() : 0;
result = 31 * result + (value != null ? value.hashCode() : 0);
return result;
}
}
}

View File

@@ -115,6 +115,7 @@ public class TelemetryImpl implements TelemetryDefinition {
if (data == null) {
data = new Bundle();
}
telemetry.push(new PerformanceEvent(UUID.randomUUID().toString(), data));
telemetry.push(MapEventFactory.buildPerformanceEvent(new PhoneState(appContext),
UUID.randomUUID().toString(), data));
}
}

View File

@@ -1,8 +1,10 @@
package com.mapbox.mapboxsdk.module.telemetry;
import android.os.Build;
import android.os.Bundle;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.mapbox.mapboxsdk.BuildConfig;
import com.mapbox.mapboxsdk.constants.TelemetryConstants;
import com.mapbox.mapboxsdk.offline.OfflineRegion;
@@ -10,8 +12,15 @@ import com.mapbox.mapboxsdk.offline.OfflineRegion;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import static com.mapbox.mapboxsdk.module.telemetry.PerformanceEvent.PerformanceAttribute;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class MapEventFactoryTest {
private static final float FONT_SCALE = 1.f;
@@ -29,9 +38,10 @@ public class MapEventFactoryTest {
private static final Double MIN_ZOOM = 1.0;
private static final Double MAX_ZOOM = 10.0;
private static final String STYLE_URL = "style url";
private static final long SIZE_OF_RESOURCES_COMPLETED = 100L;
private static final long NUMBER_OF_TILE_COMPLETED = 1000L;
private static final long SIZE_OF_RESOURCES_COMPLETED = 100;
private static final long NUMBER_OF_TILE_COMPLETED = 1000;
private static final int STATE = OfflineRegion.STATE_ACTIVE;
private static final String SESSION_ID = "001";
private MapState mapState;
private PhoneState phoneState;
@@ -121,7 +131,7 @@ public class MapEventFactoryTest {
assertEquals(STYLE_URL, offlineDownloadEndEvent.getStyleURL());
assertEquals(SIZE_OF_RESOURCES_COMPLETED, offlineDownloadEndEvent.getSizeOfResourcesCompleted());
assertEquals(NUMBER_OF_TILE_COMPLETED, offlineDownloadEndEvent.getNumberOfTilesCompleted());
assertEquals(STATE, offlineDownloadEndEvent.getState());
assertEquals(String.valueOf(STATE), offlineDownloadEndEvent.getState());
assertEquals(CREATED, offlineDownloadEndEvent.getCreated());
String json = gson.toJson(offlineDownloadEndEvent);
OfflineDownloadEndEvent event = gson.fromJson(json, OfflineDownloadEndEvent.class);
@@ -141,4 +151,44 @@ public class MapEventFactoryTest {
OfflineDownloadStartEvent event = gson.fromJson(json, OfflineDownloadStartEvent.class);
assertEquals(offlineDownloadStartEvent, event);
}
@Test
public void testPerformanceEvent() {
String nameAttribute = "nameAttribute";
String valueAttribute = "100";
String nameCounters = "nameCounters";
Double valuesCounters = 1000.0;
JsonObject metaData = new JsonObject();
metaData.addProperty("os", "android");
metaData.addProperty("manufacturer", Build.MANUFACTURER);
metaData.addProperty("brand", Build.BRAND);
metaData.addProperty("device", Build.MODEL);
metaData.addProperty("version", Build.VERSION.RELEASE);
metaData.addProperty("abi", Build.CPU_ABI);
metaData.addProperty("country", Locale.getDefault().getISO3Country());
metaData.addProperty("ram", "ram");
metaData.addProperty("screenSize", "1000");
Bundle data = mock(Bundle.class);
ArrayList<PerformanceEvent.PerformanceAttribute<String>> attribtueList = new ArrayList<>();
PerformanceAttribute<String> attribute = new PerformanceAttribute<>(nameAttribute, valueAttribute);
attribtueList.add(attribute);
ArrayList<PerformanceEvent.PerformanceAttribute<Double>> countersList = new ArrayList<>();
PerformanceAttribute<Double> counter = new PerformanceAttribute<>(nameCounters, valuesCounters);
countersList.add(counter);
when(data.getString("attributes")).thenReturn(gson.toJson(attribtueList));
when(data.getString("counters")).thenReturn(gson.toJson(countersList));
when(data.getString("metadata")).thenReturn(metaData.toString());
PerformanceEvent performanceEvent = MapEventFactory.buildPerformanceEvent(phoneState,
SESSION_ID, data);
assertEquals(CREATED, performanceEvent.getCreated());
assertEquals(metaData.toString(), performanceEvent.getMetadata().toString());
assertEquals(SESSION_ID, performanceEvent.getSessionId());
List<PerformanceEvent.PerformanceAttribute<String>> attributeList = performanceEvent.getAttributes();
assertEquals(1, attribtueList.size());
assertEquals(attribute, attribtueList.get(0));
List<PerformanceEvent.PerformanceAttribute<Double>> counterList = performanceEvent.getCounters();
assertEquals(1, counterList.size());
assertEquals(counter, counterList.get(0));
}
}

View File

@@ -31,6 +31,9 @@ public class SchemaTest {
private static final String MAP_CLICK = "map.click";
private static final String MAP_DRAG = "map.dragend";
private static final String MAP_LOAD = "map.load";
private static final String MAP_PERFORMANCE = "mobile.performance_trace";
private static final String OFFLINE_DOWNLOAD_END = "map.offlineDownload.end";
private static final String OFFLINE_DOWNLOAD_START = "map.offlineDownload.start";
private static ArrayList<JsonObject> schemaArray;
@BeforeClass
@@ -38,8 +41,31 @@ public class SchemaTest {
unpackSchemas();
}
private static ByteArrayInputStream getFileBytes() throws IOException {
InputStream inputStream = SchemaTest.class.getClassLoader().getResourceAsStream("mobile-event-schemas.jsonl.gz");
byte[] byteOut = IOUtils.toByteArray(inputStream);
return new ByteArrayInputStream(byteOut);
}
private static void unpackSchemas() throws IOException {
ByteArrayInputStream bais = getFileBytes();
GZIPInputStream gzis = new GZIPInputStream(bais);
InputStreamReader reader = new InputStreamReader(gzis);
BufferedReader in = new BufferedReader(reader);
schemaArray = new ArrayList<>();
Gson gson = new Gson();
String readed;
while ((readed = in.readLine()) != null) {
JsonObject schema = gson.fromJson(readed, JsonObject.class);
schemaArray.add(schema);
}
}
@Test
public void checkMapClickEventSize() throws Exception {
public void checkMapClickEventSize() {
JsonObject schema = grabSchema(MAP_CLICK);
List<Field> fields = grabClassFields(MapClickEvent.class);
@@ -47,7 +73,7 @@ public class SchemaTest {
}
@Test
public void checkMapClickEventFields() throws Exception {
public void checkMapClickEventFields() {
JsonObject schema = grabSchema(MAP_CLICK);
List<Field> fields = grabClassFields(MapClickEvent.class);
@@ -55,7 +81,7 @@ public class SchemaTest {
}
@Test
public void checkMapDragEndEventSize() throws Exception {
public void checkMapDragEndEventSize() {
JsonObject schema = grabSchema(MAP_DRAG);
List<Field> fields = grabClassFields(MapDragendEvent.class);
@@ -63,7 +89,7 @@ public class SchemaTest {
}
@Test
public void checkMapDragEndEventFields() throws Exception {
public void checkMapDragEndEventFields() {
JsonObject schema = grabSchema(MAP_DRAG);
List<Field> fields = grabClassFields(MapDragendEvent.class);
@@ -71,19 +97,66 @@ public class SchemaTest {
}
@Test
public void checkMapLoadEventSize() throws Exception {
JsonObject schema = grabSchema(MAP_LOAD);
List<Field> fields = grabClassFields(MapLoadEvent.class);
public void checkOfflineDownloadEndEventSize() {
JsonObject schema = grabSchema(OFFLINE_DOWNLOAD_END);
List<Field> fields = grabClassFields(OfflineDownloadEndEvent.class);
//FIXME: this assertion is invalid: we should introduce a concept of mandatory/optional field to schema validation
//assertEquals(schema.size(), fields.size());
assertEquals(schema.size(), fields.size());
}
@Test
public void checkMapLoadEventFields() throws Exception {
public void checkOfflineDownloadEndEventFields() {
JsonObject schema = grabSchema(OFFLINE_DOWNLOAD_END);
List<Field> fields = grabClassFields(OfflineDownloadEndEvent.class);
schemaContainsFields(schema, fields);
}
@Test
public void checkOfflineDownloadStartEventSize() {
JsonObject schema = grabSchema(OFFLINE_DOWNLOAD_START);
List<Field> fields = grabClassFields(OfflineDownloadStartEvent.class);
assertEquals(schema.size(), fields.size());
}
@Test
public void checkOfflineDownloadStartEventFields() {
JsonObject schema = grabSchema(OFFLINE_DOWNLOAD_START);
List<Field> fields = grabClassFields(OfflineDownloadStartEvent.class);
schemaContainsFields(schema, fields);
}
@Test
public void checkMapLoadEventSize() {
JsonObject schema = grabSchema(MAP_LOAD);
List<Field> fields = grabClassFields(MapLoadEvent.class);
assertEquals(schema.size(), fields.size());
}
@Test
public void checkMapLoadEventFields() {
JsonObject schema = grabSchema(MAP_LOAD);
List<Field> fields = grabClassFields(MapLoadEvent.class);
schemaContainsFields(schema, fields);
}
@Test
public void checkPerformanceEventSize() {
JsonObject schema = grabSchema(MAP_PERFORMANCE);
List<Field> fields = grabClassFields(PerformanceEvent.class);
assertEquals(schema.size(), fields.size());
}
@Test
public void checkPerformanceEventFields() {
JsonObject schema = grabSchema(MAP_PERFORMANCE);
List<Field> fields = grabClassFields(PerformanceEvent.class);
schemaContainsFields(schema, fields);
}
@@ -139,14 +212,17 @@ public class SchemaTest {
private void typesMatch(JsonObject schema, String type) {
if (type.equalsIgnoreCase("int") || type.equalsIgnoreCase("integer")
|| type.equalsIgnoreCase("double") || type.equalsIgnoreCase("float")) {
|| type.equalsIgnoreCase("double") || type.equalsIgnoreCase("float")
|| type.equalsIgnoreCase("long")) {
type = "number";
}
if (type.contains("[]")) {
if (type.contains("[]") || type.equalsIgnoreCase("list")) {
type = "array";
}
if (type.equalsIgnoreCase("jsonobject")) {
type = "object";
}
Class<? extends JsonElement> typeClass = schema.get("type").getClass();
JsonElement jsonElement = new JsonParser().parse(type.toLowerCase());
@@ -159,29 +235,6 @@ public class SchemaTest {
}
}
private static ByteArrayInputStream getFileBytes() throws IOException {
InputStream inputStream = SchemaTest.class.getClassLoader().getResourceAsStream("mobile-event-schemas.jsonl.gz");
byte[] byteOut = IOUtils.toByteArray(inputStream);
return new ByteArrayInputStream(byteOut);
}
private static void unpackSchemas() throws IOException {
ByteArrayInputStream bais = getFileBytes();
GZIPInputStream gzis = new GZIPInputStream(bais);
InputStreamReader reader = new InputStreamReader(gzis);
BufferedReader in = new BufferedReader(reader);
schemaArray = new ArrayList<>();
Gson gson = new Gson();
String readed;
while ((readed = in.readLine()) != null) {
JsonObject schema = gson.fromJson(readed, JsonObject.class);
schemaArray.add(schema);
}
}
private JsonObject grabSchema(String eventName) {
for (JsonObject thisSchema : schemaArray) {
String name = thisSchema.get("name").getAsString();

View File

@@ -1,188 +0,0 @@
package com.mapbox.mapboxsdk.module.telemetry;
import android.app.ActivityManager;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcel;
import android.support.test.runner.AndroidJUnit4;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.WindowManager;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.mapbox.mapboxsdk.Mapbox;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.UUID;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
@RunWith(AndroidJUnit4.class)
public class PerformanceEventTest {
@Test
public void checksPerformanceEventWithMetaData() throws Exception {
PerformanceEvent event = obtainPerformanceEvent();
assertNotNull(event);
Parcel parcel = Parcel.obtain();
event.writeToParcel(parcel, 0);
parcel.setDataPosition(0);
PerformanceEvent newPerfEvent = PerformanceEvent.CREATOR.createFromParcel(parcel);
assertNotNull(newPerfEvent);
compare(event, newPerfEvent, "attributes", "style_id");
compare(event, newPerfEvent, "counters", "int_value");
compare(event, newPerfEvent, "counters", "long_value");
compare(event, newPerfEvent, "counters", "double_value");
assertEquals(getMetadata(event), getMetadata(newPerfEvent));
}
@Test
public void checksPerformanceEventOnlyRequiredData() throws Exception {
Bundle bundle = new Bundle();
bundle.putString("property ignored", "value will be ignored");
PerformanceEvent event = new PerformanceEvent(UUID.randomUUID().toString(), bundle);
assertNotNull(event);
Parcel parcel = Parcel.obtain();
event.writeToParcel(parcel, 0);
parcel.setDataPosition(0);
PerformanceEvent newPerfEvent = PerformanceEvent.CREATOR.createFromParcel(parcel);
assertNotNull(newPerfEvent);
assertEquals(getAttributes(event).size(), 0);
assertEquals(getCounters(event).size(), 0);
assertEquals(getAttributes(newPerfEvent).size(), 0);
assertEquals(getCounters(newPerfEvent).size(), 0);
assertEquals(getMetadata(event), getMetadata(newPerfEvent));
}
private PerformanceEvent obtainPerformanceEvent() {
String styleStr = "mapbox://styles/mapbox/streets-v11";
boolean testPerfEvent = true;
Double doubleValue = 40.5;
Long longValue = 40L;
Integer intValue = 40;
List<Attribute<String>> attributes = new ArrayList<>();
attributes.add(
new Attribute<>("style_id", styleStr));
attributes.add(
new Attribute<>("test_perf_event", String.valueOf(testPerfEvent)));
List<Attribute<? extends Number>> counters = new ArrayList();
counters.add(new Attribute<>("long_value", longValue));
counters.add(new Attribute<>("double_value", doubleValue));
counters.add(new Attribute<>("int_value", intValue));
Gson gson = new Gson();
Bundle bundle = new Bundle();
bundle.putString("attributes", gson.toJson(attributes));
bundle.putString("counters", gson.toJson(counters));
JsonObject metaData = new JsonObject();
metaData.addProperty("os", "android");
metaData.addProperty("manufacturer", Build.MANUFACTURER);
metaData.addProperty("brand", Build.BRAND);
metaData.addProperty("device", Build.MODEL);
metaData.addProperty("version", Build.VERSION.RELEASE);
metaData.addProperty("abi", Build.CPU_ABI);
metaData.addProperty("country", Locale.getDefault().getISO3Country());
metaData.addProperty("ram", getRam());
metaData.addProperty("screenSize", getWindowSize());
bundle.putString("metadata", metaData.toString());
return new PerformanceEvent(UUID.randomUUID().toString(), bundle);
}
private void compare(PerformanceEvent event1, PerformanceEvent event2, String listFieldName, String name)
throws NoSuchFieldException, IllegalAccessException {
Object value1 = getValue(event1, listFieldName, name);
Object value2 = getValue(event2, listFieldName, name);
if (value1 instanceof Double && value2 instanceof Double) {
assertEquals((Double)value1, (Double)value2, 0.00006);
} else {
assertEquals(value1, value2);
}
}
private Object getPrivateFieldValue(Object object, String fieldName)
throws NoSuchFieldException, IllegalAccessException {
Field field = object.getClass().getDeclaredField(fieldName);
field.setAccessible(true);
return field.get(object);
}
private Object getValue(PerformanceEvent event, String listFieldName, String name)
throws NoSuchFieldException, IllegalAccessException {
ArrayList list = (ArrayList)getPrivateFieldValue(event, listFieldName);
for (Object element : list) {
Object elementName = getPrivateFieldValue(element, "name");
if (elementName != null && elementName.equals((String)name)) {
return getPrivateFieldValue(element, "value");
}
}
return null;
}
private JsonObject getMetadata(PerformanceEvent event)
throws NoSuchFieldException, IllegalAccessException {
return (JsonObject)getPrivateFieldValue(event, "metadata");
}
private ArrayList getAttributes(PerformanceEvent event)
throws NoSuchFieldException, IllegalAccessException {
return (ArrayList)getPrivateFieldValue(event, "attributes");
}
private ArrayList getCounters(PerformanceEvent event)
throws NoSuchFieldException, IllegalAccessException {
return (ArrayList)getPrivateFieldValue(event, "counters");
}
private static String getRam() {
ActivityManager actManager =
(ActivityManager) Mapbox.getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
ActivityManager.MemoryInfo memInfo = new ActivityManager.MemoryInfo();
actManager.getMemoryInfo(memInfo);
return String.valueOf(memInfo.totalMem);
}
private static String getWindowSize() {
WindowManager windowManager =
(WindowManager) Mapbox.getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
Display display = windowManager.getDefaultDisplay();
DisplayMetrics metrics = new DisplayMetrics();
display.getMetrics(metrics);
int width = metrics.widthPixels;
int height = metrics.heightPixels;
return "{" + width + "," + height + "}";
}
private class Attribute<T> {
private String name;
private T value;
Attribute(String name, T value) {
this.name = name;
this.value = value;
}
}
}