deleted Tracker app test-suite

This commit is contained in:
Peter Siegmund committed 2015-02-10 09:45:24 +01:00
1 parent cca54ea5d8
commit c2b904ca85
27 files changed
-1213

No files matched your search

@@ -1,10 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="src" path="gen"/>
<classpathentry combineaccessrules="false" kind="src" path="/com.sap.sailing.android.tracking.app"/>
<classpathentry kind="con" path="com.android.ide.eclipse.adt.ANDROID_FRAMEWORK"/>
<classpathentry exported="true" kind="con" path="com.android.ide.eclipse.adt.LIBRARIES"/>
<classpathentry exported="true" kind="con" path="com.android.ide.eclipse.adt.DEPENDENCIES"/>
<classpathentry kind="output" path="bin/classes"/>
</classpath>
@@ -1,34 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>com.sap.sailing.android.tracking.app.test</name>
<comment></comment>
<projects>
<project>com.sap.sailing.android.tracking.app</project>
</projects>
<buildSpec>
<buildCommand>
<name>com.android.ide.eclipse.adt.ResourceManagerBuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>com.android.ide.eclipse.adt.PreCompilerBuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>com.android.ide.eclipse.adt.ApkBuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>com.android.ide.eclipse.adt.AndroidNature</nature>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>
@@ -1,4 +0,0 @@
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6
org.eclipse.jdt.core.compiler.compliance=1.6
org.eclipse.jdt.core.compiler.source=1.6
@@ -1,19 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.sap.sailing.android.tracking.app.test"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="14" />
<instrumentation
android:name="android.test.InstrumentationTestRunner"
android:targetPackage="com.sap.sailing.android.tracking.app" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<uses-library android:name="android.test.runner" />
</application>
</manifest>
@@ -1,6 +0,0 @@
/** Automatically generated file. DO NOT MODIFY */
package com.sap.sailing.android.tracking.app.test;
public final class BuildConfig {
public final static boolean DEBUG = true;
}
@@ -1,19 +0,0 @@
/* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* aapt tool from the resource data it found. It
* should not be modified by hand.
*/
package com.sap.sailing.android.tracking.app.test;
public final class R {
public static final class attr {
}
public static final class drawable {
public static final int ic_launcher=0x7f020000;
}
public static final class string {
public static final int app_name=0x7f030000;
}
}
@@ -1,20 +0,0 @@
# To enable ProGuard in your project, edit project.properties
# to define the proguard.config property as described in that file.
#
# Add project specific ProGuard rules here.
# By default, the flags in this file are appended to flags specified
# in ${sdk.dir}/tools/proguard/proguard-android.txt
# You can edit the include path and order by changing the ProGuard
# include property in project.properties.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# Add any project specific keep options here:
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
@@ -1,14 +0,0 @@
# This file is automatically generated by Android Tools.
# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
#
# This file must be checked in Version Control Systems.
#
# To customize properties used by the Ant build system edit
# "ant.properties", and override values to adapt the script to your
# project structure.
#
# To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home):
#proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt
# Project target.
target=android-21
Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

@@ -1,6 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Com.sap.sailing.android.tracking.app.testTest</string>
</resources>
@@ -1,343 +0,0 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* 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.sap.sailing.android.tracking.app.test;
import android.app.Activity;
import android.app.Application;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.IBinder;
import android.test.ActivityInstrumentationTestCase;
import android.test.ActivityTestCase;
import android.test.mock.MockApplication;
import android.view.Window;
/**
* This class provides isolated testing of a single activity. The activity under test will
* be created with minimal connection to the system infrastructure, and you can inject mocked or
* wrappered versions of many of Activity's dependencies. Most of the work is handled
* automatically here by {@link #setUp} and {@link #tearDown}.
*
* <p>If you prefer a functional test, see {@link android.test.ActivityInstrumentationTestCase}.
*
* <p>It must be noted that, as a true unit test, your Activity will not be running in the
* normal system and will not participate in the normal interactions with other Activities.
* The following methods should not be called in this configuration - most of them will throw
* exceptions:
* <ul>
* <li>{@link android.app.Activity#createPendingResult(int, Intent, int)}</li>
* <li>{@link android.app.Activity#startActivityIfNeeded(Intent, int)}</li>
* <li>{@link android.app.Activity#startActivityFromChild(Activity, Intent, int)}</li>
* <li>{@link android.app.Activity#startNextMatchingActivity(Intent)}</li>
* <li>{@link android.app.Activity#getCallingActivity()}</li>
* <li>{@link android.app.Activity#getCallingPackage()}</li>
* <li>{@link android.app.Activity#createPendingResult(int, Intent, int)}</li>
* <li>{@link android.app.Activity#getTaskId()}</li>
* <li>{@link android.app.Activity#isTaskRoot()}</li>
* <li>{@link android.app.Activity#moveTaskToBack(boolean)}</li>
* <li>{@link android.app.Activity#setPersistent(boolean)}</li>
* </ul>
*
* <p>The following methods may be called but will not do anything. For test purposes, you can use
* the methods {@link #getStartedActivityIntent()} and {@link #getStartedActivityRequest()} to
* inspect the parameters that they were called with.
* <ul>
* <li>{@link android.app.Activity#startActivity(Intent)}</li>
* <li>{@link android.app.Activity#startActivityForResult(Intent, int)}</li>
* </ul>
*
* <p>The following methods may be called but will not do anything. For test purposes, you can use
* the methods {@link #isFinishCalled()} and {@link #getFinishedActivityRequest()} to inspect the
* parameters that they were called with.
* <ul>
* <li>{@link android.app.Activity#finish()}</li>
* <li>{@link android.app.Activity#finishFromChild(Activity child)}</li>
* <li>{@link android.app.Activity#finishActivity(int requestCode)}</li>
* </ul>
*
*/
public abstract class ActivityUnitTestCase<T extends Activity>
extends ActivityTestCase {
private Class<T> mActivityClass;
private Context mActivityContext;
private Application mApplication;
private MockParent mMockParent;
private boolean mAttached = false;
private boolean mCreated = false;
public ActivityUnitTestCase(Class<T> activityClass) {
mActivityClass = activityClass;
}
@Override
public T getActivity() {
return (T) super.getActivity();
}
@Override
protected void setUp() throws Exception {
super.setUp();
// default value for target context, as a default
mActivityContext = getInstrumentation().getTargetContext();
}
/**
* Start the activity under test, in the same way as if it was started by
* {@link android.content.Context#startActivity Context.startActivity()}, providing the
* arguments it supplied. When you use this method to start the activity, it will automatically
* be stopped by {@link #tearDown}.
*
* <p>This method will call onCreate(), but if you wish to further exercise Activity life
* cycle methods, you must call them yourself from your test case.
*
* <p><i>Do not call from your setUp() method. You must call this method from each of your
* test methods.</i>
*
* @param intent The Intent as if supplied to {@link android.content.Context#startActivity}.
* @param savedInstanceState The instance state, if you are simulating this part of the life
* cycle. Typically null.
* @param lastNonConfigurationInstance This Object will be available to the
* Activity if it calls {@link android.app.Activity#getLastNonConfigurationInstance()}.
* Typically null.
* @return Returns the Activity that was created
*/
protected T startActivity(Intent intent, Bundle savedInstanceState,
Object lastNonConfigurationInstance) {
assertFalse("Activity already created", mCreated);
if (!mAttached) {
assertNotNull(mActivityClass);
setActivity(null);
T newActivity = null;
try {
IBinder token = null;
if (mApplication == null) {
setApplication(new MockApplication());
}
// ComponentName cn = new ComponentName(mActivityClass.getPackage().getName(),
// mActivityClass.getName());
ComponentName cn = new ComponentName(getInstrumentation().getTargetContext(), mActivityClass);
intent.setComponent(cn);
ActivityInfo info = new ActivityInfo();
CharSequence title = mActivityClass.getName();
mMockParent = new MockParent();
String id = null;
newActivity = (T) getInstrumentation().newActivity(mActivityClass, mActivityContext,
token, mApplication, intent, info, title, mMockParent, id,
lastNonConfigurationInstance);
} catch (Exception e) {
assertNotNull(newActivity);
}
assertNotNull(newActivity);
setActivity(newActivity);
mAttached = true;
}
T result = getActivity();
if (result != null) {
getInstrumentation().callActivityOnCreate(getActivity(), savedInstanceState);
mCreated = true;
}
return result;
}
@Override
protected void tearDown() throws Exception {
setActivity(null);
// Scrub out members - protects against memory leaks in the case where someone
// creates a non-static inner class (thus referencing the test case) and gives it to
// someone else to hold onto
scrubClass(ActivityInstrumentationTestCase.class);
super.tearDown();
}
/**
* Set the application for use during the test. You must call this function before calling
* {@link #startActivity}. If your test does not call this method,
* @param application The Application object that will be injected into the Activity under test.
*/
public void setApplication(Application application) {
mApplication = application;
}
/**
* If you wish to inject a Mock, Isolated, or otherwise altered context, you can do so
* here. You must call this function before calling {@link #startActivity}. If you wish to
* obtain a real Context, as a building block, use getInstrumentation().getTargetContext().
*/
public void setActivityContext(Context activityContext) {
mActivityContext = activityContext;
}
/**
* This method will return the value if your Activity under test calls
* {@link android.app.Activity#setRequestedOrientation}.
*/
public int getRequestedOrientation() {
if (mMockParent != null) {
return mMockParent.mRequestedOrientation;
}
return 0;
}
/**
* This method will return the launch intent if your Activity under test calls
* {@link android.app.Activity#startActivity(Intent)} or
* {@link android.app.Activity#startActivityForResult(Intent, int)}.
* @return The Intent provided in the start call, or null if no start call was made.
*/
public Intent getStartedActivityIntent() {
if (mMockParent != null) {
return mMockParent.mStartedActivityIntent;
}
return null;
}
/**
* This method will return the launch request code if your Activity under test calls
* {@link android.app.Activity#startActivityForResult(Intent, int)}.
* @return The request code provided in the start call, or -1 if no start call was made.
*/
public int getStartedActivityRequest() {
if (mMockParent != null) {
return mMockParent.mStartedActivityRequest;
}
return 0;
}
/**
* This method will notify you if the Activity under test called
* {@link android.app.Activity#finish()},
* {@link android.app.Activity#finishFromChild(Activity)}, or
* {@link android.app.Activity#finishActivity(int)}.
* @return Returns true if one of the listed finish methods was called.
*/
public boolean isFinishCalled() {
if (mMockParent != null) {
return mMockParent.mFinished;
}
return false;
}
/**
* This method will return the request code if the Activity under test called
* {@link android.app.Activity#finishActivity(int)}.
* @return The request code provided in the start call, or -1 if no finish call was made.
*/
public int getFinishedActivityRequest() {
if (mMockParent != null) {
return mMockParent.mFinishedActivityRequest;
}
return 0;
}
/**
* This mock Activity represents the "parent" activity. By injecting this, we allow the user
* to call a few more Activity methods, including:
* <ul>
* <li>{@link android.app.Activity#getRequestedOrientation()}</li>
* <li>{@link android.app.Activity#setRequestedOrientation(int)}</li>
* <li>{@link android.app.Activity#finish()}</li>
* <li>{@link android.app.Activity#finishActivity(int requestCode)}</li>
* <li>{@link android.app.Activity#finishFromChild(Activity child)}</li>
* </ul>
*
* TODO: Make this overrideable, and the unit test can look for calls to other methods
*/
private static class MockParent extends Activity {
public int mRequestedOrientation = 0;
public Intent mStartedActivityIntent = null;
public int mStartedActivityRequest = -1;
public boolean mFinished = false;
public int mFinishedActivityRequest = -1;
/**
* Implementing in the parent allows the user to call this function on the tested activity.
*/
@Override
public void setRequestedOrientation(int requestedOrientation) {
mRequestedOrientation = requestedOrientation;
}
/**
* Implementing in the parent allows the user to call this function on the tested activity.
*/
@Override
public int getRequestedOrientation() {
return mRequestedOrientation;
}
/**
* By returning null here, we inhibit the creation of any "container" for the window.
*/
@Override
public Window getWindow() {
return null;
}
/**
* By defining this in the parent, we allow the tested activity to call
* <ul>
* <li>{@link android.app.Activity#startActivity(Intent)}</li>
* <li>{@link android.app.Activity#startActivityForResult(Intent, int)}</li>
* </ul>
*/
@Override
public void startActivityFromChild(Activity child, Intent intent, int requestCode) {
mStartedActivityIntent = intent;
mStartedActivityRequest = requestCode;
}
/**
* By defining this in the parent, we allow the tested activity to call
* <ul>
* <li>{@link android.app.Activity#finish()}</li>
* <li>{@link android.app.Activity#finishFromChild(Activity child)}</li>
* </ul>
*/
@Override
public void finishFromChild(Activity child) {
mFinished = true;
}
/**
* By defining this in the parent, we allow the tested activity to call
* <ul>
* <li>{@link android.app.Activity#finishActivity(int requestCode)}</li>
* </ul>
*/
@Override
public void finishActivityFromChild(Activity child, int requestCode) {
mFinished = true;
mFinishedActivityRequest = requestCode;
}
}
}
@@ -1,67 +0,0 @@
package com.sap.sailing.android.tracking.app.test;
import com.sap.sailing.android.tracking.app.valueobjects.CheckinData;
import com.sap.sailing.android.tracking.app.valueobjects.CompetitorInfo;
import com.sap.sailing.android.tracking.app.valueobjects.EventInfo;
import com.sap.sailing.android.tracking.app.valueobjects.LeaderboardInfo;
import junit.framework.TestCase;
public class CheckinDataTest extends TestCase {
private CheckinData checkinData;
@Override
protected void setUp() throws Exception {
checkinData = new CheckinData();
checkinData.leaderboardName = "lt";
checkinData.eventId = "et";
checkinData.eventName = "ent";
checkinData.eventStartDateStr = "123";
checkinData.eventEndDateStr = "456";
checkinData.eventFirstImageUrl = "http://1.2.3.4/test.png";
checkinData.eventServerUrl = "http://5.6.7.8";
checkinData.checkinURL = "http://9.1.2.3/checkin";
checkinData.competitorCountryCode = "DE";
checkinData.competitorName = "cn";
checkinData.competitorNationality = "GER";
checkinData.competitorSailId = "SAIL 1";
checkinData.competitorId = "1-2-3-4";
checkinData.deviceUid = "0011223344";
super.setUp();
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
}
public void testGetEvent()
{
EventInfo event = checkinData.getEvent();
assertEquals("et", event.id);
assertEquals("ent", event.name);
assertEquals(123, event.startMillis);
assertEquals(456, event.endMillis);
assertEquals("http://1.2.3.4/test.png", event.imageUrl);
assertEquals("http://5.6.7.8", event.server);
}
public void testGetCompetitor()
{
CompetitorInfo competitor = checkinData.getCompetitor();
assertEquals("DE", competitor.countryCode);
assertEquals("cn", competitor.name);
assertEquals("GER", competitor.nationality);
assertEquals("SAIL 1", competitor.sailId);
assertEquals("1-2-3-4", competitor.id);
}
public void testGetLeaderboard()
{
LeaderboardInfo leaderboard = checkinData.getLeaderboard();
assertEquals("lt", leaderboard.name);
}
}
@@ -1,44 +0,0 @@
package com.sap.sailing.android.tracking.app.test;
import com.sap.sailing.android.tracking.app.R;
import com.sap.sailing.android.tracking.app.utils.DatabaseHelper;
import android.app.Activity;
import android.content.Intent;
import android.support.v4.app.FragmentManager;
import android.view.ContextThemeWrapper;
public class DatabaseCallsTest extends ActivityUnitTestCase<Activity> {
private Intent mStartIntent;
public DatabaseCallsTest() {
super(Activity.class);
}
@Override
protected void setUp() throws Exception {
super.setUp();
mStartIntent = new Intent(Intent.ACTION_MAIN);
startActivity(mStartIntent, null, null);
DatabaseTestHelper.deleteAllEventsFromDB(getActivity());
}
public void testDeleteRegatta()
{
DatabaseTestHelper.createNewRegattaInDBAndReturnEventRowId(getActivity(), "TEST-EVENT",
"123-456-789", "TEST-LEADERBOARD", "TEST-COMPETITOR", "TEST-DIGEST1");
DatabaseTestHelper.createNewRegattaInDBAndReturnEventRowId(getActivity(), "TEST-EVENT 2",
"234-567-890", "TEST-LEADERBOARD 2", "TEST-COMPETITOR 2", "TEST-DIGEST2");
DatabaseHelper.getInstance().deleteRegattaFromDatabase(getActivity(), "TEST-DIGEST1");
assertEquals(1, DatabaseTestHelper.getNumberOfEventsFromDB(getActivity()));
//TODO: Continue, ensure context is not null
}
}
@@ -1,156 +0,0 @@
package com.sap.sailing.android.tracking.app.test;
import java.util.ArrayList;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import com.sap.sailing.android.shared.logging.ExLog;
import com.sap.sailing.android.tracking.app.provider.AnalyticsContract.Competitor;
import com.sap.sailing.android.tracking.app.provider.AnalyticsContract.Event;
import com.sap.sailing.android.tracking.app.provider.AnalyticsContract.EventGpsFixesJoined;
import com.sap.sailing.android.tracking.app.provider.AnalyticsContract.Leaderboard;
import com.sap.sailing.android.tracking.app.provider.AnalyticsContract.SensorGps;
import com.sap.sailing.android.tracking.app.valueobjects.GpsFix;
/**
* Testing helper methods
* @author Lukas Zielinski
*
*/
public class DatabaseTestHelper {
static final String TAG = DatabaseTestHelper.class.getName();
static public void deleteAllGpsFixesFromDB(Context context)
{
ContentResolver cr = context.getContentResolver();
cr.delete(SensorGps.CONTENT_URI, null, null);
ExLog.i(context, TAG, "deleteAllGpsFixesFromDB");
}
static public ArrayList<GpsFix> getAllGpsFixesFromDB(Context context)
{
ArrayList<GpsFix> result = new ArrayList<GpsFix>();
String selectionClause = SensorGps.GPS_SYNCED + " = 0";
// differs from trackingService projectionClause, taking event_id from sensor_gps.event_id,
// because event does not exist.
String projectionClauseStr = "sensor_gps.event_id as _eid,sensor_gps.gps_time,sensor_gps.gps_latitude,"
+ "sensor_gps.gps_longitude,sensor_gps.gps_speed,sensor_gps.gps_bearing,sensor_gps.gps_synced,"
+ "events.event_server,sensor_gps._id as _gid";
ContentResolver cr = context.getContentResolver();
Cursor cursor = cr.query(EventGpsFixesJoined.CONTENT_URI, projectionClauseStr.split(","), selectionClause, null, null);
while (cursor.moveToNext()) {
GpsFix gpsFix = new GpsFix();
for (int i = 0; i < cursor.getColumnCount(); i++)
{
System.out.println(cursor.getColumnName(i) + " -~> " + cursor.getString(i));
}
gpsFix.id = cursor.getInt(cursor.getColumnIndex("_gid"));
gpsFix.timestamp = cursor.getLong(cursor.getColumnIndex(SensorGps.GPS_TIME));
gpsFix.latitude = cursor.getDouble(cursor.getColumnIndex(SensorGps.GPS_LATITUDE));
gpsFix.longitude = cursor.getDouble(cursor.getColumnIndex(SensorGps.GPS_LONGITUDE));
gpsFix.speed = cursor.getDouble(cursor.getColumnIndex(SensorGps.GPS_SPEED));
gpsFix.course = cursor.getDouble(cursor.getColumnIndex(SensorGps.GPS_BEARING));
gpsFix.synced = cursor.getInt(cursor.getColumnIndex(SensorGps.GPS_SYNCED));
gpsFix.host = cursor.getString(cursor.getColumnIndex(Event.EVENT_SERVER));
gpsFix.eventId = cursor.getString(cursor.getColumnIndex("_eid"));
result.add(gpsFix);
}
cursor.close();
ExLog.i(context, TAG, "getAllGpsFixesFromDB: " + result);
return result;
}
static public int getNumberOfEventsFromDB(Context context)
{
ContentResolver cr = context.getContentResolver();
Cursor cursor = cr.query(Event.CONTENT_URI, null, null, null, null);
int result = cursor.getCount();
cursor.close();
return result;
}
static public void deleteAllEventsFromDB(Context context)
{
ContentResolver cr = context.getContentResolver();
cr.delete(Event.CONTENT_URI, null, null);
ExLog.i(context, TAG, "deleteAllEventsFromDB");
}
public static void createNewGpsFixInDatabase(Context context, long eventId, double lat, double lon, double accuracy, long timestamp)
{
ContentResolver cr = context.getContentResolver();
ContentValues cv = new ContentValues();
cv.put(SensorGps.GPS_LATITUDE, lat);
cv.put(SensorGps.GPS_LONGITUDE, lon);
cv.put(SensorGps.GPS_ACCURACY, accuracy);
cv.put(SensorGps.GPS_TIME, timestamp);
cv.put(SensorGps.GPS_EVENT_FK, eventId);
cv.put(SensorGps.GPS_SYNCED, 0);
cr.insert(SensorGps.CONTENT_URI, cv);
}
public static long createNewEventInDBAndReturnItsId(Context context, String eventName, String eventId, String checkinDigest)
{
ContentResolver cr = context.getContentResolver();
ContentValues cv = new ContentValues();
cv.put(Event.EVENT_NAME, eventName);
cv.put(Event.EVENT_ID, eventId);
cv.put(Event.EVENT_SERVER, "127.0.0.1");
cv.put(Event.EVENT_CHECKIN_DIGEST, checkinDigest);
Uri uri = cr.insert(Event.CONTENT_URI, cv);
return ContentUris.parseId(uri);
}
public static long createNewRegattaInDBAndReturnEventRowId(Context context, String eventName,
String eventId, String leaderboardName, String competitorName, String checkinDigest) {
long leaderboardRowId = createNewLeaderboardInDBAndReturnItsId(context, leaderboardName, checkinDigest);
long eventRowId = createNewEventInDBAndReturnItsId(context, eventName, eventId, leaderboardRowId, checkinDigest);
createNewCompetitorInDBAndReturnItsId(context, competitorName, leaderboardRowId, checkinDigest);
return eventRowId;
}
private static long createNewEventInDBAndReturnItsId(Context context, String eventName, String eventId, long leaderboardRowId, String checkinDigest)
{
ContentResolver cr = context.getContentResolver();
ContentValues cv = new ContentValues();
cv.put(Event.EVENT_NAME, eventName);
cv.put(Event.EVENT_ID, eventId);
cv.put(Event.EVENT_SERVER, "127.0.0.1");
cv.put(Event.EVENT_CHECKIN_DIGEST, checkinDigest);
Uri uri = cr.insert(Event.CONTENT_URI, cv);
return ContentUris.parseId(uri);
}
private static long createNewLeaderboardInDBAndReturnItsId(Context context, String leaderboardName, String checkinDigest)
{
ContentResolver cr = context.getContentResolver();
ContentValues cv = new ContentValues();
cv.put(Leaderboard.LEADERBOARD_NAME, leaderboardName);
cv.put(Leaderboard.LEADERBOARD_CHECKIN_DIGEST, checkinDigest);
Uri uri = cr.insert(Leaderboard.CONTENT_URI, cv);
return ContentUris.parseId(uri);
}
private static long createNewCompetitorInDBAndReturnItsId(Context context,
String competitorDisplayName, long leaderboardRowId, String checkinDigest) {
ContentResolver cr = context.getContentResolver();
ContentValues cv = new ContentValues();
cv.put(Competitor.COMPETITOR_DISPLAY_NAME, competitorDisplayName);
cv.put(Competitor.COMPETITOR_CHECKIN_DIGEST, checkinDigest);
Uri uri = cr.insert(Competitor.CONTENT_URI, cv);
return ContentUris.parseId(uri);
}
}
@@ -1,50 +0,0 @@
package com.sap.sailing.android.tracking.app.test;
import android.content.Intent;
import android.support.v4.app.FragmentManager;
import android.view.ContextThemeWrapper;
import android.widget.Button;
import com.sap.sailing.android.tracking.app.R;
import com.sap.sailing.android.tracking.app.ui.activities.StartActivity;
public class StartActivityTest extends ActivityUnitTestCase<StartActivity> {
private Intent mStartIntent;
private FragmentManager fragmentManager;
public StartActivityTest() {
super(StartActivity.class);
}
@Override
protected void setUp() throws Exception {
super.setUp();
ContextThemeWrapper context = new ContextThemeWrapper(
getInstrumentation().getTargetContext(), R.style.AppTheme);
setActivityContext(context);
mStartIntent = new Intent(Intent.ACTION_MAIN);
startActivity(mStartIntent, null, null);
fragmentManager = getActivity().getSupportFragmentManager();
}
public void testHasTwoButtons() {
getInstrumentation().callActivityOnStart(getActivity());
getInstrumentation().callActivityOnResume(getActivity());
getActivity().getFragmentManager().executePendingTransactions();
fragmentManager.executePendingTransactions();
Button scanButton = (Button) getActivity().findViewById(R.id.scanQr);
Button noQRButton = (Button) getActivity().findViewById(R.id.noQrCode);
assertNotNull(getActivity());
assertNotNull(scanButton);
assertNotNull(noQRButton);
}
}
@@ -1,232 +0,0 @@
package com.sap.sailing.android.tracking.app.test;
import java.util.ArrayList;
import java.util.Date;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.os.IBinder;
import android.test.ServiceTestCase;
import com.sap.sailing.android.tracking.app.R;
import com.sap.sailing.android.tracking.app.services.TrackingService;
import com.sap.sailing.android.tracking.app.services.TrackingService.GPSQuality;
import com.sap.sailing.android.tracking.app.services.TrackingService.GPSQualityListener;
import com.sap.sailing.android.tracking.app.test.extensions.ServiceHelperTestable;
import com.sap.sailing.android.tracking.app.valueobjects.GpsFix;
public class TrackingServiceTest extends ServiceTestCase<TrackingService> {
static final String TAG = TrackingServiceTest.class.getName();
final String checkinDigest = "testDigest123";
long eventRowId;
private ServiceHelperTestable serviceHelperSpy;
public TrackingServiceTest() {
super(TrackingService.class);
}
@Override
protected void setUp() throws Exception {
super.setUp();
System.setProperty("dexmaker.dexcache", getContext().getCacheDir().toString());
DatabaseTestHelper.deleteAllGpsFixesFromDB(getContext());
DatabaseTestHelper.deleteAllEventsFromDB(getContext());
eventRowId = DatabaseTestHelper.createNewEventInDBAndReturnItsId(getContext(), "test123", "123-456", checkinDigest);
serviceHelperSpy = Mockito.mock(ServiceHelperTestable.class);
ServiceHelperTestable.injectInstance(serviceHelperSpy);
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
}
private void startService() {
Intent startIntent = new Intent();
startIntent.setClass(getContext(), TrackingService.class);
startIntent.putExtra(getContext().getString(R.string.tracking_service_checkin_digest_parameter), checkinDigest);
startIntent.setAction(getContext().getString(R.string.tracking_service_start));
startService(startIntent);
}
/**
* Test basic startup/shutdown of Service
*/
public void testStartable() {
startService();
TrackingService service = getService();
assertNotNull(service);
}
/**
* Test binding to service
*/
public void testBindable() {
Intent startIntent = new Intent();
startIntent.setClass(getContext(), TrackingService.class);
IBinder service = bindService(startIntent);
assertNotNull(service);
}
/**
* Test that location updates are stored into DB.
*
* @throws InterruptedException
*/
public void testGPSFixesStoredToDatabase() throws InterruptedException {
startService();
long timestamp = new Date().getTime();
Location location = new Location("Test");
location.setLatitude(20.0);
location.setLongitude(30.0);
location.setAccuracy(0);
location.setTime(timestamp);
location.setSpeed(12.5f);
location.setBearing(123);
getService().onLocationChanged(location);
ArrayList<GpsFix> fixes = DatabaseTestHelper.getAllGpsFixesFromDB(getContext());
assertEquals(1, fixes.size());
GpsFix fix = fixes.get(0);
assertEquals(20.0, fix.latitude);
assertEquals(30.0, fix.longitude);
assertEquals(timestamp, fix.timestamp);
assertEquals(123.0, fix.course);
assertEquals(12.5, fix.speed);
assertEquals(0, fix.synced);
assertEquals(String.valueOf(eventRowId), fix.eventId);
shutdownService();
}
/**
* ================ TEST GPS QUALITY ================
*/
public void testReportsGpsQualityGreat() {
MockGpsListener listener = Mockito.spy(new MockGpsListener());
ArgumentCaptor<GPSQuality> gpsQualityCaptor = ArgumentCaptor.forClass(GPSQuality.class);
ArgumentCaptor<Float> accuracyCaptor = ArgumentCaptor.forClass(Float.class);
ArgumentCaptor<Float> bearingCaptor = ArgumentCaptor.forClass(Float.class);
ArgumentCaptor<Float> speedCaptor = ArgumentCaptor.forClass(Float.class);
startService();
TrackingService service = getService();
service.registerGPSQualityListener(listener);
getService().onLocationChanged(getTestLocation(2, 12.5f, 123));
Mockito.verify(listener, Mockito.times(1)).gpsQualityAndAccurracyUpdated(
gpsQualityCaptor.capture(), accuracyCaptor.capture(), bearingCaptor.capture(),
speedCaptor.capture());
assertEquals(GPSQuality.great, gpsQualityCaptor.getValue());
assertEquals(2f, accuracyCaptor.getValue().floatValue());
assertEquals(123f, bearingCaptor.getValue().floatValue());
assertEquals(12.5f, speedCaptor.getValue().floatValue());
shutdownService();
}
public void testReportsGpsQualityGood() {
MockGpsListener listener = Mockito.spy(new MockGpsListener());
ArgumentCaptor<GPSQuality> gpsQualityCaptor = ArgumentCaptor.forClass(GPSQuality.class);
ArgumentCaptor<Float> accuracyCaptor = ArgumentCaptor.forClass(Float.class);
ArgumentCaptor<Float> bearingCaptor = ArgumentCaptor.forClass(Float.class);
ArgumentCaptor<Float> speedCaptor = ArgumentCaptor.forClass(Float.class);
startService();
TrackingService service = getService();
service.registerGPSQualityListener(listener);
getService().onLocationChanged(getTestLocation(12, 12.5f, 123));
Mockito.verify(listener, Mockito.times(1)).gpsQualityAndAccurracyUpdated(
gpsQualityCaptor.capture(), accuracyCaptor.capture(), bearingCaptor.capture(),
speedCaptor.capture());
assertEquals(GPSQuality.good, gpsQualityCaptor.getValue());
assertEquals(12f, accuracyCaptor.getValue().floatValue());
assertEquals(123f, bearingCaptor.getValue().floatValue());
assertEquals(12.5f, speedCaptor.getValue().floatValue());
shutdownService();
}
public void testReportsGpsQualityPoor() {
MockGpsListener listener = Mockito.spy(new MockGpsListener());
ArgumentCaptor<GPSQuality> gpsQualityCaptor = ArgumentCaptor.forClass(GPSQuality.class);
ArgumentCaptor<Float> accuracyCaptor = ArgumentCaptor.forClass(Float.class);
ArgumentCaptor<Float> bearingCaptor = ArgumentCaptor.forClass(Float.class);
ArgumentCaptor<Float> speedCaptor = ArgumentCaptor.forClass(Float.class);
startService();
TrackingService service = getService();
service.registerGPSQualityListener(listener);
getService().onLocationChanged(getTestLocation(200, 12.5f, 123));
Mockito.verify(listener, Mockito.times(1)).gpsQualityAndAccurracyUpdated(
gpsQualityCaptor.capture(), accuracyCaptor.capture(), bearingCaptor.capture(),
speedCaptor.capture());
assertEquals(GPSQuality.poor, gpsQualityCaptor.getValue());
assertEquals(200f, accuracyCaptor.getValue().floatValue());
assertEquals(123f, bearingCaptor.getValue().floatValue());
assertEquals(12.5f, speedCaptor.getValue().floatValue());
shutdownService();
}
/**
* ======= ENSURE TRANSMITTING SERVICE IS STARTED =======
*/
public void testStartsTransmittingService() {
MockGpsListener listener = Mockito.spy(new MockGpsListener());
startService();
TrackingService service = getService();
service.registerGPSQualityListener(listener);
getService().onLocationChanged(getTestLocation(1, 2f, 3));
Mockito.verify(serviceHelperSpy, Mockito.times(1)).startTransmittingService(Mockito.any(Context.class));
shutdownService();
}
/**
* ======= HELPERS =======
*/
private Location getTestLocation(float accurracy, float speed, float bearing) {
long timestamp = new Date().getTime();
Location location = new Location("Test");
location.setLatitude(20.0);
location.setLongitude(30.0);
location.setAccuracy(accurracy);
location.setTime(timestamp);
location.setSpeed(speed);
location.setBearing(bearing);
return location;
}
public class MockGpsListener implements GPSQualityListener {
@Override
public void gpsQualityAndAccurracyUpdated(GPSQuality quality, float gpsAccurracy,
float gpsBearing, float gpsSpeed) {
}
}
}
@@ -1,115 +0,0 @@
package com.sap.sailing.android.tracking.app.test;
import java.util.ArrayList;
import java.util.Date;
import org.json.JSONException;
import org.json.JSONObject;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import android.content.Context;
import android.content.Intent;
import android.test.ServiceTestCase;
import com.sap.sailing.android.shared.data.http.HttpJsonPostRequest;
import com.sap.sailing.android.shared.data.http.HttpRequest;
import com.sap.sailing.android.tracking.app.R;
import com.sap.sailing.android.tracking.app.services.TrackingService;
import com.sap.sailing.android.tracking.app.services.TransmittingService;
import com.sap.sailing.android.tracking.app.test.extensions.DatabaseHelperTestable;
import com.sap.sailing.android.tracking.app.test.extensions.NetworkHelperTestable;
import com.sap.sailing.android.tracking.app.utils.NetworkHelper.NetworkHelperFailureListener;
import com.sap.sailing.android.tracking.app.utils.NetworkHelper.NetworkHelperSuccessListener;
import com.sap.sailing.android.tracking.app.valueobjects.GpsFix;
public class TransmittingServiceTest extends ServiceTestCase<TransmittingService> {
static final String TAG = TransmittingServiceTest.class.getName();
final String eventId = "test123";
private NetworkHelperTestable networkHelperSpy;
private DatabaseHelperTestable databaseHelperMock;
public TransmittingServiceTest() {
super(TransmittingService.class);
}
@Override
protected void setUp() throws Exception {
super.setUp();
System.setProperty("dexmaker.dexcache", getContext().getCacheDir().toString());
DatabaseTestHelper.deleteAllEventsFromDB(getContext());
DatabaseTestHelper.deleteAllGpsFixesFromDB(getContext());
if (networkHelperSpy == null)
{
networkHelperSpy = Mockito.spy(new NetworkHelperTestable());
NetworkHelperTestable.injectInstance(getContext(), networkHelperSpy);
}
if (databaseHelperMock == null)
{
databaseHelperMock = Mockito.mock(DatabaseHelperTestable.class);
DatabaseHelperTestable.injectInstance(databaseHelperMock);
}
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
}
private void startService()
{
Intent startIntent = new Intent();
startIntent.setClass(getContext(), TrackingService.class);
startIntent.setAction(getContext().getString(R.string.transmitting_service_start));
startService(startIntent);
}
@SuppressWarnings("unchecked")
public void testTransmittingServiceTransmitsGpsFix() throws InterruptedException, JSONException {
long timestamp = (new Date()).getTime();
ArgumentCaptor<HttpJsonPostRequest> requestCaptor = ArgumentCaptor.forClass(HttpJsonPostRequest.class);
//ArgumentCaptor<String> urlCaptor = ArgumentCaptor.forClass(String.class);
ArrayList<GpsFix> list = new ArrayList<GpsFix>();
GpsFix fix = new GpsFix();
fix.id = 99;
fix.longitude = 12.0f;
fix.latitude = 13.0f;
fix.speed = 14.0f;
fix.course = 101.5f;
fix.eventId = "whatever";
fix.timestamp = timestamp;
fix.host = "http://127.0.0.1";
list.add(fix);
Mockito.when(databaseHelperMock.getUnsentFixes(Mockito.any(Context.class), Mockito.anyList(), Mockito.anyInt())).thenReturn(list);
startService();
Thread.sleep(3500);
Mockito.verify(networkHelperSpy, Mockito.times(1)).executeHttpJsonRequestAsnchronously(requestCaptor.capture(),
(NetworkHelperSuccessListener)Mockito.any(), (NetworkHelperFailureListener)Mockito.any());
JSONObject json = new JSONObject(requestCaptor.getValue().getRequestBody());
assertEquals(1, json.getJSONArray("fixes").length());
JSONObject jsonFix = (JSONObject)json.getJSONArray("fixes").get(0);
assertEquals(timestamp, jsonFix.getLong("timestamp"));
assertEquals(12, jsonFix.getLong("longitude"));
assertEquals(13, jsonFix.getLong("latitude"));
assertEquals(14, jsonFix.getLong("speed"));
assertEquals(101.5, jsonFix.getDouble("course"));
assertEquals("http://127.0.0.1/sailingserver/api/v1/gps_fixes", requestCaptor.getValue().getUrlAsString());
shutdownService();
}
}
@@ -1,15 +0,0 @@
package com.sap.sailing.android.tracking.app.test.extensions;
import com.sap.sailing.android.tracking.app.utils.DatabaseHelper;
public class DatabaseHelperTestable extends DatabaseHelper {
public DatabaseHelperTestable() {
super();
}
public static void injectInstance(DatabaseHelper instance) {
mInstance = instance;
}
}
@@ -1,36 +0,0 @@
package com.sap.sailing.android.tracking.app.test.extensions;
import java.lang.reflect.Field;
import java.net.URL;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import com.sap.sailing.android.shared.data.http.HttpJsonPostRequest;
public class HttpJsonPostRequestTestable extends HttpJsonPostRequest {
public HttpJsonPostRequestTestable(URL requestUrl, String body, Context context) {
super(requestUrl, body, context);
}
public JSONObject getPayloadJSON() throws NoSuchFieldException, IllegalAccessException, IllegalArgumentException, JSONException{
Class<?> clazz = getClass().getSuperclass();
Field requestBodyField = clazz.getDeclaredField("requestBody");
requestBodyField.setAccessible(true);
return new JSONObject((String)requestBodyField.get(this));
}
public URL getUrl() throws NoSuchFieldException, IllegalAccessException, IllegalArgumentException
{
Class<?> clazz = getClass().getSuperclass();
Field requestBodyField = clazz.getDeclaredField("url");
requestBodyField.setAccessible(true);
return (URL)requestBodyField.get(this);
}
}
@@ -1,13 +0,0 @@
package com.sap.sailing.android.tracking.app.test.extensions;
import android.content.Context;
import com.sap.sailing.android.tracking.app.utils.NetworkHelper;
public class NetworkHelperTestable extends NetworkHelper {
public static void injectInstance(Context context, NetworkHelper instance)
{
mContext = context;
mInstance = instance;
}
}
@@ -1,10 +0,0 @@
package com.sap.sailing.android.tracking.app.test.extensions;
import com.sap.sailing.android.tracking.app.utils.ServiceHelper;
public class ServiceHelperTestable extends ServiceHelper {
public static void injectInstance(ServiceHelper instance) {
mInstance = instance;
}
}