mirror of
https://codeberg.org/OpenTracksApp/OpenTracks.git
synced 2026-10-08 04:13:06 +02:00
Patch 3 CLs from
http://code.google.com/r/rdamazio-mytracks-staging2/ - 7781a7c23cf1 - 883427ab11f8 - d801f8f7c16b - Use Halo them for api level 11 or higher. - Use action bar for api level 11 or higher. - Move all menu items for the 3 tabs to MenuManager.
This commit is contained in:
@@ -0,0 +1,53 @@
|
||||
/*
|
||||
* Copyright 2012 Google Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
|
||||
* use this file except in compliance with the License. You may obtain a copy of
|
||||
* the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
|
||||
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
|
||||
* License for the specific language governing permissions and limitations under
|
||||
* the License.
|
||||
*/
|
||||
package com.google.android.apps.mytracks;
|
||||
|
||||
import com.google.android.maps.mytracks.R;
|
||||
|
||||
import android.test.AndroidTestCase;
|
||||
|
||||
/**
|
||||
* Tests for the AntPreference.
|
||||
*
|
||||
* @author Youtao Liu
|
||||
*/
|
||||
public class AntPreferenceTest extends AndroidTestCase {
|
||||
|
||||
public void testNotPaired() {
|
||||
|
||||
AntPreference antPreference = new AntPreference(getContext()) {
|
||||
@Override
|
||||
protected int getPersistedInt(int defaultReturnValue) {
|
||||
return 0;
|
||||
}
|
||||
};
|
||||
assertEquals(getContext().getString(R.string.settings_sensor_ant_not_paired),
|
||||
antPreference.getSummary());
|
||||
}
|
||||
|
||||
public void testPaired() {
|
||||
int persistInt = 1;
|
||||
AntPreference antPreference = new AntPreference(getContext()) {
|
||||
@Override
|
||||
protected int getPersistedInt(int defaultReturnValue) {
|
||||
return 1;
|
||||
}
|
||||
};
|
||||
assertEquals(
|
||||
getContext().getString(R.string.settings_sensor_ant_paired, persistInt),
|
||||
antPreference.getSummary());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
/*
|
||||
* Copyright 2012 Google Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
|
||||
* use this file except in compliance with the License. You may obtain a copy of
|
||||
* the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
|
||||
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
|
||||
* License for the specific language governing permissions and limitations under
|
||||
* the License.
|
||||
*/
|
||||
package com.google.android.apps.mytracks;
|
||||
|
||||
import com.google.android.apps.mytracks.services.TrackRecordingService;
|
||||
|
||||
import android.app.ActivityManager;
|
||||
import android.app.ActivityManager.RunningServiceInfo;
|
||||
import android.content.ComponentName;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.test.AndroidTestCase;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Tests for the BootReceiver.
|
||||
*
|
||||
* @author Youtao Liu
|
||||
*/
|
||||
public class BootReceiverTest extends AndroidTestCase {
|
||||
private static final String SERVICE_NAME = "com.google.android.apps.mytracks.services.TrackRecordingService";
|
||||
|
||||
/**
|
||||
* Tests the behavior when receive notification which is the phone boot.
|
||||
*/
|
||||
public void testOnReceive_startService() {
|
||||
// Make sure no TrackRecordingService
|
||||
Intent stopIntent = new Intent(getContext(), TrackRecordingService.class);
|
||||
getContext().stopService(stopIntent);
|
||||
assertFalse(isServiceExisted(getContext(), SERVICE_NAME));
|
||||
|
||||
BootReceiver bootReceiver = new BootReceiver();
|
||||
Intent intent = new Intent();
|
||||
intent.setAction(Intent.ACTION_BOOT_COMPLETED);
|
||||
bootReceiver.onReceive(getContext(), intent);
|
||||
// Check if the service is started
|
||||
assertTrue(isServiceExisted(getContext(), SERVICE_NAME));
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the behavior when receive notification which is not the phone boot.
|
||||
*/
|
||||
public void testOnReceive_noStartService() {
|
||||
// Make sure no TrackRecordingService
|
||||
Intent stopIntent = new Intent(getContext(), TrackRecordingService.class);
|
||||
getContext().stopService(stopIntent);
|
||||
assertFalse(isServiceExisted(getContext(), SERVICE_NAME));
|
||||
|
||||
BootReceiver bootReceiver = new BootReceiver();
|
||||
Intent intent = new Intent();
|
||||
intent.setAction(Intent.ACTION_BUG_REPORT);
|
||||
bootReceiver.onReceive(getContext(), intent);
|
||||
// Check if the service is not started
|
||||
assertFalse(isServiceExisted(getContext(), SERVICE_NAME));
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if a service is started in a context.
|
||||
*
|
||||
* @param context the context for checking a service
|
||||
* @param serviceName the service name to find if existed
|
||||
*/
|
||||
private boolean isServiceExisted(Context context, String serviceName) {
|
||||
ActivityManager activityManager = (ActivityManager) context
|
||||
.getSystemService(Context.ACTIVITY_SERVICE);
|
||||
List<ActivityManager.RunningServiceInfo> serviceList = activityManager
|
||||
.getRunningServices(Integer.MAX_VALUE);
|
||||
for (int i = 0; i < serviceList.size(); i++) {
|
||||
RunningServiceInfo serviceInfo = serviceList.get(i);
|
||||
ComponentName componentName = serviceInfo.service;
|
||||
if (componentName.getClassName().equals(serviceName)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,401 @@
|
||||
/*
|
||||
* Copyright 2012 Google Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
|
||||
* use this file except in compliance with the License. You may obtain a copy of
|
||||
* the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
|
||||
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
|
||||
* License for the specific language governing permissions and limitations under
|
||||
* the License.
|
||||
*/
|
||||
package com.google.android.apps.mytracks;
|
||||
|
||||
import com.google.android.apps.mytracks.content.MyTracksLocation;
|
||||
import com.google.android.apps.mytracks.content.Sensor;
|
||||
import com.google.android.apps.mytracks.content.Sensor.SensorDataSet;
|
||||
import com.google.android.apps.mytracks.util.UnitConversions;
|
||||
import com.google.android.maps.mytracks.R;
|
||||
|
||||
import android.app.Instrumentation;
|
||||
import android.location.Location;
|
||||
import android.test.ActivityInstrumentationTestCase2;
|
||||
import android.view.View;
|
||||
import android.widget.ZoomControls;
|
||||
|
||||
/**
|
||||
* Tests {@link ChartActivity}.
|
||||
*
|
||||
* @author Youtao Liu
|
||||
*/
|
||||
public class ChartActivityTest extends ActivityInstrumentationTestCase2<ChartActivity> {
|
||||
|
||||
private Instrumentation instrumentation;
|
||||
private ChartActivity chartActivity;
|
||||
private View zoomIn;
|
||||
private View zoomOut;
|
||||
private int currentZoomLevel;
|
||||
|
||||
private static final String LOCATION_PROVIDER = "gps";
|
||||
private static final double INITIAL_LONGTITUDE = 22;
|
||||
private static final double INITIAL_LATITUDE = 22;
|
||||
private static final double INITIAL_ALTITUDE = 22;
|
||||
private static final float INITIAL_ACCURACY = 5;
|
||||
private static final float INITIAL_SPEED = 10;
|
||||
private static final float INITIAL_BEARING = 3.0f;
|
||||
// 10 is same with the default value in ChartView
|
||||
private static final int MAX_ZOOM_LEVEL = 10;
|
||||
private static final int MIN_ZOOM_LEVEL = 1;
|
||||
// The ratio from meter/second to kilometer/hour, the conversion is 60 * 60 /
|
||||
// 1000 = 3.6.
|
||||
private final double METER_PER_SECOND_TO_KILOMETER_PER_HOUR = 3.6;
|
||||
private final double KILOMETER_TO_METER = 1000.0;
|
||||
private final double HOURS_PER_UNIT = 60;
|
||||
|
||||
public ChartActivityTest() {
|
||||
super(ChartActivity.class);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void setUp() throws Exception {
|
||||
super.setUp();
|
||||
instrumentation = getInstrumentation();
|
||||
chartActivity = getActivity();
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests {@link ChartActivity#zoomIn()} and {@link ChartActivity#zoomOut()}.
|
||||
*/
|
||||
public void testZoomInAndZoomOut() {
|
||||
currentZoomLevel = chartActivity.getChartView().getZoomLevel();
|
||||
chartActivity.runOnUiThread(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
ZoomControls zoomControls = (ZoomControls) chartActivity.findViewById(R.id.elevation_zoom);
|
||||
zoomIn = zoomControls.getChildAt(0);
|
||||
zoomOut = zoomControls.getChildAt(1);
|
||||
// Invoke following two methods method to initial the display of
|
||||
// ZoomControls.
|
||||
zoomControls.setIsZoomInEnabled(chartActivity.getChartView().canZoomIn());
|
||||
zoomControls.setIsZoomOutEnabled(chartActivity.getChartView().canZoomOut());
|
||||
// Click zoomIn button to disable.
|
||||
for (int i = currentZoomLevel; i > MIN_ZOOM_LEVEL; i--) {
|
||||
zoomIn.performClick();
|
||||
}
|
||||
}
|
||||
});
|
||||
instrumentation.waitForIdleSync();
|
||||
assertEquals(false, zoomIn.isEnabled());
|
||||
assertEquals(true, zoomOut.isEnabled());
|
||||
chartActivity.runOnUiThread(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
// Click to the second max zoom level
|
||||
for (int i = MIN_ZOOM_LEVEL; i < MAX_ZOOM_LEVEL - 1; i++) {
|
||||
zoomOut.performClick();
|
||||
assertEquals(true, zoomIn.isEnabled());
|
||||
assertEquals(true, zoomOut.isEnabled());
|
||||
}
|
||||
zoomOut.performClick();
|
||||
}
|
||||
});
|
||||
instrumentation.waitForIdleSync();
|
||||
assertEquals(true, zoomIn.isEnabled());
|
||||
assertEquals(false, zoomOut.isEnabled());
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the logic to get the incorrect values of sensor in {@link
|
||||
* ChartActivity#fillDataPoint(Location, double[])}.
|
||||
*/
|
||||
public void testFillDataPoint_sensorIncorrect() {
|
||||
MyTracksLocation myTracksLocation = getMyTracksLocation();
|
||||
// No input.
|
||||
double[] point = fillDataPointTestHelper(myTracksLocation, false);
|
||||
assertEquals(Double.NaN, point[3]);
|
||||
assertEquals(Double.NaN, point[4]);
|
||||
assertEquals(Double.NaN, point[5]);
|
||||
|
||||
// Input incorrect state.
|
||||
// Creates SensorData.
|
||||
Sensor.SensorData.Builder powerData = Sensor.SensorData.newBuilder().setValue(20)
|
||||
.setState(Sensor.SensorState.NONE);
|
||||
Sensor.SensorData.Builder cadenceData = Sensor.SensorData.newBuilder().setValue(20)
|
||||
.setState(Sensor.SensorState.NONE);
|
||||
Sensor.SensorData.Builder heartRateData = Sensor.SensorData.newBuilder().setValue(20)
|
||||
.setState(Sensor.SensorState.NONE);
|
||||
// Creates SensorDataSet.
|
||||
SensorDataSet sensorDataSet = myTracksLocation.getSensorDataSet();
|
||||
sensorDataSet = sensorDataSet.toBuilder().setPower(powerData).setCadence(cadenceData)
|
||||
.setHeartRate(heartRateData).build();
|
||||
myTracksLocation.setSensorData(sensorDataSet);
|
||||
// Test.
|
||||
point = fillDataPointTestHelper(myTracksLocation, false);
|
||||
assertEquals(Double.NaN, point[3]);
|
||||
assertEquals(Double.NaN, point[4]);
|
||||
assertEquals(Double.NaN, point[5]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the logic to get the correct values of sensor in {@link
|
||||
* ChartActivity#fillDataPoint(Location, double[])}.
|
||||
*/
|
||||
public void testFillDataPoint_sensorCorrect() {
|
||||
MyTracksLocation myTracksLocation = getMyTracksLocation();
|
||||
// No input.
|
||||
double[] point = fillDataPointTestHelper(myTracksLocation, false);
|
||||
assertEquals(Double.NaN, point[3]);
|
||||
assertEquals(Double.NaN, point[4]);
|
||||
assertEquals(Double.NaN, point[5]);
|
||||
|
||||
// Creates SensorData.
|
||||
Sensor.SensorData.Builder powerData = Sensor.SensorData.newBuilder().setValue(20)
|
||||
.setState(Sensor.SensorState.SENDING);
|
||||
Sensor.SensorData.Builder cadenceData = Sensor.SensorData.newBuilder().setValue(20)
|
||||
.setState(Sensor.SensorState.SENDING);
|
||||
Sensor.SensorData.Builder heartRateData = Sensor.SensorData.newBuilder().setValue(20)
|
||||
.setState(Sensor.SensorState.SENDING);
|
||||
// Creates SensorDataSet.
|
||||
SensorDataSet sensorDataSet = myTracksLocation.getSensorDataSet();
|
||||
sensorDataSet = sensorDataSet.toBuilder().setPower(powerData).setCadence(cadenceData)
|
||||
.setHeartRate(heartRateData).build();
|
||||
myTracksLocation.setSensorData(sensorDataSet);
|
||||
// Test.
|
||||
point = fillDataPointTestHelper(myTracksLocation, false);
|
||||
assertEquals(20.0, point[3]);
|
||||
assertEquals(20.0, point[4]);
|
||||
assertEquals(20.0, point[5]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the logic to get the value of metric Distance in
|
||||
* {@link ChartActivity#fillDataPoint(Location, double[])}.
|
||||
*/
|
||||
public void testFillDataPoint_distanceMetric() {
|
||||
// By distance.
|
||||
chartActivity.getChartView().setMode(ChartView.Mode.BY_DISTANCE);
|
||||
// Resets last location and writes first location.
|
||||
MyTracksLocation myTracksLocation1 = getMyTracksLocation();
|
||||
double[] point = fillDataPointTestHelper(myTracksLocation1, true);
|
||||
assertEquals(0.0, point[0]);
|
||||
|
||||
// The second is a same location, just different time.
|
||||
MyTracksLocation myTracksLocation2 = getMyTracksLocation();
|
||||
point = fillDataPointTestHelper(myTracksLocation2, false);
|
||||
assertEquals(0.0, point[0]);
|
||||
|
||||
// The third location is a new location, and use metric.
|
||||
MyTracksLocation myTracksLocation3 = getMyTracksLocation();
|
||||
myTracksLocation3.setLatitude(23);
|
||||
point = fillDataPointTestHelper(myTracksLocation3, false);
|
||||
// Computes the distance between Latitude 22 and 23.
|
||||
float[] results = new float[4];
|
||||
Location.distanceBetween(myTracksLocation2.getLatitude(), myTracksLocation2.getLongitude(),
|
||||
myTracksLocation3.getLatitude(), myTracksLocation3.getLongitude(), results);
|
||||
double distance1 = results[0];
|
||||
assertEquals(distance1 / KILOMETER_TO_METER, point[0]);
|
||||
|
||||
// The fourth location is a new location, and use metric.
|
||||
MyTracksLocation myTracksLocation4 = getMyTracksLocation();
|
||||
myTracksLocation4.setLatitude(24);
|
||||
point = fillDataPointTestHelper(myTracksLocation4, false);
|
||||
// Computes the distance between Latitude 23 and 24.
|
||||
|
||||
Location.distanceBetween(myTracksLocation3.getLatitude(), myTracksLocation3.getLongitude(),
|
||||
myTracksLocation4.getLatitude(), myTracksLocation4.getLongitude(), results);
|
||||
double distance2 = results[0];
|
||||
assertEquals((distance1 + distance2) / KILOMETER_TO_METER, point[0]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the logic to get the value of imperial Distance in
|
||||
* {@link ChartActivity#fillDataPoint(Location, double[])}.
|
||||
*/
|
||||
public void testFillDataPoint_distanceImperial() {
|
||||
// Setups to use imperial.
|
||||
chartActivity.onUnitsChanged(false);
|
||||
|
||||
// The first is a same location, just different time.
|
||||
MyTracksLocation myTracksLocation1 = getMyTracksLocation();
|
||||
double[] point = fillDataPointTestHelper(myTracksLocation1, true);
|
||||
assertEquals(0.0, point[0]);
|
||||
|
||||
// The second location is a new location, and use imperial.
|
||||
MyTracksLocation myTracksLocation2 = getMyTracksLocation();
|
||||
myTracksLocation2.setLatitude(23);
|
||||
point = fillDataPointTestHelper(myTracksLocation2, false);
|
||||
/*
|
||||
* Computes the distance between Latitude 22 and 23. And for we set using
|
||||
* imperial, the distance should be multiplied by UnitConversions.KM_TO_MI.
|
||||
*/
|
||||
float[] results = new float[4];
|
||||
Location.distanceBetween(myTracksLocation1.getLatitude(), myTracksLocation1.getLongitude(),
|
||||
myTracksLocation2.getLatitude(), myTracksLocation2.getLongitude(), results);
|
||||
double distance1 = results[0] * UnitConversions.KM_TO_MI;
|
||||
assertEquals(distance1 / KILOMETER_TO_METER, point[0]);
|
||||
|
||||
// The third location is a new location, and use imperial.
|
||||
MyTracksLocation myTracksLocation3 = getMyTracksLocation();
|
||||
myTracksLocation3.setLatitude(24);
|
||||
point = fillDataPointTestHelper(myTracksLocation3, false);
|
||||
/*
|
||||
* Computes the distance between Latitude 23 and 24. And for we set using
|
||||
* imperial, the distance should be multiplied by UnitConversions.KM_TO_MI.
|
||||
*/
|
||||
|
||||
Location.distanceBetween(myTracksLocation2.getLatitude(), myTracksLocation2.getLongitude(),
|
||||
myTracksLocation3.getLatitude(), myTracksLocation3.getLongitude(), results);
|
||||
double distance2 = results[0] * UnitConversions.KM_TO_MI;
|
||||
assertEquals(distance1 / KILOMETER_TO_METER + distance2 / KILOMETER_TO_METER , point[0]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the logic to get the values of time in {@link ChartActivity#fillDataPoint(Location, double[])}.
|
||||
*/
|
||||
public void testFillDataPoint_time() {
|
||||
// By time
|
||||
chartActivity.getChartView().setMode(ChartView.Mode.BY_TIME);
|
||||
MyTracksLocation myTracksLocation1 = getMyTracksLocation();
|
||||
double[] point = fillDataPointTestHelper(myTracksLocation1, true);
|
||||
assertEquals(0.0, point[0]);
|
||||
long timeSpan = 222;
|
||||
MyTracksLocation myTracksLocation2 = getMyTracksLocation();
|
||||
myTracksLocation2.setTime(myTracksLocation1.getTime() + timeSpan);
|
||||
point = fillDataPointTestHelper(myTracksLocation2, false);
|
||||
assertEquals((double) timeSpan, point[0]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the logic to get the value of elevation in
|
||||
* {@link ChartActivity#fillDataPoint} by one and two points.
|
||||
*/
|
||||
public void testFillDataPoint_elevation() {
|
||||
MyTracksLocation myTracksLocation1 = getMyTracksLocation();
|
||||
/*
|
||||
* At first, clear old points of elevation, so give true to the second
|
||||
* parameter. Then only one value INITIALLONGTITUDE in buffer.
|
||||
*/
|
||||
double[] point = fillDataPointTestHelper(myTracksLocation1, true);
|
||||
assertEquals(INITIAL_ALTITUDE, point[1]);
|
||||
/*
|
||||
* Send another value to buffer, now there are two values, INITIALALTITUDE
|
||||
* and INITIALALTITUDE * 2.
|
||||
*/
|
||||
MyTracksLocation myTracksLocation2 = getMyTracksLocation();
|
||||
myTracksLocation2.setAltitude(INITIAL_ALTITUDE * 2);
|
||||
point = fillDataPointTestHelper(myTracksLocation2, false);
|
||||
assertEquals((INITIAL_ALTITUDE + INITIAL_ALTITUDE * 2) / 2.0, point[1]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the logic to get the value of speed in
|
||||
* {@link ChartActivity#fillDataPoint}. In this test, firstly remove all
|
||||
* points in memory, and then fill in two points one by one. The speed values
|
||||
* of these points are 129, 130.
|
||||
*/
|
||||
public void testFillDataPoint_speed() {
|
||||
// Set max speed to make the speed of points are valid.
|
||||
chartActivity.setTrackMaxSpeed(200.0);
|
||||
/*
|
||||
* At first, clear old points of speed, so give true to the second
|
||||
* parameter. It will not be filled in to the speed buffer.
|
||||
*/
|
||||
MyTracksLocation myTracksLocation1 = getMyTracksLocation();
|
||||
myTracksLocation1.setSpeed(129);
|
||||
double[] point = fillDataPointTestHelper(myTracksLocation1, true);
|
||||
assertEquals(0.0, point[2]);
|
||||
|
||||
/*
|
||||
* Tests the logic when both metricUnits and reportSpeed are true.This
|
||||
* location will be filled into speed buffer.
|
||||
*/
|
||||
MyTracksLocation myTracksLocation2 = getMyTracksLocation();
|
||||
// Add a time span here to make sure the second point is valid, the value
|
||||
// 222 here is doesn't matter.
|
||||
myTracksLocation2.setTime(myTracksLocation1.getTime() + 222);
|
||||
myTracksLocation2.setSpeed(130);
|
||||
point = fillDataPointTestHelper(myTracksLocation2, false);
|
||||
assertEquals(130.0 * METER_PER_SECOND_TO_KILOMETER_PER_HOUR, point[2]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the logic to compute speed when use Imperial.
|
||||
*/
|
||||
public void testFillDataPoint_speedImperial() {
|
||||
// Setups to use imperial.
|
||||
chartActivity.onUnitsChanged(false);
|
||||
MyTracksLocation myTracksLocation = getMyTracksLocation();
|
||||
myTracksLocation.setSpeed(132);
|
||||
double[] point = fillDataPointTestHelper(myTracksLocation, true);
|
||||
assertEquals(132.0 * METER_PER_SECOND_TO_KILOMETER_PER_HOUR * UnitConversions.KM_TO_MI,
|
||||
point[2]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the logic to get pace value when reportSpeed is false.
|
||||
*/
|
||||
public void testFillDataPoint_pace_nonZeroSpeed() {
|
||||
// Setups reportSpeed to false.
|
||||
chartActivity.onReportSpeedChanged(false);
|
||||
MyTracksLocation myTracksLocation = getMyTracksLocation();
|
||||
myTracksLocation.setSpeed(134);
|
||||
double[] point = fillDataPointTestHelper(myTracksLocation, true);
|
||||
assertEquals(HOURS_PER_UNIT / (134.0 * METER_PER_SECOND_TO_KILOMETER_PER_HOUR), point[2]);
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the logic to get pace value when reportSpeed is false and average
|
||||
* speed is zero.
|
||||
*/
|
||||
public void testFillDataPoint_pace_zeroSpeed() {
|
||||
// Setups reportSpeed to false.
|
||||
chartActivity.onReportSpeedChanged(false);
|
||||
MyTracksLocation myTracksLocation = getMyTracksLocation();
|
||||
myTracksLocation.setSpeed(0);
|
||||
double[] point = fillDataPointTestHelper(myTracksLocation, true);
|
||||
assertEquals(Double.NaN, point[2]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Simulates a MyTracksLocation for test.
|
||||
*
|
||||
* @return a simulated location.
|
||||
*/
|
||||
private MyTracksLocation getMyTracksLocation() {
|
||||
// Initial Location
|
||||
Location loc = new Location(LOCATION_PROVIDER);
|
||||
loc.setLongitude(INITIAL_LONGTITUDE);
|
||||
loc.setLatitude(INITIAL_LATITUDE);
|
||||
loc.setAltitude(INITIAL_ALTITUDE);
|
||||
loc.setAccuracy(INITIAL_ACCURACY);
|
||||
loc.setSpeed(INITIAL_SPEED);
|
||||
loc.setTime(System.currentTimeMillis());
|
||||
loc.setBearing(INITIAL_BEARING);
|
||||
SensorDataSet sd = SensorDataSet.newBuilder().build();
|
||||
MyTracksLocation myTracksLocation = new MyTracksLocation(loc, sd);
|
||||
|
||||
return myTracksLocation;
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper method to test fillDataPoint.
|
||||
*
|
||||
* @param location location to fill
|
||||
* @param operation a flag to do some operations
|
||||
* @return data of this location
|
||||
*/
|
||||
private double[] fillDataPointTestHelper(Location location, boolean isNeedClear) {
|
||||
if (isNeedClear) {
|
||||
chartActivity.clearTrackPoints();
|
||||
}
|
||||
double[] point = new double[6];
|
||||
chartActivity.fillDataPoint(location, point);
|
||||
return point;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
/*
|
||||
* Copyright 2012 Google Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
|
||||
* use this file except in compliance with the License. You may obtain a copy of
|
||||
* the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
|
||||
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
|
||||
* License for the specific language governing permissions and limitations under
|
||||
* the License.
|
||||
*/
|
||||
package com.google.android.apps.mytracks;
|
||||
|
||||
import com.google.android.apps.mytracks.ChartView.Mode;
|
||||
import com.google.android.maps.mytracks.R;
|
||||
|
||||
import android.test.ActivityInstrumentationTestCase2;
|
||||
|
||||
/**
|
||||
* Tests the {@link ChartSettingsDialog}.
|
||||
*
|
||||
* @author Youtao Liu
|
||||
*/
|
||||
public class ChartSettingsDialogTest extends ActivityInstrumentationTestCase2<ChartActivity> {
|
||||
|
||||
private ChartSettingsDialog chartSettingsDialog;
|
||||
|
||||
public ChartSettingsDialogTest() {
|
||||
super(ChartActivity.class);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void setUp() throws Exception {
|
||||
super.setUp();
|
||||
chartSettingsDialog = new ChartSettingsDialog(getActivity());
|
||||
chartSettingsDialog.show();
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the {@link ChartSettingsDialog#setMode} and check the result by
|
||||
* {@link ChartSettingsDialog#getMode}. Gets all modes of Mode, then set and
|
||||
* get each mode.
|
||||
*/
|
||||
public void testSetMode() {
|
||||
Mode[] modes = Mode.values();
|
||||
for (Mode mode : modes) {
|
||||
chartSettingsDialog.setMode(mode);
|
||||
assertEquals(mode, chartSettingsDialog.getMode());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the {@link ChartSettingsDialog#setDisplaySpeed}.
|
||||
*/
|
||||
public void testSetDisplaySpeed() {
|
||||
chartSettingsDialog.setDisplaySpeed(true);
|
||||
assertEquals(getActivity().getString(R.string.stat_speed),
|
||||
chartSettingsDialog.getSeries()[ChartView.SPEED_SERIES].getText());
|
||||
chartSettingsDialog.setDisplaySpeed(false);
|
||||
assertEquals(getActivity().getString(R.string.stat_pace),
|
||||
chartSettingsDialog.getSeries()[ChartView.SPEED_SERIES].getText());
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the {@link ChartSettingsDialog#setSeriesEnabled} and check the result
|
||||
* by {@link ChartSettingsDialog#isSeriesEnabled}.
|
||||
*/
|
||||
public void testSetSeriesEnabled() {
|
||||
for (int i = 0; i < ChartView.NUM_SERIES; i++) {
|
||||
chartSettingsDialog.setSeriesEnabled(i, true);
|
||||
assertEquals(true, chartSettingsDialog.getSeries()[i].isChecked());
|
||||
assertEquals(true, chartSettingsDialog.isSeriesEnabled(i));
|
||||
chartSettingsDialog.setSeriesEnabled(i, false);
|
||||
assertEquals(false, chartSettingsDialog.getSeries()[i].isChecked());
|
||||
assertEquals(false, chartSettingsDialog.isSeriesEnabled(i));
|
||||
}
|
||||
}
|
||||
}
|
||||
+213
@@ -0,0 +1,213 @@
|
||||
/*
|
||||
* Copyright 2012 Google Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
|
||||
* use this file except in compliance with the License. You may obtain a copy of
|
||||
* the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
|
||||
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
|
||||
* License for the specific language governing permissions and limitations under
|
||||
* the License.
|
||||
*/
|
||||
|
||||
package com.google.android.apps.mytracks.content;
|
||||
|
||||
import com.google.android.apps.mytracks.stats.TripStatistics;
|
||||
import com.google.android.apps.mytracks.util.UnitConversions;
|
||||
import com.google.android.maps.mytracks.R;
|
||||
|
||||
import android.test.AndroidTestCase;
|
||||
import android.util.Pair;
|
||||
|
||||
/**
|
||||
* Tests for {@link DescriptionGeneratorImpl}.
|
||||
*
|
||||
* @author Jimmy Shih
|
||||
*/
|
||||
public class DescriptionGeneratorImplTest extends AndroidTestCase {
|
||||
|
||||
private DescriptionGeneratorImpl descriptionGenerator;
|
||||
|
||||
@Override
|
||||
protected void setUp() throws Exception {
|
||||
descriptionGenerator = new DescriptionGeneratorImpl(getContext());
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests {@link DescriptionGeneratorImpl#generateTrackDescription(Track,
|
||||
* java.util.Vector, java.util.Vector)}.
|
||||
*/
|
||||
public void testGenerateTrackDescription() {
|
||||
Track track = new Track();
|
||||
TripStatistics stats = new TripStatistics();
|
||||
stats.setTotalDistance(20000);
|
||||
stats.setTotalTime(600000);
|
||||
stats.setMovingTime(300000);
|
||||
stats.setMaxSpeed(100);
|
||||
stats.setMaxElevation(550);
|
||||
stats.setMinElevation(-500);
|
||||
stats.setTotalElevationGain(6000);
|
||||
stats.setMaxGrade(0.42);
|
||||
stats.setMinGrade(0.11);
|
||||
stats.setStartTime(1288721514000L);
|
||||
track.setStatistics(stats);
|
||||
track.setCategory("hiking");
|
||||
String expected = "Created by"
|
||||
+ " <a href='http://www.google.com/mobile/mytracks'>My Tracks</a> on Android.<p>"
|
||||
+ "Total distance: 20.00 km (12.4 mi)<br>"
|
||||
+ "Total time: 10:00<br>"
|
||||
+ "Moving time: 05:00<br>"
|
||||
+ "Average speed: 120.00 km/h (74.6 mi/h)<br>"
|
||||
+ "Average moving speed: 240.00 km/h (149.1 mi/h)<br>"
|
||||
+ "Max speed: 360.00 km/h (223.7 mi/h)<br>"
|
||||
+ "Average pace: 0.50 min/km (0.8 min/mi)<br>"
|
||||
+ "Average moving pace: 0.25 min/km (0.4 min/mi)<br>"
|
||||
+ "Min pace: 0.17 min/km (0.3 min/mi)<br>"
|
||||
+ "Max elevation: 550 m (1804 ft)<br>"
|
||||
+ "Min elevation: -500 m (-1640 ft)<br>"
|
||||
+ "Elevation gain: 6000 m (19685 ft)<br>"
|
||||
+ "Max grade: 42 %<br>"
|
||||
+ "Min grade: 11 %<br>"
|
||||
+ "Recorded: 11/2/2010 11:11 AM<br>"
|
||||
+ "Activity type: hiking<br>";
|
||||
assertEquals(expected, descriptionGenerator.generateTrackDescription(track, null, null));
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests {@link DescriptionGeneratorImpl#generateWaypointDescription(Waypoint)}.
|
||||
*/
|
||||
public void testGenerateWaypointDescription() {
|
||||
Waypoint waypoint = new Waypoint();
|
||||
TripStatistics stats = new TripStatistics();
|
||||
stats.setTotalDistance(20000);
|
||||
stats.setTotalTime(600000);
|
||||
stats.setMovingTime(300000);
|
||||
stats.setMaxSpeed(100);
|
||||
stats.setMaxElevation(550);
|
||||
stats.setMinElevation(-500);
|
||||
stats.setTotalElevationGain(6000);
|
||||
stats.setMaxGrade(0.42);
|
||||
stats.setMinGrade(0.11);
|
||||
stats.setStartTime(1288721514000L);
|
||||
waypoint.setStatistics(stats);
|
||||
String expected = "Total distance: 20.00 km (12.4 mi)\n"
|
||||
+ "Total time: 10:00\n"
|
||||
+ "Moving time: 05:00\n"
|
||||
+ "Average speed: 120.00 km/h (74.6 mi/h)\n"
|
||||
+ "Average moving speed: 240.00 km/h (149.1 mi/h)\n"
|
||||
+ "Max speed: 360.00 km/h (223.7 mi/h)\n"
|
||||
+ "Average pace: 0.50 min/km (0.8 min/mi)\n"
|
||||
+ "Average moving pace: 0.25 min/km (0.4 min/mi)\n"
|
||||
+ "Min pace: 0.17 min/km (0.3 min/mi)\n"
|
||||
+ "Max elevation: 550 m (1804 ft)\n"
|
||||
+ "Min elevation: -500 m (-1640 ft)\n"
|
||||
+ "Elevation gain: 6000 m (19685 ft)\n"
|
||||
+ "Max grade: 42 %\n"
|
||||
+ "Min grade: 11 %\n"
|
||||
+ "Recorded: 11/2/2010 11:11 AM\n";
|
||||
assertEquals(expected, descriptionGenerator.generateWaypointDescription(waypoint));
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests {@link DescriptionGeneratorImpl#writeDistance(double, StringBuilder,
|
||||
* int, String)}.
|
||||
*/
|
||||
public void testWriteDistance() {
|
||||
StringBuilder builder = new StringBuilder();
|
||||
descriptionGenerator.writeDistance(1100, builder, R.string.description_total_distance, "<br>");
|
||||
assertEquals("Total distance: 1.10 km (0.7 mi)<br>", builder.toString());
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests {@link DescriptionGeneratorImpl#writeTime(long, StringBuilder, int,
|
||||
* String)}.
|
||||
*/
|
||||
public void testWriteTime() {
|
||||
StringBuilder builder = new StringBuilder();
|
||||
descriptionGenerator.writeTime(1000, builder, R.string.description_total_time, "<br>");
|
||||
assertEquals("Total time: 00:01<br>", builder.toString());
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests {@link DescriptionGeneratorImpl#writeSpeed(double, StringBuilder,
|
||||
* int, String)}.
|
||||
*/
|
||||
public void testWriteSpeed() {
|
||||
StringBuilder builder = new StringBuilder();
|
||||
Pair<Double, Double> speed = descriptionGenerator.writeSpeed(
|
||||
1.1, builder, R.string.description_average_speed, "\n");
|
||||
assertEquals(3.96, speed.first);
|
||||
assertEquals(3.96 * UnitConversions.KM_TO_MI, speed.second);
|
||||
assertEquals("Average speed: 3.96 km/h (2.5 mi/h)\n", builder.toString());
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests {@link DescriptionGeneratorImpl#writeElevation(double, StringBuilder,
|
||||
* int, String)}.
|
||||
*/
|
||||
public void testWriteElevation() {
|
||||
StringBuilder builder = new StringBuilder();
|
||||
descriptionGenerator.writeElevation(4.2, builder, R.string.description_min_elevation, "<br>");
|
||||
assertEquals("Min elevation: 4 m (14 ft)<br>", builder.toString());
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests {@link DescriptionGeneratorImpl#writePace(Pair, StringBuilder, int,
|
||||
* String)}.
|
||||
*/
|
||||
public void testWritePace() {
|
||||
StringBuilder builder = new StringBuilder();
|
||||
descriptionGenerator.writePace(
|
||||
new Pair<Double, Double>(1.1, 2.2), builder, R.string.description_average_pace, "\n");
|
||||
assertEquals("Average pace: 54.55 min/km (27.3 min/mi)\n", builder.toString());
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests {@link DescriptionGeneratorImpl#writeGrade(double, StringBuilder,
|
||||
* int, String)}.
|
||||
*/
|
||||
public void testWriteGrade() {
|
||||
StringBuilder builder = new StringBuilder();
|
||||
descriptionGenerator.writeGrade(.042, builder, R.string.description_max_grade, "<br>");
|
||||
assertEquals("Max grade: 4 %<br>", builder.toString());
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests {@link DescriptionGeneratorImpl#writeGrade(double, StringBuilder,
|
||||
* int, String)} with a NaN.
|
||||
*/
|
||||
public void testWriteGrade_nan() {
|
||||
StringBuilder builder = new StringBuilder();
|
||||
descriptionGenerator.writeGrade(Double.NaN, builder, R.string.description_max_grade, "<br>");
|
||||
assertEquals("Max grade: 0 %<br>", builder.toString());
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests {@link DescriptionGeneratorImpl#writeGrade(double, StringBuilder,
|
||||
* int, String)} with an infinite number.
|
||||
*/
|
||||
public void testWriteGrade_infinite() {
|
||||
StringBuilder builder = new StringBuilder();
|
||||
descriptionGenerator.writeGrade(
|
||||
Double.POSITIVE_INFINITY, builder, R.string.description_max_grade, "<br>");
|
||||
assertEquals("Max grade: 0 %<br>", builder.toString());
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests {@link DescriptionGeneratorImpl#getPace(double)}.
|
||||
*/
|
||||
public void testGetPace() {
|
||||
assertEquals(12.0, descriptionGenerator.getPace(5));
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests {@link DescriptionGeneratorImpl#getPace(double)} with zero speed.
|
||||
*/
|
||||
public void testGetPace_zero() {
|
||||
assertEquals(0.0, descriptionGenerator.getPace(0));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,326 @@
|
||||
/*
|
||||
* Copyright 2012 Google Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
|
||||
* use this file except in compliance with the License. You may obtain a copy of
|
||||
* the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
|
||||
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
|
||||
* License for the specific language governing permissions and limitations under
|
||||
* the License.
|
||||
*/
|
||||
|
||||
package com.google.android.apps.mytracks.content;
|
||||
|
||||
import com.google.android.apps.mytracks.content.SearchEngine.ScoredResult;
|
||||
import com.google.android.apps.mytracks.content.SearchEngine.SearchQuery;
|
||||
import com.google.android.apps.mytracks.services.TrackRecordingServiceTest.MockContext;
|
||||
import com.google.android.apps.mytracks.stats.TripStatistics;
|
||||
|
||||
import android.content.ContentUris;
|
||||
import android.location.Location;
|
||||
import android.net.Uri;
|
||||
import android.test.AndroidTestCase;
|
||||
import android.test.RenamingDelegatingContext;
|
||||
import android.test.mock.MockContentResolver;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Tests for {@link SearchEngine}.
|
||||
* These are not meant to be quality tests, but instead feature-by-feature tests
|
||||
* (in other words, they don't test the mixing of different score boostings, just
|
||||
* each boosting separately)
|
||||
*
|
||||
* @author Rodrigo Damazio
|
||||
*/
|
||||
public class SearchEngineTest extends AndroidTestCase {
|
||||
|
||||
private static final Location HERE = new Location("gps");
|
||||
private static final long NOW = 1234567890000L; // After OLDEST_ALLOWED_TIMESTAMP
|
||||
private MyTracksProviderUtils providerUtils;
|
||||
private SearchEngine engine;
|
||||
|
||||
@Override
|
||||
protected void setUp() throws Exception {
|
||||
super.setUp();
|
||||
|
||||
MockContentResolver mockContentResolver = new MockContentResolver();
|
||||
RenamingDelegatingContext targetContext = new RenamingDelegatingContext(
|
||||
getContext(), getContext(), "test.");
|
||||
MockContext context = new MockContext(mockContentResolver, targetContext);
|
||||
MyTracksProvider provider = new MyTracksProvider();
|
||||
provider.attachInfo(context, null);
|
||||
mockContentResolver.addProvider(MyTracksProviderUtils.AUTHORITY, provider);
|
||||
setContext(context);
|
||||
|
||||
providerUtils = MyTracksProviderUtils.Factory.get(context);
|
||||
engine = new SearchEngine(providerUtils);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void tearDown() throws Exception {
|
||||
providerUtils.deleteAllTracks();
|
||||
|
||||
super.tearDown();
|
||||
}
|
||||
|
||||
private long insertTrack(String title, String description, String category, double distance, long hoursAgo) {
|
||||
Track track = new Track();
|
||||
track.setName(title);
|
||||
track.setDescription(description);
|
||||
track.setCategory(category);
|
||||
|
||||
TripStatistics stats = track.getStatistics();
|
||||
if (hoursAgo > 0) {
|
||||
// Started twice hoursAgo, so the average time is hoursAgo.
|
||||
stats.setStartTime(NOW - hoursAgo * 1000L * 60L * 60L * 2);
|
||||
stats.setStopTime(NOW);
|
||||
}
|
||||
|
||||
int latitude = (int) ((HERE.getLatitude() + distance) * 1E6);
|
||||
int longitude = (int) ((HERE.getLongitude() + distance) * 1E6);
|
||||
stats.setBounds(latitude, longitude, latitude, longitude);
|
||||
|
||||
Uri uri = providerUtils.insertTrack(track);
|
||||
return ContentUris.parseId(uri);
|
||||
}
|
||||
|
||||
private long insertTrack(String title, String description, String category) {
|
||||
return insertTrack(title, description, category, 0, -1);
|
||||
}
|
||||
|
||||
private long insertTrack(String title, double distance) {
|
||||
return insertTrack(title, "", "", distance, -1);
|
||||
}
|
||||
|
||||
private long insertTrack(String title, long hoursAgo) {
|
||||
return insertTrack(title, "", "", 0.0, hoursAgo);
|
||||
}
|
||||
|
||||
private long insertWaypoint(String title, String description, String category, double distance, long hoursAgo, long trackId) {
|
||||
Waypoint waypoint = new Waypoint();
|
||||
waypoint.setName(title);
|
||||
waypoint.setDescription(description);
|
||||
waypoint.setCategory(category);
|
||||
waypoint.setTrackId(trackId);
|
||||
|
||||
Location location = new Location(HERE);
|
||||
location.setLatitude(location.getLatitude() + distance);
|
||||
location.setLongitude(location.getLongitude() + distance);
|
||||
if (hoursAgo >= 0) {
|
||||
location.setTime(NOW - hoursAgo * 1000L * 60L * 60L);
|
||||
}
|
||||
waypoint.setLocation(location);
|
||||
|
||||
Uri uri = providerUtils.insertWaypoint(waypoint);
|
||||
return ContentUris.parseId(uri);
|
||||
}
|
||||
|
||||
private long insertWaypoint(String title, String description, String category) {
|
||||
return insertWaypoint(title, description, category, 0.0, -1, -1);
|
||||
}
|
||||
|
||||
private long insertWaypoint(String title, double distance) {
|
||||
return insertWaypoint(title, "", "", distance, -1, -1);
|
||||
}
|
||||
|
||||
private long insertWaypoint(String title, long hoursAgo) {
|
||||
return insertWaypoint(title, "", "", 0.0, hoursAgo, -1);
|
||||
}
|
||||
|
||||
private long insertWaypoint(String title, long hoursAgo, long trackId) {
|
||||
return insertWaypoint(title, "", "", 0.0, hoursAgo, trackId);
|
||||
}
|
||||
|
||||
public void testSearchText() {
|
||||
// Insert 7 tracks (purposefully out of result order):
|
||||
// - one which won't match
|
||||
// - one which will match the description
|
||||
// - one which will match the category
|
||||
// - one which will match the title
|
||||
// - one which will match in title and category
|
||||
// - one which will match in title and description
|
||||
// - one which will match in all fields
|
||||
insertTrack("bb", "cc", "dd");
|
||||
long descriptionMatchId = insertTrack("bb", "aa", "cc");
|
||||
long categoryMatchId = insertTrack("bb", "cc", "aa");
|
||||
long titleMatchId = insertTrack("aa", "bb", "cc");
|
||||
long titleCategoryMatchId = insertTrack("aa", "bb", "ca");
|
||||
long titleDescriptionMatchId = insertTrack("aa", "ba", "cc");
|
||||
long allMatchId = insertTrack("aa", "ba", "ca");
|
||||
|
||||
SearchQuery query = new SearchQuery("a", null, -1, NOW);
|
||||
ArrayList<ScoredResult> results = new ArrayList<ScoredResult>(engine.search(query));
|
||||
|
||||
// Title > Description > Category.
|
||||
assertTrackResults(results,
|
||||
allMatchId, titleDescriptionMatchId, titleCategoryMatchId, titleMatchId, descriptionMatchId,
|
||||
categoryMatchId);
|
||||
}
|
||||
|
||||
public void testSearchWaypointText() {
|
||||
// Insert 7 waypoints (purposefully out of result order):
|
||||
// - one which won't match
|
||||
// - one which will match the description
|
||||
// - one which will match the category
|
||||
// - one which will match the title
|
||||
// - one which will match in title and category
|
||||
// - one which will match in title and description
|
||||
// - one which will match in all fields
|
||||
insertWaypoint("bb", "cc", "dd");
|
||||
long descriptionMatchId = insertWaypoint("bb", "aa", "cc");
|
||||
long categoryMatchId = insertWaypoint("bb", "cc", "aa");
|
||||
long titleMatchId = insertWaypoint("aa", "bb", "cc");
|
||||
long titleCategoryMatchId = insertWaypoint("aa", "bb", "ca");
|
||||
long titleDescriptionMatchId = insertWaypoint("aa", "ba", "cc");
|
||||
long allMatchId = insertWaypoint("aa", "ba", "ca");
|
||||
|
||||
SearchQuery query = new SearchQuery("a", null, -1, NOW);
|
||||
ArrayList<ScoredResult> results = new ArrayList<ScoredResult>(engine.search(query));
|
||||
|
||||
// Title > Description > Category.
|
||||
assertWaypointResults(results,
|
||||
allMatchId, titleDescriptionMatchId, titleCategoryMatchId, titleMatchId, descriptionMatchId,
|
||||
categoryMatchId);
|
||||
}
|
||||
|
||||
public void testSearchMixedText() {
|
||||
// Insert 5 entries (purposefully out of result order):
|
||||
// - one waypoint which will match by description
|
||||
// - one waypoint which won't match
|
||||
// - one waypoint which will match by title
|
||||
// - one track which won't match
|
||||
// - one track which will match by title
|
||||
long descriptionWaypointId = insertWaypoint("bb", "aa", "cc");
|
||||
insertWaypoint("bb", "cc", "dd");
|
||||
long titleWaypointId = insertWaypoint("aa", "bb", "cc");
|
||||
insertTrack("bb", "cc", "dd");
|
||||
long trackId = insertTrack("aa", "bb", "cc");
|
||||
|
||||
SearchQuery query = new SearchQuery("a", null, -1, NOW);
|
||||
ArrayList<ScoredResult> results = new ArrayList<ScoredResult>(engine.search(query));
|
||||
|
||||
// Title > Description > Category.
|
||||
assertEquals(results.toString(), 3, results.size());
|
||||
assertTrackResult(trackId, results.get(0));
|
||||
assertWaypointResult(titleWaypointId, results.get(1));
|
||||
assertWaypointResult(descriptionWaypointId, results.get(2));
|
||||
}
|
||||
|
||||
public void testSearchTrackDistance() {
|
||||
// All results match text, but they're at difference distances from the user.
|
||||
long farFarAwayId = insertTrack("aa", 0.3);
|
||||
long nearId = insertTrack("ab", 0.1);
|
||||
long farId = insertTrack("ac", 0.2);
|
||||
|
||||
SearchQuery query = new SearchQuery("a", HERE, -1, NOW);
|
||||
ArrayList<ScoredResult> results = new ArrayList<ScoredResult>(engine.search(query));
|
||||
|
||||
// Distance order.
|
||||
assertTrackResults(results, nearId, farId, farFarAwayId);
|
||||
}
|
||||
|
||||
public void testSearchWaypointDistance() {
|
||||
// All results match text, but they're at difference distances from the user.
|
||||
long farFarAwayId = insertWaypoint("aa", 0.3);
|
||||
long nearId = insertWaypoint("ab", 0.1);
|
||||
long farId = insertWaypoint("ac", 0.2);
|
||||
|
||||
SearchQuery query = new SearchQuery("a", HERE, -1, NOW);
|
||||
ArrayList<ScoredResult> results = new ArrayList<ScoredResult>(engine.search(query));
|
||||
|
||||
// Distance order.
|
||||
assertWaypointResults(results, nearId, farId, farFarAwayId);
|
||||
}
|
||||
|
||||
public void testSearchTrackRecent() {
|
||||
// All results match text, but they're were recorded at different times.
|
||||
long oldestId = insertTrack("aa", 3);
|
||||
long recentId = insertTrack("ab", 1);
|
||||
long oldId = insertTrack("ac", 2);
|
||||
|
||||
SearchQuery query = new SearchQuery("a", null, -1, NOW);
|
||||
ArrayList<ScoredResult> results = new ArrayList<ScoredResult>(engine.search(query));
|
||||
|
||||
// Reverse time order.
|
||||
assertTrackResults(results, recentId, oldId, oldestId);
|
||||
}
|
||||
|
||||
public void testSearchWaypointRecent() {
|
||||
// All results match text, but they're were recorded at different times.
|
||||
long oldestId = insertWaypoint("aa", 2);
|
||||
long recentId = insertWaypoint("ab", 0);
|
||||
long oldId = insertWaypoint("ac", 1);
|
||||
|
||||
SearchQuery query = new SearchQuery("a", null, -1, NOW);
|
||||
ArrayList<ScoredResult> results = new ArrayList<ScoredResult>(engine.search(query));
|
||||
|
||||
// Reverse time order.
|
||||
assertWaypointResults(results, recentId, oldId, oldestId);
|
||||
}
|
||||
|
||||
public void testSearchCurrentTrack() {
|
||||
// All results match text, but one of them is the current track.
|
||||
long currentId = insertTrack("ab", 1);
|
||||
long otherId = insertTrack("aa", 1);
|
||||
|
||||
SearchQuery query = new SearchQuery("a", null, currentId, NOW);
|
||||
ArrayList<ScoredResult> results = new ArrayList<ScoredResult>(engine.search(query));
|
||||
|
||||
// Current track should be demoted.
|
||||
assertTrackResults(results, otherId, currentId);
|
||||
}
|
||||
|
||||
public void testSearchCurrentTrackWaypoint() {
|
||||
// All results match text, but one of them is in the current track.
|
||||
long otherId = insertWaypoint("aa", 1, 456);
|
||||
long currentId = insertWaypoint("ab", 1, 123);
|
||||
|
||||
SearchQuery query = new SearchQuery("a", null, 123, NOW);
|
||||
ArrayList<ScoredResult> results = new ArrayList<ScoredResult>(engine.search(query));
|
||||
|
||||
// Waypoint in current track should be promoted.
|
||||
assertWaypointResults(results, currentId, otherId);
|
||||
}
|
||||
|
||||
private void assertTrackResult(long trackId, ScoredResult result) {
|
||||
assertNotNull("Not a track", result.track);
|
||||
assertNull("Ambiguous result", result.waypoint);
|
||||
assertEquals(trackId, result.track.getId());
|
||||
}
|
||||
|
||||
private void assertTrackResults(List<ScoredResult> results, long... trackIds) {
|
||||
String errMsg = "Expected IDs=" + Arrays.toString(trackIds) + "; results=" + results;
|
||||
assertEquals(results.size(), trackIds.length);
|
||||
for (int i = 0; i < results.size(); i++) {
|
||||
ScoredResult result = results.get(i);
|
||||
assertNotNull(errMsg, result.track);
|
||||
assertNull(errMsg, result.waypoint);
|
||||
assertEquals(errMsg, trackIds[i], result.track.getId());
|
||||
}
|
||||
}
|
||||
|
||||
private void assertWaypointResult(long waypointId, ScoredResult result) {
|
||||
assertNotNull("Not a waypoint", result.waypoint);
|
||||
assertNull("Ambiguous result", result.track);
|
||||
assertEquals(waypointId, result.waypoint.getId());
|
||||
}
|
||||
|
||||
private void assertWaypointResults(List<ScoredResult> results, long... waypointIds) {
|
||||
String errMsg = "Expected IDs=" + Arrays.toString(waypointIds) + "; results=" + results;
|
||||
assertEquals(results.size(), waypointIds.length);
|
||||
for (int i = 0; i < results.size(); i++) {
|
||||
ScoredResult result = results.get(i);
|
||||
assertNotNull(errMsg, result.waypoint);
|
||||
assertNull(errMsg, result.track);
|
||||
assertEquals(errMsg, waypointIds[i], result.waypoint.getId());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,102 +0,0 @@
|
||||
/*
|
||||
* Copyright 2010 Google Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
|
||||
* use this file except in compliance with the License. You may obtain a copy of
|
||||
* the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
|
||||
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
|
||||
* License for the specific language governing permissions and limitations under
|
||||
* the License.
|
||||
*/
|
||||
package com.google.android.apps.mytracks.io.docs;
|
||||
|
||||
import com.google.android.apps.mytracks.io.gdata.GDataWrapper;
|
||||
import com.google.wireless.gdata.client.GDataServiceClient;
|
||||
|
||||
import android.content.Context;
|
||||
import android.test.mock.MockContext;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* Tests for {@link DocsHelper}, with the exception of
|
||||
* {@link DocsHelper#addTrackRow}, which is in
|
||||
* {@link DocsHelper_AddTrackRowTest}.
|
||||
*
|
||||
* @author Matthew Simmons
|
||||
*/
|
||||
public class DocsHelperTest extends TestCase {
|
||||
private Context mockContext = new MockContext();
|
||||
|
||||
// TODO(simmonmt): Use AndroidMock to mock this class. We do it the hard
|
||||
// way because use of AndroidMock to mock GDataWrapper triggers a compile
|
||||
// error in an unrelated file. Specifically, it causes a NoClassDefFound
|
||||
// exception for com.google.wireless.gdata2.client.AuthenticationException,
|
||||
// (wrongly) attributed to the first source file in the project. Using the
|
||||
// @UsesMocks(GDataWrapper.class) annotation is enough -- you don't have to
|
||||
// touch AndroidMock at all to get this failure.
|
||||
// The bug is filed with Android Mock as
|
||||
// http://code.google.com/p/android-mock/issues/detail?id=3
|
||||
private class MockGDataWrapper extends GDataWrapper<GDataServiceClient> {
|
||||
private final boolean returnValue;
|
||||
|
||||
MockGDataWrapper(boolean returnValue) {
|
||||
this.returnValue = returnValue;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean runQuery(QueryFunction<GDataServiceClient> queryFunction) {
|
||||
return returnValue;
|
||||
}
|
||||
}
|
||||
|
||||
public void testCreateSpreadsheet_noException() throws Exception {
|
||||
// Our mock GDataWrapper isn't able to affect the return value from
|
||||
// DocsHelper#createSpreadsheet. As such, we're only able to simulate the
|
||||
// case where there weren't any GData errors, but not spreadsheet ID was
|
||||
// actually returned. createSpreadsheet is defined to return null in that
|
||||
// situation.
|
||||
assertNull(new DocsHelper().createSpreadsheet(
|
||||
mockContext, new MockGDataWrapper(true), "sheetName"));
|
||||
}
|
||||
|
||||
public void testCreateSpreadsheet_exception() throws Exception {
|
||||
try {
|
||||
new DocsHelper().createSpreadsheet(
|
||||
mockContext, new MockGDataWrapper(false), "sheetName");
|
||||
fail();
|
||||
} catch (IOException expected) {}
|
||||
}
|
||||
|
||||
public void testRequestSpreadsheetId_noException() throws Exception {
|
||||
assertNull(new DocsHelper().requestSpreadsheetId(
|
||||
new MockGDataWrapper(true), "sheetName"));
|
||||
}
|
||||
|
||||
public void testRequestSpreadsheetId_exception() throws Exception {
|
||||
try {
|
||||
new DocsHelper().requestSpreadsheetId(new MockGDataWrapper(false),
|
||||
"sheetName");
|
||||
fail();
|
||||
} catch (IOException expected) {}
|
||||
}
|
||||
|
||||
public void testGetWorksheetId_noException() throws Exception {
|
||||
assertNull(new DocsHelper().getWorksheetId(new MockGDataWrapper(true),
|
||||
"sheetId"));
|
||||
}
|
||||
|
||||
public void testGetWorksheetId_exception() throws Exception {
|
||||
try {
|
||||
new DocsHelper().getWorksheetId(new MockGDataWrapper(false), "sheetId");
|
||||
fail();
|
||||
} catch (IOException expected) {}
|
||||
}
|
||||
}
|
||||
-128
@@ -1,128 +0,0 @@
|
||||
/*
|
||||
* Copyright 2010 Google Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
|
||||
* use this file except in compliance with the License. You may obtain a copy of
|
||||
* the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
|
||||
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
|
||||
* License for the specific language governing permissions and limitations under
|
||||
* the License.
|
||||
*/
|
||||
package com.google.android.apps.mytracks.io.docs;
|
||||
|
||||
import com.google.android.apps.mytracks.content.Track;
|
||||
import com.google.android.apps.mytracks.io.AuthManager;
|
||||
import com.google.android.apps.mytracks.stats.TripStatistics;
|
||||
import com.google.android.apps.mytracks.util.StringUtils;
|
||||
import com.google.android.testing.mocking.AndroidMock;
|
||||
import com.google.android.testing.mocking.UsesMocks;
|
||||
|
||||
import android.test.AndroidTestCase;
|
||||
import android.test.mock.MockResources;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* Tests for {@link DocsHelper#addTrackRow}
|
||||
*
|
||||
* @author Matthew Simmons
|
||||
*/
|
||||
public class DocsHelper_AddTrackRowTest extends AndroidTestCase {
|
||||
private static final long TIME = 1288721514000L;
|
||||
|
||||
private static class StringWritingDocsHelper extends DocsHelper {
|
||||
String writtenSheetUri = null;
|
||||
String writtenData = null;
|
||||
|
||||
@Override
|
||||
protected void writeRowData(AuthManager trixAuth, String worksheetUri,
|
||||
String postText) {
|
||||
writtenSheetUri = worksheetUri;
|
||||
writtenData = postText;
|
||||
}
|
||||
}
|
||||
|
||||
public void testAddTrackRow_imperial() throws Exception {
|
||||
StringWritingDocsHelper docsHelper = new StringWritingDocsHelper();
|
||||
addTrackRow(docsHelper, false);
|
||||
|
||||
String expectedData =
|
||||
"<entry xmlns='http://www.w3.org/2005/Atom' "
|
||||
+ "xmlns:gsx='http://schemas.google.com/spreadsheets/2006/extended'>"
|
||||
+ "<gsx:name><![CDATA[trackName]]></gsx:name>"
|
||||
+ "<gsx:description><![CDATA[trackDescription]]></gsx:description>"
|
||||
+ "<gsx:date><![CDATA[" + StringUtils.formatDateTime(getContext(), TIME) + "]]></gsx:date>"
|
||||
+ "<gsx:totaltime><![CDATA[00:05]]></gsx:totaltime>"
|
||||
+ "<gsx:movingtime><![CDATA[00:04]]></gsx:movingtime>"
|
||||
+ "<gsx:distance><![CDATA[12.43]]></gsx:distance>"
|
||||
+ "<gsx:distanceunit><![CDATA[mi]]></gsx:distanceunit>"
|
||||
+ "<gsx:averagespeed><![CDATA[8,947.75]]></gsx:averagespeed>"
|
||||
+ "<gsx:averagemovingspeed><![CDATA[11,184.68]]>"
|
||||
+ "</gsx:averagemovingspeed>"
|
||||
+ "<gsx:maxspeed><![CDATA[3,355.40]]></gsx:maxspeed>"
|
||||
+ "<gsx:speedunit><![CDATA[mi/h]]></gsx:speedunit>"
|
||||
+ "<gsx:elevationgain><![CDATA[19,685]]></gsx:elevationgain>"
|
||||
+ "<gsx:minelevation><![CDATA[-1,640]]></gsx:minelevation>"
|
||||
+ "<gsx:maxelevation><![CDATA[1,804]]></gsx:maxelevation>"
|
||||
+ "<gsx:elevationunit><![CDATA[ft]]></gsx:elevationunit>"
|
||||
+ "<gsx:map>"
|
||||
+ "<![CDATA[https://maps.google.com/maps/ms?msa=0&msid=trackMapId]]>"
|
||||
+ "</gsx:map>"
|
||||
+ "</entry>";
|
||||
|
||||
assertEquals(
|
||||
"https://spreadsheets.google.com/feeds/list/ssid/wsid/private/full",
|
||||
docsHelper.writtenSheetUri);
|
||||
assertEquals(expectedData, docsHelper.writtenData);
|
||||
}
|
||||
|
||||
public void testAddTrackRow_metric() throws Exception {
|
||||
StringWritingDocsHelper docsHelper = new StringWritingDocsHelper();
|
||||
addTrackRow(docsHelper, true);
|
||||
|
||||
// The imperial test verifies that the tags come out in the proper order,
|
||||
// and with the proper names. We need only verify that the labels are
|
||||
// correct, and that at least one of the unit-dependent value tags is
|
||||
// correct.
|
||||
assertTrue(docsHelper.writtenData.contains(
|
||||
"<gsx:distanceunit><![CDATA[km]]></gsx:distanceunit>"));
|
||||
assertTrue(docsHelper.writtenData.contains(
|
||||
"<gsx:speedunit><![CDATA[km/h]]></gsx:speedunit>"));
|
||||
assertTrue(docsHelper.writtenData.contains(
|
||||
"<gsx:elevationunit><![CDATA[m]]></gsx:elevationunit>"));
|
||||
|
||||
assertTrue(docsHelper.writtenData.contains(
|
||||
"<gsx:distance><![CDATA[20.00]]></gsx:distance>"));
|
||||
}
|
||||
|
||||
/** Adds a row to the spreadsheet, using the provided helper. */
|
||||
@UsesMocks({AuthManager.class, MockResources.class, Track.class})
|
||||
private void addTrackRow(DocsHelper docsHelper, boolean useMetric) throws IOException {
|
||||
AuthManager mockAuthManager = AndroidMock.createMock(AuthManager.class);
|
||||
AndroidMock.replay(mockAuthManager);
|
||||
|
||||
TripStatistics stats = new TripStatistics();
|
||||
stats.setStartTime(TIME);
|
||||
stats.setTotalTime(5000);
|
||||
stats.setMovingTime(4000);
|
||||
stats.setTotalDistance(20000);
|
||||
stats.setMaxSpeed(1500);
|
||||
stats.setTotalElevationGain(6000);
|
||||
stats.setMinElevation(-500);
|
||||
stats.setMaxElevation(550);
|
||||
|
||||
Track track = new Track();
|
||||
track.setName("trackName");
|
||||
track.setDescription("trackDescription");
|
||||
track.setMapId("trackMapId");
|
||||
track.setStatistics(stats);
|
||||
|
||||
docsHelper.addTrackRow(getContext(), mockAuthManager, "ssid", "wsid",
|
||||
track, useMetric);
|
||||
}
|
||||
}
|
||||
@@ -1,60 +0,0 @@
|
||||
/*
|
||||
* Copyright 2010 Google Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
|
||||
* use this file except in compliance with the License. You may obtain a copy of
|
||||
* the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
|
||||
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
|
||||
* License for the specific language governing permissions and limitations under
|
||||
* the License.
|
||||
*/
|
||||
package com.google.android.apps.mytracks.io.docs;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
/**
|
||||
* This class tests {@link DocsTagBuilder}
|
||||
*
|
||||
* @author Matthew Simmons
|
||||
*/
|
||||
public class DocsTagBuilderTest extends TestCase {
|
||||
public void testAppend() {
|
||||
assertEquals("<gsx:tag><![CDATA[value]]></gsx:tag>",
|
||||
new DocsTagBuilder(false).append("tag", "value").build());
|
||||
}
|
||||
|
||||
public void testMultiAppend() {
|
||||
String actual = new DocsTagBuilder(false)
|
||||
.append("tag1", "value1")
|
||||
.append("tag2", "value2")
|
||||
.build();
|
||||
|
||||
assertEquals("<gsx:tag1><![CDATA[value1]]></gsx:tag1>"
|
||||
+ "<gsx:tag2><![CDATA[value2]]></gsx:tag2>", actual);
|
||||
}
|
||||
|
||||
public void testAppendLargeUnits_imperial() {
|
||||
assertEquals("<gsx:tag><![CDATA[62.14]]></gsx:tag>",
|
||||
new DocsTagBuilder(false).appendLargeUnits("tag", 100.0).build());
|
||||
}
|
||||
|
||||
public void testAppendLargeUnits_metric() {
|
||||
assertEquals("<gsx:tag><![CDATA[100.00]]></gsx:tag>",
|
||||
new DocsTagBuilder(true).appendLargeUnits("tag", 100.0).build());
|
||||
}
|
||||
|
||||
public void testAppendSmallUnits_imperial() {
|
||||
assertEquals("<gsx:tag><![CDATA[328]]></gsx:tag>",
|
||||
new DocsTagBuilder(false).appendSmallUnits("tag", 100.0).build());
|
||||
}
|
||||
|
||||
public void testAppendSmallUnits_metric() {
|
||||
assertEquals("<gsx:tag><![CDATA[100]]></gsx:tag>",
|
||||
new DocsTagBuilder(true).appendSmallUnits("tag", 100.0).build());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
/*
|
||||
* Copyright 2012 Google Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
|
||||
* use this file except in compliance with the License. You may obtain a copy of
|
||||
* the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
|
||||
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
|
||||
* License for the specific language governing permissions and limitations under
|
||||
* the License.
|
||||
*/
|
||||
package com.google.android.apps.mytracks.io.docs;
|
||||
|
||||
import com.google.android.apps.mytracks.content.Track;
|
||||
import com.google.android.apps.mytracks.io.gdata.docs.SpreadsheetsClient.WorksheetEntry;
|
||||
import com.google.android.apps.mytracks.stats.TripStatistics;
|
||||
import com.google.android.apps.mytracks.util.StringUtils;
|
||||
import com.google.wireless.gdata.data.Entry;
|
||||
|
||||
import android.test.AndroidTestCase;
|
||||
|
||||
/**
|
||||
* Tests {@link SendDocsUtils}.
|
||||
*
|
||||
* @author Jimmy Shih
|
||||
*/
|
||||
public class SendDocsUtilsTest extends AndroidTestCase {
|
||||
|
||||
private static final long TIME = 1288721514000L;
|
||||
|
||||
/**
|
||||
* Tests {@link SendDocsUtils#getEntryId(Entry)} with a valid id.
|
||||
*/
|
||||
public void testGetEntryId_valid() {
|
||||
Entry entry = new Entry();
|
||||
entry.setId("https://docs.google.com/feeds/documents/private/full/spreadsheet%3A123");
|
||||
assertEquals("123", SendDocsUtils.getEntryId(entry));
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests {@link SendDocsUtils#getEntryId(Entry)} with an invalid id.
|
||||
*/
|
||||
public void testGetEntryId_invalid() {
|
||||
Entry entry = new Entry();
|
||||
entry.setId("123");
|
||||
assertEquals(null, SendDocsUtils.getEntryId(entry));
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests {@link SendDocsUtils#getNewSpreadsheetId(String)} with a valid id.
|
||||
*/
|
||||
public void testGetNewSpreadsheetId_valid_id() {
|
||||
assertEquals("123", SendDocsUtils.getNewSpreadsheetId(
|
||||
"<id>https://docs.google.com/feeds/documents/private/full/spreadsheet%3A123</id>"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests {@link SendDocsUtils#getNewSpreadsheetId(String)} without an open
|
||||
* tag, <id>.
|
||||
*/
|
||||
public void testGetNewSpreadsheetId_no_open_tag() {
|
||||
assertEquals(null, SendDocsUtils.getNewSpreadsheetId(
|
||||
"https://docs.google.com/feeds/documents/private/full/spreadsheet%3A123</id>"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests {@link SendDocsUtils#getNewSpreadsheetId(String)} without an end tag,
|
||||
* </id>.
|
||||
*/
|
||||
public void testGetNewSpreadsheetId_no_end_tag() {
|
||||
assertEquals(null, SendDocsUtils.getNewSpreadsheetId(
|
||||
"<id>https://docs.google.com/feeds/documents/private/full/spreadsheet%3A123"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests {@link SendDocsUtils#getNewSpreadsheetId(String)} without the url
|
||||
* prefix,
|
||||
* https://docs.google.com/feeds/documents/private/full/spreadsheet%3A.
|
||||
*/
|
||||
public void testGetNewSpreadsheetId_no_prefix() {
|
||||
assertEquals(null, SendDocsUtils.getNewSpreadsheetId("<id>123</id>"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests {@link SendDocsUtils#getWorksheetEntryId(WorksheetEntry)} with a
|
||||
* valid entry.
|
||||
*/
|
||||
public void testGetWorksheetEntryId_valid() {
|
||||
WorksheetEntry entry = new WorksheetEntry();
|
||||
entry.setId("/123");
|
||||
assertEquals("123", SendDocsUtils.getWorksheetEntryId(entry));
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests {@link SendDocsUtils#getWorksheetEntryId(WorksheetEntry)} with a
|
||||
* invalid entry.
|
||||
*/
|
||||
public void testGetWorksheetEntryId_invalid() {
|
||||
WorksheetEntry entry = new WorksheetEntry();
|
||||
entry.setId("123");
|
||||
assertEquals(null, SendDocsUtils.getWorksheetEntryId(entry));
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests {@link SendDocsUtils#getRowContent(Track, boolean,
|
||||
* android.content.Context)} with metric units.
|
||||
*/
|
||||
public void testGetRowContent_metric() throws Exception {
|
||||
Track track = getTrack();
|
||||
String expectedData = "<entry xmlns='http://www.w3.org/2005/Atom' "
|
||||
+ "xmlns:gsx='http://schemas.google.com/spreadsheets/2006/extended'>"
|
||||
+ "<gsx:name><![CDATA[trackName]]></gsx:name>"
|
||||
+ "<gsx:description><![CDATA[trackDescription]]></gsx:description>" + "<gsx:date><![CDATA["
|
||||
+ StringUtils.formatDateTime(getContext(), TIME) + "]]></gsx:date>"
|
||||
+ "<gsx:totaltime><![CDATA[00:05]]></gsx:totaltime>"
|
||||
+ "<gsx:movingtime><![CDATA[00:04]]></gsx:movingtime>"
|
||||
+ "<gsx:distance><![CDATA[20.00]]></gsx:distance>"
|
||||
+ "<gsx:distanceunit><![CDATA[km]]></gsx:distanceunit>"
|
||||
+ "<gsx:averagespeed><![CDATA[14,400.00]]></gsx:averagespeed>"
|
||||
+ "<gsx:averagemovingspeed><![CDATA[18,000.00]]>" + "</gsx:averagemovingspeed>"
|
||||
+ "<gsx:maxspeed><![CDATA[5,400.00]]></gsx:maxspeed>"
|
||||
+ "<gsx:speedunit><![CDATA[km/h]]></gsx:speedunit>"
|
||||
+ "<gsx:elevationgain><![CDATA[6,000]]></gsx:elevationgain>"
|
||||
+ "<gsx:minelevation><![CDATA[-500]]></gsx:minelevation>"
|
||||
+ "<gsx:maxelevation><![CDATA[550]]></gsx:maxelevation>"
|
||||
+ "<gsx:elevationunit><![CDATA[m]]></gsx:elevationunit>" + "<gsx:map>"
|
||||
+ "<![CDATA[https://maps.google.com/maps/ms?msa=0&msid=trackMapId]]>" + "</gsx:map>"
|
||||
+ "</entry>";
|
||||
assertEquals(expectedData, SendDocsUtils.getRowContent(track, true, getContext()));
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests {@link SendDocsUtils#getRowContent(Track, boolean,
|
||||
* android.content.Context)} with imperial units.
|
||||
*/
|
||||
public void testGetRowContent_imperial() throws Exception {
|
||||
Track track = getTrack();
|
||||
String expectedData = "<entry xmlns='http://www.w3.org/2005/Atom' "
|
||||
+ "xmlns:gsx='http://schemas.google.com/spreadsheets/2006/extended'>"
|
||||
+ "<gsx:name><![CDATA[trackName]]></gsx:name>"
|
||||
+ "<gsx:description><![CDATA[trackDescription]]></gsx:description>" + "<gsx:date><![CDATA["
|
||||
+ StringUtils.formatDateTime(getContext(), TIME) + "]]></gsx:date>"
|
||||
+ "<gsx:totaltime><![CDATA[00:05]]></gsx:totaltime>"
|
||||
+ "<gsx:movingtime><![CDATA[00:04]]></gsx:movingtime>"
|
||||
+ "<gsx:distance><![CDATA[12.43]]></gsx:distance>"
|
||||
+ "<gsx:distanceunit><![CDATA[mi]]></gsx:distanceunit>"
|
||||
+ "<gsx:averagespeed><![CDATA[8,947.75]]></gsx:averagespeed>"
|
||||
+ "<gsx:averagemovingspeed><![CDATA[11,184.68]]>" + "</gsx:averagemovingspeed>"
|
||||
+ "<gsx:maxspeed><![CDATA[3,355.40]]></gsx:maxspeed>"
|
||||
+ "<gsx:speedunit><![CDATA[mi/h]]></gsx:speedunit>"
|
||||
+ "<gsx:elevationgain><![CDATA[19,685]]></gsx:elevationgain>"
|
||||
+ "<gsx:minelevation><![CDATA[-1,640]]></gsx:minelevation>"
|
||||
+ "<gsx:maxelevation><![CDATA[1,804]]></gsx:maxelevation>"
|
||||
+ "<gsx:elevationunit><![CDATA[ft]]></gsx:elevationunit>" + "<gsx:map>"
|
||||
+ "<![CDATA[https://maps.google.com/maps/ms?msa=0&msid=trackMapId]]>" + "</gsx:map>"
|
||||
+ "</entry>";
|
||||
assertEquals(expectedData, SendDocsUtils.getRowContent(track, false, getContext()));
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a track for testing {@link SendDocsUtils#getRowContent(Track, boolean,
|
||||
* android.content.Context)}.
|
||||
*/
|
||||
private Track getTrack() {
|
||||
TripStatistics stats = new TripStatistics();
|
||||
stats.setStartTime(TIME);
|
||||
stats.setTotalTime(5000);
|
||||
stats.setMovingTime(4000);
|
||||
stats.setTotalDistance(20000);
|
||||
stats.setMaxSpeed(1500);
|
||||
stats.setTotalElevationGain(6000);
|
||||
stats.setMinElevation(-500);
|
||||
stats.setMaxElevation(550);
|
||||
|
||||
Track track = new Track();
|
||||
track.setName("trackName");
|
||||
track.setDescription("trackDescription");
|
||||
track.setMapId("trackMapId");
|
||||
track.setStatistics(stats);
|
||||
return track;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests {@link SendDocsUtils#appendTag(StringBuilder, String, String)} with
|
||||
* repeated calls.
|
||||
*/
|
||||
public void testAppendTag() {
|
||||
StringBuilder stringBuilder = new StringBuilder();
|
||||
SendDocsUtils.appendTag(stringBuilder, "name1", "value1");
|
||||
assertEquals("<gsx:name1><![CDATA[value1]]></gsx:name1>", stringBuilder.toString());
|
||||
|
||||
SendDocsUtils.appendTag(stringBuilder, "name2", "value2");
|
||||
assertEquals(
|
||||
"<gsx:name1><![CDATA[value1]]></gsx:name1><gsx:name2><![CDATA[value2]]></gsx:name2>",
|
||||
stringBuilder.toString());
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests {@link SendDocsUtils#getDistance(double, boolean)} with metric units.
|
||||
*/
|
||||
public void testGetDistance_metric() {
|
||||
assertEquals("1.22", SendDocsUtils.getDistance(1222.3, true));
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests {@link SendDocsUtils#getDistance(double, boolean)} with imperial
|
||||
* units.
|
||||
*/
|
||||
public void testGetDistance_imperial() {
|
||||
assertEquals("0.76", SendDocsUtils.getDistance(1222.3, false));
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests {@link SendDocsUtils#getSpeed(double, boolean)} with metric units.
|
||||
*/
|
||||
public void testGetSpeed_metric() {
|
||||
assertEquals("15.55", SendDocsUtils.getSpeed(4.32, true));
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests {@link SendDocsUtils#getSpeed(double, boolean)} with imperial units.
|
||||
*/
|
||||
public void testGetSpeed_imperial() {
|
||||
assertEquals("9.66", SendDocsUtils.getSpeed(4.32, false));
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests {@link SendDocsUtils#getElevation(double, boolean)} with metric
|
||||
* units.
|
||||
*/
|
||||
public void testGetElevation_metric() {
|
||||
assertEquals("3", SendDocsUtils.getElevation(3.456, true));
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests {@link SendDocsUtils#getElevation(double, boolean)} with imperial
|
||||
* units.
|
||||
*/
|
||||
public void testGetElevation_imperial() {
|
||||
assertEquals("11", SendDocsUtils.getElevation(3.456, false));
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,81 @@
|
||||
// Copyright 2010 Google Inc. All Rights Reserved.
|
||||
|
||||
/*
|
||||
* Copyright 2012 Google Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
|
||||
* use this file except in compliance with the License. You may obtain a copy of
|
||||
* the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
|
||||
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
|
||||
* License for the specific language governing permissions and limitations under
|
||||
* the License.
|
||||
*/
|
||||
package com.google.android.apps.mytracks.io.file;
|
||||
|
||||
|
||||
/**
|
||||
* Tests for the CSV track exporter.
|
||||
* Tests for {@link CsvTrackWriter}.
|
||||
*
|
||||
* @author Rodrigo Damazio
|
||||
*/
|
||||
public class CsvTrackWriterTest extends TrackFormatWriterTest {
|
||||
|
||||
private static final String BEGIN_TAG = "\"";
|
||||
private static final String END_TAG = "\"\n";
|
||||
private static final String SEPARATOR = "\",\"";
|
||||
|
||||
public void testCsvOutput() throws Exception {
|
||||
String expectedTrackHeader = getExpectedLine(
|
||||
"Track name", "Activity type", "Track description");
|
||||
String expectedTrack = getExpectedLine(TRACK_NAME, TRACK_CATEGORY, TRACK_DESCRIPTION);
|
||||
String expectedMarkerHeader = getExpectedLine("Marker name", "Marker type",
|
||||
"Marker description", "Latitude (deg)", "Longitude (deg)", "Altitude (m)", "Bearing (deg)",
|
||||
"Accuracy (m)", "Speed (m/s)", "Time");
|
||||
String expectedMarker1 = getExpectedLine(WAYPOINT1_NAME, WAYPOINT1_CATEGORY,
|
||||
WAYPOINT1_DESCRIPTION, "1.0", "-1.0", "10.0", "100.0", "1,000", "10,000",
|
||||
"1970-01-01T00:01:40Z");
|
||||
String expectedMarker2 = getExpectedLine(WAYPOINT2_NAME, WAYPOINT2_CATEGORY,
|
||||
WAYPOINT2_DESCRIPTION, "2.0", "-2.0", "20.0", "200.0", "2,000", "20,000",
|
||||
"1970-01-01T00:03:20Z");
|
||||
String expectedPointHeader = getExpectedLine("Segment", "Point", "Latitude (deg)",
|
||||
"Longitude (deg)", "Altitude (m)", "Bearing (deg)", "Accuracy (m)", "Speed (m/s)", "Time",
|
||||
"Power (W)", "Cadence (rpm)", "Heart rate (bpm)", "Battery level (%)");
|
||||
String expectedPoint1 = getExpectedLine("1", "1", "0.0", "0.0", "0.0", "0.0", "0", "0",
|
||||
"1970-01-01T00:00:00Z", "100.0", "200.0", "300.0", "400.0");
|
||||
String expectedPoint2 = getExpectedLine("1", "2", "1.0", "-1.0", "10.0", "100.0", "1,000",
|
||||
"10,000", "1970-01-01T00:01:40Z", "101.0", "201.0", "301.0", "401.0");
|
||||
String expectedPoint3 = getExpectedLine("2", "1", "2.0", "-2.0", "20.0", "200.0", "2,000",
|
||||
"20,000", "1970-01-01T00:03:20Z", "102.0", "202.0", "302.0", "402.0");
|
||||
String expectedPoint4 = getExpectedLine("2", "2", "3.0", "-3.0", "30.0", "300.0", "3,000",
|
||||
"30,000", "1970-01-01T00:05:00Z", "103.0", "203.0", "303.0", "403.0");
|
||||
String expected = expectedTrackHeader + expectedTrack + "\n"
|
||||
+ expectedMarkerHeader + expectedMarker1 + expectedMarker2 + "\n"
|
||||
+ expectedPointHeader + expectedPoint1 + expectedPoint2 + expectedPoint3 + expectedPoint4;
|
||||
|
||||
CsvTrackWriter writer = new CsvTrackWriter(getContext());
|
||||
assertEquals(expected, writeTrack(writer));
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the expected CSV line from a list of expected values.
|
||||
*
|
||||
* @param values expected values
|
||||
*/
|
||||
private String getExpectedLine(String... values) {
|
||||
StringBuilder builder = new StringBuilder();
|
||||
builder.append(BEGIN_TAG);
|
||||
boolean first = true;
|
||||
for (String value : values) {
|
||||
if (!first) {
|
||||
builder.append(SEPARATOR);
|
||||
}
|
||||
first = false;
|
||||
builder.append(value);
|
||||
}
|
||||
builder.append(END_TAG);
|
||||
return builder.toString();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,23 +1,34 @@
|
||||
// Copyright 2010 Google Inc. All Rights Reserved.
|
||||
/*
|
||||
* Copyright 2010 Google Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
|
||||
* use this file except in compliance with the License. You may obtain a copy of
|
||||
* the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
|
||||
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
|
||||
* License for the specific language governing permissions and limitations under
|
||||
* the License.
|
||||
*/
|
||||
package com.google.android.apps.mytracks.io.file;
|
||||
|
||||
import com.google.android.apps.mytracks.io.file.GpxTrackWriter;
|
||||
import com.google.android.apps.mytracks.io.file.TrackFormatWriter;
|
||||
import java.util.List;
|
||||
|
||||
import org.w3c.dom.Document;
|
||||
import org.w3c.dom.Element;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Tests for the GPX track exporter.
|
||||
* Tests for {@link GpxTrackWriter}.
|
||||
*
|
||||
* @author Rodrigo Damazio
|
||||
*/
|
||||
public class GpxTrackWriterTest extends TrackFormatWriterTest {
|
||||
|
||||
public void testXmlOutput() throws Exception {
|
||||
TrackFormatWriter writer = new GpxTrackWriter();
|
||||
TrackFormatWriter writer = new GpxTrackWriter(getContext());
|
||||
String result = writeTrack(writer);
|
||||
Document doc = parseXmlDocument(result);
|
||||
|
||||
@@ -25,44 +36,41 @@ public class GpxTrackWriterTest extends TrackFormatWriterTest {
|
||||
Element trackTag = getChildElement(gpxTag, "trk");
|
||||
assertEquals(TRACK_NAME, getChildTextValue(trackTag, "name"));
|
||||
assertEquals(TRACK_DESCRIPTION, getChildTextValue(trackTag, "desc"));
|
||||
assertEquals(Long.toString(TRACK_ID),
|
||||
getChildTextValue(trackTag, "number"));
|
||||
List<Element> segmentTags = getChildElements(trackTag, "trkseg", 2);
|
||||
List<Element> segPointTags = getChildElements(segmentTags.get(0), "trkpt", 2);
|
||||
assertTagMatchesLocation(segPointTags.get(0),
|
||||
"0", "0", "1970-01-01T02:46:40Z", "0");
|
||||
assertTagMatchesLocation(segPointTags.get(1),
|
||||
"1", "-1", "1970-01-01T02:46:41Z", "5000000");
|
||||
assertTagMatchesLocation(segPointTags.get(0), "0", "0", "1970-01-01T00:00:00Z", "0");
|
||||
assertTagMatchesLocation(segPointTags.get(1), "1", "-1", "1970-01-01T00:01:40Z", "10");
|
||||
|
||||
segPointTags = getChildElements(segmentTags.get(1), "trkpt", 2);
|
||||
assertTagMatchesLocation(segPointTags.get(0),
|
||||
"2", "-2", "1970-01-01T02:46:42Z", "10000000");
|
||||
assertTagMatchesLocation(segPointTags.get(1),
|
||||
"3", "-3", "1970-01-01T02:46:43Z", "15000000");
|
||||
assertTagMatchesLocation(segPointTags.get(0), "2", "-2", "1970-01-01T00:03:20Z", "20");
|
||||
assertTagMatchesLocation(segPointTags.get(1), "3", "-3", "1970-01-01T00:05:00Z", "30");
|
||||
|
||||
List<Element> waypointTags = getChildElements(gpxTag, "wpt", 2);
|
||||
Element wptTag = waypointTags.get(0);
|
||||
assertEquals(WAYPOINT1_NAME, getChildTextValue(wptTag, "name"));
|
||||
assertEquals(WAYPOINT1_DESCRIPTION, getChildTextValue(wptTag, "desc"));
|
||||
assertTagMatchesLocation(wptTag,
|
||||
"1", "-1", "1970-01-01T02:46:41Z", "5000000");
|
||||
assertTagMatchesLocation(wptTag, "1", "-1", "1970-01-01T00:01:40Z", "10");
|
||||
|
||||
wptTag = waypointTags.get(1);
|
||||
assertEquals(WAYPOINT2_NAME, getChildTextValue(wptTag, "name"));
|
||||
assertEquals(WAYPOINT2_DESCRIPTION, getChildTextValue(wptTag, "desc"));
|
||||
assertTagMatchesLocation(wptTag,
|
||||
"2", "-2", "1970-01-01T02:46:42Z", "10000000");
|
||||
assertTagMatchesLocation(wptTag, "2", "-2", "1970-01-01T00:03:20Z", "20");
|
||||
}
|
||||
|
||||
/**
|
||||
* Asserts that the given tag describes the location given by the
|
||||
* Strings lat, lon, time, and ele.
|
||||
* Asserts that the given tag describes a location.
|
||||
*
|
||||
* @param tag the tag
|
||||
* @param latitude the location's latitude
|
||||
* @param longitude the location's longitude
|
||||
* @param time the location's time
|
||||
* @param elevation the location's elevation
|
||||
*/
|
||||
private void assertTagMatchesLocation(Element tag, String lat,
|
||||
String lon, String time, String ele) {
|
||||
assertEquals(lat, tag.getAttribute("lat"));
|
||||
assertEquals(lon, tag.getAttribute("lon"));
|
||||
private void assertTagMatchesLocation(
|
||||
Element tag, String latitude, String longitude, String time, String elevation) {
|
||||
assertEquals(latitude, tag.getAttribute("lat"));
|
||||
assertEquals(longitude, tag.getAttribute("lon"));
|
||||
assertEquals(time, getChildTextValue(tag, "time"));
|
||||
assertEquals(ele, getChildTextValue(tag, "ele"));
|
||||
assertEquals(elevation, getChildTextValue(tag, "ele"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,47 +1,60 @@
|
||||
// Copyright 2010 Google Inc. All Rights Reserved.
|
||||
/*
|
||||
* Copyright 2010 Google Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
|
||||
* use this file except in compliance with the License. You may obtain a copy of
|
||||
* the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
|
||||
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
|
||||
* License for the specific language governing permissions and limitations under
|
||||
* the License.
|
||||
*/
|
||||
package com.google.android.apps.mytracks.io.file;
|
||||
|
||||
import com.google.android.apps.mytracks.content.DescriptionGenerator;
|
||||
import com.google.android.apps.mytracks.content.Track;
|
||||
import com.google.android.apps.mytracks.io.file.KmlTrackWriter;
|
||||
import com.google.android.apps.mytracks.util.StringUtils;
|
||||
import com.google.android.apps.mytracks.content.Waypoint;
|
||||
|
||||
import android.location.Location;
|
||||
|
||||
import org.w3c.dom.Document;
|
||||
import org.w3c.dom.Element;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Vector;
|
||||
|
||||
import org.w3c.dom.Document;
|
||||
import org.w3c.dom.Element;
|
||||
|
||||
/**
|
||||
* Tests for the KML track exporter.
|
||||
* Tests for {@link KmlTrackWriter}.
|
||||
*
|
||||
* @author Rodrigo Damazio
|
||||
*/
|
||||
public class KmlTrackWriterTest extends TrackFormatWriterTest {
|
||||
|
||||
private static final String FULL_TRACK_DESCRIPTION = "full track description";
|
||||
|
||||
/**
|
||||
* A fake version of {@link StringUtils} which returns a fixed track
|
||||
* A fake version of {@link DescriptionGenerator} which returns a fixed track
|
||||
* description, thus not depending on the context.
|
||||
*/
|
||||
private class FakeStringUtils extends StringUtils {
|
||||
public FakeStringUtils() {
|
||||
super(null);
|
||||
private class FakeDescriptionGenerator implements DescriptionGenerator {
|
||||
@Override
|
||||
public String generateTrackDescription(
|
||||
Track aTrack, Vector<Double> distances, Vector<Double> elevations) {
|
||||
return FULL_TRACK_DESCRIPTION;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String generateTrackDescription(Track trackToDescribe,
|
||||
Vector<Double> distances, Vector<Double> elevations) {
|
||||
assertSame(KmlTrackWriterTest.super.track, trackToDescribe);
|
||||
assertTrue(distances.isEmpty());
|
||||
assertTrue(elevations.isEmpty());
|
||||
return FULL_TRACK_DESCRIPTION;
|
||||
public String generateWaypointDescription(Waypoint waypoint) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public void testXmlOutput() throws Exception {
|
||||
KmlTrackWriter writer = new KmlTrackWriter(new FakeStringUtils());
|
||||
KmlTrackWriter writer = new KmlTrackWriter(getContext(), new FakeDescriptionGenerator());
|
||||
String result = writeTrack(writer);
|
||||
Document doc = parseXmlDocument(result);
|
||||
|
||||
@@ -50,65 +63,63 @@ public class KmlTrackWriterTest extends TrackFormatWriterTest {
|
||||
assertEquals(TRACK_NAME, getChildTextValue(docTag, "name"));
|
||||
assertEquals(TRACK_DESCRIPTION, getChildTextValue(docTag, "description"));
|
||||
|
||||
// There are 5 placemarks - start, segments, end, waypoint 1, waypoint 2
|
||||
List<Element> placemarkTags = getChildElements(docTag, "Placemark", 5);
|
||||
assertTagIsPlacemark(placemarkTags.get(0),
|
||||
"(Start)", TRACK_DESCRIPTION, location1);
|
||||
assertTagIsPlacemark(placemarkTags.get(2),
|
||||
"(End)", FULL_TRACK_DESCRIPTION, location4);
|
||||
assertTagIsPlacemark(placemarkTags.get(3),
|
||||
WAYPOINT1_NAME, WAYPOINT1_DESCRIPTION, location2);
|
||||
assertTagIsPlacemark(placemarkTags.get(4),
|
||||
WAYPOINT2_NAME, WAYPOINT2_DESCRIPTION, location3);
|
||||
// There are 3 placemarks - start, track, and end
|
||||
List<Element> placemarkTags = getChildElements(docTag, "Placemark", 3);
|
||||
assertTagIsPlacemark(
|
||||
placemarkTags.get(0), TRACK_NAME + " (Start)", TRACK_DESCRIPTION, location1);
|
||||
assertTagIsPlacemark(
|
||||
placemarkTags.get(2), TRACK_NAME + " (End)", FULL_TRACK_DESCRIPTION, location4);
|
||||
|
||||
List<Element> folderTag = getChildElements(docTag, "Folder", 1);
|
||||
List<Element> folderPlacemarkTags = getChildElements(folderTag.get(0), "Placemark", 2);
|
||||
assertTagIsPlacemark(
|
||||
folderPlacemarkTags.get(0), WAYPOINT1_NAME, WAYPOINT1_DESCRIPTION, location2);
|
||||
assertTagIsPlacemark(
|
||||
folderPlacemarkTags.get(1), WAYPOINT2_NAME, WAYPOINT2_DESCRIPTION, location3);
|
||||
|
||||
Element trackPlacemarkTag = placemarkTags.get(1);
|
||||
assertEquals(TRACK_NAME, getChildTextValue(trackPlacemarkTag, "name"));
|
||||
assertEquals(TRACK_DESCRIPTION,
|
||||
getChildTextValue(trackPlacemarkTag, "description"));
|
||||
Element geometryTag = getChildElement(trackPlacemarkTag, "MultiGeometry");
|
||||
List<Element> segmentTags = getChildElements(geometryTag, "LineString", 2);
|
||||
assertTagHasPoints(segmentTags.get(0), location1, location2);
|
||||
assertTagHasPoints(segmentTags.get(1), location3, location4);
|
||||
assertEquals(TRACK_DESCRIPTION, getChildTextValue(trackPlacemarkTag, "description"));
|
||||
Element multiTrackTag = getChildElement(trackPlacemarkTag, "gx:MultiTrack");
|
||||
List<Element> trackTags = getChildElements(multiTrackTag, "gx:Track", 2);
|
||||
assertTagHasPoints(trackTags.get(0), location1, location2);
|
||||
assertTagHasPoints(trackTags.get(1), location3, location4);
|
||||
}
|
||||
|
||||
/**
|
||||
* Asserts that the given XML tag is a placemark with the given properties.
|
||||
* Asserts that the given tag is a placemark with the given properties.
|
||||
*
|
||||
* @param tag the tag to analyze
|
||||
* @param name the expected name for the placemark
|
||||
* @param description the expected description for the placemark
|
||||
* @param location the expected location of the placemark
|
||||
* @param tag the tag
|
||||
* @param name the expected placemark name
|
||||
* @param description the expected placemark description
|
||||
* @param location the expected placemark location
|
||||
*/
|
||||
private void assertTagIsPlacemark(Element tag, String name,
|
||||
String description, Location location) {
|
||||
private void assertTagIsPlacemark(
|
||||
Element tag, String name, String description, Location location) {
|
||||
assertEquals(name, getChildTextValue(tag, "name"));
|
||||
assertEquals(description, getChildTextValue(tag, "description"));
|
||||
Element pointTag = getChildElement(tag, "Point");
|
||||
String expectedCoords =
|
||||
location.getLongitude() + "," + location.getLatitude();
|
||||
String actualCoords = getChildTextValue(pointTag, "coordinates");
|
||||
assertEquals(expectedCoords, actualCoords);
|
||||
String expected = location.getLongitude() + "," + location.getLatitude() + ","
|
||||
+ location.getAltitude();
|
||||
String actual = getChildTextValue(pointTag, "coordinates");
|
||||
assertEquals(expected, actual);
|
||||
}
|
||||
|
||||
/**
|
||||
* Asserts that the given tag has a "coordinates" subtag with the given
|
||||
* locations.
|
||||
* Asserts that the given tag has a list of "gx:coord" subtags matching the
|
||||
* expected locations.
|
||||
*
|
||||
* @param tag the tag to analyze
|
||||
* @param locs the locations to expect in the coordinates
|
||||
* @param tag the parent tag
|
||||
* @param locations list of expected locations
|
||||
*/
|
||||
private void assertTagHasPoints(Element tag, Location... locs) {
|
||||
StringBuilder expectedBuilder = new StringBuilder();
|
||||
for (Location loc : locs) {
|
||||
expectedBuilder.append(loc.getLongitude());
|
||||
expectedBuilder.append(',');
|
||||
expectedBuilder.append(loc.getLatitude());
|
||||
expectedBuilder.append(',');
|
||||
expectedBuilder.append(loc.getAltitude());
|
||||
expectedBuilder.append(' ');
|
||||
private void assertTagHasPoints(Element tag, Location... locations) {
|
||||
List<Element> coordTags = getChildElements(tag, "gx:coord", locations.length);
|
||||
for (int i = 0; i < locations.length; i++) {
|
||||
Location location = locations[i];
|
||||
String expected = location.getLongitude() + " " + location.getLatitude() + " "
|
||||
+ location.getAltitude();
|
||||
String actual = coordTags.get(i).getFirstChild().getTextContent();
|
||||
assertEquals(expected, actual);
|
||||
}
|
||||
String expectedCoordinates = expectedBuilder.toString().trim();
|
||||
String actualCoordinates = getChildTextValue(tag, "coordinates").trim();
|
||||
assertEquals(expectedCoordinates, actualCoordinates);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,9 +1,23 @@
|
||||
// Copyright 2010 Google Inc. All Rights Reserved.
|
||||
/*
|
||||
* Copyright 2010 Google Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
|
||||
* use this file except in compliance with the License. You may obtain a copy of
|
||||
* the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
|
||||
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
|
||||
* License for the specific language governing permissions and limitations under
|
||||
* the License.
|
||||
*/
|
||||
package com.google.android.apps.mytracks.io.file;
|
||||
|
||||
import com.google.android.apps.mytracks.content.MyTracksLocation;
|
||||
import com.google.android.apps.mytracks.content.Sensor;
|
||||
import com.google.android.apps.mytracks.util.FileUtils;
|
||||
import com.google.android.apps.mytracks.util.StringUtils;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@@ -11,7 +25,7 @@ import org.w3c.dom.Document;
|
||||
import org.w3c.dom.Element;
|
||||
|
||||
/**
|
||||
* Tests for the GPX track exporter.
|
||||
* Tests for {@link TcxTrackWriter}.
|
||||
*
|
||||
* @author Sandor Dornbush
|
||||
*/
|
||||
@@ -37,42 +51,46 @@ public class TcxTrackWriterTest extends TrackFormatWriterTest {
|
||||
}
|
||||
|
||||
/**
|
||||
* Asserts that the given tags describe the given points, in the same order.
|
||||
* Asserts that the given tags describe the given locations in the same order.
|
||||
*
|
||||
* @param tags list of tags
|
||||
* @param locations list of locations
|
||||
*/
|
||||
private void assertTagsMatchPoints(List<Element> tags, MyTracksLocation... locs) {
|
||||
assertEquals(locs.length, tags.size());
|
||||
for (int i = 0; i < locs.length; i++) {
|
||||
Element tag = tags.get(i);
|
||||
MyTracksLocation loc = locs[i];
|
||||
|
||||
assertTagMatchesLocation(tag, loc);
|
||||
private void assertTagsMatchPoints(List<Element> tags, MyTracksLocation... locations) {
|
||||
assertEquals(locations.length, tags.size());
|
||||
for (int i = 0; i < locations.length; i++) {
|
||||
assertTagMatchesLocation(tags.get(i), locations[i]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Asserts that the given tag describes the given location.
|
||||
*
|
||||
* @param tag the tag
|
||||
* @param location the location
|
||||
*/
|
||||
private void assertTagMatchesLocation(Element tag, MyTracksLocation loc) {
|
||||
Element posTag = getChildElement(tag, "Position");
|
||||
assertEquals(Double.toString(loc.getLatitude()),
|
||||
getChildTextValue(posTag, "LatitudeDegrees"));
|
||||
assertEquals(Double.toString(loc.getLongitude()),
|
||||
getChildTextValue(posTag, "LongitudeDegrees"));
|
||||
private void assertTagMatchesLocation(Element tag, MyTracksLocation location) {
|
||||
assertEquals(StringUtils.formatDateTimeIso8601(location.getTime()), getChildTextValue(tag, "Time"));
|
||||
|
||||
assertEquals(FileUtils.FILE_TIMESTAMP_FORMAT.format(loc.getTime()),
|
||||
getChildTextValue(tag, "Time"));
|
||||
assertEquals(Double.toString(loc.getAltitude()),
|
||||
getChildTextValue(tag, "AltitudeMeters"));
|
||||
assertTrue(loc.getSensorDataSet() != null);
|
||||
Sensor.SensorDataSet sds = loc.getSensorDataSet();
|
||||
Element positionTag = getChildElement(tag, "Position");
|
||||
assertEquals(
|
||||
Double.toString(location.getLatitude()), getChildTextValue(positionTag, "LatitudeDegrees"));
|
||||
assertEquals(Double.toString(location.getLongitude()),
|
||||
getChildTextValue(positionTag, "LongitudeDegrees"));
|
||||
|
||||
List<Element> bpm = getChildElements(tag, "HeartRateBpm", 1);
|
||||
assertEquals(Double.toString(location.getAltitude()), getChildTextValue(tag, "AltitudeMeters"));
|
||||
assertTrue(location.getSensorDataSet() != null);
|
||||
Sensor.SensorDataSet sds = location.getSensorDataSet();
|
||||
|
||||
List<Element> heartRate = getChildElements(tag, "HeartRateBpm", 1);
|
||||
assertEquals(Integer.toString(sds.getHeartRate().getValue()),
|
||||
getChildTextValue(bpm.get(0), "Value"));
|
||||
getChildTextValue(heartRate.get(0), "Value"));
|
||||
|
||||
List<Element> ext = getChildElements(tag, "Extensions", 1);
|
||||
List<Element> tpx = getChildElements(ext.get(0), "TPX", 1);
|
||||
assertEquals(Integer.toString(sds.getPower().getValue()),
|
||||
getChildTextValue(tpx.get(0), "Watts"));
|
||||
List<Element> extensions = getChildElements(tag, "Extensions", 1);
|
||||
List<Element> tpx = getChildElements(extensions.get(0), "TPX", 1);
|
||||
assertEquals(
|
||||
Integer.toString(sds.getCadence().getValue()), getChildTextValue(tpx.get(0), "RunCadence"));
|
||||
assertEquals(
|
||||
Integer.toString(sds.getPower().getValue()), getChildTextValue(tpx.get(0), "Watts"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,86 +0,0 @@
|
||||
/*
|
||||
* Copyright 2010 Google Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
|
||||
* use this file except in compliance with the License. You may obtain a copy of
|
||||
* the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
|
||||
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
|
||||
* License for the specific language governing permissions and limitations under
|
||||
* the License.
|
||||
*/
|
||||
package com.google.android.apps.mytracks.io.file;
|
||||
|
||||
import static com.google.android.testing.mocking.AndroidMock.expect;
|
||||
|
||||
import com.google.android.apps.mytracks.io.file.TempFileCleaner;
|
||||
import com.google.android.testing.mocking.AndroidMock;
|
||||
import com.google.android.testing.mocking.UsesMocks;
|
||||
|
||||
import android.test.AndroidTestCase;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
/**
|
||||
* @author Sandor Dornbush
|
||||
*/
|
||||
public class TempFileCleanerTest extends AndroidTestCase {
|
||||
|
||||
@UsesMocks({
|
||||
File.class,
|
||||
})
|
||||
|
||||
public void test_noDir() {
|
||||
File dir = AndroidMock.createMock(File.class, "/no_file");
|
||||
TempFileCleaner cleaner = new TempFileCleaner(0);
|
||||
expect(dir.exists()).andStubReturn(false);
|
||||
AndroidMock.replay(dir);
|
||||
assertEquals(0, cleaner.cleanTmpDirectory(dir));
|
||||
AndroidMock.verify(dir);
|
||||
}
|
||||
|
||||
public void test_emptyDir() {
|
||||
File dir = AndroidMock.createMock(File.class, "/no_file");
|
||||
TempFileCleaner cleaner = new TempFileCleaner(0);
|
||||
expect(dir.exists()).andStubReturn(true);
|
||||
expect(dir.listFiles()).andStubReturn(new File[0]);
|
||||
AndroidMock.replay(dir);
|
||||
assertEquals(0, cleaner.cleanTmpDirectory(dir));
|
||||
AndroidMock.verify(dir);
|
||||
}
|
||||
|
||||
public void test_newFile() {
|
||||
File dir = AndroidMock.createMock(File.class, "/no_file");
|
||||
long now = 100000000;
|
||||
TempFileCleaner cleaner = new TempFileCleaner(now);
|
||||
expect(dir.exists()).andStubReturn(true);
|
||||
File file = AndroidMock.createMock(File.class, "/no_file/foo");
|
||||
expect(file.lastModified()).andStubReturn(now);
|
||||
File[] list = { file };
|
||||
expect(dir.listFiles()).andStubReturn(list);
|
||||
|
||||
AndroidMock.replay(dir, file);
|
||||
assertEquals(0, cleaner.cleanTmpDirectory(dir));
|
||||
AndroidMock.verify(dir, file);
|
||||
}
|
||||
|
||||
public void test_oldFile() {
|
||||
File dir = AndroidMock.createMock(File.class, "/no_file");
|
||||
long now = 100000000;
|
||||
TempFileCleaner cleaner = new TempFileCleaner(now);
|
||||
expect(dir.exists()).andStubReturn(true);
|
||||
File file = AndroidMock.createMock(File.class, "/no_file/foo");
|
||||
expect(file.lastModified()).andStubReturn(now - 3600001);
|
||||
expect(file.delete()).andStubReturn(true);
|
||||
File[] list = { file };
|
||||
expect(dir.listFiles()).andStubReturn(list);
|
||||
|
||||
AndroidMock.replay(dir, file);
|
||||
assertEquals(1, cleaner.cleanTmpDirectory(dir));
|
||||
AndroidMock.verify(dir, file);
|
||||
}
|
||||
}
|
||||
+34
-23
@@ -39,13 +39,15 @@ public abstract class TrackFormatWriterTest extends AndroidTestCase {
|
||||
// All the user-provided strings have "]]>" to ensure that proper escaping is
|
||||
// being done.
|
||||
protected static final String TRACK_NAME = "Home]]>";
|
||||
protected static final String TRACK_CATEGORY = "Hiking";
|
||||
protected static final String TRACK_DESCRIPTION = "The long ]]> journey home";
|
||||
protected static final String WAYPOINT1_NAME = "point]]>1";
|
||||
protected static final String WAYPOINT1_CATEGORY = "Statistics";
|
||||
protected static final String WAYPOINT1_DESCRIPTION = "point 1]]>description";
|
||||
protected static final String WAYPOINT2_NAME = "point]]>2";
|
||||
protected static final String WAYPOINT2_CATEGORY = "Waypoint";
|
||||
protected static final String WAYPOINT2_DESCRIPTION = "point 2]]>description";
|
||||
private static final int BUFFER_SIZE = 10240;
|
||||
protected static final long TRACK_ID = 12345L;
|
||||
protected Track track;
|
||||
protected MyTracksLocation location1, location2, location3, location4;
|
||||
protected Waypoint wp1, wp2;
|
||||
@@ -55,8 +57,8 @@ public abstract class TrackFormatWriterTest extends AndroidTestCase {
|
||||
super.setUp();
|
||||
|
||||
track = new Track();
|
||||
track.setId(TRACK_ID);
|
||||
track.setName(TRACK_NAME);
|
||||
track.setCategory(TRACK_CATEGORY);
|
||||
track.setDescription(TRACK_DESCRIPTION);
|
||||
|
||||
location1 = new MyTracksLocation("mock");
|
||||
@@ -69,33 +71,40 @@ public abstract class TrackFormatWriterTest extends AndroidTestCase {
|
||||
wp2 = new Waypoint();
|
||||
wp1.setLocation(location2);
|
||||
wp1.setName(WAYPOINT1_NAME);
|
||||
wp1.setCategory(WAYPOINT1_CATEGORY);
|
||||
wp1.setDescription(WAYPOINT1_DESCRIPTION);
|
||||
wp2.setLocation(location3);
|
||||
wp2.setName(WAYPOINT2_NAME);
|
||||
wp2.setCategory(WAYPOINT2_CATEGORY);
|
||||
wp2.setDescription(WAYPOINT2_DESCRIPTION);
|
||||
}
|
||||
|
||||
/**
|
||||
* Populates the given locations with coordinates and time.
|
||||
* Populates a list of locations with values.
|
||||
*
|
||||
* @param locations a list of locations
|
||||
*/
|
||||
protected void populateLocations(MyTracksLocation... locs) {
|
||||
for (int i = 0; i < locs.length; i++) {
|
||||
MyTracksLocation loc = locs[i];
|
||||
loc.setAltitude(i * 5000000);
|
||||
loc.setLatitude(i);
|
||||
loc.setLongitude(-i);
|
||||
loc.setTime(10000000 + i * 1000);
|
||||
Sensor.SensorData.Builder hr = Sensor.SensorData.newBuilder()
|
||||
.setValue(100 + i)
|
||||
.setState(Sensor.SensorState.SENDING);
|
||||
Sensor.SensorData.Builder power = Sensor.SensorData.newBuilder()
|
||||
.setValue(400 + i)
|
||||
.setState(Sensor.SensorState.SENDING);
|
||||
Sensor.SensorDataSet sds =
|
||||
Sensor.SensorDataSet.newBuilder().setHeartRate(hr.build())
|
||||
.setPower(power)
|
||||
.build();
|
||||
loc.setSensorData(sds);
|
||||
private void populateLocations(MyTracksLocation... locations) {
|
||||
for (int i = 0; i < locations.length; i++) {
|
||||
MyTracksLocation location = locations[i];
|
||||
location.setLatitude(i);
|
||||
location.setLongitude(-i);
|
||||
location.setAltitude(i * 10);
|
||||
location.setBearing(i * 100);
|
||||
location.setAccuracy(i * 1000);
|
||||
location.setSpeed(i * 10000);
|
||||
location.setTime(i * 100000);
|
||||
Sensor.SensorData.Builder power = Sensor.SensorData.newBuilder().setValue(100 + i)
|
||||
.setState(Sensor.SensorState.SENDING);
|
||||
Sensor.SensorData.Builder cadence = Sensor.SensorData.newBuilder().setValue(200 + i)
|
||||
.setState(Sensor.SensorState.SENDING);
|
||||
Sensor.SensorData.Builder heartRate = Sensor.SensorData.newBuilder().setValue(300 + i)
|
||||
.setState(Sensor.SensorState.SENDING);
|
||||
Sensor.SensorData.Builder batteryLevel = Sensor.SensorData.newBuilder().setValue(400 + i)
|
||||
.setState(Sensor.SensorState.SENDING);
|
||||
Sensor.SensorDataSet sensorDataSet = Sensor.SensorDataSet.newBuilder().setPower(power)
|
||||
.setCadence(cadence).setHeartRate(heartRate).setBatteryLevel(batteryLevel).build();
|
||||
location.setSensorData(sensorDataSet);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -110,6 +119,10 @@ public abstract class TrackFormatWriterTest extends AndroidTestCase {
|
||||
OutputStream output = new ByteArrayOutputStream(BUFFER_SIZE);
|
||||
writer.prepare(track, output);
|
||||
writer.writeHeader();
|
||||
writer.writeBeginWaypoints();
|
||||
writer.writeWaypoint(wp1);
|
||||
writer.writeWaypoint(wp2);
|
||||
writer.writeEndWaypoints();
|
||||
writer.writeBeginTrack(location1);
|
||||
writer.writeOpenSegment();
|
||||
writer.writeLocation(location1);
|
||||
@@ -120,8 +133,6 @@ public abstract class TrackFormatWriterTest extends AndroidTestCase {
|
||||
writer.writeLocation(location4);
|
||||
writer.writeCloseSegment();
|
||||
writer.writeEndTrack(location4);
|
||||
writer.writeWaypoint(wp1);
|
||||
writer.writeWaypoint(wp2);
|
||||
writer.writeFooter();
|
||||
writer.close();
|
||||
return output.toString();
|
||||
|
||||
@@ -20,6 +20,7 @@ import android.test.RenamingDelegatingContext;
|
||||
import android.test.mock.MockContentResolver;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.OutputStream;
|
||||
|
||||
@@ -59,6 +60,10 @@ public class TrackWriterTest extends AndroidTestCase {
|
||||
|
||||
this.stream = stream;
|
||||
this.canWrite = canWrite;
|
||||
|
||||
// The directory is set in the canWriteFile. However, this class
|
||||
// overwrites canWriteFile, thus needs to set it.
|
||||
setDirectory(new File("/"));
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
+85
@@ -0,0 +1,85 @@
|
||||
/*
|
||||
* Copyright 2012 Google Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
|
||||
* use this file except in compliance with the License. You may obtain a copy of
|
||||
* the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
|
||||
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
|
||||
* License for the specific language governing permissions and limitations under
|
||||
* the License.
|
||||
*/
|
||||
package com.google.android.apps.mytracks.io.fusiontables;
|
||||
|
||||
import com.google.android.apps.mytracks.io.docs.SendDocsActivity;
|
||||
import com.google.android.apps.mytracks.io.sendtogoogle.SendRequest;
|
||||
import com.google.android.apps.mytracks.io.sendtogoogle.UploadResultActivity;
|
||||
|
||||
import android.test.AndroidTestCase;
|
||||
|
||||
/**
|
||||
* Tests the {@link SendFusionTablesActivity}.
|
||||
*
|
||||
* @author Youtao Liu
|
||||
*/
|
||||
public class SendFusionTablesActivityTest extends AndroidTestCase {
|
||||
|
||||
private SendFusionTablesActivity sendFusionTablesActivity;
|
||||
private SendRequest sendRequest;
|
||||
|
||||
@Override
|
||||
protected void setUp() throws Exception {
|
||||
super.setUp();
|
||||
sendRequest = new SendRequest(1L, true, false, true);
|
||||
sendFusionTablesActivity = new SendFusionTablesActivity();
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the method
|
||||
* {@link SendFusionTablesActivity#getNextClass(SendRequest, boolean)}. Sets
|
||||
* the flags of "sendDocs" and "cancel" to false and false.
|
||||
*/
|
||||
public void testGetNextClass_notCancelNotSendDocs() {
|
||||
sendRequest.setSendDocs(false);
|
||||
Class<?> next = sendFusionTablesActivity.getNextClass(sendRequest, false);
|
||||
assertEquals(UploadResultActivity.class, next);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the method
|
||||
* {@link SendFusionTablesActivity#getNextClass(SendRequest, boolean)}. Sets
|
||||
* the flags of "sendDocs" and "cancel" to true and false.
|
||||
*/
|
||||
public void testGetNextClass_notCancelSendDocs() {
|
||||
sendRequest.setSendDocs(true);
|
||||
Class<?> next = sendFusionTablesActivity.getNextClass(sendRequest, false);
|
||||
assertEquals(SendDocsActivity.class, next);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the method
|
||||
* {@link SendFusionTablesActivity#getNextClass(SendRequest,boolean)}. Sets
|
||||
* the flags of "sendDocs" and "cancel" to true and true.
|
||||
*/
|
||||
public void testGetNextClass_cancelSendDocs() {
|
||||
sendRequest.setSendDocs(true);
|
||||
Class<?> next = sendFusionTablesActivity.getNextClass(sendRequest, true);
|
||||
assertEquals(UploadResultActivity.class, next);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the method
|
||||
* {@link SendFusionTablesActivity#getNextClass(SendRequest,boolean)}. Sets
|
||||
* the flags of "sendDocs" and "cancel" to false and true.
|
||||
*/
|
||||
public void testGetNextClass_cancelNotSendDocs() {
|
||||
sendRequest.setSendDocs(false);
|
||||
Class<?> next = sendFusionTablesActivity.getNextClass(sendRequest, true);
|
||||
assertEquals(UploadResultActivity.class, next);
|
||||
}
|
||||
|
||||
}
|
||||
+285
@@ -0,0 +1,285 @@
|
||||
/*
|
||||
* Copyright 2012 Google Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
|
||||
* use this file except in compliance with the License. You may obtain a copy of
|
||||
* the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
|
||||
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
|
||||
* License for the specific language governing permissions and limitations under
|
||||
* the License.
|
||||
*/
|
||||
package com.google.android.apps.mytracks.io.fusiontables;
|
||||
|
||||
import com.google.android.apps.mytracks.content.Track;
|
||||
import com.google.android.apps.mytracks.stats.TripStatistics;
|
||||
|
||||
import android.location.Location;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.InputStream;
|
||||
import java.util.ArrayList;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
/**
|
||||
* Tests {@link SendFusionTablesUtils}.
|
||||
*
|
||||
* @author Jimmy Shih
|
||||
*/
|
||||
public class SendFusionTablesUtilsTest extends TestCase {
|
||||
|
||||
/**
|
||||
* Tests {@link SendFusionTablesUtils#getMapUrl(Track)} with null track.
|
||||
*/
|
||||
public void testGetMapUrl_null_track() {
|
||||
assertEquals(null, SendFusionTablesUtils.getMapUrl(null));
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests {@link SendFusionTablesUtils#getMapUrl(Track)} with null table id.
|
||||
*/
|
||||
public void testGetMapUrl_null_table_id() {
|
||||
Track track = new Track();
|
||||
TripStatistics stats = new TripStatistics();
|
||||
stats.setBounds((int) 100.E6, (int) 10.E6, (int) 50.E6, (int) 5.E6);
|
||||
track.setStatistics(stats);
|
||||
track.setTableId(null);
|
||||
assertEquals(null, SendFusionTablesUtils.getMapUrl(track));
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests {@link SendFusionTablesUtils#getMapUrl(Track)} with null stats.
|
||||
*/
|
||||
public void testGetMapUrl_null_stats() {
|
||||
Track track = new Track();
|
||||
track.setStatistics(null);
|
||||
track.setTableId("123");
|
||||
assertEquals(null, SendFusionTablesUtils.getMapUrl(track));
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests {@link SendFusionTablesUtils#getMapUrl(Track)} with a valid track.
|
||||
*/
|
||||
public void testGetMapUrl_valid_track() {
|
||||
Track track = new Track();
|
||||
TripStatistics stats = new TripStatistics();
|
||||
stats.setBounds((int) 100.E6, (int) 10.E6, (int) 50.E6, (int) 5.E6);
|
||||
track.setStatistics(stats);
|
||||
track.setTableId("123");
|
||||
assertEquals(
|
||||
"https://www.google.com/fusiontables/embedviz?"
|
||||
+ "viz=MAP&q=select+col0,+col1,+col2,+col3+from+123+&h=false&lat=7.500000&lng=75.000000"
|
||||
+ "&z=15&t=1&l=col2", SendFusionTablesUtils.getMapUrl(track));
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests (@link {@link SendFusionTablesUtils#formatSqlValues(String...)} with
|
||||
* no value.
|
||||
*/
|
||||
public void testFormatSqlValues_no_value() {
|
||||
assertEquals("()", SendFusionTablesUtils.formatSqlValues());
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests (@link {@link SendFusionTablesUtils#formatSqlValues(String...)} with
|
||||
* an empty string.
|
||||
*/
|
||||
public void testFormatSqlValues_empty_string() {
|
||||
assertEquals("(\'\')", SendFusionTablesUtils.formatSqlValues(""));
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests (@link {@link SendFusionTablesUtils#formatSqlValues(String...)} with
|
||||
* one value.
|
||||
*/
|
||||
public void testFormatSqlValues_one_value() {
|
||||
assertEquals("(\'first\')", SendFusionTablesUtils.formatSqlValues("first"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests (@link {@link SendFusionTablesUtils#formatSqlValues(String...)} with
|
||||
* two values.
|
||||
*/
|
||||
public void testFormatSqlValues_two_values() {
|
||||
assertEquals(
|
||||
"(\'first\',\'second\')", SendFusionTablesUtils.formatSqlValues("first", "second"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests {@link SendFusionTablesUtils#escapeSqlString(String)} with a value
|
||||
* containing several single quotes.
|
||||
*/
|
||||
public void testEscapeSqValuel() {
|
||||
String value = "let's'";
|
||||
assertEquals("let''s''", SendFusionTablesUtils.escapeSqlString(value));
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests {@link SendFusionTablesUtils#getKmlPoint(Location)} with a null
|
||||
* point.
|
||||
*/
|
||||
public void testGetKmlPoint_null_point() {
|
||||
assertEquals(
|
||||
"<Point><coordinates></coordinates></Point>", SendFusionTablesUtils.getKmlPoint(null));
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests {@link SendFusionTablesUtils#getKmlPoint(Location)} with a valid
|
||||
* point.
|
||||
*/
|
||||
public void testGetKmlPoint_valid_point() {
|
||||
Location location = new Location("test");
|
||||
location.setLongitude(10.1);
|
||||
location.setLatitude(20.2);
|
||||
location.setAltitude(30.3);
|
||||
assertEquals("<Point><coordinates>10.1,20.2,30.3</coordinates></Point>",
|
||||
SendFusionTablesUtils.getKmlPoint(location));
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests {@link SendFusionTablesUtils#getKmlLineString(ArrayList)} with a null
|
||||
* locations.
|
||||
*/
|
||||
public void testKmlLineString_null_locations() {
|
||||
assertEquals("<LineString><coordinates></coordinates></LineString>",
|
||||
SendFusionTablesUtils.getKmlLineString(null));
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests {@link SendFusionTablesUtils#getKmlLineString(ArrayList)} with no
|
||||
* location.
|
||||
*/
|
||||
public void testKmlLineString_no_location() {
|
||||
ArrayList<Location> locations = new ArrayList<Location>();
|
||||
assertEquals("<LineString><coordinates></coordinates></LineString>",
|
||||
SendFusionTablesUtils.getKmlLineString(locations));
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests {@link SendFusionTablesUtils#getKmlLineString(ArrayList)} with one
|
||||
* location.
|
||||
*/
|
||||
public void testKmlLineString_one_location() {
|
||||
ArrayList<Location> locations = new ArrayList<Location>();
|
||||
Location location = new Location("test");
|
||||
location.setLongitude(10.1);
|
||||
location.setLatitude(20.2);
|
||||
location.setAltitude(30.3);
|
||||
locations.add(location);
|
||||
assertEquals("<LineString><coordinates>10.1,20.2,30.3</coordinates></LineString>",
|
||||
SendFusionTablesUtils.getKmlLineString(locations));
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests {@link SendFusionTablesUtils#getKmlLineString(ArrayList)} with two
|
||||
* locations.
|
||||
*/
|
||||
public void testKmlLineString_two_locations() {
|
||||
ArrayList<Location> locations = new ArrayList<Location>();
|
||||
Location location1 = new Location("test");
|
||||
location1.setLongitude(10.1);
|
||||
location1.setLatitude(20.2);
|
||||
location1.setAltitude(30.3);
|
||||
locations.add(location1);
|
||||
|
||||
Location location2 = new Location("test");
|
||||
location2.setLongitude(1.1);
|
||||
location2.setLatitude(2.2);
|
||||
location2.removeAltitude();
|
||||
locations.add(location2);
|
||||
|
||||
assertEquals("<LineString><coordinates>10.1,20.2,30.3 1.1,2.2</coordinates></LineString>",
|
||||
SendFusionTablesUtils.getKmlLineString(locations));
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests {@link SendFusionTablesUtils#appendLocation(Location, StringBuilder)}
|
||||
* with no altitude.
|
||||
*/
|
||||
public void testAppendLocation_no_altitude() {
|
||||
StringBuilder builder = new StringBuilder();
|
||||
Location location = new Location("test");
|
||||
location.setLongitude(10.1);
|
||||
location.setLatitude(20.2);
|
||||
location.removeAltitude();
|
||||
SendFusionTablesUtils.appendLocation(location, builder);
|
||||
assertEquals("10.1,20.2", builder.toString());
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests {@link SendFusionTablesUtils#appendLocation(Location, StringBuilder)}
|
||||
* with altitude.
|
||||
*/
|
||||
public void testAppendLocation_has_altitude() {
|
||||
StringBuilder builder = new StringBuilder();
|
||||
Location location = new Location("test");
|
||||
location.setLongitude(10.1);
|
||||
location.setLatitude(20.2);
|
||||
location.setAltitude(30.3);
|
||||
SendFusionTablesUtils.appendLocation(location, builder);
|
||||
assertEquals("10.1,20.2,30.3", builder.toString());
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests {@link SendFusionTablesUtils#getTableId(InputStream)} with a null
|
||||
* inputstream.
|
||||
*/
|
||||
public void testGetTableId_null() {
|
||||
assertEquals(null, SendFusionTablesUtils.getTableId(null));
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests {@link SendFusionTablesUtils#getTableId(InputStream)} with an
|
||||
* inputstream containing no data.
|
||||
*/
|
||||
public void testGetTableId_no_data() {
|
||||
InputStream inputStream = new ByteArrayInputStream(new byte[0]);
|
||||
assertEquals(null, SendFusionTablesUtils.getTableId(inputStream));
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests {@link SendFusionTablesUtils#getTableId(InputStream)} with an empty
|
||||
* inputstream.
|
||||
*/
|
||||
public void testGetTableId_empty() {
|
||||
String string = "";
|
||||
InputStream inputStream = new ByteArrayInputStream(string.getBytes());
|
||||
assertEquals(null, SendFusionTablesUtils.getTableId(inputStream));
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests {@link SendFusionTablesUtils#getTableId(InputStream)} with an one
|
||||
* line inputstream.
|
||||
*/
|
||||
public void testGetTableId_one_line() {
|
||||
String string = "tableid";
|
||||
InputStream inputStream = new ByteArrayInputStream(string.getBytes());
|
||||
assertEquals(null, SendFusionTablesUtils.getTableId(inputStream));
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests {@link SendFusionTablesUtils#getTableId(InputStream)} with an
|
||||
* inputstream not containing "tableid".
|
||||
*/
|
||||
public void testGetTableId_no_table_id() {
|
||||
String string = "error\n123";
|
||||
InputStream inputStream = new ByteArrayInputStream(string.getBytes());
|
||||
assertEquals(null, SendFusionTablesUtils.getTableId(inputStream));
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests {@link SendFusionTablesUtils#getTableId(InputStream)} with a valid
|
||||
* inputstream.
|
||||
*/
|
||||
public void testGetTableId() {
|
||||
String string = "tableid\n123";
|
||||
InputStream inputStream = null;
|
||||
inputStream = new ByteArrayInputStream(string.getBytes());
|
||||
assertEquals("123", SendFusionTablesUtils.getTableId(inputStream));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
/*
|
||||
* Copyright 2012 Google Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
|
||||
* use this file except in compliance with the License. You may obtain a copy of
|
||||
* the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
|
||||
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
|
||||
* License for the specific language governing permissions and limitations under
|
||||
* the License.
|
||||
*/
|
||||
package com.google.android.apps.mytracks.io.maps;
|
||||
|
||||
import com.google.android.apps.mytracks.io.gdata.maps.MapsMapMetadata;
|
||||
import com.google.android.maps.mytracks.R;
|
||||
|
||||
import android.content.Intent;
|
||||
import android.test.AndroidTestCase;
|
||||
import android.widget.ArrayAdapter;
|
||||
|
||||
import java.util.ArrayList;
|
||||
|
||||
/**
|
||||
* Tests the {@link ChooseMapActivity}.
|
||||
*
|
||||
* @author Youtao Liu
|
||||
*/
|
||||
public class ChooseMapActivityTest extends AndroidTestCase {
|
||||
|
||||
private static final String MAP_ID = "mapid";
|
||||
private static final String MAP_TITLE = "title";
|
||||
private static final String MAP_DESC = "desc";
|
||||
|
||||
private ArrayList<String> mapIds = new ArrayList<String>();
|
||||
private ArrayList<MapsMapMetadata> mapDatas = new ArrayList<MapsMapMetadata>();
|
||||
private boolean errorDialogShown = false;
|
||||
private boolean progressDialogRemoved = false;
|
||||
|
||||
/**
|
||||
* Creates a class to override some methods of {@link ChooseMapActivity} to
|
||||
* makes it testable.
|
||||
*
|
||||
* @author youtaol
|
||||
*/
|
||||
public class ChooseMapActivityMock extends ChooseMapActivity {
|
||||
/**
|
||||
* By overriding this method, avoids to start next activity.
|
||||
*/
|
||||
@Override
|
||||
public void startActivity(Intent intent) {}
|
||||
|
||||
/**
|
||||
* By overriding this method, avoids to show an error dialog and set the
|
||||
* show flag to true.
|
||||
*/
|
||||
@Override
|
||||
public void showErrorDialog() {
|
||||
errorDialogShown = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* By overriding this method, avoids to show an error dialog and set the
|
||||
* show flag to true.
|
||||
*/
|
||||
@Override
|
||||
public void removeProgressDialog() {
|
||||
progressDialogRemoved = true;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the method
|
||||
* {@link ChooseMapActivity#onAsyncTaskCompleted(boolean, ArrayList, ArrayList)}
|
||||
* . An alert dialog should be shown when there is no map.
|
||||
*/
|
||||
public void testOnAsyncTaskCompleted_fail() {
|
||||
ChooseMapActivityMock chooseMapActivityMock = new ChooseMapActivityMock();
|
||||
errorDialogShown = false;
|
||||
progressDialogRemoved = false;
|
||||
chooseMapActivityMock.onAsyncTaskCompleted(false, null, null);
|
||||
assertTrue(progressDialogRemoved);
|
||||
assertTrue(errorDialogShown);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the method
|
||||
* {@link ChooseMapActivity#onAsyncTaskCompleted(boolean, ArrayList, ArrayList)}
|
||||
* . Check the logic when there is only map.
|
||||
*/
|
||||
public void testOnAsyncTaskCompleted_success_oneMap() {
|
||||
ChooseMapActivityMock chooseMapActivityMock = new ChooseMapActivityMock();
|
||||
chooseMapActivityMock.arrayAdapter = new ArrayAdapter<ChooseMapActivity.ListItem>(getContext(),
|
||||
R.layout.choose_map_item);
|
||||
simulateMaps(1);
|
||||
chooseMapActivityMock.onAsyncTaskCompleted(true, mapIds, mapDatas);
|
||||
assertEquals(1, chooseMapActivityMock.arrayAdapter.getCount());
|
||||
assertEquals(MAP_ID + "0", chooseMapActivityMock.arrayAdapter.getItem(0).getMapId());
|
||||
assertEquals(MAP_TITLE + "0", chooseMapActivityMock.arrayAdapter.getItem(0).getMapData()
|
||||
.getTitle());
|
||||
assertEquals(MAP_DESC + "0", chooseMapActivityMock.arrayAdapter.getItem(0).getMapData()
|
||||
.getDescription());
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the method
|
||||
* {@link ChooseMapActivity#onAsyncTaskCompleted(boolean, ArrayList, ArrayList)}
|
||||
* . Check the logic when there are 10 maps.
|
||||
*/
|
||||
public void testOnAsyncTaskCompleted_success_twoMaps() {
|
||||
ChooseMapActivityMock chooseMapActivityMock = new ChooseMapActivityMock();
|
||||
chooseMapActivityMock.arrayAdapter = new ArrayAdapter<ChooseMapActivity.ListItem>(getContext(),
|
||||
R.layout.choose_map_item);
|
||||
simulateMaps(10);
|
||||
chooseMapActivityMock.onAsyncTaskCompleted(true, mapIds, mapDatas);
|
||||
assertEquals(10, chooseMapActivityMock.arrayAdapter.getCount());
|
||||
assertEquals(MAP_ID + "9", chooseMapActivityMock.arrayAdapter.getItem(9).getMapId());
|
||||
assertEquals(MAP_TITLE + "9", chooseMapActivityMock.arrayAdapter.getItem(9).getMapData()
|
||||
.getTitle());
|
||||
assertEquals(MAP_DESC + "9", chooseMapActivityMock.arrayAdapter.getItem(9).getMapData()
|
||||
.getDescription());
|
||||
}
|
||||
|
||||
/**
|
||||
* Simulates map data for the test.
|
||||
*
|
||||
* @param number of data should be simulated.
|
||||
*/
|
||||
private void simulateMaps(int number) {
|
||||
mapIds = new ArrayList<String>();
|
||||
mapDatas = new ArrayList<MapsMapMetadata>();
|
||||
for (int i = 0; i < number; i++) {
|
||||
mapIds.add(MAP_ID + i);
|
||||
MapsMapMetadata metaData = new MapsMapMetadata();
|
||||
metaData.setTitle(MAP_TITLE + i);
|
||||
metaData.setDescription(MAP_DESC + i);
|
||||
metaData.setSearchable(true);
|
||||
mapDatas.add(metaData);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
/*
|
||||
* Copyright 2012 Google Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
|
||||
* use this file except in compliance with the License. You may obtain a copy of
|
||||
* the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
|
||||
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
|
||||
* License for the specific language governing permissions and limitations under
|
||||
* the License.
|
||||
*/
|
||||
package com.google.android.apps.mytracks.io.maps;
|
||||
|
||||
import com.google.android.apps.mytracks.io.docs.SendDocsActivity;
|
||||
import com.google.android.apps.mytracks.io.fusiontables.SendFusionTablesActivity;
|
||||
import com.google.android.apps.mytracks.io.sendtogoogle.SendRequest;
|
||||
import com.google.android.apps.mytracks.io.sendtogoogle.UploadResultActivity;
|
||||
|
||||
import android.test.AndroidTestCase;
|
||||
|
||||
/**
|
||||
* Tests the {@link SendMapsActivity}.
|
||||
*
|
||||
* @author Youtao Liu
|
||||
*/
|
||||
public class SendMapsActivityTest extends AndroidTestCase {
|
||||
|
||||
private SendMapsActivity sendMapsActivity;
|
||||
private SendRequest sendRequest;
|
||||
|
||||
@Override
|
||||
protected void setUp() throws Exception {
|
||||
super.setUp();
|
||||
sendRequest = new SendRequest(1L, true, false, true);
|
||||
sendMapsActivity = new SendMapsActivity();
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the method
|
||||
* {@link SendMapsActivity#getNextClass(SendRequest, boolean)}. Sets the flags
|
||||
* of "sendFusionTables","sendDocs" and "cancel" to true, true and false.
|
||||
*/
|
||||
public void testGetNextClass_notCancelSendFusionTables() {
|
||||
sendRequest.setSendFusionTables(true);
|
||||
sendRequest.setSendDocs(true);
|
||||
Class<?> next = sendMapsActivity.getNextClass(sendRequest, false);
|
||||
assertEquals(SendFusionTablesActivity.class, next);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the method
|
||||
* {@link SendMapsActivity#getNextClass(SendRequest, boolean)}. Sets the flags
|
||||
* of "sendFusionTables","sendDocs" and "cancel" to false, true and false.
|
||||
*/
|
||||
public void testGetNextClass_notCancelSendDocs() {
|
||||
sendRequest.setSendFusionTables(false);
|
||||
sendRequest.setSendDocs(true);
|
||||
Class<?> next = sendMapsActivity.getNextClass(sendRequest, false);
|
||||
assertEquals(SendDocsActivity.class, next);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the method
|
||||
* {@link SendMapsActivity#getNextClass(SendRequest, boolean)}. Sets the flags
|
||||
* of "sendFusionTables","sendDocs" and "cancel" to false, false and false.
|
||||
*/
|
||||
public void testGetNextClass_notCancelNotSend() {
|
||||
sendRequest.setSendFusionTables(false);
|
||||
sendRequest.setSendDocs(false);
|
||||
Class<?> next = sendMapsActivity.getNextClass(sendRequest, false);
|
||||
assertEquals(UploadResultActivity.class, next);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the method
|
||||
* {@link SendMapsActivity#getNextClass(SendRequest, boolean)}. Sets the flags
|
||||
* of "sendFusionTables","sendDocs" and "cancel" to true, true and true.
|
||||
*/
|
||||
public void testGetNextClass_cancelSendDocs() {
|
||||
sendRequest.setSendFusionTables(true);
|
||||
sendRequest.setSendDocs(true);
|
||||
Class<?> next = sendMapsActivity.getNextClass(sendRequest, true);
|
||||
assertEquals(UploadResultActivity.class, next);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
/*
|
||||
* Copyright 2012 Google Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
|
||||
* use this file except in compliance with the License. You may obtain a copy of
|
||||
* the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
|
||||
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
|
||||
* License for the specific language governing permissions and limitations under
|
||||
* the License.
|
||||
*/
|
||||
package com.google.android.apps.mytracks.io.maps;
|
||||
|
||||
import com.google.android.apps.mytracks.content.Track;
|
||||
import com.google.android.apps.mytracks.io.gdata.maps.MapsFeature;
|
||||
import com.google.android.maps.GeoPoint;
|
||||
|
||||
import android.location.Location;
|
||||
|
||||
import java.util.ArrayList;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
/**
|
||||
* Tests {@link SendMapsUtils}.
|
||||
*
|
||||
* @author Jimmy Shih
|
||||
*/
|
||||
public class SendMapsUtilsTest extends TestCase {
|
||||
|
||||
/**
|
||||
* Tests {@link SendMapsUtils#getMapUrl(Track)} with null track.
|
||||
*/
|
||||
public void testGetMapUrl_null_track() {
|
||||
assertEquals(null, SendMapsUtils.getMapUrl(null));
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests {@link SendMapsUtils#getMapUrl(Track)} with null map id.
|
||||
*/
|
||||
public void testGetMapUrl_null_map_id() {
|
||||
Track track = new Track();
|
||||
track.setMapId(null);
|
||||
assertEquals(null, SendMapsUtils.getMapUrl(track));
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests {@link SendMapsUtils#getMapUrl(Track)} with a valid track.
|
||||
*/
|
||||
public void testGetMapUrl_valid_track() {
|
||||
Track track = new Track();
|
||||
track.setMapId("123");
|
||||
assertEquals("https://maps.google.com/maps/ms?msa=0&msid=123", SendMapsUtils.getMapUrl(track));
|
||||
}
|
||||
|
||||
/**
|
||||
* Test {@link SendMapsUtils#buildMapsMarkerFeature(String, String, String,
|
||||
* GeoPoint)} with a title.
|
||||
*/
|
||||
public void testBuildMapsMarkerFeature_with_title() {
|
||||
MapsFeature mapFeature = SendMapsUtils.buildMapsMarkerFeature(
|
||||
"name", "this\nmap\ndescription", "url", new GeoPoint(123, 456));
|
||||
assertEquals(MapsFeature.MARKER, mapFeature.getType());
|
||||
assertNotNull(mapFeature.getAndroidId());
|
||||
assertEquals("name", mapFeature.getTitle());
|
||||
assertEquals("this<br>map<br>description", mapFeature.getDescription());
|
||||
assertEquals("url", mapFeature.getIconUrl());
|
||||
assertEquals(123, mapFeature.getPoint(0).getLatitudeE6());
|
||||
assertEquals(456, mapFeature.getPoint(0).getLongitudeE6());
|
||||
}
|
||||
|
||||
/**
|
||||
* Test {@link SendMapsUtils#buildMapsMarkerFeature(String, String, String,
|
||||
* GeoPoint)} with an empty title.
|
||||
*/
|
||||
public void testBuildMapsMarkerFeature_empty_title() {
|
||||
MapsFeature mapFeature = SendMapsUtils.buildMapsMarkerFeature(
|
||||
"", "description", "url", new GeoPoint(123, 456));
|
||||
assertEquals(MapsFeature.MARKER, mapFeature.getType());
|
||||
assertNotNull(mapFeature.getAndroidId());
|
||||
assertEquals("-", mapFeature.getTitle());
|
||||
assertEquals("description", mapFeature.getDescription());
|
||||
assertEquals("url", mapFeature.getIconUrl());
|
||||
assertEquals(123, mapFeature.getPoint(0).getLatitudeE6());
|
||||
assertEquals(456, mapFeature.getPoint(0).getLongitudeE6());
|
||||
}
|
||||
|
||||
/**
|
||||
* Test {@link SendMapsUtils#buildMapsMarkerFeature(String, String, String,
|
||||
* GeoPoint)} with a null title.
|
||||
*/
|
||||
public void testBuildMapsMarkerFeature_null_title() {
|
||||
MapsFeature mapFeature = SendMapsUtils.buildMapsMarkerFeature(
|
||||
null, "description", "url", new GeoPoint(123, 456));
|
||||
assertEquals(MapsFeature.MARKER, mapFeature.getType());
|
||||
assertNotNull(mapFeature.getAndroidId());
|
||||
assertEquals("-", mapFeature.getTitle());
|
||||
assertEquals("description", mapFeature.getDescription());
|
||||
assertEquals("url", mapFeature.getIconUrl());
|
||||
assertEquals(123, mapFeature.getPoint(0).getLatitudeE6());
|
||||
assertEquals(456, mapFeature.getPoint(0).getLongitudeE6());
|
||||
}
|
||||
|
||||
/**
|
||||
* Test {@link SendMapsUtils#buildMapsLineFeature(String, ArrayList)} with a
|
||||
* title.
|
||||
*/
|
||||
public void testBuildMapsLineFeature_with_title() {
|
||||
ArrayList<Location> locations = new ArrayList<Location>();
|
||||
Location location = new Location("test");
|
||||
location.setLatitude(50);
|
||||
location.setLongitude(100);
|
||||
locations.add(location);
|
||||
MapsFeature mapFeature = SendMapsUtils.buildMapsLineFeature("name", locations);
|
||||
|
||||
assertEquals(MapsFeature.LINE, mapFeature.getType());
|
||||
assertNotNull(mapFeature.getAndroidId());
|
||||
assertEquals("name", mapFeature.getTitle());
|
||||
assertEquals(0x80FF0000, mapFeature.getColor());
|
||||
assertEquals(50000000, mapFeature.getPoint(0).getLatitudeE6());
|
||||
assertEquals(100000000, mapFeature.getPoint(0).getLongitudeE6());
|
||||
}
|
||||
|
||||
/**
|
||||
* Test {@link SendMapsUtils#buildMapsLineFeature(String, ArrayList)} with an
|
||||
* empty title.
|
||||
*/
|
||||
public void testBuildMapsLineFeature_empty_title() {
|
||||
ArrayList<Location> locations = new ArrayList<Location>();
|
||||
Location location = new Location("test");
|
||||
location.setLatitude(50);
|
||||
location.setLongitude(100);
|
||||
locations.add(location);
|
||||
MapsFeature mapFeature = SendMapsUtils.buildMapsLineFeature("", locations);
|
||||
|
||||
assertEquals(MapsFeature.LINE, mapFeature.getType());
|
||||
assertNotNull(mapFeature.getAndroidId());
|
||||
assertEquals("-", mapFeature.getTitle());
|
||||
assertEquals(0x80FF0000, mapFeature.getColor());
|
||||
assertEquals(50000000, mapFeature.getPoint(0).getLatitudeE6());
|
||||
assertEquals(100000000, mapFeature.getPoint(0).getLongitudeE6());
|
||||
}
|
||||
|
||||
/**
|
||||
* Test {@link SendMapsUtils#buildMapsLineFeature(String, ArrayList)} with a
|
||||
* null title.
|
||||
*/
|
||||
public void testBuildMapsLineFeature_null_title() {
|
||||
ArrayList<Location> locations = new ArrayList<Location>();
|
||||
Location location = new Location("test");
|
||||
location.setLatitude(50);
|
||||
location.setLongitude(100);
|
||||
locations.add(location);
|
||||
MapsFeature mapFeature = SendMapsUtils.buildMapsLineFeature(null, locations);
|
||||
|
||||
assertEquals(MapsFeature.LINE, mapFeature.getType());
|
||||
assertNotNull(mapFeature.getAndroidId());
|
||||
assertEquals("-", mapFeature.getTitle());
|
||||
assertEquals(0x80FF0000, mapFeature.getColor());
|
||||
assertEquals(50000000, mapFeature.getPoint(0).getLatitudeE6());
|
||||
assertEquals(100000000, mapFeature.getPoint(0).getLongitudeE6());
|
||||
}
|
||||
|
||||
/**
|
||||
* Test {@link SendMapsUtils#getGeoPoint(Location)}.
|
||||
*/
|
||||
public void testGeoPoint() {
|
||||
Location location = new Location("test");
|
||||
location.setLatitude(50);
|
||||
location.setLongitude(100);
|
||||
GeoPoint geoPoint = SendMapsUtils.getGeoPoint(location);
|
||||
assertEquals(50000000, geoPoint.getLatitudeE6());
|
||||
assertEquals(100000000, geoPoint.getLongitudeE6());
|
||||
}
|
||||
}
|
||||
-130
@@ -1,130 +0,0 @@
|
||||
/*
|
||||
* Copyright 2011 Google Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
|
||||
* use this file except in compliance with the License. You may obtain a copy of
|
||||
* the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
|
||||
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
|
||||
* License for the specific language governing permissions and limitations under
|
||||
* the License.
|
||||
*/
|
||||
package com.google.android.apps.mytracks.io.sendtogoogle;
|
||||
|
||||
import com.google.android.apps.mytracks.MyTracks;
|
||||
import com.google.android.maps.mytracks.R;
|
||||
|
||||
import android.app.AlertDialog;
|
||||
import android.content.DialogInterface;
|
||||
import android.test.ActivityInstrumentationTestCase2;
|
||||
import android.view.View;
|
||||
import android.widget.ListAdapter;
|
||||
import android.widget.ListView;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Tests {@link ResultDialogFactory}.
|
||||
*
|
||||
* @author Matthew Simmons
|
||||
*/
|
||||
public class ResultDialogFactoryTest extends ActivityInstrumentationTestCase2<MyTracks> {
|
||||
public ResultDialogFactoryTest() {
|
||||
super(MyTracks.class);
|
||||
}
|
||||
|
||||
private List<SendResult> makeResults(SendResult... results) {
|
||||
List<SendResult> resultsList = new ArrayList<SendResult>();
|
||||
for (SendResult result : results) {
|
||||
resultsList.add(result);
|
||||
}
|
||||
return resultsList;
|
||||
}
|
||||
|
||||
private DialogInterface.OnClickListener clickListener = new DialogInterface.OnClickListener() {
|
||||
@Override
|
||||
public void onClick(DialogInterface dialog, int which) {}
|
||||
};
|
||||
|
||||
private MyTracks myTracks;
|
||||
|
||||
protected void setUp() throws Exception {
|
||||
super.setUp();
|
||||
myTracks = getActivity();
|
||||
};
|
||||
|
||||
public void testSuccess_noShare() {
|
||||
List<SendResult> results = makeResults(new SendResult(SendType.MAPS, true),
|
||||
new SendResult(SendType.DOCS, true));
|
||||
|
||||
AlertDialog dialog = ResultDialogFactory.makeDialog(
|
||||
myTracks, results, clickListener, null, null);
|
||||
dialog.show();
|
||||
|
||||
ListView listView = (ListView) dialog.findViewById(R.id.send_to_google_result_list);
|
||||
ListAdapter listAdapter = listView.getAdapter();
|
||||
assertEquals(2, listAdapter.getCount());
|
||||
|
||||
assertEquals(SendType.MAPS, ((SendResult) listAdapter.getItem(0)).getType());
|
||||
assertEquals(SendType.DOCS, ((SendResult) listAdapter.getItem(1)).getType());
|
||||
|
||||
// Checking the return code of Dialog#getButton doesn't appear to be
|
||||
// sufficient, as a Button will be returned even if it doesn't appear in
|
||||
// the rendered dialog.
|
||||
assertEquals(View.VISIBLE, dialog.getButton(AlertDialog.BUTTON_POSITIVE).getVisibility());
|
||||
assertEquals(View.GONE, dialog.getButton(AlertDialog.BUTTON_NEUTRAL).getVisibility());
|
||||
|
||||
assertEquals(View.VISIBLE,
|
||||
dialog.findViewById(R.id.send_to_google_result_comment).getVisibility());
|
||||
assertEquals(View.GONE,
|
||||
dialog.findViewById(R.id.send_to_google_result_error).getVisibility());
|
||||
|
||||
// TODO: Test correct listener invocation. Neither TouchUtils#clickView
|
||||
// nor Button#performClick appear to cause listener invocation. This
|
||||
// might be Android bug
|
||||
// http://code.google.com/p/android/issues/detail?id=6564
|
||||
}
|
||||
|
||||
public void testSuccess_share() {
|
||||
List<SendResult> results = makeResults(
|
||||
new SendResult(SendType.MAPS, true), new SendResult(SendType.DOCS, true));
|
||||
|
||||
AlertDialog dialog = ResultDialogFactory.makeDialog(
|
||||
myTracks, results, clickListener, clickListener, null);
|
||||
dialog.show();
|
||||
|
||||
assertEquals(View.VISIBLE, dialog.getButton(AlertDialog.BUTTON_POSITIVE).getVisibility());
|
||||
assertEquals(View.VISIBLE, dialog.getButton(AlertDialog.BUTTON_NEGATIVE).getVisibility());
|
||||
}
|
||||
|
||||
public void testFailure_noShare() {
|
||||
List<SendResult> results = makeResults(new SendResult(SendType.MAPS, true),
|
||||
new SendResult(SendType.DOCS, false));
|
||||
|
||||
AlertDialog dialog = ResultDialogFactory.makeDialog(
|
||||
myTracks, results, clickListener, null, null);
|
||||
dialog.show();
|
||||
|
||||
assertEquals(View.GONE,
|
||||
dialog.findViewById(R.id.send_to_google_result_comment).getVisibility());
|
||||
assertEquals(View.VISIBLE,
|
||||
dialog.findViewById(R.id.send_to_google_result_error).getVisibility());
|
||||
}
|
||||
|
||||
public void testFailure_share() {
|
||||
List<SendResult> results = makeResults(new SendResult(SendType.MAPS, true),
|
||||
new SendResult(SendType.DOCS, false));
|
||||
|
||||
AlertDialog dialog = ResultDialogFactory.makeDialog(
|
||||
myTracks, results, clickListener, clickListener, null);
|
||||
dialog.show();
|
||||
|
||||
assertEquals(View.VISIBLE, dialog.getButton(AlertDialog.BUTTON_POSITIVE).getVisibility());
|
||||
assertEquals(View.VISIBLE, dialog.getButton(AlertDialog.BUTTON_NEGATIVE).getVisibility());
|
||||
}
|
||||
}
|
||||
-117
@@ -1,117 +0,0 @@
|
||||
/*
|
||||
* Copyright 2011 Google Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
|
||||
* use this file except in compliance with the License. You may obtain a copy of
|
||||
* the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
|
||||
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
|
||||
* License for the specific language governing permissions and limitations under
|
||||
* the License.
|
||||
*/
|
||||
package com.google.android.apps.mytracks.io.sendtogoogle;
|
||||
|
||||
import com.google.android.maps.mytracks.R;
|
||||
|
||||
import android.content.Context;
|
||||
import android.test.AndroidTestCase;
|
||||
import android.view.LayoutInflater;
|
||||
import android.view.View;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Tests {@link ResultListAdapter}.
|
||||
*
|
||||
* @author Matthew Simmons
|
||||
*/
|
||||
public class ResultListAdapterTest extends AndroidTestCase {
|
||||
private static class TestResultListAdapter extends ResultListAdapter {
|
||||
public View contentView;
|
||||
public int drawableId;
|
||||
public int nameId;
|
||||
public int urlId;
|
||||
|
||||
public TestResultListAdapter(Context context, List<SendResult> results) {
|
||||
super(context, 0, results);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void setImage(View content, int drawableId) {
|
||||
saveContentView(content);
|
||||
this.drawableId = drawableId;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void setName(View content, int nameId) {
|
||||
saveContentView(content);
|
||||
this.nameId = nameId;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void setUrl(View content, int urlId) {
|
||||
saveContentView(content);
|
||||
this.urlId = urlId;
|
||||
}
|
||||
|
||||
@SuppressWarnings("hiding")
|
||||
private void saveContentView(View contentView) {
|
||||
if (this.contentView == null) {
|
||||
this.contentView = contentView;
|
||||
} else {
|
||||
AndroidTestCase.assertEquals(this.contentView, contentView);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private final SendType sendType = SendType.MAPS;
|
||||
|
||||
private View inflateContentView(int viewId) {
|
||||
LayoutInflater layoutInflater
|
||||
= (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
|
||||
return layoutInflater.inflate(viewId, null);
|
||||
}
|
||||
|
||||
private List<SendResult> makeResult(SendType type, boolean success) {
|
||||
List<SendResult> results = new ArrayList<SendResult>();
|
||||
results.add(new SendResult(type, success));
|
||||
return results;
|
||||
}
|
||||
|
||||
public void testSuccess_createsNewView() {
|
||||
TestResultListAdapter adapter = new TestResultListAdapter(getContext(),
|
||||
makeResult(sendType, true));
|
||||
adapter.getView(0, null, null);
|
||||
|
||||
assertEquals(R.drawable.success, adapter.drawableId);
|
||||
assertEquals(sendType.getServiceName(), adapter.nameId);
|
||||
assertEquals(sendType.getServiceUrl(), adapter.urlId);
|
||||
}
|
||||
|
||||
public void testSuccess_reusesView() {
|
||||
View contentView = inflateContentView(R.layout.send_to_google_result_list_item);
|
||||
TestResultListAdapter adapter = new TestResultListAdapter(getContext(),
|
||||
makeResult(sendType, true));
|
||||
adapter.getView(0, contentView, null);
|
||||
|
||||
assertEquals(contentView, adapter.contentView);
|
||||
assertEquals(R.drawable.success, adapter.drawableId);
|
||||
assertEquals(sendType.getServiceName(), adapter.nameId);
|
||||
assertEquals(sendType.getServiceUrl(), adapter.urlId);
|
||||
}
|
||||
|
||||
public void testFailure() {
|
||||
TestResultListAdapter adapter = new TestResultListAdapter(getContext(),
|
||||
makeResult(sendType, false));
|
||||
adapter.getView(0, null, null);
|
||||
|
||||
assertEquals(R.drawable.failure, adapter.drawableId);
|
||||
assertEquals(sendType.getServiceName(), adapter.nameId);
|
||||
assertEquals(sendType.getServiceUrl(), adapter.urlId);
|
||||
}
|
||||
}
|
||||
+333
@@ -0,0 +1,333 @@
|
||||
/*
|
||||
* Copyright 2012 Google Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
|
||||
* use this file except in compliance with the License. You may obtain a copy of
|
||||
* the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
|
||||
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
|
||||
* License for the specific language governing permissions and limitations under
|
||||
* the License.
|
||||
*/
|
||||
package com.google.android.apps.mytracks.io.sendtogoogle;
|
||||
|
||||
import android.accounts.Account;
|
||||
import android.os.Parcel;
|
||||
import android.os.Parcelable;
|
||||
import android.test.AndroidTestCase;
|
||||
|
||||
/**
|
||||
* Tests the {@link SendRequest}.
|
||||
*
|
||||
* @author Youtao Liu
|
||||
*/
|
||||
public class SendRequestTest extends AndroidTestCase {
|
||||
private SendRequest sendRequest;
|
||||
|
||||
final static private String ACCOUNTNAME = "testAccount1";
|
||||
final static private String ACCOUNTYPE = "testType1";
|
||||
final static private String MAPID = "mapId1";
|
||||
|
||||
@Override
|
||||
protected void setUp() throws Exception {
|
||||
super.setUp();
|
||||
sendRequest = new SendRequest(1, true, true, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the method {@link SendRequest#getTrackId()}. The value should be set
|
||||
* to 1 when it is initialed in setup method.
|
||||
*/
|
||||
public void testGetTrackId() {
|
||||
assertEquals(1, sendRequest.getTrackId());
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the method {@link SendRequest#isShowMaps()}. The value should be set
|
||||
* to true when it is initialed in setup method.
|
||||
*/
|
||||
public void testIsShowMaps() {
|
||||
assertEquals(true, sendRequest.isShowMaps());
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the method {@link SendRequest#isShowFusionTables()}. The value should
|
||||
* be set to true when it is initialed in setup method.
|
||||
*/
|
||||
public void testIsShowFusionTables() {
|
||||
assertEquals(true, sendRequest.isShowFusionTables());
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the method {@link SendRequest#isShowDocs()}. The value should be set
|
||||
* to true when it is initialed in setup method.
|
||||
*/
|
||||
public void testIsShowDocs() {
|
||||
assertEquals(true, sendRequest.isShowDocs());
|
||||
}
|
||||
|
||||
public void testIsShowAll() {
|
||||
assertEquals(true, sendRequest.isShowAll());
|
||||
sendRequest = new SendRequest(1, false, true, true);
|
||||
assertEquals(false, sendRequest.isShowAll());
|
||||
sendRequest = new SendRequest(1, true, false, true);
|
||||
assertEquals(false, sendRequest.isShowAll());
|
||||
sendRequest = new SendRequest(1, true, true, false);
|
||||
assertEquals(false, sendRequest.isShowAll());
|
||||
sendRequest = new SendRequest(1, false, true, false);
|
||||
assertEquals(false, sendRequest.isShowAll());
|
||||
sendRequest = new SendRequest(1, false, false, false);
|
||||
assertEquals(false, sendRequest.isShowAll());
|
||||
}
|
||||
|
||||
public void testIsSendMaps() {
|
||||
assertEquals(false, sendRequest.isSendMaps());
|
||||
sendRequest.setSendMaps(true);
|
||||
assertEquals(true, sendRequest.isSendMaps());
|
||||
}
|
||||
|
||||
public void testIsSendFusionTables() {
|
||||
assertEquals(false, sendRequest.isSendFusionTables());
|
||||
sendRequest.setSendFusionTables(true);
|
||||
assertEquals(true, sendRequest.isSendFusionTables());
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the method {@link SendRequest#isSendDocs()}. The value should be set
|
||||
* to false which is its default value when it is initialed in setup method.
|
||||
*/
|
||||
public void testIsSendDocs() {
|
||||
assertEquals(false, sendRequest.isSendDocs());
|
||||
sendRequest.setSendDocs(true);
|
||||
assertEquals(true, sendRequest.isSendDocs());
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the method {@link SendRequest#isNewMap()}. The value should be set to
|
||||
* false which is its default value when it is initialed in setup method.
|
||||
*/
|
||||
public void testIsNewMap() {
|
||||
assertEquals(false, sendRequest.isNewMap());
|
||||
sendRequest.setNewMap(true);
|
||||
assertEquals(true, sendRequest.isNewMap());
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the method {@link SendRequest#getAccount()}. The value should be set
|
||||
* to null which is its default value when it is initialed in setup method.
|
||||
*/
|
||||
public void testGetAccount() {
|
||||
assertEquals(null, sendRequest.getAccount());
|
||||
Account account = new Account(ACCOUNTNAME, ACCOUNTYPE);
|
||||
sendRequest.setAccount(account);
|
||||
assertEquals(account, sendRequest.getAccount());
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the method {@link SendRequest#getMapId()}. The value should be set to
|
||||
* null which is its default value when it is initialed in setup method.
|
||||
*/
|
||||
public void testGetMapId() {
|
||||
assertEquals(null, sendRequest.getMapId());
|
||||
sendRequest.setMapId("1");
|
||||
assertEquals("1", "1");
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the method {@link SendRequest#isMapsSuccess()}. The value should be
|
||||
* set to false which is its default value when it is initialed in setup
|
||||
* method.
|
||||
*/
|
||||
public void testIsMapsSuccess() {
|
||||
assertEquals(false, sendRequest.isMapsSuccess());
|
||||
sendRequest.setMapsSuccess(true);
|
||||
assertEquals(true, sendRequest.isMapsSuccess());
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the method {@link SendRequest#isFusionTablesSuccess()}. The value
|
||||
* should be set to false which is its default value when it is initialed in
|
||||
* setup method.
|
||||
*/
|
||||
public void testIsFusionTablesSuccess() {
|
||||
assertEquals(false, sendRequest.isFusionTablesSuccess());
|
||||
sendRequest.setFusionTablesSuccess(true);
|
||||
assertEquals(true, sendRequest.isFusionTablesSuccess());
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the method {@link SendRequest#isDocsSuccess()}. The value should be
|
||||
* set to false which is its default value when it is initialed in setup
|
||||
* method.
|
||||
*/
|
||||
public void testIsDocsSuccess() {
|
||||
assertEquals(false, sendRequest.isDocsSuccess());
|
||||
sendRequest.setDocsSuccess(true);
|
||||
assertEquals(true, sendRequest.isDocsSuccess());
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests {@link SendRequest#SendRequest(Parcel in)} when all values are true.
|
||||
*/
|
||||
public void testCreateFromParcel_true() {
|
||||
Parcel sourceParcel = Parcel.obtain();
|
||||
sourceParcel.setDataPosition(0);
|
||||
sourceParcel.writeLong(2);
|
||||
sourceParcel.writeByte((byte) 1);
|
||||
sourceParcel.writeByte((byte) 1);
|
||||
sourceParcel.writeByte((byte) 1);
|
||||
sourceParcel.writeByte((byte) 1);
|
||||
sourceParcel.writeByte((byte) 1);
|
||||
sourceParcel.writeByte((byte) 1);
|
||||
sourceParcel.writeByte((byte) 1);
|
||||
Account account = new Account(ACCOUNTNAME, ACCOUNTYPE);
|
||||
sourceParcel.writeParcelable(account, 0);
|
||||
sourceParcel.writeString(MAPID);
|
||||
sourceParcel.writeByte((byte) 1);
|
||||
sourceParcel.writeByte((byte) 1);
|
||||
sourceParcel.writeByte((byte) 1);
|
||||
sourceParcel.setDataPosition(0);
|
||||
sendRequest = SendRequest.CREATOR.createFromParcel(sourceParcel);
|
||||
assertEquals(2, sendRequest.getTrackId());
|
||||
assertEquals(true, sendRequest.isShowMaps());
|
||||
assertEquals(true, sendRequest.isShowFusionTables());
|
||||
assertEquals(true, sendRequest.isShowDocs());
|
||||
assertEquals(true, sendRequest.isSendMaps());
|
||||
assertEquals(true, sendRequest.isSendFusionTables());
|
||||
assertEquals(true, sendRequest.isSendDocs());
|
||||
assertEquals(true, sendRequest.isNewMap());
|
||||
assertEquals(account, sendRequest.getAccount());
|
||||
assertEquals(MAPID, sendRequest.getMapId());
|
||||
assertEquals(true, sendRequest.isMapsSuccess());
|
||||
assertEquals(true, sendRequest.isFusionTablesSuccess());
|
||||
assertEquals(true, sendRequest.isDocsSuccess());
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests {@link SendRequest#SendRequest(Parcel in)} when all values are false.
|
||||
*/
|
||||
public void testCreateFromParcel_false() {
|
||||
Parcel sourceParcel = Parcel.obtain();
|
||||
sourceParcel.setDataPosition(0);
|
||||
sourceParcel.writeLong(4);
|
||||
sourceParcel.writeByte((byte) 0);
|
||||
sourceParcel.writeByte((byte) 0);
|
||||
sourceParcel.writeByte((byte) 0);
|
||||
sourceParcel.writeByte((byte) 0);
|
||||
sourceParcel.writeByte((byte) 0);
|
||||
sourceParcel.writeByte((byte) 0);
|
||||
sourceParcel.writeByte((byte) 0);
|
||||
Account account = new Account(ACCOUNTNAME, ACCOUNTYPE);
|
||||
sourceParcel.writeParcelable(account, 0);
|
||||
sourceParcel.writeString(MAPID);
|
||||
sourceParcel.writeByte((byte) 0);
|
||||
sourceParcel.writeByte((byte) 0);
|
||||
sourceParcel.writeByte((byte) 0);
|
||||
sourceParcel.setDataPosition(0);
|
||||
sendRequest = SendRequest.CREATOR.createFromParcel(sourceParcel);
|
||||
assertEquals(4, sendRequest.getTrackId());
|
||||
assertEquals(false, sendRequest.isShowMaps());
|
||||
assertEquals(false, sendRequest.isShowFusionTables());
|
||||
assertEquals(false, sendRequest.isShowDocs());
|
||||
assertEquals(false, sendRequest.isSendMaps());
|
||||
assertEquals(false, sendRequest.isSendFusionTables());
|
||||
assertEquals(false, sendRequest.isSendDocs());
|
||||
assertEquals(false, sendRequest.isNewMap());
|
||||
assertEquals(account, sendRequest.getAccount());
|
||||
assertEquals(MAPID, sendRequest.getMapId());
|
||||
assertEquals(false, sendRequest.isMapsSuccess());
|
||||
assertEquals(false, sendRequest.isFusionTablesSuccess());
|
||||
assertEquals(false, sendRequest.isDocsSuccess());
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests {@link SendRequest#writeToParcel(Parcel, int)} when all input values
|
||||
* are true or affirmative.
|
||||
*/
|
||||
public void testWriteToParcel_allTrue() {
|
||||
sendRequest = new SendRequest(1, false, false, false);
|
||||
Parcel parcelWrite1st = Parcel.obtain();
|
||||
parcelWrite1st.setDataPosition(0);
|
||||
sendRequest.writeToParcel(parcelWrite1st, 1);
|
||||
parcelWrite1st.setDataPosition(0);
|
||||
long trackId = parcelWrite1st.readLong();
|
||||
boolean showMaps = parcelWrite1st.readByte() == 1;
|
||||
boolean showFusionTables = parcelWrite1st.readByte() == 1;
|
||||
boolean showDocs = parcelWrite1st.readByte() == 1;
|
||||
boolean sendMaps = parcelWrite1st.readByte() == 1;
|
||||
boolean sendFusionTables = parcelWrite1st.readByte() == 1;
|
||||
boolean sendDocs = parcelWrite1st.readByte() == 1;
|
||||
boolean newMap = parcelWrite1st.readByte() == 1;
|
||||
Parcelable account = parcelWrite1st.readParcelable(null);
|
||||
String mapId = parcelWrite1st.readString();
|
||||
boolean mapsSuccess = parcelWrite1st.readByte() == 1;
|
||||
boolean fusionTablesSuccess = parcelWrite1st.readByte() == 1;
|
||||
boolean docsSuccess = parcelWrite1st.readByte() == 1;
|
||||
assertEquals(1, trackId);
|
||||
assertEquals(false, showMaps);
|
||||
assertEquals(false, showFusionTables);
|
||||
assertEquals(false, showDocs);
|
||||
assertEquals(false, sendMaps);
|
||||
assertEquals(false, sendFusionTables);
|
||||
assertEquals(false, sendDocs);
|
||||
assertEquals(false, newMap);
|
||||
assertEquals(null, account);
|
||||
assertEquals(null, mapId);
|
||||
assertEquals(false, mapsSuccess);
|
||||
assertEquals(false, fusionTablesSuccess);
|
||||
assertEquals(false, docsSuccess);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests {@link SendRequest#writeToParcel(Parcel, int)} when all input values
|
||||
* are false or negative.
|
||||
*/
|
||||
public void testWriteToParcel_allFalse() {
|
||||
sendRequest = new SendRequest(4, true, true, true);
|
||||
sendRequest.setSendMaps(true);
|
||||
sendRequest.setSendFusionTables(true);
|
||||
sendRequest.setSendDocs(true);
|
||||
sendRequest.setNewMap(true);
|
||||
Account accountNew = new Account(ACCOUNTNAME + "2", ACCOUNTYPE + "2");
|
||||
sendRequest.setAccount(accountNew);
|
||||
sendRequest.setMapId(MAPID);
|
||||
sendRequest.setMapsSuccess(true);
|
||||
sendRequest.setFusionTablesSuccess(true);
|
||||
sendRequest.setDocsSuccess(true);
|
||||
Parcel parcelWrite2nd = Parcel.obtain();
|
||||
parcelWrite2nd.setDataPosition(0);
|
||||
sendRequest.writeToParcel(parcelWrite2nd, 1);
|
||||
parcelWrite2nd.setDataPosition(0);
|
||||
long trackId = parcelWrite2nd.readLong();
|
||||
boolean showMaps = parcelWrite2nd.readByte() == 1;
|
||||
boolean showFusionTables = parcelWrite2nd.readByte() == 1;
|
||||
boolean showDocs = parcelWrite2nd.readByte() == 1;
|
||||
boolean sendMaps = parcelWrite2nd.readByte() == 1;
|
||||
boolean sendFusionTables = parcelWrite2nd.readByte() == 1;
|
||||
boolean sendDocs = parcelWrite2nd.readByte() == 1;
|
||||
boolean newMap = parcelWrite2nd.readByte() == 1;
|
||||
Parcelable account = parcelWrite2nd.readParcelable(null);
|
||||
String mapId = parcelWrite2nd.readString();
|
||||
boolean mapsSuccess = parcelWrite2nd.readByte() == 1;
|
||||
boolean fusionTablesSuccess = parcelWrite2nd.readByte() == 1;
|
||||
boolean docsSuccess = parcelWrite2nd.readByte() == 1;
|
||||
assertEquals(4, trackId);
|
||||
assertEquals(true, showMaps);
|
||||
assertEquals(true, showFusionTables);
|
||||
assertEquals(true, showDocs);
|
||||
assertEquals(true, sendMaps);
|
||||
assertEquals(true, sendFusionTables);
|
||||
assertEquals(true, sendDocs);
|
||||
assertEquals(true, newMap);
|
||||
assertEquals(accountNew, account);
|
||||
assertEquals(MAPID, mapId);
|
||||
assertEquals(true, mapsSuccess);
|
||||
assertEquals(true, fusionTablesSuccess);
|
||||
assertEquals(true, docsSuccess);
|
||||
}
|
||||
|
||||
}
|
||||
+309
@@ -0,0 +1,309 @@
|
||||
/*
|
||||
* Copyright 2012 Google Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
|
||||
* use this file except in compliance with the License. You may obtain a copy of
|
||||
* the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
|
||||
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
|
||||
* License for the specific language governing permissions and limitations under
|
||||
* the License.
|
||||
*/
|
||||
package com.google.android.apps.mytracks.io.sendtogoogle;
|
||||
|
||||
import com.google.android.apps.mytracks.Constants;
|
||||
import com.google.android.maps.mytracks.R;
|
||||
|
||||
import android.app.Instrumentation;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.content.SharedPreferences;
|
||||
import android.content.SharedPreferences.Editor;
|
||||
import android.test.ActivityInstrumentationTestCase2;
|
||||
import android.widget.Button;
|
||||
import android.widget.CheckBox;
|
||||
import android.widget.RadioButton;
|
||||
|
||||
/**
|
||||
* Tests the {@link UploadServiceChooserActivity}.
|
||||
*
|
||||
* @author Youtao Liu
|
||||
*/
|
||||
public class UploadServiceChooserActivityTest extends
|
||||
ActivityInstrumentationTestCase2<UploadServiceChooserActivity> {
|
||||
|
||||
private Instrumentation instrumentation;
|
||||
private UploadServiceChooserActivity uploadServiceChooserActivity;
|
||||
|
||||
public UploadServiceChooserActivityTest() {
|
||||
super(UploadServiceChooserActivity.class);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void setUp() throws Exception {
|
||||
super.setUp();
|
||||
instrumentation = getInstrumentation();
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the logic to control display all send options. This test cover code
|
||||
* in method {@link UploadServiceChooserActivity#onCreateDialog(int)},
|
||||
* {@link UploadServiceChooserActivity#updateStateBySendRequest()} and
|
||||
* {@link UploadServiceChooserActivity#updateStateBySelection()}.
|
||||
*/
|
||||
public void testOnCreateDialog_displayAll() {
|
||||
// Initials activity to display all send items.
|
||||
initialActivity(true, true, true);
|
||||
instrumentation.waitForIdleSync();
|
||||
assertTrue(getMapsCheckBox().isShown());
|
||||
assertTrue(getFusionTablesCheckBox().isShown());
|
||||
assertTrue(getDocsCheckBox().isShown());
|
||||
assertTrue(getCancelButton().isEnabled());
|
||||
|
||||
// Clicks to disable all send items.
|
||||
uploadServiceChooserActivity.runOnUiThread(new Runnable() {
|
||||
public void run() {
|
||||
if (getMapsCheckBox().isChecked()) {
|
||||
getMapsCheckBox().performClick();
|
||||
}
|
||||
if (getFusionTablesCheckBox().isChecked()) {
|
||||
getFusionTablesCheckBox().performClick();
|
||||
}
|
||||
if (getDocsCheckBox().isChecked()) {
|
||||
getDocsCheckBox().performClick();
|
||||
}
|
||||
}
|
||||
});
|
||||
instrumentation.waitForIdleSync();
|
||||
assertTrue(getMapsCheckBox().isShown());
|
||||
assertTrue(getFusionTablesCheckBox().isShown());
|
||||
assertTrue(getDocsCheckBox().isShown());
|
||||
assertTrue(getCancelButton().isEnabled());
|
||||
|
||||
assertFalse(getNewMapRadioButton().isShown());
|
||||
assertFalse(getExistingMapRadioButton().isShown());
|
||||
assertFalse(getSendButton().isEnabled());
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the logic to check the send to Google Maps option. This test cover
|
||||
* code in method {@link UploadServiceChooserActivity#onCreateDialog(int)},
|
||||
* {@link UploadServiceChooserActivity#updateStateBySendRequest()} and
|
||||
* {@link UploadServiceChooserActivity#updateStateBySelection()}.
|
||||
*/
|
||||
public void testOnCreateDialog_displayOne() {
|
||||
// Initials activity to display all send items.
|
||||
initialActivity(true, false, false);
|
||||
instrumentation.waitForIdleSync();
|
||||
assertTrue(getMapsCheckBox().isShown());
|
||||
assertTrue(getCancelButton().isEnabled());
|
||||
|
||||
// Clicks to enable this items.
|
||||
uploadServiceChooserActivity.runOnUiThread(new Runnable() {
|
||||
public void run() {
|
||||
if (!getMapsCheckBox().isChecked()) {
|
||||
getMapsCheckBox().performClick();
|
||||
}
|
||||
}
|
||||
});
|
||||
instrumentation.waitForIdleSync();
|
||||
assertTrue(getMapsCheckBox().isShown());
|
||||
assertTrue(getNewMapRadioButton().isShown());
|
||||
assertTrue(getExistingMapRadioButton().isShown());
|
||||
assertTrue(getSendButton().isEnabled());
|
||||
assertTrue(getCancelButton().isEnabled());
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the logic to control display none. This test cover code in method
|
||||
* {@link UploadServiceChooserActivity#onCreateDialog(int)},
|
||||
* {@link UploadServiceChooserActivity#updateStateBySendRequest()} and
|
||||
* {@link UploadServiceChooserActivity#updateStateBySelection()}.
|
||||
*/
|
||||
public void testOnCreateDialog_displayNone() {
|
||||
initialActivity(false, false, false);
|
||||
assertFalse(getMapsCheckBox().isShown());
|
||||
assertFalse(getFusionTablesCheckBox().isShown());
|
||||
assertFalse(getDocsCheckBox().isShown());
|
||||
assertFalse(getSendButton().isEnabled());
|
||||
assertTrue(getCancelButton().isEnabled());
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the logic to initial state of check box to unchecked. This test cover
|
||||
* code in method {@link UploadServiceChooserActivity#onCreateDialog(int)},
|
||||
* {@link UploadServiceChooserActivity#initState()}.
|
||||
*/
|
||||
public void testOnCreateDialog_initStateUnchecked() {
|
||||
initialActivity(true, true, true);
|
||||
// Initial all values to false in SharedPreferences.
|
||||
SharedPreferences prefs = uploadServiceChooserActivity.getSharedPreferences(
|
||||
Constants.SETTINGS_NAME, Context.MODE_PRIVATE);
|
||||
Editor editor = prefs.edit();
|
||||
editor.putBoolean(uploadServiceChooserActivity.getString(R.string.send_to_maps_key), false);
|
||||
editor.putBoolean(uploadServiceChooserActivity.getString(R.string.send_to_fusion_tables_key),
|
||||
false);
|
||||
editor.putBoolean(uploadServiceChooserActivity.getString(R.string.send_to_docs_key), false);
|
||||
editor.commit();
|
||||
uploadServiceChooserActivity.runOnUiThread(new Runnable() {
|
||||
public void run() {
|
||||
uploadServiceChooserActivity.initState();
|
||||
}
|
||||
});
|
||||
instrumentation.waitForIdleSync();
|
||||
assertFalse(getMapsCheckBox().isChecked());
|
||||
assertFalse(getFusionTablesCheckBox().isChecked());
|
||||
assertFalse(getDocsCheckBox().isChecked());
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the logic to initial state of check box to checked. This test cover
|
||||
* code in method {@link UploadServiceChooserActivity#onCreateDialog(int)},
|
||||
* {@link UploadServiceChooserActivity#initState()}.
|
||||
*/
|
||||
public void testOnCreateDialog_initStateChecked() {
|
||||
initialActivity(true, true, true);
|
||||
// Initial all values to true in SharedPreferences.
|
||||
SharedPreferences prefs = uploadServiceChooserActivity.getSharedPreferences(
|
||||
Constants.SETTINGS_NAME, Context.MODE_PRIVATE);
|
||||
Editor editor = prefs.edit();
|
||||
editor.putBoolean(uploadServiceChooserActivity.getString(R.string.send_to_maps_key), true);
|
||||
editor.putBoolean(uploadServiceChooserActivity.getString(R.string.pick_existing_map_key), true);
|
||||
editor.putBoolean(uploadServiceChooserActivity.getString(R.string.send_to_fusion_tables_key),
|
||||
true);
|
||||
editor.putBoolean(uploadServiceChooserActivity.getString(R.string.send_to_docs_key), true);
|
||||
editor.commit();
|
||||
uploadServiceChooserActivity.runOnUiThread(new Runnable() {
|
||||
public void run() {
|
||||
uploadServiceChooserActivity.initState();
|
||||
}
|
||||
});
|
||||
instrumentation.waitForIdleSync();
|
||||
assertTrue(getMapsCheckBox().isChecked());
|
||||
assertTrue(getFusionTablesCheckBox().isChecked());
|
||||
assertTrue(getDocsCheckBox().isChecked());
|
||||
assertTrue(getExistingMapRadioButton().isChecked());
|
||||
|
||||
assertFalse(getNewMapRadioButton().isChecked());
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the logic of saveState when click send button. This test cover code
|
||||
* in method {@link UploadServiceChooserActivity#saveState()},
|
||||
* {@link UploadServiceChooserActivity#initState()} ,
|
||||
* {@link UploadServiceChooserActivity#sendMaps()},
|
||||
* {@link UploadServiceChooserActivity#sendFusionTables()}, and
|
||||
* {@link UploadServiceChooserActivity#sendDocs()}.
|
||||
*/
|
||||
public void testOnCreateDialog_saveState() {
|
||||
initialActivity(true, true, true);
|
||||
// Initial all values to true in SharedPreferences.
|
||||
SharedPreferences prefs = uploadServiceChooserActivity.getSharedPreferences(
|
||||
Constants.SETTINGS_NAME, Context.MODE_PRIVATE);
|
||||
Editor editor = prefs.edit();
|
||||
editor.putBoolean(uploadServiceChooserActivity.getString(R.string.send_to_maps_key), true);
|
||||
editor.putBoolean(uploadServiceChooserActivity.getString(R.string.send_to_fusion_tables_key),
|
||||
true);
|
||||
editor.putBoolean(uploadServiceChooserActivity.getString(R.string.send_to_docs_key), true);
|
||||
editor.commit();
|
||||
uploadServiceChooserActivity.runOnUiThread(new Runnable() {
|
||||
public void run() {
|
||||
uploadServiceChooserActivity.initState();
|
||||
}
|
||||
});
|
||||
instrumentation.waitForIdleSync();
|
||||
uploadServiceChooserActivity.saveState();
|
||||
// All values in SharedPreferences must be changed.
|
||||
assertTrue(prefs.getBoolean(uploadServiceChooserActivity.getString(R.string.send_to_maps_key),
|
||||
false));
|
||||
assertTrue(prefs.getBoolean(uploadServiceChooserActivity.getString(R.string.send_to_maps_key),
|
||||
false));
|
||||
assertTrue(prefs.getBoolean(uploadServiceChooserActivity.getString(R.string.send_to_maps_key),
|
||||
false));
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the logic of startNextActivity when click send button. This test
|
||||
* cover code in method
|
||||
* {@link UploadServiceChooserActivity#startNextActivity()} ,
|
||||
* {@link UploadServiceChooserActivity#initState()} ,
|
||||
* {@link UploadServiceChooserActivity#sendMaps()},
|
||||
* {@link UploadServiceChooserActivity#sendFusionTables()}, and
|
||||
* {@link UploadServiceChooserActivity#sendDocs()}.
|
||||
*/
|
||||
public void testOnCreateDialog_startNextActivity() {
|
||||
initialActivity(true, true, true);
|
||||
// Initial all values to true or false in SharedPreferences.
|
||||
SharedPreferences prefs = uploadServiceChooserActivity.getSharedPreferences(
|
||||
Constants.SETTINGS_NAME, Context.MODE_PRIVATE);
|
||||
Editor editor = prefs.edit();
|
||||
editor.putBoolean(uploadServiceChooserActivity.getString(R.string.send_to_maps_key), true);
|
||||
editor.putBoolean(uploadServiceChooserActivity.getString(R.string.send_to_docs_key), true);
|
||||
editor.putBoolean(uploadServiceChooserActivity.getString(R.string.send_to_fusion_tables_key),
|
||||
false);
|
||||
editor.commit();
|
||||
uploadServiceChooserActivity.runOnUiThread(new Runnable() {
|
||||
public void run() {
|
||||
uploadServiceChooserActivity.initState();
|
||||
}
|
||||
});
|
||||
instrumentation.waitForIdleSync();
|
||||
uploadServiceChooserActivity.startNextActivity();
|
||||
// All values in SendRequest must be same as set above.
|
||||
assertTrue(uploadServiceChooserActivity.getSendRequest().isSendMaps());
|
||||
assertTrue(uploadServiceChooserActivity.getSendRequest().isSendDocs());
|
||||
|
||||
assertFalse(uploadServiceChooserActivity.getSendRequest().isSendFusionTables());
|
||||
}
|
||||
|
||||
/**
|
||||
* Initials a activity to be tested.
|
||||
*
|
||||
* @param showMaps
|
||||
* @param showFusionTables
|
||||
* @param showDocs
|
||||
*/
|
||||
private void initialActivity(boolean showMaps, boolean showFusionTables, boolean showDocs) {
|
||||
Intent intent = new Intent();
|
||||
intent.putExtra(SendRequest.SEND_REQUEST_KEY, new SendRequest(1L, showMaps, showFusionTables,
|
||||
showDocs));
|
||||
setActivityIntent(intent);
|
||||
uploadServiceChooserActivity = this.getActivity();
|
||||
}
|
||||
|
||||
private Button getSendButton() {
|
||||
return (Button) uploadServiceChooserActivity.getDialog()
|
||||
.findViewById(R.id.send_google_send_now);
|
||||
}
|
||||
|
||||
Button getCancelButton() {
|
||||
return (Button) uploadServiceChooserActivity.getDialog().findViewById(R.id.send_google_cancel);
|
||||
}
|
||||
|
||||
private CheckBox getMapsCheckBox() {
|
||||
return (CheckBox) uploadServiceChooserActivity.getDialog().findViewById(R.id.send_google_maps);
|
||||
}
|
||||
|
||||
private CheckBox getFusionTablesCheckBox() {
|
||||
return (CheckBox) uploadServiceChooserActivity.getDialog().findViewById(
|
||||
R.id.send_google_fusion_tables);
|
||||
}
|
||||
|
||||
private CheckBox getDocsCheckBox() {
|
||||
return (CheckBox) uploadServiceChooserActivity.getDialog().findViewById(R.id.send_google_docs);
|
||||
}
|
||||
|
||||
private RadioButton getNewMapRadioButton() {
|
||||
return (RadioButton) uploadServiceChooserActivity.getDialog().findViewById(
|
||||
R.id.send_google_new_map);
|
||||
}
|
||||
|
||||
private RadioButton getExistingMapRadioButton() {
|
||||
return (RadioButton) uploadServiceChooserActivity.getDialog().findViewById(
|
||||
R.id.send_google_existing_map);
|
||||
}
|
||||
}
|
||||
+180
@@ -0,0 +1,180 @@
|
||||
/*
|
||||
* Copyright 2012 Google Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
|
||||
* use this file except in compliance with the License. You may obtain a copy of
|
||||
* the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
|
||||
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
|
||||
* License for the specific language governing permissions and limitations under
|
||||
* the License.
|
||||
*/
|
||||
package com.google.android.apps.mytracks.maps;
|
||||
|
||||
import com.google.android.apps.mytracks.Constants;
|
||||
import com.google.android.maps.mytracks.R;
|
||||
|
||||
import android.content.Context;
|
||||
import android.content.SharedPreferences;
|
||||
import android.content.SharedPreferences.Editor;
|
||||
import android.test.AndroidTestCase;
|
||||
|
||||
/**
|
||||
* Tests for the {@link DynamicSpeedTrackPathDescriptor}.
|
||||
*
|
||||
* @author Youtao Liu
|
||||
*/
|
||||
public class DynamicSpeedTrackPathDescriptorTest extends AndroidTestCase {
|
||||
|
||||
private Context context;
|
||||
private SharedPreferences sharedPreferences;
|
||||
private Editor sharedPreferencesEditor;
|
||||
|
||||
@Override
|
||||
protected void setUp() throws Exception {
|
||||
super.setUp();
|
||||
context = getContext();
|
||||
sharedPreferences = context.getSharedPreferences(Constants.SETTINGS_NAME, Context.MODE_PRIVATE);
|
||||
sharedPreferencesEditor = sharedPreferences.edit();
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the method {@link DynamicSpeedTrackPathDescriptor#getSpeedMargin()}
|
||||
* with zero, normal and illegal value.
|
||||
*/
|
||||
public void testGetSpeedMargin() {
|
||||
String[] actuals = { "0", "50", "99", "" };
|
||||
// The default value of speedMargin is 25.
|
||||
int[] expectations = { 0, 50, 99, 25 };
|
||||
// Test
|
||||
for (int i = 0; i < expectations.length; i++) {
|
||||
sharedPreferencesEditor.putString(
|
||||
context.getString(R.string.track_color_mode_dynamic_speed_variation_key), actuals[i]);
|
||||
sharedPreferencesEditor.commit();
|
||||
DynamicSpeedTrackPathDescriptor dynamicSpeedTrackPathDescriptor = new DynamicSpeedTrackPathDescriptor(
|
||||
context);
|
||||
assertEquals(expectations[i],
|
||||
dynamicSpeedTrackPathDescriptor.getSpeedMargin(sharedPreferences));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests {@link
|
||||
* DynamicSpeedTrackPathDescriptor#onSharedPreferenceChanged(SharedPreferences,
|
||||
* String)} when the key is null.
|
||||
*/
|
||||
public void testOnSharedPreferenceChanged_nullKey() {
|
||||
DynamicSpeedTrackPathDescriptor dynamicSpeedTrackPathDescriptor = new DynamicSpeedTrackPathDescriptor(
|
||||
context);
|
||||
int speedMargin = dynamicSpeedTrackPathDescriptor.getSpeedMargin(sharedPreferences);
|
||||
// Change value in shared preferences.
|
||||
sharedPreferencesEditor.putString(
|
||||
context.getString(R.string.track_color_mode_dynamic_speed_variation_key),
|
||||
Integer.toString(speedMargin + 2));
|
||||
sharedPreferencesEditor.commit();
|
||||
|
||||
dynamicSpeedTrackPathDescriptor.onSharedPreferenceChanged(sharedPreferences, null);
|
||||
assertEquals(speedMargin, dynamicSpeedTrackPathDescriptor.getSpeedMargin());
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests {@link
|
||||
* DynamicSpeedTrackPathDescriptor#onSharedPreferenceChanged(SharedPreferences,
|
||||
* String)} when the key is not null, and not trackColorModeDynamicVariation.
|
||||
*/
|
||||
public void testOnSharedPreferenceChanged_otherKey() {
|
||||
DynamicSpeedTrackPathDescriptor dynamicSpeedTrackPathDescriptor = new DynamicSpeedTrackPathDescriptor(
|
||||
context);
|
||||
int speedMargin = dynamicSpeedTrackPathDescriptor.getSpeedMargin(sharedPreferences);
|
||||
// Change value in shared preferences.
|
||||
sharedPreferencesEditor.putString(
|
||||
context.getString(R.string.track_color_mode_dynamic_speed_variation_key),
|
||||
Integer.toString(speedMargin + 2));
|
||||
sharedPreferencesEditor.commit();
|
||||
|
||||
dynamicSpeedTrackPathDescriptor.onSharedPreferenceChanged(sharedPreferences, "anyKey");
|
||||
assertEquals(speedMargin, dynamicSpeedTrackPathDescriptor.getSpeedMargin());
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests {@link
|
||||
* DynamicSpeedTrackPathDescriptor#onSharedPreferenceChanged(SharedPreferences,
|
||||
* String)} when the key is trackColorModeDynamicVariation.
|
||||
*/
|
||||
public void testOnSharedPreferenceChanged_trackColorModeDynamicVariationKey() {
|
||||
DynamicSpeedTrackPathDescriptor dynamicSpeedTrackPathDescriptor = new DynamicSpeedTrackPathDescriptor(
|
||||
context);
|
||||
int speedMargin = dynamicSpeedTrackPathDescriptor.getSpeedMargin(sharedPreferences);
|
||||
// Change value in shared preferences.
|
||||
sharedPreferencesEditor.putString(
|
||||
"trackColorModeDynamicVariation",
|
||||
Integer.toString(speedMargin + 2));
|
||||
sharedPreferencesEditor.commit();
|
||||
|
||||
dynamicSpeedTrackPathDescriptor.onSharedPreferenceChanged(sharedPreferences,
|
||||
"trackColorModeDynamicVariation");
|
||||
assertEquals(speedMargin + 2, dynamicSpeedTrackPathDescriptor.getSpeedMargin());
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests {@link
|
||||
* DynamicSpeedTrackPathDescriptor#onSharedPreferenceChanged(SharedPreferences,
|
||||
* String)} when the values of speedMargin is "".
|
||||
*/
|
||||
public void testOnSharedPreferenceChanged_emptyValue() {
|
||||
DynamicSpeedTrackPathDescriptor dynamicSpeedTrackPathDescriptor = new DynamicSpeedTrackPathDescriptor(
|
||||
context);
|
||||
// Change value in shared preferences
|
||||
sharedPreferencesEditor.putString(
|
||||
context.getString(R.string.track_color_mode_dynamic_speed_variation_key), "");
|
||||
sharedPreferencesEditor.commit();
|
||||
|
||||
dynamicSpeedTrackPathDescriptor.onSharedPreferenceChanged(sharedPreferences,
|
||||
context.getString(R.string.track_color_mode_dynamic_speed_variation_key));
|
||||
// The default value of speedMargin is 25.
|
||||
assertEquals(25, dynamicSpeedTrackPathDescriptor.getSpeedMargin());
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests {@link DynamicSpeedTrackPathDescriptor#needsRedraw()} by wrong track
|
||||
* id.
|
||||
*/
|
||||
public void testNeedsRedraw_WrongTrackId() {
|
||||
long trackId = -1;
|
||||
sharedPreferencesEditor.putLong(context.getString(R.string.selected_track_key), trackId);
|
||||
sharedPreferencesEditor.commit();
|
||||
DynamicSpeedTrackPathDescriptor dynamicSpeedTrackPathDescriptor = new DynamicSpeedTrackPathDescriptor(
|
||||
context);
|
||||
assertEquals(false, dynamicSpeedTrackPathDescriptor.needsRedraw());
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests {@link DynamicSpeedTrackPathDescriptor#needsRedraw()} by different
|
||||
* averageMovingSpeed.
|
||||
*/
|
||||
public void testIsDiffereceSignificant() {
|
||||
DynamicSpeedTrackPathDescriptor dynamicSpeedTrackPathDescriptor = new DynamicSpeedTrackPathDescriptor(
|
||||
context);
|
||||
double[] averageMovingSpeeds = { 0, 30, 30, 30 };
|
||||
double[] newAverageMovingSpeed = { 20, 30,
|
||||
// Difference is less than CRITICAL_DIFFERENCE_PERCENTAGE
|
||||
30 * (1 + (DynamicSpeedTrackPathDescriptor.CRITICAL_DIFFERENCE_PERCENTAGE / 100) / 2),
|
||||
// Difference is more than CRITICAL_DIFFERENCE_PERCENTAGE
|
||||
30 * (1 + (DynamicSpeedTrackPathDescriptor.CRITICAL_DIFFERENCE_PERCENTAGE / 100.00) * 2) };
|
||||
boolean[] expectedValues = { true, false, false, true };
|
||||
double[] expectedAverageMovingSpeed = { 20, 30, 30,
|
||||
30 * (1 + (DynamicSpeedTrackPathDescriptor.CRITICAL_DIFFERENCE_PERCENTAGE / 100.00) * 2) };
|
||||
// Test
|
||||
for (int i = 0; i < newAverageMovingSpeed.length; i++) {
|
||||
dynamicSpeedTrackPathDescriptor.setAverageMovingSpeed(averageMovingSpeeds[i]);
|
||||
assertEquals(expectedValues[i], dynamicSpeedTrackPathDescriptor.isDifferenceSignificant(
|
||||
averageMovingSpeeds[i], newAverageMovingSpeed[i]));
|
||||
assertEquals(expectedAverageMovingSpeed[i],
|
||||
dynamicSpeedTrackPathDescriptor.getAverageMovingSpeed());
|
||||
}
|
||||
}
|
||||
}
|
||||
+187
@@ -0,0 +1,187 @@
|
||||
/*
|
||||
* Copyright 2012 Google Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
|
||||
* use this file except in compliance with the License. You may obtain a copy of
|
||||
* the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
|
||||
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
|
||||
* License for the specific language governing permissions and limitations under
|
||||
* the License.
|
||||
*/
|
||||
package com.google.android.apps.mytracks.maps;
|
||||
|
||||
import com.google.android.apps.mytracks.Constants;
|
||||
import com.google.android.maps.mytracks.R;
|
||||
|
||||
import android.content.Context;
|
||||
import android.content.SharedPreferences;
|
||||
import android.content.SharedPreferences.Editor;
|
||||
import android.test.AndroidTestCase;
|
||||
|
||||
/**
|
||||
* Tests for the {@link DynamicSpeedTrackPathDescriptor}.
|
||||
*
|
||||
* @author Youtao Liu
|
||||
*/
|
||||
public class FixedSpeedTrackPathDescriptorTest extends AndroidTestCase {
|
||||
private Context context;
|
||||
private SharedPreferences sharedPreferences;
|
||||
private Editor sharedPreferencesEditor;
|
||||
private int slowDefault;
|
||||
private int normalDefault;
|
||||
|
||||
@Override
|
||||
protected void setUp() throws Exception {
|
||||
super.setUp();
|
||||
context = getContext();
|
||||
sharedPreferences = context.getSharedPreferences(Constants.SETTINGS_NAME, Context.MODE_PRIVATE);
|
||||
sharedPreferencesEditor = sharedPreferences.edit();
|
||||
// Get the default value
|
||||
slowDefault = 9;
|
||||
normalDefault = 15;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the initialization of slowSpeed and normalSpeed in {@link
|
||||
* DynamicSpeedTrackPathDescriptor#DynamicSpeedTrackPathDescriptor(Context)}.
|
||||
*/
|
||||
public void testConstructor() {
|
||||
String[] slowSpeedsInShPre = { "0", "1", "99", "" };
|
||||
int[] slowSpeedExpectations = { 0, 1, 99, slowDefault };
|
||||
String[] normalSpeedsInShPre = { "0", "1", "99", "" };
|
||||
int[] normalSpeedExpectations = { 0, 1, 99, normalDefault };
|
||||
for (int i = 0; i < slowSpeedsInShPre.length; i++) {
|
||||
sharedPreferencesEditor.putString(
|
||||
context.getString(R.string.track_color_mode_fixed_speed_slow_key), slowSpeedsInShPre[i]);
|
||||
sharedPreferencesEditor.putString(
|
||||
context.getString(R.string.track_color_mode_fixed_speed_medium_key),
|
||||
normalSpeedsInShPre[i]);
|
||||
sharedPreferencesEditor.commit();
|
||||
FixedSpeedTrackPathDescriptor fixedSpeedTrackPathDescriptor = new FixedSpeedTrackPathDescriptor(
|
||||
context);
|
||||
assertEquals(slowSpeedExpectations[i], fixedSpeedTrackPathDescriptor.getSlowSpeed());
|
||||
assertEquals(normalSpeedExpectations[i], fixedSpeedTrackPathDescriptor.getNormalSpeed());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests {@link
|
||||
* DynamicSpeedTrackPathDescriptor#onSharedPreferenceChanged(SharedPreferences,
|
||||
* String)} when the key is null.
|
||||
*/
|
||||
public void testOnSharedPreferenceChanged_null_key() {
|
||||
FixedSpeedTrackPathDescriptor fixedSpeedTrackPathDescriptor = new FixedSpeedTrackPathDescriptor(
|
||||
context);
|
||||
int slowSpeed = fixedSpeedTrackPathDescriptor.getSlowSpeed();
|
||||
int normalSpeed = fixedSpeedTrackPathDescriptor.getNormalSpeed();
|
||||
// Change value in shared preferences
|
||||
sharedPreferencesEditor.putString(
|
||||
context.getString(R.string.track_color_mode_fixed_speed_slow_key),
|
||||
Integer.toString(slowSpeed + 2));
|
||||
sharedPreferencesEditor.putString(
|
||||
context.getString(R.string.track_color_mode_fixed_speed_medium_key),
|
||||
Integer.toString(normalSpeed + 2));
|
||||
sharedPreferencesEditor.commit();
|
||||
|
||||
fixedSpeedTrackPathDescriptor.onSharedPreferenceChanged(sharedPreferences, null);
|
||||
assertEquals(slowSpeed, fixedSpeedTrackPathDescriptor.getSlowSpeed());
|
||||
assertEquals(normalSpeed, fixedSpeedTrackPathDescriptor.getNormalSpeed());
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests {@link
|
||||
* DynamicSpeedTrackPathDescriptor#onSharedPreferenceChanged(SharedPreferences,
|
||||
* String)} when the key is not null, and not slowSpeed and not normalSpeed.
|
||||
*/
|
||||
public void testOnSharedPreferenceChanged_other_key() {
|
||||
FixedSpeedTrackPathDescriptor fixedSpeedTrackPathDescriptor = new FixedSpeedTrackPathDescriptor(
|
||||
context);
|
||||
int slowSpeed = fixedSpeedTrackPathDescriptor.getSlowSpeed();
|
||||
int normalSpeed = fixedSpeedTrackPathDescriptor.getNormalSpeed();
|
||||
// Change value in shared preferences
|
||||
sharedPreferencesEditor.putString(
|
||||
context.getString(R.string.track_color_mode_fixed_speed_slow_key),
|
||||
Integer.toString(slowSpeed + 2));
|
||||
sharedPreferencesEditor.putString(
|
||||
context.getString(R.string.track_color_mode_fixed_speed_medium_key),
|
||||
Integer.toString(normalSpeed + 2));
|
||||
sharedPreferencesEditor.commit();
|
||||
fixedSpeedTrackPathDescriptor.onSharedPreferenceChanged(sharedPreferences, "anyKey");
|
||||
assertEquals(slowSpeed, fixedSpeedTrackPathDescriptor.getSlowSpeed());
|
||||
assertEquals(normalSpeed, fixedSpeedTrackPathDescriptor.getNormalSpeed());
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests {@link
|
||||
* DynamicSpeedTrackPathDescriptor#onSharedPreferenceChanged(SharedPreferences,
|
||||
* String)} when the key is slowSpeed.
|
||||
*/
|
||||
public void testOnSharedPreferenceChanged_slowSpeedKey() {
|
||||
FixedSpeedTrackPathDescriptor fixedSpeedTrackPathDescriptor = new FixedSpeedTrackPathDescriptor(
|
||||
context);
|
||||
int slowSpeed = fixedSpeedTrackPathDescriptor.getSlowSpeed();
|
||||
int normalSpeed = fixedSpeedTrackPathDescriptor.getNormalSpeed();
|
||||
// Change value in shared preferences
|
||||
sharedPreferencesEditor.putString(
|
||||
context.getString(R.string.track_color_mode_fixed_speed_slow_key),
|
||||
Integer.toString(slowSpeed + 2));
|
||||
sharedPreferencesEditor.putString(
|
||||
context.getString(R.string.track_color_mode_fixed_speed_medium_key),
|
||||
Integer.toString(normalSpeed + 2));
|
||||
sharedPreferencesEditor.commit();
|
||||
fixedSpeedTrackPathDescriptor.onSharedPreferenceChanged(sharedPreferences,
|
||||
context.getString(R.string.track_color_mode_fixed_speed_slow_key));
|
||||
assertEquals(slowSpeed + 2, fixedSpeedTrackPathDescriptor.getSlowSpeed());
|
||||
assertEquals(normalSpeed + 2, fixedSpeedTrackPathDescriptor.getNormalSpeed());
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests {@link
|
||||
* DynamicSpeedTrackPathDescriptor#onSharedPreferenceChanged(SharedPreferences,
|
||||
* String)} when the key is normalSpeed.
|
||||
*/
|
||||
public void testOnSharedPreferenceChanged_normalSpeedKey() {
|
||||
FixedSpeedTrackPathDescriptor fixedSpeedTrackPathDescriptor = new FixedSpeedTrackPathDescriptor(
|
||||
context);
|
||||
int slowSpeed = fixedSpeedTrackPathDescriptor.getSlowSpeed();
|
||||
int normalSpeed = fixedSpeedTrackPathDescriptor.getNormalSpeed();
|
||||
sharedPreferencesEditor.putString(
|
||||
context.getString(R.string.track_color_mode_fixed_speed_slow_key),
|
||||
Integer.toString(slowSpeed + 4));
|
||||
sharedPreferencesEditor.putString(
|
||||
context.getString(R.string.track_color_mode_fixed_speed_medium_key),
|
||||
Integer.toString(normalSpeed + 4));
|
||||
sharedPreferencesEditor.commit();
|
||||
|
||||
fixedSpeedTrackPathDescriptor.onSharedPreferenceChanged(sharedPreferences,
|
||||
context.getString(R.string.track_color_mode_fixed_speed_medium_key));
|
||||
assertEquals(slowSpeed + 4, fixedSpeedTrackPathDescriptor.getSlowSpeed());
|
||||
assertEquals(normalSpeed + 4, fixedSpeedTrackPathDescriptor.getNormalSpeed());
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests {@link
|
||||
* DynamicSpeedTrackPathDescriptor#onSharedPreferenceChanged(SharedPreferences,
|
||||
* String)} when the values of slowSpeed and normalSpeed in SharedPreference
|
||||
* is "". In such situation, the default value should get returned.
|
||||
*/
|
||||
public void testOnSharedPreferenceChanged_emptyValue() {
|
||||
FixedSpeedTrackPathDescriptor fixedSpeedTrackPathDescriptor = new FixedSpeedTrackPathDescriptor(
|
||||
context);
|
||||
sharedPreferencesEditor.putString(
|
||||
context.getString(R.string.track_color_mode_fixed_speed_slow_key), "");
|
||||
sharedPreferencesEditor.putString(
|
||||
context.getString(R.string.track_color_mode_fixed_speed_medium_key), "");
|
||||
sharedPreferencesEditor.commit();
|
||||
|
||||
fixedSpeedTrackPathDescriptor.onSharedPreferenceChanged(sharedPreferences,
|
||||
context.getString(R.string.track_color_mode_fixed_speed_medium_key));
|
||||
assertEquals(slowDefault, fixedSpeedTrackPathDescriptor.getSlowSpeed());
|
||||
assertEquals(normalDefault, fixedSpeedTrackPathDescriptor.getNormalSpeed());
|
||||
}
|
||||
}
|
||||
+103
@@ -0,0 +1,103 @@
|
||||
/*
|
||||
* Copyright 2010 Google Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
|
||||
* use this file except in compliance with the License. You may obtain a copy of
|
||||
* the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
|
||||
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
|
||||
* License for the specific language governing permissions and limitations under
|
||||
* the License.
|
||||
*/
|
||||
|
||||
package com.google.android.apps.mytracks.services;
|
||||
|
||||
import static com.google.android.testing.mocking.AndroidMock.expect;
|
||||
|
||||
import com.google.android.testing.mocking.AndroidMock;
|
||||
import com.google.android.testing.mocking.UsesMocks;
|
||||
|
||||
import android.test.AndroidTestCase;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
/**
|
||||
* Tests {@link RemoveTempFilesService}.
|
||||
*
|
||||
* @author Sandor Dornbush
|
||||
*/
|
||||
public class RemoveTempFilesServiceTest extends AndroidTestCase {
|
||||
|
||||
private static final String DIR_NAME = "/tmp";
|
||||
private static final String FILE_NAME = "foo";
|
||||
|
||||
private RemoveTempFilesService service;
|
||||
|
||||
@UsesMocks({ File.class, })
|
||||
protected void setUp() throws Exception {
|
||||
service = new RemoveTempFilesService();
|
||||
};
|
||||
|
||||
/**
|
||||
* Tests when the directory doesn't exists.
|
||||
*/
|
||||
public void test_noDir() {
|
||||
File dir = AndroidMock.createMock(File.class, DIR_NAME);
|
||||
expect(dir.exists()).andStubReturn(false);
|
||||
AndroidMock.replay(dir);
|
||||
|
||||
assertEquals(0, service.cleanTempDirectory(dir));
|
||||
AndroidMock.verify(dir);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests when the directory is empty.
|
||||
*/
|
||||
public void test_emptyDir() {
|
||||
File dir = AndroidMock.createMock(File.class, DIR_NAME);
|
||||
expect(dir.exists()).andStubReturn(true);
|
||||
expect(dir.listFiles()).andStubReturn(new File[0]);
|
||||
AndroidMock.replay(dir);
|
||||
|
||||
assertEquals(0, service.cleanTempDirectory(dir));
|
||||
AndroidMock.verify(dir);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests when there is a new file and it shouldn't get deleted.
|
||||
*/
|
||||
public void test_newFile() {
|
||||
File file = AndroidMock.createMock(File.class, DIR_NAME + FILE_NAME);
|
||||
expect(file.lastModified()).andStubReturn(System.currentTimeMillis());
|
||||
|
||||
File dir = AndroidMock.createMock(File.class, DIR_NAME);
|
||||
expect(dir.exists()).andStubReturn(true);
|
||||
expect(dir.listFiles()).andStubReturn(new File[] { file });
|
||||
AndroidMock.replay(dir, file);
|
||||
|
||||
assertEquals(0, service.cleanTempDirectory(dir));
|
||||
AndroidMock.verify(dir, file);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests when there is an old file and it should get deleted.
|
||||
*/
|
||||
public void test_oldFile() {
|
||||
File file = AndroidMock.createMock(File.class, DIR_NAME + FILE_NAME);
|
||||
// qSet to one hour and 1 millisecond later than the current time
|
||||
expect(file.lastModified()).andStubReturn(System.currentTimeMillis() - 3600001);
|
||||
expect(file.delete()).andStubReturn(true);
|
||||
|
||||
File dir = AndroidMock.createMock(File.class, DIR_NAME);
|
||||
expect(dir.exists()).andStubReturn(true);
|
||||
expect(dir.listFiles()).andStubReturn(new File[] { file });
|
||||
AndroidMock.replay(dir, file);
|
||||
|
||||
assertEquals(1, service.cleanTempDirectory(dir));
|
||||
AndroidMock.verify(dir, file);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
// Copyright 2012 Google Inc. All Rights Reserved.
|
||||
|
||||
package com.google.android.apps.mytracks.services;
|
||||
|
||||
import android.app.Notification;
|
||||
import android.app.Service;
|
||||
import android.test.ServiceTestCase;
|
||||
import android.util.Log;
|
||||
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Method;
|
||||
|
||||
/**
|
||||
* A {@link TrackRecordingService} that can be used with {@link ServiceTestCase}.
|
||||
* {@link ServiceTestCase} throws a null pointer exception when the service
|
||||
* calls {@link Service#startForeground(int, android.app.Notification)} and
|
||||
* {@link Service#stopForeground(boolean)}.
|
||||
* <p>
|
||||
* See http://code.google.com/p/android/issues/detail?id=12122
|
||||
* <p>
|
||||
* Wrap these two methods in wrappers and override them.
|
||||
*
|
||||
* @author Jimmy Shih
|
||||
*/
|
||||
public class TestRecordingService extends TrackRecordingService {
|
||||
|
||||
private static final String TAG = TestRecordingService.class.getSimpleName();
|
||||
|
||||
@Override
|
||||
protected void startForegroundService(Notification notification) {
|
||||
try {
|
||||
Method setForegroundMethod = Service.class.getMethod("setForeground", boolean.class);
|
||||
setForegroundMethod.invoke(this, true);
|
||||
} catch (SecurityException e) {
|
||||
Log.e(TAG, "Unable to start a service in foreground", e);
|
||||
} catch (NoSuchMethodException e) {
|
||||
Log.e(TAG, "Unable to start a service in foreground", e);
|
||||
} catch (IllegalArgumentException e) {
|
||||
Log.e(TAG, "Unable to start a service in foreground", e);
|
||||
} catch (IllegalAccessException e) {
|
||||
Log.e(TAG, "Unable to start a service in foreground", e);
|
||||
} catch (InvocationTargetException e) {
|
||||
Log.e(TAG, "Unable to start a service in foreground", e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void stopForegroundService() {
|
||||
try {
|
||||
Method setForegroundMethod = Service.class.getMethod("setForeground", boolean.class);
|
||||
setForegroundMethod.invoke(this, false);
|
||||
} catch (SecurityException e) {
|
||||
Log.e(TAG, "Unable to start a service in foreground", e);
|
||||
} catch (NoSuchMethodException e) {
|
||||
Log.e(TAG, "Unable to start a service in foreground", e);
|
||||
} catch (IllegalArgumentException e) {
|
||||
Log.e(TAG, "Unable to start a service in foreground", e);
|
||||
} catch (IllegalAccessException e) {
|
||||
Log.e(TAG, "Unable to start a service in foreground", e);
|
||||
} catch (InvocationTargetException e) {
|
||||
Log.e(TAG, "Unable to start a service in foreground", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
+2
-19
@@ -24,7 +24,6 @@ import com.google.android.apps.mytracks.content.Track;
|
||||
import com.google.android.apps.mytracks.content.Waypoint;
|
||||
import com.google.android.apps.mytracks.content.WaypointCreationRequest;
|
||||
import com.google.android.apps.mytracks.stats.TripStatistics;
|
||||
import com.google.android.apps.mytracks.util.ApiFeatures;
|
||||
import com.google.android.maps.mytracks.R;
|
||||
|
||||
import android.content.BroadcastReceiver;
|
||||
@@ -57,8 +56,7 @@ import java.util.List;
|
||||
* is called, which prevents from testing multiple scenarios in a single
|
||||
* test (see runFunctionTest for more details).
|
||||
*/
|
||||
public class TrackRecordingServiceTest
|
||||
extends ServiceTestCase<TrackRecordingService> {
|
||||
public class TrackRecordingServiceTest extends ServiceTestCase<TestRecordingService> {
|
||||
|
||||
private Context context;
|
||||
private MyTracksProviderUtils providerUtils;
|
||||
@@ -74,7 +72,7 @@ public class TrackRecordingServiceTest
|
||||
private Intent serviceIntent;
|
||||
|
||||
public TrackRecordingServiceTest() {
|
||||
super(TrackRecordingService.class);
|
||||
super(TestRecordingService.class);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -96,19 +94,6 @@ public class TrackRecordingServiceTest
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A mock class that forces API level < 5 to make sure we can workaround a bug
|
||||
* in ServiceTestCase (throwing a NPE).
|
||||
* See http://code.google.com/p/android/issues/detail?id=12122 for more
|
||||
* details.
|
||||
*/
|
||||
private static class MockApiFeatures extends ApiFeatures {
|
||||
@Override
|
||||
protected int getApiLevel() {
|
||||
return 4;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected IBinder bindService(Intent intent) {
|
||||
if (getService() != null) {
|
||||
@@ -138,8 +123,6 @@ public class TrackRecordingServiceTest
|
||||
protected void setUp() throws Exception {
|
||||
super.setUp();
|
||||
|
||||
ApiFeatures.injectInstance(new MockApiFeatures());
|
||||
|
||||
MockContentResolver mockContentResolver = new MockContentResolver();
|
||||
RenamingDelegatingContext targetContext = new RenamingDelegatingContext(
|
||||
getContext(), getContext(), "test.");
|
||||
|
||||
+7
-6
@@ -17,23 +17,23 @@ public class SensorManagerFactoryTest extends AndroidTestCase {
|
||||
@Override
|
||||
protected void setUp() throws Exception {
|
||||
super.setUp();
|
||||
|
||||
|
||||
sharedPreferences = getContext().getSharedPreferences(
|
||||
Constants.SETTINGS_NAME, Context.MODE_PRIVATE);
|
||||
// Let's use default values.
|
||||
sharedPreferences.edit().clear().apply();
|
||||
}
|
||||
|
||||
|
||||
@SmallTest
|
||||
public void testDefaultSettings() throws Exception {
|
||||
assertNull(SensorManagerFactory.getSensorManager(getContext()));
|
||||
assertNull(SensorManagerFactory.getInstance().getSensorManager(getContext()));
|
||||
}
|
||||
|
||||
|
||||
@SmallTest
|
||||
public void testCreateZephyr() throws Exception {
|
||||
assertClassForName(ZephyrSensorManager.class, R.string.sensor_type_value_zephyr);
|
||||
}
|
||||
|
||||
|
||||
@SmallTest
|
||||
public void testCreateAnt() throws Exception {
|
||||
assertClassForName(AntDirectSensorManager.class, R.string.sensor_type_value_ant);
|
||||
@@ -49,8 +49,9 @@ public class SensorManagerFactoryTest extends AndroidTestCase {
|
||||
.putString(getContext().getString(R.string.sensor_type_key),
|
||||
getContext().getString(i))
|
||||
.apply();
|
||||
SensorManager sm = SensorManagerFactory.getSensorManager(getContext());
|
||||
SensorManager sm = SensorManagerFactory.getInstance().getSensorManager(getContext());
|
||||
assertNotNull(sm);
|
||||
assertTrue(c.isInstance(sm));
|
||||
SensorManagerFactory.getInstance().releaseSensorManager(sm);
|
||||
}
|
||||
}
|
||||
|
||||
+48
-27
@@ -28,6 +28,22 @@ import android.test.suitebuilder.annotation.SmallTest;
|
||||
public class AntDirectSensorManagerTest extends AndroidTestCase {
|
||||
|
||||
private SharedPreferences sharedPreferences;
|
||||
private AntSensorBase heartRateSensor;
|
||||
private static final byte HEART_RATE_CHANNEL = 0;
|
||||
|
||||
private class MockAntDirectSensorManager extends AntDirectSensorManager {
|
||||
public MockAntDirectSensorManager(Context context) {
|
||||
super(context);
|
||||
}
|
||||
@Override
|
||||
protected boolean setupChannel(AntSensorBase sensor, byte channel) {
|
||||
if (channel == HEART_RATE_CHANNEL) {
|
||||
heartRateSensor = sensor;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
private AntDirectSensorManager manager;
|
||||
|
||||
public void setUp() {
|
||||
@@ -35,19 +51,19 @@ public class AntDirectSensorManagerTest extends AndroidTestCase {
|
||||
Constants.SETTINGS_NAME, Context.MODE_PRIVATE);
|
||||
// Let's use default values.
|
||||
sharedPreferences.edit().clear().apply();
|
||||
manager = new AntDirectSensorManager(getContext());
|
||||
manager = new MockAntDirectSensorManager(getContext());
|
||||
}
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
@SmallTest
|
||||
public void testBroadcastData() {
|
||||
manager.setDeviceNumberHRM((short) 42);
|
||||
byte[] buff = new byte[11];
|
||||
buff[0] = 9;
|
||||
buff[1] = AntMesg.MESG_BROADCAST_DATA_ID;
|
||||
buff[2] = 0; // HRM CHANNEL
|
||||
buff[10] = (byte) 220;
|
||||
manager.handleMessage(buff);
|
||||
manager.setupAntSensorChannels();
|
||||
assertNotNull(heartRateSensor);
|
||||
|
||||
heartRateSensor.setDeviceNumber((short) 42);
|
||||
byte[] buff = new byte[9];
|
||||
buff[0] = HEART_RATE_CHANNEL;
|
||||
buff[8] = (byte) 220;
|
||||
manager.handleMessage(AntMesg.MESG_BROADCAST_DATA_ID, buff);
|
||||
|
||||
Sensor.SensorDataSet sds = manager.getSensorDataSet();
|
||||
assertNotNull(sds);
|
||||
@@ -58,38 +74,43 @@ public class AntDirectSensorManagerTest extends AndroidTestCase {
|
||||
|
||||
assertFalse(sds.hasCadence());
|
||||
assertFalse(sds.hasPower());
|
||||
assertEquals(Sensor.SensorState.CONNECTED, manager.getSensorState());
|
||||
}
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
@SmallTest
|
||||
public void testChannelId() {
|
||||
byte[] buff = new byte[11];
|
||||
buff[0] = 9;
|
||||
buff[1] = AntMesg.MESG_CHANNEL_ID_ID;
|
||||
buff[3] = 42;
|
||||
manager.handleMessage(buff);
|
||||
manager.setupAntSensorChannels();
|
||||
assertNotNull(heartRateSensor);
|
||||
|
||||
assertEquals(42, manager.getDeviceNumberHRM());
|
||||
assertEquals(42,
|
||||
byte[] buff = new byte[9];
|
||||
buff[1] = 43;
|
||||
manager.handleMessage(AntMesg.MESG_CHANNEL_ID_ID, buff);
|
||||
|
||||
assertEquals(43, heartRateSensor.getDeviceNumber());
|
||||
assertEquals(43,
|
||||
sharedPreferences.getInt(
|
||||
getContext().getString(R.string.ant_heart_rate_sensor_id_key), -1));
|
||||
assertNull(manager.getSensorDataSet());
|
||||
}
|
||||
|
||||
@SuppressWarnings("deprecation")
|
||||
@SmallTest
|
||||
public void testResponseEvent() {
|
||||
assertEquals(Sensor.SensorState.NONE, manager.getSensorState());
|
||||
byte[] buff = new byte[5];
|
||||
buff[0] = 3; // length
|
||||
buff[1] = AntMesg.MESG_RESPONSE_EVENT_ID;
|
||||
buff[2] = 0; // channel
|
||||
buff[3] = AntMesg.MESG_UNASSIGN_CHANNEL_ID;
|
||||
buff[4] = 0; // code
|
||||
manager.handleMessage(buff);
|
||||
manager.setupAntSensorChannels();
|
||||
assertNotNull(heartRateSensor);
|
||||
manager.setHeartRate(210);
|
||||
heartRateSensor.setDeviceNumber((short) 42);
|
||||
|
||||
assertEquals(Sensor.SensorState.CONNECTED, manager.getSensorState());
|
||||
byte[] buff = new byte[3];
|
||||
buff[0] = HEART_RATE_CHANNEL;
|
||||
buff[1] = AntMesg.MESG_UNASSIGN_CHANNEL_ID;
|
||||
buff[2] = 0; // code
|
||||
manager.handleMessage(AntMesg.MESG_RESPONSE_EVENT_ID, buff);
|
||||
assertEquals(Sensor.SensorState.CONNECTED, manager.getSensorState());
|
||||
|
||||
heartRateSensor.setDeviceNumber((short) 0);
|
||||
manager.handleMessage(AntMesg.MESG_RESPONSE_EVENT_ID, buff);
|
||||
assertEquals(Sensor.SensorState.DISCONNECTED, manager.getSensorState());
|
||||
assertNull(manager.getSensorDataSet());
|
||||
}
|
||||
|
||||
// TODO: Test timeout too.
|
||||
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
/*
|
||||
* Copyright 2012 Google Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
|
||||
* use this file except in compliance with the License. You may obtain a copy of
|
||||
* the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
|
||||
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
|
||||
* License for the specific language governing permissions and limitations under
|
||||
* the License.
|
||||
*/
|
||||
package com.google.android.apps.mytracks.services.sensors.ant;
|
||||
|
||||
import android.test.AndroidTestCase;
|
||||
import android.test.suitebuilder.annotation.SmallTest;
|
||||
|
||||
/**
|
||||
* @author Laszlo Molnar
|
||||
*/
|
||||
public class SensorEventCounterTest extends AndroidTestCase {
|
||||
|
||||
@SmallTest
|
||||
public void testGetEventsPerMinute() {
|
||||
SensorEventCounter sec = new SensorEventCounter();
|
||||
assertEquals(0, sec.getEventsPerMinute(0, 0, 0));
|
||||
assertEquals(0, sec.getEventsPerMinute(1, 1024, 1000));
|
||||
assertEquals(60, sec.getEventsPerMinute(2, 1024 * 2, 2000));
|
||||
assertEquals(60, sec.getEventsPerMinute(2, 1024 * 2, 2500));
|
||||
assertTrue(60 > sec.getEventsPerMinute(2, 1024 * 2, 4000));
|
||||
}
|
||||
}
|
||||
+1
-61
@@ -15,13 +15,6 @@
|
||||
*/
|
||||
package com.google.android.apps.mytracks.services.tasks;
|
||||
|
||||
import com.google.android.apps.mytracks.services.tasks.PeriodicTask;
|
||||
import com.google.android.apps.mytracks.services.tasks.StatusAnnouncerFactory;
|
||||
import com.google.android.apps.mytracks.services.tasks.StatusAnnouncerTask;
|
||||
import com.google.android.apps.mytracks.util.ApiFeatures;
|
||||
|
||||
import android.media.AudioManager;
|
||||
import android.speech.tts.TextToSpeech;
|
||||
import android.test.AndroidTestCase;
|
||||
|
||||
/**
|
||||
@@ -31,62 +24,9 @@ import android.test.AndroidTestCase;
|
||||
* @author Rodrigo Damazio
|
||||
*/
|
||||
public class StatusAnnouncerFactoryTest extends AndroidTestCase {
|
||||
/**
|
||||
* Mock version of the {@link ApiFeatures} class.
|
||||
*/
|
||||
private class MockApiFeatures extends ApiFeatures {
|
||||
private boolean hasTts;
|
||||
|
||||
public void setHasTextToSpeech(boolean hasTts) {
|
||||
this.hasTts = hasTts;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasTextToSpeech() {
|
||||
return hasTts;
|
||||
}
|
||||
}
|
||||
|
||||
private MockApiFeatures apiFeatures;
|
||||
|
||||
@Override
|
||||
protected void setUp() throws Exception {
|
||||
super.setUp();
|
||||
|
||||
apiFeatures = new MockApiFeatures();
|
||||
}
|
||||
|
||||
public void testCreate() {
|
||||
apiFeatures.setHasTextToSpeech(true);
|
||||
PeriodicTaskFactory factory =
|
||||
new StatusAnnouncerFactory(apiFeatures);
|
||||
PeriodicTaskFactory factory = new StatusAnnouncerFactory();
|
||||
PeriodicTask task = factory.create(getContext());
|
||||
assertTrue(task instanceof StatusAnnouncerTask);
|
||||
}
|
||||
|
||||
public void testCreate_notAvailable() {
|
||||
apiFeatures.setHasTextToSpeech(false);
|
||||
PeriodicTaskFactory factory =
|
||||
new StatusAnnouncerFactory(apiFeatures);
|
||||
PeriodicTask task = factory.create(getContext());
|
||||
assertNull(task);
|
||||
}
|
||||
|
||||
public void testGetVolumeStream() {
|
||||
apiFeatures.setHasTextToSpeech(true);
|
||||
StatusAnnouncerFactory factory =
|
||||
new StatusAnnouncerFactory(apiFeatures);
|
||||
assertEquals(
|
||||
TextToSpeech.Engine.DEFAULT_STREAM,
|
||||
factory.getVolumeStream());
|
||||
}
|
||||
|
||||
public void testGetVolumeStream_notAvailable() {
|
||||
apiFeatures.setHasTextToSpeech(false);
|
||||
StatusAnnouncerFactory factory =
|
||||
new StatusAnnouncerFactory(apiFeatures);
|
||||
assertEquals(
|
||||
AudioManager.USE_DEFAULT_STREAM_TYPE,
|
||||
factory.getVolumeStream());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,62 +0,0 @@
|
||||
/*
|
||||
* Copyright 2010 Google Inc.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
|
||||
* use this file except in compliance with the License. You may obtain a copy of
|
||||
* the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
|
||||
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
|
||||
* License for the specific language governing permissions and limitations under
|
||||
* the License.
|
||||
*/
|
||||
package com.google.android.apps.mytracks.util;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
/**
|
||||
* Tests the API feature detection code in {@link ApiFeatures}.
|
||||
* This test requires Froyo+ to run.
|
||||
*
|
||||
* @author Rodrigo Damazio
|
||||
*/
|
||||
public class ApiFeaturesTest extends TestCase {
|
||||
|
||||
private TestableApiFeatures features;
|
||||
|
||||
private class TestableApiFeatures extends ApiFeatures {
|
||||
private int apiLevel;
|
||||
|
||||
public void setApiLevel(int apiLevel) {
|
||||
this.apiLevel = apiLevel;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected int getApiLevel() {
|
||||
return apiLevel;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void setUp() throws Exception {
|
||||
super.setUp();
|
||||
|
||||
features = new TestableApiFeatures();
|
||||
}
|
||||
|
||||
public void testHasTextToSpeech() {
|
||||
features.setApiLevel(3);
|
||||
assertFalse(features.hasTextToSpeech());
|
||||
for (int i = 4; i <= 8; i++) {
|
||||
features.setApiLevel(i);
|
||||
assertTrue(features.hasTextToSpeech());
|
||||
}
|
||||
}
|
||||
|
||||
public void testGetApiAdapter() {
|
||||
assertNotNull(features.getApiAdapter());
|
||||
}
|
||||
}
|
||||
@@ -15,68 +15,217 @@
|
||||
*/
|
||||
package com.google.android.apps.mytracks.util;
|
||||
|
||||
import android.test.AndroidTestCase;
|
||||
|
||||
import java.util.GregorianCalendar;
|
||||
import java.util.TimeZone;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
/**
|
||||
* Tests for {@link StringUtils}.
|
||||
*
|
||||
* @author Rodrigo Damazio
|
||||
*/
|
||||
public class StringUtilsTest extends TestCase {
|
||||
public void testParseXmlDateTime() {
|
||||
assertParseXmlDateTime("2010-05-04T03:02:01",
|
||||
2010, 5, 4, 3, 2, 1, 0);
|
||||
public class StringUtilsTest extends AndroidTestCase {
|
||||
|
||||
/**
|
||||
* Tests {@link StringUtils#formatDateTime(android.content.Context, long)}.
|
||||
*/
|
||||
public void testFormatTime() {
|
||||
// Unix time 0 in UTC is "4:00 PM" in Pacific Standard time zone.
|
||||
// This test can break if run on a different time zone or with a different
|
||||
// time format preference.
|
||||
assertEquals("4:00 PM", StringUtils.formatTime(getContext(), 0L));
|
||||
}
|
||||
|
||||
public void testParseXmlDateTime_fractional() {
|
||||
assertParseXmlDateTime("2010-05-04T03:02:01.3",
|
||||
2010, 5, 4, 3, 2, 1, 300);
|
||||
assertParseXmlDateTime("2010-05-04T03:02:01.35",
|
||||
2010, 5, 4, 3, 2, 1, 350);
|
||||
assertParseXmlDateTime("2010-05-04T03:02:01.352",
|
||||
2010, 5, 4, 3, 2, 1, 352);
|
||||
assertParseXmlDateTime("2010-05-04T03:02:01.3525",
|
||||
2010, 5, 4, 3, 2, 1, 352);
|
||||
/**
|
||||
* Tests {@link StringUtils#formatDateTime(android.content.Context, long)}.
|
||||
*/
|
||||
public void testFormatDateTime() {
|
||||
// Unix time 0 in UTC is "12/31/1969 4:00 PM" in Pacific Standard time zone.
|
||||
// This test can break if run on a different time zone or with a different
|
||||
// date/time format preference.
|
||||
assertEquals("12/31/1969 4:00 PM", StringUtils.formatDateTime(getContext(), 0L));
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests {@link StringUtils#formatDateTimeIso8601(long)}.
|
||||
*/
|
||||
public void testFormatDateTimeIso8601() {
|
||||
assertEquals("1970-01-01T00:00:12.345Z", StringUtils.formatDateTimeIso8601(12345));
|
||||
}
|
||||
|
||||
public void testParseXmlDateTime_timezone() {
|
||||
assertParseXmlDateTime("2010-05-04T03:02:01Z",
|
||||
2010, 5, 4, 3, 2, 1, 0);
|
||||
assertParseXmlDateTime("2010-05-04T03:02:01+00:00",
|
||||
2010, 5, 4, 3, 2, 1, 0);
|
||||
assertParseXmlDateTime("2010-05-04T03:02:01-00:00",
|
||||
2010, 5, 4, 3, 2, 1, 0);
|
||||
assertParseXmlDateTime("2010-05-04T03:02:01+01:00",
|
||||
2010, 5, 4, 2, 2, 1, 0);
|
||||
assertParseXmlDateTime("2010-05-04T03:02:01+10:30",
|
||||
2010, 5, 3, 16, 32, 1, 0);
|
||||
assertParseXmlDateTime("2010-05-04T03:02:01-09:30",
|
||||
2010, 5, 4, 12, 32, 1, 0);
|
||||
assertParseXmlDateTime("2010-05-04T03:02:01-05:00",
|
||||
2010, 5, 4, 8, 2, 1, 0);
|
||||
/**
|
||||
* Tests {@link StringUtils#formatElapsedTime(long)}.
|
||||
*/
|
||||
public void testformatElapsedTime() {
|
||||
// 1 second
|
||||
assertEquals("00:01", StringUtils.formatElapsedTime(1000));
|
||||
// 10 seconds
|
||||
assertEquals("00:10", StringUtils.formatElapsedTime(10000));
|
||||
// 1 minute
|
||||
assertEquals("01:00", StringUtils.formatElapsedTime(60000));
|
||||
// 10 minutes
|
||||
assertEquals("10:00", StringUtils.formatElapsedTime(600000));
|
||||
// 1 hour
|
||||
assertEquals("1:00:00", StringUtils.formatElapsedTime(3600000));
|
||||
// 10 hours
|
||||
assertEquals("10:00:00", StringUtils.formatElapsedTime(36000000));
|
||||
// 100 hours
|
||||
assertEquals("100:00:00", StringUtils.formatElapsedTime(360000000));
|
||||
}
|
||||
|
||||
public void testParseXmlDateTime_fractionalAndTimezone() {
|
||||
assertParseXmlDateTime("2010-05-04T03:02:01.352Z",
|
||||
2010, 5, 4, 3, 2, 1, 352);
|
||||
assertParseXmlDateTime("2010-05-04T03:02:01.47+00:00",
|
||||
2010, 5, 4, 3, 2, 1, 470);
|
||||
assertParseXmlDateTime("2010-05-04T03:02:01.5791+03:00",
|
||||
2010, 5, 4, 0, 2, 1, 579);
|
||||
assertParseXmlDateTime("2010-05-04T03:02:01.8-05:30",
|
||||
2010, 5, 4, 8, 32, 1, 800);
|
||||
/**
|
||||
* Tests {@link StringUtils#formatElapsedTimeWithHour(long)}.
|
||||
*/
|
||||
public void testformatElapsedTimeWithHour() {
|
||||
// 1 second
|
||||
assertEquals("0:00:01", StringUtils.formatElapsedTimeWithHour(1000));
|
||||
// 10 seconds
|
||||
assertEquals("0:00:10", StringUtils.formatElapsedTimeWithHour(10000));
|
||||
// 1 minute
|
||||
assertEquals("0:01:00", StringUtils.formatElapsedTimeWithHour(60000));
|
||||
// 10 minutes
|
||||
assertEquals("0:10:00", StringUtils.formatElapsedTimeWithHour(600000));
|
||||
// 1 hour
|
||||
assertEquals("1:00:00", StringUtils.formatElapsedTimeWithHour(3600000));
|
||||
// 10 hours
|
||||
assertEquals("10:00:00", StringUtils.formatElapsedTimeWithHour(36000000));
|
||||
// 100 hours
|
||||
assertEquals("100:00:00", StringUtils.formatElapsedTimeWithHour(360000000));
|
||||
}
|
||||
|
||||
private void assertParseXmlDateTime(String dateTime,
|
||||
int year, int month, int day, int hour, int min, int second, int millis) {
|
||||
long timestamp = StringUtils.parseXmlDateTime(dateTime);
|
||||
GregorianCalendar calendar =
|
||||
new GregorianCalendar(TimeZone.getTimeZone("UTC"));
|
||||
calendar.set(year, month - 1, day, hour, min, second);
|
||||
calendar.set(GregorianCalendar.MILLISECOND, millis);
|
||||
assertEquals(calendar.getTimeInMillis(), timestamp);
|
||||
/**
|
||||
* Tests {@link StringUtils#formatDistance(android.content.Context, double,
|
||||
* boolean)}.
|
||||
*/
|
||||
public void testFormatDistance() {
|
||||
// A large number in metric
|
||||
assertEquals("5.00 km", StringUtils.formatDistance(getContext(), 5000, true));
|
||||
// A large number in imperial
|
||||
assertEquals("3.11 mi", StringUtils.formatDistance(getContext(), 5000, false));
|
||||
// A small number in metric
|
||||
assertEquals("100.00 m", StringUtils.formatDistance(getContext(), 100, true));
|
||||
// A small number in imperial
|
||||
assertEquals("328.08 ft", StringUtils.formatDistance(getContext(), 100, false));
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests {@link StringUtils#formatSpeed(android.content.Context, double,
|
||||
* boolean, boolean)}.
|
||||
*/
|
||||
public void testFormatSpeed() {
|
||||
// Speed in metric
|
||||
assertEquals("36.00 km/h", StringUtils.formatSpeed(getContext(), 10, true, true));
|
||||
// Speed in imperial
|
||||
assertEquals("22.37 mi/h", StringUtils.formatSpeed(getContext(), 10, false, true));
|
||||
// Pace in metric
|
||||
assertEquals("1.67 min/km", StringUtils.formatSpeed(getContext(), 10, true, false));
|
||||
// Pace in imperial
|
||||
assertEquals("2.68 min/mi", StringUtils.formatSpeed(getContext(), 10, false, false));
|
||||
// zero pace
|
||||
assertEquals("0.00 min/km", StringUtils.formatSpeed(getContext(), 0, true, false));
|
||||
assertEquals("0.00 min/mi", StringUtils.formatSpeed(getContext(), 0, false, false));
|
||||
// speed is NaN
|
||||
assertEquals("-", StringUtils.formatSpeed(getContext(), Double.NaN, true, true));
|
||||
// speed is infinite
|
||||
assertEquals("-", StringUtils.formatSpeed(getContext(), Double.NEGATIVE_INFINITY, true, true));
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests {@link StringUtils#formatTimeDistance(android.content.Context, long, double, boolean)}.
|
||||
*/
|
||||
public void testFormatTimeDistance() {
|
||||
assertEquals("00:10 5.00 km", StringUtils.formatTimeDistance(getContext(), 10000, 5000, true));
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests {@link StringUtils#formatCData(String)}.
|
||||
*/
|
||||
public void testFormatCData() {
|
||||
assertEquals("<![CDATA[hello]]>", StringUtils.formatCData("hello"));
|
||||
assertEquals("<![CDATA[hello]]]]><![CDATA[>there]]>", StringUtils.formatCData("hello]]>there"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests {@link StringUtils#getTime(String)}.
|
||||
*/
|
||||
public void testGetTime() {
|
||||
assertGetTime("2010-05-04T03:02:01", 2010, 5, 4, 3, 2, 1, 0);
|
||||
assertGetTime("2010-05-04T03:02:01Z", 2010, 5, 4, 3, 2, 1, 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests {@link StringUtils#getTime(String)} with fractional seconds.
|
||||
*/
|
||||
public void testGetTime_fractional() {
|
||||
assertGetTime("2010-05-04T03:02:01.3", 2010, 5, 4, 3, 2, 1, 300);
|
||||
assertGetTime("2010-05-04T03:02:01.35", 2010, 5, 4, 3, 2, 1, 350);
|
||||
assertGetTime("2010-05-04T03:02:01.352Z", 2010, 5, 4, 3, 2, 1, 352);
|
||||
assertGetTime("2010-05-04T03:02:01.3525Z", 2010, 5, 4, 3, 2, 1, 352);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests {@link StringUtils#getTime(String)} with time zone.
|
||||
*/
|
||||
public void testGetTime_timezone() {
|
||||
assertGetTime("2010-05-04T03:02:01Z", 2010, 5, 4, 3, 2, 1, 0);
|
||||
assertGetTime("2010-05-04T03:02:01+00:00", 2010, 5, 4, 3, 2, 1, 0);
|
||||
assertGetTime("2010-05-04T03:02:01-00:00", 2010, 5, 4, 3, 2, 1, 0);
|
||||
assertGetTime("2010-05-04T03:02:01+01:00", 2010, 5, 4, 2, 2, 1, 0);
|
||||
assertGetTime("2010-05-04T03:02:01+10:30", 2010, 5, 3, 16, 32, 1, 0);
|
||||
assertGetTime("2010-05-04T03:02:01-09:30", 2010, 5, 4, 12, 32, 1, 0);
|
||||
assertGetTime("2010-05-04T03:02:01-05:00", 2010, 5, 4, 8, 2, 1, 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests {@link StringUtils#getTime(String)} with fractional seconds and time
|
||||
* zone.
|
||||
*/
|
||||
public void testGetTime_fractionalAndTimezone() {
|
||||
assertGetTime("2010-05-04T03:02:01.352Z", 2010, 5, 4, 3, 2, 1, 352);
|
||||
assertGetTime("2010-05-04T03:02:01.47+00:00", 2010, 5, 4, 3, 2, 1, 470);
|
||||
assertGetTime("2010-05-04T03:02:01.5791+03:00", 2010, 5, 4, 0, 2, 1, 579);
|
||||
assertGetTime("2010-05-04T03:02:01.8-05:30", 2010, 5, 4, 8, 32, 1, 800);
|
||||
}
|
||||
|
||||
/**
|
||||
* Asserts the {@link StringUtils#getTime(String)} returns the expected
|
||||
* values.
|
||||
*
|
||||
* @param xmlDateTime the xml date time string
|
||||
* @param year the expected year
|
||||
* @param month the expected month
|
||||
* @param day the expected day
|
||||
* @param hour the expected hour
|
||||
* @param minute the expected minute
|
||||
* @param second the expected second
|
||||
* @param millisecond the expected milliseconds
|
||||
*/
|
||||
private void assertGetTime(String xmlDateTime, int year, int month, int day, int hour, int minute,
|
||||
int second, int millisecond) {
|
||||
GregorianCalendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
|
||||
calendar.set(year, month - 1, day, hour, minute, second);
|
||||
calendar.set(GregorianCalendar.MILLISECOND, millisecond);
|
||||
assertEquals(calendar.getTimeInMillis(), StringUtils.getTime(xmlDateTime));
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests {@link StringUtils#getTimeParts(long)} with a positive number.
|
||||
*/
|
||||
public void testGetTimeParts_postive() {
|
||||
int parts[] = StringUtils.getTimeParts(61000);
|
||||
assertEquals(1, parts[0]);
|
||||
assertEquals(1, parts[1]);
|
||||
assertEquals(0, parts[2]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests {@link StringUtils#getTimeParts(long)} with a negative number.
|
||||
*/
|
||||
public void testGetTimeParts_negative() {
|
||||
int parts[] = StringUtils.getTimeParts(-61000);
|
||||
assertEquals(-1, parts[0]);
|
||||
assertEquals(-1, parts[1]);
|
||||
assertEquals(0, parts[2]);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user