Removed testing code that is "All rights reserved." by Google.

This commit is contained in:
Dennis Guse
2019-07-09 22:06:29 +02:00
parent fa0b154d0d
commit 2cf77d09b2
7 changed files with 0 additions and 1138 deletions
@@ -1,314 +0,0 @@
// Copyright 2010 Google Inc. All Rights Reserved.
package com.google.android.apps.mytracks.io.file.exporter;
import com.google.android.apps.mytracks.content.MyTracksProvider;
import com.google.android.apps.mytracks.content.MyTracksProviderUtils;
import com.google.android.apps.mytracks.content.MyTracksProviderUtils.Factory;
import com.google.android.apps.mytracks.content.Track;
import com.google.android.apps.mytracks.content.Waypoint;
import com.google.android.apps.mytracks.services.TrackRecordingServiceTest.MockContext;
import com.google.android.apps.mytracks.testing.TestingProviderUtilsFactory;
import android.content.Context;
import android.location.Location;
import android.test.AndroidTestCase;
import android.test.RenamingDelegatingContext;
import android.test.mock.MockContentResolver;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import org.easymock.EasyMock;
import org.easymock.IArgumentMatcher;
import org.easymock.IMocksControl;
/**
* Tests for {@link FileTrackExporter}.
*
* @author Rodrigo Damazio
*/
public class FileTrackExporterTest extends AndroidTestCase {
private static final long TRACK_ID = 1234567L;
private static final String TRACK_NAME = "Swimming across the pacific";
private MyTracksProviderUtils myTracksProviderUtils;
private Factory oldProviderUtilsFactory;
private IMocksControl mocksControl;
private TrackWriter trackWriter;
private Track[] tracks;
private OutputStream outputStream;
private FileTrackExporter fileTrackExporter;
@Override
protected void setUp() throws Exception {
super.setUp();
MockContentResolver mockContentResolver = new MockContentResolver();
RenamingDelegatingContext targetContext = new RenamingDelegatingContext(
getContext(), getContext(), "test.");
Context context = new MockContext(mockContentResolver, targetContext);
MyTracksProvider myTracksProvider = new MyTracksProvider();
myTracksProvider.attachInfo(context, null);
mockContentResolver.addProvider(MyTracksProviderUtils.AUTHORITY, myTracksProvider);
setContext(context);
myTracksProviderUtils = MyTracksProviderUtils.Factory.get(context);
oldProviderUtilsFactory = TestingProviderUtilsFactory.installWithInstance(
myTracksProviderUtils);
mocksControl = EasyMock.createStrictControl();
trackWriter = mocksControl.createMock(TrackWriter.class);
Track track = new Track();
track.setName(TRACK_NAME);
track.setId(TRACK_ID);
tracks = new Track[] {track};
outputStream = new ByteArrayOutputStream();
TrackExporterListener trackExporterListener = new TrackExporterListener() {
@Override
public void onProgressUpdate(int number, int max) {
// Safe to ignore
}
};
fileTrackExporter = new FileTrackExporter(
myTracksProviderUtils, tracks, trackWriter, trackExporterListener);
}
@Override
protected void tearDown() throws Exception {
TestingProviderUtilsFactory.restoreOldFactory(oldProviderUtilsFactory);
super.tearDown();
}
/**
* Tests write track with an empty track.
*/
public void testWriteTrack_emptyTrack() throws Exception {
// Set expected mock behavior
trackWriter.prepare(outputStream);
trackWriter.writeHeader(tracks);
trackWriter.writeBeginTracks();
trackWriter.writeBeginTrack(tracks[0], null);
trackWriter.writeEndTrack(tracks[0], null);
trackWriter.writeEndTracks();
trackWriter.writeFooter();
trackWriter.close();
mocksControl.replay();
assertTrue(fileTrackExporter.writeTrack(outputStream));
mocksControl.verify();
}
/**
* Tests write track with invalid locations. Make sure an empty track is
* written.
*/
public void testWriteTrack_oneInvalidLocation() throws Exception {
// Add two locations
Location[] locations = { new Location("fake0"), new Location("fake1") };
fillLocations(locations);
// Make locations invalid
locations[0].setLatitude(100.0);
locations[1].setLatitude(100.0);
assertEquals(locations.length,
myTracksProviderUtils.bulkInsertTrackPoint(locations, locations.length, TRACK_ID));
// Set expected mock behavior
trackWriter.prepare(outputStream);
trackWriter.writeHeader(tracks);
trackWriter.writeBeginTracks();
trackWriter.writeBeginTrack(tracks[0], null);
trackWriter.writeEndTrack(tracks[0], null);
trackWriter.writeEndTracks();
trackWriter.writeFooter();
trackWriter.close();
mocksControl.replay();
assertTrue(fileTrackExporter.writeTrack(outputStream));
mocksControl.verify();
}
/**
* Tests write track.
*/
public void testWriteTrack() throws Exception {
// Add six locations
Location[] locations = { new Location("fake0"), new Location("fake1"), new Location("fake2"),
new Location("fake3"), new Location("fake4"), new Location("fake5") };
fillLocations(locations);
// Make location 3 invalid
locations[2].setLatitude(100.0);
assertEquals(locations.length,
myTracksProviderUtils.bulkInsertTrackPoint(locations, locations.length, TRACK_ID));
Waypoint[] waypoints = { new Waypoint(), new Waypoint(), new Waypoint() };
for (int i = 0; i < waypoints.length; i++) {
Waypoint waypoint = waypoints[i];
waypoint.setTrackId(TRACK_ID);
assertNotNull(myTracksProviderUtils.insertWaypoint(waypoint));
waypoint.setId(i + 1);
}
trackWriter.prepare(outputStream);
trackWriter.writeHeader(tracks);
// Expect reading/writing of the waypoints (except the first)
trackWriter.writeBeginWaypoints(tracks[0]);
trackWriter.writeWaypoint(waypointEq(waypoints[1]));
trackWriter.writeWaypoint(waypointEq(waypoints[2]));
trackWriter.writeEndWaypoints();
// Begin the track
trackWriter.writeBeginTracks();
trackWriter.writeBeginTrack(trackEq(tracks[0]), locationEq(locations[0]));
// Write locations 1-2
trackWriter.writeOpenSegment();
trackWriter.writeLocation(locationEq(locations[0]));
trackWriter.writeLocation(locationEq(locations[1]));
trackWriter.writeCloseSegment();
// Location 3 is not written - it's invalid
// Write locations 4-6
trackWriter.writeOpenSegment();
trackWriter.writeLocation(locationEq(locations[3]));
trackWriter.writeLocation(locationEq(locations[4]));
trackWriter.writeLocation(locationEq(locations[5]));
trackWriter.writeCloseSegment();
// End the track
trackWriter.writeEndTrack(trackEq(tracks[0]), locationEq(locations[5]));
trackWriter.writeEndTracks();
trackWriter.writeFooter();
trackWriter.close();
mocksControl.replay();
assertTrue(fileTrackExporter.writeTrack(outputStream));
mocksControl.verify();
}
/**
* Waypoint equals.
*
* @param waypoint the waypoint
*/
private Waypoint waypointEq(final Waypoint waypoint) {
EasyMock.reportMatcher(new IArgumentMatcher() {
@Override
public boolean matches(Object object) {
if (object == null || waypoint == null) {
return waypoint == object;
}
Waypoint waypoint2 = (Waypoint) object;
return waypoint.getId() == waypoint2.getId();
}
@Override
public void appendTo(StringBuffer buffer) {
buffer.append("waypointEq(");
buffer.append(waypoint);
buffer.append(")");
}
});
return null;
}
/**
* Location equals.
*
* @param location the location
*/
private Location locationEq(final Location location) {
EasyMock.reportMatcher(new IArgumentMatcher() {
@Override
public boolean matches(Object object) {
if (object == null || location == null) {
return location == object;
}
Location location2 = (Location) object;
return location.hasAccuracy() == location2.hasAccuracy()
&& (!location.hasAccuracy() || location.getAccuracy() == location2.getAccuracy())
&& location.hasAltitude() == location2.hasAltitude()
&& (!location.hasAltitude() || location.getAltitude() == location2.getAltitude())
&& location.hasBearing() == location2.hasBearing()
&& (!location.hasBearing() || location.getBearing() == location2.getBearing())
&& location.hasSpeed() == location2.hasSpeed()
&& (!location.hasSpeed() || location.getSpeed() == location2.getSpeed())
&& location.getLatitude() == location2.getLatitude()
&& location.getLongitude() == location2.getLongitude()
&& location.getTime() == location2.getTime();
}
@Override
public void appendTo(StringBuffer buffer) {
buffer.append("locationEq(");
buffer.append(location);
buffer.append(")");
}
});
return null;
}
/**
* Track equals.
*
* @param track1 the track
*/
private Track trackEq(final Track track1) {
EasyMock.reportMatcher(new IArgumentMatcher() {
@Override
public boolean matches(Object object) {
if (object == null || track1 == null) {
return track1 == object;
}
Track track2 = (Track) object;
return track1.getName().equals(track2.getName());
}
@Override
public void appendTo(StringBuffer buffer) {
buffer.append("trackEq(");
buffer.append(track1);
buffer.append(")");
}
});
return null;
}
/**
* Fills the locations.
*
* @param locations the locations
*/
private void fillLocations(Location... locations) {
assertTrue(locations.length < 90);
for (int i = 0; i < locations.length; i++) {
Location location = locations[i];
location.setLatitude(i + 1);
location.setLongitude(i + 1);
location.setTime(i + 1000);
}
}
}
@@ -1,218 +0,0 @@
// Copyright 2010 Google Inc. All Rights Reserved.
package com.google.android.apps.mytracks.io.file.exporter;
import com.google.android.apps.mytracks.content.MyTracksLocation;
import com.google.android.apps.mytracks.content.Sensor;
import com.google.android.apps.mytracks.content.Track;
import com.google.android.apps.mytracks.content.Waypoint;
import android.test.AndroidTestCase;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
/**
* Base class for track format writer tests, which sets up a fake track and
* gives auxiliary methods for verifying XML output.
*
* @author Rodrigo Damazio
*/
public abstract class TrackWriterTest extends AndroidTestCase {
// All the user-provided strings have "]]>" to ensure that proper escaping is
// being done.
protected static final String TRACK_NAME = "Home]]>";
protected static final String TRACK_CATEGORY = "Hiking";
protected static final String TRACK_DESCRIPTION = "The long ]]> journey home";
protected static final String WAYPOINT1_NAME = "point]]>1";
protected static final String WAYPOINT1_CATEGORY = "Statistics";
protected static final String WAYPOINT1_DESCRIPTION = "point 1]]>description";
protected static final String WAYPOINT2_NAME = "point]]>2";
protected static final String WAYPOINT2_CATEGORY = "Waypoint";
protected static final String WAYPOINT2_DESCRIPTION = "point 2]]>description";
private static final int BUFFER_SIZE = 10240;
protected Track track;
protected MyTracksLocation location1, location2, location3, location4;
protected Waypoint wp1, wp2;
@Override
protected void setUp() throws Exception {
super.setUp();
track = new Track();
track.setName(TRACK_NAME);
track.setCategory(TRACK_CATEGORY);
track.setDescription(TRACK_DESCRIPTION);
location1 = new MyTracksLocation("mock");
location2 = new MyTracksLocation("mock");
location3 = new MyTracksLocation("mock");
location4 = new MyTracksLocation("mock");
populateLocations(location1, location2, location3, location4);
wp1 = new Waypoint();
wp2 = new Waypoint();
wp1.setLocation(location2);
wp1.setName(WAYPOINT1_NAME);
wp1.setCategory(WAYPOINT1_CATEGORY);
wp1.setDescription(WAYPOINT1_DESCRIPTION);
wp2.setLocation(location3);
wp2.setName(WAYPOINT2_NAME);
wp2.setCategory(WAYPOINT2_CATEGORY);
wp2.setDescription(WAYPOINT2_DESCRIPTION);
}
/**
* Populates a list of locations with values.
*
* @param locations a list of locations
*/
private void populateLocations(MyTracksLocation... locations) {
for (int i = 0; i < locations.length; i++) {
MyTracksLocation location = locations[i];
location.setLatitude(i);
location.setLongitude(-i);
location.setAltitude(i * 10);
location.setBearing(i * 100);
location.setAccuracy(i * 1000);
location.setSpeed(i * 10000);
location.setTime(i * 100000);
Sensor.SensorData.Builder power = Sensor.SensorData.newBuilder().setValue(100 + i)
.setState(Sensor.SensorState.SENDING);
Sensor.SensorData.Builder cadence = Sensor.SensorData.newBuilder().setValue(200 + i)
.setState(Sensor.SensorState.SENDING);
Sensor.SensorData.Builder heartRate = Sensor.SensorData.newBuilder().setValue(300 + i)
.setState(Sensor.SensorState.SENDING);
Sensor.SensorDataSet sensorDataSet = Sensor.SensorDataSet.newBuilder().setPower(power)
.setCadence(cadence).setHeartRate(heartRate).build();
location.setSensorDataSet(sensorDataSet);
}
}
/**
* Makes the right sequence of calls to the writer in order to write the fake
* track in {@link #track}.
*
* @param trackWriter the track writer
* @return the written contents
*/
protected String writeTrack(TrackWriter trackWriter) throws Exception {
OutputStream output = new ByteArrayOutputStream(BUFFER_SIZE);
trackWriter.prepare(output);
trackWriter.writeHeader(new Track[] {track});
trackWriter.writeBeginWaypoints(track);
trackWriter.writeWaypoint(wp1);
trackWriter.writeWaypoint(wp2);
trackWriter.writeEndWaypoints();
trackWriter.writeBeginTracks();
trackWriter.writeBeginTrack(track, location1);
trackWriter.writeOpenSegment();
trackWriter.writeLocation(location1);
trackWriter.writeLocation(location2);
trackWriter.writeCloseSegment();
trackWriter.writeOpenSegment();
trackWriter.writeLocation(location3);
trackWriter.writeLocation(location4);
trackWriter.writeCloseSegment();
trackWriter.writeEndTrack(track, location4);
trackWriter.writeEndTracks();
trackWriter.writeFooter();
trackWriter.close();
return output.toString();
}
/**
* Gets the text data contained inside a tag.
*
* @param parent the parent of the tag containing the text
* @param elementName the name of the tag containing the text
* @return the text contents
*/
protected String getChildTextValue(Element parent, String elementName) {
Element child = getChildElement(parent, elementName);
assertTrue(child.hasChildNodes());
NodeList children = child.getChildNodes();
int length = children.getLength();
assertTrue(length > 0);
// The children may be a sucession of text elements, just concatenate them
StringBuilder result = new StringBuilder();
for (int i = 0; i < length; i++) {
Text textNode = (Text) children.item(i);
result.append(textNode.getNodeValue());
}
return result.toString();
}
/**
* Returns all child elements of a given parent which have the given name.
*
* @param parent the parent to get children from
* @param elementName the element name to look for
* @param expectedChildren the number of children we're expected to find
* @return a list of the found elements
*/
protected List<Element> getChildElements(Node parent, String elementName,
int expectedChildren) {
assertTrue(parent.hasChildNodes());
NodeList children = parent.getChildNodes();
int length = children.getLength();
List<Element> result = new ArrayList<Element>();
for (int i = 0; i < length; i++) {
Node childNode = children.item(i);
if (childNode.getNodeType() == Node.ELEMENT_NODE
&& childNode.getNodeName().equalsIgnoreCase(elementName)) {
result.add((Element) childNode);
}
}
assertTrue(children.toString(), result.size() == expectedChildren);
return result;
}
/**
* Returns the single child element of the given parent with the given type.
*
* @param parent the parent to get a child from
* @param elementName the name of the child to look for
* @return the child element
*/
protected Element getChildElement(Node parent, String elementName) {
return getChildElements(parent, elementName, 1).get(0);
}
/**
* Parses the given XML contents and returns a DOM {@link Document} for it.
*/
protected Document parseXmlDocument(String contents)
throws FactoryConfigurationError, ParserConfigurationException,
SAXException, IOException {
DocumentBuilderFactory builderFactory =
DocumentBuilderFactory.newInstance();
builderFactory.setCoalescing(true);
// TODO: Somehow do XML validation on Android
// builderFactory.setValidating(true);
builderFactory.setNamespaceAware(true);
builderFactory.setIgnoringComments(true);
builderFactory.setIgnoringElementContentWhitespace(true);
DocumentBuilder documentBuilder = builderFactory.newDocumentBuilder();
return documentBuilder.parse(new InputSource(new StringReader(contents)));
}
}
@@ -1,65 +0,0 @@
// Copyright 2012 Google Inc. All Rights Reserved.
package com.google.android.apps.mytracks.services;
import android.app.PendingIntent;
import android.app.Service;
import android.test.ServiceTestCase;
import android.util.Log;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* A {@link TrackRecordingService} that can be used with
* {@link ServiceTestCase}. {@link ServiceTestCase} throws a null pointer
* exception when the service calls
* {@link Service#startForeground(int, android.app.Notification)} and
* {@link Service#stopForeground(boolean)}.
* <p>
* See http://code.google.com/p/android/issues/detail?id=12122
* <p>
* Wrap these two methods in wrappers and override them.
*
* @author Jimmy Shih
*/
public class TestRecordingService extends TrackRecordingService {
private static final String TAG = TestRecordingService.class.getSimpleName();
@Override
protected void startForegroundService(PendingIntent pendingIntent, int messageId) {
try {
Method setForegroundMethod = Service.class.getMethod("setForeground", boolean.class);
setForegroundMethod.invoke(this, true);
} catch (SecurityException e) {
Log.e(TAG, "Unable to start a service in foreground", e);
} catch (NoSuchMethodException e) {
Log.e(TAG, "Unable to start a service in foreground", e);
} catch (IllegalArgumentException e) {
Log.e(TAG, "Unable to start a service in foreground", e);
} catch (IllegalAccessException e) {
Log.e(TAG, "Unable to start a service in foreground", e);
} catch (InvocationTargetException e) {
Log.e(TAG, "Unable to start a service in foreground", e);
}
}
@Override
protected void stopForegroundService() {
try {
Method setForegroundMethod = Service.class.getMethod("setForeground", boolean.class);
setForegroundMethod.invoke(this, false);
} catch (SecurityException e) {
Log.e(TAG, "Unable to start a service in foreground", e);
} catch (NoSuchMethodException e) {
Log.e(TAG, "Unable to start a service in foreground", e);
} catch (IllegalArgumentException e) {
Log.e(TAG, "Unable to start a service in foreground", e);
} catch (IllegalAccessException e) {
Log.e(TAG, "Unable to start a service in foreground", e);
} catch (InvocationTargetException e) {
Log.e(TAG, "Unable to start a service in foreground", e);
}
}
}
@@ -1,117 +0,0 @@
/*
* Copyright 2009 Google Inc. All Rights Reserved.
*/
package com.google.android.apps.mytracks.stats;
import junit.framework.TestCase;
/**
* Test for the DoubleBuffer class.
*
* @author Sandor Dornbush
*/
public class DoubleBufferTest extends TestCase {
/**
* Tests that the constructor leaves the buffer in a valid state.
*/
public void testConstructor() {
DoubleBuffer buffer = new DoubleBuffer(10);
assertFalse(buffer.isFull());
assertEquals(0.0, buffer.getAverage());
double[] averageAndVariance = buffer.getAverageAndVariance();
assertEquals(0.0, averageAndVariance[0]);
assertEquals(0.0, averageAndVariance[1]);
}
/**
* Simple test with 10 of the same values.
*/
public void testBasic() {
DoubleBuffer buffer = new DoubleBuffer(10);
for (int i = 0; i < 9; i++) {
buffer.setNext(1.0);
assertFalse(buffer.isFull());
assertEquals(1.0, buffer.getAverage());
double[] averageAndVariance = buffer.getAverageAndVariance();
assertEquals(1.0, averageAndVariance[0]);
assertEquals(0.0, averageAndVariance[1]);
}
buffer.setNext(1);
assertTrue(buffer.isFull());
assertEquals(1.0, buffer.getAverage());
double[] averageAndVariance = buffer.getAverageAndVariance();
assertEquals(1.0, averageAndVariance[0]);
assertEquals(0.0, averageAndVariance[1]);
}
/**
* Tests with 5 entries of -10 and 5 entries of 10.
*/
public void testSplit() {
DoubleBuffer buffer = new DoubleBuffer(10);
for (int i = 0; i < 5; i++) {
buffer.setNext(-10);
assertFalse(buffer.isFull());
assertEquals(-10.0, buffer.getAverage());
double[] averageAndVariance = buffer.getAverageAndVariance();
assertEquals(-10.0, averageAndVariance[0]);
assertEquals(0.0, averageAndVariance[1]);
}
for (int i = 1; i < 5; i++) {
buffer.setNext(10);
assertFalse(buffer.isFull());
double expectedAverage = ((i * 10.0) - 50.0) / (i + 5);
assertEquals(buffer.toString(),
expectedAverage, buffer.getAverage(), 0.01);
double[] averageAndVariance = buffer.getAverageAndVariance();
assertEquals(expectedAverage, averageAndVariance[0]);
}
buffer.setNext(10);
assertTrue(buffer.isFull());
assertEquals(0.0, buffer.getAverage());
double[] averageAndVariance = buffer.getAverageAndVariance();
assertEquals(0.0, averageAndVariance[0]);
assertEquals(100.0, averageAndVariance[1]);
}
/**
* Tests that reset leaves the buffer in a valid state.
*/
public void testReset() {
DoubleBuffer buffer = new DoubleBuffer(10);
for (int i = 0; i < 100; i++) {
buffer.setNext(i);
}
assertTrue(buffer.isFull());
buffer.reset();
assertFalse(buffer.isFull());
assertEquals(0.0, buffer.getAverage());
double[] averageAndVariance = buffer.getAverageAndVariance();
assertEquals(0.0, averageAndVariance[0]);
assertEquals(0.0, averageAndVariance[1]);
}
/**
* Tests that if a lot of items are inserted the smoothing and looping works.
*/
public void testLoop() {
DoubleBuffer buffer = new DoubleBuffer(10);
for (int i = 0; i < 1000; i++) {
buffer.setNext(i);
assertEquals(i >= 9, buffer.isFull());
if (i > 10) {
assertEquals(i - 4.5, buffer.getAverage());
}
}
}
}
@@ -1,63 +0,0 @@
/**
* Copyright 2009 Google Inc. All Rights Reserved.
*/
package com.google.android.apps.mytracks.stats;
import junit.framework.TestCase;
import java.util.Random;
/**
* This class test the ExtremityMonitor class.
*
* @author Sandor Dornbush
*/
public class ExtremityMonitorTest extends TestCase {
public ExtremityMonitorTest(String name) {
super(name);
}
public void testInitialize() {
ExtremityMonitor monitor = new ExtremityMonitor();
assertEquals(Double.POSITIVE_INFINITY, monitor.getMin());
assertEquals(Double.NEGATIVE_INFINITY, monitor.getMax());
}
public void testSimple() {
ExtremityMonitor monitor = new ExtremityMonitor();
assertTrue(monitor.update(0));
assertTrue(monitor.update(1));
assertEquals(0.0, monitor.getMin());
assertEquals(1.0, monitor.getMax());
assertFalse(monitor.update(1));
assertFalse(monitor.update(0.5));
}
/**
* Throws a bunch of random numbers between [0,1] at the monitor.
*/
public void testRandom() {
ExtremityMonitor monitor = new ExtremityMonitor();
Random random = new Random(42);
for (int i = 0; i < 1000; i++) {
monitor.update(random.nextDouble());
}
assertTrue(monitor.getMin() < 0.1);
assertTrue(monitor.getMax() < 1.0);
assertTrue(monitor.getMin() >= 0.0);
assertTrue(monitor.getMax() > 0.9);
}
public void testReset() {
ExtremityMonitor monitor = new ExtremityMonitor();
assertTrue(monitor.update(0));
assertTrue(monitor.update(1));
monitor.reset();
assertEquals(Double.POSITIVE_INFINITY, monitor.getMin());
assertEquals(Double.NEGATIVE_INFINITY, monitor.getMax());
assertTrue(monitor.update(0));
assertTrue(monitor.update(1));
assertEquals(0.0, monitor.getMin());
assertEquals(1.0, monitor.getMax());
}
}
@@ -1,323 +0,0 @@
// Copyright 2009 Google Inc. All Rights Reserved.
package com.google.android.apps.mytracks.stats;
import com.google.android.apps.mytracks.util.PreferencesUtils;
import android.location.Location;
import junit.framework.TestCase;
/**
* Tests {@link TripStatisticsUpdater}.
*
* @author Sandor Dornbush
*/
public class TripStatisticsUpdaterTest extends TestCase {
private static final long ONE_SECOND = 1000;
private static final long TEN_SECONDS = 10 * ONE_SECOND;
private static final float MOVING_SPEED = 11.1f;
private TripStatisticsUpdater tripStatisticsUpdater = null;
@Override
protected void setUp() throws Exception {
tripStatisticsUpdater = new TripStatisticsUpdater(System.currentTimeMillis());
}
/**
* Sends some moving and waiting locations and then checks the statistics.
*/
public void testAddLocationSimple() {
long startTime = 1000;
tripStatisticsUpdater = new TripStatisticsUpdater(startTime);
TripStatistics tripStatistics = tripStatisticsUpdater.getTripStatistics();
assertEquals(0.0, tripStatisticsUpdater.getSmoothedElevation());
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());
// Time:0 ~ 99; Location:0 ~ 99
addMoveLocations(100, startTime, tripStatistics, 0, 0);
// Time:100 ~ 199; Location:99
addWaitLocations(100, startTime, tripStatistics, 100, 99);
// Time:200 ~ 299; Location:100 ~ 199
addMoveLocations(100, startTime, tripStatistics, 200, 100);
// Time:300 ~ 399; Location:199
addWaitLocations(100, startTime, tripStatistics, 300, 199);
// Time:400 ~ 499; Location:200 ~ 299
addMoveLocations(100, startTime, tripStatistics, 400, 200);
// Time:500 ~ 599; Location:299
addWaitLocations(100, startTime, tripStatistics, 500, 299);
// Time:600 ~ 699; Location:300 ~ 399
addMoveLocations(100, startTime, tripStatistics, 600, 300);
}
/**
* Sends some disordered locations and checks the statistics. In some
* situation, especially when signal is not good, MyTracks may receive such
* data.
*/
public void testAddLocation_disorderedLocatiions() {
long startTime = 1000;
tripStatisticsUpdater = new TripStatisticsUpdater(startTime);
TripStatistics tripStatistics = tripStatisticsUpdater.getTripStatistics();
addLocations(5, startTime, tripStatistics, 0, 0);
addLocations(5, startTime, tripStatistics, 5, 0);
addLocations(5, startTime, tripStatistics, 10, -5);
addLocations(5, startTime, tripStatistics, 15, 5);
}
/**
* Tests {@link TripStatisticsUpdater#updateElevation(double)} with constant
* elevations.
*/
public void testElevationSimple() throws Exception {
for (double elevation = 0; elevation < 1000; elevation += 10) {
tripStatisticsUpdater = new TripStatisticsUpdater(System.currentTimeMillis());
for (int i = 0; i < 100; i++) {
tripStatisticsUpdater.updateElevation(elevation);
assertEquals(elevation, tripStatisticsUpdater.getSmoothedElevation());
TripStatistics tripStatistics = tripStatisticsUpdater.getTripStatistics();
assertEquals(elevation, tripStatistics.getMinElevation());
assertEquals(elevation, tripStatistics.getMaxElevation());
assertEquals(elevation, tripStatistics.getTotalElevationGain());
}
}
}
/**
* Tests {@link TripStatisticsUpdater#updateGrade(double, double)} with
* elevation gain.
*/
public void testElevationGain() throws Exception {
for (double i = 0; i < 1000; i++) {
tripStatisticsUpdater.updateElevation(i);
assertEquals(i, tripStatisticsUpdater.getSmoothedElevation(),
TripStatisticsUpdater.ELEVATION_SMOOTHING_FACTOR / 2);
TripStatistics data = tripStatisticsUpdater.getTripStatistics();
assertEquals(0.0, data.getMinElevation());
assertEquals(i, data.getMaxElevation(), TripStatisticsUpdater.ELEVATION_SMOOTHING_FACTOR / 2);
assertEquals(
i, data.getTotalElevationGain(), TripStatisticsUpdater.ELEVATION_SMOOTHING_FACTOR);
}
}
/**
* Tests {@link TripStatisticsUpdater#updateGrade(double, double)} with grade
* of 1 and -1.
*/
public void testGradeSimple() throws Exception {
for (double i = 0; i < 1000; i++) {
tripStatisticsUpdater.updateGrade(100.0, 100.0);
assertEquals(1.0, tripStatisticsUpdater.getTripStatistics().getMaxGrade());
assertEquals(1.0, tripStatisticsUpdater.getTripStatistics().getMinGrade());
}
for (double i = 0; i < 1000; i++) {
tripStatisticsUpdater.updateGrade(100.0, -100.0);
if (i >= TripStatisticsUpdater.GRADE_SMOOTHING_FACTOR) {
assertEquals(1.0, tripStatisticsUpdater.getTripStatistics().getMaxGrade());
// add 0.1 delta since changing min grade from 1 to -1
assertEquals(-1.0, tripStatisticsUpdater.getTripStatistics().getMinGrade(), 0.1);
}
}
}
/**
* Tests {@link TripStatisticsUpdater#updateGrade(double, double)} with
* distance of 1. The grade should get ignored.
*/
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
* elevation buffer.
*/
tripStatisticsUpdater.updateElevation(i);
tripStatisticsUpdater.updateGrade(1.0, 100.0);
assertEquals(
Double.NEGATIVE_INFINITY, tripStatisticsUpdater.getTripStatistics().getMaxGrade());
assertEquals(
Double.POSITIVE_INFINITY, tripStatisticsUpdater.getTripStatistics().getMinGrade());
}
}
/**
* Tests {@link TripStatisticsUpdater#updateSpeed(long, double, long, double)}
* with speed of zero.
*/
public void testUpdateSpeedIncludeZero() {
for (int i = 0; i < 1000; i++) {
tripStatisticsUpdater.updateSpeed(i + ONE_SECOND, 0.0, i, 4.0);
assertEquals(0.0, tripStatisticsUpdater.getTripStatistics().getMaxSpeed());
}
}
/**
* Tests {@link TripStatisticsUpdater#updateSpeed(long, double, long, double)}
* with the error code 128. The speed should get ignored.
*/
public void testUpdateSpeedIngoreErrorCode() {
long time = 12344000;
tripStatisticsUpdater.updateSpeed(time + ONE_SECOND, 128.0, time, 0.0);
assertEquals(0.0, tripStatisticsUpdater.getTripStatistics().getMaxSpeed());
}
/**
* Tests {@link TripStatisticsUpdater#updateSpeed(long, double, long, double)}
* with a large speed change. The speed should get ignored.
*/
public void testUpdateSpeedIngoreLargeAcceleration() {
long time = 12344000;
tripStatisticsUpdater.updateSpeed(time + ONE_SECOND, 100.0, time, 1.0);
assertEquals(0.0, tripStatisticsUpdater.getTripStatistics().getMaxSpeed());
}
/**
* Tests {@link TripStatisticsUpdater#updateSpeed(long, double, long, double)}
* with constant speed.
*/
public void testUpdateSpeed() {
double speed = 4.0;
for (int i = 0; i < 1000; i++) {
tripStatisticsUpdater.updateSpeed(i + ONE_SECOND, speed, i, speed);
assertEquals(speed, tripStatisticsUpdater.getTripStatistics().getMaxSpeed());
}
}
/**
* Sends some locations which keeping moving and checks the statistics.
*
* @param points number of locations
* @param startTime start time of this track
* @param tripStatistics the TripStatistics object
* @param timeOffset offset to start time
* @param locationOffset location offset to start
*/
private void addMoveLocations(int points, long startTime, TripStatistics tripStatistics,
int timeOffset, int locationOffset) {
for (int i = 0; i < points; i++) {
// Going up by 1 meter each time.
// Moving by .001 degree latitude (111 meters).
// Each time slice is 10 seconds.
Location location = getLocation(i + locationOffset, (i + locationOffset) * .001, MOVING_SPEED,
startTime + (timeOffset + i) * TEN_SECONDS);
tripStatisticsUpdater.addLocation(location, PreferencesUtils.RECORDING_DISTANCE_INTERVAL_DEFAULT);
tripStatistics = tripStatisticsUpdater.getTripStatistics();
assertEquals((timeOffset + i) * TEN_SECONDS, tripStatistics.getTotalTime());
assertEquals((locationOffset + i) * TEN_SECONDS, tripStatistics.getMovingTime());
assertEquals(i + locationOffset, tripStatisticsUpdater.getSmoothedElevation(),
TripStatisticsUpdater.ELEVATION_SMOOTHING_FACTOR / 2);
if (i + locationOffset >= TripStatisticsUpdater.ELEVATION_SMOOTHING_FACTOR) {
assertEquals(0.0, tripStatistics.getMinElevation());
assertEquals(i + locationOffset, tripStatistics.getMaxElevation(),
TripStatisticsUpdater.ELEVATION_SMOOTHING_FACTOR / 2);
assertEquals(i + locationOffset, tripStatistics.getTotalElevationGain(),
TripStatisticsUpdater.ELEVATION_SMOOTHING_FACTOR);
}
if (i + locationOffset >= TripStatisticsUpdater.SPEED_SMOOTHING_FACTOR) {
assertEquals(MOVING_SPEED, tripStatistics.getMaxSpeed(), 0.1);
}
// If there are only moving locations in the track.
if (locationOffset == 0 && (i + locationOffset) >= TripStatisticsUpdater.RUN_SMOOTHING_FACTOR
+ TripStatisticsUpdater.GRADE_SMOOTHING_FACTOR) {
// 0.5 m / 111 m = .0045
assertEquals(0.0045, tripStatistics.getMinGrade(), 0.0001);
// 1 m / 111 m = .009
assertEquals(0.009, tripStatistics.getMaxGrade(), 0.0001);
}
assertEquals((i + locationOffset) * 111.0, tripStatistics.getTotalDistance(),
(i + locationOffset) * 111.0 * 0.01);
}
}
/**
* Sends some locations which are not moving and checks the statistics.
*
* @param points number of locations
* @param startTime start time of this track
* @param tripStatistics the TripStatistics object
* @param timeOffset offset to start time
* @param locationOffset location offset to start
*/
private void addWaitLocations(int points, long startTime, TripStatistics tripStatistics,
int timeOffset, int locationOffset) {
for (int i = 0; i < points; i++) {
Location location = getLocation(
locationOffset, locationOffset * .001, 0, startTime + (i + timeOffset) * TEN_SECONDS);
tripStatisticsUpdater.addLocation(location, PreferencesUtils.RECORDING_DISTANCE_INTERVAL_DEFAULT);
tripStatistics = tripStatisticsUpdater.getTripStatistics();
assertEquals((i + timeOffset) * TEN_SECONDS, tripStatistics.getTotalTime());
assertEquals((locationOffset) * TEN_SECONDS, tripStatistics.getMovingTime());
assertEquals(locationOffset, tripStatisticsUpdater.getSmoothedElevation(),
TripStatisticsUpdater.ELEVATION_SMOOTHING_FACTOR / 2);
assertEquals(0.0, tripStatistics.getMinElevation());
assertEquals(locationOffset, tripStatistics.getMaxElevation(),
TripStatisticsUpdater.ELEVATION_SMOOTHING_FACTOR / 2);
assertEquals(locationOffset, tripStatistics.getTotalElevationGain(),
TripStatisticsUpdater.ELEVATION_SMOOTHING_FACTOR);
assertEquals(MOVING_SPEED, tripStatistics.getMaxSpeed(), 0.1);
assertEquals(MOVING_SPEED, tripStatistics.getMaxSpeed(), 0.1);
assertEquals(
locationOffset * 111.0, tripStatistics.getTotalDistance(), locationOffset * 111.0 * 0.01);
}
}
/**
* Sends some locations which are moving and checks some simple policy.
*
* @param points number of locations
* @param startTime start time of this track
* @param tripStatistics the TripStatistics object
* @param timeOffset offset to start time
* @param locationOffset location offset to start
*/
private void addLocations(int points, long startTime, TripStatistics tripStatistics,
int timeOffset, int locationOffset) {
for (int i = 0; i < points; i++) {
// 99999 means a speed should bigger than given speed.
Location location = getLocation(i + locationOffset, (i + locationOffset) * .001, 99999,
startTime + (timeOffset + i) * TEN_SECONDS);
tripStatisticsUpdater.addLocation(location, PreferencesUtils.RECORDING_DISTANCE_INTERVAL_DEFAULT);
tripStatistics = tripStatisticsUpdater.getTripStatistics();
assertTrue(tripStatistics.getMovingTime() <= tripStatistics.getTotalTime());
assertTrue(tripStatistics.getAverageSpeed() <= tripStatistics.getAverageMovingSpeed());
assertTrue(tripStatistics.getAverageMovingSpeed() <= tripStatistics.getMaxSpeed());
assertTrue(tripStatistics.getStopTime() >= tripStatistics.getStartTime());
}
}
/**
* Creates a location and returns it.
*
* @param altitude altitude of location
* @param latitude latitude of location
* @param speed speed of location
* @param time time of location
*/
private Location getLocation(double altitude, double latitude, float speed, long time) {
Location location = new Location("test");
location.setAccuracy(1.0f);
location.setLongitude(45.0);
location.setAltitude(altitude);
location.setLatitude(latitude);
location.setSpeed(speed);
location.setTime(time);
return location;
}
}
@@ -1,38 +0,0 @@
// Copyright 2010 Google Inc. All Rights Reserved.
package com.google.android.apps.mytracks.testing;
import com.google.android.apps.mytracks.content.MyTracksProviderUtils;
import com.google.android.apps.mytracks.content.MyTracksProviderUtils.Factory;
import android.content.Context;
/**
* A fake factory for {@link MyTracksProviderUtils} which always returns a
* predefined instance.
*
* @author Rodrigo Damazio
*/
public class TestingProviderUtilsFactory extends Factory {
private MyTracksProviderUtils instance;
public TestingProviderUtilsFactory(MyTracksProviderUtils instance) {
this.instance = instance;
}
@Override
protected MyTracksProviderUtils newForContext(Context context) {
return instance;
}
public static Factory installWithInstance(MyTracksProviderUtils instance) {
Factory oldFactory = Factory.getInstance();
Factory factory = new TestingProviderUtilsFactory(instance);
MyTracksProviderUtils.Factory.overrideInstance(factory);
return oldFactory;
}
public static void restoreOldFactory(Factory factory) {
MyTracksProviderUtils.Factory.overrideInstance(factory);
}
}