merge heads with Google Location settings change from My Tracks 2.0.1

This commit is contained in:
Jimmy Shih
2012-08-14 12:32:56 -07:00
100 changed files with 8715 additions and 7279 deletions
@@ -25,121 +25,137 @@ import android.location.Location;
import android.test.AndroidTestCase;
/**
* Tests for the MyTracks map overlay.
* Tests {@link MapOverlay}.
*
* @author Bartlomiej Niechwiej
* @author Vangelis S.
*/
public class MapOverlayTest extends AndroidTestCase {
private Canvas canvas;
private MockMyTracksOverlay myTracksOverlay;
private MapView mockView;
private MockMyTracksOverlay mockMyTracksOverlay;
private MapView mapView;
@Override
protected void setUp() throws Exception {
super.setUp();
canvas = new Canvas();
myTracksOverlay = new MockMyTracksOverlay(getContext());
mockMyTracksOverlay = new MockMyTracksOverlay(getContext());
// Enable drawing.
myTracksOverlay.setTrackDrawingEnabled(true);
mockMyTracksOverlay.setTrackDrawingEnabled(true);
// Set a TrackPathPainter with a MockPath.
myTracksOverlay.setTrackPathPainter(new SingleColorTrackPathPainter(getContext()) {
@Override
mockMyTracksOverlay.setTrackPathPainter(new SingleColorTrackPathPainter(getContext()) {
@Override
public Path newPath() {
return new MockPath();
}
}
});
mockView = null;
mapView = null;
}
public void testAddLocation() throws Exception {
/**
* Tests {@link MapOverlay#addLocation(Location)}.
*/
public void testAddLocation() throws Exception {
Location location = new Location("gps");
location.setLatitude(10);
location.setLongitude(20);
myTracksOverlay.addLocation(location);
assertEquals(1, myTracksOverlay.getNumLocations());
assertEquals(0, myTracksOverlay.getNumWaypoints());
mockMyTracksOverlay.addLocation(location);
assertEquals(1, mockMyTracksOverlay.getNumLocations());
assertEquals(0, mockMyTracksOverlay.getNumWaypoints());
location.setLatitude(20);
location.setLongitude(30);
myTracksOverlay.addLocation(location);
assertEquals(2, myTracksOverlay.getNumLocations());
assertEquals(0, myTracksOverlay.getNumWaypoints());
assertNull(myTracksOverlay.getTrackPathPainter().getLastPath());
mockMyTracksOverlay.addLocation(location);
assertEquals(2, mockMyTracksOverlay.getNumLocations());
assertEquals(0, mockMyTracksOverlay.getNumWaypoints());
assertFalse(mockMyTracksOverlay.getTrackPathPainter().hasPath());
// Draw and make sure that we don't lose any point.
myTracksOverlay.draw(canvas, mockView, false);
assertEquals(2, myTracksOverlay.getNumLocations());
assertEquals(0, myTracksOverlay.getNumWaypoints());
assertNotNull(myTracksOverlay.getTrackPathPainter().getLastPath());
assertTrue(myTracksOverlay.getTrackPathPainter().getLastPath() instanceof MockPath);
MockPath path = (MockPath) myTracksOverlay.getTrackPathPainter().getLastPath();
assertEquals(2, path.totalPoints);
myTracksOverlay.draw(canvas, mockView, true);
assertEquals(2, myTracksOverlay.getNumLocations());
assertEquals(0, myTracksOverlay.getNumWaypoints());
assertNotNull(myTracksOverlay.getTrackPathPainter().getLastPath());
mockMyTracksOverlay.draw(canvas, mapView, false);
assertEquals(2, mockMyTracksOverlay.getNumLocations());
assertEquals(0, mockMyTracksOverlay.getNumWaypoints());
assertTrue(mockMyTracksOverlay.getTrackPathPainter().hasPath());
SingleColorTrackPathPainter trackPathPainter = (SingleColorTrackPathPainter) mockMyTracksOverlay
.getTrackPathPainter();
MockPath path = (MockPath) trackPathPainter.getPath();
assertEquals(2, path.getTotalPoints());
mockMyTracksOverlay.draw(canvas, mapView, true);
assertEquals(2, mockMyTracksOverlay.getNumLocations());
assertEquals(0, mockMyTracksOverlay.getNumWaypoints());
assertTrue(mockMyTracksOverlay.getTrackPathPainter().hasPath());
}
/**
* Tests {@link MapOverlay#clearPoints()}.
*/
public void testClearPoints() throws Exception {
Location location = new Location("gps");
location.setLatitude(10);
location.setLongitude(20);
myTracksOverlay.addLocation(location);
assertEquals(1, myTracksOverlay.getNumLocations());
myTracksOverlay.clearPoints();
assertEquals(0, myTracksOverlay.getNumLocations());
mockMyTracksOverlay.addLocation(location);
assertEquals(1, mockMyTracksOverlay.getNumLocations());
mockMyTracksOverlay.clearPoints();
assertEquals(0, mockMyTracksOverlay.getNumLocations());
// Same after drawing on canvas.
// Test after drawing on canvas
final int locations = 100;
for (int i = 0; i < locations; ++i) {
myTracksOverlay.addLocation(location);
mockMyTracksOverlay.addLocation(location);
}
assertEquals(locations, myTracksOverlay.getNumLocations());
myTracksOverlay.draw(canvas, mockView, false);
myTracksOverlay.draw(canvas, mockView, true);
myTracksOverlay.clearPoints();
assertEquals(0, myTracksOverlay.getNumLocations());
assertEquals(locations, mockMyTracksOverlay.getNumLocations());
mockMyTracksOverlay.draw(canvas, mapView, false);
mockMyTracksOverlay.draw(canvas, mapView, true);
mockMyTracksOverlay.clearPoints();
assertEquals(0, mockMyTracksOverlay.getNumLocations());
}
/**
* Tests {@link MapOverlay#addWaypoint(Waypoint)}.
*/
public void testAddWaypoint() throws Exception {
Location location = new Location("gps");
location.setLatitude(10);
location.setLongitude(20);
Waypoint waypoint = new Waypoint();
waypoint.setLocation(location);
myTracksOverlay.addWaypoint(waypoint);
assertEquals(1, myTracksOverlay.getNumWaypoints());
assertEquals(0, myTracksOverlay.getNumLocations());
assertNull(myTracksOverlay.getTrackPathPainter().getLastPath());
mockMyTracksOverlay.addWaypoint(waypoint);
assertEquals(1, mockMyTracksOverlay.getNumWaypoints());
assertEquals(0, mockMyTracksOverlay.getNumLocations());
assertFalse(mockMyTracksOverlay.getTrackPathPainter().hasPath());
final int waypoints = 10;
for (int i = 0; i < waypoints; ++i) {
waypoint = new Waypoint();
waypoint.setLocation(location);
myTracksOverlay.addWaypoint(waypoint);
mockMyTracksOverlay.addWaypoint(waypoint);
}
assertEquals(1 + waypoints, myTracksOverlay.getNumWaypoints());
assertEquals(0, myTracksOverlay.getNumLocations());
assertNull(myTracksOverlay.getTrackPathPainter().getLastPath());
assertEquals(1 + waypoints, mockMyTracksOverlay.getNumWaypoints());
assertEquals(0, mockMyTracksOverlay.getNumLocations());
assertFalse(mockMyTracksOverlay.getTrackPathPainter().hasPath());
}
/**
* Tests {@link MapOverlay#clearWaypoints()}.
*/
public void testClearWaypoints() throws Exception {
Location location = new Location("gps");
location.setLatitude(10);
location.setLongitude(20);
Waypoint waypoint = new Waypoint();
waypoint.setLocation(location);
myTracksOverlay.addWaypoint(waypoint);
assertEquals(1, myTracksOverlay.getNumWaypoints());
myTracksOverlay.clearWaypoints();
assertEquals(0, myTracksOverlay.getNumWaypoints());
mockMyTracksOverlay.addWaypoint(waypoint);
assertEquals(1, mockMyTracksOverlay.getNumWaypoints());
mockMyTracksOverlay.clearWaypoints();
assertEquals(0, mockMyTracksOverlay.getNumWaypoints());
}
/**
* Tests {@link MapOverlay#draw(Canvas, MapView, boolean)}.
*/
public void testDrawing() {
Location location = new Location("gps");
location.setLatitude(10);
@@ -147,30 +163,30 @@ public class MapOverlayTest extends AndroidTestCase {
location.setLongitude(20 + i);
Waypoint waypoint = new Waypoint();
waypoint.setLocation(location);
myTracksOverlay.addWaypoint(waypoint);
mockMyTracksOverlay.addWaypoint(waypoint);
}
for (int i = 0; i < 100; ++i) {
location = new Location("gps");
location.setLatitude(20 + i / 2);
location.setLongitude(150 - i);
myTracksOverlay.addLocation(location);
mockMyTracksOverlay.addLocation(location);
}
// Shadow.
myTracksOverlay.draw(canvas, mockView, true);
// We don't expect to do anything if
assertNull(myTracksOverlay.getTrackPathPainter().getLastPath());
assertEquals(40, myTracksOverlay.getNumWaypoints());
assertEquals(100, myTracksOverlay.getNumLocations());
mockMyTracksOverlay.draw(canvas, mapView, true);
// We don't expect to do anything if
assertFalse(mockMyTracksOverlay.getTrackPathPainter().hasPath());
assertEquals(40, mockMyTracksOverlay.getNumWaypoints());
assertEquals(100, mockMyTracksOverlay.getNumLocations());
// No shadow.
myTracksOverlay.draw(canvas, mockView, false);
assertNotNull(myTracksOverlay.getTrackPathPainter().getLastPath());
assertTrue(myTracksOverlay.getTrackPathPainter().getLastPath() instanceof MockPath);
MockPath path = (MockPath) myTracksOverlay.getTrackPathPainter().getLastPath();
assertEquals(40, myTracksOverlay.getNumWaypoints());
assertEquals(100, myTracksOverlay.getNumLocations());
assertEquals(100, path.totalPoints);
// TODO: Check the points from the path (and the segments).
mockMyTracksOverlay.draw(canvas, mapView, false);
assertTrue(mockMyTracksOverlay.getTrackPathPainter().hasPath());
SingleColorTrackPathPainter trackPathPainter = (SingleColorTrackPathPainter) mockMyTracksOverlay
.getTrackPathPainter();
MockPath path = (MockPath) trackPathPainter.getPath();
assertEquals(40, mockMyTracksOverlay.getNumWaypoints());
assertEquals(100, mockMyTracksOverlay.getNumLocations());
assertEquals(100, path.getTotalPoints());
}
}
@@ -22,30 +22,28 @@ import android.content.Context;
import android.graphics.Rect;
/**
* Elements for Tests for the MyTracks map overlay.
* A mock {@link MapOverlay} for testing.
*
* @author Bartlomiej Niechwiej
* @author Vangelis S.
*
* A mock version of {@code MapOverlay} that does not use
* {@class MapView}.
*/
public class MockMyTracksOverlay extends MapOverlay {
private Projection mockProjection;
private Projection projection;
public MockMyTracksOverlay(Context context) {
super(context);
mockProjection = new MockProjection();
projection = new MockProjection();
}
@Override
public Projection getMapProjection(MapView mapView) {
return mockProjection;
return projection;
}
@Override
public Rect getMapViewRect(MapView mapView) {
return new Rect(0, 0, 100, 100);
return new Rect(0, 0, (int) (100 * 1E6), (int) (100 * 1E6));
}
}
@@ -26,20 +26,19 @@ import java.util.List;
import junit.framework.Assert;
/**
* Elements for Tests for the MyTracks map overlay.
* A mock {@link Path}. Records calls to {@link Path#lineTo(float, float)} and
* {@link Path#moveTo(float, float)}.
*
* @author Bartlomiej Niechwiej
* @author Vangelis S.
*
* A mock class that intercepts {@code Path}'s and records calls to
* {@code #moveTo()} and {@code #lineTo()}.
*/
public class MockPath extends Path {
// A list of disjointed path segments.
private final List<List<PointF>> segments = new LinkedList<List<PointF>>();
/** A list of disjoined path segments. */
public final List<List<PointF>> segments = new LinkedList<List<PointF>>();
/** The total number of points in this path. */
public int totalPoints;
// The total number of points in this path.
private int totalPoints;
private List<PointF> currentSegment;
@Override
@@ -49,12 +48,20 @@ public class MockPath extends Path {
currentSegment.add(new PointF(x, y));
totalPoints++;
}
@Override
public void moveTo(float x, float y) {
super.moveTo(x, y);
segments.add(currentSegment =
new ArrayList<PointF>(Arrays.asList(new PointF(x, y))));
currentSegment = new ArrayList<PointF>(Arrays.asList(new PointF(x, y)));
segments.add(currentSegment);
totalPoints++;
}
/**
* Gets the total number of points in this path.
*/
public int getTotalPoints() {
return totalPoints;
}
}
@@ -13,6 +13,7 @@
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks;
import com.google.android.maps.GeoPoint;
@@ -21,18 +22,17 @@ import com.google.android.maps.Projection;
import android.graphics.Point;
/**
* Elements for Tests for the MyTracks map overlay.
* A mock {@link Projection}. Acts as an identity matrix.
*
* @author Bartlomiej Niechwiej
* @author Vangelis S.
*
* A mock {@code Projection} that acts as the identity matrix.
*/
public class MockProjection implements Projection {
@Override
public Point toPixels(GeoPoint in, Point out) {
return out;
public Point toPixels(GeoPoint geoPoint, Point point) {
return point;
}
@Override
@@ -112,7 +112,8 @@ public class DescriptionGeneratorImplTest extends AndroidTestCase {
+ "Max grade: 42 %\n"
+ "Min grade: 11 %\n"
+ "Recorded: " + StringUtils.formatDateTime(getContext(), START_TIME) + "\n";
assertEquals(expected, descriptionGenerator.generateWaypointDescription(waypoint));
assertEquals(
expected, descriptionGenerator.generateWaypointDescription(waypoint.getTripStatistics()));
}
/**
@@ -0,0 +1,196 @@
/*
* 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.MyTracksProvider.DatabaseHelper;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.test.AndroidTestCase;
/**
* A unit test for {@link MyTracksProvider}.
*
* @author Youtao Liu
*/
public class MyTracksProviderTest extends AndroidTestCase {
private SQLiteDatabase db;
private MyTracksProvider myTracksProvider;
private String DATABASE_NAME = "mytrackstest.db";
@Override
protected void setUp() throws Exception {
getContext().deleteDatabase(DATABASE_NAME);
db = (new DatabaseHelper(getContext(), DATABASE_NAME)).getWritableDatabase();
myTracksProvider = new MyTracksProvider();
super.setUp();
}
/**
* Tests the method {@link MyTracksProvider.DatabaseHelper#onCreate()}.
*/
public void testDatabaseHelper_OnCreate() {
assertTrue(checkTable(TrackPointsColumns.TABLE_NAME));
assertTrue(checkTable(TracksColumns.TABLE_NAME));
assertTrue(checkTable(WaypointsColumns.TABLE_NAME));
}
/**
* Tests the method
* {@link MyTracksProvider.DatabaseHelper#onUpgrade(SQLiteDatabase, int, int)}
* when version is less than 17.
*/
public void testDatabaseHelper_onUpgrade_Version16() {
DatabaseHelper databaseHelper = new DatabaseHelper(getContext());
dropTable(TrackPointsColumns.TABLE_NAME);
dropTable(TracksColumns.TABLE_NAME);
dropTable(WaypointsColumns.TABLE_NAME);
databaseHelper.onUpgrade(db, 16, 20);
assertTrue(checkTable(TrackPointsColumns.TABLE_NAME));
assertTrue(checkTable(TracksColumns.TABLE_NAME));
assertTrue(checkTable(WaypointsColumns.TABLE_NAME));
}
/**
* Tests the method
* {@link MyTracksProvider.DatabaseHelper#onUpgrade(SQLiteDatabase, int, int)}
* when version is 17.
*/
public void testDatabaseHelper_onUpgrade_Version17() {
DatabaseHelper databaseHelper = new DatabaseHelper(getContext());
// Make two table is only contains one normal integer column.
dropTable(TrackPointsColumns.TABLE_NAME);
dropTable(TracksColumns.TABLE_NAME);
createEmptyTable(TrackPointsColumns.TABLE_NAME);
createEmptyTable(TracksColumns.TABLE_NAME);
databaseHelper.onUpgrade(db, 17, 20);
assertTrue(isColumnExisted(TrackPointsColumns.TABLE_NAME, TrackPointsColumns.SENSOR));
assertTrue(isColumnExisted(TracksColumns.TABLE_NAME, TracksColumns.TABLEID));
assertTrue(isColumnExisted(TracksColumns.TABLE_NAME, TracksColumns.ICON));
}
/**
* Tests the method
* {@link MyTracksProvider.DatabaseHelper#onUpgrade(SQLiteDatabase, int, int)}
* when version is 18.
*/
public void testDatabaseHelper_onUpgrade_Version18() {
DatabaseHelper databaseHelper = new DatabaseHelper(getContext());
// Make two table is only contains one normal integer column.
dropTable(TrackPointsColumns.TABLE_NAME);
dropTable(TracksColumns.TABLE_NAME);
createEmptyTable(TrackPointsColumns.TABLE_NAME);
createEmptyTable(TracksColumns.TABLE_NAME);
databaseHelper.onUpgrade(db, 18, 20);
assertFalse(isColumnExisted(TrackPointsColumns.TABLE_NAME, TrackPointsColumns.SENSOR));
assertTrue(isColumnExisted(TracksColumns.TABLE_NAME, TracksColumns.TABLEID));
assertTrue(isColumnExisted(TracksColumns.TABLE_NAME, TracksColumns.ICON));
}
/**
* Tests the method
* {@link MyTracksProvider.DatabaseHelper#onUpgrade(SQLiteDatabase, int, int)}
* when version is 19.
*/
public void testDatabaseHelper_onUpgrade_Version19() {
DatabaseHelper databaseHelper = new DatabaseHelper(getContext());
// Make two table is only contains one normal integer column.
dropTable(TrackPointsColumns.TABLE_NAME);
dropTable(TracksColumns.TABLE_NAME);
createEmptyTable(TrackPointsColumns.TABLE_NAME);
createEmptyTable(TracksColumns.TABLE_NAME);
databaseHelper.onUpgrade(db, 19, 20);
assertFalse(isColumnExisted(TrackPointsColumns.TABLE_NAME, TrackPointsColumns.SENSOR));
assertFalse(isColumnExisted(TracksColumns.TABLE_NAME, TracksColumns.TABLEID));
assertTrue(isColumnExisted(TracksColumns.TABLE_NAME, TracksColumns.ICON));
}
/**
* Tests the method {@link MyTracksProvider#onCreate()}.
*/
public void testOnCreate() {
assertTrue(myTracksProvider.onCreate(getContext()));
}
/**
* Tests the method {@link MyTracksProvider#getType(Uri)}.
*/
public void testGetType() {
assertEquals(TrackPointsColumns.CONTENT_TYPE,
myTracksProvider.getType(TrackPointsColumns.CONTENT_URI));
assertEquals(TracksColumns.CONTENT_TYPE, myTracksProvider.getType(TracksColumns.CONTENT_URI));
assertEquals(WaypointsColumns.CONTENT_TYPE,
myTracksProvider.getType(WaypointsColumns.CONTENT_URI));
}
/**
* Creates an table only contains one column.
*
* @param table the name of table
*/
private void createEmptyTable(String table) {
db.execSQL("CREATE TABLE " + table + " (test INTEGER)");
}
/**
* Drops a table in database.
*
* @param table
*/
private void dropTable(String table) {
db.execSQL("Drop TABLE " + table);
}
/**
* Checks whether a table is existed.
*
* @param table the name of table
* @return true means the table has existed
*/
private boolean checkTable(String table) {
try {
db.rawQuery("select count(*) from " + table, null);
return true;
} catch (Exception e) {
return false;
}
}
/**
* Checks whether a column in a table is existed by whether can order by the
* column.
*
* @param table the name of table
* @param column the name of column
* @return true means the column has existed
*/
private boolean isColumnExisted(String table, String column) {
try {
db.execSQL("SElECT count(*) from " + table + " order by " + column);
} catch (Exception e) {
if (e.getMessage().indexOf("no such column") > -1) {
return false;
}
}
return true;
}
}
@@ -18,8 +18,14 @@ package com.google.android.apps.mytracks.content;
import com.google.android.apps.mytracks.content.MyTracksProviderUtils.LocationFactory;
import com.google.android.apps.mytracks.content.MyTracksProviderUtils.LocationIterator;
import com.google.android.apps.mytracks.services.TrackRecordingServiceTest.MockContext;
import com.google.android.apps.mytracks.stats.TripStatistics;
import com.google.android.testing.mocking.AndroidMock;
import com.google.android.testing.mocking.UsesMocks;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.location.Location;
import android.test.AndroidTestCase;
import android.test.RenamingDelegatingContext;
@@ -27,16 +33,27 @@ import android.test.mock.MockContentResolver;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import java.util.concurrent.atomic.AtomicInteger;
/**
* A unit test for {@link MyTracksProviderUtilsImpl}.
*
* @author Bartlomiej Niechwiej
* @author Youtao Liu
*/
public class MyTracksProviderUtilsImplTest extends AndroidTestCase {
private Context context;
private MyTracksProviderUtils providerUtils;
private static final String NAME_PREFIX = "test name";
private static final String TRACK_CATEGORY = "test category";
private static final String MOCK_DESC = "Mock Next Waypoint Desc!";
private static final String TEST_DESC = "Test Desc!";
private static final String TEST_DESC_NEW = "Test Desc new!";
private double INITIAL_LATITUDE = 37.0;
private double INITIAL_LONGITUDE = -57.0;
private double ALTITUDE_INTERVAL = 2.5;
@Override
protected void setUp() throws Exception {
@@ -52,6 +69,7 @@ public class MyTracksProviderUtilsImplTest extends AndroidTestCase {
setContext(context);
providerUtils = MyTracksProviderUtils.Factory.get(context);
providerUtils.deleteAllTracks();
}
public void testLocationIterator_noPoints() {
@@ -168,4 +186,888 @@ public class MyTracksProviderUtilsImplTest extends AndroidTestCase {
return lastPointId;
}
/**
* Tests the method {@link MyTracksProviderUtilsImpl#getAllTracks()}
*/
public void testGetAllTracks() {
int initialTrackNumber = providerUtils.getAllTracks().size();
long trackId = System.currentTimeMillis();
providerUtils.insertTrack(getTrack(trackId, 0));
List<Track> allTracks = providerUtils.getAllTracks();
assertEquals(initialTrackNumber + 1, allTracks.size());
assertEquals(trackId, allTracks.get(allTracks.size() - 1).getId());
}
/**
* Tests the method {@link MyTracksProviderUtilsImpl#getTrack(long)}
*/
public void testGetTrack() {
long trackId = System.currentTimeMillis();
providerUtils.insertTrack(getTrack(trackId, 0));
assertNotNull(providerUtils.getTrack(trackId));
}
/**
* Tests the method {@link MyTracksProviderUtilsImpl#getLastTrack()}
*/
public void testGetLastTrack() {
long trackId = System.currentTimeMillis();
providerUtils.insertTrack(getTrack(trackId, 0));
assertEquals(trackId, providerUtils.getLastTrack().getId());
}
/**
* Tests the method {@link MyTracksProviderUtilsImpl#getLastTrackId()}
*/
public void testGetLastTrackId() {
long trackId = System.currentTimeMillis();
providerUtils.insertTrack(getTrack(trackId, 0));
assertEquals(trackId, providerUtils.getLastTrackId());
}
/**
* Tests the method {@link MyTracksProviderUtilsImpl#trackExists(long)}
*/
public void testTrackExists() {
long trackId = System.currentTimeMillis();
providerUtils.insertTrack(getTrack(trackId, 0));
assertTrue(providerUtils.trackExists(trackId));
}
/**
* Tests the method {@link MyTracksProviderUtilsImpl#updateTrack(Track)}
*/
public void testUpdateTrack() {
long trackId = System.currentTimeMillis();
Track track = getTrack(trackId, 0);
String nameOld = "name1";
String nameNew = "name2";
track.setName(nameOld);
providerUtils.insertTrack(track);
assertEquals(nameOld, providerUtils.getTrack(trackId).getName());
track.setName(nameNew);
providerUtils.updateTrack(track);
assertEquals(nameNew, providerUtils.getTrack(trackId).getName());
}
/**
* Tests the method {@link MyTracksProviderUtilsImpl#deleteAllTracks()}
*/
public void testDeleteAllTracks() {
// Insert track, points and waypoint at first.
long trackId = System.currentTimeMillis();
Track track = getTrack(trackId, 10);
insertTrackWithLocations(track);
Waypoint waypoint = new Waypoint();
providerUtils.insertWaypoint(waypoint);
ContentResolver contentResolver = context.getContentResolver();
Cursor tracksCursor = contentResolver.query(TracksColumns.CONTENT_URI, null, null, null,
TracksColumns._ID);
assertEquals(1, tracksCursor.getCount());
Cursor tracksPointsCursor = contentResolver.query(TrackPointsColumns.CONTENT_URI, null, null,
null, TrackPointsColumns._ID);
assertEquals(10, tracksPointsCursor.getCount());
Cursor waypointCursor = contentResolver.query(WaypointsColumns.CONTENT_URI, null, null,
null, WaypointsColumns._ID);
assertEquals(1, waypointCursor.getCount());
// Delete all.
providerUtils.deleteAllTracks();
// Check whether all have been deleted.
tracksCursor = contentResolver.query(TracksColumns.CONTENT_URI, null, null, null,
TracksColumns._ID);
assertEquals(0, tracksCursor.getCount());
tracksPointsCursor = contentResolver.query(TrackPointsColumns.CONTENT_URI, null, null,
null, TrackPointsColumns._ID);
assertEquals(0, tracksPointsCursor.getCount());
waypointCursor = contentResolver.query(WaypointsColumns.CONTENT_URI, null, null,
null, WaypointsColumns._ID);
assertEquals(0, waypointCursor.getCount());
}
/**
* Tests the method {@link MyTracksProviderUtilsImpl#deleteTrack(long)}.
*/
public void testDeleteTrack() {
// Insert three tracks, points of two tracks and way point of one track.
long trackId = System.currentTimeMillis();
Track track = getTrack(trackId, 10);
providerUtils.insertTrack(track);
insertTrackWithLocations(getTrack(trackId + 1, 10));
insertTrackWithLocations(getTrack(trackId + 2, 10));
Waypoint waypoint = new Waypoint();
waypoint.setTrackId(trackId);
providerUtils.insertWaypoint(waypoint);
ContentResolver contentResolver = context.getContentResolver();
Cursor tracksCursor = contentResolver.query(TracksColumns.CONTENT_URI, null, null, null,
TracksColumns._ID);
assertEquals(3, tracksCursor.getCount());
Cursor tracksPointsCursor = contentResolver.query(TrackPointsColumns.CONTENT_URI, null, null,
null, TrackPointsColumns._ID);
assertEquals(20, tracksPointsCursor.getCount());
Cursor waypointCursor = contentResolver.query(WaypointsColumns.CONTENT_URI, null, null,
null, WaypointsColumns._ID);
assertEquals(1, waypointCursor.getCount());
// Delete one track.
providerUtils.deleteTrack(trackId);
// Check whether all data of a track has been deleted.
tracksCursor = contentResolver.query(TracksColumns.CONTENT_URI, null, null, null,
TracksColumns._ID);
assertEquals(2, tracksCursor.getCount());
tracksPointsCursor = contentResolver.query(TrackPointsColumns.CONTENT_URI, null, null,
null, TrackPointsColumns._ID);
assertEquals(20, tracksPointsCursor.getCount());
waypointCursor = contentResolver.query(WaypointsColumns.CONTENT_URI, null, null,
null, WaypointsColumns._ID);
assertEquals(0, waypointCursor.getCount());
}
/**
* Tests the method {@link MyTracksProviderUtilsImpl#createTrack(Cursor)}.
*/
@UsesMocks(Cursor.class)
public void testCreateTrack() {
Cursor cursorMock = AndroidMock.createNiceMock(Cursor.class);
int startColumnIndex = 1;
int columnIndex = startColumnIndex;
AndroidMock.expect(cursorMock.getColumnIndexOrThrow(TracksColumns._ID))
.andReturn(columnIndex++);
AndroidMock.expect(cursorMock.getColumnIndexOrThrow(TracksColumns.NAME)).andReturn(
columnIndex++);
columnIndex = startColumnIndex;
// Id
AndroidMock.expect(cursorMock.isNull(columnIndex++)).andReturn(false);
// Name
AndroidMock.expect(cursorMock.isNull(columnIndex++)).andReturn(false);
long trackId = System.currentTimeMillis();
columnIndex = startColumnIndex;
// Id
AndroidMock.expect(cursorMock.getLong(columnIndex++)).andReturn(trackId);
// Name
String name = NAME_PREFIX + Long.toString(trackId);
AndroidMock.expect(cursorMock.getString(columnIndex++)).andReturn(name);
AndroidMock.replay(cursorMock);
Track track = providerUtils.createTrack(cursorMock);
assertEquals(trackId, track.getId());
assertEquals(name, track.getName());
AndroidMock.verify(cursorMock);
}
/**
* Tests the method {@link MyTracksProviderUtilsImpl#createContentValues(Track)}.
*/
@UsesMocks(TripStatistics.class)
public void testCreateContentValues_track() {
// ID
long trackId = System.currentTimeMillis();
// Name
String name = NAME_PREFIX + Long.toString(trackId);
Track track = getTrack(trackId, 10);
track.setName(name);
track.setCategory(TRACK_CATEGORY);
TripStatistics tripStatistics = AndroidMock.createNiceMock(TripStatistics.class);
// Bottom
int bottom = 22;
// AverageSpeed
double averageSpeed = 1.11;
AndroidMock.expect(tripStatistics.getBottom()).andReturn(bottom);
AndroidMock.expect(tripStatistics.getAverageSpeed()).andReturn(averageSpeed);
track.setTripStatistics(tripStatistics);
AndroidMock.replay(tripStatistics);
ContentValues contentValues = providerUtils.createContentValues(track);
assertEquals(trackId, contentValues.get(TracksColumns._ID));
assertEquals(name, contentValues.get(TracksColumns.NAME));
assertEquals(bottom, contentValues.get(TracksColumns.MINLAT));
assertEquals(averageSpeed, contentValues.get(TracksColumns.AVGSPEED));
AndroidMock.verify(tripStatistics);
}
/**
* Tests the method {@link MyTracksProviderUtilsImpl#getFirstWaypoint(long)}.
*/
public void testGetFirstWaypoint() {
long trackId = System.currentTimeMillis();
Track track = getTrack(trackId, 10);
providerUtils.insertTrack(track);
Waypoint waypoint1 = new Waypoint();
waypoint1.setDescription("Desc1");
waypoint1.setTrackId(trackId);
Waypoint waypoint2 = new Waypoint();
waypoint2.setDescription("Desc2");
waypoint2.setTrackId(trackId);
providerUtils.insertWaypoint(waypoint1);
providerUtils.insertWaypoint(waypoint2);
assertNull(providerUtils.getFirstWaypoint(-1));
Waypoint wayPoint = providerUtils.getFirstWaypoint(trackId);
assertEquals("Desc1", wayPoint.getDescription());
}
/**
* Tests the method {@link MyTracksProviderUtilsImpl#getFirstWaypointId(long)}.
*/
public void testGetFirstWaypointId() {
long trackId = System.currentTimeMillis();
Track track = getTrack(trackId, 10);
providerUtils.insertTrack(track);
Waypoint waypoint1 = new Waypoint();
waypoint1.setTrackId(trackId);
Waypoint waypoint2 = new Waypoint();
waypoint2.setTrackId(trackId);
providerUtils.insertWaypoint(waypoint1);
providerUtils.insertWaypoint(waypoint2);
assertEquals(-1L, providerUtils.getFirstWaypointId(-1));
assertEquals(1L, providerUtils.getFirstWaypointId(trackId));
}
/**
* Tests the method {@link MyTracksProviderUtilsImpl#getLastWaypointId(long)}.
*/
public void testGetLastWaypointId() {
long trackId = System.currentTimeMillis();
Track track = getTrack(trackId, 10);
providerUtils.insertTrack(track);
Waypoint waypoint1 = new Waypoint();
waypoint1.setTrackId(trackId);
Waypoint waypoint2 = new Waypoint();
waypoint2.setTrackId(trackId);
Waypoint waypoint3 = new Waypoint();
waypoint3.setTrackId(trackId);
providerUtils.insertWaypoint(waypoint1);
providerUtils.insertWaypoint(waypoint2);
providerUtils.insertWaypoint(waypoint3);
assertEquals(-1L, providerUtils.getLastWaypointId(-1));
assertEquals(3L, providerUtils.getLastWaypointId(trackId));
}
/**
* Tests the method
* {@link MyTracksProviderUtils#getLastStatisticsWaypoint(long)}.
*/
public void testGetLastStatisticsWaypoint() {
long trackId = System.currentTimeMillis();
Track track = getTrack(trackId, 10);
providerUtils.insertTrack(track);
Waypoint waypoint1 = new Waypoint();
waypoint1.setTrackId(trackId);
waypoint1.setType(Waypoint.TYPE_STATISTICS);
waypoint1.setDescription("Desc1");
Waypoint waypoint2 = new Waypoint();
waypoint2.setTrackId(trackId);
waypoint2.setType(Waypoint.TYPE_STATISTICS);
waypoint2.setDescription("Desc2");
Waypoint waypoint3 = new Waypoint();
waypoint3.setTrackId(trackId);
waypoint3.setType(Waypoint.TYPE_WAYPOINT);
waypoint3.setDescription("Desc3");
providerUtils.insertWaypoint(waypoint1);
providerUtils.insertWaypoint(waypoint2);
providerUtils.insertWaypoint(waypoint3);
assertEquals("Desc2", providerUtils.getLastStatisticsWaypoint(trackId).getDescription());
}
/**
* Tests the method {@link MyTracksProviderUtilsImpl#getNextMarkerNumber(long, boolean)}.
*/
public void testGetNextMarkerNumber() {
long trackId = System.currentTimeMillis();
Track track = getTrack(trackId, 10);
providerUtils.insertTrack(track);
Waypoint waypoint1 = new Waypoint();
waypoint1.setType(Waypoint.TYPE_STATISTICS);
waypoint1.setTrackId(trackId);
Waypoint waypoint2 = new Waypoint();
waypoint2.setType(Waypoint.TYPE_WAYPOINT);
waypoint2.setTrackId(trackId);
Waypoint waypoint3 = new Waypoint();
waypoint3.setType(Waypoint.TYPE_STATISTICS);
waypoint3.setTrackId(trackId);
Waypoint waypoint4 = new Waypoint();
waypoint4.setType(Waypoint.TYPE_WAYPOINT);
waypoint4.setTrackId(trackId);
providerUtils.insertWaypoint(waypoint1);
providerUtils.insertWaypoint(waypoint2);
providerUtils.insertWaypoint(waypoint3);
providerUtils.insertWaypoint(waypoint4);
assertEquals(2, providerUtils.getNextMarkerNumber(trackId, true));
assertEquals(3, providerUtils.getNextMarkerNumber(trackId, false));
}
/**
* Tests the method {@link MyTracksProviderUtilsImpl#getNextStatisticsWaypointAfter(Waypoint)}.
*/
public void testGetNextStatisticsWaypointAfter() {
long trackId = System.currentTimeMillis();
Track track = getTrack(trackId, 10);
providerUtils.insertTrack(track);
Waypoint waypoint1 = new Waypoint();
waypoint1.setType(Waypoint.TYPE_STATISTICS);
waypoint1.setTrackId(trackId);
Waypoint waypoint2 = new Waypoint();
waypoint2.setType(Waypoint.TYPE_WAYPOINT);
waypoint2.setTrackId(trackId);
Waypoint waypoint3 = new Waypoint();
waypoint3.setType(Waypoint.TYPE_STATISTICS);
waypoint3.setTrackId(trackId);
waypoint3.setDescription("Desc3");
Waypoint waypoint4 = new Waypoint();
waypoint4.setType(Waypoint.TYPE_STATISTICS);
waypoint4.setTrackId(trackId);
waypoint4.setDescription("Desc4");
providerUtils.insertWaypoint(waypoint1);
providerUtils.insertWaypoint(waypoint2);
providerUtils.insertWaypoint(waypoint3);
providerUtils.insertWaypoint(waypoint4);
assertEquals("Desc3", providerUtils.getNextStatisticsWaypointAfter(providerUtils.getFirstWaypoint(trackId)).getDescription());
}
/**
* Tests the method {@link MyTracksProviderUtilsImpl#insertWaypoint(Waypoint)} and
* {@link MyTracksProviderUtilsImpl#getWaypoint(long)}.
*/
public void testInsertAndGetWaypoint() {
long trackId = System.currentTimeMillis();
Track track = getTrack(trackId, 10);
providerUtils.insertTrack(track);
Waypoint waypoint = new Waypoint();
waypoint.setDescription(TEST_DESC);
waypoint.setTrackId(trackId);
providerUtils.insertWaypoint(waypoint);
assertEquals(TEST_DESC, providerUtils.getWaypoint(1).getDescription());
}
/**
* Tests the method {@link MyTracksProviderUtilsImpl#updateWaypoint(Waypoint)}.
*/
public void testUpdateWaypoint() {
long trackId = System.currentTimeMillis();
Track track = getTrack(trackId, 10);
providerUtils.insertTrack(track);
// Insert at first.
Waypoint waypoint = new Waypoint();
waypoint.setDescription(TEST_DESC);
waypoint.setTrackId(trackId);
providerUtils.insertWaypoint(waypoint);
// Update
waypoint = providerUtils.getWaypoint(1);
waypoint.setDescription(TEST_DESC_NEW);
providerUtils.updateWaypoint(waypoint);
assertEquals(TEST_DESC_NEW, providerUtils.getWaypoint(1).getDescription());
}
/**
* Tests the method
* {@link MyTracksProviderUtilsImpl#deleteWaypoint(long, DescriptionGenerator)}
* when there is only one waypoint in the track.
*/
public void testDeleteWaypoint_onlyOneWayPoint() {
long trackId = System.currentTimeMillis();
Track track = getTrack(trackId, 10);
providerUtils.insertTrack(track);
// Insert at first.
Waypoint waypoint1 = new Waypoint();
waypoint1.setDescription(TEST_DESC);
waypoint1.setTrackId(trackId);
waypoint1.setType(Waypoint.TYPE_STATISTICS);
providerUtils.insertWaypoint(waypoint1);
// Delete
DescriptionGenerator descriptionGenerator = new DescriptionGenerator() {
@Override
public String generateWaypointDescription(TripStatistics tripStatistics) {
return MyTracksProviderUtilsImplTest.MOCK_DESC;
}
@SuppressWarnings("hiding")
@Override
public String generateTrackDescription(Track track, Vector<Double> distances,
Vector<Double> elevations, boolean html) {
return null;
}
};
providerUtils.deleteWaypoint(1, descriptionGenerator);
assertNull(providerUtils.getWaypoint(1));
}
/**
* Tests the method
* {@link MyTracksProviderUtilsImpl#deleteWaypoint(long, DescriptionGenerator)}
* when there is more than one waypoint in the track.
*/
public void testDeleteWaypoint_hasNextWayPoint() {
long trackId = System.currentTimeMillis();
Track track = getTrack(trackId, 10);
providerUtils.insertTrack(track);
TripStatistics statistics = new TripStatistics();
statistics.setStartTime(1000L);
statistics.setStopTime(2500L);
statistics.setTotalTime(1500L);
statistics.setMovingTime(700L);
statistics.setTotalDistance(750.0);
statistics.setTotalElevationGain(50.0);
statistics.setMaxSpeed(60.0);
statistics.setMaxElevation(1250.0);
statistics.setMinElevation(1200.0);
statistics.setMaxGrade(15.0);
statistics.setMinGrade(-25.0);
statistics.setBounds(-10000, 20000, 30000, -40000);
// Insert at first.
Waypoint waypoint1 = new Waypoint();
waypoint1.setDescription(Long.toString(trackId));
waypoint1.setTrackId(trackId);
waypoint1.setType(Waypoint.TYPE_STATISTICS);
waypoint1.setTripStatistics(statistics);
providerUtils.insertWaypoint(waypoint1);
Waypoint waypoint2 = new Waypoint();
waypoint2.setDescription(Long.toString(trackId));
waypoint2.setTrackId(trackId);
waypoint2.setType(Waypoint.TYPE_STATISTICS);
waypoint2.setTripStatistics(statistics);
providerUtils.insertWaypoint(waypoint2);
// Delete
DescriptionGenerator descriptionGenerator = new DescriptionGenerator() {
@Override
public String generateWaypointDescription(TripStatistics tripStatistics) {
return MyTracksProviderUtilsImplTest.MOCK_DESC;
}
@SuppressWarnings("hiding")
@Override
public String generateTrackDescription(Track track, Vector<Double> distances,
Vector<Double> elevations, boolean html) {
return null;
}
};
providerUtils.deleteWaypoint(1, descriptionGenerator);
assertNull(providerUtils.getWaypoint(1));
assertEquals(MyTracksProviderUtilsImplTest.MOCK_DESC, providerUtils.getWaypoint(2)
.getDescription());
}
/**
* Tests the method {@link MyTracksProviderUtilsImpl#createWaypoint(Cursor)}.
*/
@UsesMocks(Cursor.class)
public void testCreateWaypoint() {
Cursor cursorMock = AndroidMock.createNiceMock(Cursor.class);
int startColumnIndex = 1;
int columnIndex = startColumnIndex;
AndroidMock.expect(cursorMock.getColumnIndexOrThrow(WaypointsColumns._ID))
.andReturn(columnIndex++);
AndroidMock.expect(cursorMock.getColumnIndexOrThrow(WaypointsColumns.NAME)).andReturn(
columnIndex++);
AndroidMock.expect(cursorMock.getColumnIndexOrThrow(WaypointsColumns.TRACKID)).andReturn(
columnIndex++);
columnIndex = startColumnIndex;
// Id
AndroidMock.expect(cursorMock.isNull(columnIndex++)).andReturn(false);
// Name
AndroidMock.expect(cursorMock.isNull(columnIndex++)).andReturn(false);
// trackIdIndex
AndroidMock.expect(cursorMock.isNull(columnIndex++)).andReturn(false);
long id = System.currentTimeMillis();
columnIndex = startColumnIndex;
// Id
AndroidMock.expect(cursorMock.getLong(columnIndex++)).andReturn(id);
// Name
String name = NAME_PREFIX + Long.toString(id);
AndroidMock.expect(cursorMock.getString(columnIndex++)).andReturn(name);
// trackIdIndex
long trackId = 11L;
AndroidMock.expect(cursorMock.getLong(columnIndex++)).andReturn(trackId);
AndroidMock.replay(cursorMock);
Waypoint waypoint = providerUtils.createWaypoint(cursorMock);
assertEquals(id, waypoint.getId());
assertEquals(name, waypoint.getName());
assertEquals(trackId, waypoint.getTrackId());
AndroidMock.verify(cursorMock);
}
/**
* Tests the method {@link MyTracksProviderUtilsImpl#createContentValues(Waypoint)}.
*/
public void testCreateContentValues_waypoint() {
long trackId = System.currentTimeMillis();
Track track = getTrack(trackId, 10);
providerUtils.insertTrack(track);
// Bottom
long startTime = 1000L;
// AverageSpeed
double minGrade = -20.11;
TripStatistics statistics = new TripStatistics();
statistics.setStartTime(startTime);
statistics.setStopTime(2500L);
statistics.setTotalTime(1500L);
statistics.setMovingTime(700L);
statistics.setTotalDistance(750.0);
statistics.setTotalElevationGain(50.0);
statistics.setMaxSpeed(60.0);
statistics.setMaxElevation(1250.0);
statistics.setMinElevation(1200.0);
statistics.setMaxGrade(15.0);
statistics.setMinGrade(minGrade);
statistics.setBounds(-10000, 20000, 30000, -40000);
// Insert at first.
Waypoint waypoint = new Waypoint();
waypoint.setDescription(TEST_DESC);
waypoint.setType(Waypoint.TYPE_STATISTICS);
waypoint.setTripStatistics(statistics);
Location loc = new Location("test");
loc.setLatitude(22);
loc.setLongitude(22);
loc.setAccuracy((float) 1 / 100.0f);
loc.setAltitude(2.5);
waypoint.setLocation(loc);
providerUtils.insertWaypoint(waypoint);
MyTracksProviderUtilsImpl myTracksProviderUtilsImpl = new MyTracksProviderUtilsImpl(
new MockContentResolver());
long waypointId = System.currentTimeMillis();
waypoint.setId(waypointId);
ContentValues contentValues = myTracksProviderUtilsImpl.createContentValues(waypoint);
assertEquals(waypointId, contentValues.get(WaypointsColumns._ID));
assertEquals(22 * 1000000, contentValues.get(WaypointsColumns.LONGITUDE));
assertEquals(TEST_DESC, contentValues.get(WaypointsColumns.DESCRIPTION));
assertEquals(startTime, contentValues.get(WaypointsColumns.STARTTIME));
assertEquals(minGrade, contentValues.get(WaypointsColumns.MINGRADE));
}
/**
* Tests the method {@link MyTracksProviderUtilsImpl#getFirstLocation()}.
*/
public void testGetFirstLocation() {
// Insert track, points at first.
long trackId = System.currentTimeMillis();
Track track = getTrack(trackId, 10);
insertTrackWithLocations(track);
Location firstLocation = providerUtils.getFirstLocation();
checkLocation(0, firstLocation);
}
/**
* Tests the method {@link MyTracksProviderUtilsImpl#getLastLocation()}.
*/
public void testGetLastLocation() {
// Insert track, points at first.
long trackId = System.currentTimeMillis();
Track track = getTrack(trackId, 10);
insertTrackWithLocations(track);
Location lastLocation = providerUtils.getLastLocation();
checkLocation(9, lastLocation);
}
/**
* Tests the method {@link MyTracksProviderUtilsImpl#getLocation(long)}.
*/
public void testGetLocation() {
// Insert track, points at first.
long trackId = System.currentTimeMillis();
Track track = getTrack(trackId, 10);
insertTrackWithLocations(track);
Location location1 = providerUtils.getLocation(1L);
checkLocation(0, location1);
Location location5 = providerUtils.getLocation(5L);
checkLocation(4, location5);
Location location10 = providerUtils.getLocation(10L);
checkLocation(9, location10);
}
/**
* Tests the method
* {@link MyTracksProviderUtilsImpl#getLocationsCursor(long, long, int, boolean)}
* in descending.
*/
public void testGetLocationCursor_desc() {
// Insert track, points at first.
long trackId = System.currentTimeMillis();
Track track = getTrack(trackId, 10);
insertTrackWithLocations(track);
Cursor cursor = providerUtils.getLocationsCursor(trackId, 2L, 5, true);
assertEquals(2, cursor.getCount());
}
/**
* Tests the method
* {@link MyTracksProviderUtilsImpl#getLocationsCursor(long, long, int, boolean)}
* in ascending.
*/
public void testGetLocationCursor_asc() {
// Insert track, points at first.
long trackId = System.currentTimeMillis();
Track track = getTrack(trackId, 10);
insertTrackWithLocations(track);
Cursor cursor = providerUtils.getLocationsCursor(trackId, 2L, 5, false);
assertEquals(5, cursor.getCount());
}
/**
* Tests the method
* {@link MyTracksProviderUtilsImpl#getLocationIterator(long, long, boolean, LocationFactory)}
* in descending.
*/
public void testGeLocationIterator_desc() {
// Insert track, points at first.
long trackId = System.currentTimeMillis();
Track track = getTrack(trackId, 10);
insertTrackWithLocations(track);
long startTrackPointId = 2L;
LocationIterator locationIterator = providerUtils.getLocationIterator(trackId,
startTrackPointId, true, MyTracksProviderUtils.DEFAULT_LOCATION_FACTORY);
for (int i = 1; i >= 0; i--) {
assertTrue(locationIterator.hasNext());
Location location = locationIterator.next();
assertEquals(2 + (i - 1), locationIterator.getLocationId());
checkLocation(i, location);
}
assertFalse(locationIterator.hasNext());
}
/**
* Tests the method
* {@link MyTracksProviderUtilsImpl#getLocationIterator(long, long, boolean, LocationFactory)}
* in ascending.
*/
public void testGeLocationIterator_asc() {
// Insert track, point at first.
long trackId = System.currentTimeMillis();
Track track = getTrack(trackId, 10);
insertTrackWithLocations(track);
long startTrackPointId = 2L;
LocationIterator locationIterator = providerUtils.getLocationIterator(trackId,
startTrackPointId, false, MyTracksProviderUtils.DEFAULT_LOCATION_FACTORY);
for (int i = 1; i < 10; i++) {
assertTrue(locationIterator.hasNext());
Location location = locationIterator.next();
assertEquals(2 + (i - 1), locationIterator.getLocationId());
checkLocation(i, location);
}
assertFalse(locationIterator.hasNext());
}
/**
* Tests the method {@link MyTracksProviderUtilsImpl#getLastTrackLocationId(long)}.
*/
public void testGetLastTrackLocationId() {
// Insert track, point at first.
long trackId = System.currentTimeMillis();
Track track = getTrack(trackId, 10);
insertTrackWithLocations(track);
assertEquals(10, providerUtils.getLastTrackLocationId(trackId));
}
/**
* Tests the method {@link MyTracksProviderUtilsImpl#getLastTrackLocation(long)}.
*/
public void testGetLastTrackLocation() {
// Insert track, point at first.
long trackId = System.currentTimeMillis();
Track track = getTrack(trackId, 10);
insertTrackWithLocations(track);
checkLocation(9, providerUtils.getLastTrackLocation(trackId));
}
/**
* Tests the method
* {@link MyTracksProviderUtilsImpl#insertTrackPoint(Location, long)}. This
* test also covers the method
* {@link MyTracksProviderUtilsImpl#createContentValues(Location, long)}.
*/
@SuppressWarnings("javadoc")
public void testInsertTrackPoint() {
// Insert track, point at first.
long trackId = System.currentTimeMillis();
Track track = getTrack(trackId, 10);
insertTrackWithLocations(track);
providerUtils.insertTrackPoint(createLocation(22), trackId);
assertEquals(11, providerUtils.getLocationsCursor(trackId, 0, 1000, false).getCount());
}
/**
* Tests the method
* {@link MyTracksProviderUtilsImpl#bulkInsertTrackPoints(Location[], int, long)}
* . This test also covers the method
* {@link MyTracksProviderUtilsImpl#createContentValues(Location, long)} and
* the inner class {@link MyTracksProviderUtilsImpl.CachedTrackPointsIndexes}.
*/
@SuppressWarnings("javadoc")
public void testBulkInsertTrackPoints() {
// Insert track, point at first.
long trackId = System.currentTimeMillis();
Track track = getTrack(trackId, 10);
insertTrackWithLocations(track);
providerUtils.bulkInsertTrackPoints(track.getLocations().toArray(new Location[0]), -1, trackId);
assertEquals(20, providerUtils.getLocationsCursor(trackId, 0, 1000, false).getCount());
providerUtils.bulkInsertTrackPoints(track.getLocations().toArray(new Location[0]), 8, trackId);
assertEquals(28, providerUtils.getLocationsCursor(trackId, 0, 1000, false).getCount());
}
/**
* Tests the method {@link MyTracksProviderUtilsImpl#createLocation(Cursor)}.
* This test also covers the method
* {@link MyTracksProviderUtilsImpl#fillLocation(Cursor, Location)} and
* {@link MyTracksProviderUtilsImpl#fillLocation(Cursor, MyTracksProviderUtilsImpl.CachedTrackPointsIndexes, Location)}
* and the inner class
* {@link MyTracksProviderUtilsImpl.CachedTrackPointsIndexes}.
*/
@SuppressWarnings("javadoc")
@UsesMocks(Cursor.class)
public void testCreateLocation() {
Cursor cursorMock = AndroidMock.createNiceMock(Cursor.class);
// Set index.
int index = 1;
// Id
AndroidMock.expect(cursorMock.getColumnIndex(TrackPointsColumns._ID)).andReturn(index++);
// Longitude
AndroidMock.expect(cursorMock.getColumnIndexOrThrow(TrackPointsColumns.LONGITUDE)).andReturn(
index++);
// Latitude
AndroidMock.expect(cursorMock.getColumnIndexOrThrow(TrackPointsColumns.LATITUDE)).andReturn(
index++);
// Time
AndroidMock.expect(cursorMock.getColumnIndexOrThrow(TrackPointsColumns.TIME))
.andReturn(index++);
// Speed
AndroidMock.expect(cursorMock.getColumnIndexOrThrow(TrackPointsColumns.SPEED)).andReturn(
index++);
// Sensor
AndroidMock.expect(cursorMock.getColumnIndexOrThrow(TrackPointsColumns.SENSOR)).andReturn(
index++);
// Set return value of isNull().
index = 2;
// Longitude
AndroidMock.expect(cursorMock.isNull(index++)).andReturn(false);
// Latitude
AndroidMock.expect(cursorMock.isNull(index++)).andReturn(false);
// Time
AndroidMock.expect(cursorMock.isNull(index++)).andReturn(false);
// Speed
AndroidMock.expect(cursorMock.isNull(index++)).andReturn(false);
// Sensor
AndroidMock.expect(cursorMock.isNull(index++)).andReturn(false);
// Set return value of isNull().
index = 2;
// Longitude
int longitude = 11;
AndroidMock.expect(cursorMock.getInt(index++)).andReturn(longitude * 1000000);
// Latitude.
int latitude = 22;
AndroidMock.expect(cursorMock.getInt(index++)).andReturn(latitude * 1000000);
// Time
long time = System.currentTimeMillis();
AndroidMock.expect(cursorMock.getLong(index++)).andReturn(time);
// Speed
float speed = 2.2f;
AndroidMock.expect(cursorMock.getFloat(index++)).andReturn(speed);
// Sensor
byte[] sensor = "Sensor state".getBytes();
AndroidMock.expect(cursorMock.getBlob(index++)).andReturn(sensor);
AndroidMock.replay(cursorMock);
Location location = providerUtils.createLocation(cursorMock);
assertEquals((double) longitude, location.getLongitude());
assertEquals((double) latitude, location.getLatitude());
assertEquals(time, location.getTime());
assertEquals(speed, location.getSpeed());
AndroidMock.verify(cursorMock);
}
/**
* Simulates a track which is used for testing.
*
* @param id the id of the track
* @param numPoints the location number in the track
* @return the simulated track
*/
private Track getTrack(long id,int numPoints) {
Track track = new Track();
track.setId(id);
track.setName("Test: " + id);
track.setNumberOfPoints(numPoints);
for(int i = 0; i < numPoints; i++) {
track.addLocation(createLocation(i));
}
return track;
}
/**
* Creates a location.
* @param i the index to set the value of location.
* @return created location
*/
private Location createLocation(int i) {
Location loc = new Location("test");
loc.setLatitude(INITIAL_LATITUDE + (double) i / 10000.0);
loc.setLongitude(INITIAL_LONGITUDE - (double) i / 10000.0);
loc.setAccuracy((float) i / 100.0f);
loc.setAltitude(i * ALTITUDE_INTERVAL);
return loc;
}
/**
* Checks the value of a location.
*
* @param i the index of this location which created in the method
* {@link MyTracksProviderUtilsImplTest#getTrack(long, int)}
* @param location the location to be checked
*/
private void checkLocation(int i, Location location) {
assertEquals(INITIAL_LATITUDE + (double) i / 10000.0, location.getLatitude());
assertEquals(INITIAL_LONGITUDE - (double) i / 10000.0, location.getLongitude());
assertEquals((float) i / 100.0f, location.getAccuracy());
assertEquals(i * ALTITUDE_INTERVAL, location.getAltitude());
}
/**
* Inserts a track with locations into the database.
*
* @param track track to be inserted
*/
private void insertTrackWithLocations(Track track) {
providerUtils.insertTrack(track);
providerUtils.bulkInsertTrackPoints(track.getLocations().toArray(new Location[0]), track
.getLocations().size(), track.getId());
}
}
File diff suppressed because it is too large Load Diff
@@ -23,7 +23,6 @@ import android.app.Instrumentation;
import android.test.ActivityInstrumentationTestCase2;
import android.view.KeyEvent;
import android.widget.CheckBox;
import android.widget.EditText;
import java.util.ArrayList;
@@ -104,6 +103,8 @@ public class CreateAndSendTrackTest extends ActivityInstrumentationTestCase2<Tra
if (checkBoxs.size() < 3) {
EndToEndTestUtils.SOLO.scrollDown();
checkBoxs = EndToEndTestUtils.SOLO.getCurrentCheckBoxes();
// Choose all Google service.
for (int i = 0; i < checkBoxs.size(); i++) {
if (!checkBoxs.get(i).isChecked()) {
EndToEndTestUtils.SOLO.clickOnCheckBox(i);
@@ -111,26 +112,41 @@ public class CreateAndSendTrackTest extends ActivityInstrumentationTestCase2<Tra
}
}
instrumentation.waitForIdleSync();
EndToEndTestUtils.SOLO.clickOnText(activityMyTracks.getString(R.string.send_google_send_now));
EndToEndTestUtils.getButtonOnScreen(activityMyTracks.getString(R.string.send_google_send_now),
true, true);
// If no account is binded with this device.
if (EndToEndTestUtils.SOLO.waitForText(activityMyTracks
.getString(R.string.send_google_no_account_title), 1, 10000)) {
EndToEndTestUtils.getButtonOnScreen(activityMyTracks.getString(R.string.generic_ok), true, true);
} else {
if (EndToEndTestUtils.SOLO.waitForText(
activityMyTracks.getString(R.string.send_google_no_account_title), 1,
EndToEndTestUtils.SHORT_WAIT_TIME)) {
EndToEndTestUtils.getButtonOnScreen(activityMyTracks.getString(R.string.generic_ok), true,
true);
} else if (EndToEndTestUtils.SOLO.waitForText(
activityMyTracks.getString(R.string.send_google_no_account_permission), 1,
EndToEndTestUtils.SHORT_WAIT_TIME)) {} else {
assertTrue(EndToEndTestUtils.SOLO.waitForText(activityMyTracks
.getString(R.string.generic_progress_title)));
// Waiting the send is finish.
while (EndToEndTestUtils.SOLO.waitForText(activityMyTracks
.getString(R.string.generic_progress_title), 1, 500)) {
}
// For we not sure the send will be successful, just check whether the result dialog is display.
while (EndToEndTestUtils.SOLO.waitForText(
activityMyTracks.getString(R.string.generic_progress_title), 1,
EndToEndTestUtils.SHORT_WAIT_TIME)) {}
// Check whether the result dialog is display.
assertTrue(EndToEndTestUtils.SOLO.waitForText(activityMyTracks
.getString(R.string.share_track_share_url)));
EndToEndTestUtils.getButtonOnScreen(activityMyTracks.getString(R.string.generic_ok), true, true);
EndToEndTestUtils.getButtonOnScreen(activityMyTracks.getString(R.string.generic_ok), true,
true);
// Check whether all data is correct on Google Map, Documents, and
// Spreadsheet.
assertTrue(GoogleUtils.deleteMap(EndToEndTestUtils.trackName, activityMyTracks));
assertTrue(GoogleUtils.searchFusionTableByTitle(EndToEndTestUtils.TRACK_NAME_PREFIX,
activityMyTracks));
assertTrue(GoogleUtils
.deleteTrackInSpreadSheet(EndToEndTestUtils.trackName, activityMyTracks));
assertTrue(GoogleUtils.dropFusionTables(EndToEndTestUtils.trackName, activityMyTracks));
}
}
/**
@@ -142,25 +158,17 @@ public class CreateAndSendTrackTest extends ActivityInstrumentationTestCase2<Tra
EndToEndTestUtils.findMenuItem(activityMyTracks.getString(R.string.menu_edit), true);
String newTrackName = EndToEndTestUtils.TRACK_NAME_PREFIX + "_new" + System.currentTimeMillis();
String newType = "type" + newTrackName;
String newType = EndToEndTestUtils.DEFAULTACTIVITY;
String newDesc = "desc" + newTrackName;
instrumentation.waitForIdleSync();
EndToEndTestUtils.rotateAllActivities();
EndToEndTestUtils.SOLO.waitForText(activityMyTracks.getString(R.string.generic_save));
sendKeys(KeyEvent.KEYCODE_DEL);
ArrayList<EditText> editTexts = EndToEndTestUtils.SOLO.getCurrentEditTexts();
EndToEndTestUtils.SOLO.enterText(editTexts.get(0), newTrackName);
EndToEndTestUtils.SOLO.enterText(editTexts.get(1), newType);
// In landscape, there are only two visible edit texts.
if (editTexts.size() > 2) {
EndToEndTestUtils.SOLO.enterText(editTexts.get(2), newDesc);
} else {
EndToEndTestUtils.SOLO.scrollDown();
editTexts = EndToEndTestUtils.SOLO.getCurrentEditTexts();
EndToEndTestUtils.SOLO.enterText(editTexts.get(editTexts.size() - 1), newDesc);
}
EndToEndTestUtils.enterTextAvoidSoftKeyBoard(0, newTrackName);
EndToEndTestUtils.enterTextAvoidSoftKeyBoard(1, newType);
EndToEndTestUtils.enterTextAvoidSoftKeyBoard(2, newDesc);
EndToEndTestUtils.SOLO.clickOnButton(activityMyTracks.getString(R.string.generic_save));
instrumentation.waitForIdleSync();
// Go back to track list.
@@ -169,6 +177,23 @@ public class CreateAndSendTrackTest extends ActivityInstrumentationTestCase2<Tra
assertTrue(EndToEndTestUtils.SOLO.searchText(newTrackName));
assertTrue(EndToEndTestUtils.SOLO.searchText(newDesc));
}
/**
* Checks the voice frequency and split frequency menus.
*/
public void testFrequencyMenu() {
EndToEndTestUtils.startRecording();
assertTrue(EndToEndTestUtils.findMenuItem(
activityMyTracks.getString(R.string.menu_voice_frequency), false));
assertTrue(EndToEndTestUtils.findMenuItem(
activityMyTracks.getString(R.string.menu_split_frequency), false));
EndToEndTestUtils.stopRecording(true);
assertFalse(EndToEndTestUtils.findMenuItem(
activityMyTracks.getString(R.string.menu_voice_frequency), false));
assertFalse(EndToEndTestUtils.findMenuItem(
activityMyTracks.getString(R.string.menu_split_frequency), false));
}
/**
* Creates one track with a two locations, a way point and a statistics point.
@@ -183,6 +208,7 @@ public class CreateAndSendTrackTest extends ActivityInstrumentationTestCase2<Tra
assertTrue(EndToEndTestUtils.SOLO.searchText(activityMyTracks
.getString(R.string.icon_recording)));
}
createWaypoint();
EndToEndTestUtils.sendGps(2);
// Back to tracks list.
@@ -192,16 +218,15 @@ public class CreateAndSendTrackTest extends ActivityInstrumentationTestCase2<Tra
EndToEndTestUtils.stopRecording(false);
EndToEndTestUtils.trackName = EndToEndTestUtils.TRACK_NAME_PREFIX + System.currentTimeMillis();
EndToEndTestUtils.SOLO.enterText(0, EndToEndTestUtils.trackName);
if(!EndToEndTestUtils.isEmulator) {
// Close soft keyboard.
EndToEndTestUtils.SOLO.goBack();
}
EndToEndTestUtils.SOLO.enterText(1, EndToEndTestUtils.DEFAULTACTIVITY);
EndToEndTestUtils.SOLO.clickOnButton(activityMyTracks.getString(R.string.generic_save));
instrumentation.waitForIdleSync();
// Check the new track
assertTrue(EndToEndTestUtils.SOLO.waitForText(EndToEndTestUtils.trackName, 1, 5000, true,
false));
EndToEndTestUtils.SOLO.scrollUp();
assertTrue(EndToEndTestUtils.SOLO.waitForText(EndToEndTestUtils.trackName, 1,
EndToEndTestUtils.NORMAL_WAIT_TIME, true, false));
}
/**
@@ -211,9 +236,7 @@ public class CreateAndSendTrackTest extends ActivityInstrumentationTestCase2<Tra
*/
public void testTrackStartTime() {
// Delete all track first.
EndToEndTestUtils.findMenuItem(activityMyTracks.getString(R.string.menu_delete_all), true);
EndToEndTestUtils.getButtonOnScreen(activityMyTracks.getString(R.string.generic_ok), true, true);
EndToEndTestUtils.deleteAllTracks();
// Reset all settings.
EndToEndTestUtils.resetAllSettings(activityMyTracks, false);
@@ -223,17 +246,50 @@ public class CreateAndSendTrackTest extends ActivityInstrumentationTestCase2<Tra
instrumentation.waitForIdleSync();
EndToEndTestUtils.stopRecording(false);
instrumentation.waitForIdleSync();
EndToEndTestUtils.SOLO.clickOnText(activityMyTracks.getString(R.string.generic_save));
EndToEndTestUtils.getButtonOnScreen(activityMyTracks.getString(R.string.generic_save), true,
true);
instrumentation.waitForIdleSync();
EndToEndTestUtils.SOLO.goBack();
instrumentation.waitForIdleSync();
assertFalse(EndToEndTestUtils.SOLO.waitForText(EndToEndTestUtils.RELATIVE_STARTTIME_POSTFIX, 1, 5000));
assertFalse(EndToEndTestUtils.SOLO.searchText(EndToEndTestUtils.RELATIVE_STARTTIME_POSTFIX, 1, false, true));
// Test should show relative time for createSimpleTrack would save a track
// name that is different with the start time.
EndToEndTestUtils.createSimpleTrack(2);
EndToEndTestUtils.SOLO.goBack();
assertTrue(EndToEndTestUtils.SOLO.waitForText(EndToEndTestUtils.RELATIVE_STARTTIME_POSTFIX, 1, 5000));
assertTrue(EndToEndTestUtils.SOLO.waitForText(EndToEndTestUtils.RELATIVE_STARTTIME_POSTFIX, 1, EndToEndTestUtils.NORMAL_WAIT_TIME));
}
/**
* Tests whether the split marker is created as setting.
* @throws InterruptedException
*/
public void testSplitSetting() throws InterruptedException {
EndToEndTestUtils.startRecording();
EndToEndTestUtils.findMenuItem(activityMyTracks.getString(R.string.menu_split_frequency), true);
boolean isFoundKM = EndToEndTestUtils.SOLO.searchText(EndToEndTestUtils.KM);
if (isFoundKM) {
EndToEndTestUtils.SOLO.clickOnText(EndToEndTestUtils.KM, 0);
} else {
EndToEndTestUtils.SOLO.clickOnText(EndToEndTestUtils.MILE, 0);
}
EndToEndTestUtils
.getButtonOnScreen(activityMyTracks.getString(R.string.generic_ok), true, true);
// Send Gps to give a distance more than one kilometer or one mile.
EndToEndTestUtils.sendGps(20);
assertTrue(EndToEndTestUtils.findMenuItem(activityMyTracks.getString(R.string.menu_markers),
true));
instrumentation.waitForIdleSync();
if (EndToEndTestUtils.hasGpsSingal) {
assertTrue(EndToEndTestUtils.SOLO.getCurrentListViews().get(0).getCount() > 0);
} else {
assertTrue(EndToEndTestUtils.SOLO.getCurrentListViews().get(0).getCount() == 0);
}
EndToEndTestUtils.SOLO.goBack();
EndToEndTestUtils.stopRecording(true);
}
/**
@@ -243,15 +299,13 @@ public class CreateAndSendTrackTest extends ActivityInstrumentationTestCase2<Tra
EndToEndTestUtils.findMenuItem(activityMyTracks.getString(R.string.menu_markers), true);
EndToEndTestUtils.SOLO.waitForText(activityMyTracks.getString(R.string.marker_list_empty_message));
EndToEndTestUtils.findMenuItem(activityMyTracks.getString(R.string.menu_insert_marker), true);
// Rotate when show insert page.
EndToEndTestUtils.rotateAllActivities();
EndToEndTestUtils.SOLO.enterText(0, WAYPOINT_NAME);
if(!EndToEndTestUtils.isEmulator) {
// Close soft keyboard.
EndToEndTestUtils.SOLO.goBack();
}
EndToEndTestUtils.enterTextAvoidSoftKeyBoard(0, WAYPOINT_NAME);
EndToEndTestUtils.SOLO.clickOnButton(activityMyTracks.getString(R.string.generic_add));
assertTrue(EndToEndTestUtils.SOLO.searchText(WAYPOINT_NAME));
if (EndToEndTestUtils.hasGpsSingal) {
assertTrue(EndToEndTestUtils.SOLO.waitForText(WAYPOINT_NAME, 1, EndToEndTestUtils.LONG_WAIT_TIME, true));
} else {
assertFalse(EndToEndTestUtils.SOLO.searchText(WAYPOINT_NAME));
}
EndToEndTestUtils.SOLO.goBack();
}
@@ -62,8 +62,11 @@ public class DeleteTest extends ActivityInstrumentationTestCase2<TrackListActivi
EndToEndTestUtils.findMenuItem(activityMyTracks.getString(R.string.menu_delete_all), true);
instrumentation.waitForIdleSync();
EndToEndTestUtils.rotateAllActivities();
EndToEndTestUtils.getButtonOnScreen(activityMyTracks.getString(R.string.generic_ok), true, true);
EndToEndTestUtils
.getButtonOnScreen(activityMyTracks.getString(R.string.generic_ok), true, true);
instrumentation.waitForIdleSync();
assertTrue(EndToEndTestUtils.SOLO.waitForText(activityMyTracks
.getString(R.string.track_list_empty_message)));
// There is no track now.
trackListView = EndToEndTestUtils.SOLO.getCurrentListViews();
assertEquals(0, trackListView.get(0).getCount());
@@ -74,7 +77,8 @@ public class DeleteTest extends ActivityInstrumentationTestCase2<TrackListActivi
EndToEndTestUtils.GPX.toUpperCase()));
assertTrue(EndToEndTestUtils.SOLO.waitForText(activityMyTracks
.getString(R.string.sd_card_save_error_no_track)));
EndToEndTestUtils.getButtonOnScreen(activityMyTracks.getString(R.string.generic_ok), true, true);
EndToEndTestUtils
.getButtonOnScreen(activityMyTracks.getString(R.string.generic_ok), true, true);
}
/**
@@ -90,7 +94,7 @@ public class DeleteTest extends ActivityInstrumentationTestCase2<TrackListActivi
EndToEndTestUtils.SOLO.clickOnView(trackListView.get(0).getChildAt(0));
EndToEndTestUtils.findMenuItem(activityMyTracks.getString(R.string.menu_delete), true);
EndToEndTestUtils
.getButtonOnScreen(activityMyTracks.getString(R.string.generic_ok), true, true);
.getButtonOnScreen(activityMyTracks.getString(R.string.generic_ok), true, true);
instrumentation.waitForIdleSync();
trackListView = EndToEndTestUtils.SOLO.getCurrentListViews();
int trackNumberNew = trackListView.get(0).getCount();
@@ -0,0 +1,44 @@
/*
* 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.endtoendtest;
import android.os.Bundle;
import android.test.InstrumentationTestRunner;
import android.util.Log;
/**
* A test runner can be used to run end-to-end test.
*
* @author Youtao Liu
*/
public class EndToEndTestRunner extends InstrumentationTestRunner {
/**
* Gets the parameter port which is used to fix GPS signal to emulators.
*/
@Override
public void onCreate(Bundle arguments) {
try {
EndToEndTestUtils.emulatorPort = Integer.parseInt(arguments.getString("port"));
} catch (Exception e) {
Log.e(EndToEndTestUtils.LOG_TAG, "Unable to get port parameter, use default value." + EndToEndTestUtils.emulatorPort, e);
}
Log.d(EndToEndTestUtils.LOG_TAG, "Use port number when run test on emulator:" + EndToEndTestUtils.emulatorPort);
super.onCreate(arguments);
}
}
@@ -23,10 +23,14 @@ import com.jayway.android.robotium.solo.Solo;
import android.app.Activity;
import android.app.Instrumentation;
import android.content.Context;
import android.content.res.Configuration;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
@@ -38,6 +42,7 @@ import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;
/**
* Provides utilities to smoke test.
@@ -45,9 +50,10 @@ import java.util.HashMap;
* @author Youtao Liu
*/
public class EndToEndTestUtils {
private static final String ANDROID_LOCAL_IP = "10.0.2.2";
// usually 5554.
private static final int ANDROID_LOCAL_PORT = 5554;
public static int emulatorPort = 5558;
private static final int ORIENTATION_PORTRAIT = 1;
private static final int ORIENTATION_LANDSCAPE = 0;
@@ -57,9 +63,11 @@ public class EndToEndTestUtils {
private static final float START_LATITUDE = -1.3f;
private static final float DELTA_LONGITUDE = 0.0005f;
private static final float DELTA_LADITUDE = 0.0005f;
private static final String NO_GPS_MESSAGE_PREFIX = "GPS is not available";
private static final String MOREOPTION_CLASSNAME = "com.android.internal.view.menu.ActionMenuPresenter$OverflowMenuButton";
static final String DEFAULTACTIVITY = "TestActivity";
static final String TRACK_NAME_PREFIX = "testTrackName";
static final String GPX = "gpx";
static final String KML = "kml";
@@ -71,9 +79,46 @@ public class EndToEndTestUtils {
// Following is some check strings in English and Chinese
private static final HashMap<String, String> RELATIVE_STARTTIME_POSTFIX_MULTILINGUAL = new HashMap<String, String>();
private static final HashMap<String, String> VIEW_MODE_ENGLISH_MULTILINGUAL = new HashMap<String, String>();
private static final HashMap<String, String> VIEW_MODE_MULTILINGUAL = new HashMap<String, String>();
private static final HashMap<String, String> KM_MULTILINGUAL = new HashMap<String, String>();
private static final HashMap<String, String> MILE_MULTILINGUAL = new HashMap<String, String>();
public static String RELATIVE_STARTTIME_POSTFIX = "";
public static String VIEW_MODE = "";
public static String KM = "";
public static String MILE = "";
public static int SHORT_WAIT_TIME = 2000;
public static int NORMAL_WAIT_TIME = 8000;
public static int LONG_WAIT_TIME = 15000;
public static int SUPER_LONG_WAIT_TIME = 100000;
public static String deviceLanguage = "";
static {
RELATIVE_STARTTIME_POSTFIX_MULTILINGUAL.put("es", "mins ago");
RELATIVE_STARTTIME_POSTFIX_MULTILINGUAL.put("de", "Minuten");
RELATIVE_STARTTIME_POSTFIX_MULTILINGUAL.put("fr", "minute");
RELATIVE_STARTTIME_POSTFIX_MULTILINGUAL.put("ar", "دقيقة");
RELATIVE_STARTTIME_POSTFIX_MULTILINGUAL.put("zh", "分钟前");
VIEW_MODE_MULTILINGUAL.put("es", "mode");
VIEW_MODE_MULTILINGUAL.put("de", "modus");
VIEW_MODE_MULTILINGUAL.put("fr", "Mode");
VIEW_MODE_MULTILINGUAL.put("ar", "وضع");
VIEW_MODE_MULTILINGUAL.put("zh", "模式");
KM_MULTILINGUAL.put("es", "km");
KM_MULTILINGUAL.put("de", "km");
KM_MULTILINGUAL.put("fr", "km");
KM_MULTILINGUAL.put("ar", "كم");
KM_MULTILINGUAL.put("zh", "公里");
MILE_MULTILINGUAL.put("es", "mi");
MILE_MULTILINGUAL.put("de", "mi");
MILE_MULTILINGUAL.put("fr", "mile");
MILE_MULTILINGUAL.put("ar", "ميل");
MILE_MULTILINGUAL.put("zh", "英里");
}
static Solo SOLO;
static Instrumentation instrumentation;
@@ -82,32 +127,35 @@ public class EndToEndTestUtils {
// Android OS.
static boolean hasActionBar = false;
static boolean isEmulator = true;
static boolean hasGpsSingal = true;
static boolean isCheckedFirstLaunch = false;
public static final String LOG_TAG = "MyTracksTest";
private EndToEndTestUtils() {}
/**
* Checks the language, then sets the fields with right string.
*/
private static void checkLanguage() {
RELATIVE_STARTTIME_POSTFIX_MULTILINGUAL.put("es", "mins ago");
RELATIVE_STARTTIME_POSTFIX_MULTILINGUAL.put("de", "Minuten");
RELATIVE_STARTTIME_POSTFIX_MULTILINGUAL.put("fr", "minute");
RELATIVE_STARTTIME_POSTFIX_MULTILINGUAL.put("ar", "دقيقة");
RELATIVE_STARTTIME_POSTFIX_MULTILINGUAL.put("zh", "分钟前");
VIEW_MODE_ENGLISH_MULTILINGUAL.put("es", "mode");
VIEW_MODE_ENGLISH_MULTILINGUAL.put("de", "modus");
VIEW_MODE_ENGLISH_MULTILINGUAL.put("fr", "Mode");
VIEW_MODE_ENGLISH_MULTILINGUAL.put("ar", "وضع");
VIEW_MODE_ENGLISH_MULTILINGUAL.put("zh", "模式");
Locale locale = null;
Configuration config=null;
config = activityMytracks.getBaseContext().getResources().getConfiguration();
locale = new Locale("en");
Locale.setDefault(locale);
config.locale = locale;
// Check the language, test in Chinese or English.
String deviceLanguage = instrumentation.getContext().getResources().getConfiguration().locale.getLanguage();
deviceLanguage = instrumentation.getContext().getResources().getConfiguration().locale.getLanguage();
if (RELATIVE_STARTTIME_POSTFIX_MULTILINGUAL.get(deviceLanguage) != null) {
RELATIVE_STARTTIME_POSTFIX = RELATIVE_STARTTIME_POSTFIX_MULTILINGUAL.get(deviceLanguage);
VIEW_MODE = VIEW_MODE_ENGLISH_MULTILINGUAL.get(deviceLanguage);
VIEW_MODE = VIEW_MODE_MULTILINGUAL.get(deviceLanguage);
KM = KM_MULTILINGUAL.get(deviceLanguage);
MILE = MILE_MULTILINGUAL.get(deviceLanguage);
} else {
RELATIVE_STARTTIME_POSTFIX = RELATIVE_STARTTIME_POSTFIX_MULTILINGUAL.get("es");
VIEW_MODE = VIEW_MODE_ENGLISH_MULTILINGUAL.get("es");
VIEW_MODE = VIEW_MODE_MULTILINGUAL.get("es");
KM = KM_MULTILINGUAL.get("es");
MILE = MILE_MULTILINGUAL.get("es");
}
}
@@ -128,7 +176,7 @@ public class EndToEndTestUtils {
PrintStream out = null;
Socket socket = null;
try {
socket = new Socket(ANDROID_LOCAL_IP, ANDROID_LOCAL_PORT);
socket = new Socket(ANDROID_LOCAL_IP, emulatorPort);
out = new PrintStream(socket.getOutputStream());
float longitude = START_LONGITUDE;
float latitude = START_LATITUDE;
@@ -138,6 +186,8 @@ public class EndToEndTestUtils {
longitude += DELTA_LONGITUDE;
latitude += DELTA_LADITUDE;
}
// Wait the GPS signal can be obtained by MyTracks.
Thread.sleep(SHORT_WAIT_TIME);
} catch (UnknownHostException e) {
System.exit(-1);
} catch (IOException e) {
@@ -166,27 +216,39 @@ public class EndToEndTestUtils {
*/
static void setupForAllTest(Instrumentation instrumentation, TrackListActivity activityMyTracks) {
setIsEmulator();
EndToEndTestUtils.instrumentation = instrumentation;
EndToEndTestUtils.activityMytracks = activityMyTracks;
EndToEndTestUtils.SOLO = new Solo(EndToEndTestUtils.instrumentation,
SOLO = new Solo(EndToEndTestUtils.instrumentation,
EndToEndTestUtils.activityMytracks);
// For emulator, we would fix GPS signal.
if(!isEmulator) {
GoToMyLocationTest.findAndClickMyLocation(activityMyTracks);
hasGpsSingal = !SOLO.waitForText(NO_GPS_MESSAGE_PREFIX, 1,
EndToEndTestUtils.SHORT_WAIT_TIME);
SOLO.goBack();
}
// Check if open MyTracks first time after install. If so, there would be a
// welcome view with accept buttons. And makes sure only check once.
if (!EndToEndTestUtils.isCheckedFirstLaunch) {
if ((EndToEndTestUtils.getButtonOnScreen(EndToEndTestUtils.activityMytracks
if (!isCheckedFirstLaunch) {
if ((getButtonOnScreen(EndToEndTestUtils.activityMytracks
.getString(R.string.eula_accept), false, false) != null)) {
EndToEndTestUtils.verifyFirstLaunch();
} else if (EndToEndTestUtils.SOLO.waitForText(
verifyFirstLaunch();
} else if (SOLO.waitForText(
// After reset setting, welcome page will show again.
activityMytracks.getString(R.string.welcome_title), 0, 500)) {
activityMytracks.getString(R.string.welcome_title), 0, SHORT_WAIT_TIME)) {
resetPreferredUnits();
}
hasActionBar = setHasActionBar();
checkLanguage();
EndToEndTestUtils.isCheckedFirstLaunch = true;
EndToEndTestUtils.setHasActionBar();
} else if (EndToEndTestUtils.SOLO.waitForText(
isCheckedFirstLaunch = true;
deleteAllTracks();
resetAllSettings(activityMyTracks, false);
} else if (SOLO.waitForText(
// After reset setting, welcome page will show again.
activityMytracks.getString(R.string.welcome_title), 0, 500)) {
activityMytracks.getString(R.string.welcome_title), 0, SHORT_WAIT_TIME)) {
resetPreferredUnits();
}
@@ -241,7 +303,7 @@ public class EndToEndTestUtils {
*/
static void createSimpleTrack(int numberOfGpsData) {
startRecording();
EndToEndTestUtils.sendGps(numberOfGpsData);
sendGps(numberOfGpsData);
instrumentation.waitForIdleSync();
stopRecording(true);
}
@@ -276,12 +338,14 @@ public class EndToEndTestUtils {
* activity
*/
static void createTrackIfEmpty(int gpsNumber, boolean showTrackList) {
if (EndToEndTestUtils.isTrackListEmpty(!showTrackList)) {
if (isTrackListEmpty(!showTrackList)) {
// Create a simple track.
EndToEndTestUtils.createSimpleTrack(gpsNumber);
createSimpleTrack(gpsNumber);
instrumentation.waitForIdleSync();
if (showTrackList) {
EndToEndTestUtils.SOLO.goBack();
SOLO.goBack();
}
instrumentation.waitForIdleSync();
}
}
@@ -290,7 +354,7 @@ public class EndToEndTestUtils {
*/
static void startRecording() {
if (hasActionBar) {
Button startButton = getButtonOnScreen(activityMytracks.getString(R.string.menu_record_track), false, false);
View startButton = getButtonOnScreen(activityMytracks.getString(R.string.menu_record_track), false, false);
// In case a track is recording.
if (startButton == null) {
stopRecording(true);
@@ -298,7 +362,7 @@ public class EndToEndTestUtils {
}
SOLO.clickOnView(startButton);
} else {
showMoreMenuItem();
showMenuItem();
if (!SOLO.searchText(activityMytracks.getString(R.string.menu_record_track))) {
// Check if in TrackDetailActivity.
if (SOLO.searchText(activityMytracks.getString(R.string.menu_play))) {
@@ -306,12 +370,13 @@ public class EndToEndTestUtils {
} else {
// In case a track is recording.
stopRecording(true);
showMoreMenuItem();
showMenuItem();
}
}
instrumentation.waitForIdleSync();
SOLO.clickOnText(activityMytracks.getString(R.string.menu_record_track));
}
instrumentation.waitForIdleSync();
}
/**
@@ -324,7 +389,7 @@ public class EndToEndTestUtils {
return getButtonOnScreen(activityMytracks
.getString(R.string.menu_record_track), false, false) == null;
}
showMoreMenuItem();
showMenuItem();
if (SOLO.searchText(activityMytracks.getString(R.string.menu_record_track))
|| SOLO.searchText(activityMytracks.getString(R.string.menu_play))) {
SOLO.goBack();
@@ -343,22 +408,21 @@ public class EndToEndTestUtils {
if (hasActionBar) {
getButtonOnScreen(activityMytracks.getString(R.string.menu_stop_recording), false, true);
} else {
showMoreMenuItem();
showMenuItem();
instrumentation.waitForIdleSync();
SOLO.clickOnText(activityMytracks.getString(R.string.menu_stop_recording));
}
if (isSave) {
EndToEndTestUtils.SOLO.waitForText(activityMytracks.getString(R.string.generic_save), 1, 5000);
SOLO.waitForText(activityMytracks.getString(R.string.generic_save), 1, 5000);
// Make every track name is unique to make sure every check can be
// trusted.
EndToEndTestUtils.trackName = EndToEndTestUtils.TRACK_NAME_PREFIX
trackName = TRACK_NAME_PREFIX
+ System.currentTimeMillis();
SOLO.enterText(0, trackName);
if(!EndToEndTestUtils.isEmulator) {
// Close soft keyboard.
EndToEndTestUtils.SOLO.goBack();
}
SOLO.clickLongOnText(activityMytracks.getString(R.string.generic_save));
SOLO.sendKey(KeyEvent.KEYCODE_DEL);
enterTextAvoidSoftKeyBoard(0, trackName);
enterTextAvoidSoftKeyBoard(1, DEFAULTACTIVITY);
SOLO.clickOnText(activityMytracks.getString(R.string.generic_save));
instrumentation.waitForIdleSync();
}
}
@@ -376,7 +440,16 @@ public class EndToEndTestUtils {
}
}
}
/**
* Deletes all tracks. This method should be call when the TracksListActivity
* is shown.
*/
static void deleteAllTracks() {
findMenuItem(activityMytracks.getString(R.string.menu_delete_all), true);
getButtonOnScreen(activityMytracks.getString(R.string.generic_ok), true, true);
}
/**
* Gets a kind of exported files.
*
@@ -417,22 +490,49 @@ public class EndToEndTestUtils {
* @param isClick whether click the button if find it
* @return the button to search, and null means can not find the button
*/
static Button getButtonOnScreen(String buttonName, boolean isWait,boolean isClick) {
static View getButtonOnScreen(String buttonName, boolean isWait,boolean isClick) {
View button = null;
instrumentation.waitForIdleSync();
if (isWait) {
SOLO.waitForText(buttonName);
}
ArrayList<Button> currentButtons = SOLO.getCurrentButtons();
for (Button button : currentButtons) {
String title = (String) button.getText();
if (title.equalsIgnoreCase(buttonName)) {
if(isClick) {
SOLO.clickOnView(button);
// Find on action bar.
if (hasActionBar) {
ArrayList<View> allViews = SOLO.getViews();
for (View view : allViews) {
String className = view.getClass().getName();
if(className.indexOf("ActionMenuItemView") > 0) {
String menuItemNameString = view.getContentDescription().toString();
if(menuItemNameString.equalsIgnoreCase(buttonName)) {
button = view;
break;
}
}
return button;
}
}
return null;
// Get all buttons and find.
if(button == null) {
ArrayList<Button> currentButtons = SOLO.getCurrentButtons();
for (Button oneButton : currentButtons) {
String title = (String) oneButton.getText();
if (title.equalsIgnoreCase(buttonName)) {
button = oneButton;
}
}
}
if(button != null && isClick) {
SOLO.clickOnView(button);
}
if (button == null && isClick) {
Log.d(LOG_TAG, "Don't find the button " + buttonName);
}
return button;
}
/**
@@ -441,31 +541,19 @@ public class EndToEndTestUtils {
* @return false means can not check failed.
*/
static boolean setHasActionBar() {
instrumentation.waitForIdleSync();
// If can find record button without pressing Menu, it should be an action
// bar.
Button startButton = getButtonOnScreen(activityMytracks.getString(R.string.menu_record_track), false, false);
Button stopButton = getButtonOnScreen(activityMytracks.getString(R.string.menu_stop_recording), false, false);
if (startButton != null || stopButton != null) {
hasActionBar = true;
} else {
showMoreMenuItem();
if (SOLO.searchText(activityMytracks.getString(R.string.menu_record_track))
|| SOLO.searchText(activityMytracks.getString(R.string.menu_stop_recording))) {
hasActionBar = false;
} else {
return false;
}
SOLO.goBack();
try {
return activityMytracks.getActionBar() == null ? false : true;
}catch (Throwable e) {
// For in Android which does not has action bar, here will meet a error.
return false;
}
return true;
}
/**
* Rotates the current activity.
*/
static void rotateCurrentActivity() {
EndToEndTestUtils.rotateActivity(SOLO.getCurrentActivity());
rotateActivity(SOLO.getCurrentActivity());
instrumentation.waitForIdleSync();
}
@@ -473,11 +561,12 @@ public class EndToEndTestUtils {
* Rotates all activities.
*/
static void rotateAllActivities() {
ArrayList<Activity> allActivities = SOLO.getAllOpenedActivities();
for (Activity activity : allActivities) {
EndToEndTestUtils.rotateActivity(activity);
if (hasActionBar) {
ArrayList<Activity> allActivities = SOLO.getAllOpenedActivities();
for (Activity activity : allActivities) {
rotateActivity(activity);
}
}
instrumentation.waitForIdleSync();
}
@@ -490,47 +579,86 @@ public class EndToEndTestUtils {
*/
static boolean findMenuItem(String menuName, boolean click) {
boolean findResult = false;
boolean isMoreMenuOpened = false;
// Firstly find in action bar.
Button button = getButtonOnScreen(menuName, false, false);
if (button != null) {
findResult = true;
if (click) {
SOLO.clickOnView(button);
instrumentation.waitForIdleSync();
// ICS phone.
if (hasActionBar) {
// Firstly find in action bar.
View button = getButtonOnScreen(menuName, false, false);
if (button != null) {
findResult = true;
if (click) {
SOLO.clickOnView(button);
instrumentation.waitForIdleSync();
}
return findResult;
}
return findResult;
}
showMoreMenuItem();
if (SOLO.searchText(menuName)) {
findResult = true;
} else if (SOLO.searchText(MENU_MORE)) {
SOLO.clickOnText(MENU_MORE);
showMenuItem();
findResult = SOLO.searchText(menuName);
} else {
// Non-ICS phone.
SOLO.sendKey(KeyEvent.KEYCODE_MENU);
if (SOLO.searchText(menuName)) {
findResult = true;
} else if (SOLO.searchText(MENU_MORE)) {
SOLO.clickOnText(MENU_MORE);
findResult = SOLO.searchText(menuName);
isMoreMenuOpened = true;
}
}
if (findResult && click) {
SOLO.clickOnText(menuName);
instrumentation.waitForIdleSync();
} else {
// Quit more menu list if opened.
if (isMoreMenuOpened) {
SOLO.goBack();
}
// Quit menu list.
SOLO.goBack();
}
return findResult;
}
/**
* Get more menu items operation is different for different Android OS.
* Show menu item list.
*/
public static void showMoreMenuItem() {
public static void showMenuItem() {
showMenuItem(0);
}
/**
* Gets more menu items operation is different for different Android OS. When
* get overflow button view on action, it usually be able to click. But in
* some situation, will meet an error when click it. So catch it and try
* again. In most situation, the second click will be pass.
*
* @param depth control the depth of recursion to prevent dead circulation
*/
private static void showMenuItem(int depth) {
// ICS phone.
if (hasActionBar) {
instrumentation.waitForIdleSync();
View moreButton = getMoreOptionView();
// ICS phone without menu key.
if (moreButton != null) {
SOLO.clickOnView(moreButton);
try {
SOLO.clickOnView(moreButton);
} catch (Throwable e) {
if (depth < 5 && e.getMessage().indexOf("Click can not be completed") > -1) {
showMenuItem(depth++);
}
}
return;
}
} else {
// ICS phone with menu key.
SOLO.sendKey(KeyEvent.KEYCODE_MENU);
}
} else {
// Non-ICS phone with menu key.
SOLO.sendKey(KeyEvent.KEYCODE_MENU);
}
SOLO.sendKey(KeyEvent.KEYCODE_MENU);
}
/**
@@ -559,7 +687,7 @@ public class EndToEndTestUtils {
* @return the text view, null means can not find it
*/
static TextView findTextView(String findText, View parent) {
ArrayList<TextView> textViews = EndToEndTestUtils.SOLO.getCurrentTextViews(parent);
ArrayList<TextView> textViews = SOLO.getCurrentTextViews(parent);
for (TextView textView : textViews) {
String text = (String) textView.getText();
if (textView.isShown() && text.endsWith(findText)) {
@@ -575,7 +703,7 @@ public class EndToEndTestUtils {
* @return the ChartView or null if not find
*/
static ChartView getChartView() {
ArrayList<View> views = EndToEndTestUtils.SOLO.getViews();
ArrayList<View> views = SOLO.getViews();
for (View view : views) {
if (view instanceof ChartView) {
return (ChartView) view;
@@ -591,13 +719,28 @@ public class EndToEndTestUtils {
* @param keepInSettingList whether keep in setting list or not
*/
public static void resetAllSettings(Activity activityMyTracks, boolean keepInSettingList) {
EndToEndTestUtils.findMenuItem(activityMyTracks.getString(R.string.menu_settings), true);
findMenuItem(activityMyTracks.getString(R.string.menu_settings), true);
SOLO.waitForText(activityMyTracks.getString(R.string.settings_reset));
SOLO.clickOnText(activityMyTracks.getString(R.string.settings_reset));
getButtonOnScreen(activityMytracks.getString(R.string.generic_ok), true, true);
instrumentation.waitForIdleSync();
if (!keepInSettingList) {
EndToEndTestUtils.SOLO.goBack();
SOLO.goBack();
}
}
}
/**
* Finds a edit text and enter text in it. This method can hides soft key
* board when input text.
*
* @param editTextIndex the index of edit text
* @param text to enter
*/
public static void enterTextAvoidSoftKeyBoard(int editTextIndex, String text) {
InputMethodManager imm = (InputMethodManager) activityMytracks.getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);
EditText editText = SOLO.getEditText(editTextIndex);
imm.hideSoftInputFromWindow(editText.getWindowToken(), InputMethodManager.HIDE_IMPLICIT_ONLY);
SOLO.enterText(editText, text);
}
}
@@ -91,7 +91,6 @@ public class ExportAndImportTest extends ActivityInstrumentationTestCase2<TrackL
EndToEndTestUtils.SOLO
.clickOnText(String.format(activityMyTracks.getString(R.string.menu_save_format),
EndToEndTestUtils.GPX.toUpperCase()));
EndToEndTestUtils.rotateAllActivities();
EndToEndTestUtils.SOLO.waitForText(activityMyTracks.getString(R.string.sd_card_save_success));
EndToEndTestUtils.getButtonOnScreen(activityMyTracks.getString(R.string.generic_ok), true, true);
// Check export file.
@@ -113,6 +112,7 @@ public class ExportAndImportTest extends ActivityInstrumentationTestCase2<TrackL
// gpxFilesNumber;
EndToEndTestUtils.getButtonOnScreen(activityMyTracks.getString(R.string.generic_ok), true, true);
instrumentation.waitForIdleSync();
assertTrue(EndToEndTestUtils.SOLO.waitForText(EndToEndTestUtils.trackName));
assertEquals(trackNumber + gpxFilesNumber, EndToEndTestUtils.SOLO.getCurrentListViews().get(0)
.getCount());
@@ -19,10 +19,13 @@ import com.google.android.apps.mytracks.TrackListActivity;
import com.google.android.apps.mytracks.util.GoogleLocationUtils;
import com.google.android.maps.mytracks.R;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Instrumentation;
import android.test.ActivityInstrumentationTestCase2;
import android.view.View;
import android.widget.ImageButton;
import java.util.ArrayList;
/**
* Tests the function of go to my location.
@@ -34,7 +37,6 @@ public class GoToMyLocationTest extends ActivityInstrumentationTestCase2<TrackLi
private Instrumentation instrumentation;
private TrackListActivity activityMyTracks;
@TargetApi(8)
public GoToMyLocationTest() {
super(TrackListActivity.class);
}
@@ -51,22 +53,44 @@ public class GoToMyLocationTest extends ActivityInstrumentationTestCase2<TrackLi
* Tests the menu My Location.
*/
public void testGotoMyLocation() {
EndToEndTestUtils.createTrackIfEmpty(1, false);
EndToEndTestUtils.sendGps(30);
instrumentation.waitForIdleSync();
View myLocation = EndToEndTestUtils.SOLO.getCurrentActivity()
.findViewById(R.id.map_my_location);
EndToEndTestUtils.SOLO.clickOnView(myLocation);
findAndClickMyLocation(activityMyTracks);
if (EndToEndTestUtils.isEmulator) {
String setting = activityMyTracks.getString(
GoogleLocationUtils.isAvailable(activityMyTracks) ? R.string.gps_google_location_settings
: R.string.gps_location_access);
EndToEndTestUtils.SOLO.waitForText(
activityMyTracks.getString(R.string.my_location_no_gps, setting), 1, 1000);
activityMyTracks.getString(R.string.my_location_no_gps, setting), 1,
EndToEndTestUtils.SHORT_WAIT_TIME);
} else {
// TODO How to verify the location is shown on the map.
}
}
/**
* Finds the My Location view and click it.
*
* @param activity
*/
public static void findAndClickMyLocation(Activity activity) {
EndToEndTestUtils.createTrackIfEmpty(1, false);
EndToEndTestUtils.sendGps(30);
View myLocation = EndToEndTestUtils.SOLO.getCurrentActivity()
.findViewById(R.id.map_my_location);
// Find the My Location button in another if null.
if (myLocation == null) {
ArrayList<ImageButton> aa = EndToEndTestUtils.SOLO.getCurrentImageButtons();
for (ImageButton imageButton : aa) {
if (imageButton.getContentDescription() != null
&& imageButton.getContentDescription().equals(
activity.getString(R.string.icon_my_location))) {
myLocation = imageButton;
break;
}
}
}
EndToEndTestUtils.SOLO.clickOnView(myLocation);
}
@Override
protected void tearDown() throws Exception {
@@ -0,0 +1,365 @@
/*
* 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.endtoendtest;
import com.google.android.apps.mytracks.Constants;
import com.google.android.apps.mytracks.io.docs.SendDocsUtils;
import com.google.android.apps.mytracks.io.fusiontables.SendFusionTablesAsyncTask;
import com.google.android.apps.mytracks.io.fusiontables.SendFusionTablesUtils;
import com.google.android.apps.mytracks.io.gdata.GDataClientFactory;
import com.google.android.apps.mytracks.io.gdata.docs.DocumentsClient;
import com.google.android.apps.mytracks.io.gdata.docs.SpreadsheetsClient;
import com.google.android.apps.mytracks.io.gdata.docs.XmlDocsGDataParserFactory;
import com.google.android.apps.mytracks.io.gdata.maps.MapFeatureEntry;
import com.google.android.apps.mytracks.io.gdata.maps.MapsClient;
import com.google.android.apps.mytracks.io.gdata.maps.MapsConstants;
import com.google.android.apps.mytracks.io.gdata.maps.MapsGDataConverter;
import com.google.android.apps.mytracks.io.gdata.maps.MapsMapMetadata;
import com.google.android.apps.mytracks.io.gdata.maps.XmlMapsGDataParserFactory;
import com.google.android.apps.mytracks.util.ApiAdapterFactory;
import com.google.android.apps.mytracks.util.SystemUtils;
import com.google.android.common.gdata.AndroidXmlParserFactory;
import com.google.api.client.googleapis.GoogleHeaders;
import com.google.api.client.googleapis.MethodOverride;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.InputStreamContent;
import com.google.api.client.util.Strings;
import com.google.wireless.gdata.data.Entry;
import com.google.wireless.gdata.data.Feed;
import com.google.wireless.gdata.parser.GDataParser;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Locale;
/**
* Provides utilities to access Google Maps, Google Documents, Google Fusion
* Tables.
*
* @author Youtao Liu
*/
public class GoogleUtils {
public static final String DOCUMENT_NAME_PREFIX = "My Tracks";
public static final String SPREADSHEET_NAME = DOCUMENT_NAME_PREFIX + "-" + EndToEndTestUtils.DEFAULTACTIVITY;
/**
* Gets the account to access Google Services.
*
* @param context context used to get account
* @return the first account which is bound with current device
*/
private static Account getAccount(Context context) {
return AccountManager.get(context).getAccountsByType(Constants.ACCOUNT_TYPE)[0];
}
/**
* Gets Google maps of a user.
*
* @param context used to get maps
* @param mapsClient the client to access Google Maps
* @return true means set successfully
*/
private static ArrayList<MapsMapMetadata> getMaps(Context context, MapsClient mapsClient) {
String authToken = null;
ArrayList<String> mapIds = new ArrayList<String>();
ArrayList<MapsMapMetadata> mapData = new ArrayList<MapsMapMetadata>();
try {
authToken = AccountManager.get(context).blockingGetAuthToken(getAccount(context),
MapsConstants.SERVICE_NAME, false);
} catch (Exception e) {
Log.d(EndToEndTestUtils.LOG_TAG, "Unable to get auth token", e);
return mapData;
}
GDataParser gDataParser = null;
try {
gDataParser = mapsClient.getParserForFeed(MapFeatureEntry.class, MapsClient.getMapsFeed(),
authToken);
gDataParser.init();
while (gDataParser.hasMoreData()) {
MapFeatureEntry entry = (MapFeatureEntry) gDataParser.readNextEntry(null);
mapIds.add(MapsGDataConverter.getMapidForEntry(entry));
mapData.add(MapsGDataConverter.getMapMetadataForEntry(entry));
}
} catch (Exception e) {
Log.d(EndToEndTestUtils.LOG_TAG, "Unable to get maps", e);
} finally {
if (gDataParser != null) {
gDataParser.close();
}
}
return mapData;
}
/**
* Searches a map in user's Google Maps.
*
* @param title the title of map
* @param activity activity to get context
* @param isDelete whether delete the map of this track in the Google Maps
* @return true means find the map
*/
private static boolean searchMapByTitle(String title, Activity activity, boolean isDelete) {
Context context = activity.getApplicationContext();
MapsClient mapsClient = new MapsClient(GDataClientFactory.getGDataClient(context),
new XmlMapsGDataParserFactory(new AndroidXmlParserFactory()));
ArrayList<MapsMapMetadata> mapData = getMaps(context, mapsClient);
for (MapsMapMetadata oneData : mapData) {
if (oneData.getDescription().indexOf(DOCUMENT_NAME_PREFIX) > -1
&& oneData.getTitle().equals(title)) {
if (isDelete) {
try {
mapsClient.deleteEntry(oneData.getGDataEditUri(), AccountManager.get(context).blockingGetAuthToken(getAccount(context),
MapsConstants.SERVICE_NAME, false));
return true;
} catch (Exception e) {
Log.d(EndToEndTestUtils.LOG_TAG, "Unable to drop map", e);
return false;
}
}
return true;
}
}
return false;
}
/**
* Searches a map in user's Google Maps.
*
* @param title the title of map
* @param activity activity to get context
* @return true means find the map
*/
public static boolean searchMap(String title, Activity activity) {
return searchMapByTitle(title, activity, false);
}
/**
* Searches a map in user's Google Maps and then delete it.
*
* @param title the title of map
* @param activity activity to get context
* @return true means find the map and delete it successfully
*/
public static boolean deleteMap(String title, Activity activity) {
return searchMapByTitle(title, activity, true);
}
/**
* Searches a doc in user's Google Documents.
*
* @param title the title of doc
* @param activity to get context
* @return the entry of the document, null means can not find the spreadsheet.
*/
private static Entry searchSpreadsheetByTitle(String title, Activity activity) {
Context context = activity.getApplicationContext();
DocumentsClient documentsClient = new DocumentsClient(
GDataClientFactory.getGDataClient(context),
new XmlDocsGDataParserFactory(new AndroidXmlParserFactory()));
try {
String documentsAuthToken = AccountManager.get(context)
.blockingGetAuthToken(getAccount(context), documentsClient.getServiceName(), false);
String uri = String.format(Locale.US, SendDocsUtils.GET_SPREADSHEET_BY_TITLE_URI,
URLEncoder.encode(title, "utf-8"));
GDataParser gDataParser = documentsClient.getParserForFeed(Entry.class, uri,
documentsAuthToken);
gDataParser.init();
while (gDataParser.hasMoreData()) {
Entry entry = gDataParser.readNextEntry(null);
String entryTitle = entry.getTitle();
if (entryTitle.equals(title)) {
return entry;
}
}
} catch (Exception e) {
Log.d(EndToEndTestUtils.LOG_TAG, "Unable to fetch spreadsheet.", e);
}
return null;
}
/**
* Searches a track title in a spreadsheet.
*
* @param title the track name to search
* @param activity to get context
* @param spreadsheetTitle the title of spreadsheet
* @param isDelete whether delete the information of this track in the document
* @return true means find the track name in the spreadsheet
*/
private static boolean searchTrackTitleInSpreadsheet(String title, Activity activity, String spreadsheetTitle, boolean isDelete) {
String spreadsheetId = searchSpreadsheetByTitle(spreadsheetTitle, activity).getId().replace(SendDocsUtils.SPREADSHEET_ID_PREFIX, "");
if(spreadsheetId == null) {
Log.d(EndToEndTestUtils.LOG_TAG, "Unable to find the spreadsheet -- " + spreadsheetTitle);
return false;
}
Context context = activity.getApplicationContext();
try {
SpreadsheetsClient spreadsheetsClient = new SpreadsheetsClient(
GDataClientFactory.getGDataClient(context), new XmlDocsGDataParserFactory(new AndroidXmlParserFactory()));
String spreadsheetsAuthToken = AccountManager.get(activity.getApplicationContext()).blockingGetAuthToken(
getAccount(context), spreadsheetsClient.getServiceName(), false);
String weekSheetId = SendDocsUtils.getWorksheetId(spreadsheetId, spreadsheetsClient, spreadsheetsAuthToken);
String worksheetUri = String.format(Locale.US, SendDocsUtils.GET_WORKSHEET_URI, URLEncoder.encode(spreadsheetId, "utf-8"),
weekSheetId);
GDataParser gDataParser = spreadsheetsClient.getParserForFeed(Feed.class, worksheetUri,
spreadsheetsAuthToken);
gDataParser.init();
while (gDataParser.hasMoreData()) {
Entry entry = gDataParser.readNextEntry(null);
String entryTitle = entry.getTitle();
if (entryTitle.indexOf(title) > -1) {
if (isDelete) {
spreadsheetsClient.deleteEntry(entry.getEditUri(), spreadsheetsAuthToken);
}
return true;
}
}
} catch (Exception e) {
Log.d(EndToEndTestUtils.LOG_TAG, "Unable to fetch content of spreadsheet.", e);
}
return false;
}
/**
* Searches a track in spreadsheet.
*
* @param title the track name to search
* @param activity to get context
* @return true means find the track name in the spreadsheet
*/
public static boolean searchTrackInSpreadSheet(String title, Activity activity) {
return searchTrackTitleInSpreadsheet(title, activity, GoogleUtils.SPREADSHEET_NAME, false);
}
/**
* Searches and deletes a track in spreadsheet.
*
* @param title the track name to search
* @param activity to get context
* @return true means find and delete successfully
*/
public static boolean deleteTrackInSpreadSheet(String title, Activity activity) {
return searchTrackTitleInSpreadsheet(title, activity, GoogleUtils.SPREADSHEET_NAME, true);
}
/**
* Searches a fusion table in user's Google tables.
*
* @param title the title of fusion table
* @param activity to get context
* @return true means find the fusion table
*/
public static boolean searchFusionTableByTitle(String title, Activity activity) {
Context context = activity.getApplicationContext();
try {
HttpResponse response = sendFusionTableQuery("SHOW TABLES", context);
// We can use index of method to check new table for every track name is unique.
if (response != null && response.parseAsString().indexOf(title) > 0) {
return true;
}
} catch (Exception e) {
Log.d(EndToEndTestUtils.LOG_TAG, "Unable to query fusion table.", e);
}
return false;
}
/**
* Drops one fusion table which contain the string in title of current user.
*
* @param title the title of a track to drop
* @param activity to get context
* @return the result of drop
*/
public static boolean dropFusionTables(String title, Activity activity) {
Context context = activity.getApplicationContext();
HttpResponse response = sendFusionTableQuery("SHOW TABLES", context);
String[] rowsTable;
try {
rowsTable = response.parseAsString().split("\n");
for (String row : rowsTable) {
String firstColumn = row.split(",")[0];
String secondColumn = row.split(",")[1];
// If the first column is all figure, it is the table id.
String regularExpression = "^[0-9]*$";
if (firstColumn.matches(regularExpression) && secondColumn.equals(title)) {
sendFusionTableQuery("DROP TABLE " + row.split(",")[0], context);
return true;
}
}
} catch (IOException e) {
Log.d(EndToEndTestUtils.LOG_TAG, "Failed when delete all fusion tables.", e);
}
return false;
}
/**
* Sends query to operate fusion tables.
*
* @param query to executed
* @param context application context
* @return the response of execution
*/
private static HttpResponse sendFusionTableQuery(String query, Context context) {
try {
String fusionTableAuthToken = AccountManager.get(context).blockingGetAuthToken(getAccount(context),
SendFusionTablesUtils.SERVICE, false);
GenericUrl url = new GenericUrl(SendFusionTablesAsyncTask.FUSION_TABLES_BASE_URL);
String sql = "sql=" + query;
ByteArrayInputStream inputStream = new ByteArrayInputStream(Strings.toBytesUtf8(sql));
InputStreamContent inputStreamContent = new InputStreamContent(null, inputStream);
HttpRequest request;
request = (ApiAdapterFactory.getApiAdapter().getHttpTransport()
.createRequestFactory(new MethodOverride())).buildPostRequest(url, inputStreamContent);
GoogleHeaders headers = new GoogleHeaders();
headers.setApplicationName(SendFusionTablesAsyncTask.APP_NAME_PREFIX
+ SystemUtils.getMyTracksVersion(context));
headers.gdataVersion = SendFusionTablesAsyncTask.GDATA_VERSION;
headers.setGoogleLogin(fusionTableAuthToken);
headers.setContentType(SendFusionTablesAsyncTask.CONTENT_TYPE);
request.setHeaders(headers);
HttpResponse response;
response = request.execute();
return response;
} catch (Exception e) {
Log.d(EndToEndTestUtils.LOG_TAG, "Failed when send fusion table query.", e);
return null;
}
}
}
@@ -22,9 +22,6 @@ import android.annotation.TargetApi;
import android.app.Instrumentation;
import android.test.ActivityInstrumentationTestCase2;
import android.view.KeyEvent;
import android.widget.EditText;
import java.util.ArrayList;
/**
* Tests some menu items of MyTracks.
@@ -67,13 +64,16 @@ public class MenuItemsTest extends ActivityInstrumentationTestCase2<TrackListAct
EndToEndTestUtils.createTrackIfEmpty(1, false);
instrumentation.waitForIdleSync();
// Menu in TrackDetailActivity.
EndToEndTestUtils.findMenuItem(activityMyTracks.getString(R.string.menu_sensor_state), true);
EndToEndTestUtils.SOLO.waitForText(activityMyTracks
.getString(R.string.sensor_state_last_sensor_time));
// When there is no sensor connected this menu will be hidden.
if (EndToEndTestUtils
.findMenuItem(activityMyTracks.getString(R.string.menu_sensor_state), true)) {
EndToEndTestUtils.SOLO.waitForText(activityMyTracks
.getString(R.string.sensor_state_last_sensor_time));
}
EndToEndTestUtils.SOLO.goBack();
EndToEndTestUtils.findMenuItem(activityMyTracks.getString(R.string.menu_help), true);
EndToEndTestUtils.SOLO.clickOnText(activityMyTracks.getString(R.string.help_about));
EndToEndTestUtils.getButtonOnScreen(activityMyTracks.getString(R.string.help_about), true, true);
EndToEndTestUtils.getButtonOnScreen(activityMyTracks.getString(R.string.generic_ok), true, true);
EndToEndTestUtils.getButtonOnScreen(activityMyTracks.getString(R.string.generic_ok), true, true);
}
@@ -85,8 +85,7 @@ public class MenuItemsTest extends ActivityInstrumentationTestCase2<TrackListAct
EndToEndTestUtils.createSimpleTrack(1);
EndToEndTestUtils.SOLO.goBack();
EndToEndTestUtils.findMenuItem(activityMyTracks.getString(R.string.menu_search), true);
ArrayList<EditText> editTexts = EndToEndTestUtils.SOLO.getCurrentEditTexts();
EndToEndTestUtils.SOLO.enterText(editTexts.get(0), EndToEndTestUtils.trackName);
EndToEndTestUtils.enterTextAvoidSoftKeyBoard(0, EndToEndTestUtils.trackName);
sendKeys(KeyEvent.KEYCODE_ENTER);
instrumentation.waitForIdleSync();
assertEquals(1, EndToEndTestUtils.SOLO.getCurrentListViews().size());
@@ -32,9 +32,7 @@ import java.util.ArrayList;
* @author Youtao Liu
*/
public class SettingTest extends ActivityInstrumentationTestCase2<TrackListActivity> {
private final String DEFAULTACTIVITY = "TestActivity";
private Instrumentation instrumentation;
private TrackListActivity activityMyTracks;
@@ -78,14 +76,14 @@ public class SettingTest extends ActivityInstrumentationTestCase2<TrackListActiv
// Change a setting of sharing.
EndToEndTestUtils.SOLO.clickOnText(activityMyTracks.getString(R.string.settings_sharing));
assertTrue(EndToEndTestUtils.SOLO.waitForText(
activityMyTracks.getString(R.string.settings_sharing_allow_access), 1, 5000));
activityMyTracks.getString(R.string.settings_sharing_allow_access), 1, EndToEndTestUtils.NORMAL_WAIT_TIME));
ArrayList<CheckBox> sharingCheckBoxs = EndToEndTestUtils.SOLO.getCurrentCheckBoxes();
boolean newMapsPublic = sharingCheckBoxs.get(0).isChecked();
EndToEndTestUtils.SOLO.clickOnCheckBox(0);
instrumentation.waitForIdleSync();
assertTrue(EndToEndTestUtils.SOLO.waitForText(
activityMyTracks.getString(R.string.settings_sharing_allow_access), 1, 5000));
assertEquals(!newMapsPublic, sharingCheckBoxs.get(0).isChecked());
activityMyTracks.getString(R.string.settings_sharing_allow_access), 1, EndToEndTestUtils.NORMAL_WAIT_TIME));
assertEquals(!newMapsPublic, EndToEndTestUtils.SOLO.getCurrentCheckBoxes().get(0).isChecked());
EndToEndTestUtils.SOLO.goBack();
// Reset all settings.
@@ -93,9 +91,11 @@ public class SettingTest extends ActivityInstrumentationTestCase2<TrackListActiv
EndToEndTestUtils.getButtonOnScreen(activityMyTracks.getString(R.string.generic_ok), true, true);
// Check settings.
// Add following scroll up for a bug of Robotium.
EndToEndTestUtils.SOLO.scrollUp();
EndToEndTestUtils.SOLO.clickOnText(activityMyTracks.getString(R.string.track_detail_stats_tab));
EndToEndTestUtils.SOLO.waitForText(activityMyTracks
.getString(R.string.settings_stats_units_title), 1, 20000);
assertTrue(EndToEndTestUtils.SOLO.waitForText(activityMyTracks
.getString(R.string.settings_stats_units_title), 1, EndToEndTestUtils.LONG_WAIT_TIME));
displayCheckBoxs = EndToEndTestUtils.SOLO.getCurrentCheckBoxes();
assertEquals(useMetric, displayCheckBoxs.get(0).isChecked());
@@ -153,9 +153,11 @@ public class SettingTest extends ActivityInstrumentationTestCase2<TrackListActiv
EndToEndTestUtils.createTrackIfEmpty(5, false);
EndToEndTestUtils.resetAllSettings(activityMyTracks, true);
ChangeStatsSettings(false, false, true, true, true);
instrumentation.waitForIdleSync();
EndToEndTestUtils.SOLO.clickOnText(activityMyTracks.getString(R.string.track_detail_stats_tab));
assertTrue(EndToEndTestUtils.SOLO.waitForText(activityMyTracks
.getString(R.string.stats_min_elevation)));
assertTrue(EndToEndTestUtils.SOLO.waitForText(
activityMyTracks.getString(R.string.stats_min_elevation), 1,
EndToEndTestUtils.NORMAL_WAIT_TIME, true));
assertTrue(EndToEndTestUtils.SOLO.waitForText(activityMyTracks
.getString(R.string.stats_min_grade)));
assertTrue(EndToEndTestUtils.SOLO.waitForText(activityMyTracks
@@ -241,27 +243,28 @@ public class SettingTest extends ActivityInstrumentationTestCase2<TrackListActiv
// Write to SD card.
EndToEndTestUtils.findMenuItem(activityMyTracks.getString(R.string.menu_settings), true);
EndToEndTestUtils.SOLO.clickOnText(activityMyTracks.getString(R.string.settings_backup));
EndToEndTestUtils.SOLO
.clickOnText(activityMyTracks.getString(R.string.settings_backup_now));
EndToEndTestUtils.SOLO.clickOnText(activityMyTracks.getString(R.string.settings_backup_now));
assertTrue(EndToEndTestUtils.SOLO.waitForText(
activityMyTracks.getString(R.string.sd_card_save_success), 0, 100000));
activityMyTracks.getString(R.string.sd_card_save_success), 0,
EndToEndTestUtils.SUPER_LONG_WAIT_TIME));
instrumentation.waitForIdleSync();
// Delete all tracks.
EndToEndTestUtils.SOLO.goBack();
EndToEndTestUtils.SOLO.goBack();
EndToEndTestUtils.findMenuItem(activityMyTracks.getString(R.string.menu_delete_all), true);
EndToEndTestUtils.getButtonOnScreen(activityMyTracks.getString(R.string.generic_ok), true, true);
EndToEndTestUtils.deleteAllTracks();
instrumentation.waitForIdleSync();
// Read from SD card.
EndToEndTestUtils.findMenuItem(activityMyTracks.getString(R.string.menu_settings), true);
EndToEndTestUtils.SOLO.clickOnText(activityMyTracks.getString(R.string.settings_backup));
EndToEndTestUtils.SOLO.clickOnText(activityMyTracks
.getString(R.string.settings_backup_restore));
EndToEndTestUtils.getButtonOnScreen(activityMyTracks.getString(R.string.generic_ok), true, true);
EndToEndTestUtils.SOLO
.clickOnText(activityMyTracks.getString(R.string.settings_backup_restore));
EndToEndTestUtils
.getButtonOnScreen(activityMyTracks.getString(R.string.generic_ok), true, true);
assertTrue(EndToEndTestUtils.SOLO.waitForText(
activityMyTracks.getString(R.string.sd_card_import_success), 0, 10000));
activityMyTracks.getString(R.string.sd_card_import_success), 0,
EndToEndTestUtils.SUPER_LONG_WAIT_TIME));
// Check restore track.
assertTrue(EndToEndTestUtils.SOLO.searchText(EndToEndTestUtils.trackName));
}
@@ -281,13 +284,10 @@ public class SettingTest extends ActivityInstrumentationTestCase2<TrackListActiv
// Changes the setting of default activity.
EndToEndTestUtils.SOLO.clickOnText(activityMyTracks
.getString(R.string.settings_recording_default_activity));
EndToEndTestUtils.SOLO.enterText(0, DEFAULTACTIVITY);
if(!EndToEndTestUtils.isEmulator) {
// Close soft keyboard.
EndToEndTestUtils.SOLO.goBack();
}
EndToEndTestUtils.getButtonOnScreen(activityMyTracks.getString(R.string.generic_ok), true, true);
EndToEndTestUtils.enterTextAvoidSoftKeyBoard(0, EndToEndTestUtils.DEFAULTACTIVITY);
EndToEndTestUtils
.getButtonOnScreen(activityMyTracks.getString(R.string.generic_ok), true, true);
EndToEndTestUtils.SOLO.goBack();
EndToEndTestUtils.SOLO.goBack();
@@ -297,9 +297,8 @@ public class SettingTest extends ActivityInstrumentationTestCase2<TrackListActiv
instrumentation.waitForIdleSync();
assertTrue(EndToEndTestUtils.SOLO.searchText(activityMyTracks.getString(
R.string.track_name_format).split(" ")[0]));
assertTrue(EndToEndTestUtils.SOLO.searchText(DEFAULTACTIVITY));
assertTrue(EndToEndTestUtils.SOLO.searchText(EndToEndTestUtils.DEFAULTACTIVITY));
EndToEndTestUtils.SOLO.clickOnText(activityMyTracks.getString(R.string.generic_save));
}
@Override
@@ -23,7 +23,6 @@ import com.google.android.maps.mytracks.R;
import android.annotation.TargetApi;
import android.app.Instrumentation;
import android.test.ActivityInstrumentationTestCase2;
import android.view.KeyEvent;
import android.view.View;
import java.util.ArrayList;
@@ -57,38 +56,33 @@ public class ViewsTest extends ActivityInstrumentationTestCase2<TrackListActivit
* menus in these views.
*/
public void testSwitchViewsAndMenusOfView() {
EndToEndTestUtils.createTrackIfEmpty(3, false);
EndToEndTestUtils.SOLO.goBack();
EndToEndTestUtils.SOLO.clickOnText(EndToEndTestUtils.trackName);
EndToEndTestUtils.createTrackIfEmpty(3, true);
EndToEndTestUtils.SOLO.scrollUp();
EndToEndTestUtils.SOLO.clickOnText(EndToEndTestUtils.trackName, 1, true);
EndToEndTestUtils.SOLO.clickOnText(activityMyTracks.getString(R.string.track_detail_chart_tab));
EndToEndTestUtils.rotateAllActivities();
EndToEndTestUtils.showMoreMenuItem();
assertTrue(EndToEndTestUtils.SOLO.waitForText(
activityMyTracks.getString(R.string.menu_settings), 1, 3000));
assertFalse(EndToEndTestUtils.SOLO.waitForText(
activityMyTracks.getString(R.string.menu_satellite_mode), 1, 0));
assertFalse(EndToEndTestUtils.SOLO.waitForText(
activityMyTracks.getString(R.string.menu_map_mode), 1, 0));
EndToEndTestUtils.SOLO.goBack();
assertTrue(EndToEndTestUtils.findMenuItem(activityMyTracks.getString(R.string.menu_settings),
false));
assertFalse(EndToEndTestUtils.findMenuItem(
activityMyTracks.getString(R.string.menu_satellite_mode), false));
assertFalse(EndToEndTestUtils.findMenuItem(activityMyTracks.getString(R.string.menu_map_mode),
false));
EndToEndTestUtils.SOLO.clickOnText(activityMyTracks.getString(R.string.track_detail_stats_tab));
EndToEndTestUtils.SOLO.sendKey(KeyEvent.KEYCODE_MENU);
assertTrue(EndToEndTestUtils.SOLO.waitForText(
activityMyTracks.getString(R.string.menu_settings), 1, 3000));
assertFalse(EndToEndTestUtils.SOLO.waitForText(
activityMyTracks.getString(R.string.menu_satellite_mode), 1, 0));
assertFalse(EndToEndTestUtils.SOLO.waitForText(
activityMyTracks.getString(R.string.menu_map_mode), 1, 0));
EndToEndTestUtils.SOLO.goBack();
assertTrue(EndToEndTestUtils.findMenuItem(activityMyTracks.getString(R.string.menu_settings),
false));
assertFalse(EndToEndTestUtils.findMenuItem(
activityMyTracks.getString(R.string.menu_satellite_mode), false));
assertFalse(EndToEndTestUtils.findMenuItem(activityMyTracks.getString(R.string.menu_map_mode),
false));
EndToEndTestUtils.SOLO.clickOnText(activityMyTracks.getString(R.string.track_detail_map_tab));
EndToEndTestUtils.showMoreMenuItem();
assertTrue(EndToEndTestUtils.SOLO.waitForText(
activityMyTracks.getString(R.string.menu_settings), 1, 3000));
assertTrue(EndToEndTestUtils.SOLO.searchText(EndToEndTestUtils.VIEW_MODE, 1, true, false));
assertTrue(EndToEndTestUtils.findMenuItem(
activityMyTracks.getString(R.string.menu_settings), false));
assertTrue(EndToEndTestUtils.findMenuItem(EndToEndTestUtils.VIEW_MODE, false));
}
/**
@@ -105,7 +99,7 @@ public class ViewsTest extends ActivityInstrumentationTestCase2<TrackListActivit
false)) {
isMapMode = false;
}
EndToEndTestUtils.showMoreMenuItem();
EndToEndTestUtils.showMenuItem();
// Switch to satellite mode if it's map mode now..
EndToEndTestUtils.SOLO.clickOnText(activityMyTracks
.getString(isMapMode ? R.string.menu_satellite_mode : R.string.menu_map_mode));
@@ -125,7 +119,7 @@ public class ViewsTest extends ActivityInstrumentationTestCase2<TrackListActivit
EndToEndTestUtils.rotateAllActivities();
// Switch back.
EndToEndTestUtils.showMoreMenuItem();
EndToEndTestUtils.showMenuItem();
EndToEndTestUtils.SOLO.clickOnText(activityMyTracks
.getString(isMapMode ? R.string.menu_satellite_mode : R.string.menu_map_mode));
isMapMode = !isMapMode;
@@ -139,7 +133,7 @@ public class ViewsTest extends ActivityInstrumentationTestCase2<TrackListActivit
// Wait for the TrackDetailActivity, or the stop button will can not be
// found in next step.
EndToEndTestUtils.SOLO.waitForText(activityMyTracks.getString(R.string.track_detail_chart_tab),
0, 1000);
0, EndToEndTestUtils.SHORT_WAIT_TIME);
}
@Override
@@ -148,7 +148,7 @@ public class GpxImporterTest extends AndroidTestCase {
expect(providerUtils.insertTrack(AndroidMock.capture(trackParam)))
.andReturn(TRACK_ID_URI);
expect(providerUtils.getLastLocationId(TRACK_ID)).andReturn(TRACK_POINT_ID_1).andReturn(TRACK_POINT_ID_2);
expect(providerUtils.getLastTrackLocationId(TRACK_ID)).andReturn(TRACK_POINT_ID_1).andReturn(TRACK_POINT_ID_2);
// A flush happens after the first insertion to get the starting point ID,
// which is why we get two calls
@@ -225,7 +225,7 @@ public class GpxImporterTest extends AndroidTestCase {
expect(providerUtils.bulkInsertTrackPoints((Location[]) AndroidMock.anyObject(),
AndroidMock.anyInt(), AndroidMock.anyLong())).andStubReturn(1);
expect(providerUtils.getLastLocationId(TRACK_ID)).andStubReturn(TRACK_POINT_ID_1);
expect(providerUtils.getLastTrackLocationId(TRACK_ID)).andStubReturn(TRACK_POINT_ID_1);
providerUtils.deleteTrack(TRACK_ID);
@@ -17,7 +17,7 @@ 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.content.Waypoint;
import com.google.android.apps.mytracks.stats.TripStatistics;
import android.annotation.TargetApi;
import android.location.Location;
@@ -49,7 +49,7 @@ public class KmlTrackWriterTest extends TrackFormatWriterTest {
}
@Override
public String generateWaypointDescription(Waypoint waypoint) {
public String generateWaypointDescription(TripStatistics tripStatistics) {
return null;
}
}
@@ -57,35 +57,6 @@ public class DynamicSpeedTrackPathDescriptorTest extends AndroidTestCase {
}
}
/**
* Tests {@link DynamicSpeedTrackPathDescriptor#onSharedPreferenceChanged(SharedPreferences,
* String)} when the key is null.
*/
public void testOnSharedPreferenceChanged_nullKey() {
DynamicSpeedTrackPathDescriptor dynamicSpeedTrackPathDescriptor = new DynamicSpeedTrackPathDescriptor(
context);
int speedMargin = dynamicSpeedTrackPathDescriptor.getSpeedMargin();
// Change value in shared preferences.
PreferencesUtils.setInt(context, R.string.track_color_mode_percentage_key, speedMargin + 2);
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();
// Change value in shared preferences.
PreferencesUtils.setInt(context, R.string.track_color_mode_percentage_key, speedMargin + 2);
dynamicSpeedTrackPathDescriptor.onSharedPreferenceChanged(sharedPreferences, "anyKey");
assertEquals(speedMargin, dynamicSpeedTrackPathDescriptor.getSpeedMargin());
}
/**
* Tests {@link DynamicSpeedTrackPathDescriptor#onSharedPreferenceChanged(SharedPreferences,
* String)} when the key is trackColorModeDynamicVariation.
@@ -120,7 +91,7 @@ public class DynamicSpeedTrackPathDescriptorTest extends AndroidTestCase {
}
/**
* Tests {@link DynamicSpeedTrackPathDescriptor#needsRedraw()} by wrong track
* Tests {@link DynamicSpeedTrackPathDescriptor#updateState()} by wrong track
* id.
*/
public void testNeedsRedraw_WrongTrackId() {
@@ -128,11 +99,11 @@ public class DynamicSpeedTrackPathDescriptorTest extends AndroidTestCase {
context, R.string.selected_track_id_key, PreferencesUtils.SELECTED_TRACK_ID_DEFAULT);
DynamicSpeedTrackPathDescriptor dynamicSpeedTrackPathDescriptor = new DynamicSpeedTrackPathDescriptor(
context);
assertEquals(false, dynamicSpeedTrackPathDescriptor.needsRedraw());
assertEquals(false, dynamicSpeedTrackPathDescriptor.updateState());
}
/**
* Tests {@link DynamicSpeedTrackPathDescriptor#needsRedraw()} by different
* Tests {@link DynamicSpeedTrackPathDescriptor#updateState()} by different
* averageMovingSpeed.
*/
public void testIsDiffereceSignificant() {
@@ -145,8 +116,7 @@ public class DynamicSpeedTrackPathDescriptorTest extends AndroidTestCase {
// 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) };
double[] expectedAverageMovingSpeed = { 0, 30, 30, 30 };
// Test
for (int i = 0; i < newAverageMovingSpeed.length; i++) {
dynamicSpeedTrackPathDescriptor.setAverageMovingSpeed(averageMovingSpeeds[i]);
@@ -62,7 +62,7 @@ public class DynamicSpeedTrackPathPainterTest extends TrackPathPainterTestCase {
public void testUpdatePath_AllInvalidLocation() {
List<CachedLocation> points = createCachedLocations(NUMBER_OF_LOCATIONS, INVALID_LATITUDE, -1);
dynamicSpeedTrackPathPainter.updatePath(myTracksOverlay.getMapProjection(mockView),
myTracksOverlay.getMapViewRect(mockView), 1, true, points);
myTracksOverlay.getMapViewRect(mockView), 1, points);
AndroidMock.verify(trackPathDescriptor);
// Should be zero for there is no valid locations.
assertEquals(0, dynamicSpeedTrackPathPainter.getColoredPaths().size());
@@ -80,7 +80,7 @@ public class DynamicSpeedTrackPathPainterTest extends TrackPathPainterTestCase {
// Gets a number as the start index of points.
int startLocationIdx = NUMBER_OF_LOCATIONS / 2;
dynamicSpeedTrackPathPainter.updatePath(myTracksOverlay.getMapProjection(mockView),
myTracksOverlay.getMapViewRect(mockView), startLocationIdx, true, points);
myTracksOverlay.getMapViewRect(mockView), startLocationIdx, points);
AndroidMock.verify(trackPathDescriptor);
assertEquals(NUMBER_OF_LOCATIONS - startLocationIdx, dynamicSpeedTrackPathPainter
@@ -123,7 +123,7 @@ public class DynamicSpeedTrackPathPainterTest extends TrackPathPainterTestCase {
slowSpeed));
dynamicSpeedTrackPathPainter.updatePath(myTracksOverlay.getMapProjection(mockView),
myTracksOverlay.getMapViewRect(mockView), startLocationIdx, true, points);
myTracksOverlay.getMapViewRect(mockView), startLocationIdx, points);
AndroidMock.verify(trackPathDescriptor);
List<ColoredPath> coloredPath = dynamicSpeedTrackPathPainter.getColoredPaths();
@@ -31,9 +31,10 @@ import java.util.List;
*/
public class SingleColorTrackPathPainterTest extends TrackPathPainterTestCase {
private static final int NUMBER_OF_LOCATIONS = 10;
private SingleColorTrackPathPainter singleColorTrackPathPainter;
private Path pathMock;
private static final int NUMBER_OF_LOCATIONS = 100;
/**
* Initials a mocked TrackPathDescriptor object and
@@ -44,8 +45,8 @@ public class SingleColorTrackPathPainterTest extends TrackPathPainterTestCase {
protected void setUp() throws Exception {
super.setUp();
pathMock = AndroidMock.createStrictMock(Path.class);
singleColorTrackPathPainter = new SingleColorTrackPathPainter(getContext());
pathMock = AndroidMock.createStrictMock(Path.class);
}
/**
@@ -54,11 +55,12 @@ public class SingleColorTrackPathPainterTest extends TrackPathPainterTestCase {
* method when all locations are valid.
*/
public void testUpdatePath_AllValidLocation() {
pathMock.incReserve(NUMBER_OF_LOCATIONS);
List<CachedLocation> points = createCachedLocations(NUMBER_OF_LOCATIONS,
TrackStubUtils.INITIAL_LATITUDE, -1);
// Gets a number as the start index of points.
int startLocationIdx = NUMBER_OF_LOCATIONS / 2;
pathMock.incReserve(NUMBER_OF_LOCATIONS - startLocationIdx);
List<CachedLocation> points = createCachedLocations(NUMBER_OF_LOCATIONS,
TrackStubUtils.INITIAL_LATITUDE, -1);
for (int i = startLocationIdx; i < NUMBER_OF_LOCATIONS; i++) {
pathMock.lineTo(0, 0);
@@ -66,7 +68,7 @@ public class SingleColorTrackPathPainterTest extends TrackPathPainterTestCase {
AndroidMock.replay(pathMock);
singleColorTrackPathPainter.updatePath(myTracksOverlay.getMapProjection(mockView),
myTracksOverlay.getMapViewRect(mockView), startLocationIdx, true, points, pathMock);
myTracksOverlay.getMapViewRect(mockView), startLocationIdx, points, pathMock);
AndroidMock.verify(pathMock);
}
@@ -76,20 +78,20 @@ public class SingleColorTrackPathPainterTest extends TrackPathPainterTestCase {
* method when all locations are invalid.
*/
public void testUpdatePath_AllInvalidLocation() {
pathMock.incReserve(NUMBER_OF_LOCATIONS);
int startLocationIdx = NUMBER_OF_LOCATIONS / 2;
pathMock.incReserve(NUMBER_OF_LOCATIONS - startLocationIdx);
List<CachedLocation> points = createCachedLocations(NUMBER_OF_LOCATIONS, INVALID_LATITUDE, -1);
// Gets a random number from 1 to numberOfLocations.
int startLocationIdx = NUMBER_OF_LOCATIONS / 2;
AndroidMock.replay(pathMock);
singleColorTrackPathPainter.updatePath(myTracksOverlay.getMapProjection(mockView),
myTracksOverlay.getMapViewRect(mockView), startLocationIdx, true, points, pathMock);
myTracksOverlay.getMapViewRect(mockView), startLocationIdx, points, pathMock);
AndroidMock.verify(pathMock);
}
/**
* Tests the
* {@link SingleColorTrackPathPainter#updatePath(com.google.android.maps.Projection, android.graphics.Rect, int, Boolean, List, Path)}
* method when there are three segments.
* Tests the {@link SingleColorTrackPathPainter#updatePath(com.google.android.maps.Projection,
* android.graphics.Rect, int, Boolean, List, Path)} method when there are
* three segments.
*/
public void testUpdatePath_ThreeSegments() {
// First segment.
@@ -103,7 +105,7 @@ public class SingleColorTrackPathPainterTest extends TrackPathPainterTestCase {
points.addAll(createCachedLocations(NUMBER_OF_LOCATIONS, TrackStubUtils.INITIAL_LATITUDE, -1));
// Gets a random number from 1 to numberOfLocations.
int startLocationIdx = NUMBER_OF_LOCATIONS / 2;
pathMock.incReserve(NUMBER_OF_LOCATIONS *3 + 1 +1);
pathMock.incReserve(NUMBER_OF_LOCATIONS *3 + 1 +1 - startLocationIdx);
for (int i = 0; i < NUMBER_OF_LOCATIONS - startLocationIdx; i++) {
pathMock.lineTo(0, 0);
}
@@ -118,7 +120,7 @@ public class SingleColorTrackPathPainterTest extends TrackPathPainterTestCase {
AndroidMock.replay(pathMock);
singleColorTrackPathPainter.updatePath(myTracksOverlay.getMapProjection(mockView),
myTracksOverlay.getMapViewRect(mockView), startLocationIdx, true, points, pathMock);
myTracksOverlay.getMapViewRect(mockView), startLocationIdx, points, pathMock);
AndroidMock.verify(pathMock);
}
}
@@ -40,13 +40,12 @@ public class TrackPathDescriptorDynamicSpeedTest extends TrackPathPainterTestCas
myTracksOverlay.setTrackPathPainter(painter);
int startLocationIdx = 0;
Boolean alwaysVisible = true;
assertNotNull(painter);
painter.updatePath(myTracksOverlay.getMapProjection(mockView),
myTracksOverlay.getMapViewRect(mockView), startLocationIdx, alwaysVisible,
myTracksOverlay.getMapViewRect(mockView), startLocationIdx,
myTracksOverlay.getPoints());
assertNotNull(myTracksOverlay.getTrackPathPainter().getLastPath());
painter.drawTrack(canvas);
assertNotNull(myTracksOverlay.getTrackPathPainter().hasPath());
painter.drawPath(canvas);
}
}
@@ -40,13 +40,11 @@ public class TrackPathDescriptorFixedSpeedTest extends TrackPathPainterTestCase
myTracksOverlay.setTrackPathPainter(painter);
int startLocationIdx = 0;
Boolean alwaysVisible = true;
assertNotNull(painter);
painter.updatePath(myTracksOverlay.getMapProjection(mockView),
myTracksOverlay.getMapViewRect(mockView), startLocationIdx, alwaysVisible,
myTracksOverlay.getPoints());
assertNotNull(myTracksOverlay.getTrackPathPainter().getLastPath());
painter.drawTrack(canvas);
myTracksOverlay.getMapViewRect(mockView), startLocationIdx, myTracksOverlay.getPoints());
assertNotNull(myTracksOverlay.getTrackPathPainter().hasPath());
painter.drawPath(canvas);
}
}
@@ -55,8 +55,7 @@ public class TrackPathPainterFactoryTest extends TrackPathPainterTestCase {
context, R.string.track_color_mode_key, context.getString(track_color_mode));
int startLocationIdx = 0;
Boolean alwaysVisible = true;
TrackPathPainter painter = TrackPathPainterFactory.getTrackPathPainter(context);
myTracksOverlay.setTrackPathPainter(painter);
@@ -64,9 +63,9 @@ public class TrackPathPainterFactoryTest extends TrackPathPainterTestCase {
assertTrue(c.isInstance(painter));
painter.updatePath(myTracksOverlay.getMapProjection(mockView),
myTracksOverlay.getMapViewRect(mockView), startLocationIdx, alwaysVisible,
myTracksOverlay.getMapViewRect(mockView), startLocationIdx,
myTracksOverlay.getPoints());
assertNotNull(myTracksOverlay.getTrackPathPainter().getLastPath());
painter.drawTrack(canvas);
assertNotNull(myTracksOverlay.getTrackPathPainter().hasPath());
painter.drawPath(canvas);
}
}
@@ -39,13 +39,12 @@ public class TrackPathPainterSingleColorTest extends TrackPathPainterTestCase {
myTracksOverlay.setTrackPathPainter(painter);
int startLocationIdx = 0;
Boolean alwaysVisible = true;
assertNotNull(painter);
painter.updatePath(myTracksOverlay.getMapProjection(mockView),
myTracksOverlay.getMapViewRect(mockView), startLocationIdx, alwaysVisible,
myTracksOverlay.getMapViewRect(mockView), startLocationIdx,
myTracksOverlay.getPoints());
assertNotNull(myTracksOverlay.getTrackPathPainter().getLastPath());
painter.drawTrack(canvas);
assertNotNull(myTracksOverlay.getTrackPathPainter().hasPath());
painter.drawPath(canvas);
}
}
@@ -13,20 +13,21 @@
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.services.tasks;
import android.test.AndroidTestCase;
/**
* Tests for {@link StatusAnnouncerFactory}.
* Tests for {@link AnnouncementPeriodicTaskFactory}.
* These tests require Donut+ to run.
*
* @author Rodrigo Damazio
*/
public class StatusAnnouncerFactoryTest extends AndroidTestCase {
public class AnnouncementPeriodicTaskFactoryTest extends AndroidTestCase {
public void testCreate() {
PeriodicTaskFactory factory = new StatusAnnouncerFactory();
PeriodicTaskFactory factory = new AnnouncementPeriodicTaskFactory();
PeriodicTask task = factory.create(getContext());
assertTrue(task instanceof StatusAnnouncerTask);
assertTrue(task instanceof AnnouncementPeriodicTask);
}
}
@@ -40,21 +40,21 @@ import java.util.concurrent.atomic.AtomicBoolean;
import org.easymock.Capture;
/**
* Tests for {@link StatusAnnouncerTask}.
* Tests for {@link AnnouncementPeriodicTask}.
* WARNING: I'm not responsible if your eyes start bleeding while reading this
* code. You have been warned. It's still better than no test, though.
*
* @author Rodrigo Damazio
*/
public class StatusAnnouncerTaskTest extends AndroidTestCase {
public class AnnouncementPeriodicTaskTest extends AndroidTestCase {
// Use something other than our hardcoded value
private static final Locale DEFAULT_LOCALE = Locale.KOREAN;
private static final String ANNOUNCEMENT = "I can haz cheeseburger?";
private Locale oldDefaultLocale;
private StatusAnnouncerTask task;
private StatusAnnouncerTask mockTask;
private AnnouncementPeriodicTask task;
private AnnouncementPeriodicTask mockTask;
private Capture<OnInitListener> initListenerCapture;
private Capture<PhoneStateListener> phoneListenerCapture;
private TextToSpeechDelegate ttsDelegate;
@@ -252,7 +252,7 @@ public class StatusAnnouncerTaskTest extends AndroidTestCase {
}
@UsesMocks({
StatusAnnouncerTask.class,
AnnouncementPeriodicTask.class,
StringUtils.class,
})
@Override
@@ -291,8 +291,8 @@ public class StatusAnnouncerTaskTest extends AndroidTestCase {
phoneListenerCapture = new Capture<PhoneStateListener>();
// Create a partial forwarding mock
mockTask = AndroidMock.createMock(StatusAnnouncerTask.class, getContext());
task = new StatusAnnouncerTask(getContext()) {
mockTask = AndroidMock.createMock(AnnouncementPeriodicTask.class, getContext());
task = new AnnouncementPeriodicTask(getContext()) {
@Override
protected TextToSpeech newTextToSpeech(Context ctx,
OnInitListener onInitListener) {
@@ -322,32 +322,6 @@ public class StatusAnnouncerTaskTest extends AndroidTestCase {
OnInitListener ttsInitListener = initListenerCapture.getValue();
assertNotNull(ttsInitListener);
expect(tts.isLanguageAvailable(DEFAULT_LOCALE))
.andStubReturn(TextToSpeech.LANG_AVAILABLE);
expect(tts.setLanguage(DEFAULT_LOCALE))
.andReturn(TextToSpeech.LANG_AVAILABLE);
expect(tts.setSpeechRate(StatusAnnouncerTask.TTS_SPEECH_RATE))
.andReturn(TextToSpeech.SUCCESS);
AndroidMock.replay(tts);
ttsInitListener.onInit(TextToSpeech.SUCCESS);
AndroidMock.verify(mockTask, tts);
}
public void testStart_languageNotSupported() {
doStart();
OnInitListener ttsInitListener = initListenerCapture.getValue();
assertNotNull(ttsInitListener);
expect(tts.isLanguageAvailable(DEFAULT_LOCALE))
.andStubReturn(TextToSpeech.LANG_NOT_SUPPORTED);
expect(tts.setLanguage(Locale.ENGLISH))
.andReturn(TextToSpeech.LANG_AVAILABLE);
expect(tts.setSpeechRate(StatusAnnouncerTask.TTS_SPEECH_RATE))
.andReturn(TextToSpeech.SUCCESS);
AndroidMock.replay(tts);
ttsInitListener.onInit(TextToSpeech.SUCCESS);
@@ -393,6 +367,10 @@ public class StatusAnnouncerTaskTest extends AndroidTestCase {
// Put task in "ready" state
startTask(TextToSpeech.SUCCESS);
expect(tts.isLanguageAvailable(DEFAULT_LOCALE)).andStubReturn(TextToSpeech.LANG_AVAILABLE);
expect(tts.setLanguage(DEFAULT_LOCALE)).andReturn(TextToSpeech.LANG_AVAILABLE);
expect(tts.setSpeechRate(AnnouncementPeriodicTask.TTS_SPEECH_RATE)).andReturn(TextToSpeech.SUCCESS);
// Expect actual announcement call
expect(tts.speak(
eq(ANNOUNCEMENT), eq(TextToSpeech.QUEUE_FLUSH),
@@ -401,7 +379,7 @@ public class StatusAnnouncerTaskTest extends AndroidTestCase {
// Run the announcement
AndroidMock.replay(tts);
task.runWithStatistics(stats);
task.announce(stats);
AndroidMock.verify(mockTask, tts);
}
@@ -411,7 +389,7 @@ public class StatusAnnouncerTaskTest extends AndroidTestCase {
// Run the announcement
AndroidMock.replay(tts);
task.runWithStatistics(null);
task.run(null);
AndroidMock.verify(mockTask, tts);
}
@@ -424,7 +402,7 @@ public class StatusAnnouncerTaskTest extends AndroidTestCase {
AndroidMock.replay(tts);
PhoneStateListener phoneListener = phoneListenerCapture.getValue();
phoneListener.onCallStateChanged(TelephonyManager.CALL_STATE_OFFHOOK, null);
task.runWithStatistics(null);
task.run(null);
AndroidMock.verify(mockTask, tts);
}
@@ -441,7 +419,7 @@ public class StatusAnnouncerTaskTest extends AndroidTestCase {
phoneListener.onCallStateChanged(TelephonyManager.CALL_STATE_RINGING, null);
// Run the announcement - this should do nothing.
task.runWithStatistics(null);
task.run(null);
AndroidMock.verify(mockTask, tts);
}
@@ -455,7 +433,7 @@ public class StatusAnnouncerTaskTest extends AndroidTestCase {
AndroidMock.replay(tts);
PhoneStateListener phoneListener = phoneListenerCapture.getValue();
phoneListener.onCallStateChanged(TelephonyManager.CALL_STATE_RINGING, null);
task.runWithStatistics(null);
task.run(null);
AndroidMock.verify(mockTask, tts);
}
@@ -475,12 +453,12 @@ public class StatusAnnouncerTaskTest extends AndroidTestCase {
// Run the announcement
AndroidMock.replay(tts);
task.runWithStatistics(null);
task.run(null);
AndroidMock.verify(mockTask, tts);
}
/**
* Tests {@link StatusAnnouncerTask#getAnnounceTime(long)} with time zero.
* Tests {@link AnnouncementPeriodicTask#getAnnounceTime(long)} with time zero.
*/
public void testGetAnnounceTime_time_zero() {
long time = 0; // 0 seconds
@@ -488,7 +466,7 @@ public class StatusAnnouncerTaskTest extends AndroidTestCase {
}
/**
* Tests {@link StatusAnnouncerTask#getAnnounceTime(long)} with time one.
* Tests {@link AnnouncementPeriodicTask#getAnnounceTime(long)} with time one.
*/
public void testGetAnnounceTime_time_one() {
long time = 1 * 1000; // 1 second
@@ -496,7 +474,7 @@ public class StatusAnnouncerTaskTest extends AndroidTestCase {
}
/**
* Tests {@link StatusAnnouncerTask#getAnnounceTime(long)} with singular
* Tests {@link AnnouncementPeriodicTask#getAnnounceTime(long)} with singular
* numbers with the hour unit.
*/
public void testGetAnnounceTime_singular_has_hour() {
@@ -505,7 +483,7 @@ public class StatusAnnouncerTaskTest extends AndroidTestCase {
}
/**
* Tests {@link StatusAnnouncerTask#getAnnounceTime(long)} with plural numbers
* Tests {@link AnnouncementPeriodicTask#getAnnounceTime(long)} with plural numbers
* with the hour unit.
*/
public void testGetAnnounceTime_plural_has_hour() {
@@ -514,7 +492,7 @@ public class StatusAnnouncerTaskTest extends AndroidTestCase {
}
/**
* Tests {@link StatusAnnouncerTask#getAnnounceTime(long)} with singular
* Tests {@link AnnouncementPeriodicTask#getAnnounceTime(long)} with singular
* numbers without the hour unit.
*/
public void testGetAnnounceTime_singular_no_hour() {
@@ -523,7 +501,7 @@ public class StatusAnnouncerTaskTest extends AndroidTestCase {
}
/**
* Tests {@link StatusAnnouncerTask#getAnnounceTime(long)} with plural numbers
* Tests {@link AnnouncementPeriodicTask#getAnnounceTime(long)} with plural numbers
* without the hour unit.
*/
public void testGetAnnounceTime_plural_no_hour() {
@@ -10,7 +10,7 @@ import junit.framework.TestCase;
/**
* Test the the function of the TripStatisticsBuilder class.
*
*
* @author Sandor Dornbush
*/
public class TripStatisticsBuilderTest extends TestCase {
@@ -25,55 +25,49 @@ public class TripStatisticsBuilderTest extends TestCase {
public void testAddLocationSimple() throws Exception {
builder = new TripStatisticsBuilder(1000);
TripStatistics stats = builder.getStatistics();
TripStatistics tripStatistics = builder.getTripStatistics();
assertEquals(0.0, builder.getSmoothedElevation());
assertEquals(Double.POSITIVE_INFINITY, stats.getMinElevation());
assertEquals(Double.NEGATIVE_INFINITY, stats.getMaxElevation());
assertEquals(0.0, stats.getMaxSpeed());
assertEquals(Double.POSITIVE_INFINITY, stats.getMinGrade());
assertEquals(Double.NEGATIVE_INFINITY, stats.getMaxGrade());
assertEquals(0.0, stats.getTotalElevationGain());
assertEquals(0, stats.getMovingTime());
assertEquals(0.0, stats.getTotalDistance());
assertEquals(Double.POSITIVE_INFINITY, tripStatistics.getMinElevation());
assertEquals(Double.NEGATIVE_INFINITY, tripStatistics.getMaxElevation());
assertEquals(0.0, tripStatistics.getMaxSpeed());
assertEquals(Double.POSITIVE_INFINITY, tripStatistics.getMinGrade());
assertEquals(Double.NEGATIVE_INFINITY, tripStatistics.getMaxGrade());
assertEquals(0.0, tripStatistics.getTotalElevationGain());
assertEquals(0, tripStatistics.getMovingTime());
assertEquals(0.0, tripStatistics.getTotalDistance());
for (int i = 0; i < 100; i++) {
Location l = new Location("test");
l.setAccuracy(1.0f);
l.setLongitude(45.0);
Location location = new Location("test");
location.setAccuracy(1.0f);
location.setLongitude(45.0);
// Going up by 5 meters each time.
l.setAltitude(i);
// Moving by .1% of a degree latitude.
l.setLatitude(i * .001);
l.setSpeed(11.1f);
// Going up by 1 meter each time.
location.setAltitude(i);
location.setLatitude(i * .001); // Moving by .001 degree latitude (111 meters)
location.setSpeed(11.1f);
// Each time slice is 10 seconds.
long time = 1000 + 10000 * i;
l.setTime(time);
boolean moving = builder.addLocation(l, time);
location.setTime(time);
boolean moving = builder.addLocation(location, time);
assertEquals((i != 0), moving);
stats = builder.getStatistics();
assertEquals(10000 * i, stats.getTotalTime());
assertEquals(10000 * i, stats.getMovingTime());
assertEquals(i, builder.getSmoothedElevation(),
Constants.ELEVATION_SMOOTHING_FACTOR / 2);
assertEquals(0.0, stats.getMinElevation());
assertEquals(i, stats.getMaxElevation(),
Constants.ELEVATION_SMOOTHING_FACTOR / 2);
assertEquals(i, stats.getTotalElevationGain(),
Constants.ELEVATION_SMOOTHING_FACTOR);
tripStatistics = builder.getTripStatistics();
assertEquals(10000 * i, tripStatistics.getTotalTime());
assertEquals(10000 * i, tripStatistics.getMovingTime());
assertEquals(i, builder.getSmoothedElevation(), Constants.ELEVATION_SMOOTHING_FACTOR / 2);
assertEquals(0.0, tripStatistics.getMinElevation());
assertEquals(i, tripStatistics.getMaxElevation(), Constants.ELEVATION_SMOOTHING_FACTOR / 2);
assertEquals(i, tripStatistics.getTotalElevationGain(), Constants.ELEVATION_SMOOTHING_FACTOR);
if (i > Constants.SPEED_SMOOTHING_FACTOR) {
assertEquals(11.1f, stats.getMaxSpeed(), 0.1);
assertEquals(11.1f, tripStatistics.getMaxSpeed(), 0.1);
}
if ((i > Constants.GRADE_SMOOTHING_FACTOR)
&& (i > Constants.ELEVATION_SMOOTHING_FACTOR)) {
assertEquals(0.009, stats.getMinGrade(), 0.0001);
assertEquals(0.009, stats.getMaxGrade(), 0.0001);
if (i > Constants.DISTANCE_SMOOTHING_FACTOR && i > Constants.ELEVATION_SMOOTHING_FACTOR) {
// 1 m / 111 m = .009
assertEquals(0.009, tripStatistics.getMinGrade(), 0.0001);
assertEquals(0.009, tripStatistics.getMaxGrade(), 0.0001);
}
// 1 degree = 111 km
// 1 timeslice = 0.001 degree = 111 m
assertEquals(111.0 * i, stats.getTotalDistance(), 100);
assertEquals(111.0 * i, tripStatistics.getTotalDistance(), 100);
}
}
@@ -86,7 +80,7 @@ public class TripStatisticsBuilderTest extends TestCase {
for (int j = 0; j < 100; j++) {
assertEquals(0.0, builder.updateElevation(elevation));
assertEquals(elevation, builder.getSmoothedElevation());
TripStatistics data = builder.getStatistics();
TripStatistics data = builder.getTripStatistics();
assertEquals(elevation, data.getMinElevation());
assertEquals(elevation, data.getMaxElevation());
assertEquals(0.0, data.getTotalElevationGain());
@@ -104,80 +98,71 @@ public class TripStatisticsBuilderTest extends TestCase {
} else {
expectedGain = 1.0;
}
assertEquals(expectedGain,
builder.updateElevation(i));
assertEquals(expectedGain, builder.updateElevation(i));
assertEquals(i, builder.getSmoothedElevation(), 20);
TripStatistics data = builder.getStatistics();
TripStatistics data = builder.getTripStatistics();
assertEquals(0.0, data.getMinElevation(), 0.0);
assertEquals(i, data.getMaxElevation(),
Constants.ELEVATION_SMOOTHING_FACTOR);
assertEquals(i, data.getTotalElevationGain(),
Constants.ELEVATION_SMOOTHING_FACTOR);
assertEquals(i, data.getMaxElevation(), Constants.ELEVATION_SMOOTHING_FACTOR);
assertEquals(i, data.getTotalElevationGain(), Constants.ELEVATION_SMOOTHING_FACTOR);
}
}
public void testGradeSimple() throws Exception {
for (double i = 0; i < 1000; i++) {
// The value of the elevation does not matter. This is just to fill the
// The value of the elevation does not matter. This is just to fill the
// buffer.
builder.updateElevation(i);
builder.updateGrade(100, 100);
if ((i > Constants.GRADE_SMOOTHING_FACTOR)
&& (i > Constants.ELEVATION_SMOOTHING_FACTOR)) {
assertEquals(1.0, builder.getStatistics().getMaxGrade());
assertEquals(1.0, builder.getStatistics().getMinGrade());
if ((i > Constants.GRADE_SMOOTHING_FACTOR) && (i > Constants.ELEVATION_SMOOTHING_FACTOR)) {
assertEquals(1.0, builder.getTripStatistics().getMaxGrade());
assertEquals(1.0, builder.getTripStatistics().getMinGrade());
}
}
for (double i = 0; i < 1000; i++) {
// The value of the elevation does not matter. This is just to fill the
// The value of the elevation does not matter. This is just to fill the
// buffer.
builder.updateElevation(i);
builder.updateGrade(100, -100);
if ((i > Constants.GRADE_SMOOTHING_FACTOR)
&& (i > Constants.ELEVATION_SMOOTHING_FACTOR)) {
assertEquals(1.0, builder.getStatistics().getMaxGrade());
assertEquals(-1.0, builder.getStatistics().getMinGrade());
if ((i > Constants.GRADE_SMOOTHING_FACTOR) && (i > Constants.ELEVATION_SMOOTHING_FACTOR)) {
assertEquals(1.0, builder.getTripStatistics().getMaxGrade());
assertEquals(-1.0, builder.getTripStatistics().getMinGrade());
}
}
}
public void testGradeIgnoreShort() throws Exception {
for (double i = 0; i < 100; i++) {
// The value of the elevation does not matter. This is just to fill the
// The value of the elevation does not matter. This is just to fill the
// buffer.
builder.updateElevation(i);
builder.updateGrade(1, 100);
assertEquals(Double.NEGATIVE_INFINITY, builder.getStatistics().getMaxGrade());
assertEquals(Double.POSITIVE_INFINITY, builder.getStatistics().getMinGrade());
assertEquals(Double.NEGATIVE_INFINITY, builder.getTripStatistics().getMaxGrade());
assertEquals(Double.POSITIVE_INFINITY, builder.getTripStatistics().getMinGrade());
}
}
public void testUpdateSpeedIncludeZero() {
for (int i = 0; i < 1000; i++) {
builder.updateSpeed(i + 1000, 0.0, i, 4.0);
assertEquals(0.0, builder.getStatistics().getMaxSpeed());
assertEquals((i + 1) * 1000, builder.getStatistics().getMovingTime());
assertEquals(0.0, builder.getTripStatistics().getMaxSpeed());
}
}
public void testUpdateSpeedIngoreErrorCode() {
builder.updateSpeed(12345000, 128.0, 12344000, 0.0);
assertEquals(0.0, builder.getStatistics().getMaxSpeed());
assertEquals(1000, builder.getStatistics().getMovingTime());
assertEquals(0.0, builder.getTripStatistics().getMaxSpeed());
}
public void testUpdateSpeedIngoreLargeAcceleration() {
builder.updateSpeed(12345000, 100.0, 12344000, 1.0);
assertEquals(0.0, builder.getStatistics().getMaxSpeed());
assertEquals(1000, builder.getStatistics().getMovingTime());
assertEquals(0.0, builder.getTripStatistics().getMaxSpeed());
}
public void testUpdateSpeed() {
for (int i = 0; i < 1000; i++) {
builder.updateSpeed(i + 1000, 4.0, i, 4.0);
assertEquals((i + 1) * 1000, builder.getStatistics().getMovingTime());
if (i > Constants.SPEED_SMOOTHING_FACTOR) {
assertEquals(4.0, builder.getStatistics().getMaxSpeed());
assertEquals(4.0, builder.getTripStatistics().getMaxSpeed());
}
}
}