From 5505a387f23f7e384c03382646d5a32e7db79479 Mon Sep 17 00:00:00 2001 From: Ajay Panicker Date: Tue, 25 Oct 2016 10:37:54 -0700 Subject: [PATCH] Remove all old Bluetooth tests - Remove all old Bluetooth tests that do not compile - Change Android.mk to compile the tests as "tests" instead of "optional" Bug: 32402820 Test: Tests now compile Change-Id: Iadafae095a8ba9602a632ed55bd0208fcf64e4a8 --- tests/Android.mk | 2 +- .../android/bluetooth/gatt/GattServiceTest.java | 22 - .../bluetooth/tests/BluetoothMapContentTest.java | 876 --------------------- .../bluetooth/tests/BluetoothMapIMContentTest.java | 166 ---- .../bluetooth/tests/BluetoothMapUtilsTest.java | 113 --- .../bluetooth/tests/BluetoothMapbMessageTest.java | 570 -------------- .../bluetooth/tests/BluetoothTestUtils.java | 54 -- .../bluetooth/tests/DevicePolicyUtilsTest.java | 115 --- .../com/android/bluetooth/tests/IResultLogger.java | 34 - .../android/bluetooth/tests/ISeqStepAction.java | 13 - .../android/bluetooth/tests/ISeqStepValidator.java | 15 - .../bluetooth/tests/ITestSequenceBuilder.java | 11 - .../bluetooth/tests/ITestSequenceConfigurator.java | 17 - .../android/bluetooth/tests/MapObexLevelTest.java | 286 ------- .../android/bluetooth/tests/MapObexTestServer.java | 187 ----- .../com/android/bluetooth/tests/MapStepsConvo.java | 237 ------ .../android/bluetooth/tests/MapStepsFolder.java | 158 ---- .../com/android/bluetooth/tests/MapTestData.java | 285 ------- .../android/bluetooth/tests/MockMasInstance.java | 30 - .../android/bluetooth/tests/ObexPipeTransport.java | 89 --- .../src/com/android/bluetooth/tests/ObexTest.java | 711 ----------------- .../bluetooth/tests/ObexTestDataHandler.java | 154 ---- .../android/bluetooth/tests/ObexTestParams.java | 14 - .../android/bluetooth/tests/ObexTestServer.java | 142 ---- .../com/android/bluetooth/tests/SapServerTest.java | 608 -------------- .../com/android/bluetooth/tests/SapSocketTest.java | 174 ---- .../android/bluetooth/tests/SdpManagerTest.java | 293 ------- .../bluetooth/tests/SdpManagerTestServer.java | 339 -------- .../com/android/bluetooth/tests/SecurityTest.java | 51 -- tests/src/com/android/bluetooth/tests/SeqStep.java | 88 --- .../android/bluetooth/tests/TestResultLogger.java | 88 --- .../com/android/bluetooth/tests/TestSequencer.java | 283 ------- .../bluetooth/tests/mock/BluetoothMockContext.java | 50 -- .../tests/mock/SimpleMockContentProvider.java | 37 - .../tests/pbap/BluetoothPbapVcardManagerTest.java | 149 ---- .../tests/pbap/ContactCursorFilterTest.java | 161 ---- .../android/bluetooth/util/NumberUtilsTest.java | 43 - 37 files changed, 1 insertion(+), 6664 deletions(-) delete mode 100644 tests/src/com/android/bluetooth/gatt/GattServiceTest.java delete mode 100644 tests/src/com/android/bluetooth/tests/BluetoothMapContentTest.java delete mode 100644 tests/src/com/android/bluetooth/tests/BluetoothMapIMContentTest.java delete mode 100644 tests/src/com/android/bluetooth/tests/BluetoothMapUtilsTest.java delete mode 100755 tests/src/com/android/bluetooth/tests/BluetoothMapbMessageTest.java delete mode 100644 tests/src/com/android/bluetooth/tests/BluetoothTestUtils.java delete mode 100644 tests/src/com/android/bluetooth/tests/DevicePolicyUtilsTest.java delete mode 100644 tests/src/com/android/bluetooth/tests/IResultLogger.java delete mode 100644 tests/src/com/android/bluetooth/tests/ISeqStepAction.java delete mode 100644 tests/src/com/android/bluetooth/tests/ISeqStepValidator.java delete mode 100644 tests/src/com/android/bluetooth/tests/ITestSequenceBuilder.java delete mode 100644 tests/src/com/android/bluetooth/tests/ITestSequenceConfigurator.java delete mode 100644 tests/src/com/android/bluetooth/tests/MapObexLevelTest.java delete mode 100644 tests/src/com/android/bluetooth/tests/MapObexTestServer.java delete mode 100644 tests/src/com/android/bluetooth/tests/MapStepsConvo.java delete mode 100644 tests/src/com/android/bluetooth/tests/MapStepsFolder.java delete mode 100644 tests/src/com/android/bluetooth/tests/MapTestData.java delete mode 100644 tests/src/com/android/bluetooth/tests/MockMasInstance.java delete mode 100644 tests/src/com/android/bluetooth/tests/ObexPipeTransport.java delete mode 100644 tests/src/com/android/bluetooth/tests/ObexTest.java delete mode 100644 tests/src/com/android/bluetooth/tests/ObexTestDataHandler.java delete mode 100644 tests/src/com/android/bluetooth/tests/ObexTestParams.java delete mode 100644 tests/src/com/android/bluetooth/tests/ObexTestServer.java delete mode 100644 tests/src/com/android/bluetooth/tests/SapServerTest.java delete mode 100644 tests/src/com/android/bluetooth/tests/SapSocketTest.java delete mode 100644 tests/src/com/android/bluetooth/tests/SdpManagerTest.java delete mode 100644 tests/src/com/android/bluetooth/tests/SdpManagerTestServer.java delete mode 100644 tests/src/com/android/bluetooth/tests/SecurityTest.java delete mode 100644 tests/src/com/android/bluetooth/tests/SeqStep.java delete mode 100644 tests/src/com/android/bluetooth/tests/TestResultLogger.java delete mode 100644 tests/src/com/android/bluetooth/tests/TestSequencer.java delete mode 100644 tests/src/com/android/bluetooth/tests/mock/BluetoothMockContext.java delete mode 100644 tests/src/com/android/bluetooth/tests/mock/SimpleMockContentProvider.java delete mode 100644 tests/src/com/android/bluetooth/tests/pbap/BluetoothPbapVcardManagerTest.java delete mode 100644 tests/src/com/android/bluetooth/tests/pbap/ContactCursorFilterTest.java delete mode 100644 tests/src/com/android/bluetooth/util/NumberUtilsTest.java diff --git a/tests/Android.mk b/tests/Android.mk index e18a6969..32f0111f 100755 --- a/tests/Android.mk +++ b/tests/Android.mk @@ -2,7 +2,7 @@ LOCAL_PATH:= $(call my-dir) include $(CLEAR_VARS) # We only want this apk build for tests. -LOCAL_MODULE_TAGS := optional +LOCAL_MODULE_TAGS := tests LOCAL_CERTIFICATE := platform LOCAL_JAVA_LIBRARIES := javax.obex android.test.runner telephony-common libprotobuf-java-micro diff --git a/tests/src/com/android/bluetooth/gatt/GattServiceTest.java b/tests/src/com/android/bluetooth/gatt/GattServiceTest.java deleted file mode 100644 index 28c5a10e..00000000 --- a/tests/src/com/android/bluetooth/gatt/GattServiceTest.java +++ /dev/null @@ -1,22 +0,0 @@ - -package com.android.bluetooth.gatt; - -import android.test.AndroidTestCase; -import android.test.suitebuilder.annotation.SmallTest; - -import com.android.bluetooth.gatt.GattService; - -/** - * Test cases for {@link GattService}. - */ -public class GattServiceTest extends AndroidTestCase { - - @SmallTest - public void testParseBatchTimestamp() { - GattService service = new GattService(); - long timestampNanos = service.parseTimestampNanos(new byte[] { - -54, 7 }); - assertEquals(99700000000L, timestampNanos); - } - -} diff --git a/tests/src/com/android/bluetooth/tests/BluetoothMapContentTest.java b/tests/src/com/android/bluetooth/tests/BluetoothMapContentTest.java deleted file mode 100644 index 438ee81e..00000000 --- a/tests/src/com/android/bluetooth/tests/BluetoothMapContentTest.java +++ /dev/null @@ -1,876 +0,0 @@ -package com.android.bluetooth.tests; - -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.UnsupportedEncodingException; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Date; -import java.util.LinkedHashMap; - -import android.content.ContentResolver; -import android.content.ContentValues; -import android.content.Context; -import android.database.Cursor; -import android.net.Uri; -import android.os.Bundle; -import android.os.Debug; -import android.os.ParcelFileDescriptor; -import android.provider.BaseColumns; -import android.provider.Telephony.Mms; -import android.provider.Telephony.MmsSms; -import android.provider.Telephony.Threads; -import android.test.AndroidTestCase; -import android.util.Log; - -import com.android.bluetooth.map.BluetoothMapMasInstance; -import com.android.bluetooth.map.BluetoothMapAccountItem; -import com.android.bluetooth.map.BluetoothMapAccountLoader; -import com.android.bluetooth.map.BluetoothMapAppParams; -import com.android.bluetooth.map.BluetoothMapContent; -import com.android.bluetooth.map.BluetoothMapFolderElement; -import com.android.bluetooth.map.BluetoothMapMessageListing; -import com.android.bluetooth.map.BluetoothMapUtils; -import com.android.bluetooth.map.BluetoothMapUtils.TYPE; -import com.android.bluetooth.map.MapContact; -import com.android.bluetooth.map.SmsMmsContacts; -import com.android.bluetooth.mapapi.BluetoothMapContract; - -public class BluetoothMapContentTest extends AndroidTestCase { - - private static final String TAG = "BluetoothMapContentTest"; - - private static final boolean D = true; - - private Context mContext; - private ContentResolver mResolver; - private SmsMmsContacts mContacts = new SmsMmsContacts(); - - private BluetoothMapFolderElement mCurrentFolder; - private BluetoothMapAccountItem mAccount = null; - - private static final int MAS_ID = 0; - private static final int REMOTE_FEATURE_MASK = 0x07FFFFFF; - private static final BluetoothMapMasInstance mMasInstance = - new MockMasInstance(MAS_ID, REMOTE_FEATURE_MASK); - - - private Uri mEmailUri = null; - private Uri mEmailMessagesUri = null; - private Uri mEmailFolderUri = null; - private Uri mEmailAccountUri = null; - - static final String[] EMAIL_ACCOUNT_PROJECTION = new String[] { - BluetoothMapContract.MessageColumns.FOLDER_ID, - BluetoothMapContract.MessageColumns.ACCOUNT_ID, - }; - - private void printAccountInfo(Cursor c) { - if (D) Log.d(TAG, BluetoothMapContract.MessageColumns.ACCOUNT_ID + " : " + - c.getInt(c.getColumnIndex(BluetoothMapContract.MessageColumns.ACCOUNT_ID)) ); - } - - static final String[] BT_MESSAGE_ID_PROJECTION = new String[] { - BluetoothMapContract.MessageColumns._ID, - BluetoothMapContract.MessageColumns.DATE, - }; - - static final String[] BT_MESSAGE_PROJECTION = BluetoothMapContract.BT_MESSAGE_PROJECTION; - - static final String[] BT_ACCOUNT_PROJECTION = BluetoothMapContract.BT_ACCOUNT_PROJECTION; - - static final String[] BT_FOLDER_PROJECTION = BluetoothMapContract.BT_FOLDER_PROJECTION; - - BluetoothMapAccountLoader loader; - LinkedHashMap> mFullList; - - public BluetoothMapContentTest() { - super(); - } - - private void initTestSetup(){ - mContext = this.getContext(); - mResolver = mContext.getContentResolver(); - - // find enabled account - loader = new BluetoothMapAccountLoader(mContext); - mFullList = loader.parsePackages(false); - String accountId = getEnabledAccount(); - Uri tmpEmailUri = Uri.parse("content://com.android.email.bluetoothprovider/"); - - mEmailUri = Uri.withAppendedPath(tmpEmailUri, accountId + "/"); - mEmailMessagesUri = Uri.parse(mEmailUri + BluetoothMapContract.TABLE_MESSAGE); - mEmailFolderUri = Uri.parse(mEmailUri + BluetoothMapContract.TABLE_FOLDER); - mEmailAccountUri = Uri.parse(tmpEmailUri + BluetoothMapContract.TABLE_ACCOUNT); - - buildFolderStructure(); - - } - - public String getEnabledAccount(){ - if(D)Log.d(TAG,"getEnabledAccountItems()\n"); - String account = null; - for(BluetoothMapAccountItem app:mFullList.keySet()){ - ArrayList accountList = mFullList.get(app); - for(BluetoothMapAccountItem acc: accountList){ - mAccount = acc; - account = acc.getId(); - break; - } - } - return account; - } - - private void buildFolderStructure(){ - mCurrentFolder = new BluetoothMapFolderElement("root", null); // This will be the root element - BluetoothMapFolderElement tmpFolder; - tmpFolder = mCurrentFolder.addFolder("telecom"); // root/telecom - tmpFolder = tmpFolder.addFolder("msg"); // root/telecom/msg - if(mEmailFolderUri != null) { - addEmailFolders(tmpFolder); - } - } - - private void addEmailFolders(BluetoothMapFolderElement parentFolder) { - BluetoothMapFolderElement newFolder; - String where = BluetoothMapContract.FolderColumns.PARENT_FOLDER_ID + - " = " + parentFolder.getFolderId(); - Cursor c = mContext.getContentResolver().query(mEmailFolderUri, - BluetoothMapContract.BT_FOLDER_PROJECTION, where, null, null); - if (c != null) { - c.moveToPosition(-1); - while (c.moveToNext()) { - String name = c.getString(c.getColumnIndex(BluetoothMapContract.FolderColumns.NAME)); - long id = c.getLong(c.getColumnIndex(BluetoothMapContract.FolderColumns._ID)); - newFolder = parentFolder.addEmailFolder(name, id); - addEmailFolders(newFolder); // Use recursion to add any sub folders - } - c.close(); - } else { - if (D) Log.d(TAG, "addEmailFolders(): no elements found"); - } - } - - private BluetoothMapFolderElement getInbox() { - BluetoothMapFolderElement tmpFolderElement = null; - - tmpFolderElement = mCurrentFolder.getSubFolder("telecom"); - tmpFolderElement = tmpFolderElement.getSubFolder("msg"); - tmpFolderElement = tmpFolderElement.getSubFolder("inbox"); - return tmpFolderElement; - } - - private BluetoothMapFolderElement getOutbox() { - BluetoothMapFolderElement tmpFolderElement = null; - - tmpFolderElement = mCurrentFolder.getSubFolder("telecom"); - tmpFolderElement = tmpFolderElement.getSubFolder("msg"); - tmpFolderElement = tmpFolderElement.getSubFolder("outbox"); - return tmpFolderElement; - } - - - private String getDateTimeString(long timestamp) { - SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd'T'HHmmss"); - Date date = new Date(timestamp); - return format.format(date); // Format to YYYYMMDDTHHMMSS local time - } - - private void printCursor(Cursor c) { - StringBuilder sb = new StringBuilder(); - sb.append("\nprintCursor:\n"); - for(int i = 0; i < c.getColumnCount(); i++) { - if(c.getColumnName(i).equals(BluetoothMapContract.MessageColumns.DATE)){ - sb.append(" ").append(c.getColumnName(i)) - .append(" : ").append(getDateTimeString(c.getLong(i))).append("\n"); - } else { - sb.append(" ").append(c.getColumnName(i)) - .append(" : ").append(c.getString(i)).append("\n"); - } - } - Log.d(TAG, sb.toString()); - } - - private void dumpMessageContent(Cursor c) { - long id = c.getLong(c.getColumnIndex(BluetoothMapContract.MessageColumns._ID)); - Uri uri = Uri.parse(mEmailMessagesUri + "/" + id - + "/" + BluetoothMapContract.FILE_MSG_NO_ATTACHMENTS); - FileInputStream is = null; - ParcelFileDescriptor fd = null; - int count; - try { - fd = mResolver.openFileDescriptor(uri, "r"); - is = new FileInputStream(fd.getFileDescriptor()); - byte[] buffer = new byte[1024]; - - while((count = is.read(buffer)) != -1) { - Log.d(TAG, new String(buffer,0, count)); - } - - - } catch (FileNotFoundException e) { - Log.w(TAG, e); - } catch (IOException e) { - Log.w(TAG, e); - } - finally { - try { - if(is != null) - is.close(); - } catch (IOException e) {} - try { - if(fd != null) - fd.close(); - } catch (IOException e) {} - } - } - - /** - * Create a new message in the database outbox, based on the content of c. - * @param c - */ - private void writeMessageContent(Cursor c) { - long id = c.getLong(c.getColumnIndex(BluetoothMapContract.MessageColumns._ID)); - Uri uri = Uri.parse(mEmailMessagesUri + "/" + id + "/" - + BluetoothMapContract.FILE_MSG_NO_ATTACHMENTS); - FileInputStream is = null; - ParcelFileDescriptor fd = null; - FileOutputStream os = null; - ParcelFileDescriptor fdOut = null; - - ContentValues newMessage = new ContentValues(); - BluetoothMapFolderElement outFolder = getOutbox(); - newMessage.put(BluetoothMapContract.MessageColumns.FOLDER_ID, outFolder.getFolderId()); - // Now insert the empty message into outbox (Maybe it should be draft first, and then a move?) - // TODO: Examine if we need to set some additional flags, e.g. visable? - Uri uriOut = mResolver.insert(mEmailMessagesUri, newMessage); - int count; - try { - fd = mResolver.openFileDescriptor(uri, "r"); - is = new FileInputStream(fd.getFileDescriptor()); - fdOut = mResolver.openFileDescriptor(uri, "w"); - os = new FileOutputStream(fdOut.getFileDescriptor()); - byte[] buffer = new byte[1024]; - - while((count = is.read(buffer)) != -1) { - Log.d(TAG, new String(buffer,0, count)); - os.write(buffer, 0, count); - } - } catch (FileNotFoundException e) { - Log.w(TAG, e); - } catch (IOException e) { - Log.w(TAG, e); - } - finally { - try { - if(is != null) - is.close(); - } catch (IOException e) {} - try { - if(fd != null) - fd.close(); - } catch (IOException e) {} - try { - if(os != null) - os.close(); - } catch (IOException e) {} - try { - if(fdOut != null) - fdOut.close(); - } catch (IOException e) {} - } - } - - private void writeMessage(Cursor c) { - Log.d(TAG, "c.getCount() = " + c.getCount()); - c.moveToPosition(-1); - if (c.moveToNext()) { - writeMessageContent(c); - } - c.close(); - } - - - private void dumpCursor(Cursor c) { - Log.d(TAG, "c.getCount() = " + c.getCount()); - c.moveToPosition(-1); - while (c.moveToNext()) { - printCursor(c); - } - c.close(); - } - - private void callBluetoothProvider() { - Log.d(TAG, "**** Test call into email provider ****"); - int accountId = 0; - int mailboxId = 0; - - Log.d(TAG, "contentUri = " + mEmailMessagesUri); - - Cursor c = mResolver.query(mEmailMessagesUri, EMAIL_ACCOUNT_PROJECTION, - null, null, "_id DESC"); - if (c != null) { - Log.d(TAG, "c.getCount() = " + c.getCount()); - c.moveToPosition(-1); - while (c.moveToNext()) { - printAccountInfo(c); - mailboxId = c.getInt(c.getColumnIndex( - BluetoothMapContract.MessageColumns.FOLDER_ID)); - accountId = c.getInt(c.getColumnIndex( - BluetoothMapContract.MessageColumns.ACCOUNT_ID)); - } - c.close(); - } else { - Log.d(TAG, "query failed"); - } - - final Bundle extras = new Bundle(2); - /* TODO: find mailbox from DB */ - extras.putLong(BluetoothMapContract.EXTRA_UPDATE_FOLDER_ID, mailboxId); - extras.putLong(BluetoothMapContract.EXTRA_UPDATE_ACCOUNT_ID, accountId); - Bundle myBundle = mResolver.call(mEmailUri, BluetoothMapContract.METHOD_UPDATE_FOLDER, - null, extras); - } - - - public void testMsgListing() { - initTestSetup(); - BluetoothMapContent mBtMapContent = new BluetoothMapContent(mContext, mAccount, - mMasInstance); - BluetoothMapAppParams appParams = new BluetoothMapAppParams(); - Log.d(TAG, "**** testMsgListing **** "); - BluetoothMapFolderElement fe = getInbox(); - - if (fe != null) { - if (D) Log.d(TAG, "folder name=" + fe.getName()); - - appParams.setFilterMessageType(0x0B); - appParams.setMaxListCount(1024); - appParams.setStartOffset(0); - - BluetoothMapMessageListing msgListing = mBtMapContent.msgListing(fe, appParams); - int listCount = msgListing.getCount(); - int msgListingSize = mBtMapContent.msgListingSize(fe, appParams); - - if (listCount == msgListingSize) { - Log.d(TAG, "testMsgListing - " + listCount ); - } - else { - Log.d(TAG, "testMsgListing - None"); - } - } - else { - Log.d(TAG, "testMsgListing - failed "); - } - - } - - public void testMsgListingUnread() { - initTestSetup(); - BluetoothMapContent mBtMapContent = new BluetoothMapContent(mContext, mAccount, - mMasInstance); - BluetoothMapAppParams appParams = new BluetoothMapAppParams(); - Log.d(TAG, "**** testMsgListingUnread **** "); - BluetoothMapFolderElement fe = getInbox(); - - if (fe != null) { - - appParams.setFilterReadStatus(0x01); - appParams.setFilterMessageType(0x0B); - appParams.setMaxListCount(1024); - appParams.setStartOffset(0); - - BluetoothMapMessageListing msgListing = mBtMapContent.msgListing(fe, appParams); - - int listCount = msgListing.getCount(); - if (msgListing.getCount() > 0) { - Log.d(TAG, "testMsgListingUnread - " + listCount ); - } - else { - Log.d(TAG, "testMsgListingUnread - None"); - } - } - else { - Log.d(TAG, "testMsgListingUnread - getInbox failed "); - } - } - - public void testMsgListingWithOriginator() { - initTestSetup(); - BluetoothMapContent mBtMapContent = new BluetoothMapContent(mContext, mAccount, - mMasInstance); - BluetoothMapAppParams appParams = new BluetoothMapAppParams(); - Log.d(TAG, "**** testMsgListingUnread **** "); - BluetoothMapFolderElement fe = getInbox(); - - if (fe != null) { - - appParams.setFilterOriginator("*scsc.*"); - appParams.setFilterMessageType(0x0B); - appParams.setMaxListCount(1024); - appParams.setStartOffset(0); - - BluetoothMapMessageListing msgListing = mBtMapContent.msgListing(fe, appParams); - - int listCount = msgListing.getCount(); - if (msgListing.getCount() > 0) { - Log.d(TAG, "testMsgListingWithOriginator - " + listCount ); - } - else { - Log.d(TAG, "testMsgListingWithOriginator - None"); - } - } else { - Log.d(TAG, "testMsgListingWithOriginator - getInbox failed "); - } - } - - public void testGetMessages() { - initTestSetup(); - BluetoothMapContent mBtMapContent = new BluetoothMapContent(mContext, mAccount, - mMasInstance); - BluetoothMapAppParams appParams = new BluetoothMapAppParams(); - Log.d(TAG, "**** testGetMessages **** "); - BluetoothMapFolderElement fe = getInbox(); - - if (fe != null) { - appParams.setAttachment(0); - appParams.setCharset(BluetoothMapContent.MAP_MESSAGE_CHARSET_UTF8); - - //get message handles - Cursor c = mResolver.query(mEmailMessagesUri, BT_MESSAGE_ID_PROJECTION, - null, null, "_id DESC"); - if (c != null) { - c.moveToPosition(-1); - while (c.moveToNext()) { - Long id = c.getLong(c.getColumnIndex(BluetoothMapContract.MessageColumns._ID)); - String handle = BluetoothMapUtils.getMapHandle(id, TYPE.EMAIL); - try { - // getMessage - byte[] bytes = mBtMapContent.getMessage(handle, appParams, fe, "1.1"); - Log.d(TAG, "testGetMessages id=" + id + ", handle=" + handle + - ", length=" + bytes.length ); - String testPrint = new String(bytes); - Log.d(TAG, "testGetMessage (only dump first part):\n" + testPrint ); - } catch (UnsupportedEncodingException e) { - Log.w(TAG, e); - } finally { - - } - } - } else { - Log.d(TAG, "testGetMessages - no cursor "); - } - } else { - Log.d(TAG, "testGetMessages - getInbox failed "); - } - - } - - public void testDumpAccounts() { - initTestSetup(); - Log.d(TAG, "**** testDumpAccounts **** \n from: " + mEmailAccountUri.toString()); - Cursor c = mResolver.query(mEmailAccountUri, BT_ACCOUNT_PROJECTION, null, null, "_id DESC"); - if (c != null) { - dumpCursor(c); - } else { - Log.d(TAG, "query failed"); - } - Log.w(TAG, "testDumpAccounts(): ThreadId: " + Thread.currentThread().getId()); - - } - - public void testAccountUpdate() { - initTestSetup(); - Log.d(TAG, "**** testAccountUpdate **** \n of: " + mEmailAccountUri.toString()); - Cursor c = mResolver.query(mEmailAccountUri, BT_ACCOUNT_PROJECTION, null, null, "_id DESC"); - - if (c != null) { - c.moveToPosition(-1); - while (c.moveToNext()) { - printCursor(c); - Long id = c.getLong(c.getColumnIndex(BluetoothMapContract.AccountColumns._ID)); - int exposeFlag = c.getInt( - c.getColumnIndex(BluetoothMapContract.AccountColumns.FLAG_EXPOSE)); - String where = BluetoothMapContract.AccountColumns._ID + " = " + id; - ContentValues values = new ContentValues(); - if(exposeFlag == 1) { - values.put(BluetoothMapContract.AccountColumns.FLAG_EXPOSE, (int) 0); - } else { - values.put(BluetoothMapContract.AccountColumns.FLAG_EXPOSE, (int) 1); - } - Log.i(TAG, "Calling update() with selection: " + where + - "values(exposeFlag): " + - values.getAsInteger(BluetoothMapContract.AccountColumns.FLAG_EXPOSE)); - mResolver.update(mEmailAccountUri, values, where, null); - } - c.close(); - } - - } - - public void testDumpMessages() { - initTestSetup(); - - if (D) Log.d(TAG, "**** testDumpMessages **** \n uri=" + mEmailMessagesUri.toString()); - BluetoothMapFolderElement fe = getInbox(); - if (fe != null) - { - Cursor c = mResolver.query(mEmailMessagesUri, BT_MESSAGE_PROJECTION, - "", null, "_id DESC"); - if (c != null) { - dumpCursor(c); - } else { - if (D) Log.d(TAG, "query failed"); - } - if (D) Log.w(TAG, "dumpMessage(): ThreadId: " + Thread.currentThread().getId()); - } else { - if (D) Log.w(TAG, "dumpMessage(): ThreadId: " + Thread.currentThread().getId()); - } - } - - public void testDumpMessageContent() { - initTestSetup(); - - Log.d(TAG, "**** testDumpMessageContent **** from: " + mEmailMessagesUri.toString()); - - Cursor c = mResolver.query(mEmailMessagesUri, BT_MESSAGE_PROJECTION, null, null, "_id DESC"); - if (c != null && c.moveToNext()) { - dumpMessageContent(c); - } else { - Log.d(TAG, "query failed"); - } - Log.w(TAG, "dumpMessage(): ThreadId: " + Thread.currentThread().getId()); - } - - public void testWriteMessageContent() { - initTestSetup(); - Log.d(TAG, "**** testWriteMessageContent **** from: " + mEmailMessagesUri.toString()); - BluetoothMapFolderElement fe = getInbox(); - String where = BluetoothMapContract.MessageColumns.FOLDER_ID + " = " + fe.getFolderId(); - Cursor c = mResolver.query(mEmailMessagesUri, BT_MESSAGE_PROJECTION, where, null, "_id DESC"); - if (c != null) { - writeMessage(c); - } else { - Log.d(TAG, "query failed"); - } - Log.w(TAG, "writeMessage(): ThreadId: " + Thread.currentThread().getId()); - } - - /* - * Handle test cases - */ - private static final long HANDLE_TYPE_SMS_CDMA_MASK = (((long)0x1)<<60); - - public void testHandle() { - String handleStr = null; - Debug.startMethodTracing("str_format"); - for(long i = 0; i < 10000; i++) { - handleStr = String.format("%016X",(i | HANDLE_TYPE_SMS_CDMA_MASK)); - } - Debug.stopMethodTracing(); - Debug.startMethodTracing("getHandleString"); - for(long i = 0; i < 10000; i++) { - handleStr = BluetoothMapUtils.getLongAsString(i | HANDLE_TYPE_SMS_CDMA_MASK); - } - Debug.stopMethodTracing(); - } - - /* - * Folder test cases - */ - - public void testDumpEmailFolders() { - initTestSetup(); - Debug.startMethodTracing(); - String where = null; - Cursor c = mResolver.query(mEmailFolderUri, BT_FOLDER_PROJECTION, where, null, "_id DESC"); - if (c != null) { - dumpCursor(c); - c.close(); - } else { - Log.d(TAG, "query failed"); - } - Debug.stopMethodTracing(); - } - - public void testFolderPath() { - initTestSetup(); - Log.d(TAG, "**** testFolderPath **** "); - BluetoothMapFolderElement fe = getInbox(); - BluetoothMapFolderElement folder = fe.getFolderById(fe.getFolderId()); - if(folder == null) { - Log.d(TAG, "**** testFolderPath unable to find the folder with id: " + - fe.getFolderId()); - } - else { - Log.d(TAG, "**** testFolderPath found the folder with id: " + - fe.getFolderId() + "\nFull path: " + - folder.getFullPath()); - } - } - - public void testFolderElement() { - Log.d(TAG, "**** testFolderElement **** "); - BluetoothMapFolderElement fe = new BluetoothMapFolderElement("root", null); - fe = fe.addEmailFolder("MsG", 1); - fe.addEmailFolder("Outbox", 100); - fe.addEmailFolder("Sent", 200); - BluetoothMapFolderElement inbox = fe.addEmailFolder("Inbox", 300); - fe.addEmailFolder("Draft", 400); - fe.addEmailFolder("Deleted", 500); - inbox.addEmailFolder("keep", 301); - inbox.addEmailFolder("private", 302); - inbox.addEmailFolder("junk", 303); - - BluetoothMapFolderElement folder = fe.getFolderById(400); - assertEquals("draft", folder.getName()); - assertEquals("private", fe.getFolderById(302).getName()); - assertEquals("junk", fe.getRoot().getFolderById(303).getName()); - assertEquals("msg/inbox/keep", fe.getFolderById(301).getFullPath()); - } - - /* - * SMS test cases - */ - public void testAddSmsEntries() { - int count = 1000; - mContext = this.getContext(); - mResolver = mContext.getContentResolver(); - ContentValues values[] = new ContentValues[count]; - long date = System.currentTimeMillis(); - Log.i(TAG, "Preparing messages..."); - for (int x=0;x> 4) & 0x0f,16)); // MS-nibble first - scTimeSb.append(Integer.toString( scTimeData[i] & 0x0f,16)); - } - if(D) Log.v(TAG, "Generated time string: " + scTimeSb.toString()); - String expected = - "BEGIN:BMSG\r\n" + - "VERSION:1.0\r\n" + - "STATUS:UNREAD\r\n" + - "TYPE:SMS_GSM\r\n" + - "FOLDER:telecom/msg/inbox\r\n" + - "BEGIN:VCARD\r\n" + - "VERSION:3.0\r\n" + - "FN:Casper Bonde\r\n" + - "N:Bonde,Casper\r\n" + - "TEL:00498912345678\r\n" + - "TEL:+4587654321\r\n" + - "EMAIL:casper@email.add\r\n" + - "EMAIL:bonde@email.add\r\n" + - "END:VCARD\r\n" + - "BEGIN:BENV\r\n" + - "BEGIN:VCARD\r\n" + - "VERSION:3.0\r\n" + - "FN:Jens Hansen\r\n" + - "N:\r\n" + - "TEL:00498912345678\r\n" + - "TEL:+4587654321\r\n" + - "EMAIL:casper@email.add\r\n" + - "EMAIL:bonde@email.add\r\n" + - "END:VCARD\r\n" + - "BEGIN:BBODY\r\n" + - "ENCODING:G-7BIT\r\n" + - "LENGTH:94\r\n" + - "BEGIN:MSG\r\n" + - "00040E81009498214365870000" + scTimeSb.toString() + - "11CC32FD34079DDF20737A8E4EBBCF21\r\n" + - "END:MSG\r\n" + - "END:BBODY\r\n" + - "END:BENV\r\n" + - "END:BMSG\r\n"; - - String encoded; - String[] phone = {"00498912345678", "+4587654321"}; - String[] email = {"casper@email.add", "bonde@email.add"}; - msg.addOriginator("Bonde,Casper", "Casper Bonde", phone, email, null, null); - msg.addRecipient("", "Jens Hansen", phone, email, null, null); - msg.setFolder("inbox"); - /* TODO: extract current time, and build the expected string */ - msg.setSmsBodyPdus(BluetoothMapSmsPdu.getDeliverPdus("Let's go fishing!", "00498912345678", date.getTime())); - msg.setStatus(false); - msg.setType(TYPE.SMS_GSM); - try { - byte[] encodedBytes = msg.encode(); - encoded = new String(encodedBytes); - if(D) Log.d(TAG, "\nExpected: \n" + expected); - if(D) Log.d(TAG, "\nEncoded: \n" + encoded); - assertTrue(expected.equalsIgnoreCase(encoded)); - } catch (UnsupportedEncodingException e) { - Log.d(TAG, "Encoding failed.",e); - assertTrue("Encoding failed.", true); - } - } - - /*** - * Test native Submit PDU encoding and decoding, based on the example in the MAP 1.1 specification. - * The difference between this PDU, and the one in the specification: - * - The invalid SC address 0191 is replaced with no address 00 - * - The PDU is converted to a submit PDU by adding the TP-MR and removing the service center time stamp. - * - The phone number type is changed from private 91 to international 81 - */ - public void testSmsEncodeDecodeNativeSubmitPdu() { - BluetoothMapbMessageSms msg = new BluetoothMapbMessageSms(); - String expected = - "BEGIN:BMSG\r\n" + - "VERSION:1.0\r\n" + - "STATUS:UNREAD\r\n" + - "TYPE:SMS_GSM\r\n" + - "FOLDER:telecom/msg/outbox\r\n" + - "BEGIN:VCARD\r\n" + - "VERSION:3.0\r\n" + - "FN:Casper Bonde\r\n" + - "N:Bonde,Casper\r\n" + - "TEL:00498912345678\r\n" + - "TEL:+4587654321\r\n" + - "EMAIL:casper@email.add\r\n" + - "EMAIL:bonde@email.add\r\n" + - "END:VCARD\r\n" + - "BEGIN:BENV\r\n" + - "BEGIN:VCARD\r\n" + - "VERSION:3.0\r\n" + - "FN:Jens Hansen\r\n" + - "N:\r\n" + - "TEL:00498912345678\r\n" + - "TEL:+4587654321\r\n" + - "EMAIL:casper@email.add\r\n" + - "EMAIL:bonde@email.add\r\n" + - "END:VCARD\r\n" + - "BEGIN:BBODY\r\n" + - "ENCODING:G-7BIT\r\n" + - "LENGTH:82\r\n" + - "BEGIN:MSG\r\n" + /*Length 11 */ - "0001000E8100949821436587000011CC32FD34079DDF20737A8E4EBBCF21\r\n" + /* Length 62 */ - "END:MSG\r\n" + /* Length 9 */ - "END:BBODY\r\n" + - "END:BENV\r\n" + - "END:BMSG\r\n"; - - String encoded; - String[] phone = {"00498912345678", "+4587654321"}; - String[] email = {"casper@email.add", "bonde@email.add"}; - msg.addOriginator("Bonde,Casper", "Casper Bonde", phone, email, null, null); - msg.addRecipient("", "Jens Hansen", phone, email, null, null); - msg.setFolder("outbox"); - /* TODO: extract current time, and build the expected string */ - msg.setSmsBodyPdus(BluetoothMapSmsPdu.getSubmitPdus("Let's go fishing!", "00498912345678")); - msg.setStatus(false); - msg.setType(TYPE.SMS_GSM); - try { - byte[] encodedBytes = msg.encode(); - InputStream is = new ByteArrayInputStream(encodedBytes); - encoded = new String(encodedBytes); - BluetoothMapbMessage newMsg = BluetoothMapbMessage.parse(is, BluetoothMapAppParams.CHARSET_NATIVE); - String decoded = ((BluetoothMapbMessageSms) newMsg).getSmsBody(); - if(D) Log.d(TAG, "\nCalling encoder on decoded message to log its content"); - newMsg.encode(); - if(D) Log.d(TAG, "\nExpected: \n" + expected); - if(D) Log.d(TAG, "\nEncoded: \n" + encoded); - if(D) Log.d(TAG, "\nDecoded: \n" + decoded); - assertTrue("The encoded bMessage do not match the expected.", expected.equalsIgnoreCase(encoded)); - assertTrue("The decoded text is \"" + decoded + "\" - expected \"Let's go fishing!\"", decoded.equalsIgnoreCase("Let's go fishing!")); - } catch (UnsupportedEncodingException e) { - Log.d(TAG, "Encoding failed.",e); - assertTrue("Encoding failed.", true); - } - } - - /*** - * Test native Submit PDU encoding and decoding, based on the example in the MAP 1.1 specification. - * The difference between this PDU, and the one in the specification: - * - The invalid SC address 0191 is replaced with no address 00 - * - The PDU is converted to a submit PDU by adding the TP-MR and removing the service center time stamp. - * - The phone number type is changed from private 91 to international 81 - */ - public void testSmsEncodeDecodeNativeSubmitPduWithSc() { - BluetoothMapbMessageSms msg = new BluetoothMapbMessageSms(); - String encoded = - "BEGIN:BMSG\r\n" + - "VERSION:1.0\r\n" + - "STATUS:UNREAD\r\n" + - "TYPE:SMS_GSM\r\n" + - "FOLDER:telecom/msg/outbox\r\n" + - "BEGIN:VCARD\r\n" + - "VERSION:3.0\r\n" + - "FN:Casper Bonde\r\n" + - "N:Bonde,Casper\r\n" + - "TEL:00498912345678\r\n" + - "TEL:+4587654321\r\n" + - "EMAIL:casper@email.add\r\n" + - "EMAIL:bonde@email.add\r\n" + - "END:VCARD\r\n" + - "BEGIN:BENV\r\n" + - "BEGIN:VCARD\r\n" + - "VERSION:3.0\r\n" + - "FN:Jens Hansen\r\n" + - "N:\r\n" + - "TEL:00498912345678\r\n" + - "TEL:+4587654321\r\n" + - "EMAIL:casper@email.add\r\n" + - "EMAIL:bonde@email.add\r\n" + - "END:VCARD\r\n" + - "BEGIN:BBODY\r\n" + - "ENCODING:G-7BIT\r\n" + - "LENGTH:58 \r\n" + - "BEGIN:MSG\r\n" + /*Length 11 */ - "018001000B912184254590F500000346F61B\r\n" + /* Length 38 */ - "END:MSG\r\n" + /* Length 9 */ - "END:BBODY\r\n" + - "END:BENV\r\n" + - "END:BMSG\r\n"; - try { - String expected = "Flo"; - InputStream is = new ByteArrayInputStream(encoded.getBytes("UTF-8")); - BluetoothMapbMessage newMsg = BluetoothMapbMessage.parse(is, BluetoothMapAppParams.CHARSET_NATIVE); - String decoded = ((BluetoothMapbMessageSms) newMsg).getSmsBody(); - if(D) Log.d(TAG, "\nEncoded: \n" + encoded); - if(D) Log.d(TAG, "\nDecoded: \n" + decoded); - assertTrue("Decoded string (" + decoded + ") did not match expected (" + expected + ")", expected.equals(decoded)); - } catch (UnsupportedEncodingException e) { - Log.d(TAG, "Encoding failed.",e); - assertTrue("Encoding failed.", false); - } - } - - /*** - * Validate that the folder is correctly truncated to 512 bytes, if a longer folder path - * is supplied. - */ - public void testFolderLengthTruncation() { - String folder = ""; - int levelCount = 0; - while(folder.length()<640) - folder += "/folder" + levelCount++; - - String expected = folder.substring(folder.length()-512, folder.length()); - - BluetoothMapbMessageSms msg = new BluetoothMapbMessageSms(); - msg.setFolder(folder); - msg.setStatus(false); - msg.setType(TYPE.SMS_GSM); - - try { - byte[] encoded = msg.encode(); - InputStream is = new ByteArrayInputStream(encoded); - if(D) Log.d(TAG, new String(encoded)); - BluetoothMapbMessage newMsg = BluetoothMapbMessage.parse(is, BluetoothMapAppParams.CHARSET_UTF8); - assertTrue("Wrong length expected 512, got " + expected.length(), expected.length() == 512); - Log.d(TAG, "expected: " + expected); - Log.d(TAG, "newMsg.getFolder(): " + newMsg.getFolder()); - assertTrue("Folder string did not match", expected.equals(newMsg.getFolder())); - - } catch (UnsupportedEncodingException e) { - Log.d(TAG, "Encoding failed.",e); - assertTrue("Encoding failed", false); - } - } - - /*** - * Test multipart message decoding. - */ - public void testSmsMultipartDecode() { - BluetoothMapbMessageSms msg = new BluetoothMapbMessageSms(); - String encoded = - "BEGIN:BMSG\r\n" + - "VERSION:1.0\r\n" + - "STATUS:READ\r\n" + - "TYPE:SMS_GSM\r\n" + - "FOLDER:/telecom/msg/outbox\r\n" + - "BEGIN:VCARD\r\n" + - "VERSION:2.1\r\n" + - "N:12485254094 \r\n" + - "TEL:12485254094\r\n" + - "END:VCARD\r\n" + - "BEGIN:BENV\r\n" + - "BEGIN:VCARD\r\n" + - "VERSION:2.1\r\n" + - "N:+12485254095 \r\n" + - "TEL:+12485254095\r\n" + - "END:VCARD\r\n" + - "BEGIN:BBODY\r\n" + - "ENCODING:G-7BIT\r\n" + - "LENGTH:762\r\n" + - "BEGIN:MSG\r\n" + - "018041000B912184254590F50000A0050003010301A8E8F41C949E83C220F69B0E7A9B41F7B79C3C07D1DF20F35BDE068541E3B77B1CA697DD617A990C6A97E7F3F0B90C0ABBC9203ABA0C32A7E5733A889E6E9741F437888E2E83E66537B92C07A5DBED32391DA697D97990FB4D4F9BF3A07619B476BFEFA03B3A4C07E5DF7550585E06B9DF74D0BC2E2F83F2EF3A681C7683C86F509A0EBABFEB\r\n" + - "END:MSG\r\n" + - "BEGIN:MSG\r\n" + - "018041000B912184254590F50000A0050003010302C820767A5D06D1D16550DA4D2FBBC96532485E1EA7E1E9B29B0E82B3CBE17919644EBBC9A0779D0EA2A3CB20735A3EA783E8E8B4FB0CA2BF41E437C8FDA683E6757919947FD741E3B01B447E83D274D0FD5D679341ECB7BD0C4AD341F7F01C44479741E6B47C4E0791C379D0DB0C6AE741F2F2BCDE2E83CC6F3928FFAECB41E57638CD06A5E7\r\n" + - "END:MSG\r\n" + - "BEGIN:MSG\r\n" + - "018041000B912184254590F500001A050003010303DC6F3A685E979741F9771D340EBB41E437\r\n" + - "END:MSG\r\n" + - "END:BBODY\r\n" + - "END:BENV\r\n" + - "END:BMSG\r\n"; - try { - InputStream is = new ByteArrayInputStream(encoded.getBytes("UTF-8")); - BluetoothMapbMessage newMsg = BluetoothMapbMessage.parse(is, BluetoothMapAppParams.CHARSET_NATIVE); - String decoded = ((BluetoothMapbMessageSms) newMsg).getSmsBody(); - if(D) Log.d(TAG, "\nEncoded: \n" + encoded); - if(D) Log.d(TAG, "\nDecoded: \n" + decoded); - } catch (UnsupportedEncodingException e) { - Log.d(TAG, "Decoding failed.",e); - assertTrue("Decoding failed.", false); - } - } - - /*** - * Test encoding of a simple MMS text message (UTF8). This validates most parameters. - */ - public void testMmsEncodeText() { - BluetoothMapbMessageMime msg = new BluetoothMapbMessageMime (); - String str1 = - "BEGIN:BMSG\r\n" + - "VERSION:1.0\r\n" + - "STATUS:UNREAD\r\n" + - "TYPE:MMS\r\n" + - "FOLDER:telecom/msg/inbox\r\n" + - "BEGIN:VCARD\r\n" + - "VERSION:3.0\r\n" + - "FN:Casper Bonde\r\n" + - "N:Bonde,Casper\r\n" + - "TEL:+4512345678\r\n" + - "TEL:+4587654321\r\n" + - "EMAIL:casper@email.add\r\n" + - "EMAIL:bonde@email.add\r\n" + - "END:VCARD\r\n" + - "BEGIN:BENV\r\n" + - "BEGIN:VCARD\r\n" + - "VERSION:3.0\r\n" + - "FN:Jørn Hansen\r\n" + - "N:\r\n" + - "TEL:+4512345678\r\n" + - "TEL:+4587654321\r\n" + - "EMAIL:casper@email.add\r\n" + - "EMAIL:bonde@email.add\r\n" + - "END:VCARD\r\n" + - "BEGIN:BBODY\r\n" + - "CHARSET:UTF-8\r\n" + - "LENGTH:184\r\n" + - "BEGIN:MSG\r\n" + - "From: \"Jørn Hansen\" ;\r\n" + - "To: \"Jørn Hansen\" ;\r\n" + - "Cc: Jens Hansen ;\r\n" + - "\r\n" + - "This is a short message\r\n" + - "\r\n" + - "\r\n" + - "\r\n" + - "END:MSG\r\n" + - "END:BBODY\r\n" + - "END:BENV\r\n" + - "END:BMSG\r\n"; - - String encoded; - String[] phone = {"+4512345678", "+4587654321"}; - String[] email = {"casper@email.add", "bonde@email.add"}; - msg.addOriginator("Bonde,Casper", "Casper Bonde", phone, email, null, null); - msg.addRecipient("", "Jørn Hansen", phone, email, null, null); - msg.setFolder("inbox"); - msg.setIncludeAttachments(false); - msg.addTo("Jørn Hansen", "bonde@email.add"); - msg.addCc("Jens Hansen", "bonde@email.add"); - msg.addFrom("Jørn Hansen", "bonde@email.add"); - BluetoothMapbMessageMime .MimePart part = msg.addMimePart(); - part.mPartName = "partNameText"; - part.mContentType ="dsfajfdlk/text/asdfafda"; - try { - part.mData = new String("This is a short message\r\n").getBytes("UTF-8"); - } - catch (UnsupportedEncodingException e) { - if(D) Log.e(TAG, "UnsupportedEncodingException should never happen???", e); - assertTrue(false); - } - - part = msg.addMimePart(); - part.mPartName = "partNameimage"; - part.mContentType = "dsfajfdlk/image/asdfafda"; - part.mData = null; - - msg.setStatus(false); - msg.setType(TYPE.MMS); - msg.updateCharset(); - - try { - encoded = new String(msg.encode()); - if(D) Log.d(TAG, encoded); - assertTrue(str1.equals(encoded)); - } catch (UnsupportedEncodingException e) { - Log.d(TAG, "Encoding failed.",e); - assertTrue("Encoding failed.", true); - } - } - - public void testQuotedPrintable() { - testQuotedPrintableIso8859_1(); - testQuotedPrintableUTF_8(); - } - - public void testQuotedPrintableIso8859_1() { - String charset = "iso-8859-1"; - String input = "Hello, here are some danish letters: =E6=F8=E5.\r\n" + - "Please check that you are able to remove soft " + - "line breaks and handle '=3D' =\r\ncharacters within the text. \r\n" + - "Just a sequence of non optimal characters to make " + - "it complete: !\"#$@[\\]^{|}=\r\n~\r\n\r\n" + - "Thanks\r\n" + - "Casper"; - String expected = "Hello, here are some danish letters: æøå.\r\n" + - "Please check that you are able to remove soft " + - "line breaks and handle '=' characters within the text. \r\n" + - "Just a sequence of non optimal characters to make " + - "it complete: !\"#$@[\\]^{|}~\r\n\r\n" + - "Thanks\r\n" + - "Casper"; - String output; - output = new String(BluetoothMapUtils.quotedPrintableToUtf8(input, charset)); - if(D) Log.d(TAG, "\nExpected: \n" + expected); - if(D) Log.d(TAG, "\nOutput: \n" + output); - assertTrue(output.equals(expected)); - } - - public void testQuotedPrintableUTF_8() { - String charset = "utf-8"; - String input = "Hello, here are some danish letters: =C3=A6=C3=B8=C3=A5.\r\n" + - "Please check that you are able to remove soft " + - "line breaks and handle '=3D' =\r\ncharacters within the text. \r\n" + - "Just a sequence of non optimal characters to make " + - "it complete: !\"#$@[\\]^{|}=\r\n~\r\n\r\n" + - "Thanks\r\n" + - "Casper"; - String expected = "Hello, here are some danish letters: æøå.\r\n" + - "Please check that you are able to remove soft " + - "line breaks and handle '=' characters within the text. \r\n" + - "Just a sequence of non optimal characters to make " + - "it complete: !\"#$@[\\]^{|}~\r\n\r\n" + - "Thanks\r\n" + - "Casper"; - String output; - output = new String(BluetoothMapUtils.quotedPrintableToUtf8(input, charset)); - if(D) Log.d(TAG, "\nExpected: \n" + expected); - if(D) Log.d(TAG, "\nOutput: \n" + output); - assertTrue(output.equals(expected)); - } - -} - diff --git a/tests/src/com/android/bluetooth/tests/BluetoothTestUtils.java b/tests/src/com/android/bluetooth/tests/BluetoothTestUtils.java deleted file mode 100644 index 4ef89e17..00000000 --- a/tests/src/com/android/bluetooth/tests/BluetoothTestUtils.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.android.bluetooth.tests; - -import android.annotation.TargetApi; -import android.bluetooth.BluetoothAdapter; -import android.os.Build; -import android.test.AndroidTestCase; -import android.util.Log; - - -@TargetApi(Build.VERSION_CODES.ECLAIR) -public class BluetoothTestUtils extends AndroidTestCase { - - protected static String TAG = "BluetoothTestUtils"; - protected static final boolean D = true; - - static final int POLL_TIME = 500; - static final int ENABLE_TIMEOUT = 5000; - - /** Helper to turn BT on. - * This method will either fail on an assert, or return with BT turned on. - * Behavior of getState() and isEnabled() are validated along the way. - */ - public static void enableBt(BluetoothAdapter adapter) { - if (adapter.getState() == BluetoothAdapter.STATE_ON) { - assertTrue(adapter.isEnabled()); - return; - } - assertEquals(BluetoothAdapter.STATE_OFF, adapter.getState()); - assertFalse(adapter.isEnabled()); - adapter.enable(); - for (int i=0; i MANAGED_USERINFO_LIST = Arrays.asList(new UserInfo[]{ - new UserInfo(0, "user0", 0), - new UserInfo(10, "user10", UserInfo.FLAG_MANAGED_PROFILE)}); - - private Context getMockContext(boolean managedProfileExists, - boolean isBluetoothContactsSharingDisabled) { - DevicePolicyManager mockDpm = mock(DevicePolicyManager.class); - doReturn(isBluetoothContactsSharingDisabled).when(mockDpm) - .getBluetoothContactSharingDisabled(LittleMock.anyObject()); - - UserManager mockUm = mock(UserManager.class); - doReturn(managedProfileExists ? MANAGED_USERINFO_LIST : NORMAL_USERINFO_LIST) - .when(mockUm).getProfiles(anyInt()); - - Context mockContext = mock(Context.class); - doReturn(mockDpm).when(mockContext).getSystemService(Context.DEVICE_POLICY_SERVICE); - doReturn(mockUm).when(mockContext).getSystemService(Context.USER_SERVICE); - - return mockContext; - } -} - diff --git a/tests/src/com/android/bluetooth/tests/IResultLogger.java b/tests/src/com/android/bluetooth/tests/IResultLogger.java deleted file mode 100644 index 01b00a10..00000000 --- a/tests/src/com/android/bluetooth/tests/IResultLogger.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.android.bluetooth.tests; - -/** - * The interface for results - makes it easy to replace the result - * logger implementation at a later point if needed. - * @author cbonde - * - */ -public interface IResultLogger { - /** - * Add an entry to the result log. - * To make the first entry count, add a result of 0 bytes - * transfered then starting the test. - * Or add a result with 1 byte when e.g. the first byte is received. - * @param bytesTransfered The amount of bytes transfered - */ - void addResult(long bytesTransfered); - - /** - * Get the current average speed of the transfer. - * (based on the last entry in the log, and not the current time) - * @return the average speed in bytes/sec - */ - int getAverageSpeed(); - - /** - * Get the current average speed of the last period of the transfer. - * (based on the last entry in the log, and not the current time) - * @param period the period over which the average is taken. - * @return the average speed in bytes/sec - */ - int getAverageSpeed(long period); - -} diff --git a/tests/src/com/android/bluetooth/tests/ISeqStepAction.java b/tests/src/com/android/bluetooth/tests/ISeqStepAction.java deleted file mode 100644 index db66af2d..00000000 --- a/tests/src/com/android/bluetooth/tests/ISeqStepAction.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.android.bluetooth.tests; - -import java.io.IOException; - -import javax.obex.HeaderSet; -import javax.obex.Operation; - -public interface ISeqStepAction { - - void execute(SeqStep step, HeaderSet request, Operation op) - throws IOException; - -} diff --git a/tests/src/com/android/bluetooth/tests/ISeqStepValidator.java b/tests/src/com/android/bluetooth/tests/ISeqStepValidator.java deleted file mode 100644 index 5819f06e..00000000 --- a/tests/src/com/android/bluetooth/tests/ISeqStepValidator.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.android.bluetooth.tests; - -import java.io.IOException; - -import javax.obex.HeaderSet; -import javax.obex.Operation; - -/** - * Interface to validate test step result - */ -public interface ISeqStepValidator { - boolean validate(SeqStep step, HeaderSet response, Operation op) - throws IOException; - -} diff --git a/tests/src/com/android/bluetooth/tests/ITestSequenceBuilder.java b/tests/src/com/android/bluetooth/tests/ITestSequenceBuilder.java deleted file mode 100644 index 3314fd6c..00000000 --- a/tests/src/com/android/bluetooth/tests/ITestSequenceBuilder.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.android.bluetooth.tests; - -public interface ITestSequenceBuilder { - - /** - * Add steps to a sequencer - * @param sequencer The sequencer the steps will be added to. - */ - public void build(TestSequencer sequencer); - -} diff --git a/tests/src/com/android/bluetooth/tests/ITestSequenceConfigurator.java b/tests/src/com/android/bluetooth/tests/ITestSequenceConfigurator.java deleted file mode 100644 index d260d8b2..00000000 --- a/tests/src/com/android/bluetooth/tests/ITestSequenceConfigurator.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.android.bluetooth.tests; - -import java.util.ArrayList; -import java.util.concurrent.CountDownLatch; - -import javax.obex.ServerRequestHandler; - -public interface ITestSequenceConfigurator { - - /** Use this to customize a serverRequestHandler - * @param sequence A reference to the sequence to handle - * @param stopLatch a reference to a latch that must be count down, when test completes. - * @return Reference to the ServerRequestHandler. - */ - public ServerRequestHandler getObexServer(ArrayList sequence, - CountDownLatch stopLatch); -} diff --git a/tests/src/com/android/bluetooth/tests/MapObexLevelTest.java b/tests/src/com/android/bluetooth/tests/MapObexLevelTest.java deleted file mode 100644 index fb5de24b..00000000 --- a/tests/src/com/android/bluetooth/tests/MapObexLevelTest.java +++ /dev/null @@ -1,286 +0,0 @@ -package com.android.bluetooth.tests; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.concurrent.CountDownLatch; - -import javax.obex.HeaderSet; -import javax.obex.Operation; -import javax.obex.ServerRequestHandler; - -import junit.framework.Assert; -import android.annotation.TargetApi; -import android.bluetooth.BluetoothServerSocket; -import android.bluetooth.BluetoothSocket; -import android.net.LocalServerSocket; -import android.net.LocalSocket; -import android.os.Build; -import android.os.RemoteException; -import android.test.AndroidTestCase; -import android.util.Log; - -import com.android.bluetooth.BluetoothObexTransport; -import com.android.bluetooth.tests.TestSequencer.OPTYPE; - -@TargetApi(Build.VERSION_CODES.KITKAT) -public class MapObexLevelTest extends AndroidTestCase implements ITestSequenceConfigurator { - protected static String TAG = "MapObexLevelTest"; - protected static final boolean D = true; - protected static final boolean TRACE = false; - protected static final boolean DELAY_PASS_30_SEC = true; - - // 128 bit UUID for MAP MAS - static final byte[] MAS_TARGET = new byte[] { - (byte)0xBB, (byte)0x58, (byte)0x2B, (byte)0x40, - (byte)0x42, (byte)0x0C, (byte)0x11, (byte)0xDB, - (byte)0xB0, (byte)0xDE, (byte)0x08, (byte)0x00, - (byte)0x20, (byte)0x0C, (byte)0x9A, (byte)0x66 - }; - - // 128 bit UUID for MAP MNS - static final byte[] MNS_TARGET = new byte[] { - (byte)0xBB, (byte)0x58, (byte)0x2B, (byte)0x41, - (byte)0x42, (byte)0x0C, (byte)0x11, (byte)0xDB, - (byte)0xB0, (byte)0xDE, (byte)0x08, (byte)0x00, - (byte)0x20, (byte)0x0C, (byte)0x9A, (byte)0x66 - }; - - /* Message types */ - static final String TYPE_GET_FOLDER_LISTING = "x-obex/folder-listing"; - static final String TYPE_GET_MESSAGE_LISTING = "x-bt/MAP-msg-listing"; - static final String TYPE_GET_CONVO_LISTING = "x-bt/MAP-convo-listing"; - static final String TYPE_MESSAGE = "x-bt/message"; - static final String TYPE_SET_MESSAGE_STATUS = "x-bt/messageStatus"; - static final String TYPE_SET_NOTIFICATION_REGISTRATION = "x-bt/MAP-NotificationRegistration"; - static final String TYPE_MESSAGE_UPDATE = "x-bt/MAP-messageUpdate"; - static final String TYPE_GET_MAS_INSTANCE_INFORMATION = "x-bt/MASInstanceInformation"; - - public void testFolder() { - testLocalSockets(new buildFolderTestSeq()); - } - - public void testFolderServer() { - testServer(new buildFolderTestSeq()); - } - - public void testFolderClient() { - testClient(new buildFolderTestSeq()); - } - - protected class buildFolderTestSeq implements ITestSequenceBuilder { - @Override - public void build(TestSequencer sequencer) { - addConnectStep(sequencer); - - MapStepsFolder.addGoToMsgFolderSteps(sequencer); - - // MAP DISCONNECT Step - addDisconnectStep(sequencer); - } - } - - - public void testConvo() { - testLocalSockets(new buildConvoTestSeq()); - } - - public void testConvoServer() { - testServer(new buildConvoTestSeq()); - } - - public void testConvoClient() { - testClient(new buildConvoTestSeq()); - } - - class buildConvoTestSeq implements ITestSequenceBuilder { - @Override - public void build(TestSequencer sequencer) { - addConnectStep(sequencer); - - MapStepsFolder.addGoToMsgFolderSteps(sequencer); - - MapStepsConvo.addConvoListingSteps(sequencer); - - // MAP DISCONNECT Step - addDisconnectStep(sequencer); - } - } - - /** - * Run the test sequence using a local socket on a single device. - * Throughput around 4000 kbyte/s - with a larger OBEX package size. - * - * Downside: Unable to get a BT-snoop file... - */ - protected void testLocalSockets(ITestSequenceBuilder builder) { - mContext = this.getContext(); - MapTestData.init(mContext); - Log.i(TAG,"Setting up sockets..."); - - try { - /* Create and interconnect local pipes for transport */ - LocalServerSocket serverSock = new LocalServerSocket("com.android.bluetooth.tests.sock"); - LocalSocket clientSock = new LocalSocket(); - LocalSocket acceptSock; - - clientSock.connect(serverSock.getLocalSocketAddress()); - - acceptSock = serverSock.accept(); - - /* Create the OBEX transport objects to wrap the pipes - enable SRM */ - ObexPipeTransport clientTransport = new ObexPipeTransport(clientSock.getInputStream(), - clientSock.getOutputStream(), true); - ObexPipeTransport serverTransport = new ObexPipeTransport(acceptSock.getInputStream(), - acceptSock.getOutputStream(), true); - - TestSequencer sequencer = new TestSequencer(clientTransport, serverTransport, this); - - builder.build(sequencer); - - //Debug.startMethodTracing("ObexTrace"); - assertTrue(sequencer.run(mContext)); - //Debug.stopMethodTracing(); - - clientSock.close(); - acceptSock.close(); - serverSock.close(); - } catch (IOException e) { - Log.e(TAG, "IOException", e); - } - } - - /** - * Server side of a dual device test using a Bluetooth Socket. - * Enables the possibility to get a BT-snoop file. - * If you need the btsnoop from the device which completes the test with success - * you need to add a delay after the test ends, and fetch the file before this delay - * expires. When the test completes, the Bluetooth subsystem will be restarted, causing - * a new bt-snoop to overwrite the one used in test. - */ - public void testServer(ITestSequenceBuilder builder) { - mContext = this.getContext(); - MapTestData.init(mContext); - Log.i(TAG,"Setting up sockets..."); - - try { - /* This will turn on BT and create a server socket on which accept can be called. */ - BluetoothServerSocket serverSocket=ObexTest.createServerSocket(BluetoothSocket.TYPE_L2CAP, true); - - Log.i(TAG, "Waiting for client to connect..."); - BluetoothSocket socket = serverSocket.accept(); - Log.i(TAG, "Client connected..."); - - BluetoothObexTransport serverTransport = new BluetoothObexTransport(socket); - - TestSequencer sequencer = new TestSequencer(null, serverTransport, this); - - builder.build(sequencer); - - //Debug.startMethodTracing("ObexTrace"); - assertTrue(sequencer.run(mContext)); - //Debug.stopMethodTracing(); - - serverSocket.close(); - socket.close(); - } catch (IOException e) { - Log.e(TAG, "IOException", e); - } - if(DELAY_PASS_30_SEC) { - Log.i(TAG, "\n\n\nTest done - please fetch logs within 30 seconds...\n\n\n"); - try { - Thread.sleep(30000); - } catch (InterruptedException e) {} - } - } - - /** - * Server side of a dual device test using a Bluetooth Socket. - * Enables the possibility to get a BT-snoop file. - * If you need the btsnoop from the device which completes the test with success - * you need to add a delay after the test ends, and fetch the file before this delay - * expires. When the test completes, the Bluetooth subsystem will be restarted, causing - * a new bt-snoop to overwrite the one used in test. - */ - public void testClient(ITestSequenceBuilder builder) { - mContext = this.getContext(); - MapTestData.init(mContext); - Log.i(TAG, "Setting up sockets..."); - - try { - /* This will turn on BT and connect */ - BluetoothSocket clientSock = - ObexTest.connectClientSocket(BluetoothSocket.TYPE_L2CAP, true, mContext); - - BluetoothObexTransport clientTransport = new BluetoothObexTransport(clientSock); - - TestSequencer sequencer = new TestSequencer(clientTransport, null, this); - - builder.build(sequencer); - - //Debug.startMethodTracing("ObexTrace"); - assertTrue(sequencer.run(mContext)); - //Debug.stopMethodTracing(); - - clientSock.close(); - } catch (IOException e) { - Log.e(TAG, "IOException", e); - } - if(DELAY_PASS_30_SEC) { - Log.i(TAG, "\n\n\nTest done - please fetch logs within 30 seconds...\n\n\n"); - try { - Thread.sleep(30000); - } catch (InterruptedException e) {} - } - } - - protected void addConnectStep(TestSequencer sequencer) { - SeqStep step; - - // MAP CONNECT Step - step = sequencer.addStep(OPTYPE.CONNECT, null); - HeaderSet hs = new HeaderSet(); - hs.setHeader(HeaderSet.TARGET, MAS_TARGET); - step.mReqHeaders = hs; - step.mValidator = new MapConnectValidator(); - //step.mServerPreAction = new MapAddSmsMessages(); // could take in parameters - } - - protected void addDisconnectStep(TestSequencer sequencer) { - sequencer.addStep(OPTYPE.DISCONNECT, ObexTest.getResponsecodevalidator()); - } - - /* Functions to validate results */ - - private class MapConnectValidator implements ISeqStepValidator { - @Override - public boolean validate(SeqStep step, HeaderSet response, Operation notUsed) - throws IOException { - Assert.assertNotNull(response); - byte[] who = (byte[])response.getHeader(HeaderSet.WHO); - Assert.assertNotNull(who); - Assert.assertTrue(Arrays.equals(who, MAS_TARGET)); - Assert.assertNotNull(response.getHeader(HeaderSet.CONNECTION_ID)); - return true; - } - } - - /** - * This is the function creating the Obex Server to be used in this class. - * Here we use a mocked version of the MapObexServer class - */ - @Override - public ServerRequestHandler getObexServer(ArrayList sequence, - CountDownLatch stopLatch) { - try { - return new MapObexTestServer(mContext, sequence, stopLatch); - } catch (RemoteException e) { - Log.e(TAG, "exception", e); - fail("Unable to create MapObexTestServer"); - } - return null; - } - - -} - diff --git a/tests/src/com/android/bluetooth/tests/MapObexTestServer.java b/tests/src/com/android/bluetooth/tests/MapObexTestServer.java deleted file mode 100644 index 4aa04d79..00000000 --- a/tests/src/com/android/bluetooth/tests/MapObexTestServer.java +++ /dev/null @@ -1,187 +0,0 @@ -package com.android.bluetooth.tests; - -import java.util.ArrayList; -import java.util.concurrent.CountDownLatch; - -import javax.obex.HeaderSet; -import javax.obex.Operation; -import javax.obex.ResponseCodes; - -import junit.framework.Assert; - -import android.bluetooth.BluetoothAdapter; -import android.content.Context; -import android.os.RemoteException; -import android.util.Log; - -import com.android.bluetooth.map.BluetoothMapAccountItem; -import com.android.bluetooth.map.BluetoothMapContentObserver; -import com.android.bluetooth.map.BluetoothMapMasInstance; -import com.android.bluetooth.map.BluetoothMapObexServer; -import com.android.bluetooth.map.BluetoothMnsObexClient; - -public class MapObexTestServer extends BluetoothMapObexServer { - - private static final String TAG = "MapObexTestServer"; - private static final boolean V = true; - - ArrayList mSequence; - CountDownLatch mStopLatch; - - ObexTestDataHandler mDataHandler; - int mOperationIndex = 0; - - /* This needs to be static, as calling the super-constructor must be the first step. - * Alternatively add the account as constructor parameter, and create a builder - * function - factory pattern. */ -// private static BluetoothMapAccountItem mAccountMock = new BluetoothMapAccountItem("1", -// "TestAccount", -// "do.not.exist.package.name.and.never.used.anyway:-)", -// "info.guardianproject.otr.app.im.provider.bluetoothprovider", -// null, -// BluetoothMapUtils.TYPE.IM, -// null, -// null); - private static BluetoothMapAccountItem mAccountMock = null; - - /* MAP Specific instance variables - private final BluetoothMapContentObserver mObserver = null; - private final BluetoothMnsObexClient mMnsClient = null;*/ - - /* Test values, consider gathering somewhere else */ - private static final int MAS_ID = 0; - private static final int REMOTE_FEATURE_MASK = 0x07FFFFFF; - private static final BluetoothMapMasInstance mMasInstance = - new MockMasInstance(MAS_ID, REMOTE_FEATURE_MASK); - - public MapObexTestServer(final Context context, ArrayList sequence, - CountDownLatch stopLatch) throws RemoteException { - - super(null, context, - new BluetoothMapContentObserver(context, - new BluetoothMnsObexClient( - BluetoothAdapter.getDefaultAdapter(). - getRemoteDevice("12:23:34:45:56:67"), null, null), - /* TODO: this will not work for single device test... */ - mMasInstance, - mAccountMock, /* Account */ - true) /* Enable SMS/MMS*/, - mMasInstance, - mAccountMock /* Account */, - true /* SMS/MMS enabled*/); - mSequence = sequence; - mDataHandler = new ObexTestDataHandler("(Server)"); - mStopLatch = stopLatch; - } - - /* OBEX operation handlers */ - @Override - public int onConnect(HeaderSet request, HeaderSet reply) { - Log.i(TAG,"onConnect()"); - int index; - int result = ResponseCodes.OBEX_HTTP_OK; - try { - index = ((Long)request.getHeader(TestSequencer.STEP_INDEX_HEADER)).intValue(); - mOperationIndex = index; - SeqStep step = mSequence.get(mOperationIndex); - Assert.assertNotNull("invalid step index!", step); - if(step.mServerPreAction != null) { - step.mServerPreAction.execute(step, request, null); - } - result = super.onConnect(request, reply); - } catch (Exception e) { - Log.e(TAG, "Exception in onConnect - aborting...", e); - result = ResponseCodes.OBEX_HTTP_INTERNAL_ERROR; - // A read from null will produce exception to end the test. - } - return result; - } - - @Override - public void onDisconnect(HeaderSet request, HeaderSet reply) { - Log.i(TAG,"onDisconnect()"); - /* TODO: validate request headers, and set response headers */ - int index; - int result = ResponseCodes.OBEX_HTTP_OK; - try { - index = ((Long)request.getHeader(TestSequencer.STEP_INDEX_HEADER)).intValue(); - mOperationIndex = index; - SeqStep step = mSequence.get(mOperationIndex); - Assert.assertNotNull("invalid step index!", step); - if(step.mServerPreAction != null) { - step.mServerPreAction.execute(step, request, null); - } - super.onDisconnect(request, reply); - } catch (Exception e) { - Log.e(TAG, "Exception in onDisconnect - aborting...", e); - result = ResponseCodes.OBEX_HTTP_INTERNAL_ERROR; - // A read from null will produce exception to end the test. - } - if(mOperationIndex >= (mSequence.size()-1)) { - /* End of test, signal test runner thread */ - Log.i(TAG, "Sending latch close signal..."); - mStopLatch.countDown(); - } else { - Log.i(TAG, "Got disconnect with mOperationCounter = " + mOperationIndex); - } - reply.responseCode = result; - } - - @Override - public int onPut(Operation operation) { - Log.i(TAG,"onPut()"); - int result = ResponseCodes.OBEX_HTTP_OK; - try{ - HeaderSet reqHeaders = operation.getReceivedHeader(); - int index = ((Long)reqHeaders.getHeader(TestSequencer.STEP_INDEX_HEADER)).intValue(); - mOperationIndex = index; - SeqStep step = mSequence.get(mOperationIndex); - Assert.assertNotNull("invalid step index!", step); - if(step.mServerPreAction != null) { - step.mServerPreAction.execute(step, reqHeaders, operation); - } - super.onPut(operation); - } catch (Exception e) { - Log.e(TAG, "Exception in onPut - aborting...", e); - result = ResponseCodes.OBEX_HTTP_INTERNAL_ERROR; - // A read from null will produce exception to end the test. - } - if(result == ResponseCodes.OBEX_HTTP_OK) { - Log.i(TAG, "OBEX-HANDLER: operation complete success"); - } else { - Log.e(TAG, "OBEX-HANDLER: operation complete FAILED!"); - } - return result; - } - - @Override - public int onGet(Operation operation) { - Log.i(TAG,"onGet()"); - int result = ResponseCodes.OBEX_HTTP_OK; - try{ - HeaderSet reqHeaders = operation.getReceivedHeader(); - int index = ((Long)reqHeaders.getHeader(TestSequencer.STEP_INDEX_HEADER)).intValue(); - mOperationIndex = index; - SeqStep step = mSequence.get(mOperationIndex); - Assert.assertNotNull("invalid step index!", step); - if(step.mServerPreAction != null) { - step.mServerPreAction.execute(step, reqHeaders, operation); - } - super.onGet(operation); - } catch (Exception e) { - Log.e(TAG, "Exception in onGet - aborting...", e); - result = ResponseCodes.OBEX_HTTP_INTERNAL_ERROR; - // A read from null will produce exception to end the test. - } - if(result == ResponseCodes.OBEX_HTTP_OK) { - Log.i(TAG, "OBEX-HANDLER: operation complete success"); - } else { - Log.e(TAG, "OBEX-HANDLER: operation complete FAILED!"); - } - return result; - } - - - -} - diff --git a/tests/src/com/android/bluetooth/tests/MapStepsConvo.java b/tests/src/com/android/bluetooth/tests/MapStepsConvo.java deleted file mode 100644 index f125ea4c..00000000 --- a/tests/src/com/android/bluetooth/tests/MapStepsConvo.java +++ /dev/null @@ -1,237 +0,0 @@ -package com.android.bluetooth.tests; - -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.text.ParseException; - -import javax.obex.HeaderSet; -import javax.obex.Operation; -import javax.obex.ResponseCodes; - -import junit.framework.Assert; -import android.util.Log; - -import com.android.bluetooth.map.BluetoothMapAppParams; -import com.android.bluetooth.map.BluetoothMapConvoListing; -import com.android.bluetooth.tests.TestSequencer.OPTYPE; - -public class MapStepsConvo { - private static final String TAG = "MapStepsConvo"; - - - protected static void addConvoListingSteps(TestSequencer sequencer) { - SeqStep step; - final int count = 5; - - // TODO: As we use the default message database, these tests will fail if the - // database has any content. - // To cope with this for now, the validation is disabled. - - /* Request the number of messages */ - step = addConvoListingStep(sequencer, - 0 /*maxListCount*/, - -1 /*listStartOffset*/, - null /*activityBegin*/, - null /*activityEnd*/, - -1 /*readStatus*/, - null /*recipient*/, - new MapConvoListValidator() - /*new MapConvoListValidator(MapTestData.TEST_NUM_CONTACTS)validator*/); - /* Add messages and contacts for the entire sequence of tests */ - step.mServerPreAction = new MapTestData.MapAddSmsMessages(count); - - /* Request the XML for all conversations */ - step = addConvoListingStep(sequencer, - -1 /*maxListCount*/, - -1 /*listStartOffset*/, - null /*activityBegin*/, - null /*activityEnd*/, - -1 /*readStatus*/, - null /*recipient*/, - /*nearly impossible to validate due to auto assigned ID values*/ - new MapConvoListValidator() - /*new MapConvoListValidator(MapTestData.TEST_NUM_CONTACTS)validator*/); - - step = addConvoListingStep(sequencer, - 2 /*maxListCount*/, - -1 /*listStartOffset*/, - null /*activityBegin*/, - null /*activityEnd*/, - -1 /*readStatus*/, - null /*recipient*/, - /*nearly impossible to validate due to auto assigned ID values*/ - new MapConvoListValidator() - /*new MapConvoListValidator(MapTestData.TEST_NUM_CONTACTS)validator*/); - - step = addConvoListingStep(sequencer, - 2 /*maxListCount*/, - 1 /*listStartOffset*/, - null /*activityBegin*/, - null /*activityEnd*/, - -1 /*readStatus*/, - null /*recipient*/, - /*nearly impossible to validate due to auto assigned ID values*/ - new MapConvoListValidator() - /*new MapConvoListValidator(MapTestData.TEST_NUM_CONTACTS)validator*/); - - step = addConvoListingStep(sequencer, - 3 /*maxListCount*/, - 2 /*listStartOffset*/, - null /*activityBegin*/, - null /*activityEnd*/, - -1 /*readStatus*/, - null /*recipient*/, - /*nearly impossible to validate due to auto assigned ID values*/ - new MapConvoListValidator() - /*new MapConvoListValidator(MapTestData.TEST_NUM_CONTACTS)validator*/); - - step = addConvoListingStep(sequencer, - 5 /*maxListCount*/, - 1 /*listStartOffset*/, - MapTestData.TEST_ACTIVITY_BEGIN_STRING /*activityBegin*/, - null /*activityEnd*/, - -1 /*readStatus*/, - null /*recipient*/, - /*nearly impossible to validate due to auto assigned ID values*/ - new MapConvoListValidator() - /*new MapConvoListValidator(MapTestData.TEST_NUM_CONTACTS)validator*/); - - step = addConvoListingStep(sequencer, - 5 /*maxListCount*/, - 0 /*listStartOffset*/, - MapTestData.TEST_ACTIVITY_BEGIN_STRING /*activityBegin*/, - MapTestData.TEST_ACTIVITY_END_STRING /*activityEnd*/, - -1 /*readStatus*/, - null /*recipient*/, - /*nearly impossible to validate due to auto assigned ID values*/ - new MapConvoListValidator() - /*new MapConvoListValidator(MapTestData.TEST_NUM_CONTACTS)validator*/); - - step = addConvoListingStep(sequencer, - 5 /*maxListCount*/, - 1 /*listStartOffset*/, - MapTestData.TEST_ACTIVITY_BEGIN_STRING /*activityBegin*/, - null /*activityEnd*/, - 2/* read only */ /*readStatus*/, - null /*recipient*/, - /*nearly impossible to validate due to auto assigned ID values*/ - new MapConvoListValidator() - /*new MapConvoListValidator(MapTestData.TEST_NUM_CONTACTS)validator*/); - - /* TODO: Test the different combinations of filtering */ - } - - /** - * Use -1 or null to omit value in request - * @param sequencer - * @param maxListCount - * @param listStartOffset - * @param activityBegin - * @param activityEnd - * @param readStatus -1 omit value, 0 = no filtering, 1 = get unread only, 2 = get read only, - * 3 = 1+2 - hence get none... - * @param recipient substring of the recipient name - * @param validator - * @return a reference to the step added, for further decoration - */ - private static SeqStep addConvoListingStep(TestSequencer sequencer, int maxListCount, - int listStartOffset, String activityBegin, String activityEnd, - int readStatus, String recipient, ISeqStepValidator validator) { - SeqStep step; - BluetoothMapAppParams appParams = new BluetoothMapAppParams(); - try { - if(activityBegin != null) { - appParams.setFilterLastActivityBegin(activityBegin); - } - if(activityEnd != null) { - appParams.setFilterLastActivityEnd(activityEnd); - } - if(readStatus != -1) { - appParams.setFilterReadStatus(readStatus); - } - if(recipient != null) { - appParams.setFilterRecipient(recipient); - } - if(maxListCount != -1) { - appParams.setMaxListCount(maxListCount); - } - if(listStartOffset != -1) { - appParams.setStartOffset(listStartOffset); - } - } catch (ParseException e) { - Log.e(TAG, "unable to build appParams", e); - } - step = sequencer.addStep(OPTYPE.GET, null); - HeaderSet hs = new HeaderSet(); - hs.setHeader(HeaderSet.TYPE, MapObexLevelTest.TYPE_GET_CONVO_LISTING); - try { - hs.setHeader(HeaderSet.APPLICATION_PARAMETER, appParams.EncodeParams()); - } catch (UnsupportedEncodingException e) { - Log.e(TAG, "ERROR", e); - Assert.fail(); - } - step.mReqHeaders = hs; - step.mValidator = validator; - return step; - } - - /* Functions to validate results */ - private static class MapConvoListValidator implements ISeqStepValidator { - - final BluetoothMapConvoListing mExpectedListing; - final int mExpectedSize; - - public MapConvoListValidator(BluetoothMapConvoListing listing) { - this.mExpectedListing = listing; - this.mExpectedSize = -1; - } - - public MapConvoListValidator(int convoListingSize) { - this.mExpectedListing = null; - this.mExpectedSize = convoListingSize; - } - - public MapConvoListValidator() { - this.mExpectedListing = null; - this.mExpectedSize = -1; - } - - @Override - public boolean validate(SeqStep step, HeaderSet response, Operation op) - throws IOException { - Assert.assertNotNull(op); - op.noBodyHeader(); - try { - // For some odd reason, the request will not be send before we start to read the - // reply data, hence we need to do this first? - BluetoothMapConvoListing receivedListing = new BluetoothMapConvoListing(); - receivedListing.appendFromXml(op.openInputStream()); - response = op.getReceivedHeader(); - byte[] appParamsRaw = (byte[])response.getHeader(HeaderSet.APPLICATION_PARAMETER); - Assert.assertNotNull(appParamsRaw); - BluetoothMapAppParams appParams; - appParams = new BluetoothMapAppParams(appParamsRaw); - Assert.assertNotNull(appParams); - Assert.assertNotNull(appParams.getDatabaseIdentifier()); - Assert.assertNotSame(BluetoothMapAppParams.INVALID_VALUE_PARAMETER, - appParams.getConvoListingSize()); - if(mExpectedSize >= 0) { - Assert.assertSame(mExpectedSize, appParams.getConvoListingSize()); - } - if(mExpectedListing != null) { - // Recursively compare - Assert.assertTrue(mExpectedListing.equals(receivedListing)); - Assert.assertSame(mExpectedListing.getList().size(), - appParams.getConvoListingSize()); - } - int responseCode = op.getResponseCode(); - Assert.assertEquals(ResponseCodes.OBEX_HTTP_OK, responseCode); - op.close(); - } catch (Exception e) { - Log.e(TAG,"",e); - Assert.fail(); - } - return true; - } - } -} diff --git a/tests/src/com/android/bluetooth/tests/MapStepsFolder.java b/tests/src/com/android/bluetooth/tests/MapStepsFolder.java deleted file mode 100644 index 9c87d8e9..00000000 --- a/tests/src/com/android/bluetooth/tests/MapStepsFolder.java +++ /dev/null @@ -1,158 +0,0 @@ -package com.android.bluetooth.tests; - -import java.io.IOException; - -import javax.obex.HeaderSet; -import javax.obex.Operation; -import javax.obex.ResponseCodes; - -import junit.framework.Assert; -import android.util.Log; - -import com.android.bluetooth.map.BluetoothMapAppParams; -import com.android.bluetooth.map.BluetoothMapFolderElement; -import com.android.bluetooth.tests.TestSequencer.OPTYPE; - -public class MapStepsFolder { - private final static String TAG = "MapStepsFolder"; - /** - * Request and expect the following folder structure: - * root - * telecom - * msg - * inbox - * outbox - * draft - * sent - * deleted - * - * The order in which they occur in the listing will not matter. - * @param sequencer - */ - protected static void addGoToMsgFolderSteps(TestSequencer sequencer) { - SeqStep step; - - // MAP Get Folder Listing Steps - // The telecom folder - step = sequencer.addStep(OPTYPE.GET, null); - HeaderSet hs = new HeaderSet(); - hs.setHeader(HeaderSet.TYPE, MapObexLevelTest.TYPE_GET_FOLDER_LISTING); - step.mReqHeaders = hs; - step.mValidator = new MapBuildFolderStructurValidator(1, null); - - step = sequencer.addStep(OPTYPE.SET_PATH, ObexTest.getResponsecodevalidator()); - hs = new HeaderSet(); - hs.setHeader(HeaderSet.NAME, "telecom"); - step.mReqHeaders = hs; - step.mClientPostAction = new MapSetClientFolder("telecom"); - - - // The msg folder - step = sequencer.addStep(OPTYPE.GET, null); - hs = new HeaderSet(); - hs.setHeader(HeaderSet.TYPE, MapObexLevelTest.TYPE_GET_FOLDER_LISTING); - step.mReqHeaders = hs; - step.mValidator = new MapBuildFolderStructurValidator(1, null); - - step = sequencer.addStep(OPTYPE.SET_PATH, ObexTest.getResponsecodevalidator()); - hs = new HeaderSet(); - hs.setHeader(HeaderSet.NAME, "msg"); - step.mReqHeaders = hs; - step.mClientPostAction = new MapSetClientFolder("msg"); - - // The msg folder - step = sequencer.addStep(OPTYPE.GET, null); - hs = new HeaderSet(); - hs.setHeader(HeaderSet.TYPE, MapObexLevelTest.TYPE_GET_FOLDER_LISTING); - step.mReqHeaders = hs; - step.mValidator = new MapBuildFolderStructurValidator(5, buildDefaultFolderStructure()); - } - - /** - * Sets the current folder on the client, to the folder name specified in the constructor. - * TODO: Could be extended to be able to navigate back and forth in the folder structure. - */ - private static class MapSetClientFolder implements ISeqStepAction { - final String mFolderName; - public MapSetClientFolder(String folderName) { - super(); - this.mFolderName = folderName; - } - @Override - public void execute(SeqStep step, HeaderSet request, Operation op) - throws IOException { - MapBuildFolderStructurValidator.sCurrentFolder = - MapBuildFolderStructurValidator.sCurrentFolder.getSubFolder(mFolderName); - Assert.assertNotNull(MapBuildFolderStructurValidator.sCurrentFolder); - Log.i(TAG, "MapSetClientFolder(): Current path: " + - MapBuildFolderStructurValidator.sCurrentFolder.getFullPath()); - } - } - - /* Functions to validate results */ - private static class MapBuildFolderStructurValidator implements ISeqStepValidator { - - final int mExpectedListingSize; - static BluetoothMapFolderElement sCurrentFolder = null; - final BluetoothMapFolderElement mExpectedFolderElement; - - public MapBuildFolderStructurValidator(int mExpectedListingSize, - BluetoothMapFolderElement folderElement) { - super(); - if(sCurrentFolder == null) { - sCurrentFolder = new BluetoothMapFolderElement("root", null); - } - this.mExpectedListingSize = mExpectedListingSize; - this.mExpectedFolderElement = folderElement; - } - - - @Override - public boolean validate(SeqStep step, HeaderSet response, Operation op) - throws IOException { - Assert.assertNotNull(op); - op.noBodyHeader(); - try { - // For some odd reason, the request will not be send before we start to read the - // reply data, hence we need to do this first? - sCurrentFolder.appendSubfolders(op.openInputStream()); - response = op.getReceivedHeader(); - byte[] appParamsRaw = (byte[])response.getHeader(HeaderSet.APPLICATION_PARAMETER); - Assert.assertNotNull(appParamsRaw); - BluetoothMapAppParams appParams; - appParams = new BluetoothMapAppParams(appParamsRaw); - Assert.assertNotNull(appParams); - if(mExpectedFolderElement != null) { - // Recursively compare - Assert.assertTrue(mExpectedFolderElement.compareTo(sCurrentFolder.getRoot()) - == 0); - } - int responseCode = op.getResponseCode(); - Assert.assertEquals(ResponseCodes.OBEX_HTTP_OK, responseCode); - op.close(); - } catch (Exception e) { - Log.e(TAG,"",e); - Assert.fail(); - } - return true; - } - - } - - - private static BluetoothMapFolderElement buildDefaultFolderStructure(){ - BluetoothMapFolderElement root = - new BluetoothMapFolderElement("root", null); // This will be the root element - BluetoothMapFolderElement tmpFolder; - tmpFolder = root.addFolder("telecom"); // root/telecom - tmpFolder = tmpFolder.addFolder("msg"); // root/telecom/msg - tmpFolder.addFolder("inbox"); // root/telecom/msg/inbox - tmpFolder.addFolder("outbox"); // root/telecom/msg/outbox - tmpFolder.addFolder("sent"); // root/telecom/msg/sent - tmpFolder.addFolder("deleted"); // root/telecom/msg/deleted - tmpFolder.addFolder("draft"); // root/telecom/msg/draft - return root; - } - - -} diff --git a/tests/src/com/android/bluetooth/tests/MapTestData.java b/tests/src/com/android/bluetooth/tests/MapTestData.java deleted file mode 100644 index 561b91e6..00000000 --- a/tests/src/com/android/bluetooth/tests/MapTestData.java +++ /dev/null @@ -1,285 +0,0 @@ -package com.android.bluetooth.tests; - -import java.io.IOException; -import java.util.Date; - -import javax.obex.HeaderSet; -import javax.obex.Operation; - -import android.annotation.TargetApi; -import android.content.ContentResolver; -import android.content.ContentValues; -import android.content.Context; -import android.net.Uri; -import android.provider.ContactsContract; -import android.provider.Telephony.Sms; -import android.test.AndroidTestCase; -import android.util.Log; - -import com.android.bluetooth.map.BluetoothMapConvoContactElement; -import com.android.bluetooth.map.BluetoothMapConvoListing; -import com.android.bluetooth.map.BluetoothMapConvoListingElement; - -/** - * Class to hold test data - both the server side data to insert into the databases, and the - * validation data to validate the result, when reading back the data. - * - * Should be data only, not operation specific functionality (client). - * - * Please try to keep useful functionality call-able from a test case, to make it possible - * to call a single test case to e.g. inject some contacts or messages into the database. - * - */ -@TargetApi(20) -public class MapTestData extends AndroidTestCase { - private static final String TAG = "MapTestData"; - - /* Test validation variables */ - static final String TEST_CONTACT_NAME = "Jesus Überboss"; - static final String TEST_CONTACT_PHONE = "55566688"; - static final String TEST_CONTACT_EMAIL = "boss@the.skyes"; - static final int TEST_NUM_CONTACTS = 3; - - static final int TEST_ADD_CONTACT_PER_ITERATIONS = 4; - /* I do know this function is deprecated, but I'm unable to find a good alternative - * except from taking a copy of the Date.UTC function as suggested. */ - // NOTE: This will only set the data on the message - not the lastActivity on SMS/MMS threads - static final long TEST_ACTIVITY_BEGIN = Date.UTC( - 2014-1900, - 8-1, /* month 0-11*/ - 22, /*day 1-31 */ - 22, /*hour*/ - 15, /*minute*/ - 20 /*second*/); - - static final String TEST_ACTIVITY_BEGIN_STRING = "20150102T150047"; - static final String TEST_ACTIVITY_END_STRING = "20160102T150047"; - - static final int TEST_ACTIVITY_INTERVAL = 5*60*1000; /*ms*/ - - static Context sContext = null; - public static void init(Context context){ - sContext = context; - } - /** - * Adds messages to the SMS message database. - */ - public static class MapAddSmsMessages implements ISeqStepAction { - int mCount; - /** - * - * @param count the number of iterations to execute - */ - public MapAddSmsMessages(int count) { - mCount = count; - } - - @Override - public void execute(SeqStep step, HeaderSet request, Operation op) - throws IOException { - int count = mCount; // Number of messages in each conversation - ContentResolver resolver = sContext.getContentResolver(); - - // Insert some messages - insertTestMessages(resolver, step.index, count); - - // Cleanup if needed to avoid duplicates - deleteTestContacts(resolver); - - // And now add the contacts - setupTestContacts(resolver); - } - } - - /** - * TODO: Only works for filter on TEST_CONTACT_NAME - * @param maxCount - * @param offset - * @param filterContact - * @param read - * @param reportRead - * @param msgCount - * @return - */ - public static BluetoothMapConvoListing getConvoListingReference(int maxCount, int offset, - boolean filterContact, boolean read, boolean reportRead, int msgCount){ - BluetoothMapConvoListing list = new BluetoothMapConvoListing(); - BluetoothMapConvoListingElement element; - BluetoothMapConvoContactElement contact; - element = new BluetoothMapConvoListingElement(); - element.setRead(read, reportRead); - element.setVersionCounter(0); - contact = new BluetoothMapConvoContactElement(); - contact.setName(TEST_CONTACT_NAME); - contact.setLastActivity(TEST_ACTIVITY_BEGIN + - msgCount*TEST_ADD_CONTACT_PER_ITERATIONS*TEST_ACTIVITY_INTERVAL); - element.addContact(contact); - list.add(element); - return null; - } - - public static void insertTestMessages(ContentResolver resolver, int tag, int count) { - ContentValues values[] = new ContentValues[count*4]; // 4 messages/iteration - long date = TEST_ACTIVITY_BEGIN; - Log.i(TAG, "Preparing messages... with data = " + date); - - for (int x = 0;x < count;x++){ - /* NOTE: Update TEST_ADD_CONTACT_PER_ITERATIONS if more messages are added */ - ContentValues item = new ContentValues(5); - item.put("address", "98765432"); - item.put("body", "test message " + x + " step index: " + tag); - item.put("date", date+=TEST_ACTIVITY_INTERVAL); - item.put("read", "0"); - if(x%2 == 0) { - item.put("type", Sms.MESSAGE_TYPE_INBOX); - } else { - item.put("type", Sms.MESSAGE_TYPE_SENT); - } - values[x] = item; - - item = new ContentValues(5); - item.put("address", "23456780"); - item.put("body", "test message " + x + " step index: " + tag); - item.put("date", date += TEST_ACTIVITY_INTERVAL); - item.put("read", "0"); - if(x%2 == 0) { - item.put("type", Sms.MESSAGE_TYPE_INBOX); - } else { - item.put("type", Sms.MESSAGE_TYPE_SENT); - } - values[count+x] = item; - - item = new ContentValues(5); - item.put("address", "+4523456780"); - item.put("body", "test message "+x+" step index: " + tag); - item.put("date", date += TEST_ACTIVITY_INTERVAL); - item.put("read", "0"); - if(x%2 == 0) { - item.put("type", Sms.MESSAGE_TYPE_INBOX); - } else { - item.put("type", Sms.MESSAGE_TYPE_SENT); - } - values[2*count+x] = item; - - /* This is the message used for test */ - item = new ContentValues(5); - item.put("address", TEST_CONTACT_PHONE); - item.put("body", "test message "+x+" step index: " + tag); - item.put("date", date += TEST_ACTIVITY_INTERVAL); - item.put("read", "0"); - if(x%2 == 0) { - item.put("type", Sms.MESSAGE_TYPE_INBOX); - } else { - item.put("type", Sms.MESSAGE_TYPE_SENT); - } - values[3*count+x] = item; - } - - Log.i(TAG, "Starting bulk insert..."); - resolver.bulkInsert(Uri.parse("content://sms"), values); - Log.i(TAG, "Bulk insert done."); - } - - /** - * Insert a few contacts in the main contact database, using a test account. - */ - public static void setupTestContacts(ContentResolver resolver){ - /*TEST_NUM_CONTACTS must be updated if this function is changed */ - insertContact(resolver, "Hans Hansen", "98765432", "hans@hansens.global"); - insertContact(resolver, "Helle Børgesen", "23456780", "hb@gmail.com"); - insertContact(resolver, TEST_CONTACT_NAME, TEST_CONTACT_PHONE, TEST_CONTACT_EMAIL); - } - - /** - * Helper function to insert a contact - * @param name - * @param phone - * @param email - */ - private static void insertContact(ContentResolver resolver, String name, String phone, String email) { - // Get the account info - //Cursor c = resolver.query(uri, projection, selection, selectionArgs, sortOrder) - ContentValues item = new ContentValues(3); - item.put(ContactsContract.RawContacts.ACCOUNT_TYPE, "test_account"); - item.put(ContactsContract.RawContacts.ACCOUNT_NAME, "MAP account"); - Uri uri = resolver.insert(ContactsContract.RawContacts.CONTENT_URI, item); - Log.i(TAG, "Inserted RawContact: " + uri); - long rawId = Long.parseLong(uri.getLastPathSegment()); - - //Now add contact information - item = new ContentValues(3); - item.put(ContactsContract.Data.RAW_CONTACT_ID, rawId); - item.put(ContactsContract.Data.MIMETYPE, - ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE); - item.put(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, - name); - resolver.insert(ContactsContract.Data.CONTENT_URI, item); - - if(phone != null) { - item = new ContentValues(3); - item.put(ContactsContract.Data.RAW_CONTACT_ID, rawId); - item.put(ContactsContract.Data.MIMETYPE, - ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE); - item.put(ContactsContract.CommonDataKinds.Phone.NUMBER, phone); - resolver.insert(ContactsContract.Data.CONTENT_URI, item); - } - - if(email != null) { - item = new ContentValues(3); - item.put(ContactsContract.Data.RAW_CONTACT_ID, rawId); - item.put(ContactsContract.Data.MIMETYPE, - ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE); - item.put(ContactsContract.CommonDataKinds.Email.ADDRESS, email); - resolver.insert(ContactsContract.Data.CONTENT_URI, item); - } - } - - /** - * Delete all contacts belonging to the test_account. - */ - public static void deleteTestContacts(ContentResolver resolver){ - resolver.delete(ContactsContract.RawContacts.CONTENT_URI, - ContactsContract.RawContacts.ACCOUNT_TYPE + "=\"test_account\"", null); - } - - /**************************************************************************** - * Small test cases to trigger the functionality without running a sequence. - ****************************************************************************/ - /** - * Insert a few contacts in the main contact database, using a test account. - */ - public void testInsertMessages() { - ContentResolver resolver = mContext.getContentResolver(); - insertTestMessages(resolver, 1234, 10); - } - - public void testInsert1000Messages() { - ContentResolver resolver = mContext.getContentResolver(); - insertTestMessages(resolver, 1234, 1000); - } - - /** - * Insert a few contacts in the main contact database, using a test account. - */ - public void testSetupContacts() { - ContentResolver resolver = mContext.getContentResolver(); - setupTestContacts(resolver); - } - - /** - * Delete all contacts belonging to the test_account. - */ - public void testDeleteTestContacts() { - ContentResolver resolver = mContext.getContentResolver(); - deleteTestContacts(resolver); - } - - public void testSetup1000Contacts() { - ContentResolver resolver = mContext.getContentResolver(); - for(int i = 0; i < 1000; i++) { - insertContact(resolver, "Hans Hansen " + i, - "98765431" + i, "hans" + i + "@hansens.global"); - } - } - -} diff --git a/tests/src/com/android/bluetooth/tests/MockMasInstance.java b/tests/src/com/android/bluetooth/tests/MockMasInstance.java deleted file mode 100644 index 07de8e49..00000000 --- a/tests/src/com/android/bluetooth/tests/MockMasInstance.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.android.bluetooth.tests; - -import com.android.bluetooth.map.BluetoothMapMasInstance; -import junit.framework.Assert; - -public class MockMasInstance extends BluetoothMapMasInstance { - - private final int mMasId; - private final int mRemoteFeatureMask; - - public MockMasInstance(int masId, int remoteFeatureMask) { - super(); - this.mMasId = masId; - this.mRemoteFeatureMask = remoteFeatureMask; - } - - public int getMasId() { - return mMasId; - } - - @Override - public int getRemoteFeatureMask() { - return mRemoteFeatureMask; - } - - @Override - public void restartObexServerSession() { - Assert.fail("restartObexServerSession() should not occur"); - } -} diff --git a/tests/src/com/android/bluetooth/tests/ObexPipeTransport.java b/tests/src/com/android/bluetooth/tests/ObexPipeTransport.java deleted file mode 100644 index c63f6641..00000000 --- a/tests/src/com/android/bluetooth/tests/ObexPipeTransport.java +++ /dev/null @@ -1,89 +0,0 @@ -/* -* Copyright (C) 2015 Samsung System LSI -* 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.android.bluetooth.tests; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -import javax.obex.ObexTransport; - -public class ObexPipeTransport implements ObexTransport { - InputStream mInStream; - OutputStream mOutStream; - boolean mEnableSrm; - - public ObexPipeTransport(InputStream inStream, - OutputStream outStream, boolean enableSrm) { - mInStream = inStream; - mOutStream = outStream; - mEnableSrm = enableSrm; - } - - public void close() throws IOException { - mInStream.close(); - mOutStream.close(); - } - - public DataInputStream openDataInputStream() throws IOException { - return new DataInputStream(openInputStream()); - } - - public DataOutputStream openDataOutputStream() throws IOException { - return new DataOutputStream(openOutputStream()); - } - - public InputStream openInputStream() throws IOException { - return mInStream; - } - - public OutputStream openOutputStream() throws IOException { - return mOutStream; - } - - public void connect() throws IOException { - } - - public void create() throws IOException { - } - - public void disconnect() throws IOException { - } - - public void listen() throws IOException { - } - - public boolean isConnected() throws IOException { - return true; - } - - public int getMaxTransmitPacketSize() { - return 3*15432; - } - - public int getMaxReceivePacketSize() { - return 2*23450; - } - - @Override - public boolean isSrmSupported() { - return mEnableSrm; - } - -} - diff --git a/tests/src/com/android/bluetooth/tests/ObexTest.java b/tests/src/com/android/bluetooth/tests/ObexTest.java deleted file mode 100644 index cff95833..00000000 --- a/tests/src/com/android/bluetooth/tests/ObexTest.java +++ /dev/null @@ -1,711 +0,0 @@ -/* -* Copyright (C) 2014 Samsung System LSI -* -* 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.android.bluetooth.tests; - -import java.io.IOException; -import java.io.PipedInputStream; -import java.io.PipedOutputStream; -import java.util.ArrayList; -import java.util.concurrent.CountDownLatch; - -import javax.obex.HeaderSet; -import javax.obex.ObexTransport; -import javax.obex.Operation; -import javax.obex.ResponseCodes; -import javax.obex.ServerRequestHandler; - -import junit.framework.Assert; -import android.annotation.TargetApi; -import android.bluetooth.BluetoothAdapter; -import android.bluetooth.BluetoothDevice; -import android.bluetooth.BluetoothServerSocket; -import android.bluetooth.BluetoothSocket; -import android.bluetooth.BluetoothUuid; -import android.bluetooth.SdpMasRecord; -import android.content.BroadcastReceiver; -import android.content.Context; -import android.content.Intent; -import android.content.IntentFilter; -import android.net.LocalServerSocket; -import android.net.LocalSocket; -import android.os.Build; -import android.os.Debug; -import android.os.ParcelUuid; -import android.test.AndroidTestCase; -import android.util.Log; - -import com.android.bluetooth.BluetoothObexTransport; -import com.android.bluetooth.sdp.SdpManager; -import com.android.bluetooth.tests.TestSequencer.OPTYPE; - -/** - * Test either using the reference ril without a modem, or using a RIL implementing the - * BT SAP API, by providing the rild-bt socket as well as the extended API functions for SAP. - * - */ -@TargetApi(Build.VERSION_CODES.KITKAT) -public class ObexTest extends AndroidTestCase implements ITestSequenceConfigurator { - protected static String TAG = "ObexTest"; - protected static final boolean D = true; - protected static final boolean TRACE = false; - protected static final boolean DELAY_PASS_30_SEC = false; - public static final long PROGRESS_INTERVAL_MS = 1000; - private static final ObexTestParams defaultParams = - new ObexTestParams(2*8092, 0, 2*1024*1024); - - private static final ObexTestParams throttle100Params = - new ObexTestParams(2*8092, 100000, 1024*1024); - - private static final ObexTestParams smallParams = - new ObexTestParams(2*8092, 0, 2*1024); - - private static final ObexTestParams hugeParams = - new ObexTestParams(2*8092, 0, 100*1024*1024); - - private static final int SMALL_OPERATION_COUNT = 1000; - private static final int CONNECT_OPERATION_COUNT = 4500; - - private static final int L2CAP_PSM = 29; /* If SDP is not used */ - private static final int RFCOMM_CHANNEL = 29; /* If SDP is not used */ - - public static final String SERVER_ADDRESS = "F8:CF:C5:A8:70:7E"; - - private static final String SDP_SERVER_NAME = "Samsung Server"; - private static final String SDP_CLIENT_NAME = "Samsung Client"; - - private static final long SDP_FEATURES = 0x87654321L; /* 32 bit */ - private static final int SDP_MSG_TYPES = 0xf1; /* 8 bit */ - private static final int SDP_MAS_ID = 0xCA; /* 8 bit */ - private static final int SDP_VERSION = 0xF0C0; /* 16 bit */ - public static final ParcelUuid SDP_UUID_OBEX_MAS = BluetoothUuid.MAS; - - private static int sSdpHandle = -1; - private static final ObexTestDataHandler sDataHandler = new ObexTestDataHandler("(Client)"); - private static final ISeqStepValidator sResponseCodeValidator = new ResponseCodeValidator(); - private static final ISeqStepValidator sDataValidator = new DataValidator(); - - - private enum SequencerType { - SEQ_TYPE_PAYLOAD, - SEQ_TYPE_CONNECT_DISCONNECT - } - - private Context mContext = null; - private int mChannelType = 0; - - public ObexTest() { - super(); - } - - /** - * Test that a connection can be established. - * WARNING: The performance of the pipe implementation is not good. I'm only able to get a - * throughput of around 220 kbyte/sec - less that when using Bluetooth :-) - * UPDATE: Did a local socket implementation below to replace this... - * This has a throughput of more than 4000 kbyte/s - */ - public void testLocalPipes() { - mContext = this.getContext(); - System.out.println("Setting up pipes..."); - - PipedInputStream clientInStream = null; - PipedOutputStream clientOutStream = null; - PipedInputStream serverInStream = null; - PipedOutputStream serverOutStream = null; - ObexPipeTransport clientTransport = null; - ObexPipeTransport serverTransport = null; - - try { - /* Create and interconnect local pipes for transport */ - clientInStream = new PipedInputStream(5*8092); - clientOutStream = new PipedOutputStream(); - serverInStream = new PipedInputStream(clientOutStream, 5*8092); - serverOutStream = new PipedOutputStream(clientInStream); - - /* Create the OBEX transport objects to wrap the pipes - enable SRM */ - clientTransport = new ObexPipeTransport(clientInStream, clientOutStream, true); - serverTransport = new ObexPipeTransport(serverInStream, serverOutStream, true); - - TestSequencer sequencer = createBtPayloadTestSequence(clientTransport, serverTransport); - - assertTrue(sequencer.run(mContext)); - } catch (IOException e) { - Log.e(TAG, "IOException", e); - } - } - - /** - * Run the test sequence using a local socket. - * Throughput around 4000 kbyte/s - with a larger OBEX package size. - */ - public void testLocalSockets() { - mContext = this.getContext(); - System.out.println("Setting up sockets..."); - - try { - /* Create and interconnect local pipes for transport */ - LocalServerSocket serverSock = new LocalServerSocket("com.android.bluetooth.tests.sock"); - LocalSocket clientSock = new LocalSocket(); - LocalSocket acceptSock; - - clientSock.connect(serverSock.getLocalSocketAddress()); - - acceptSock = serverSock.accept(); - - /* Create the OBEX transport objects to wrap the pipes - enable SRM */ - ObexPipeTransport clientTransport = new ObexPipeTransport(clientSock.getInputStream(), - clientSock.getOutputStream(), true); - ObexPipeTransport serverTransport = new ObexPipeTransport(acceptSock.getInputStream(), - acceptSock.getOutputStream(), true); - - TestSequencer sequencer = createBtPayloadTestSequence(clientTransport, serverTransport); - - assertTrue(sequencer.run(mContext)); - - clientSock.close(); - acceptSock.close(); - serverSock.close(); - } catch (IOException e) { - Log.e(TAG, "IOException", e); - } - } - - /* Create a sequence of put/get operations with different payload sizes */ - private TestSequencer createBtPayloadTestSequence(ObexTransport clientTransport, - ObexTransport serverTransport) - throws IOException { - TestSequencer sequencer = new TestSequencer(clientTransport, serverTransport, this); - SeqStep step; - - step = sequencer.addStep(OPTYPE.CONNECT, sResponseCodeValidator); - if(false){ - - step = sequencer.addStep(OPTYPE.PUT, sDataValidator); - step.mParams = defaultParams; - step.mUseSrm = true; - - step = sequencer.addStep(OPTYPE.GET, sDataValidator); - step.mParams = defaultParams; - step.mUseSrm = true; - - step = sequencer.addStep(OPTYPE.PUT, sDataValidator); - step.mParams = throttle100Params; - step.mUseSrm = true; - - step = sequencer.addStep(OPTYPE.GET, sDataValidator); - step.mParams = throttle100Params; - step.mUseSrm = true; - - for(int i=0; i= 0) { - SdpManager.getDefaultManager().removeSdpRecord(sSdpHandle); - } - Log.d(TAG, "Creating record with rfcomm channel: " + rfcommChannel + - " and l2cap channel: " + l2capPsm); - sSdpHandle = SdpManager.getDefaultManager().createMapMasRecord(SDP_SERVER_NAME, - SDP_MAS_ID, rfcommChannel, l2capPsm, - SDP_VERSION, SDP_MSG_TYPES, (int)(SDP_FEATURES & 0xffffffff)); - } else { - Log.d(TAG, "SKIP creation of record with rfcomm channel: " + rfcommChannel + - " and l2cap channel: " + l2capPsm); - } - return serverSocket; - } - - public static void removeSdp() { - if(sSdpHandle > 0) { - SdpManager.getDefaultManager().removeSdpRecord(sSdpHandle); - sSdpHandle = -1; - } - } - - /** - * Server side of a two device Bluetooth test of OBEX - */ - private void testBtServer(int type, boolean useSdp, SequencerType sequencerType) { - mContext = this.getContext(); - Log.d(TAG,"Starting BT Server..."); - - if(TRACE) Debug.startMethodTracing("ServerSide"); - try { - BluetoothServerSocket serverSocket=createServerSocket(type, useSdp); - - Log.i(TAG, "Waiting for client to connect"); - BluetoothSocket socket = serverSocket.accept(); - Log.i(TAG, "Client connected"); - - BluetoothObexTransport serverTransport = new BluetoothObexTransport(socket); - TestSequencer sequencer = null; - switch(sequencerType) { - case SEQ_TYPE_CONNECT_DISCONNECT: - sequencer = createBtConnectTestSequence(null, serverTransport); - break; - case SEQ_TYPE_PAYLOAD: - sequencer = createBtPayloadTestSequence(null, serverTransport); - break; - default: - fail("Invalid sequencer type"); - break; - - } - assertTrue(sequencer.run(mContext)); - // Same as below... serverTransport.close(); - // This is done by the obex server socket.close(); - serverSocket.close(); - removeSdp(); - sequencer.shutdown(); - } catch (IOException e) { - Log.e(TAG, "IOException", e); - } - if(TRACE) Debug.stopMethodTracing(); - if(DELAY_PASS_30_SEC) { - Log.i(TAG, "\n\n\nTest done - please fetch logs within 30 seconds...\n\n\n"); - try { - Thread.sleep(30000); - } catch (InterruptedException e) {} - } - Log.i(TAG, "Test done."); - } - - /** - * Enable Bluetooth and connect to a server socket - * @param type - * @param useSdp - * @param context - * @return - * @throws IOException - */ - static public BluetoothSocket connectClientSocket(int type, boolean useSdp, Context context) - throws IOException { - int rfcommChannel = RFCOMM_CHANNEL; - int l2capPsm = L2CAP_PSM; - - BluetoothAdapter bt = BluetoothAdapter.getDefaultAdapter(); - if(bt == null) { - Log.e(TAG,"No Bluetooth Device!"); - assertTrue(false); - } - BluetoothTestUtils.enableBt(bt); - BluetoothDevice serverDevice = bt.getRemoteDevice(SERVER_ADDRESS); - - if(useSdp == true) { - SdpMasRecord record = clientAwaitSdp(serverDevice, context); - rfcommChannel = record.getRfcommCannelNumber(); - l2capPsm = record.getL2capPsm(); - } - - BluetoothSocket socket = null; - if(type == BluetoothSocket.TYPE_L2CAP) { - socket = serverDevice.createL2capSocket(l2capPsm); - } else if(type == BluetoothSocket.TYPE_RFCOMM) { - socket = serverDevice.createRfcommSocket(rfcommChannel); - } else { - fail("Invalid transport type!"); - } - - socket.connect(); - - return socket; - } - - /** - * Test that a connection can be established. - */ - private void testBtClient(int type, boolean useSdp, SequencerType sequencerType) { - mContext = this.getContext(); - mChannelType = type; - BluetoothSocket socket = null; - System.out.println("Starting BT Client..."); - if(TRACE) Debug.startMethodTracing("ClientSide"); - try { - socket = connectClientSocket(type, useSdp, mContext); - - BluetoothObexTransport clientTransport = new BluetoothObexTransport(socket); - - TestSequencer sequencer = null; - switch(sequencerType) { - case SEQ_TYPE_CONNECT_DISCONNECT: - sequencer = createBtConnectTestSequence(clientTransport, null); - break; - case SEQ_TYPE_PAYLOAD: - sequencer = createBtPayloadTestSequence(clientTransport, null); - break; - default: - fail("Invalid test type"); - break; - - } - assertTrue(sequencer.run(mContext)); - socket.close(); // Only the streams are closed by the obex client - sequencer.shutdown(); - - } catch (IOException e) { - Log.e(TAG, "IOException", e); - } - if(TRACE) Debug.stopMethodTracing(); - if(DELAY_PASS_30_SEC) { - Log.i(TAG, "\n\n\nTest done - please fetch logs within 30 seconds...\n\n\n"); - try { - Thread.sleep(30000); - } catch (InterruptedException e) {} - } - Log.i(TAG, "Test done."); - } - - /* Using an anonymous class is not efficient, but keeps a tight code structure. */ - static class SdpBroadcastReceiver extends BroadcastReceiver { - private SdpMasRecord mMasRecord; /* A non-optimal way of setting an object reference from - a anonymous class. */ - final CountDownLatch mLatch; - public SdpBroadcastReceiver(CountDownLatch latch) { - mLatch = latch; - } - - SdpMasRecord getMasRecord() { - return mMasRecord; - } - - @Override - public void onReceive(Context context, Intent intent) { - Log.d(TAG, "onReceive"); - String action = intent.getAction(); - if (action.equals(BluetoothDevice.ACTION_SDP_RECORD)){ - Log.v(TAG, "Received ACTION_SDP_RECORD."); - ParcelUuid uuid = intent.getParcelableExtra(BluetoothDevice.EXTRA_UUID); - Log.v(TAG, "Received UUID: " + uuid.toString()); - Log.v(TAG, "existing UUID: " + SDP_UUID_OBEX_MAS.toString()); - if(uuid.toString().equals(SDP_UUID_OBEX_MAS.toString())) { - assertEquals(SDP_UUID_OBEX_MAS.toString(), uuid.toString()); - Log.v(TAG, " -> MAS UUID in result."); - SdpMasRecord record = intent.getParcelableExtra( - BluetoothDevice.EXTRA_SDP_RECORD); - assertNotNull(record); - Log.v(TAG, " -> record: "+record); - if(record.getServiceName().equals(SDP_SERVER_NAME)) { - - assertEquals(((long)record.getSupportedFeatures()) - &0xffffffffL, SDP_FEATURES); - - assertEquals(record.getSupportedMessageTypes(), SDP_MSG_TYPES); - - assertEquals(record.getProfileVersion(), SDP_VERSION); - - assertEquals(record.getServiceName(), SDP_SERVER_NAME); - - assertEquals(record.getMasInstanceId(), SDP_MAS_ID); - - int status = intent.getIntExtra(BluetoothDevice.EXTRA_SDP_SEARCH_STATUS, - -1); - Log.v(TAG, " -> status: "+status); - mMasRecord = record; - mLatch.countDown(); - } else { - Log.i(TAG, "Wrong service name (" + record.getServiceName() - + ") received, still waiting..."); - } - } else { - Log.i(TAG, "Wrong UUID received, still waiting..."); - } - } else { - fail("Unexpected intent received???"); - } - } - }; - - - private static SdpMasRecord clientAwaitSdp(BluetoothDevice serverDevice, Context context) { - IntentFilter filter = new IntentFilter(); - filter.addAction(BluetoothDevice.ACTION_SDP_RECORD); - final CountDownLatch latch = new CountDownLatch(1); - SdpBroadcastReceiver broadcastReceiver = new SdpBroadcastReceiver(latch); - - context.registerReceiver(broadcastReceiver, filter); - - serverDevice.sdpSearch(SDP_UUID_OBEX_MAS); - boolean waiting = true; - while(waiting == true) { - try { - Log.i(TAG, "SDP Search requested - awaiting result..."); - latch.await(); - Log.i(TAG, "SDP Search reresult received - continueing."); - waiting = false; - } catch (InterruptedException e) { - Log.w(TAG, "Interrupted witle waiting - keep waiting.", e); - waiting = true; - } - } - context.unregisterReceiver(broadcastReceiver); - return broadcastReceiver.getMasRecord(); - } - - @Override - public ServerRequestHandler getObexServer(ArrayList sequence, - CountDownLatch stopLatch) { - return new ObexTestServer(sequence, stopLatch); - } - - - -} - diff --git a/tests/src/com/android/bluetooth/tests/ObexTestDataHandler.java b/tests/src/com/android/bluetooth/tests/ObexTestDataHandler.java deleted file mode 100644 index 220698ac..00000000 --- a/tests/src/com/android/bluetooth/tests/ObexTestDataHandler.java +++ /dev/null @@ -1,154 +0,0 @@ -package com.android.bluetooth.tests; - -import android.util.Log; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -public class ObexTestDataHandler { - - final String TAG; - String TAG_BASE = "ObexTestDataHandler"; - static final boolean V = true; - - private static final long PROGRESS_INTERVAL_MS = 1000; - int mBufferSize = 0; - int mThrottle = 0; - long mBytesToTransfer = 0; - long mBytesTransfered = 0; - long mStartTime = 0; - long mLastReport = 0; - IResultLogger mResults; - - public ObexTestDataHandler(String tag) { - TAG = TAG_BASE + tag; - } - - /** - * Call after a sleep to calculate the number of buffers to - * send to match the throttle value. - * - * @param bufferSize - * @param throttle - * @return the number of buffers to send, to match the throttle value - */ - private int getNumberOfBuffers() { - if(mThrottle == 0) { - return 1; - } - long deltaT = System.currentTimeMillis() - mStartTime; - long deltaB = deltaT*mThrottle/1000; // the amount of bytes we should have sent - long bytesMissing = deltaB-mBytesTransfered; - return (int)((bytesMissing+(mBufferSize>>1))/mBufferSize); // Round result - } - - private void publishProgressIfNeeded() { - long now = System.currentTimeMillis(); - if((now-mLastReport) > PROGRESS_INTERVAL_MS) { - mLastReport = now; - String result = "Avg: " + mResults.getAverageSpeed()/1024 - + " Avg(1s): " + mResults.getAverageSpeed(1000)/1024 + - " mBytesTransfered: " + mBytesTransfered + "\n"; - if(V) Log.v(TAG,result); - } - } - - public void readData(InputStream inStream, ObexTestParams params) { - /* TODO: parse in the step params - * Consider introducing a testStep prepare and wait for completion interface? - * in stead of using OBEX headers to carry the index... */ - - mBufferSize = params.packageSize; - mThrottle = params.throttle; - mBytesToTransfer = params.bytesToSend; - mBytesTransfered = 0; - mResults = TestResultLogger.createLogger(); - mStartTime = System.currentTimeMillis(); - - byte[] buffer = new byte[params.packageSize]; - if(V) Log.v(TAG, "readData() started data to read: " + params.bytesToSend); - try { - while(mBytesTransfered < mBytesToTransfer) { - int nRx = getNumberOfBuffers(); - for(; nRx > 0 ; nRx--) { - if(V) Log.v(TAG, "Read()"); - int count = inStream.read(buffer); - if(V) Log.v(TAG, "Read() done - count=" + count); - if(count == -1) { - throw new IOException("EOF reached too early mBytesTransfered=" + mBytesTransfered); - } - mBytesTransfered += count; - if(mBytesTransfered >= mBytesToTransfer) { - nRx=0; // break - } - mResults.addResult(mBytesTransfered); - publishProgressIfNeeded(); - } - if(mThrottle != 0) { - // Sleep one package of time. - try { - long sleepTime = (1000*mBufferSize)/mThrottle; - if(V) Log.v(TAG, "Throttle Sleep():" + sleepTime); - Thread.sleep(sleepTime); - } catch (InterruptedException e) { - // Just ignore as the getNumberOfBuffersToSend will compensate - // TODO: Handle Abort - } - } - } - } - catch(IOException e) { - Log.e(TAG, "Error in readData():",e); - } finally { - } - } - - public void writeData(OutputStream outStream, ObexTestParams params) { - mBufferSize = params.packageSize; - mThrottle = params.throttle; - mBytesToTransfer= params.bytesToSend; - mBytesTransfered = 0; - mResults = TestResultLogger.createLogger(); - mStartTime = System.currentTimeMillis(); - - byte[] buffer = new byte[params.packageSize]; - if(V) Log.v(TAG, "writeData() started data to write: " + params.bytesToSend); - try { - while(mBytesTransfered < mBytesToTransfer) { - int nTx = getNumberOfBuffers(); - if(V) Log.v(TAG, "Write nTx " + nTx + " packets"); - for(; nTx > 0 ; nTx--) { - if(V) Log.v(TAG, "Write()"); - if((mBytesTransfered + mBufferSize) < mBytesToTransfer) { - outStream.write(buffer); - mBytesTransfered += mBufferSize; - } else { - outStream.write(buffer, 0, (int) (mBytesToTransfer-mBytesTransfered)); - mBytesTransfered += mBytesToTransfer-mBytesTransfered; - nTx = 0; - } - mResults.addResult(mBytesTransfered); - publishProgressIfNeeded(); - if(V) Log.v(TAG, "Write mBytesTransfered: " + mBytesTransfered); - } - if(mThrottle != 0) { - // Sleep one package of time. - try { - long sleepTime = (1000*mBufferSize)/mThrottle; - if(V) Log.v(TAG, "Throttle Sleep():" + sleepTime); - Thread.sleep(sleepTime); - } catch (InterruptedException e) { - // Just ignore as the getNumberOfBuffersToSend will compensate - // TODO: Handle Abort - } - - } - - } - } - catch(IOException e) { - Log.e(TAG, "Error in ListenTask:",e); - } - } -} diff --git a/tests/src/com/android/bluetooth/tests/ObexTestParams.java b/tests/src/com/android/bluetooth/tests/ObexTestParams.java deleted file mode 100644 index 470bae55..00000000 --- a/tests/src/com/android/bluetooth/tests/ObexTestParams.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.android.bluetooth.tests; - -public class ObexTestParams { - - public int packageSize; - public int throttle; - public long bytesToSend; - - public ObexTestParams(int packageSize, int throttle, long bytesToSend) { - this.packageSize = packageSize; - this.throttle = throttle; - this.bytesToSend = bytesToSend; - } -} diff --git a/tests/src/com/android/bluetooth/tests/ObexTestServer.java b/tests/src/com/android/bluetooth/tests/ObexTestServer.java deleted file mode 100644 index 1efe56d5..00000000 --- a/tests/src/com/android/bluetooth/tests/ObexTestServer.java +++ /dev/null @@ -1,142 +0,0 @@ -package com.android.bluetooth.tests; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.concurrent.CountDownLatch; - -import javax.obex.HeaderSet; -import javax.obex.Operation; -import javax.obex.ResponseCodes; -import javax.obex.ServerRequestHandler; - -import android.util.Log; - -public class ObexTestServer extends ServerRequestHandler { - - private static final String TAG = "ObexTestServer"; - private static final boolean V = true; - - ArrayList mSequence; - CountDownLatch mStopLatch; - - ObexTestDataHandler mDataHandler; - int mOperationIndex = 0; - - public ObexTestServer(ArrayList sequence, CountDownLatch stopLatch) { - super(); - mSequence = sequence; - mDataHandler = new ObexTestDataHandler("(Server)"); - mStopLatch = stopLatch; - } - - /* OBEX operation handlers */ - @Override - public int onConnect(HeaderSet request, HeaderSet reply) { - Log.i(TAG,"onConnect()"); - int index; - int result = ResponseCodes.OBEX_HTTP_OK; - try { - index = ((Long)request.getHeader(TestSequencer.STEP_INDEX_HEADER)).intValue(); - mOperationIndex = index; - } catch (IOException e) { - Log.e(TAG, "Exception in onConnect - aborting..."); - result = ResponseCodes.OBEX_HTTP_INTERNAL_ERROR; - // A read from null will produce exception to end the test. - } - /* TODO: validate request headers, and set response headers */ - return result; - } - - @Override - public void onDisconnect(HeaderSet request, HeaderSet reply) { - Log.i(TAG,"onDisconnect()"); - /* TODO: validate request headers, and set response headers */ - int index; - int result = ResponseCodes.OBEX_HTTP_OK; - try { - index = ((Long)request.getHeader(TestSequencer.STEP_INDEX_HEADER)).intValue(); - mOperationIndex = index; - } catch (IOException e) { - Log.e(TAG, "Exception in onDisconnect..."); - result = ResponseCodes.OBEX_HTTP_INTERNAL_ERROR; - // A read from null will produce exception to end the test. - } - if(mOperationIndex >= (mSequence.size()-1)) { - /* End of test, signal test runner thread */ - Log.i(TAG, "Sending latch close signal..."); - mStopLatch.countDown(); - } else { - Log.i(TAG, "Got disconnect with mOperationCounter = " + mOperationIndex); - } - reply.responseCode = result; - } - - @Override - public int onPut(Operation operation) { - Log.i(TAG,"onPut()"); - /* TODO: validate request headers, and set response headers - * Also handle pause/abort */ - // 1) Validate request - // 2) Open the output stream. - // 3) Receive the data - // 4) Send response OK - InputStream inStream; - int result = ResponseCodes.OBEX_HTTP_OK; - try{ - inStream = operation.openInputStream(); - HeaderSet reqHeaders = operation.getReceivedHeader(); - int index = ((Long)reqHeaders.getHeader(TestSequencer.STEP_INDEX_HEADER)).intValue(); - mOperationIndex = index; - mDataHandler.readData(inStream, mSequence.get(index).mParams); - } catch (IOException e) { - Log.e(TAG, "Exception in onPut - aborting..."); - inStream = null; - result = ResponseCodes.OBEX_HTTP_INTERNAL_ERROR; - // A read from null will produce exception to end the test. - } finally { - } - if(result == ResponseCodes.OBEX_HTTP_OK) { - Log.i(TAG, "OBEX-HANDLER: operation complete success"); - } else { - Log.e(TAG, "OBEX-HANDLER: operation complete FAILED!"); - } - return result; - } - - @Override - public int onGet(Operation operation) { - Log.i(TAG,"onGet()"); - /* TODO: validate request headers, and set response headers - * Also handle pause/abort */ - // 1) Validate request - // 2) Open the output stream. - // 3) Receive the data - // 4) Send response OK - OutputStream outStream; - int result = ResponseCodes.OBEX_HTTP_OK; - try{ - outStream = operation.openOutputStream(); - HeaderSet reqHeaders = operation.getReceivedHeader(); - int index = ((Long)reqHeaders.getHeader(TestSequencer.STEP_INDEX_HEADER)).intValue(); - mOperationIndex = index; - mDataHandler.writeData(outStream, mSequence.get(index).mParams); - } catch (IOException e) { - Log.e(TAG, "Exception in onGet - aborting..."); - outStream = null; - result = ResponseCodes.OBEX_HTTP_INTERNAL_ERROR; - // A read from null will produce exception to end the test. - } finally { - } - if(result == ResponseCodes.OBEX_HTTP_OK) { - Log.i(TAG, "OBEX-HANDLER: operation complete success"); - } else { - Log.e(TAG, "OBEX-HANDLER: operation complete FAILED!"); - } - return result; - } - - - -} diff --git a/tests/src/com/android/bluetooth/tests/SapServerTest.java b/tests/src/com/android/bluetooth/tests/SapServerTest.java deleted file mode 100644 index 3de3240a..00000000 --- a/tests/src/com/android/bluetooth/tests/SapServerTest.java +++ /dev/null @@ -1,608 +0,0 @@ -package com.android.bluetooth.tests; - -import java.io.IOException; -import java.io.PipedInputStream; -import java.io.PipedOutputStream; -import java.util.ArrayList; -import java.util.Arrays; - -import android.annotation.TargetApi; -import android.content.Context; -import android.content.Intent; -import android.os.Build; -import android.os.Handler; -import android.os.Handler.Callback; -import android.os.HandlerThread; -import android.os.Looper; -import android.os.Message; -import android.test.AndroidTestCase; -import android.util.Log; - -import com.android.bluetooth.sap.SapMessage; -import com.android.bluetooth.sap.SapServer; - -/** - * Test either using the reference ril without a modem, or using a RIL implementing the - * BT SAP API, by providing the rild-bt socket as well as the extended API functions for SAP. - * - */ -@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) -public class SapServerTest extends AndroidTestCase { - protected static String TAG = "SapServerTest"; - protected static final boolean D = true; - // Set the RIL driver in test mode, where request stubs are used instead - // of forwarding to the Modem/SIM. - private static final boolean rilTestModeEnabled = false; - private Context mContext = null; - - public SapServerTest() { - super(); - } - - private void buildDefaultInitSeq(SapSequencer sequencer) throws IOException { - SapMessage connectReq = new SapMessage(SapMessage.ID_CONNECT_REQ); - connectReq.setMaxMsgSize(276); - - SapMessage connectResp = new SapMessage(SapMessage.ID_CONNECT_RESP); - connectResp.setConnectionStatus(SapMessage.CON_STATUS_OK); - connectResp.setMaxMsgSize(0); /* shall be connection status (0) on success */ - - SapMessage statusInd = new SapMessage(SapMessage.ID_STATUS_IND); - statusInd.setStatusChange(SapMessage.STATUS_CARD_RESET); - - int index = sequencer.addStep(connectReq, connectResp); - sequencer.addSubStep(index, null, statusInd); - - } - /** - * Test that the SapServer is capable of handling a connect request with no call ongoing. - */ - public void testSapServerConnectSimple() { - mContext = this.getContext(); - - try { - - SapSequencer sequencer = new SapSequencer(); - if(rilTestModeEnabled) { - sequencer.testModeEnable(true); - } - /* Build a default init sequence */ - buildDefaultInitSeq(sequencer); - SapMessage disconnectReq = new SapMessage(SapMessage.ID_DISCONNECT_REQ); - SapMessage disconnectResp = new SapMessage(SapMessage.ID_DISCONNECT_RESP); - - SapMessage resetResp = new SapMessage(SapMessage.ID_RESET_SIM_RESP); - resetResp.setResultCode(SapMessage.RESULT_OK); - - int index = sequencer.addStep(disconnectReq, disconnectResp); - - assertTrue(sequencer.run()); - } catch (IOException e) { - Log.e(TAG, "IOException", e); - } - } - - public void testSapServerApiComplete() { - mContext = this.getContext(); - byte[] dummyBytes = {1, 2, 3, 4}; - - /* Select file '2FE2' - observed selected in modem init sequence. - * According to spec file '2FE2' is EF_ICCID (Elementary file - * ICC identification). - */ - - byte[] selectFileApdu = {(byte)0xa0, (byte)0xa4, (byte)0x00, (byte)0x00, - (byte)0x02, (byte)0x2f, (byte)0xe2}; - - /* Command succesfull '9F', length '0F' of response data */ - byte[] selectFileApduResp = {(byte)0x9f, (byte)0x0f}; - - try { - - SapSequencer sequencer = new SapSequencer(); - if(rilTestModeEnabled) { - sequencer.testModeEnable(true); - } - - /* Build a default init sequence */ - buildDefaultInitSeq(sequencer); - - SapMessage powerOffReq = new SapMessage(SapMessage.ID_POWER_SIM_OFF_REQ); - - SapMessage powerOffResp = new SapMessage(SapMessage.ID_POWER_SIM_OFF_RESP); - powerOffResp.setResultCode(SapMessage.RESULT_OK); - sequencer.addStep(powerOffReq, powerOffResp); - - - SapMessage powerOnReq = new SapMessage(SapMessage.ID_POWER_SIM_ON_REQ); - - SapMessage powerOnResp = new SapMessage(SapMessage.ID_POWER_SIM_ON_RESP); - powerOnResp.setResultCode(SapMessage.RESULT_OK); - sequencer.addStep(powerOnReq, powerOnResp); - - SapMessage resetReq = new SapMessage(SapMessage.ID_RESET_SIM_REQ); - - SapMessage resetResp = new SapMessage(SapMessage.ID_RESET_SIM_RESP); - resetResp.setResultCode(SapMessage.RESULT_OK); - int index = sequencer.addStep(resetReq, resetResp); - - /* SapMessage statusInd = new SapMessage(SapMessage.ID_STATUS_IND); */ - /* statusInd.setStatusChange(SapMessage.STATUS_CARD_RESET); */ - /* sequencer.addSubStep(index, null, statusInd); */ - - SapMessage atrReq = new SapMessage(SapMessage.ID_TRANSFER_ATR_REQ); - - SapMessage atrResp = new SapMessage(SapMessage.ID_TRANSFER_ATR_RESP); - atrResp.setResultCode(SapMessage.RESULT_OK); - if(rilTestModeEnabled) { - /* Use the hard coded return array, must match the test array in RIL */ - byte[] atr = {1, 2, 3, 4}; - atrResp.setAtr(atr); - } else { - atrResp.setAtr(null); - } - sequencer.addStep(atrReq, atrResp); - - - SapMessage apduReq = new SapMessage(SapMessage.ID_TRANSFER_APDU_REQ); - if(rilTestModeEnabled) { - apduReq.setApdu(dummyBytes); - } else { - apduReq.setApdu(selectFileApdu); - } - - SapMessage apduResp = new SapMessage(SapMessage.ID_TRANSFER_APDU_RESP); - apduResp.setResultCode(SapMessage.RESULT_OK); - if(rilTestModeEnabled) { - apduResp.setApduResp(dummyBytes); - } else { - apduResp.setApduResp(selectFileApduResp); - } - sequencer.addStep(apduReq, apduResp); - - - SapMessage apdu7816Req = new SapMessage(SapMessage.ID_TRANSFER_APDU_REQ); - if(rilTestModeEnabled) { - apdu7816Req.setApdu7816(dummyBytes); - } else { - apdu7816Req.setApdu7816(selectFileApdu); - } - - SapMessage apdu7816Resp = new SapMessage(SapMessage.ID_TRANSFER_APDU_RESP); - apdu7816Resp.setResultCode(SapMessage.RESULT_OK); - if(rilTestModeEnabled) { - apdu7816Resp.setApduResp(dummyBytes); - } else { - apdu7816Resp.setApduResp(selectFileApduResp); - } - sequencer.addStep(apdu7816Req, apdu7816Resp); - - SapMessage transferCardReaderStatusReq = - new SapMessage(SapMessage.ID_TRANSFER_CARD_READER_STATUS_REQ); - - SapMessage transferCardReaderStatusResp = - new SapMessage(SapMessage.ID_TRANSFER_CARD_READER_STATUS_RESP); - transferCardReaderStatusResp.setResultCode(SapMessage.RESULT_OK); - sequencer.addStep(transferCardReaderStatusReq, transferCardReaderStatusResp); - - SapMessage setTransportProtocolReq = - new SapMessage(SapMessage.ID_SET_TRANSPORT_PROTOCOL_REQ); - setTransportProtocolReq.setTransportProtocol(0x01); // T=1 - - SapMessage setTransportProtocolResp = - new SapMessage(SapMessage.ID_SET_TRANSPORT_PROTOCOL_RESP); - setTransportProtocolResp.setResultCode(SapMessage.RESULT_OK); - sequencer.addStep(setTransportProtocolReq, setTransportProtocolResp); - - SapMessage disconnectReq = new SapMessage(SapMessage.ID_DISCONNECT_REQ); - - SapMessage disconnectResp = new SapMessage(SapMessage.ID_DISCONNECT_RESP); - sequencer.addStep(disconnectReq, disconnectResp); - - assertTrue(sequencer.run()); - } catch (IOException e) { - Log.e(TAG, "IOException", e); - } - } - - /** - * This test fails if the apdu request generates a response before the reset request is handled. - * This happens if the reference ril is used in test mode. - */ - public void testSapServerResetWhileWritingApdu() { - mContext = this.getContext(); - byte[] dummyBytes = {1, 2, 3, 4}; - int index; - - try { - - SapSequencer sequencer = new SapSequencer(); - if(rilTestModeEnabled) { - sequencer.testModeEnable(true); - } - - /* Build a default init sequence */ - buildDefaultInitSeq(sequencer); - - SapMessage apduReq = new SapMessage(SapMessage.ID_TRANSFER_APDU_REQ); - apduReq.setApdu(dummyBytes); - - // - // Expect no response as we send a SIM_RESET before the write APDU - // completes. - // TODO: Consider adding a real response, and add an optional flag. - // - SapMessage apduResp = null; - index = sequencer.addStep(apduReq, apduResp); - - SapMessage resetReq = new SapMessage(SapMessage.ID_RESET_SIM_REQ); - SapMessage resetResp = new SapMessage(SapMessage.ID_RESET_SIM_RESP); - resetResp.setResultCode(SapMessage.RESULT_OK); - sequencer.addSubStep(index, resetReq, resetResp); - - SapMessage statusInd = new SapMessage(SapMessage.ID_STATUS_IND); - statusInd.setStatusChange(SapMessage.STATUS_CARD_RESET); - sequencer.addSubStep(index, null, statusInd); - - assertTrue(sequencer.run()); - } catch (IOException e) { - Log.e(TAG, "IOException", e); - } - } - - /** - * Test that SapServer can disconnect based on a disconnect intent. - * TODO: This test could validate the timeout values. - * TODO: We need to add a IAction and add an action to a step, to be able to send - * the disconnect intent at the right time. - */ - public void testSapServerTimeouts() { - Intent sapDisconnectIntent = new Intent(SapServer.SAP_DISCONNECT_ACTION); - sapDisconnectIntent.putExtra( - SapServer.SAP_DISCONNECT_TYPE_EXTRA, SapMessage.DISC_IMMEDIATE); - mContext = this.getContext(); - - try { - - SapSequencer sequencer = new SapSequencer(); - if(rilTestModeEnabled) { - sequencer.testModeEnable(true); - } - /* Build a default init sequence */ - buildDefaultInitSeq(sequencer); - - SapMessage disconnectReq = new SapMessage(SapMessage.ID_DISCONNECT_REQ); - SapMessage disconnectResp = new SapMessage(SapMessage.ID_DISCONNECT_RESP); - - SapMessage resetResp = new SapMessage(SapMessage.ID_RESET_SIM_RESP); - resetResp.setResultCode(SapMessage.RESULT_OK); - - int index = sequencer.addStep(disconnectReq, disconnectResp); - - assertTrue(sequencer.run()); - - mContext.sendBroadcast(sapDisconnectIntent); - - } catch (IOException e) { - Log.e(TAG, "IOException", e); - } - } - public void testSapServerTimeoutsActionDiscIntent() { - - } - - public class SapSequencer implements Callback { - - private final static int MSG_ID_TIMEOUT = 0x01; - private final static int TIMEOUT_VALUE = 100*2000; // ms - private ArrayList sequence = null; - private HandlerThread handlerThread = null; - private Handler messageHandler = null; - - private SapServer sapServer = null; - - private PipedInputStream inStream = null; // Used to write requests to SapServer - private PipedOutputStream outStream = null; // Used to read commands from the SapServer - - - public class SeqStep { - public ArrayList requests = null; - public ArrayList responses = null; - public int index = 0; // Requests with same index are executed in - // parallel without waiting for a response - public SeqStep(SapMessage request, SapMessage response) { - requests = new ArrayList(); - responses = new ArrayList(); - this.requests.add(request); - this.responses.add(response); - } - - public void add(SapMessage request, SapMessage response) { - this.requests.add(request); - this.responses.add(response); - } - - /** - * Examine if the step has any expected response. - * @return true if one or more of the responses are != null. False otherwise. - */ - public boolean hasResponse() { - if(responses == null) - return false; - for(SapMessage response : responses) { - if(response != null) - return true; - } - return false; - } - } - - public SapSequencer() throws IOException { - /* Setup the looper thread to handle messages */ - handlerThread = new HandlerThread("SapTestTimeoutHandler", - android.os.Process.THREAD_PRIORITY_BACKGROUND); - handlerThread.start(); - Looper testLooper = handlerThread.getLooper(); - messageHandler = new Handler(testLooper, this); - - /* Initialize members */ - sequence = new ArrayList(); - - /* Create a SapServer. Fake the BtSocket using piped input/output streams*/ - inStream = new PipedInputStream(8092); - outStream = new PipedOutputStream(); - sapServer = new SapServer(null, mContext, new PipedInputStream(outStream, 8092), - new PipedOutputStream(inStream)); - sapServer.start(); - } - - /* TODO: - * - Add support for actions ? - * */ - - /** - * Enable/Disable test mode during the next connect request. - * @param enable - */ - public void testModeEnable(boolean enable) { - if(enable) - sapServer.setTestMode(SapMessage.TEST_MODE_ENABLE); - else - sapServer.setTestMode(SapMessage.TEST_MODE_DISABLE); - } - - /** - * Add a test step to the sequencer - * @param request The request to send to the SAP server - * @param response The response to EXPECT from the SAP server - * @return The created step index, which can be used when adding events or actions. - */ - public int addStep(SapMessage request, SapMessage response) { - // TODO: should we add a step trigger? (in stead of just executing in sequence) - SeqStep newStep = new SeqStep(request, response); - sequence.add(newStep); - return sequence.indexOf(newStep); - } - - /** - * Add a sub-step to a sequencer step. All requests added to the same index will be send to - * the SapServer in the order added before listening for the response. - * The response order is not validated - hence for each response received the entire list of - * responses in the step will be searched for a match. - * @param index the index returned from addStep() to which the sub-step is to be added. - * @param request The request to send to the SAP server - * @param response The response to EXPECT from the SAP server - */ - public void addSubStep(int index, SapMessage request, SapMessage response) { - SeqStep step = sequence.get(index); - step.add(request, response); - } - - - /** - * Run the sequence, by writing a request and wait for a response. Validate the response - * is either the expected response or one of the expected events. - * @return - */ - public boolean run() throws IOException { - SapMessage inMsg = null; - boolean done; - for(SeqStep step : sequence) { - - /* Write all requests - if any */ - if(step.requests != null) { - for(SapMessage request : step.requests) { - if(request != null) { - Log.i(TAG, "Writing request: " + - SapMessage.getMsgTypeName(request.getMsgType())); - writeSapMessage(request, false); // write the message without flushing - } - } - writeSapMessage(null, true); /* flush the pipe */ - } - - /* Handle and validate all responses - if any */ - if(step.hasResponse() == true) { - done = false; - boolean foundMatch = false; - SapMessage responseMatch; - while(!done) { - for(SapMessage response : step.responses) { - if(response != null) - Log.i(TAG, "Waiting for the response: " + - SapMessage.getMsgTypeName(response.getMsgType())); - } - inMsg = readSapMessage(); - if(inMsg != null) - Log.i(TAG, "Read message: " + - SapMessage.getMsgTypeName(inMsg.getMsgType())); - else - assertTrue("Failed to read message.", false); - - responseMatch = null; - for(SapMessage response : step.responses) { - if(response != null - && inMsg.getMsgType() == response.getMsgType() - && compareSapMessages(inMsg, response) == true) { - foundMatch = true; - responseMatch = response; - break; - } - } - - if(responseMatch != null) - step.responses.remove(responseMatch); - - /* If we are expecting no more responses for this step, continue. */ - if(step.hasResponse() != true) { - done = true; - } - /* Ensure what we received was expected */ - assertTrue("wrong message received.", foundMatch); - } - } - } - return true; - } - - private void startTimer() { - Message timeoutMessage = messageHandler.obtainMessage(MSG_ID_TIMEOUT); - messageHandler.sendMessageDelayed(timeoutMessage, TIMEOUT_VALUE); - } - - private void stopTimer() { - messageHandler.removeMessages(MSG_ID_TIMEOUT); - } - - /** - * Compare two messages by comparing each member variable - * @param received message - * @param expected message - * @return true if equal, else false - */ - private boolean compareSapMessages(SapMessage received, SapMessage expected) { - boolean retVal = true; - if(expected.getCardReaderStatus() != -1 && - received.getCardReaderStatus() != expected.getCardReaderStatus()) { - Log.i(TAG, "received.getCardReaderStatus() != expected.getCardReaderStatus() " - + received.getCardReaderStatus() + " != " + expected.getCardReaderStatus()); - retVal = false; - } - if(received.getConnectionStatus() != expected.getConnectionStatus()) { - Log.i(TAG, "received.getConnectionStatus() != expected.getConnectionStatus() " - + received.getConnectionStatus() + " != " + expected.getConnectionStatus()); - retVal = false; - } - if(received.getDisconnectionType() != expected.getDisconnectionType()) { - Log.i(TAG, "received.getDisconnectionType() != expected.getDisconnectionType() " - + received.getDisconnectionType() + " != " - + expected.getDisconnectionType()); - retVal = false; - } - if(received.getMaxMsgSize() != expected.getMaxMsgSize()) { - Log.i(TAG, "received.getMaxMsgSize() != expected.getMaxMsgSize() " - + received.getMaxMsgSize() +" != " + expected.getMaxMsgSize()); - retVal = false; - } - if(received.getMsgType() != expected.getMsgType()) { - Log.i(TAG, "received.getMsgType() != expected.getMsgType() " - + received.getMsgType() +" != " + expected.getMsgType()); - retVal = false; - } - if(received.getResultCode() != expected.getResultCode()) { - Log.i(TAG, "received.getResultCode() != expected.getResultCode() " - + received.getResultCode() + " != " + expected.getResultCode()); - retVal = false; - } - if(received.getStatusChange() != expected.getStatusChange()) { - Log.i(TAG, "received.getStatusChange() != expected.getStatusChange() " - + received.getStatusChange() + " != " + expected.getStatusChange()); - retVal = false; - } - if(received.getTransportProtocol() != expected.getTransportProtocol()) { - Log.i(TAG, "received.getTransportProtocol() != expected.getTransportProtocol() " - + received.getTransportProtocol() + " != " - + expected.getTransportProtocol()); - retVal = false; - } - if(!Arrays.equals(received.getApdu(), expected.getApdu())) { - Log.i(TAG, "received.getApdu() != expected.getApdu() " - + Arrays.toString(received.getApdu()) + " != " - + Arrays.toString(expected.getApdu())); - retVal = false; - } - if(!Arrays.equals(received.getApdu7816(), expected.getApdu7816())) { - Log.i(TAG, "received.getApdu7816() != expected.getApdu7816() " - + Arrays.toString(received.getApdu7816()) + " != " - + Arrays.toString(expected.getApdu7816())); - retVal = false; - } - if(expected.getApduResp() != null && !Arrays.equals(received.getApduResp(), - expected.getApduResp())) { - Log.i(TAG, "received.getApduResp() != expected.getApduResp() " - + Arrays.toString(received.getApduResp()) + " != " - + Arrays.toString(expected.getApduResp())); - retVal = false; - } - if(expected.getAtr() != null && !Arrays.equals(received.getAtr(), expected.getAtr())) { - Log.i(TAG, "received.getAtr() != expected.getAtr() " - + Arrays.toString(received.getAtr()) + " != " - + Arrays.toString(expected.getAtr())); - retVal = false; - } - return retVal; - } - - private SapMessage readSapMessage() throws IOException { - startTimer(); - int requestType = inStream.read(); - Log.i(TAG,"Received message with type: " + SapMessage.getMsgTypeName(requestType)); - SapMessage msg = SapMessage.readMessage(requestType, inStream); - stopTimer(); - if(requestType != -1) { - return msg; - } else - { - assertTrue("Reached EOF too early...", false); - } - return msg; - } - - private void writeSapMessage(SapMessage message, boolean flush) throws IOException { - startTimer(); - if(message != null) - message.write(outStream); - if(flush == true) - outStream.flush(); - stopTimer(); - } - - @Override - public boolean handleMessage(Message msg) { - - Log.i(TAG,"Handling message ID: " + msg.what); - - switch(msg.what) { - case MSG_ID_TIMEOUT: - Log.w(TAG, "Timeout occured!"); - try { - inStream.close(); - } catch (IOException e) { - Log.e(TAG, "failed to close inStream", e); - } - try { - outStream.close(); - } catch (IOException e) { - Log.e(TAG, "failed to close outStream", e); - } - break; - default: - /* Message not handled */ - return false; - } - return true; // Message handles - } - - } - -} diff --git a/tests/src/com/android/bluetooth/tests/SapSocketTest.java b/tests/src/com/android/bluetooth/tests/SapSocketTest.java deleted file mode 100644 index 9bd80313..00000000 --- a/tests/src/com/android/bluetooth/tests/SapSocketTest.java +++ /dev/null @@ -1,174 +0,0 @@ -package com.android.bluetooth.tests; - -import android.net.LocalSocket; -import android.net.LocalSocketAddress; -import android.test.AndroidTestCase; -import android.util.Log; - -import org.android.btsap.SapApi; -import org.android.btsap.SapApi.MsgHeader; -import org.android.btsap.SapApi.RIL_SIM_SAP_CONNECT_REQ; - -import com.google.protobuf.micro.ByteStringMicro; -import com.google.protobuf.micro.CodedOutputStreamMicro; -import com.google.protobuf.micro.CodedInputStreamMicro; - -import java.io.IOException; -import java.io.OutputStream; -import java.io.InputStream; -import java.util.Arrays; - -public class SapSocketTest extends AndroidTestCase { - - protected static String TAG = "SapSocketTest"; - protected static final boolean D = true; - - private static final String SOCKET_NAME_RIL_BT = "sap_uim_socket1"; - - public SapSocketTest() { - super(); - } - - private void writeLegacyLength(int length, OutputStream rawOut) throws IOException { - byte[] dataLength = new byte[4]; - dataLength[0] = dataLength[1] = 0; - dataLength[2] = (byte)((length >> 8) & 0xff); - dataLength[3] = (byte)((length) & 0xff); - rawOut.write(dataLength); - } - - private void dumpMsgHeader(MsgHeader msg){ - Log.d(TAG,"MsgHeader: ID = " + msg.getId()); - Log.d(TAG," Type= " + msg.getType()); - Log.d(TAG," Token= " + msg.getToken()); - Log.d(TAG," Error= " + msg.getError()); - Log.d(TAG," Length=" + msg.getSerializedSize()); - if(msg.hasPayload()){ - Log.d(TAG,"Payload: Length=" + msg.getPayload().size()); - Log.d(TAG," Data= " + Arrays.toString(msg.getPayload().toByteArray())); - } - - } - private void readLegacyLength(InputStream rawIn) throws IOException{ - byte[] buffer = new byte[4]; - int countRead; - int offset; - int remaining; - int messageLength; - - // Read in the length of the message - offset = 0; - remaining = 4; - do { - countRead = rawIn.read(buffer, offset, remaining); - - if (countRead < 0 ) { - Log.e(TAG, "Hit EOS reading message length"); - return; - } - - offset += countRead; - remaining -= countRead; - } while (remaining > 0); - - messageLength = ((buffer[0] & 0xff) << 24) - | ((buffer[1] & 0xff) << 16) - | ((buffer[2] & 0xff) << 8) - | (buffer[3] & 0xff); - - Log.d(TAG, "The length is: " + messageLength + " - discarding as we do not need it"); - - } - -/** -Precondition: -Add the sap_uim_socket1 to rild in init.rc: - socket sap_uim_socket1 stream 666 root bluetooth - -Ensure the socket is present in /dev/socket: -srw-rw-rw- root bluetooth 1970-04-16 06:27 sap_uim_socket1 - -Build: -mmm packages/apps/Bluetooth/tests - -rebuild with a make in the root folder to get the -android.test.InstrumentationTestRunner class included. - -Run the test(remove line breaks): -adb shell am instrument -w -e class com.android.bluetooth. -tests.SapSocketTest#testSapServerConnectSimple com.android. -bluetooth.tests/android.test.InstrumentationTestRunner - -Validate you do not get a permission denied IOException. - -Validate you do not get an error in the kernel log: -type=1400 audit(1404244298.582:25): avc: denied { write } -for pid=2421 comm="ationTestRunner" name="sap_uim_socket1" -dev="tmpfs" ino=6703 scontext=u:r:bluetooth:s0 -tcontext=u:object_r:socket_device:s0 tclass=sock_file -*/ - - /** - * Precondition: Add the sap_uim_socket1 to rild in init.rc: socket - * sap_uim_socket1 stream 666 root bluetooth - * - * Ensure the socket is present in /dev/socket: srw-rw-rw- root bluetooth - * 1970-04-16 06:27 sap_uim_socket1 - * - * Build: mmm packages/apps/Bluetooth/tests - * - * rebuild with a make in the root folder to get the - * android.test.InstrumentationTestRunner class included. - * - * Run the test(remove line breaks): adb shell am instrument -w -e class - * com.android.bluetooth. tests.SapSocketTest#testSapServerConnectSimple - * com.android. bluetooth.tests/android.test.InstrumentationTestRunner - * - * Validate you do not get a permission denied IOException. - * - * Validate you do not get an error in the kernel log: type=1400 - * audit(1404244298.582:25): avc: denied { write } for pid=2421 - * comm="ationTestRunner" name="sap_uim_socket1" dev="tmpfs" ino=6703 - * scontext=u:r:bluetooth:s0 tcontext=u:object_r:socket_device:s0 - * tclass=sock_file - */ - public void testSapServerConnectSimple() { - LocalSocketAddress address; - LocalSocket rilSocket = new LocalSocket(); - try { - address = new LocalSocketAddress(SOCKET_NAME_RIL_BT, - LocalSocketAddress.Namespace.RESERVED); - rilSocket.connect(address); - CodedInputStreamMicro in = CodedInputStreamMicro.newInstance(rilSocket.getInputStream()); - OutputStream rawOut = rilSocket.getOutputStream(); - CodedOutputStreamMicro out = CodedOutputStreamMicro.newInstance(rilSocket.getOutputStream()); - InputStream rawIn = rilSocket.getInputStream(); - int rilSerial = 1; - SapApi.MsgHeader msg = new MsgHeader(); - /* Common variables for all requests */ - msg.setToken(rilSerial); - msg.setType(SapApi.REQUEST); - msg.setError(SapApi.RIL_E_UNUSED); - SapApi.RIL_SIM_SAP_CONNECT_REQ reqMsg = new RIL_SIM_SAP_CONNECT_REQ(); - reqMsg.setMaxMessageSize(1234); - msg.setId(SapApi.RIL_SIM_SAP_CONNECT); - msg.setPayload(ByteStringMicro.copyFrom(reqMsg.toByteArray())); - writeLegacyLength(msg.getSerializedSize(), rawOut); - msg.writeTo(out); - out.flush(); - readLegacyLength(rawIn); - msg = MsgHeader.parseFrom(in); - dumpMsgHeader(msg); - assertTrue("Invalid response type", msg.getType()== SapApi.RESPONSE); - assertTrue("Invalid response id", msg.getId()== SapApi.RIL_SIM_SAP_CONNECT); - } catch (IOException e){ - Log.e(TAG, "IOException:", e); - assertTrue("Failed to connect to the socket " + SOCKET_NAME_RIL_BT + ":" + e, false); - } finally { - try { - rilSocket.close(); - } catch (IOException e2) {} - - } - } -} diff --git a/tests/src/com/android/bluetooth/tests/SdpManagerTest.java b/tests/src/com/android/bluetooth/tests/SdpManagerTest.java deleted file mode 100644 index 23353ebb..00000000 --- a/tests/src/com/android/bluetooth/tests/SdpManagerTest.java +++ /dev/null @@ -1,293 +0,0 @@ -package com.android.bluetooth.tests; - -import java.io.IOException; -import java.util.concurrent.CountDownLatch; - -import javax.obex.ClientSession; -import javax.obex.HeaderSet; -import javax.obex.Operation; -import javax.obex.ResponseCodes; -import javax.obex.ServerSession; - -import com.android.bluetooth.BluetoothObexTransport; -import com.android.bluetooth.sdp.SdpManager; - -import android.annotation.TargetApi; -import android.bluetooth.BluetoothAdapter; -import android.bluetooth.BluetoothDevice; -import android.bluetooth.BluetoothServerSocket; -import android.bluetooth.BluetoothSocket; -import android.bluetooth.BluetoothUuid; -import android.os.Build; -import android.test.AndroidTestCase; -import android.util.Log; - -@TargetApi(Build.VERSION_CODES.KITKAT) -public class SdpManagerTest extends AndroidTestCase { - - protected static String TAG = "SdpManagerTest"; - protected static final boolean D = true; - - public static final int SDP_RECORD_COUNT = 12; /* Maximum number of records to create */ - public static final int SDP_ITERATIONS = 2000; - - public static final String SDP_SERVER_NAME = "SDP test server"; - public static final String SDP_CLIENT_NAME = "SDP test client"; - - public static final long SDP_FEATURES = 0x87654321L; /* 32 bit */ - public static final int SDP_MSG_TYPES = 0xf1; /* 8 bit */ - public static final int SDP_MAS_ID = 0xCA; /* 8 bit */ - public static final int SDP_VERSION = 0xF0C0; /* 16 bit */ - public static final int SDP_REPOS = 0xCf; /* 8 bit */ - - SdpManager mManager = null; - - public void testSdpRemove() { - BluetoothAdapter bt = BluetoothAdapter.getDefaultAdapter(); - if(bt == null) { - Log.e(TAG,"No Bluetooth Device!"); - assertTrue(false); - } - BluetoothTestUtils.enableBt(bt); - mManager = SdpManager.getDefaultManager(); - addRemoveRecords(SDP_RECORD_COUNT); - } - - public void testSdpAdd() { - BluetoothAdapter bt = BluetoothAdapter.getDefaultAdapter(); - if(bt == null) { - Log.e(TAG,"No Bluetooth Device!"); - assertTrue(false); - } - BluetoothTestUtils.enableBt(bt); - mManager = SdpManager.getDefaultManager(); - - int handles[] = new int[SDP_RECORD_COUNT]; - addRecords(handles, 1); - - try { - Log.i(TAG, "\n\n\nRecords added - waiting 5 minutes...\n\n\n"); - Thread.sleep(300000); - } catch (InterruptedException e) { - Log.e(TAG, "Interrupted", e); - } - Log.i(TAG, "All done - over and out!;-)"); - } - - - private void addRecords(int handles[], int iteration) { - /* Create the records */ - int record_id = -1; /* first index is 0 */ - int count = handles.length-1; // Break condition - for(int c = 0; ; c++) { - Log.i(TAG, "Create c=" + c); - handles[++record_id] = mManager.createMapMasRecord(SDP_SERVER_NAME, - SDP_MAS_ID, record_id, record_id+iteration, SDP_VERSION, - SDP_MSG_TYPES, (int)SDP_FEATURES); - Log.i(TAG, " Added record_handle=" + handles[record_id]); - assertTrue(handles[record_id]>=0); - if(record_id == count) break; - - handles[++record_id] = mManager.createMapMnsRecord(SDP_SERVER_NAME, - record_id, record_id+iteration, SDP_VERSION, - (int)SDP_FEATURES); - Log.i(TAG, " Added record_handle=" + handles[record_id]); - assertTrue(handles[record_id]>=0); - if(record_id == count) break; - - handles[++record_id] = mManager.createOppOpsRecord(SDP_SERVER_NAME, - record_id, record_id+iteration, SDP_VERSION, SdpManager.OPP_FORMAT_ALL); - Log.i(TAG, " Added record_handle=" + handles[record_id]); - assertTrue(handles[record_id]>=0); - if(record_id == count) break; - - handles[++record_id] = mManager.createPbapPseRecord(SDP_SERVER_NAME, - record_id, record_id+iteration, SDP_VERSION, SDP_REPOS, - (int)SDP_FEATURES); - Log.i(TAG, " Added record_handle=" + handles[record_id]); - assertTrue(handles[record_id]>=0); - if(record_id == count) break; - - handles[++record_id] = mManager.createSapsRecord(SDP_SERVER_NAME, - record_id, SDP_VERSION); - Log.i(TAG, " Added record_handle=" + handles[record_id]); - assertTrue(handles[record_id]>=0); - if (record_id == count) break; - } - } - - void removeRecords(int handles[], int record_count) { - int record_id; - /* Remove the records */ - for(record_id = 0; record_id < record_count; record_id++) { - Log.i(TAG, "remove id=" + record_id); - assertTrue(mManager.removeSdpRecord(handles[record_id])); - } - } - - private void addRemoveRecords(int count) { - int record_count = count; - int handles[] = new int[record_count]; - int iteration; - for(iteration = 0; iteration < SDP_ITERATIONS; iteration++) { - - addRecords(handles, iteration); - - try { - Thread.sleep(500); - } catch (InterruptedException e) { - Log.e(TAG, "Interrupted", e); - } - - removeRecords(handles, record_count); - } - } - - /** - * Client side of SdpSearch test - * This test will: - * 1) Create a connection to a test server - * 2) Create a number of SDP records - * 3) Request the test server to read the records - * 4) Remove the records - * 5) Iterate over 2) to 4) SDP_ITERATIONS number of times - */ - public void testSdpSearchClient() { - int count = SDP_RECORD_COUNT; - int record_count = count; - int handles[] = new int[record_count]; - int iteration; - final BluetoothSocket clientSock; - final ClientSession mClientSession; - final String[] uuids = {BluetoothUuid.MAS.toString(), - BluetoothUuid.MNS.toString(), - BluetoothUuid.PBAP_PSE.toString(), - BluetoothUuid.ObexObjectPush.toString(), - BluetoothUuid.SAP.toString()}; - final String uuids_str; - final StringBuilder sb = new StringBuilder(uuids.length*2-1); - for(String str : uuids) { - sb.append(str).append(";"); - } - uuids_str = sb.toString(); - - try { - /* This will turn on BT and connect */ - clientSock = ObexTest.connectClientSocket(BluetoothSocket.TYPE_L2CAP, true, mContext); - mManager = SdpManager.getDefaultManager(); - BluetoothObexTransport clientTransport = new BluetoothObexTransport(clientSock); - mClientSession = new ClientSession(clientTransport); - { // Connect - HeaderSet reqHeaders = new HeaderSet(); - reqHeaders.setHeader(TestSequencer.STEP_INDEX_HEADER, (long)0); - HeaderSet response = mClientSession.connect(reqHeaders); - assertEquals(response.responseCode, ResponseCodes.OBEX_HTTP_OK); - } - - for(iteration = 0; iteration < SDP_ITERATIONS; iteration++) { - // Add the records - addRecords(handles, iteration); - - { // get operation to trigger SDP search on peer device - HeaderSet reqHeaders = new HeaderSet(); - reqHeaders.setHeader(TestSequencer.STEP_INDEX_HEADER, (long)iteration); - reqHeaders.setHeader(HeaderSet.COUNT, (long)count); - reqHeaders.setHeader(HeaderSet.NAME, uuids_str); - Operation op = mClientSession.get(reqHeaders); - op.noBodyHeader(); - int response = op.getResponseCode(); - op.close(); - assertEquals(response, ResponseCodes.OBEX_HTTP_OK); - } - - // Cleanup - removeRecords(handles, record_count); - } - { // disconnect to end test - HeaderSet reqHeaders = new HeaderSet(); - reqHeaders.setHeader(TestSequencer.STEP_INDEX_HEADER, 0L); // signals end of test - HeaderSet response = mClientSession.disconnect(reqHeaders); - assertEquals(response.responseCode, ResponseCodes.OBEX_HTTP_OK); - } - } catch (IOException e) { - Log.e(TAG,"IOException in testSdpSearch",e); - } - - } - - /** - * Server side of SdpSearch test - * This test will start a - * 1) Create a connection to a test server - * 2) Create a number of SDP records - * 3) Request the test server to read the records - * 4) Remove the records - * 5) Iterate over 2) to 4) SDP_ITERATIONS number of times - */ - public void testSdpSearchServer() { - mManager = SdpManager.getDefaultManager(); - try { - CountDownLatch stopLatch = new CountDownLatch(1); - BluetoothDevice clientDevice; - /* This will turn on BT and create a server socket on which accept can be called. */ - BluetoothServerSocket serverSocket=ObexTest.createServerSocket(BluetoothSocket.TYPE_L2CAP, true); - mManager = SdpManager.getDefaultManager(); - - Log.i(TAG, "Waiting for client to connect..."); - BluetoothSocket socket = serverSocket.accept(); - Log.i(TAG, "Client connected..."); - - BluetoothObexTransport serverTransport = new BluetoothObexTransport(socket); - clientDevice = socket.getRemoteDevice(); - ServerSession serverSession = new ServerSession(serverTransport, - new SdpManagerTestServer(stopLatch, mContext, clientDevice), null); - - boolean interrupted = false; - do { - try { - interrupted = false; - Log.i(TAG,"Waiting for stopLatch signal..."); - stopLatch.await(); - } catch (InterruptedException e) { - Log.w(TAG,e); - interrupted = true; - } - } while (interrupted == true); - Log.i(TAG,"stopLatch signal received closing down..."); - /* Give a little time to transfer the disconnect response before closing the socket */ - try { - Thread.sleep(1000); - } catch (InterruptedException e) {} - - // Cleanup - serverSession.close(); - socket.close(); - serverSocket.close(); - } catch (IOException e) { - Log.e(TAG, "IOException", e); - } - Log.i(TAG, "\n\n\nTest done - please fetch logs within 30 seconds...\n\n\n"); - try { - Thread.sleep(30000); - } catch (InterruptedException e) {} - Log.i(TAG, "Test done."); -} - - -/* - * Tests we need: - * - Single threaded test: - * * Add a large number of records and remove them again. - * - Multi-threaded rests: - * * Let two or more threads perform the test above, each tasking a n-threads fraction of the RECORD_COUNT - * - * - Client/server - * * Create a control connection - it might be easiest to use OBEX. - * 1) Add a number of records - * 2) Trigger read of the records - * 3) Remove the records - * 4) Validate they are gone (if they are not cached) - * 5) Multi thread the test on both sides? - * */ - -} diff --git a/tests/src/com/android/bluetooth/tests/SdpManagerTestServer.java b/tests/src/com/android/bluetooth/tests/SdpManagerTestServer.java deleted file mode 100644 index 1ed4afe1..00000000 --- a/tests/src/com/android/bluetooth/tests/SdpManagerTestServer.java +++ /dev/null @@ -1,339 +0,0 @@ -package com.android.bluetooth.tests; - -import android.bluetooth.BluetoothDevice; -import android.bluetooth.BluetoothUuid; -import android.bluetooth.SdpMasRecord; -import android.bluetooth.SdpMnsRecord; -import android.bluetooth.SdpOppOpsRecord; -import android.bluetooth.SdpPseRecord; -import android.bluetooth.SdpSapsRecord; -import android.content.BroadcastReceiver; -import android.content.Context; -import android.content.Intent; -import android.content.IntentFilter; -import android.os.ParcelUuid; -import android.util.Log; - -import com.android.bluetooth.btservice.AbstractionLayer; -import com.android.bluetooth.sdp.SdpManager; - -import java.io.IOException; -import java.util.Arrays; -import java.util.concurrent.CountDownLatch; - -import javax.obex.HeaderSet; -import javax.obex.Operation; -import javax.obex.ResponseCodes; -import javax.obex.ServerRequestHandler; - -import junit.framework.Assert; - -/** - * We use an OBEX server to execute SDP search operations, and validate results. - * @author cbonde - * - */ -public class SdpManagerTestServer extends ServerRequestHandler { - - private static final String TAG = "SdpManagerTestServer"; - private static final boolean V = true; - - int mOperationIndex = 0; - int mResult = ResponseCodes.OBEX_HTTP_OK; - - final Context mContext; - final CountDownLatch mStopLatch; - final BluetoothDevice mDevice; - - public SdpManagerTestServer(CountDownLatch stopLatch, Context context, - BluetoothDevice device) { - super(); - mStopLatch = stopLatch; - mContext = context; - mDevice = device; - Log.i(TAG, "created."); - } - - /* OBEX operation handlers */ - @Override - public int onConnect(HeaderSet request, HeaderSet reply) { - Log.i(TAG,"onConnect()"); - int index; - int result = ResponseCodes.OBEX_HTTP_OK; - try { - index = ((Long)request.getHeader(TestSequencer.STEP_INDEX_HEADER)).intValue(); - mOperationIndex = index; - } catch (IOException e) { - Log.e(TAG, "Exception in onConnect - aborting..."); - result = ResponseCodes.OBEX_HTTP_INTERNAL_ERROR; - // A read from null will produce exception to end the test. - } - return result; - } - - @Override - public void onDisconnect(HeaderSet request, HeaderSet reply) { - Log.i(TAG,"onDisconnect()"); - int index; - int result = ResponseCodes.OBEX_HTTP_OK; - try { - index = ((Long)request.getHeader(TestSequencer.STEP_INDEX_HEADER)).intValue(); - mOperationIndex = index; - } catch (IOException e) { - Log.e(TAG, "Exception in onDisconnect..."); - result = ResponseCodes.OBEX_HTTP_INTERNAL_ERROR; - // A read from null will produce exception to end the test. - } - if(mOperationIndex == 0) { - /* End of test, signal test runner thread */ - Log.i(TAG, "Sending latch close signal..."); - mStopLatch.countDown(); - } else { - Log.i(TAG, "Got disconnect with mOperationCounter = " + mOperationIndex); - } - reply.responseCode = result; - } - - /** - * Currently not used - */ - @Override - public int onPut(Operation operation) { - Log.i(TAG,"onPut()"); - int result = ResponseCodes.OBEX_HTTP_NOT_IMPLEMENTED; - return result; - } - - /** - * Used to execute SDP search operations. - */ - @Override - public int onGet(Operation operation) { - Log.i(TAG,"onGet()"); - /* - Use the name header to transfer a ';' separated list of UUID's to search for. - * - For each UUID: - * - start a search - * - validate each result received - * - ensure all records gets received (use CountDownLatch) - * */ - mResult = ResponseCodes.OBEX_HTTP_OK; - try{ - HeaderSet reqHeaders = operation.getReceivedHeader(); - int index = ((Long)reqHeaders.getHeader(TestSequencer.STEP_INDEX_HEADER)).intValue(); - mOperationIndex = index; - /* Get the expected number of records to read. */ - int count = ((Long)reqHeaders.getHeader(HeaderSet.COUNT)).intValue(); - String name = (String)reqHeaders.getHeader(HeaderSet.NAME); - String[] uuids = name.split(";"); - - // Initiate search operations, Wait for results and validate - searchAwaitAndValidate(uuids, mDevice, count); - } catch (IOException e) { - Log.e(TAG, "Exception in onPut - aborting..."); - mResult = ResponseCodes.OBEX_HTTP_INTERNAL_ERROR; - } finally { - } - if(mResult == ResponseCodes.OBEX_HTTP_OK) { - Log.i(TAG, "OBEX-HANDLER: operation complete success"); - } else { - Log.e(TAG, "OBEX-HANDLER: operation complete FAILED!"); - } - return mResult; - } - - - class SdpBroadcastReceiver extends BroadcastReceiver { - - boolean hasMas = false; - boolean hasMns = false; - boolean hasOppServer = false; - boolean hasSapServer = false; - boolean hasPse = false; - final CountDownLatch mLatch; - - public SdpBroadcastReceiver(String[] uuids, CountDownLatch latch) { - for(String uuid : uuids) { - if(uuid.toString().equals(BluetoothUuid.MAS.toString())) - hasMas = true; - if(uuid.toString().equals(BluetoothUuid.MNS.toString())) - hasMns = true; - if(uuid.toString().equals(BluetoothUuid.PBAP_PSE.toString())) - hasPse = true; - if(uuid.toString().equals(BluetoothUuid.ObexObjectPush.toString())) - hasOppServer = true; - if(uuid.toString().equals(BluetoothUuid.SAP.toString())) - hasSapServer = true; - } - mLatch = latch; - } - - @Override - public void onReceive(Context context, Intent intent) { - Log.d(TAG, "onReceive"); - String action = intent.getAction(); - if (action.equals(BluetoothDevice.ACTION_SDP_RECORD)){ - Log.v(TAG, "Received ACTION_SDP_RECORD."); - ParcelUuid uuid = intent.getParcelableExtra(BluetoothDevice.EXTRA_UUID); - Log.v(TAG, "Received UUID: " + uuid.toString()); - if(hasMas && uuid.toString().equals(BluetoothUuid.MAS.toString())) { - Log.v(TAG, " -> MAS UUID in result."); - int status = intent.getIntExtra(BluetoothDevice.EXTRA_SDP_SEARCH_STATUS, -1); - Assert.assertEquals(AbstractionLayer.BT_STATUS_SUCCESS, status); /* BT_STATUS_SUCCESS == 0 - but status is not documented... */ - Log.v(TAG, " -> status: "+status); - SdpMasRecord record = intent.getParcelableExtra(BluetoothDevice.EXTRA_SDP_RECORD); - Assert.assertNotNull(record); - Log.v(TAG, " -> Record: " + record); - /* As the normal profiles are also running, we filter out these records */ - if(record.getServiceName().equals(SdpManagerTest.SDP_SERVER_NAME)) { - Assert.assertEquals(((long)record.getSupportedFeatures())&0xffffffffL, SdpManagerTest.SDP_FEATURES); - Assert.assertEquals(record.getSupportedMessageTypes(), SdpManagerTest.SDP_MSG_TYPES); - Assert.assertEquals(record.getProfileVersion(), SdpManagerTest.SDP_VERSION); - Assert.assertEquals(record.getServiceName(), SdpManagerTest.SDP_SERVER_NAME); - Assert.assertEquals(record.getMasInstanceId(), SdpManagerTest.SDP_MAS_ID); - int rfcommChannel = record.getRfcommCannelNumber(); - int l2capPsm = record.getL2capPsm(); - /* We set RFCOMM-channel to record_id and the l2cap PSM to iteration*record_id */ - Assert.assertEquals(mOperationIndex+rfcommChannel,l2capPsm); - mLatch.countDown(); - } else { - Log.i(TAG, "Wrong service name (" + record.getServiceName() - + ") received, still waiting..."); - } - } else if(hasMns && uuid.toString().equals(BluetoothUuid.MNS.toString())) { - Log.v(TAG, " -> MAP_MNS UUID in result."); - int status = intent.getIntExtra(BluetoothDevice.EXTRA_SDP_SEARCH_STATUS, -1); - Assert.assertEquals(0, status); /* BT_STATUS_SUCCESS == 0 - but status is not documented... */ - Log.v(TAG, " -> status: "+status); - SdpMnsRecord record = intent.getParcelableExtra(BluetoothDevice.EXTRA_SDP_RECORD); - Assert.assertNotNull(record); - Log.v(TAG, " -> Record: " + record); - /* As the normal profiles are also running, we filter out these records */ - if(record.getServiceName().equals(SdpManagerTest.SDP_SERVER_NAME)) { - Assert.assertEquals(((long)record.getSupportedFeatures())&0xffffffffL, SdpManagerTest.SDP_FEATURES); - Assert.assertEquals(record.getProfileVersion(), SdpManagerTest.SDP_VERSION); - Assert.assertEquals(record.getServiceName(), SdpManagerTest.SDP_SERVER_NAME); - int rfcommChannel = record.getRfcommChannelNumber(); - int l2capPsm = record.getL2capPsm(); - /* We set RFCOMM-channel to record_id and the l2cap PSM to iteration*record_id */ - Assert.assertEquals(mOperationIndex+rfcommChannel,l2capPsm); - mLatch.countDown(); - } else { - Log.i(TAG, "Wrong service name (" + record.getServiceName() - + ") received, still waiting..."); - } - } else if(hasPse && uuid.toString().equals(BluetoothUuid.PBAP_PSE.toString())) { - Log.v(TAG, " -> PBAP_PSE UUID in result."); - int status = intent.getIntExtra(BluetoothDevice.EXTRA_SDP_SEARCH_STATUS, -1); - Assert.assertEquals(0, status); /* BT_STATUS_SUCCESS == 0 - but status is not documented... */ - Log.v(TAG, " -> status: "+status); - SdpPseRecord record = intent.getParcelableExtra(BluetoothDevice.EXTRA_SDP_RECORD); - Assert.assertNotNull(record); - Log.v(TAG, " -> Record: " + record); - /* As the normal profiles are also running, we filter out these records */ - if(record.getServiceName().equals(SdpManagerTest.SDP_SERVER_NAME)) { - Assert.assertEquals(((long)record.getSupportedFeatures())&0xffffffffL, SdpManagerTest.SDP_FEATURES); - Assert.assertEquals(((long)record.getSupportedRepositories())&0xffffffffL, SdpManagerTest.SDP_REPOS); - Assert.assertEquals(record.getProfileVersion(), SdpManagerTest.SDP_VERSION); - Assert.assertEquals(record.getServiceName(), SdpManagerTest.SDP_SERVER_NAME); - int rfcommChannel = record.getRfcommChannelNumber(); - int l2capPsm = record.getL2capPsm(); - /* We set RFCOMM-channel to record_id and the l2cap PSM to iteration*record_id */ - Assert.assertEquals(mOperationIndex+rfcommChannel,l2capPsm); - mLatch.countDown(); - } else { - Log.i(TAG, "Wrong service name (" + record.getServiceName() - + ") received, still waiting..."); - } - } else if(hasOppServer && uuid.toString().equals(BluetoothUuid.ObexObjectPush.toString())) { - Log.v(TAG, " -> OPP Server UUID in result."); - int status = intent.getIntExtra(BluetoothDevice.EXTRA_SDP_SEARCH_STATUS, -1); - Assert.assertEquals(0, status); /* BT_STATUS_SUCCESS == 0 - but status is not documented... */ - Log.v(TAG, " -> status: "+status); - SdpOppOpsRecord record = intent.getParcelableExtra(BluetoothDevice.EXTRA_SDP_RECORD); - Assert.assertNotNull(record); - Log.v(TAG, " -> Record: " + record); - /* As the normal profiles are also running, we filter out these records */ - if(record.getServiceName().equals(SdpManagerTest.SDP_SERVER_NAME)) { - Assert.assertEquals(record.getProfileVersion(), SdpManagerTest.SDP_VERSION); - Assert.assertEquals(record.getServiceName(), SdpManagerTest.SDP_SERVER_NAME); - Assert.assertTrue(Arrays.equals(record.getFormatsList(),SdpManager.OPP_FORMAT_ALL)); - int rfcommChannel = record.getRfcommChannel(); - int l2capPsm = record.getL2capPsm(); - /* We set RFCOMM-channel to record_id and the l2cap PSM to iteration*record_id */ - Assert.assertEquals(mOperationIndex+rfcommChannel,l2capPsm); - mLatch.countDown(); - } else { - Log.i(TAG, "Wrong service name (" + record.getServiceName() - + ") received, still waiting..."); - } - } else if (hasSapServer && uuid.toString().equals(BluetoothUuid.SAP.toString())) { - Log.v(TAG, " -> SAP Server UUID in result."); - int status = intent.getIntExtra(BluetoothDevice.EXTRA_SDP_SEARCH_STATUS, -1); - Assert.assertEquals(AbstractionLayer.BT_STATUS_SUCCESS, status); /* BT_STATUS_SUCCESS == 0 - but status is not documented... */ - Log.v(TAG, " -> status: "+status); - SdpSapsRecord record = intent.getParcelableExtra(BluetoothDevice.EXTRA_SDP_RECORD); - Assert.assertNotNull(record); - Log.v(TAG, " -> Record: " + record); - /* As the normal profiles are also running, we filter out these records */ - if (record.getServiceName().equals(SdpManagerTest.SDP_SERVER_NAME)) { - Assert.assertEquals(record.getProfileVersion(), SdpManagerTest.SDP_VERSION); - Assert.assertEquals(record.getServiceName(), SdpManagerTest.SDP_SERVER_NAME); - int rfcommChannel = record.getRfcommCannelNumber(); - /* We set RFCOMM-channel to record_id and the l2cap PSM to - * iteration*record_id. - * As SAP does not carry a L2CAP PSM, we cannot validate the RFCOMM value - Assert.assertEquals(mOperationIndex+rfcommChannel, l2capPsm); */ - mLatch.countDown(); - } else { - Log.i(TAG, "Wrong service name (" + record.getServiceName() - + ") received, still waiting..."); - } - } else { - Log.i(TAG, "Wrong UUID received, still waiting..."); - } - } else { - Assert.fail("Unexpected intent received???"); - } - } - }; - - private void searchAwaitAndValidate(final String[] uuids, BluetoothDevice serverDevice, int count) { - IntentFilter filter = new IntentFilter(); - filter.addAction(BluetoothDevice.ACTION_SDP_RECORD); - final CountDownLatch latch = new CountDownLatch(count); - SdpBroadcastReceiver broadcastReceiver = new SdpBroadcastReceiver(uuids, latch); - - // Register receiver - mContext.registerReceiver(broadcastReceiver, filter); - - // Initiate searches - for(String uuid : uuids) { - if(uuid.toString().equals(BluetoothUuid.MAS.toString())) - serverDevice.sdpSearch(BluetoothUuid.MAS); - if(uuid.toString().equals(BluetoothUuid.MNS.toString())) - serverDevice.sdpSearch(BluetoothUuid.MNS); - if(uuid.toString().equals(BluetoothUuid.PBAP_PSE.toString())) - serverDevice.sdpSearch(BluetoothUuid.PBAP_PSE); - if(uuid.toString().equals(BluetoothUuid.ObexObjectPush.toString())) - serverDevice.sdpSearch(BluetoothUuid.ObexObjectPush); - if(uuid.toString().equals(BluetoothUuid.SAP.toString())) - serverDevice.sdpSearch(BluetoothUuid.SAP); - } - - // Await results - boolean waiting = true; - while(waiting == true) { - try { - Log.i(TAG, "SDP Search requested - awaiting result..."); - latch.await(); - Log.i(TAG, "SDP Search reresult received - continueing."); - waiting = false; - } catch (InterruptedException e) { - Log.w(TAG, "Interrupted witle waiting - keep waiting.", e); - waiting = true; - } - } - mContext.unregisterReceiver(broadcastReceiver); - } - -} diff --git a/tests/src/com/android/bluetooth/tests/SecurityTest.java b/tests/src/com/android/bluetooth/tests/SecurityTest.java deleted file mode 100644 index 10e291ea..00000000 --- a/tests/src/com/android/bluetooth/tests/SecurityTest.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.android.bluetooth.tests; - -import android.bluetooth.BluetoothAdapter; -import android.bluetooth.BluetoothDevice; -import android.bluetooth.BluetoothSocket; -import android.bluetooth.BluetoothUuid; -import android.test.AndroidTestCase; -import android.util.Log; - -import java.io.IOException; - -public class SecurityTest extends AndroidTestCase { - static final String TAG = "SecurityTest"; - - public void connectSapNoSec() { - BluetoothAdapter bt = BluetoothAdapter.getDefaultAdapter(); - if (bt == null) { - Log.e(TAG,"No Bluetooth Device!"); - assertTrue(false); - } - - BluetoothTestUtils.enableBt(bt); - Log.i(TAG,"BT Enabled"); - BluetoothDevice serverDevice = bt.getRemoteDevice(ObexTest.SERVER_ADDRESS); - Log.i(TAG,"ServerDevice: " + serverDevice); - - try { - BluetoothSocket socket = - serverDevice.createInsecureRfcommSocketToServiceRecord(BluetoothUuid.SAP.getUuid()); - Log.i(TAG,"createInsecureRfcommSocketToServiceRecord() - waiting for connect..."); - socket.connect(); - Log.i(TAG,"Connected!"); - Thread.sleep(5000); - Log.i(TAG,"Closing..."); - socket.close(); - Log.i(TAG,"Closed!"); - - } catch (InterruptedException e) { - Log.w(TAG, "Sleep interrupted", e); - fail(); - - } catch (IOException e) { - Log.e(TAG, "Failed to create connection", e); - fail(); - } - Log.i(TAG, "\n\n\nTest done - please fetch logs within 30 seconds...\n\n\n"); - try { - Thread.sleep(30000); - } catch (InterruptedException e) {} - } -} diff --git a/tests/src/com/android/bluetooth/tests/SeqStep.java b/tests/src/com/android/bluetooth/tests/SeqStep.java deleted file mode 100644 index 3f6772a5..00000000 --- a/tests/src/com/android/bluetooth/tests/SeqStep.java +++ /dev/null @@ -1,88 +0,0 @@ -package com.android.bluetooth.tests; - -import java.io.IOException; -import java.util.ArrayList; - -import javax.obex.HeaderSet; -import javax.obex.ObexPacket; -import javax.obex.Operation; - -import junit.framework.Assert; - -import com.android.bluetooth.tests.TestSequencer.OPTYPE; - -public class SeqStep { - /** - * Test step class to define the operations to be tested. - * Some of the data in these test steps will be modified during - * test - e.g. the HeaderSets will be modified to enable SRM - * and/or carry test information - */ - /* Operation type - Connect, Get, Put etc. */ - public OPTYPE mType; - /* The headers to send in the request - and validate on server side */ - public HeaderSet mReqHeaders = null; - /* The headers to send in the response - and validate on client side */ - public HeaderSet mResHeaders = null; - /* Use SRM */ - public boolean mUseSrm = false; - /* The amount of data to include in the body */ - public ObexTestParams mParams = null; - /* The offset into the data where the un-pause signal is to be sent */ - public int mUnPauseOffset = -1; - /* The offset into the data where the Abort request is to be sent */ - public int mAbortOffset = -1; - /* The side to perform Abort */ - public boolean mServerSideAbout = false; - /* The ID of the test step */ - private int mId; - - public boolean mSetPathBackup = false; /* bit 0 in flags */ - public boolean mSetPathCreate = false; /* Inverse of bit 1 in flags */ - - - public ISeqStepValidator mValidator = null; - public ISeqStepAction mServerPreAction = null; - public ISeqStepAction mClientPostAction = null; - - /* Arrays to hold expected sequence of request/response packets. */ - public ArrayList mRequestPackets = null; - public ArrayList mResponsePackets = null; - - public int index = 0; /* requests with same index are executed in parallel - (without waiting for a response) */ - - public SeqStep(OPTYPE type) { - mRequestPackets = new ArrayList(); - mResponsePackets = new ArrayList(); - mType = type; - } - - public boolean validate(HeaderSet response, Operation op) throws IOException { - Assert.assertNotNull(mValidator); - return mValidator.validate(this, response, op); - } - - public void serverPreAction(HeaderSet request, Operation op) throws IOException { - if(mServerPreAction != null) { - mServerPreAction.execute(this, request, op); - } - } - - public void clientPostAction(HeaderSet response, Operation op) throws IOException { - if(mClientPostAction != null) { - mClientPostAction.execute(this, response, op); - } - } - - - /* TODO: Consider to build these automatically based on the operations - * to be performed. Validate using utility functions - not strict - * binary compare. - * - * OR simply remove!*/ - public void addObexPacketSet(ObexPacket request, ObexPacket response) { - mRequestPackets.add(request); - mResponsePackets.add(response); - } -} diff --git a/tests/src/com/android/bluetooth/tests/TestResultLogger.java b/tests/src/com/android/bluetooth/tests/TestResultLogger.java deleted file mode 100644 index edc38647..00000000 --- a/tests/src/com/android/bluetooth/tests/TestResultLogger.java +++ /dev/null @@ -1,88 +0,0 @@ -package com.android.bluetooth.tests; - -import java.util.ArrayList; - -/** - * Class for collecting test results, and presenting them in different formats. - * @author cbonde - * - */ -public class TestResultLogger implements IResultLogger { - - private ArrayList mResults; - - private class Result { - public long timeStamp; // ms precision Unix Time UTC. - public long receivedBytes; - public Result(long t, long b) { - timeStamp = t; - receivedBytes = b; - } - } - - private TestResultLogger() { - mResults = new ArrayList(1000); - } - - public static IResultLogger createLogger(){ - return new TestResultLogger(); - } - - @Override - public void addResult(long bytesTransfered) { - mResults.add(new Result(System.currentTimeMillis(), bytesTransfered)); - } - - @Override - public int getAverageSpeed() { - if(mResults.size() < 1){ - return 0; - } - Result first = mResults.get(0); - Result last = mResults.get(mResults.size()-1); - // Multiply by 1000 to convert from ms to sec without loss - // of precision. - return (int) ((1000*(last.receivedBytes + first.receivedBytes))/ - (last.timeStamp - first.timeStamp+1)); - } - - /** - * Optimized to perform best when period is closest to the last - * result entry. - * If the period does not match a log entry, an estimate will be made - * to compensate. - * If the result log does not contain data to cover the entire period - * the resulting value will represent the average speed of the content - * in the log. - */ - @Override - public int getAverageSpeed(long period) { - Result preFirst = null; - Result first = mResults.get(0); - int i = mResults.size()-1; - Result last = mResults.get(i--); - long firstTimeStamp = last.timeStamp - period; - if(first.timeStamp > firstTimeStamp || mResults.size() < 3) { - // Not enough data, use total average - return getAverageSpeed(); - } - for(; i >= 0 ; i--) { - preFirst = mResults.get(i); - if(preFirst.timeStamp < firstTimeStamp) { - first = mResults.get(i+1); - break; - } - } - long timeError = period - (last.timeStamp-first.timeStamp); - long errorBytes = 0; - if(timeError > 0) { - // Find the amount of bytes to use for correction - errorBytes = (timeError*(preFirst.receivedBytes - first.receivedBytes)) - /(preFirst.timeStamp - first.timeStamp+1); - } - // Calculate the result - return (int) ((1000*(errorBytes+last.receivedBytes-first.receivedBytes))/period); - } - - -} diff --git a/tests/src/com/android/bluetooth/tests/TestSequencer.java b/tests/src/com/android/bluetooth/tests/TestSequencer.java deleted file mode 100644 index 090607f3..00000000 --- a/tests/src/com/android/bluetooth/tests/TestSequencer.java +++ /dev/null @@ -1,283 +0,0 @@ -package com.android.bluetooth.tests; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.concurrent.CountDownLatch; - -import javax.obex.ClientSession; -import javax.obex.HeaderSet; -import javax.obex.ObexTransport; -import javax.obex.Operation; -import javax.obex.ServerSession; - -import junit.framework.Assert; - -import android.content.Context; -import android.os.Handler; -import android.os.Handler.Callback; -import android.os.HandlerThread; -import android.os.Message; -import android.os.PowerManager; -import android.util.Log; - -public class TestSequencer implements Callback { - protected static String TAG = "TestSequencer"; - protected static final boolean D = true; - - private final static int MSG_ID_TIMEOUT = 0x01; - private final static int TIMEOUT_VALUE = 100*2000; // ms - private ArrayList mSequence = null; - private HandlerThread mHandlerThread = null; - private Handler mMessageHandler = null; - private ObexTransport mClientTransport; - private ObexTransport mServerTransport; - - private ClientSession mClientSession = null; - private ServerSession mServerSession = null; - public static final int STEP_INDEX_HEADER = 0xF1; /*0xFE*/ - - public enum OPTYPE {CONNECT, PUT, GET, SET_PATH, DISCONNECT}; - - private ITestSequenceConfigurator mConfigurator = null; - - public TestSequencer(ObexTransport clientTransport, ObexTransport serverTransport, - ITestSequenceConfigurator configurator) - throws IOException { - /* Setup the looper thread to handle timeout messages */ -// mHandlerThread = new HandlerThread("TestTimeoutHandler", -// android.os.Process.THREAD_PRIORITY_BACKGROUND); -// mHandlerThread.start(); -// Looper testLooper = mHandlerThread.getLooper(); -// mMessageHandler = new Handler(testLooper, this); - //TODO: fix looper cleanup on server - crash after 464 iterations - related to prepare? - - mClientTransport = clientTransport; - mServerTransport = serverTransport; - - /* Initialize members */ - mSequence = new ArrayList(); - mConfigurator = configurator; - Assert.assertNotNull(configurator); - } - - /** - * Add a test step to the sequencer. - * @param type the OBEX operation to perform. - * @return the created step, which can be decorated before execution. - */ - public SeqStep addStep(OPTYPE type, ISeqStepValidator validator) { - SeqStep newStep = new SeqStep(type); - newStep.mValidator = validator; - mSequence.add(newStep); - return newStep; - } - - /** - * Add a sub-step to a sequencer step. All requests added to the same index will be send to - * the SapServer in the order added before listening for the response. - * The response order is not validated - hence for each response received the entire list of - * responses in the step will be searched for a match. - * @param index the index returned from addStep() to which the sub-step is to be added. - * @param request The request to send to the SAP server - * @param response The response to EXPECT from the SAP server - - public void addSubStep(int index, SapMessage request, SapMessage response) { - SeqStep step = sequence.get(index); - step.add(request, response); - }*/ - - - /** - * Run the sequence. - * Validate the response is either the expected response or one of the expected events. - * - * @return true when done - asserts at error/fail - */ - public boolean run(Context context) throws IOException { - CountDownLatch stopLatch = new CountDownLatch(1); - PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE); - PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG); - //wl.acquire(); - try { - /* TODO: - * First create sequencer to validate using BT-snoop - * 1) Create the transports (this could include a validation sniffer on each side) - * 2) Create a server thread with a link to the transport - * 3) execute the client operation - * 4) validate response - * - * On server: - * 1) validate the request contains the expected content - * 2) send response. - * */ - - /* Create the server */ - if(mServerTransport != null) { - mServerSession = new ServerSession(mServerTransport, - mConfigurator.getObexServer(mSequence, stopLatch) , null); - } - - /* Create the client */ - if(mClientTransport != null) { - mClientSession = new ClientSession(mClientTransport); - - for(SeqStep step : mSequence) { - long stepIndex = mSequence.indexOf(step); - - Log.i(TAG, "Executing step " + stepIndex + " of type: " + step.mType); - - switch(step.mType) { - case CONNECT: { - HeaderSet reqHeaders = step.mReqHeaders; - if(reqHeaders == null) { - reqHeaders = new HeaderSet(); - } - reqHeaders.setHeader(STEP_INDEX_HEADER, stepIndex); - HeaderSet response = mClientSession.connect(reqHeaders); - step.validate(response, null); - step.clientPostAction(response, null); - break; - } - case GET:{ - HeaderSet reqHeaders = step.mReqHeaders; - if(reqHeaders == null) { - reqHeaders = new HeaderSet(); - } - reqHeaders.setHeader(STEP_INDEX_HEADER, stepIndex); - Log.i(TAG, " Starting operation..."); - Operation op = mClientSession.get(reqHeaders); - Log.i(TAG, " Operation done..."); - step.validate(null, op); - step.clientPostAction(null, op); - break; - } - case PUT: { - HeaderSet reqHeaders = step.mReqHeaders; - if(reqHeaders == null) { - reqHeaders = new HeaderSet(); - } - reqHeaders.setHeader(STEP_INDEX_HEADER, stepIndex); - Operation op = mClientSession.put(reqHeaders); - step.validate(null, op); - step.clientPostAction(null, op); - break; - } - case SET_PATH: { - HeaderSet reqHeaders = step.mReqHeaders; - if(reqHeaders == null) { - reqHeaders = new HeaderSet(); - } - reqHeaders.setHeader(STEP_INDEX_HEADER, stepIndex); - try{ - HeaderSet response = mClientSession.setPath(reqHeaders, - step.mSetPathBackup, step.mSetPathCreate);; - Log.i(TAG,"Received setPath response..."); - step.validate(response, null); - step.clientPostAction(response, null); - } catch (IOException e) { - Log.e(TAG, "Error getting response code", e); - } - break; - } - case DISCONNECT: { - Log.i(TAG,"Requesting disconnect..."); - HeaderSet reqHeaders = step.mReqHeaders; - if(reqHeaders == null) { - reqHeaders = new HeaderSet(); - } - reqHeaders.setHeader(STEP_INDEX_HEADER, stepIndex); - try{ - HeaderSet response = mClientSession.disconnect(reqHeaders); - Log.i(TAG,"Received disconnect response..."); - step.validate(response, null); - step.clientPostAction(response, null); - } catch (IOException e) { - Log.e(TAG, "Error getting response code", e); - } - break; - } - default: - Assert.assertTrue("Unknown type: " + step.mType, false); - break; - - } - } - mClientSession.close(); - } - /* All done, close down... */ - if(mServerSession != null) { - boolean interrupted = false; - do { - try { - interrupted = false; - Log.i(TAG,"Waiting for stopLatch signal..."); - stopLatch.await(); - } catch (InterruptedException e) { - Log.w(TAG,e); - interrupted = true; - } - } while (interrupted == true); - Log.i(TAG,"stopLatch signal received closing down..."); - try { - interrupted = false; - Log.i(TAG," Sleep 50ms to allow disconnect signal to be send before closing."); - Thread.sleep(50); - } catch (InterruptedException e) { - Log.w(TAG,e); - interrupted = true; - } - mServerSession.close(); - } - // this will close the I/O streams as well. - } finally { - //wl.release(); - } - return true; - } - - public void shutdown() { -// mMessageHandler.removeCallbacksAndMessages(null); -// mMessageHandler.quit(); -// mMessageHandler = null; - } - - -// private void startTimer() { -// Message timeoutMessage = mMessageHandler.obtainMessage(MSG_ID_TIMEOUT); -// mMessageHandler.sendMessageDelayed(timeoutMessage, TIMEOUT_VALUE); -// } -// -// private void stopTimer() { -// mMessageHandler.removeMessages(MSG_ID_TIMEOUT); -// } - - @Override - public boolean handleMessage(Message msg) { - - Log.i(TAG,"Handling message ID: " + msg.what); - - switch(msg.what) { - case MSG_ID_TIMEOUT: - Log.w(TAG, "Timeout occured!"); -/* try { - //inStream.close(); - } catch (IOException e) { - Log.e(TAG, "failed to close inStream", e); - } - try { - //outStream.close(); - } catch (IOException e) { - Log.e(TAG, "failed to close outStream", e); - }*/ - break; - default: - /* Message not handled */ - return false; - } - return true; // Message handles - } - - - -} - diff --git a/tests/src/com/android/bluetooth/tests/mock/BluetoothMockContext.java b/tests/src/com/android/bluetooth/tests/mock/BluetoothMockContext.java deleted file mode 100644 index 02414491..00000000 --- a/tests/src/com/android/bluetooth/tests/mock/BluetoothMockContext.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright (C) 2015 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.android.bluetooth.tests.mock; - -import android.content.ContentResolver; -import android.content.Context; -import android.content.res.Resources; -import android.test.mock.MockContext; - -/** - * A context that return our {@link android.test.mock.MockContentResolver}. - */ -public class BluetoothMockContext extends MockContext { - private ContentResolver mMockContentResolver; - private Context mOriginalContext; - - public BluetoothMockContext(ContentResolver mockContentResolver, Context originalContext) { - mMockContentResolver = mockContentResolver; - mOriginalContext = originalContext; - } - - @Override - public ContentResolver getContentResolver() { - return mMockContentResolver; - } - - @Override - public Resources getResources() { - return mOriginalContext.getResources(); - } - - @Override - public Object getSystemService(String name) { - return mOriginalContext.getSystemService(name); - } -} diff --git a/tests/src/com/android/bluetooth/tests/mock/SimpleMockContentProvider.java b/tests/src/com/android/bluetooth/tests/mock/SimpleMockContentProvider.java deleted file mode 100644 index 1d358b22..00000000 --- a/tests/src/com/android/bluetooth/tests/mock/SimpleMockContentProvider.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (C) 2015 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.android.bluetooth.tests.mock; - -import android.database.Cursor; -import android.net.Uri; -import android.test.mock.MockContentProvider; - -/** - * A provider that always return the result you want it to return - */ -public class SimpleMockContentProvider extends MockContentProvider { - private Cursor mResult; - - public SimpleMockContentProvider(Cursor result) { - mResult = result; - } - - @Override - public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { - return mResult; - } -} diff --git a/tests/src/com/android/bluetooth/tests/pbap/BluetoothPbapVcardManagerTest.java b/tests/src/com/android/bluetooth/tests/pbap/BluetoothPbapVcardManagerTest.java deleted file mode 100644 index ec000a0e..00000000 --- a/tests/src/com/android/bluetooth/tests/pbap/BluetoothPbapVcardManagerTest.java +++ /dev/null @@ -1,149 +0,0 @@ -/* - * Copyright (C) 2015 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.android.bluetooth.tests.pbap; - -import com.android.bluetooth.pbap.BluetoothPbapObexServer; -import com.android.bluetooth.pbap.BluetoothPbapVcardManager; -import com.android.bluetooth.tests.mock.BluetoothMockContext; -import com.android.bluetooth.tests.mock.SimpleMockContentProvider; - -import android.database.Cursor; -import android.database.MatrixCursor; -import android.provider.ContactsContract; -import android.provider.ContactsContract.PhoneLookup; -import android.test.AndroidTestCase; -import android.test.mock.MockContentProvider; -import android.test.mock.MockContentResolver; -import android.provider.ContactsContract.CommonDataKinds.Phone; -import android.text.TextUtils; - - -import java.util.ArrayList; - -public class BluetoothPbapVcardManagerTest extends AndroidTestCase { - - public void testGetContactNamesByNumberWithEmptyPhoneNumber() { - getContactNamesByNumberInternal(""); - } - - public void testGetContactNamesByNumberWithPhoneNumber() { - getContactNamesByNumberInternal("111-111-111"); - } - - private void getContactNamesByNumberInternal(String phoneNumber) { - String[] columnNames; - if (TextUtils.isEmpty(phoneNumber)) { - columnNames = new String[]{Phone.CONTACT_ID, Phone.DISPLAY_NAME}; - } else { - columnNames = new String[]{PhoneLookup._ID, PhoneLookup.DISPLAY_NAME}; - } - - MatrixCursor mc = new MatrixCursor(columnNames); - mc.addRow(new Object[]{1L, "A"}); - mc.addRow(new Object[]{1L, "A (1)"}); - mc.addRow(new Object[]{2L, "B"}); - mc.addRow(new Object[]{2L, "B (1)"}); - mc.addRow(new Object[]{3L, "C"}); - mc.addRow(new Object[]{3L, "C (1)"}); - mc.addRow(new Object[]{3L, "C (2)"}); - mc.addRow(new Object[]{4L, "D"}); - BluetoothPbapVcardManager manager = createBluetoothPbapVcardManager(mc); - ArrayList nameList = manager.getContactNamesByNumber(phoneNumber); - - // If there are multiple display name per id, first one is picked. - assertEquals("A,1", nameList.get(0)); - assertEquals("B,2", nameList.get(1)); - assertEquals("C,3", nameList.get(2)); - assertEquals("D,4", nameList.get(3)); - } - - public void testGetDistinctContactIdSize() { - MatrixCursor mc = new MatrixCursor(new String[]{ContactsContract.Data.CONTACT_ID}); - mc.addRow(new String[]{"1"}); - mc.addRow(new String[]{"1"}); - mc.addRow(new String[]{"2"}); - mc.addRow(new String[]{"2"}); - mc.addRow(new String[]{"3"}); - mc.addRow(new String[]{"3"}); - mc.addRow(new String[]{"3"}); - mc.addRow(new String[]{"4"}); - mc.addRow(new String[]{"5"}); - BluetoothPbapVcardManager manager = createBluetoothPbapVcardManager(mc); - int size = manager.getContactsSize(); - - assertEquals(5 + 1, size); // +1 becoz of always has the 0.vcf - } - - public void testGetPhonebookNameListOrderByIndex() { - MatrixCursor mc = new MatrixCursor( - new String[]{ContactsContract.CommonDataKinds.Phone.CONTACT_ID, - ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME}); - // test name duplication. - mc.addRow(new Object[]{1L, "A"}); - mc.addRow(new Object[]{1L, "A (1)"}); - mc.addRow(new Object[]{2L, "B"}); - mc.addRow(new Object[]{2L, "B (1)"}); - mc.addRow(new Object[]{3L, "C"}); - mc.addRow(new Object[]{3L, "C (1)"}); - mc.addRow(new Object[]{3L, "C (2)"}); - mc.addRow(new Object[]{4L, "D"}); - // test default name. - mc.addRow(new Object[]{5L, null}); - BluetoothPbapVcardManager manager = createBluetoothPbapVcardManager(mc); - ArrayList nameList = manager - .getPhonebookNameList(BluetoothPbapObexServer.ORDER_BY_INDEXED); - - // Skip the first one which is supposed to be owner name. - assertEquals("A,1", nameList.get(1)); - assertEquals("B,2", nameList.get(2)); - assertEquals("C,3", nameList.get(3)); - assertEquals("D,4", nameList.get(4)); - assertEquals(getContext().getString(android.R.string.unknownName) + ",5", nameList.get(5)); - } - - public void testGetPhonebookNameListOrderByAlphabetical() { - MatrixCursor mc = new MatrixCursor( - new String[]{ContactsContract.CommonDataKinds.Phone.CONTACT_ID, - ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME}); - // test sorting order. - mc.addRow(new Object[]{1L, "D"}); - mc.addRow(new Object[]{1L, "D (1)"}); - mc.addRow(new Object[]{2L, "C"}); - mc.addRow(new Object[]{2L, "C (1)"}); - mc.addRow(new Object[]{3L, "A"}); - mc.addRow(new Object[]{3L, "A (1)"}); - mc.addRow(new Object[]{3L, "A (2)"}); - mc.addRow(new Object[]{4L, "B"}); - BluetoothPbapVcardManager manager = createBluetoothPbapVcardManager(mc); - ArrayList nameList = manager - .getPhonebookNameList(BluetoothPbapObexServer.ORDER_BY_ALPHABETICAL); - - // Skip the first one which is supposed to be owner name. - assertEquals("A,3", nameList.get(1)); - assertEquals("B,4", nameList.get(2)); - assertEquals("C,2", nameList.get(3)); - assertEquals("D,1", nameList.get(4)); - } - - private BluetoothPbapVcardManager createBluetoothPbapVcardManager(Cursor result) { - MockContentProvider contentProvider = new SimpleMockContentProvider(result); - MockContentResolver contentResolver = new MockContentResolver(); - contentResolver.addProvider(ContactsContract.AUTHORITY, contentProvider); - BluetoothMockContext mockContext = new BluetoothMockContext(contentResolver, getContext()); - return new BluetoothPbapVcardManager(mockContext); - } -} diff --git a/tests/src/com/android/bluetooth/tests/pbap/ContactCursorFilterTest.java b/tests/src/com/android/bluetooth/tests/pbap/ContactCursorFilterTest.java deleted file mode 100644 index 66908c94..00000000 --- a/tests/src/com/android/bluetooth/tests/pbap/ContactCursorFilterTest.java +++ /dev/null @@ -1,161 +0,0 @@ -/* - * Copyright (C) 2015 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.android.bluetooth.tests.pbap; - -import android.database.Cursor; -import android.database.MatrixCursor; -import android.provider.ContactsContract; -import android.test.AndroidTestCase; - -import com.android.bluetooth.pbap.BluetoothPbapVcardManager; - -public class ContactCursorFilterTest extends AndroidTestCase { - - public void testFilterByRangeWithoutDup() { - MatrixCursor mc = new MatrixCursor(new String[]{ - ContactsContract.CommonDataKinds.Phone.CONTACT_ID, - ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME}); - mc.addRow(new Object[]{1L, "Test"}); - mc.addRow(new Object[]{2L, "Test"}); - mc.addRow(new Object[]{3L, "Test"}); - - Cursor cursor = BluetoothPbapVcardManager.ContactCursorFilter.filterByRange(mc, 1, 2); - assertEquals(2, cursor.getCount()); - assertEquals(1L, getContactsIdFromCursor(cursor, 0)); - assertEquals(2L, getContactsIdFromCursor(cursor, 1)); - cursor.close(); - - mc.moveToPosition(-1); - cursor = BluetoothPbapVcardManager.ContactCursorFilter.filterByRange(mc, 1, 3); - assertEquals(3, cursor.getCount()); - assertEquals(1L, getContactsIdFromCursor(cursor, 0)); - assertEquals(2L, getContactsIdFromCursor(cursor, 1)); - assertEquals(3L, getContactsIdFromCursor(cursor, 2)); - cursor.close(); - - mc.moveToPosition(-1); - cursor = BluetoothPbapVcardManager.ContactCursorFilter.filterByRange(mc, 2, 3); - assertEquals(2, cursor.getCount()); - assertEquals(2L, getContactsIdFromCursor(cursor, 0)); - assertEquals(3L, getContactsIdFromCursor(cursor, 1)); - cursor.close(); - - mc.moveToPosition(-1); - cursor = BluetoothPbapVcardManager.ContactCursorFilter.filterByRange(mc, 3, 3); - assertEquals(1, cursor.getCount()); - assertEquals(3L, getContactsIdFromCursor(cursor, 0)); - cursor.close(); - } - - - public void testFilterByRangeWithDup() { - MatrixCursor mc = new MatrixCursor(new String[]{ContactsContract.CommonDataKinds.Phone - .CONTACT_ID, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME}); - mc.addRow(new Object[]{1L, "Test"}); - mc.addRow(new Object[]{1L, "Test"}); - mc.addRow(new Object[]{2L, "Test"}); - mc.addRow(new Object[]{2L, "Test"}); - mc.addRow(new Object[]{3L, "Test"}); - - Cursor cursor = BluetoothPbapVcardManager.ContactCursorFilter.filterByRange(mc, 1, 2); - assertEquals(2, cursor.getCount()); - assertEquals(1L, getContactsIdFromCursor(cursor, 0)); - assertEquals(2L, getContactsIdFromCursor(cursor, 1)); - cursor.close(); - - mc.moveToPosition(-1); - cursor = BluetoothPbapVcardManager.ContactCursorFilter.filterByRange(mc, 1, 3); - assertEquals(3, cursor.getCount()); - assertEquals(1L, getContactsIdFromCursor(cursor, 0)); - assertEquals(2L, getContactsIdFromCursor(cursor, 1)); - assertEquals(3L, getContactsIdFromCursor(cursor, 2)); - cursor.close(); - - mc.moveToPosition(-1); - cursor = BluetoothPbapVcardManager.ContactCursorFilter.filterByRange(mc, 2, 3); - assertEquals(2, cursor.getCount()); - assertEquals(2L, getContactsIdFromCursor(cursor, 0)); - assertEquals(3L, getContactsIdFromCursor(cursor, 1)); - cursor.close(); - - mc.moveToPosition(-1); - cursor = BluetoothPbapVcardManager.ContactCursorFilter.filterByRange(mc, 3, 3); - assertEquals(1, cursor.getCount()); - assertEquals(3L, getContactsIdFromCursor(cursor, 0)); - cursor.close(); - } - - public void testFilterByOffsetWithoutDup() { - MatrixCursor mc = new MatrixCursor(new String[]{ContactsContract.CommonDataKinds.Phone - .CONTACT_ID, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME}); - mc.addRow(new Object[]{1L, "Test"}); - mc.addRow(new Object[]{2L, "Test"}); - mc.addRow(new Object[]{3L, "Test"}); - - Cursor cursor = BluetoothPbapVcardManager.ContactCursorFilter.filterByOffset(mc, 1); - assertEquals(1, cursor.getCount()); - assertEquals(1L, getContactsIdFromCursor(cursor, 0)); - cursor.close(); - - mc.moveToPosition(-1); - cursor = BluetoothPbapVcardManager.ContactCursorFilter.filterByOffset(mc, 2); - assertEquals(1, cursor.getCount()); - assertEquals(2L, getContactsIdFromCursor(cursor, 0)); - cursor.close(); - - mc.moveToPosition(-1); - cursor = BluetoothPbapVcardManager.ContactCursorFilter.filterByOffset(mc, 3); - assertEquals(1, cursor.getCount()); - assertEquals(3L, getContactsIdFromCursor(cursor, 0)); - cursor.close(); - } - - public void testFilterByOffsetWithDup() { - MatrixCursor mc = new MatrixCursor(new String[]{ContactsContract.CommonDataKinds.Phone - .CONTACT_ID, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME}); - mc.addRow(new Object[]{1L, "Test"}); - mc.addRow(new Object[]{1L, "Test"}); - mc.addRow(new Object[]{2L, "Test"}); - mc.addRow(new Object[]{2L, "Test"}); - mc.addRow(new Object[]{3L, "Test"}); - - Cursor cursor = BluetoothPbapVcardManager.ContactCursorFilter.filterByOffset(mc, 1); - assertEquals(1, cursor.getCount()); - assertEquals(1L, getContactsIdFromCursor(cursor, 0)); - cursor.close(); - - mc.moveToPosition(-1); - cursor = BluetoothPbapVcardManager.ContactCursorFilter.filterByOffset(mc, 2); - assertEquals(1, cursor.getCount()); - assertEquals(2L, getContactsIdFromCursor(cursor, 0)); - cursor.close(); - - mc.moveToPosition(-1); - cursor = BluetoothPbapVcardManager.ContactCursorFilter.filterByOffset(mc, 3); - assertEquals(1, cursor.getCount()); - assertEquals(3L, getContactsIdFromCursor(cursor, 0)); - cursor.close(); - mc.moveToFirst(); - - } - - private long getContactsIdFromCursor(Cursor cursor, int offset) { - int index = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID); - cursor.moveToPosition(offset); - return cursor.getLong(index); - } -} diff --git a/tests/src/com/android/bluetooth/util/NumberUtilsTest.java b/tests/src/com/android/bluetooth/util/NumberUtilsTest.java deleted file mode 100644 index a2fa1aad..00000000 --- a/tests/src/com/android/bluetooth/util/NumberUtilsTest.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (C) 2014 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.android.bluetooth.util; - -import android.test.AndroidTestCase; -import android.test.suitebuilder.annotation.SmallTest; - -/** - * Tests for {@link NumberUtils}. - */ -public class NumberUtilsTest extends AndroidTestCase { - - @SmallTest - public static void testUnsignedByteToInt() { - assertEquals(0, NumberUtils.unsignedByteToInt((byte) 0)); - assertEquals(19, NumberUtils.unsignedByteToInt((byte) 19)); - assertEquals(154, NumberUtils.unsignedByteToInt((byte) 154)); - } - - @SmallTest - public void testLittleEndianByteArrayToInt() { - assertEquals(1, NumberUtils.littleEndianByteArrayToInt(new byte[] { - 1 })); - assertEquals(513, NumberUtils.littleEndianByteArrayToInt(new byte[] { - 1, 2 })); - assertEquals(197121, NumberUtils.littleEndianByteArrayToInt(new byte[] { - 1, 2, 3 })); - } -} -- 2.11.0