diff options
58 files changed, 7015 insertions, 59 deletions
diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..4e0470e8 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +*.pro.user +qtbluetoothversion.h +qtnfcversion.h diff --git a/src/bluetooth/qbluetoothdevicediscoveryagent_bluez.cpp b/src/bluetooth/qbluetoothdevicediscoveryagent_bluez.cpp index 3a510afa..a0b0f052 100644 --- a/src/bluetooth/qbluetoothdevicediscoveryagent_bluez.cpp +++ b/src/bluetooth/qbluetoothdevicediscoveryagent_bluez.cpp @@ -48,7 +48,7 @@ #include "bluez/adapter_p.h" #include "bluez/device_p.h" -//#define QTM_DEVICEDISCOVERY_DEBUG +//#define QT_DEVICEDISCOVERY_DEBUG QBluetoothDeviceDiscoveryAgentPrivate::QBluetoothDeviceDiscoveryAgentPrivate() : lastError(QBluetoothDeviceDiscoveryAgent::NoError), pendingCancel(false), pendingStart(false), adapter(0) @@ -86,7 +86,7 @@ void QBluetoothDeviceDiscoveryAgentPrivate::start() reply.waitForFinished(); if (reply.isError()) { errorString = reply.error().message(); -#ifdef QTM_DEVICEDISCOVERY_DEBUG +#ifdef QT_DEVICEDISCOVERY_DEBUG qDebug() << Q_FUNC_INFO << "ERROR: " << errorString; #endif lastError = QBluetoothDeviceDiscoveryAgent::IOFailure; @@ -107,7 +107,7 @@ void QBluetoothDeviceDiscoveryAgentPrivate::start() QDBusPendingReply<QVariantMap> propertiesReply = adapter->GetProperties(); propertiesReply.waitForFinished(); if(propertiesReply.isError()) { -#ifdef QTM_DEVICEDISCOVERY_DEBUG +#ifdef QT_DEVICEDISCOVERY_DEBUG qDebug() << Q_FUNC_INFO << "ERROR: " << errorString; #endif errorString = propertiesReply.error().message(); @@ -125,7 +125,7 @@ void QBluetoothDeviceDiscoveryAgentPrivate::start() lastError = QBluetoothDeviceDiscoveryAgent::IOFailure; Q_Q(QBluetoothDeviceDiscoveryAgent); emit q->error(lastError); -#ifdef QTM_DEVICEDISCOVERY_DEBUG +#ifdef QT_DEVICEDISCOVERY_DEBUG qDebug() << Q_FUNC_INFO << "ERROR: " << errorString; #endif return; @@ -135,7 +135,7 @@ void QBluetoothDeviceDiscoveryAgentPrivate::start() void QBluetoothDeviceDiscoveryAgentPrivate::stop() { if (adapter) { -#ifdef QTM_DEVICEDISCOVERY_DEBUG +#ifdef QT_DEVICEDISCOVERY_DEBUG qDebug() << Q_FUNC_INFO; #endif pendingCancel = true; @@ -152,7 +152,7 @@ void QBluetoothDeviceDiscoveryAgentPrivate::_q_deviceFound(const QString &addres const QString btName = dict.value(QLatin1String("Name")).toString(); quint32 btClass = dict.value(QLatin1String("Class")).toUInt(); -#ifdef QTM_DEVICEDISCOVERY_DEBUG +#ifdef QT_DEVICEDISCOVERY_DEBUG qDebug() << "Discovered: " << address << btName << "Num UUIDs" << dict.value(QLatin1String("UUIDs")).toStringList().count() << "total device" << discoveredDevices.count() << "cached" @@ -172,14 +172,14 @@ void QBluetoothDeviceDiscoveryAgentPrivate::_q_deviceFound(const QString &addres for(int i = 0; i < discoveredDevices.size(); i++){ if(discoveredDevices[i].address() == device.address()) { if(discoveredDevices[i] == device) { -#ifdef QTM_DEVICEDISCOVERY_DEBUG +#ifdef QT_DEVICEDISCOVERY_DEBUG qDebug() << "Duplicate: " << address; #endif return; } discoveredDevices.replace(i, device); Q_Q(QBluetoothDeviceDiscoveryAgent); -#ifdef QTM_DEVICEDISCOVERY_DEBUG +#ifdef QT_DEVICEDISCOVERY_DEBUG qDebug() << "Updated: " << address; #endif @@ -187,7 +187,7 @@ void QBluetoothDeviceDiscoveryAgentPrivate::_q_deviceFound(const QString &addres return; // this works if the list doesn't contain duplicates. Don't let it. } } -#ifdef QTM_DEVICEDISCOVERY_DEBUG +#ifdef QT_DEVICEDISCOVERY_DEBUG qDebug() << "Emit: " << address; #endif discoveredDevices.append(device); @@ -198,7 +198,7 @@ void QBluetoothDeviceDiscoveryAgentPrivate::_q_deviceFound(const QString &addres void QBluetoothDeviceDiscoveryAgentPrivate::_q_propertyChanged(const QString &name, const QDBusVariant &value) { -#ifdef QTM_DEVICEDISCOVERY_DEBUG +#ifdef QT_DEVICEDISCOVERY_DEBUG qDebug() << Q_FUNC_INFO << name << value.variant(); #endif diff --git a/src/bluetooth/qbluetoothdevicediscoveryagent_p.cpp b/src/bluetooth/qbluetoothdevicediscoveryagent_p.cpp index 83b4a623..7052f857 100644 --- a/src/bluetooth/qbluetoothdevicediscoveryagent_p.cpp +++ b/src/bluetooth/qbluetoothdevicediscoveryagent_p.cpp @@ -44,7 +44,7 @@ #include "qbluetoothaddress.h" #include "qbluetoothuuid.h" -#define QTM_DEVICEDISCOVERY_DEBUG +#define QT_DEVICEDISCOVERY_DEBUG QBluetoothDeviceDiscoveryAgentPrivate::QBluetoothDeviceDiscoveryAgentPrivate() diff --git a/src/bluetooth/qbluetoothglobal.h b/src/bluetooth/qbluetoothglobal.h index 02afa7bf..973e517b 100644 --- a/src/bluetooth/qbluetoothglobal.h +++ b/src/bluetooth/qbluetoothglobal.h @@ -69,15 +69,4 @@ # endif #endif -#include <QtCore/qglobal.h> -#if defined(QTM_BUILD_UNITTESTS) && (defined(Q_OS_WIN) || defined(Q_OS_SYMBIAN)) && defined(QT_MAKEDLL) -# define QM_AUTOTEST_EXPORT Q_DECL_EXPORT -#elif defined(QTM_BUILD_UNITTESTS) && (defined(Q_OS_WIN) || defined(Q_OS_SYMBIAN)) && defined(QT_DLL) -# define QM_AUTOTEST_EXPORT Q_DECL_IMPORT -#elif defined(QTM_BUILD_UNITTESTS) && !(defined(Q_OS_WIN) || defined(Q_OS_SYMBIAN)) && defined(QT_SHARED) -# define QM_AUTOTEST_EXPORT Q_DECL_EXPORT -#else -# define QM_AUTOTEST_EXPORT -#endif - #endif // QTBLUETOOTH_H diff --git a/src/bluetooth/qbluetoothservicediscoveryagent_bluez.cpp b/src/bluetooth/qbluetoothservicediscoveryagent_bluez.cpp index abcaa23d..af24f8ac 100644 --- a/src/bluetooth/qbluetoothservicediscoveryagent_bluez.cpp +++ b/src/bluetooth/qbluetoothservicediscoveryagent_bluez.cpp @@ -48,9 +48,9 @@ #include <QtDBus/QDBusPendingCallWatcher> -//#define QTM_SERVICEDISCOVERY_DEBUG +//#define QT_SERVICEDISCOVERY_DEBUG -#ifdef QTM_SERVICEDISCOVERY_DEBUG +#ifdef QT_SERVICEDISCOVERY_DEBUG #include <QtCore/QDebug> #endif @@ -73,7 +73,7 @@ void QBluetoothServiceDiscoveryAgentPrivate::start(const QBluetoothAddress &addr { Q_Q(QBluetoothServiceDiscoveryAgent); -#ifdef QTM_SERVICEDISCOVERY_DEBUG +#ifdef QT_SERVICEDISCOVERY_DEBUG qDebug() << "Full discovery on: " << address.toString(); #endif @@ -106,7 +106,7 @@ void QBluetoothServiceDiscoveryAgentPrivate::start(const QBluetoothAddress &addr void QBluetoothServiceDiscoveryAgentPrivate::stop() { -#ifdef QTM_SERVICEDISCOVERY_DEBUG +#ifdef QT_SERVICEDISCOVERY_DEBUG qDebug() << Q_FUNC_INFO << "Stop called"; #endif if(device){ @@ -128,7 +128,7 @@ void QBluetoothServiceDiscoveryAgentPrivate::_q_createdDevice(QDBusPendingCallWa const QBluetoothAddress &address = watcher->property("_q_BTaddress").value<QBluetoothAddress>(); -#ifdef QTM_SERVICEDISCOVERY_DEBUG +#ifdef QT_SERVICEDISCOVERY_DEBUG qDebug() << Q_FUNC_INFO << "created" << address.toString(); #endif @@ -136,7 +136,7 @@ void QBluetoothServiceDiscoveryAgentPrivate::_q_createdDevice(QDBusPendingCallWa if (deviceObjectPath.isError()) { if (deviceObjectPath.error().name() != QLatin1String("org.bluez.Error.AlreadyExists")) { _q_serviceDiscoveryFinished(); -#ifdef QTM_SERVICEDISCOVERY_DEBUG +#ifdef QT_SERVICEDISCOVERY_DEBUG qDebug() << "Create device failed Error: " << error << deviceObjectPath.error().name(); #endif return; @@ -151,7 +151,7 @@ void QBluetoothServiceDiscoveryAgentPrivate::_q_createdDevice(QDBusPendingCallWa emit q->error(error); } _q_serviceDiscoveryFinished(); -#ifdef QTM_SERVICEDISCOVERY_DEBUG +#ifdef QT_SERVICEDISCOVERY_DEBUG qDebug() << "Can't find device after creation Error: " << error << deviceObjectPath.error().name(); #endif return; @@ -173,7 +173,7 @@ void QBluetoothServiceDiscoveryAgentPrivate::_q_createdDevice(QDBusPendingCallWa foreach (const QBluetoothUuid &uuid, uuidFilter) pattern += uuid.toString().remove(QLatin1Char('{')).remove(QLatin1Char('}')) + QLatin1Char(' '); -#ifdef QTM_SERVICEDISCOVERY_DEBUG +#ifdef QT_SERVICEDISCOVERY_DEBUG qDebug() << Q_FUNC_INFO << "Discover: " << pattern.trimmed(); #endif QDBusPendingReply<ServiceMap> discoverReply = device->DiscoverServices(pattern.trimmed()); @@ -185,13 +185,13 @@ void QBluetoothServiceDiscoveryAgentPrivate::_q_createdDevice(QDBusPendingCallWa void QBluetoothServiceDiscoveryAgentPrivate::_q_discoveredServices(QDBusPendingCallWatcher *watcher) { -#ifdef QTM_SERVICEDISCOVERY_DEBUG +#ifdef QT_SERVICEDISCOVERY_DEBUG qDebug() << Q_FUNC_INFO; #endif QDBusPendingReply<ServiceMap> reply = *watcher; if (reply.isError()) { -#ifdef QTM_SERVICEDISCOVERY_DEBUG +#ifdef QT_SERVICEDISCOVERY_DEBUG qDebug() << "discoveredServices error: " << error << reply.error().message(); #endif watcher->deleteLater(); @@ -207,14 +207,14 @@ void QBluetoothServiceDiscoveryAgentPrivate::_q_discoveredServices(QDBusPendingC ServiceMap map = reply.value(); -#ifdef QTM_SERVICEDISCOVERY_DEBUG +#ifdef QT_SERVICEDISCOVERY_DEBUG qDebug() << "Parsing xml" << discoveredDevices.at(0).address().toString() << discoveredDevices.count() << map.count(); #endif foreach (const QString &record, reply.value()) { QXmlStreamReader xml(record); -#ifdef QTM_SERVICEDISCOVERY_DEBUG +#ifdef QT_SERVICEDISCOVERY_DEBUG // qDebug() << "Service xml" << record; #endif @@ -243,7 +243,7 @@ void QBluetoothServiceDiscoveryAgentPrivate::_q_discoveredServices(QDBusPendingC Q_Q(QBluetoothServiceDiscoveryAgent); discoveredServices.append(serviceInfo); -#ifdef QTM_SERVICEDISCOVERY_DEBUG +#ifdef QT_SERVICEDISCOVERY_DEBUG qDebug() << "Discovered services" << discoveredDevices.at(0).address().toString(); #endif emit q->serviceDiscovered(serviceInfo); diff --git a/src/nfc/qnearfieldmanager_p.h b/src/nfc/qnearfieldmanager_p.h index 0c811a1f..3e640000 100644 --- a/src/nfc/qnearfieldmanager_p.h +++ b/src/nfc/qnearfieldmanager_p.h @@ -54,7 +54,7 @@ QT_BEGIN_HEADER class QNdefFilter; -class QM_AUTOTEST_EXPORT QNearFieldManagerPrivate : public QObject +class Q_AUTOTEST_EXPORT QNearFieldManagerPrivate : public QObject { Q_OBJECT diff --git a/src/nfc/qnfcglobal.h b/src/nfc/qnfcglobal.h index 6b68c257..f282bb19 100644 --- a/src/nfc/qnfcglobal.h +++ b/src/nfc/qnfcglobal.h @@ -69,15 +69,4 @@ # endif #endif -#include <QtCore/qglobal.h> -#if defined(QTM_BUILD_UNITTESTS) && (defined(Q_OS_WIN) || defined(Q_OS_SYMBIAN)) && defined(QT_MAKEDLL) -# define QM_AUTOTEST_EXPORT Q_DECL_EXPORT -#elif defined(QTM_BUILD_UNITTESTS) && (defined(Q_OS_WIN) || defined(Q_OS_SYMBIAN)) && defined(QT_DLL) -# define QM_AUTOTEST_EXPORT Q_DECL_IMPORT -#elif defined(QTM_BUILD_UNITTESTS) && !(defined(Q_OS_WIN) || defined(Q_OS_SYMBIAN)) && defined(QT_SHARED) -# define QM_AUTOTEST_EXPORT Q_DECL_EXPORT -#else -# define QM_AUTOTEST_EXPORT -#endif - #endif // QTNFC_H diff --git a/src/nfc/qtlv_p.h b/src/nfc/qtlv_p.h index f4681952..0a79a3ee 100644 --- a/src/nfc/qtlv_p.h +++ b/src/nfc/qtlv_p.h @@ -53,7 +53,7 @@ QT_BEGIN_HEADER class QNearFieldTarget; -class QM_AUTOTEST_EXPORT QTlvReader +class Q_AUTOTEST_EXPORT QTlvReader { public: explicit QTlvReader(QNearFieldTarget *target); diff --git a/tests/auto/auto.pro b/tests/auto/auto.pro new file mode 100644 index 00000000..2843cf58 --- /dev/null +++ b/tests/auto/auto.pro @@ -0,0 +1,38 @@ +TEMPLATE = subdirs + +# Required by tst_maketestselftest::tests_pro_files +# Mark the following non unit test directories ok +# nfcdata + +#SUBDIRS += \ +# qndefrecord \ +# qndefmessage \ +# qnearfieldtagtype1 \ +# qnearfieldtagtype2 \ +# qnearfieldmanager + +#!win32:SUBDIRS += \ +# qbluetoothaddress\ +# qbluetoothuuid\ +# qbluetoothdeviceinfo\ +# qbluetoothdevicediscoveryagent\ +# qbluetoothserviceinfo\ +# qbluetoothservicediscoveryagent\ +# qbluetoothsocket\ +# qrfcommserver \ +# qbluetoothtransferrequest + +#enable autotests on symbian +symbian:SUBDIRS += \ + qbluetoothaddress\ + qbluetoothuuid\ + qbluetoothdeviceinfo\ + qbluetoothdevicediscoveryagent\ + qbluetoothserviceinfo\ + qbluetoothservicediscoveryagent\ + qbluetoothsocket\ + qrfcommserver \ + qbluetoothtransferrequest \ + qbluetoothlocaldevice \ + qbluetoothtransfermanager \ + ql2capserver diff --git a/tests/auto/nfcdata/Qt Labs Website Tag Type1.nfc b/tests/auto/nfcdata/Qt Labs Website Tag Type1.nfc new file mode 100644 index 00000000..6840fbd6 --- /dev/null +++ b/tests/auto/nfcdata/Qt Labs Website Tag Type1.nfc @@ -0,0 +1,8 @@ +[Target] +Name=Qt Labs Website Tag +Type=TagType1 + +[TagType1] +HR0=17 +HR1=0 +Data=@ByteArray(wfUD3\"\x11\0\xe1\x10\xe\0\x3(\x91\x1\rT\x5\x65n_USQt LabsQ\x1\x13U\x3labs.qt.nokia.com/\xfe\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\x1`\0\0\0\0\0\0) diff --git a/tests/auto/nfcdata/Qt Website Tag Type1.nfc b/tests/auto/nfcdata/Qt Website Tag Type1.nfc new file mode 100644 index 00000000..1a6c92db --- /dev/null +++ b/tests/auto/nfcdata/Qt Website Tag Type1.nfc @@ -0,0 +1,9 @@ +[Target] +Name=Qt Website Tag +UID=11:22:33:44:55:66:77 +Type=TagType1 + +[TagType1] +HR0=18 +HR1=0 +Data="@ByteArray(\x11\"3DUfw\0\xe1\x10\xff\0\x3\xff\x4*\x82\t\0\0\x3\xc0image/png\x89PNG\r\n\x1a\n\0\0\0\rIHDR\0\0\0\x39\0\0\0\x43\b\x3\0\0\0\x11\x7f]\x10\0\0\0\x1sRGB\0\xae\xce\x1c\xe9\0\0\0\xc0PLTE\x2\x43\x11\x2\x46\x1a\x4I\b\x1I#\0K\x1e\x11K'\0\0\0\0\0\0\0\0\0\x1`\0\0\0\0\0\0\0\0\0\0\0\0\0\0T\x1a\x1V\v\x10S,\x10`#\x1eZ8\xen\x10*cA\x13q\0\x1bv\x13:qO,\x82\x16\x39\x80\x42.\x8c\x1b.\x91\xfO\x7f\x63.\x95\x3;\x96\"8\x9b\x18\x36\x9f\x2^\x8bpB\xa2\x1a\x45\xa4\x1d\x43\xab\x17J\xa9\"M\xaa\x18m\x99}N\xb2\x14V\xae\x32\x80\xa1\x8bj\xadY`\xb3\x43x\xafos\xbcQy\xbeZ\x93\xb1\x9f{\xbf\x64\x92\xba\x8f\x88\xc5i\x9e\xbc\xa8\x93\xcbz\x9b\xce\x88\xb7\xcd\xbf\xba\xd0\xc2\xb1\xda\x9a\xb3\xdb\xa4\xcb\xd9\xcd\xc2\xe1\xb0\xc8\xe4\xba\xcc\xe8\xc5\xdb\xe5\xdf\xdb\xee\xd3\xe0\xf4\xd0\xe9\xf0\xec\xe8\xf3\xe1\xeb\xf6\xea\xf7\xfa\xf6\xfc\xfe\xfb\xfe\xff\xfc\xfe\x35:\x8c\0\0\0\x1\x62KGD\0\x88\x5\x1dH\0\0\0\tpHYs\0\0\v\x13\0\0\v\x13\x1\0\x9a\x9c\x18\0\0\0\atIME\a\xda\n\x1c\x5\f\t\xfc\xacP,\0\0\x2yIDATH\xc7\xed\x97k{\xda \x14\xc7\xf1\xb2\xdaj\x1b\x9dNE!q\xb4\xce\xe8\x66\xb4\xad\xb9\x38\x3\xe5\xfb\x7f\xab\x2\x41\x1bS\r\xb8\xe7\xd9\x9e\xbd\xf0\xbcJb~\xf9\xc3\xb9q\x4\xfcO\r\\\xc9\xff\x9e\x64\xec_k\xb2\xe7\xc7\xc9\x8f\xc5l\xb1\n\xb7\xf4\"2i\x83j\xf\x66\xe6N\xfd \x8c\xa9\x1d\xb9k\x82\xfa\x10#m\x12\x1fK\xfe\x35NM\xe4\b\xd4\x9c\x3\x98\xe3!\"\x8ag\xe7\xc8\xddm\xbd\xde\xf3\xd0)\x1bK}Df\xc1k\x94\xe3\xf\xe4\x6TnP\xa9\x65\xfa\xdbO\xe4\xdaHfxt\x82\xac\xe7I\xf7\x1c\x19\x97\x93\x18\xf6\x91\xeb\x8a\xf5]Jz\xf_\x97\t\xa5\xdb\xd0\xd7,\x96.\xb2!\x1b\xa3\x37\xfd\x34&\n\xed<\xf9S\x1b\xb2\x31\xfa\x88Z*P\xdc\xfd\x92\xf0\xd4Lb\xa7\xb9S\xcc\xcf\x39\xe3\x8cG\x82l\xdds\x1b\x12\x81G\x1\b\xb1~\xe3\x9b\xfc\xc1\x87\x9e\\D\xea\x9aH\xdc\xa9%\xf2>\x80\xde\0\xac\x95\xe8\x10\xcc\x5\t\x95\xb7\xca\xc8\x46[\xddO\xc7\xc8\x13\xa2\x42\xfdn\x92\x88\xe5\xd3U\xe0\x1bV[\x9d\xc8\xd7\xa9X\x9c\xda\x1f\xe7m\xf5@\xd8\xb6\x9c\x94Kc\xd9[\xd8\xb9\x95>\x9a\xd8\x91XnN\x6\x12\xea-3\x1e\xb6\x64\x94\xe8j\x15\x94\x93\xdd\xca\x46\xde\x46P_3\xfe\xfb\xa1\xc9,<\x84;\x95\xa4H:Mn\x11\x95}P\xc2O$\xfa\x8b\xe4\xb9\xd5\x1a\xc9\x13\x1e\xb2$\a\xe0\xb9\x18\x15G\xf9\xd6\x44zC\xb0<dB\xa7\xb6\x13\xd7/v\xa4\xc8>U*4\xab\x37\x99<\xc1\x83\x1d\xe9\x65\xb5\xc5\xc9!og\x96\x9aZ\x88/ r\xab#!O\x89&\xb1\xa9\xcat\xe2\x86\x87\xfaT\xdfz\xe3~\xe7\xc9-\xdf\xa7\xaeJ\xee\xf7\xb3~\xe4\xc3\xaeJ\xe\xb6\x63\xc4\xd0\x87\x6\x95\xb5\x42\xd7\x42[H\x8avYU\x85\xc7\x99\xe8\x66\xa5}H\xb5\xb0\xfd\xc9#\x13\x1dw\xef\x96\x8c\xa5\xd1/c\xd7\xf4\x9c\xfb\x8d~\x1a\xb9\xd2-\x18\xf5\bA\xa6>\xa4T{\xad\xd1&kc\xfb\x8f\x8d\xa1\xdd\xb9\x82\xbe\x37T(W\xf0\xd2\x13\tyY\xb1\xb1`ZD\xb7\xa6SP'\xa1\xf2g\xde\b3\x91\"\xdb\xd5N\v$\f\xb8QS\x86\"\xa5\x34&G \xa1\x66\x32;}\vc\xc2\x34\xe5\xdc\x66Np\x8f\x46\v1\x9a\xc4'\xa7\x9aS\x13\x6\xfc`\xd2\xf3\x93\xd4\xf1T\x93g\x98i\x6\x9b\x83\x9b#\xe6%J\x99\xe5\xc4\xb8\xac\xf6\xed\x98\"\xc9\xf8za\xc7\\\xffu\\\xc9\xbc\xbd\x3\x80M\xdfk\x14\xf5\x10\xdf\0\0\0\0IEND\xae\x42`\x82\x11\x1\x10T\x5\x65n_USQt Website\x11\x1\x1dT\x5ja_JPQt\xe3\x81\xae\xe3\x83\x9b\xe3\x83\xbc\xe3\x83\xa0\xe3\x83\x9a\xe3\x83\xbc\xe3\x82\xb8\x11\x1\x10T\x5nb_NOQt WebsideQ\x1\xeU\x3qt.nokia.com/\xfe\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0)" diff --git a/tests/auto/qbluetoothaddress/qbluetoothaddress.pro b/tests/auto/qbluetoothaddress/qbluetoothaddress.pro new file mode 100644 index 00000000..8a51143d --- /dev/null +++ b/tests/auto/qbluetoothaddress/qbluetoothaddress.pro @@ -0,0 +1,6 @@ +SOURCES += tst_qbluetoothaddress.cpp +TARGET = tst_qbluetoothaddress +CONFIG += testcase + +QT = core bluetooth testlib + diff --git a/tests/auto/qbluetoothaddress/tst_qbluetoothaddress.cpp b/tests/auto/qbluetoothaddress/tst_qbluetoothaddress.cpp new file mode 100644 index 00000000..80755420 --- /dev/null +++ b/tests/auto/qbluetoothaddress/tst_qbluetoothaddress.cpp @@ -0,0 +1,249 @@ +/**************************************************************************** +** +** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the Qt Mobility Components. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include <QtTest/QtTest> + +#include <QDebug> + +#include <qbluetoothaddress.h> + +class tst_QBluetoothAddress : public QObject +{ + Q_OBJECT + +public: + tst_QBluetoothAddress(); + ~tst_QBluetoothAddress(); + +private slots: + void tst_construction_data(); + void tst_construction(); + + void tst_assignment(); + + void tst_comparison_data(); + void tst_comparison(); + + void tst_lessThan_data(); + void tst_lessThan(); + + void tst_clear_data(); + void tst_clear(); +}; + +tst_QBluetoothAddress::tst_QBluetoothAddress() +{ +} + +tst_QBluetoothAddress::~tst_QBluetoothAddress() +{ +} + +void tst_QBluetoothAddress::tst_construction_data() +{ + QTest::addColumn<quint64>("addressUInt"); + QTest::addColumn<QString>("addressS12"); + QTest::addColumn<QString>("addressS17"); + + QTest::newRow("11:22:33:44:55:66") << Q_UINT64_C(0x112233445566) << QString("112233445566") << QString("11:22:33:44:55:66"); + QTest::newRow("AA:BB:CC:DD:EE:FF") << Q_UINT64_C(0xAABBCCDDEEFF) << QString("AABBCCDDEEFF") << QString("AA:BB:CC:DD:EE:FF"); + QTest::newRow("aa:bb:cc:dd:ee:ff") << Q_UINT64_C(0xAABBCCDDEEFF) << QString("aabbccddeeff") << QString("AA:BB:CC:DD:EE:FF"); + QTest::newRow("FF:FF:FF:FF:FF:FF") << Q_UINT64_C(0xFFFFFFFFFFFF) << QString("FFFFFFFFFFFF") << QString("FF:FF:FF:FF:FF:FF"); +} + +void tst_QBluetoothAddress::tst_construction() +{ + QFETCH(quint64, addressUInt); + QFETCH(QString, addressS12); + QFETCH(QString, addressS17); + + { + QBluetoothAddress address; + + QVERIFY(address.isNull()); + } + + { + /* construct from quint64 */ + QBluetoothAddress address(addressUInt); + + QVERIFY(!address.isNull()); + + QVERIFY(address.toUInt64() == addressUInt); + + QCOMPARE(address.toString(), addressS17); + } + + { + /* construct from string without colons */ + QBluetoothAddress address(addressS12); + + QVERIFY(!address.isNull()); + + QVERIFY(address.toUInt64() == addressUInt); + + QCOMPARE(address.toString(), addressS17); + } + + { + /* construct from string with colons */ + QBluetoothAddress address(addressS17); + + QVERIFY(!address.isNull()); + + QVERIFY(address.toUInt64() == addressUInt); + + QCOMPARE(address.toString(), addressS17); + } + + { + QString empty; + QBluetoothAddress address(empty); + + QVERIFY(address.isNull()); + } + + { + QBluetoothAddress address(addressUInt); + + QBluetoothAddress copy(address); + + QVERIFY(address.toUInt64() == copy.toUInt64()); + } +} + +void tst_QBluetoothAddress::tst_assignment() +{ + QBluetoothAddress address(Q_UINT64_C(0x112233445566)); + + { + QBluetoothAddress copy = address; + + QCOMPARE(address.toUInt64(), copy.toUInt64()); + } + + { + QBluetoothAddress copy1; + QBluetoothAddress copy2; + + QVERIFY(copy1.isNull()); + QVERIFY(copy2.isNull()); + + copy1 = copy2 = address; + + QVERIFY(!copy1.isNull()); + QVERIFY(!copy2.isNull()); + + QVERIFY(address.toUInt64() == copy1.toUInt64()); + QVERIFY(address.toUInt64() == copy2.toUInt64()); + + copy1.clear(); + QVERIFY(copy1.isNull()); + QVERIFY2(copy1 != address, "Verify that copy1 is a copy of address, the d_ptr are being copied"); + } +} + +void tst_QBluetoothAddress::tst_comparison_data() +{ + QTest::addColumn<QBluetoothAddress>("address1"); + QTest::addColumn<QBluetoothAddress>("address2"); + QTest::addColumn<bool>("result"); + + QTest::newRow("invalid == invalid") << QBluetoothAddress() << QBluetoothAddress() << true; + QTest::newRow("valid != invalid") << QBluetoothAddress(Q_UINT64_C(0x112233445566)) << QBluetoothAddress() << false; + QTest::newRow("valid == valid") << QBluetoothAddress(Q_UINT64_C(0x112233445566)) << QBluetoothAddress(Q_UINT64_C(0x112233445566)) << true; +} + +void tst_QBluetoothAddress::tst_comparison() +{ + QFETCH(QBluetoothAddress, address1); + QFETCH(QBluetoothAddress, address2); + QFETCH(bool, result); + + QCOMPARE(address1 == address2, result); + QCOMPARE(address2 == address1, result); + QCOMPARE(address1 != address2, !result); + QCOMPARE(address2 != address1, !result); +} + +void tst_QBluetoothAddress::tst_lessThan_data() +{ + QTest::addColumn<QBluetoothAddress>("address1"); + QTest::addColumn<QBluetoothAddress>("address2"); + QTest::addColumn<bool>("result"); + + QTest::newRow("invalid < invalid") << QBluetoothAddress() << QBluetoothAddress() << false; + QTest::newRow("invalid < valid") << QBluetoothAddress() << QBluetoothAddress(Q_UINT64_C(0x112233445566)) << true; + QTest::newRow("valid < invalid") << QBluetoothAddress(Q_UINT64_C(0x112233445566)) << QBluetoothAddress() << false; + QTest::newRow("valid < valid") << QBluetoothAddress(Q_UINT64_C(0x112233445566)) << QBluetoothAddress(Q_UINT64_C(0xAABBCCDDEEFF)) << true; + QTest::newRow("valid < valid") << QBluetoothAddress(Q_UINT64_C(0xAABBCCDDEEFF)) << QBluetoothAddress(Q_UINT64_C(0x112233445566)) << false; +} + +void tst_QBluetoothAddress::tst_lessThan() +{ + QFETCH(QBluetoothAddress, address1); + QFETCH(QBluetoothAddress, address2); + QFETCH(bool, result); + + QCOMPARE(address1 < address2, result); +} + +void tst_QBluetoothAddress::tst_clear_data() +{ + QTest::addColumn<QString>("addressS17"); + + QTest::newRow("FF:00:F3:25:00:00") << QString("FF:00:F3:25:00:00"); +} + +void tst_QBluetoothAddress::tst_clear() +{ + QFETCH(QString, addressS17); + + QBluetoothAddress address(addressS17); + QVERIFY(!address.isNull()); + address.clear(); + QVERIFY(address.toString() == QString("00:00:00:00:00:00")); +} + +QTEST_MAIN(tst_QBluetoothAddress) + +#include "tst_qbluetoothaddress.moc" + diff --git a/tests/auto/qbluetoothdevicediscoveryagent/qbluetoothdevicediscoveryagent.pro b/tests/auto/qbluetoothdevicediscoveryagent/qbluetoothdevicediscoveryagent.pro new file mode 100644 index 00000000..7802f970 --- /dev/null +++ b/tests/auto/qbluetoothdevicediscoveryagent/qbluetoothdevicediscoveryagent.pro @@ -0,0 +1,7 @@ +SOURCES += tst_qbluetoothdevicediscoveryagent.cpp +TARGET=tst_qbluetoothdevicediscoveryagent +CONFIG += testcase + +QT = core bluetooth testlib + +symbian: TARGET.CAPABILITY = ReadDeviceData LocalServices WriteDeviceData diff --git a/tests/auto/qbluetoothdevicediscoveryagent/tst_qbluetoothdevicediscoveryagent.cpp b/tests/auto/qbluetoothdevicediscoveryagent/tst_qbluetoothdevicediscoveryagent.cpp new file mode 100644 index 00000000..41741bf9 --- /dev/null +++ b/tests/auto/qbluetoothdevicediscoveryagent/tst_qbluetoothdevicediscoveryagent.cpp @@ -0,0 +1,336 @@ +/**************************************************************************** +** +** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the Qt Mobility Components. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include <QtTest/QtTest> + +#include <QDebug> +#include <QVariant> + +#include <qbluetoothaddress.h> +#include <qbluetoothdevicediscoveryagent.h> +#include <qbluetoothlocaldevice.h> + +Q_DECLARE_METATYPE(QBluetoothDeviceInfo) +Q_DECLARE_METATYPE(QBluetoothDeviceDiscoveryAgent::InquiryType) + +// Maximum time to for bluetooth device scan +const int MaxScanTime = 5 * 60 * 1000; // 5 minutes in ms +const int MaxWaitTime = 5 * 1000; // 5 seconds in ms + +class tst_QBluetoothDeviceDiscoveryAgent : public QObject +{ + Q_OBJECT + +public: + tst_QBluetoothDeviceDiscoveryAgent(); + ~tst_QBluetoothDeviceDiscoveryAgent(); + +public slots: + void deviceDiscoveryDebug(const QBluetoothDeviceInfo &info); + void finished(); + +private slots: + void initTestCase(); + + void tst_properties(); + + void tst_startStopDeviceDiscoveries(); + + void tst_deviceDiscovery_data(); + void tst_deviceDiscovery(); +}; + +tst_QBluetoothDeviceDiscoveryAgent::tst_QBluetoothDeviceDiscoveryAgent() +{ + qRegisterMetaType<QBluetoothDeviceDiscoveryAgent::Error>("QBluetoothDeviceDiscoveryAgent::Error"); +} + +tst_QBluetoothDeviceDiscoveryAgent::~tst_QBluetoothDeviceDiscoveryAgent() +{ +} + +void tst_QBluetoothDeviceDiscoveryAgent::initTestCase() +{ + qRegisterMetaType<QBluetoothDeviceInfo>("QBluetoothDeviceInfo"); + qRegisterMetaType<QBluetoothDeviceDiscoveryAgent::InquiryType>("QBluetoothDeviceDiscoveryAgent::InquiryType"); + + // turn on BT in case it is not on + QBluetoothLocalDevice *device = new QBluetoothLocalDevice(); + if (device->hostMode() == QBluetoothLocalDevice::HostPoweredOff) { + QSignalSpy hostModeSpy(device, SIGNAL(hostModeStateChanged(QBluetoothLocalDevice::HostMode))); + QVERIFY(hostModeSpy.isEmpty()); + device->powerOn(); + int connectTime = 5000; // ms + while (hostModeSpy.count() < 1 && connectTime > 0) { + QTest::qWait(500); + connectTime -= 500; + } + QVERIFY(hostModeSpy.count() > 0); + } + QBluetoothLocalDevice::HostMode hostMode= device->hostMode(); + QVERIFY(hostMode == QBluetoothLocalDevice::HostConnectable + || hostMode == QBluetoothLocalDevice::HostDiscoverable + || hostMode == QBluetoothLocalDevice::HostDiscoverableLimitedInquiry); + delete device; +} + +void tst_QBluetoothDeviceDiscoveryAgent::tst_properties() +{ + { + QBluetoothDeviceDiscoveryAgent discoveryAgent; + + QCOMPARE(discoveryAgent.inquiryType(), QBluetoothDeviceDiscoveryAgent::GeneralUnlimitedInquiry); + discoveryAgent.setInquiryType(QBluetoothDeviceDiscoveryAgent::LimitedInquiry); + QCOMPARE(discoveryAgent.inquiryType(), QBluetoothDeviceDiscoveryAgent::LimitedInquiry); + discoveryAgent.setInquiryType(QBluetoothDeviceDiscoveryAgent::GeneralUnlimitedInquiry); + QCOMPARE(discoveryAgent.inquiryType(), QBluetoothDeviceDiscoveryAgent::GeneralUnlimitedInquiry); + } +} + +void tst_QBluetoothDeviceDiscoveryAgent::deviceDiscoveryDebug(const QBluetoothDeviceInfo &info) +{ + qDebug() << "Discovered device:" << info.address().toString() << info.name(); +} + +void tst_QBluetoothDeviceDiscoveryAgent::tst_startStopDeviceDiscoveries() +{ + { + QBluetoothDeviceDiscoveryAgent::InquiryType inquiryType = QBluetoothDeviceDiscoveryAgent::GeneralUnlimitedInquiry; + QBluetoothDeviceDiscoveryAgent discoveryAgent; + + QVERIFY(discoveryAgent.error() == discoveryAgent.NoError); + QVERIFY(discoveryAgent.errorString().isEmpty()); + QVERIFY(!discoveryAgent.isActive()); + QVERIFY(discoveryAgent.discoveredDevices().isEmpty()); + + QSignalSpy finishedSpy(&discoveryAgent, SIGNAL(finished())); + QSignalSpy cancelSpy(&discoveryAgent, SIGNAL(canceled())); + QSignalSpy errorSpy(&discoveryAgent, SIGNAL(error(QBluetoothDeviceDiscoveryAgent::Error))); + QSignalSpy discoveredSpy(&discoveryAgent, SIGNAL(deviceDiscovered(const QBluetoothDeviceInfo&))); + + // Starting case 1: start-stop, expecting cancel signal + discoveryAgent.setInquiryType(inquiryType); + // we should have no errors at this point. + QVERIFY(errorSpy.isEmpty()); + + discoveryAgent.start(); + QVERIFY(discoveryAgent.isActive()); + QVERIFY(errorSpy.isEmpty()); + // cancel current request. + discoveryAgent.stop(); + + // Wait for up to MaxWaitTime for the cancel to finish + int waitTime = MaxWaitTime; + while (cancelSpy.count() == 0 && waitTime > 0) { + QTest::qWait(100); + waitTime-=100; + } + + // we should not be active anymore + QVERIFY(!discoveryAgent.isActive()); + QVERIFY(errorSpy.isEmpty()); + QVERIFY(cancelSpy.count() == 1); + cancelSpy.clear(); + // Starting case 2: start-start-stop, expecting cancel signal + discoveryAgent.start(); + // we should be active now + QVERIFY(discoveryAgent.isActive()); + QVERIFY(errorSpy.isEmpty()); + // start again. should this be error? + discoveryAgent.start(); + QVERIFY(discoveryAgent.isActive()); + QVERIFY(errorSpy.isEmpty()); + // stop + discoveryAgent.stop(); + + // Wait for up to MaxWaitTime for the cancel to finish + waitTime = MaxWaitTime; + while (cancelSpy.count() == 0 && waitTime > 0) { + QTest::qWait(100); + waitTime-=100; + } + + // we should not be active anymore + QVERIFY(!discoveryAgent.isActive()); + QVERIFY(errorSpy.isEmpty()); + QVERIFY(cancelSpy.count() == 1); + cancelSpy.clear(); + + // Starting case 3: stop + discoveryAgent.stop(); + QVERIFY(!discoveryAgent.isActive()); + QVERIFY(errorSpy.isEmpty()); + + // Expect finished signal with no error + QVERIFY(finishedSpy.count() == 0); + QVERIFY(discoveryAgent.error() == discoveryAgent.NoError); + QVERIFY(discoveryAgent.errorString().isEmpty()); + + + // Starting case 4: start-stop-start-stop, expecting only 1 cancel signal + discoveryAgent.start(); + QVERIFY(discoveryAgent.isActive()); + QVERIFY(errorSpy.isEmpty()); + // cancel current request. + discoveryAgent.stop(); + // start a new one + discoveryAgent.start(); + // we should be active now + QVERIFY(discoveryAgent.isActive()); + QVERIFY(errorSpy.isEmpty()); + // stop + discoveryAgent.stop(); + + // Wait for up to MaxWaitTime for the cancel to finish + waitTime = MaxWaitTime; + while (waitTime > 0) { + QTest::qWait(100); + waitTime-=100; + } + + // we should not be active anymore + QVERIFY(!discoveryAgent.isActive()); + QVERIFY(errorSpy.isEmpty()); + // should only have 1 cancel + QVERIFY(cancelSpy.count() == 1); + cancelSpy.clear(); + + // Starting case 5: start-stop-start: expecting finished signal & no cancel + discoveryAgent.start(); + QVERIFY(discoveryAgent.isActive()); + QVERIFY(errorSpy.isEmpty()); + // cancel current request. + discoveryAgent.stop(); + // start a new one + discoveryAgent.start(); + // we should be active now + QVERIFY(discoveryAgent.isActive()); + QVERIFY(errorSpy.isEmpty()); + + // Wait for up to MaxScanTime for the cancel to finish + waitTime = MaxScanTime; + while (finishedSpy.count() == 0 && waitTime > 0) { + QTest::qWait(1000); + waitTime-=1000; + } + + // we should not be active anymore + QVERIFY(!discoveryAgent.isActive()); + QVERIFY(errorSpy.isEmpty()); + // should only have 1 cancel + QVERIFY(finishedSpy.count() == 1); + QVERIFY(cancelSpy.isEmpty()); + } +} + +void tst_QBluetoothDeviceDiscoveryAgent::finished() +{ + qDebug() << "Finished called"; +} + +void tst_QBluetoothDeviceDiscoveryAgent::tst_deviceDiscovery_data() +{ + QTest::addColumn<QBluetoothDeviceDiscoveryAgent::InquiryType>("inquiryType"); + + QTest::newRow("general unlimited inquiry") << QBluetoothDeviceDiscoveryAgent::GeneralUnlimitedInquiry; + QTest::newRow("limited inquiry") << QBluetoothDeviceDiscoveryAgent::LimitedInquiry; +} + +void tst_QBluetoothDeviceDiscoveryAgent::tst_deviceDiscovery() +{ + { + QFETCH(QBluetoothDeviceDiscoveryAgent::InquiryType, inquiryType); + + QBluetoothDeviceDiscoveryAgent discoveryAgent; + QVERIFY(discoveryAgent.error() == discoveryAgent.NoError); + QVERIFY(discoveryAgent.errorString().isEmpty()); + QVERIFY(!discoveryAgent.isActive()); + + QVERIFY(discoveryAgent.discoveredDevices().isEmpty()); + + QSignalSpy finishedSpy(&discoveryAgent, SIGNAL(finished())); + QSignalSpy errorSpy(&discoveryAgent, SIGNAL(error(QBluetoothDeviceDiscoveryAgent::Error))); + QSignalSpy discoveredSpy(&discoveryAgent, SIGNAL(deviceDiscovered(const QBluetoothDeviceInfo&))); +// connect(&discoveryAgent, SIGNAL(finished()), this, SLOT(finished())); +// connect(&discoveryAgent, SIGNAL(deviceDiscovered(const QBluetoothDeviceInfo&)), +// this, SLOT(deviceDiscoveryDebug(const QBluetoothDeviceInfo&))); + + discoveryAgent.setInquiryType(inquiryType); + discoveryAgent.start(); + + QVERIFY(discoveryAgent.isActive()); + + // Wait for up to MaxScanTime for the scan to finish + int scanTime = MaxScanTime; + while (finishedSpy.count() == 0 && scanTime > 0) { + QTest::qWait(15000); + scanTime -= 15000; + } + qDebug() << scanTime << MaxScanTime; + // verify that we are finished + QVERIFY(!discoveryAgent.isActive()); + // stop + discoveryAgent.stop(); + QVERIFY(!discoveryAgent.isActive()); + qDebug() << "Scan time left:" << scanTime; + // Expect finished signal with no error + QVERIFY(finishedSpy.count() == 1); + QVERIFY(errorSpy.isEmpty()); + QVERIFY(discoveryAgent.error() == discoveryAgent.NoError); + QVERIFY(discoveryAgent.errorString().isEmpty()); + + // verify that the list is as big as the signals received. + QVERIFY(discoveredSpy.count() == discoveryAgent.discoveredDevices().length()); + // verify that there really was some devices in the array + QVERIFY(discoveredSpy.count() > 0); + + // All returned QBluetoothDeviceInfo should be valid. + while (!discoveredSpy.isEmpty()) { + const QBluetoothDeviceInfo info = + qvariant_cast<QBluetoothDeviceInfo>(discoveredSpy.takeFirst().at(0)); + QVERIFY(info.isValid()); + } + } +} + +QTEST_MAIN(tst_QBluetoothDeviceDiscoveryAgent) + +#include "tst_qbluetoothdevicediscoveryagent.moc" diff --git a/tests/auto/qbluetoothdeviceinfo/qbluetoothdeviceinfo.pro b/tests/auto/qbluetoothdeviceinfo/qbluetoothdeviceinfo.pro new file mode 100644 index 00000000..7c71ef7e --- /dev/null +++ b/tests/auto/qbluetoothdeviceinfo/qbluetoothdeviceinfo.pro @@ -0,0 +1,7 @@ +SOURCES += tst_qbluetoothdeviceinfo.cpp +TARGET=tst_qbluetoothdeviceinfo +CONFIG += testcase + +QT = core bluetooth testlib + +symbian: TARGET.CAPABILITY = ReadDeviceData LocalServices WriteDeviceData diff --git a/tests/auto/qbluetoothdeviceinfo/tst_qbluetoothdeviceinfo.cpp b/tests/auto/qbluetoothdeviceinfo/tst_qbluetoothdeviceinfo.cpp new file mode 100644 index 00000000..b5d346a8 --- /dev/null +++ b/tests/auto/qbluetoothdeviceinfo/tst_qbluetoothdeviceinfo.cpp @@ -0,0 +1,388 @@ +/**************************************************************************** +** +** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the Qt Mobility Components. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include <QtTest/QtTest> + +#include <QDebug> + +#include <qbluetoothaddress.h> +#include <qbluetoothdeviceinfo.h> +#include <qbluetoothlocaldevice.h> +#include <qbluetoothuuid.h> + +Q_DECLARE_METATYPE(QBluetoothDeviceInfo::ServiceClasses) +Q_DECLARE_METATYPE(QBluetoothDeviceInfo::MajorDeviceClass) + +class tst_QBluetoothDeviceInfo : public QObject +{ + Q_OBJECT + +public: + tst_QBluetoothDeviceInfo(); + ~tst_QBluetoothDeviceInfo(); + +private slots: + void initTestCase(); + + void tst_construction_data(); + void tst_construction(); + + void tst_assignment_data(); + void tst_assignment(); + + void tst_serviceUuids(); + + void tst_cached(); + + void tst_manufacturerSpecificData(); +}; + +tst_QBluetoothDeviceInfo::tst_QBluetoothDeviceInfo() +{ +} + +tst_QBluetoothDeviceInfo::~tst_QBluetoothDeviceInfo() +{ +} + +void tst_QBluetoothDeviceInfo::initTestCase() +{ + qRegisterMetaType<QBluetoothDeviceInfo::ServiceClasses>("QBluetoothDeviceInfo::ServiceClasses"); + qRegisterMetaType<QBluetoothDeviceInfo::MajorDeviceClass>("QBluetoothDeviceInfo::MajorDeviceClass"); + // start Bluetooth if not started + QBluetoothLocalDevice *device = new QBluetoothLocalDevice(); + device->powerOn(); + delete device; +} + +void tst_QBluetoothDeviceInfo::tst_construction_data() +{ + QTest::addColumn<QBluetoothAddress>("address"); + QTest::addColumn<QString>("name"); + QTest::addColumn<quint32>("classOfDevice"); + QTest::addColumn<QBluetoothDeviceInfo::ServiceClasses>("serviceClasses"); + QTest::addColumn<QBluetoothDeviceInfo::MajorDeviceClass>("majorDeviceClass"); + QTest::addColumn<quint8>("minorDeviceClass"); + + // bits 12-8 Major + // bits 7-2 Minor + // bits 1-0 0 + + QTest::newRow("0x000000 COD") << QBluetoothAddress("000000000000") << "My Bluetooth Device" + << quint32(0x000000) + << QBluetoothDeviceInfo::ServiceClasses(QBluetoothDeviceInfo::NoService) + << QBluetoothDeviceInfo::MiscellaneousDevice + << quint8(QBluetoothDeviceInfo::UncategorizedMiscellaneous); + QTest::newRow("0x000100 COD") << QBluetoothAddress("000000000000") << "My Bluetooth Device" + << quint32(0x000100) + << QBluetoothDeviceInfo::ServiceClasses(QBluetoothDeviceInfo::NoService) + << QBluetoothDeviceInfo::ComputerDevice + << quint8(QBluetoothDeviceInfo::UncategorizedComputer); + QTest::newRow("0x000104 COD") << QBluetoothAddress("000000000000") << "My Bluetooth Device" + << quint32(0x000104) + << QBluetoothDeviceInfo::ServiceClasses(QBluetoothDeviceInfo::NoService) + << QBluetoothDeviceInfo::ComputerDevice + << quint8(QBluetoothDeviceInfo::DesktopComputer); + QTest::newRow("0x000118 COD") << QBluetoothAddress("000000000000") << "My Bluetooth Device" + << quint32(0x000118) + << QBluetoothDeviceInfo::ServiceClasses(QBluetoothDeviceInfo::NoService) + << QBluetoothDeviceInfo::ComputerDevice + << quint8(QBluetoothDeviceInfo::WearableComputer); + QTest::newRow("0x000200 COD") << QBluetoothAddress("000000000000") << "My Bluetooth Device" << quint32(0x000200) + << QBluetoothDeviceInfo::ServiceClasses(QBluetoothDeviceInfo::NoService) + << QBluetoothDeviceInfo::PhoneDevice + << quint8(QBluetoothDeviceInfo::UncategorizedPhone); + QTest::newRow("0x000204 COD") << QBluetoothAddress("000000000000") << "My Bluetooth Device" + << quint32(0x000204) + << QBluetoothDeviceInfo::ServiceClasses(QBluetoothDeviceInfo::NoService) + << QBluetoothDeviceInfo::PhoneDevice + << quint8(QBluetoothDeviceInfo::CellularPhone); + QTest::newRow("0x000214 COD") << QBluetoothAddress("000000000000") << "My Bluetooth Device" << quint32(0x000214) + << QBluetoothDeviceInfo::ServiceClasses(QBluetoothDeviceInfo::NoService) + << QBluetoothDeviceInfo::PhoneDevice + << quint8(QBluetoothDeviceInfo::CommonIsdnAccessPhone); + QTest::newRow("0x000300 COD") << QBluetoothAddress("000000000000") << "My Bluetooth Device" + << quint32(0x000300) + << QBluetoothDeviceInfo::ServiceClasses(QBluetoothDeviceInfo::NoService) + << QBluetoothDeviceInfo::LANAccessDevice + << quint8(QBluetoothDeviceInfo::NetworkFullService); + QTest::newRow("0x000320 COD") << QBluetoothAddress("000000000000") << "My Bluetooth Device" + << quint32(0x000320) + << QBluetoothDeviceInfo::ServiceClasses(QBluetoothDeviceInfo::NoService) + << QBluetoothDeviceInfo::LANAccessDevice + << quint8(QBluetoothDeviceInfo::NetworkLoadFactorOne); + QTest::newRow("0x0003E0 COD") << QBluetoothAddress("000000000000") << "My Bluetooth Device" + << quint32(0x0003E0) + << QBluetoothDeviceInfo::ServiceClasses(QBluetoothDeviceInfo::NoService) + << QBluetoothDeviceInfo::LANAccessDevice + << quint8(QBluetoothDeviceInfo::NetworkNoService); + QTest::newRow("0x000400 COD") << QBluetoothAddress("000000000000") << "My Bluetooth Device" + << quint32(0x000400) + << QBluetoothDeviceInfo::ServiceClasses(QBluetoothDeviceInfo::NoService) + << QBluetoothDeviceInfo::AudioVideoDevice + << quint8(QBluetoothDeviceInfo::UncategorizedAudioVideoDevice); + QTest::newRow("0x00044C COD") << QBluetoothAddress("000000000000") << "My Bluetooth Device" + << quint32(0x00044C) + << QBluetoothDeviceInfo::ServiceClasses(QBluetoothDeviceInfo::NoService) + << QBluetoothDeviceInfo::AudioVideoDevice + << quint8(QBluetoothDeviceInfo::GamingDevice); + QTest::newRow("0x000500 COD") << QBluetoothAddress("000000000000") << "My Bluetooth Device" + << quint32(0x000500) + << QBluetoothDeviceInfo::ServiceClasses(QBluetoothDeviceInfo::NoService) + << QBluetoothDeviceInfo::PeripheralDevice + << quint8(QBluetoothDeviceInfo::UncategorizedPeripheral); + QTest::newRow("0x0005D8 COD") << QBluetoothAddress("000000000000") << "My Bluetooth Device" + << quint32(0x0005D8) + << QBluetoothDeviceInfo::ServiceClasses(QBluetoothDeviceInfo::NoService) + << QBluetoothDeviceInfo::PeripheralDevice + << quint8(QBluetoothDeviceInfo::KeyboardWithPointingDevicePeripheral | QBluetoothDeviceInfo::CardReaderPeripheral); + QTest::newRow("0x000600 COD") << QBluetoothAddress("000000000000") << "My Bluetooth Device" + << quint32(0x000600) + << QBluetoothDeviceInfo::ServiceClasses(QBluetoothDeviceInfo::NoService) + << QBluetoothDeviceInfo::ImagingDevice + << quint8(QBluetoothDeviceInfo::UncategorizedImagingDevice); + QTest::newRow("0x000680 COD") << QBluetoothAddress("000000000000") << "My Bluetooth Device" + << quint32(0x000680) + << QBluetoothDeviceInfo::ServiceClasses(QBluetoothDeviceInfo::NoService) + << QBluetoothDeviceInfo::ImagingDevice + << quint8(QBluetoothDeviceInfo::ImagePrinter); + QTest::newRow("0x000700 COD") << QBluetoothAddress("000000000000") << "My Bluetooth Device" + << quint32(0x000700) + << QBluetoothDeviceInfo::ServiceClasses(QBluetoothDeviceInfo::NoService) + << QBluetoothDeviceInfo::WearableDevice + << quint8(QBluetoothDeviceInfo::UncategorizedWearableDevice); + QTest::newRow("0x000714 COD") << QBluetoothAddress("000000000000") << "My Bluetooth Device" + << quint32(0x000714) + << QBluetoothDeviceInfo::ServiceClasses(QBluetoothDeviceInfo::NoService) + << QBluetoothDeviceInfo::WearableDevice + << quint8(QBluetoothDeviceInfo::WearableGlasses); + QTest::newRow("0x000800 COD") << QBluetoothAddress("000000000000") << "My Bluetooth Device" + << quint32(0x000800) + << QBluetoothDeviceInfo::ServiceClasses(QBluetoothDeviceInfo::NoService) + << QBluetoothDeviceInfo::ToyDevice + << quint8(QBluetoothDeviceInfo::UncategorizedToy); + QTest::newRow("0x000814 COD") << QBluetoothAddress("000000000000") << "My Bluetooth Device" + << quint32(0x000814) + << QBluetoothDeviceInfo::ServiceClasses(QBluetoothDeviceInfo::NoService) + << QBluetoothDeviceInfo::ToyDevice + << quint8(QBluetoothDeviceInfo::ToyGame); + QTest::newRow("0x001f00 COD") << QBluetoothAddress("000000000000") << "My Bluetooth Device" + << quint32(0x001f00) + << QBluetoothDeviceInfo::ServiceClasses(QBluetoothDeviceInfo::NoService) + << QBluetoothDeviceInfo::UncategorizedDevice + << quint8(0); + QTest::newRow("0x002000 COD") << QBluetoothAddress("000000000000") << "My Bluetooth Device" + << quint32(0x002000) + << QBluetoothDeviceInfo::ServiceClasses(QBluetoothDeviceInfo::PositioningService) + << QBluetoothDeviceInfo::MiscellaneousDevice + << quint8(QBluetoothDeviceInfo::UncategorizedMiscellaneous); + QTest::newRow("0x100000 COD") << QBluetoothAddress("000000000000") << "My Bluetooth Device" + << quint32(0x100000) + << QBluetoothDeviceInfo::ServiceClasses(QBluetoothDeviceInfo::InformationService) + << QBluetoothDeviceInfo::MiscellaneousDevice + << quint8(QBluetoothDeviceInfo::UncategorizedMiscellaneous); + QTest::newRow("0xFFE000 COD") << QBluetoothAddress("000000000000") << "My Bluetooth Device" + << quint32(0xFFE000) + << QBluetoothDeviceInfo::ServiceClasses(QBluetoothDeviceInfo::AllServices) + << QBluetoothDeviceInfo::MiscellaneousDevice + << quint8(QBluetoothDeviceInfo::UncategorizedMiscellaneous); +} + +void tst_QBluetoothDeviceInfo::tst_construction() +{ + { + QBluetoothDeviceInfo deviceInfo; + + QVERIFY(!deviceInfo.isValid()); + } + + { + QFETCH(QBluetoothAddress, address); + QFETCH(QString, name); + QFETCH(quint32, classOfDevice); + QFETCH(QBluetoothDeviceInfo::ServiceClasses, serviceClasses); + QFETCH(QBluetoothDeviceInfo::MajorDeviceClass, majorDeviceClass); + QFETCH(quint8, minorDeviceClass); + + QBluetoothDeviceInfo deviceInfo(address, name, classOfDevice); + + QVERIFY(deviceInfo.isValid()); + + QCOMPARE(deviceInfo.address(), address); + QCOMPARE(deviceInfo.name(), name); + QCOMPARE(deviceInfo.serviceClasses(), serviceClasses); + QCOMPARE(deviceInfo.majorDeviceClass(), majorDeviceClass); + QCOMPARE(deviceInfo.minorDeviceClass(), minorDeviceClass); + + QBluetoothDeviceInfo copyInfo(deviceInfo); + + QVERIFY(copyInfo.isValid()); + + QCOMPARE(copyInfo.address(), address); + QCOMPARE(copyInfo.name(), name); + QCOMPARE(copyInfo.serviceClasses(), serviceClasses); + QCOMPARE(copyInfo.majorDeviceClass(), majorDeviceClass); + QCOMPARE(copyInfo.minorDeviceClass(), minorDeviceClass); + } +} + +void tst_QBluetoothDeviceInfo::tst_assignment_data() +{ + tst_construction_data(); +} + +void tst_QBluetoothDeviceInfo::tst_assignment() +{ + QFETCH(QBluetoothAddress, address); + QFETCH(QString, name); + QFETCH(quint32, classOfDevice); + QFETCH(QBluetoothDeviceInfo::ServiceClasses, serviceClasses); + QFETCH(QBluetoothDeviceInfo::MajorDeviceClass, majorDeviceClass); + QFETCH(quint8, minorDeviceClass); + + QBluetoothDeviceInfo deviceInfo(address, name, classOfDevice); + + QVERIFY(deviceInfo.isValid()); + + { + QBluetoothDeviceInfo copyInfo = deviceInfo; + + QVERIFY(copyInfo.isValid()); + + QCOMPARE(copyInfo.address(), address); + QCOMPARE(copyInfo.name(), name); + QCOMPARE(copyInfo.serviceClasses(), serviceClasses); + QCOMPARE(copyInfo.majorDeviceClass(), majorDeviceClass); + QCOMPARE(copyInfo.minorDeviceClass(), minorDeviceClass); + } + + { + QBluetoothDeviceInfo copyInfo; + + QVERIFY(!copyInfo.isValid()); + + copyInfo = deviceInfo; + + QVERIFY(copyInfo.isValid()); + + QCOMPARE(copyInfo.address(), address); + QCOMPARE(copyInfo.name(), name); + QCOMPARE(copyInfo.serviceClasses(), serviceClasses); + QCOMPARE(copyInfo.majorDeviceClass(), majorDeviceClass); + QCOMPARE(copyInfo.minorDeviceClass(), minorDeviceClass); + } + + { + QBluetoothDeviceInfo copyInfo1; + QBluetoothDeviceInfo copyInfo2; + + QVERIFY(!copyInfo1.isValid()); + QVERIFY(!copyInfo2.isValid()); + + copyInfo1 = copyInfo2 = deviceInfo; + + QVERIFY(copyInfo1.isValid()); + QVERIFY(copyInfo2.isValid()); + QVERIFY(!(QBluetoothDeviceInfo() == copyInfo1)); + + QCOMPARE(copyInfo1.address(), address); + QCOMPARE(copyInfo2.address(), address); + QCOMPARE(copyInfo1.name(), name); + QCOMPARE(copyInfo2.name(), name); + QCOMPARE(copyInfo1.serviceClasses(), serviceClasses); + QCOMPARE(copyInfo2.serviceClasses(), serviceClasses); + QCOMPARE(copyInfo1.majorDeviceClass(), majorDeviceClass); + QCOMPARE(copyInfo2.majorDeviceClass(), majorDeviceClass); + QCOMPARE(copyInfo1.minorDeviceClass(), minorDeviceClass); + QCOMPARE(copyInfo2.minorDeviceClass(), minorDeviceClass); + } + + { + QBluetoothDeviceInfo testDeviceInfo; + QVERIFY(testDeviceInfo == QBluetoothDeviceInfo()); + } +} + +void tst_QBluetoothDeviceInfo::tst_serviceUuids() +{ + QBluetoothDeviceInfo deviceInfo; + QBluetoothDeviceInfo copyInfo = deviceInfo; + + QList<QBluetoothUuid> servicesList; + servicesList.append(QBluetoothUuid::L2cap); + servicesList.append(QBluetoothUuid::Rfcomm); + QVERIFY(servicesList.count() > 0); + + deviceInfo.setServiceUuids(servicesList, QBluetoothDeviceInfo::DataComplete); + QVERIFY(deviceInfo.serviceUuids().count() > 0); + QVERIFY(!(deviceInfo == copyInfo)); + + QVERIFY(deviceInfo.serviceUuidsCompleteness() == QBluetoothDeviceInfo::DataComplete); +} + +void tst_QBluetoothDeviceInfo::tst_cached() +{ + QBluetoothDeviceInfo deviceInfo(QBluetoothAddress("AABBCCDDEEFF"), + QString("My Bluetooth Device"), quint32(0x002000)); + QBluetoothDeviceInfo copyInfo = deviceInfo; + + QVERIFY(!deviceInfo.isCached()); + deviceInfo.setCached(true); + QVERIFY(deviceInfo.isCached()); + QVERIFY(!(deviceInfo == copyInfo)); + + deviceInfo.setCached(false); + QVERIFY(!(deviceInfo.isCached())); +} + +void tst_QBluetoothDeviceInfo::tst_manufacturerSpecificData() +{ + QBluetoothDeviceInfo deviceInfo; + QByteArray data; + bool available; + data = deviceInfo.manufacturerSpecificData(&available); + // Current API implementation returns only empty QByteArray() + QCOMPARE(data, QByteArray()); +} + +QTEST_MAIN(tst_QBluetoothDeviceInfo) + +#include "tst_qbluetoothdeviceinfo.moc" diff --git a/tests/auto/qbluetoothlocaldevice/qbluetoothlocaldevice.pro b/tests/auto/qbluetoothlocaldevice/qbluetoothlocaldevice.pro new file mode 100644 index 00000000..b9e8e367 --- /dev/null +++ b/tests/auto/qbluetoothlocaldevice/qbluetoothlocaldevice.pro @@ -0,0 +1,7 @@ +SOURCES += tst_qbluetoothlocaldevice.cpp +TARGET=tst_qbluetoothlocaldevice +CONFIG += testcase + +QT = core bluetooth testlib + +symbian: TARGET.CAPABILITY = ReadDeviceData LocalServices WriteDeviceData NetworkControl diff --git a/tests/auto/qbluetoothlocaldevice/tst_qbluetoothlocaldevice.cpp b/tests/auto/qbluetoothlocaldevice/tst_qbluetoothlocaldevice.cpp new file mode 100644 index 00000000..6f2404ef --- /dev/null +++ b/tests/auto/qbluetoothlocaldevice/tst_qbluetoothlocaldevice.cpp @@ -0,0 +1,284 @@ +/**************************************************************************** +** +** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the Qt Mobility Components. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include <QtTest/QtTest> + +#include <QDebug> +#include <QVariant> + +#include <qbluetoothaddress.h> +#include <qbluetoothlocaldevice.h> + +#define WAIT_FOR_CONDITION(a,e) \ + for (int _i = 0; _i < 5000; _i += 1) { \ + if ((a) == (e)) break; \ + QTest::qWait(100);} + +class tst_QBluetoothLocalDevice : public QObject +{ + Q_OBJECT + +public: + tst_QBluetoothLocalDevice(); + ~tst_QBluetoothLocalDevice(); + +private slots: + void tst_powerOn(); + void tst_powerOff(); + void tst_hostModes(); + void tst_hostModes_data(); + void tst_address(); + void tst_name(); + void tst_isValid(); + void tst_allDevices(); + void tst_construction(); + void tst_pairingStatus_data(); + void tst_pairingStatus(); + void tst_pairDevice_data(); + void tst_pairDevice(); +}; + +tst_QBluetoothLocalDevice::tst_QBluetoothLocalDevice() +{ + // start with host powered off + QBluetoothLocalDevice *device = new QBluetoothLocalDevice(); + device->setHostMode(QBluetoothLocalDevice::HostPoweredOff); + delete device; + // wait for the device to switch bluetooth mode. + QTest::qWait(1000); + +} + +tst_QBluetoothLocalDevice::~tst_QBluetoothLocalDevice() +{ +} + +void tst_QBluetoothLocalDevice::tst_hostModes_data() +{ + QTest::addColumn<QBluetoothLocalDevice::HostMode>("hostModeExpected"); + + QTest::newRow("HostDiscoverable") << QBluetoothLocalDevice::HostDiscoverable; + QTest::newRow("HostPoweredOff") << QBluetoothLocalDevice::HostPoweredOff; + QTest::newRow("HostConnectable") << QBluetoothLocalDevice::HostConnectable; + QTest::newRow("HostPoweredOff") << QBluetoothLocalDevice::HostPoweredOff; + QTest::newRow("HostDiscoverable") << QBluetoothLocalDevice::HostDiscoverable; + +} +void tst_QBluetoothLocalDevice::tst_pairDevice_data() +{ + QTest::addColumn<QBluetoothAddress>("deviceAddress"); + QTest::addColumn<QBluetoothLocalDevice::Pairing>("pairingExpected"); + + QTest::newRow("UnPaired Device: DUMMY") << QBluetoothAddress("11:00:00:00:00:00") + << QBluetoothLocalDevice::Unpaired; +#ifdef Q_OS_SYMBIAN + + QTest::newRow("unPAIRED Device: J X6") << QBluetoothAddress("d8:75:33:6a:82:85") + << QBluetoothLocalDevice::Unpaired; + QTest::newRow("AuthPAIRED Device: J X6") << QBluetoothAddress("d8:75:33:6a:82:85") + << QBluetoothLocalDevice::AuthorizedPaired; + QTest::newRow("PAIRED Device: J C-7-1") << QBluetoothAddress("6c:9b:02:0c:91:ca") + << QBluetoothLocalDevice::Paired; + +#endif // Q_OS_SYMBIAN +} + +void tst_QBluetoothLocalDevice::tst_pairingStatus_data() +{ + QTest::addColumn<QBluetoothAddress>("deviceAddress"); + QTest::addColumn<QBluetoothLocalDevice::Pairing>("pairingExpected"); + + QTest::newRow("UnPaired Device: DUMMY") << QBluetoothAddress("11:00:00:00:00:00") + << QBluetoothLocalDevice::Unpaired; +#ifdef Q_OS_SYMBIAN + QTest::newRow("PAIRED Device: J X6") << QBluetoothAddress("d8:75:33:6a:82:85") + << QBluetoothLocalDevice::Paired; + QTest::newRow("AuthPAIRED Device: J C-7-1") << QBluetoothAddress("6c:9b:02:0c:91:ca") + << QBluetoothLocalDevice::AuthorizedPaired; +#endif // Q_OS_SYMBIAN +} + +void tst_QBluetoothLocalDevice::tst_powerOn() +{ + { + QBluetoothLocalDevice localDevice; + + QSignalSpy hostModeSpy(&localDevice, SIGNAL(hostModeStateChanged(QBluetoothLocalDevice::HostMode))); + // there should be no changes yet + QVERIFY(hostModeSpy.isEmpty()); + + localDevice.powerOn(); + // async, wait for it + WAIT_FOR_CONDITION(hostModeSpy.count(),1); + QVERIFY(hostModeSpy.count() > 0); + QBluetoothLocalDevice::HostMode hostMode= localDevice.hostMode(); + // we should not be powered off + QVERIFY(hostMode == QBluetoothLocalDevice::HostConnectable + || hostMode == QBluetoothLocalDevice::HostDiscoverable); + } + +} +void tst_QBluetoothLocalDevice::tst_powerOff() +{ + { + QBluetoothLocalDevice *device = new QBluetoothLocalDevice(); + device->powerOn(); + delete device; + // wait for the device to switch bluetooth mode. + QTest::qWait(1000); + } + QBluetoothLocalDevice localDevice; + QSignalSpy hostModeSpy(&localDevice, SIGNAL(hostModeStateChanged(QBluetoothLocalDevice::HostMode))); + // there should be no changes yet + QVERIFY(hostModeSpy.isEmpty()); + + localDevice.setHostMode(QBluetoothLocalDevice::HostPoweredOff); + // async, wait for it + WAIT_FOR_CONDITION(hostModeSpy.count(),1); + QVERIFY(hostModeSpy.count() > 0); + // we should not be powered off + QVERIFY(localDevice.hostMode() == QBluetoothLocalDevice::HostPoweredOff); + +} + +void tst_QBluetoothLocalDevice::tst_hostModes() +{ + QFETCH(QBluetoothLocalDevice::HostMode, hostModeExpected); + + QBluetoothLocalDevice localDevice; + QSignalSpy hostModeSpy(&localDevice, SIGNAL(hostModeStateChanged(QBluetoothLocalDevice::HostMode))); + // there should be no changes yet + QVERIFY(hostModeSpy.isEmpty()); + + QTest::qWait(1000); + + localDevice.setHostMode(hostModeExpected); + // wait for the device to switch bluetooth mode. + QTest::qWait(1000); + if (hostModeExpected != localDevice.hostMode()) { + WAIT_FOR_CONDITION(hostModeSpy.count(),1); + QVERIFY(hostModeSpy.count() > 0); + } + // test the actual signal values. + QList<QVariant> arguments = hostModeSpy.takeFirst(); + QBluetoothLocalDevice::HostMode hostMode = qvariant_cast<QBluetoothLocalDevice::HostMode>(arguments.at(0)); + QCOMPARE(hostModeExpected, hostMode); + // test actual + QCOMPARE(hostModeExpected, localDevice.hostMode()); +} + +void tst_QBluetoothLocalDevice::tst_address() +{ + QBluetoothLocalDevice localDevice; + QVERIFY(!localDevice.address().toString().isEmpty()); +} +void tst_QBluetoothLocalDevice::tst_name() +{ + QBluetoothLocalDevice localDevice; + QVERIFY(!localDevice.name().isEmpty()); +} +void tst_QBluetoothLocalDevice::tst_isValid() +{ + QBluetoothLocalDevice localDevice; + QVERIFY(localDevice.isValid()); +} +void tst_QBluetoothLocalDevice::tst_allDevices() +{ + // we should have one local bluetooth device + QVERIFY(QBluetoothLocalDevice::allDevices().count() == 1); +} +void tst_QBluetoothLocalDevice::tst_construction() +{ + QBluetoothLocalDevice localDevice; + QVERIFY(localDevice.isValid()); + + QBluetoothLocalDevice anotherDevice(QBluetoothAddress(000000000000)); + QVERIFY(anotherDevice.isValid()); + QVERIFY(anotherDevice.address().toUInt64() != 0); + +} + +void tst_QBluetoothLocalDevice::tst_pairDevice() +{ + QFETCH(QBluetoothAddress, deviceAddress); + QFETCH(QBluetoothLocalDevice::Pairing, pairingExpected); + + qDebug() << "tst_pairDevice(): address=" << deviceAddress.toString() << "pairingModeExpected=" + << static_cast<int>(pairingExpected); + + QBluetoothLocalDevice localDevice; + //powerOn if not already + localDevice.powerOn(); + + QSignalSpy pairingSpy(&localDevice, SIGNAL(pairingFinished(const QBluetoothAddress &,QBluetoothLocalDevice::Pairing)) ); + // there should be no signals yet + QVERIFY(pairingSpy.isEmpty()); + + localDevice.requestPairing(deviceAddress, pairingExpected); + // async, wait for it + WAIT_FOR_CONDITION(pairingSpy.count(),1); + QVERIFY(pairingSpy.count() > 0); + + // test the actual signal values. + QList<QVariant> arguments = pairingSpy.takeFirst(); + QBluetoothAddress address = qvariant_cast<QBluetoothAddress>(arguments.at(0)); + QBluetoothLocalDevice::Pairing pairingResult = qvariant_cast<QBluetoothLocalDevice::Pairing>(arguments.at(1)); + QCOMPARE(deviceAddress, address); + QCOMPARE(pairingExpected, pairingResult); + + QCOMPARE(pairingExpected, localDevice.pairingStatus(deviceAddress)); + +} + +void tst_QBluetoothLocalDevice::tst_pairingStatus() +{ + QFETCH(QBluetoothAddress, deviceAddress); + QFETCH(QBluetoothLocalDevice::Pairing, pairingExpected); + + qDebug() << "tst_pairingStatus(): address=" << deviceAddress.toString() << "pairingModeExpected=" + << static_cast<int>(pairingExpected); + + QBluetoothLocalDevice localDevice; + QCOMPARE(pairingExpected, localDevice.pairingStatus(deviceAddress)); +} +QTEST_MAIN(tst_QBluetoothLocalDevice) + +#include "tst_qbluetoothlocaldevice.moc" diff --git a/tests/auto/qbluetoothservicediscoveryagent/qbluetoothservicediscoveryagent.pro b/tests/auto/qbluetoothservicediscoveryagent/qbluetoothservicediscoveryagent.pro new file mode 100644 index 00000000..eee23d89 --- /dev/null +++ b/tests/auto/qbluetoothservicediscoveryagent/qbluetoothservicediscoveryagent.pro @@ -0,0 +1,7 @@ +SOURCES += tst_qbluetoothservicediscoveryagent.cpp +TARGET = tst_qbluetoothservicediscoveryagent +CONFIG += testcase + +QT = core bluetooth testlib + +symbian: TARGET.CAPABILITY = ReadDeviceData LocalServices WriteDeviceData diff --git a/tests/auto/qbluetoothservicediscoveryagent/tst_qbluetoothservicediscoveryagent.cpp b/tests/auto/qbluetoothservicediscoveryagent/tst_qbluetoothservicediscoveryagent.cpp new file mode 100644 index 00000000..0e5355f3 --- /dev/null +++ b/tests/auto/qbluetoothservicediscoveryagent/tst_qbluetoothservicediscoveryagent.cpp @@ -0,0 +1,346 @@ +/**************************************************************************** +** +** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the Qt Mobility Components. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include <QtTest/QtTest> + +#include <QDebug> +#include <QVariant> +#include <QStringList> + +#include <qbluetoothaddress.h> +#include <qbluetoothdevicediscoveryagent.h> +#include <qbluetoothservicediscoveryagent.h> +#include <qbluetoothlocaldevice.h> + +Q_DECLARE_METATYPE(QBluetoothDeviceInfo) +Q_DECLARE_METATYPE(QBluetoothServiceDiscoveryAgent::Error) + +// Maximum time to for bluetooth device scan +const int MaxScanTime = 5 * 60 * 1000; // 5 minutes in ms + +class tst_QBluetoothServiceDiscoveryAgent : public QObject +{ + Q_OBJECT + +public: + tst_QBluetoothServiceDiscoveryAgent(); + ~tst_QBluetoothServiceDiscoveryAgent(); + +public slots: + void deviceDiscoveryDebug(const QBluetoothDeviceInfo &info); + void serviceDiscoveryDebug(const QBluetoothServiceInfo &info); + void serviceError(const QBluetoothServiceDiscoveryAgent::Error err); + +private slots: + void initTestCase(); + + void tst_serviceDiscovery_data(); + void tst_serviceDiscovery(); + +private: + QList<QBluetoothDeviceInfo> devices; +}; + +tst_QBluetoothServiceDiscoveryAgent::tst_QBluetoothServiceDiscoveryAgent() +{ + // start Bluetooth if not started + QBluetoothLocalDevice *device = new QBluetoothLocalDevice(); + device->powerOn(); + delete device; + // wait for the device to switch bluetooth mode. + QTest::qWait(1000); + qRegisterMetaType<QBluetoothDeviceInfo>("QBluetoothDeviceInfo"); + qRegisterMetaType<QBluetoothServiceInfo>("QBluetoothServiceInfo"); + qRegisterMetaType<QList<QBluetoothUuid> >("QList<QBluetoothUuid>"); + qRegisterMetaType<QBluetoothServiceDiscoveryAgent::Error>("QBluetoothServiceDiscoveryAgent::Error"); + qRegisterMetaType<QBluetoothDeviceDiscoveryAgent::Error>("QBluetoothDeviceDiscoveryAgent::Error"); + +} + +tst_QBluetoothServiceDiscoveryAgent::~tst_QBluetoothServiceDiscoveryAgent() +{ +} + +void tst_QBluetoothServiceDiscoveryAgent::deviceDiscoveryDebug(const QBluetoothDeviceInfo &info) +{ + qDebug() << "Discovered device:" << info.address().toString() << info.name(); +} + + +void tst_QBluetoothServiceDiscoveryAgent::serviceError(const QBluetoothServiceDiscoveryAgent::Error err) +{ + qDebug() << "Service discovery error" << err; +} + +void tst_QBluetoothServiceDiscoveryAgent::initTestCase() +{ +#if 1 + QBluetoothDeviceDiscoveryAgent discoveryAgent; + + QSignalSpy finishedSpy(&discoveryAgent, SIGNAL(finished())); + QSignalSpy errorSpy(&discoveryAgent, SIGNAL(error(QBluetoothDeviceDiscoveryAgent::Error))); + QSignalSpy discoveredSpy(&discoveryAgent, SIGNAL(deviceDiscovered(const QBluetoothDeviceInfo&))); +// connect(&discoveryAgent, SIGNAL(deviceDiscovered(const QBluetoothDeviceInfo&)), +// this, SLOT(deviceDiscoveryDebug(const QBluetoothDeviceInfo&))); + + discoveryAgent.start(); + + // Wait for up to MaxScanTime for the scan to finish + int scanTime = MaxScanTime; + while (finishedSpy.count() == 0 && scanTime > 0) { + QTest::qWait(1000); + scanTime -= 1000; + } +// qDebug() << "Scan time left:" << scanTime; + + // Expect finished signal with no error + QVERIFY(finishedSpy.count() == 1); + QVERIFY(errorSpy.isEmpty()); + + devices = discoveryAgent.discoveredDevices(); +#else + devices.append(QBluetoothDeviceInfo(QBluetoothAddress(Q_UINT64_C(0x001e3a81ba69)), "Yuna", 0)); +#endif +} + +void tst_QBluetoothServiceDiscoveryAgent::serviceDiscoveryDebug(const QBluetoothServiceInfo &info) +{ + qDebug() << "Discovered service on" + << info.device().name() << info.device().address().toString(); + qDebug() << "\tService name:" << info.serviceName() << "cached" << info.device().isCached(); + qDebug() << "\tDescription:" + << info.attribute(QBluetoothServiceInfo::ServiceDescription).toString(); + qDebug() << "\tProvider:" << info.attribute(QBluetoothServiceInfo::ServiceProvider).toString(); + qDebug() << "\tL2CAP protocol service multiplexer:" << info.protocolServiceMultiplexer(); + qDebug() << "\tRFCOMM server channel:" << info.serverChannel(); +} + +static void dumpAttributeVariant(const QVariant &var, const QString indent) +{ + if (!var.isValid()) { + qDebug("%sEmpty", indent.toLocal8Bit().constData()); + return; + } + + if (var.userType() == qMetaTypeId<QBluetoothServiceInfo::Sequence>()) { + qDebug("%sSequence", indent.toLocal8Bit().constData()); + const QBluetoothServiceInfo::Sequence *sequence = static_cast<const QBluetoothServiceInfo::Sequence *>(var.data()); + foreach (const QVariant &v, *sequence) + dumpAttributeVariant(v, indent + '\t'); + } else if (var.userType() == qMetaTypeId<QBluetoothServiceInfo::Alternative>()) { + qDebug("%sAlternative", indent.toLocal8Bit().constData()); + const QBluetoothServiceInfo::Alternative *alternative = static_cast<const QBluetoothServiceInfo::Alternative *>(var.data()); + foreach (const QVariant &v, *alternative) + dumpAttributeVariant(v, indent + '\t'); + } else if (var.userType() == qMetaTypeId<QBluetoothUuid>()) { + QBluetoothUuid uuid = var.value<QBluetoothUuid>(); + switch (uuid.minimumSize()) { + case 0: + qDebug("%suuid NULL", indent.toLocal8Bit().constData()); + break; + case 2: + qDebug("%suuid %04x", indent.toLocal8Bit().constData(), uuid.toUInt16()); + break; + case 4: + qDebug("%suuid %08x", indent.toLocal8Bit().constData(), uuid.toUInt32()); + break; + case 16: { + qDebug("%suuid %s", indent.toLocal8Bit().constData(), QByteArray(reinterpret_cast<const char *>(uuid.toUInt128().data), 16).toHex().constData()); + break; + } + default: + qDebug("%suuid ???", indent.toLocal8Bit().constData()); + } + } else { + switch (var.userType()) { + case QVariant::UInt: + qDebug("%suint %u", indent.toLocal8Bit().constData(), var.toUInt()); + break; + case QVariant::Int: + qDebug("%sint %d", indent.toLocal8Bit().constData(), var.toInt()); + break; + case QVariant::String: + qDebug("%sstring %s", indent.toLocal8Bit().constData(), var.toString().toLocal8Bit().constData()); + break; + case QVariant::Bool: + qDebug("%sbool %d", indent.toLocal8Bit().constData(), var.toBool()); + break; + case QVariant::Url: + qDebug("%surl %s", indent.toLocal8Bit().constData(), var.toUrl().toString().toLocal8Bit().constData()); + break; + default: + qDebug("%sunknown", indent.toLocal8Bit().constData()); + } + } +} + +static void dumpServiceInfoAttributes(const QBluetoothServiceInfo &info) +{ + foreach (quint16 id, info.attributes()) { + dumpAttributeVariant(info.attribute(id), QString("\t")); + } +} + + +void tst_QBluetoothServiceDiscoveryAgent::tst_serviceDiscovery_data() +{ + if (devices.isEmpty()) + QSKIP("This test requires an in-range bluetooth device", SkipAll); + + QTest::addColumn<QBluetoothDeviceInfo>("deviceInfo"); + QTest::addColumn<QList<QBluetoothUuid> >("uuidFilter"); + QTest::addColumn<QBluetoothServiceDiscoveryAgent::Error>("serviceDiscoveryError"); + + // Only need to test the first 5 live devices + int max = 5; + foreach (const QBluetoothDeviceInfo &info, devices) { + if (info.isCached()) + continue; + QTest::newRow("default filter") << info << QList<QBluetoothUuid>() + << QBluetoothServiceDiscoveryAgent::NoError; + if (!--max) + break; + //QTest::newRow("public browse group") << info << (QList<QBluetoothUuid>() << QBluetoothUuid::PublicBrowseGroup); + //QTest::newRow("l2cap") << info << (QList<QBluetoothUuid>() << QBluetoothUuid::L2cap); + } + QTest::newRow("all devices") << QBluetoothDeviceInfo() << QList<QBluetoothUuid>() + << QBluetoothServiceDiscoveryAgent::NoError; +} + + +void tst_QBluetoothServiceDiscoveryAgent::tst_serviceDiscovery() +{ + // Not all devices respond to SDP, so allow for a failure + static int expected_failures = 0; + + if (devices.isEmpty()) + QSKIP("This test requires an in-range bluetooth device", SkipAll); + + QFETCH(QBluetoothDeviceInfo, deviceInfo); + QFETCH(QList<QBluetoothUuid>, uuidFilter); + QFETCH(QBluetoothServiceDiscoveryAgent::Error, serviceDiscoveryError); + + qDebug() << "Doing address" << deviceInfo.address().toString(); + QBluetoothServiceDiscoveryAgent discoveryAgent(deviceInfo.address()); + + QVERIFY(!discoveryAgent.isActive()); + + QVERIFY(discoveryAgent.discoveredServices().isEmpty()); + + QVERIFY(discoveryAgent.uuidFilter().isEmpty()); + + discoveryAgent.setUuidFilter(uuidFilter); + + QVERIFY(discoveryAgent.uuidFilter() == uuidFilter); + + QSignalSpy finishedSpy(&discoveryAgent, SIGNAL(finished())); + QSignalSpy errorSpy(&discoveryAgent, SIGNAL(error(QBluetoothServiceDiscoveryAgent::Error))); + QSignalSpy discoveredSpy(&discoveryAgent, SIGNAL(serviceDiscovered(QBluetoothServiceInfo))); +// connect(&discoveryAgent, SIGNAL(serviceDiscovered(QBluetoothServiceInfo)), +// this, SLOT(serviceDiscoveryDebug(QBluetoothServiceInfo))); + connect(&discoveryAgent, SIGNAL(error(QBluetoothServiceDiscoveryAgent::Error)), + this, SLOT(serviceError(QBluetoothServiceDiscoveryAgent::Error))); + + discoveryAgent.start(); + + QVERIFY(discoveryAgent.isActive()); + + // Wait for up to MaxScanTime for the scan to finish + int scanTime = MaxScanTime; + while (finishedSpy.count() == 0 && scanTime > 0) { + QTest::qWait(1000); + scanTime -= 1000; + } + + if (discoveryAgent.error() && expected_failures++ < 2){ + qDebug() << "Device failed to respond to SDP, skipping device" << discoveryAgent.error() << discoveryAgent.errorString(); + return; + } + + QVERIFY(discoveryAgent.error() == serviceDiscoveryError); + QVERIFY(discoveryAgent.errorString() == QString()); + + // Expect finished signal with no error + QVERIFY(finishedSpy.count() == 1); + QVERIFY(errorSpy.isEmpty()); + + //if (discoveryAgent.discoveredServices().count() && expected_failures++ <2){ + if (discoveredSpy.isEmpty() && expected_failures++ < 2){ + qDebug() << "Device failed to return any results, skipping device" << discoveryAgent.discoveredServices().count(); + return; + } + + // All returned QBluetoothServiceInfo should be valid. + while (!discoveredSpy.isEmpty()) { + const QVariant v = discoveredSpy.takeFirst().at(0); + + // Work around limitation in QMetaType and moc. + // QBluetoothServiceInfo is registered with metatype as QBluetoothServiceInfo + // moc sees it as the unqualified QBluetoothServiceInfo. + if (qstrcmp(v.typeName(), "QBluetoothServiceInfo") == 0) { + const QBluetoothServiceInfo info = + *reinterpret_cast<const QBluetoothServiceInfo*>(v.constData()); + + QVERIFY(info.isValid()); + +#if 0 + qDebug() << info.device().name() << info.device().address().toString(); + qDebug() << "\tService name:" << info.serviceName(); + if (info.protocolServiceMultiplexer() >= 0) + qDebug() << "\tL2CAP protocol service multiplexer:" << info.protocolServiceMultiplexer(); + if (info.serverChannel() >= 0) + qDebug() << "\tRFCOMM server channel:" << info.serverChannel(); + //dumpServiceInfoAttributes(info); +#endif + } + } + + QVERIFY(discoveryAgent.discoveredServices().count() != 0); + discoveryAgent.clear(); + QVERIFY(discoveryAgent.discoveredServices().count() == 0); + + discoveryAgent.stop(); + QVERIFY(!discoveryAgent.isActive()); +} + +QTEST_MAIN(tst_QBluetoothServiceDiscoveryAgent) + +#include "tst_qbluetoothservicediscoveryagent.moc" diff --git a/tests/auto/qbluetoothserviceinfo/qbluetoothserviceinfo.pro b/tests/auto/qbluetoothserviceinfo/qbluetoothserviceinfo.pro new file mode 100644 index 00000000..1b70bafa --- /dev/null +++ b/tests/auto/qbluetoothserviceinfo/qbluetoothserviceinfo.pro @@ -0,0 +1,7 @@ +SOURCES += tst_qbluetoothserviceinfo.cpp +TARGET = tst_qbluetoothserviceinfo +CONFIG += testcase + +QT = core bluetooth testlib + +symbian: TARGET.CAPABILITY = ReadDeviceData LocalServices WriteDeviceData diff --git a/tests/auto/qbluetoothserviceinfo/tst_qbluetoothserviceinfo.cpp b/tests/auto/qbluetoothserviceinfo/tst_qbluetoothserviceinfo.cpp new file mode 100644 index 00000000..4089b2a0 --- /dev/null +++ b/tests/auto/qbluetoothserviceinfo/tst_qbluetoothserviceinfo.cpp @@ -0,0 +1,243 @@ +/**************************************************************************** +** +** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the Qt Mobility Components. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include <QtTest/QtTest> +#include <QUuid> + +#include <QDebug> + +#include <qbluetoothdeviceinfo.h> +#include <qbluetoothserviceinfo.h> +#include <qbluetoothaddress.h> +#include <qbluetoothlocaldevice.h> +#include <qbluetoothuuid.h> + +Q_DECLARE_METATYPE(QBluetoothUuid::ProtocolUuid) +Q_DECLARE_METATYPE(QUuid) +Q_DECLARE_METATYPE(QBluetoothServiceInfo::Protocol) + +class tst_QBluetoothServiceInfo : public QObject +{ + Q_OBJECT + +public: + tst_QBluetoothServiceInfo(); + ~tst_QBluetoothServiceInfo(); + +private slots: + void initTestCase(); + + void tst_construction(); + + void tst_assignment_data(); + void tst_assignment(); +}; + +tst_QBluetoothServiceInfo::tst_QBluetoothServiceInfo() +{ +} + +tst_QBluetoothServiceInfo::~tst_QBluetoothServiceInfo() +{ +} + +void tst_QBluetoothServiceInfo::initTestCase() +{ + qRegisterMetaType<QBluetoothUuid::ProtocolUuid>("QBluetoothUuid::ProtocolUuid"); + qRegisterMetaType<QUuid>("QUuid"); + qRegisterMetaType<QBluetoothServiceInfo::Protocol>("QBluetoothServiceInfo::Protocol"); + // start Bluetooth if not started + QBluetoothLocalDevice *device = new QBluetoothLocalDevice(); + device->powerOn(); + delete device; +} + +void tst_QBluetoothServiceInfo::tst_construction() +{ + const QString serviceName("My Service"); + const QBluetoothDeviceInfo deviceInfo(QBluetoothAddress("001122334455"), "Test Device", 0); + + { + QBluetoothServiceInfo serviceInfo; + + QVERIFY(!serviceInfo.isValid()); + QVERIFY(!serviceInfo.isComplete()); + } + + { + QBluetoothServiceInfo serviceInfo; + serviceInfo.setServiceName(serviceName); + serviceInfo.setDevice(deviceInfo); + + QVERIFY(serviceInfo.isValid()); + + QCOMPARE(serviceInfo.serviceName(), serviceName); + QCOMPARE(serviceInfo.device().address(), deviceInfo.address()); + + QBluetoothServiceInfo copyInfo(serviceInfo); + + QVERIFY(copyInfo.isValid()); + + QCOMPARE(copyInfo.serviceName(), serviceName); + QCOMPARE(copyInfo.device().address(), deviceInfo.address()); + } +} + +void tst_QBluetoothServiceInfo::tst_assignment_data() +{ + QTest::addColumn<QUuid>("uuid"); + QTest::addColumn<QBluetoothUuid::ProtocolUuid>("protocolUuid"); + QTest::addColumn<QBluetoothServiceInfo::Protocol>("serviceInfoProtocol"); + + QTest::newRow("assignment_data") + << QUuid(0x67c8770b, 0x44f1, 0x410a, 0xab, 0x9a, 0xf9, 0xb5, 0x44, 0x6f, 0x13, 0xee) + << QBluetoothUuid::L2cap << QBluetoothServiceInfo::L2capProtocol; +} + +void tst_QBluetoothServiceInfo::tst_assignment() +{ + QFETCH(QUuid, uuid); + QFETCH(QBluetoothUuid::ProtocolUuid, protocolUuid); + QFETCH(QBluetoothServiceInfo::Protocol, serviceInfoProtocol); + + const QString serviceName("My Service"); + const QBluetoothDeviceInfo deviceInfo(QBluetoothAddress("001122334455"), "Test Device", 0); + + QBluetoothServiceInfo serviceInfo; + serviceInfo.setServiceName(serviceName); + serviceInfo.setDevice(deviceInfo); + + QVERIFY(serviceInfo.isValid()); + + { + QBluetoothServiceInfo copyInfo = serviceInfo; + + QVERIFY(copyInfo.isValid()); + + QCOMPARE(copyInfo.serviceName(), serviceName); + QCOMPARE(copyInfo.device().address(), deviceInfo.address()); + } + + { + QBluetoothServiceInfo copyInfo; + + QVERIFY(!copyInfo.isValid()); + + copyInfo = serviceInfo; + + QVERIFY(copyInfo.isValid()); + + QCOMPARE(copyInfo.serviceName(), serviceName); + QCOMPARE(copyInfo.device().address(), deviceInfo.address()); + } + + { + QBluetoothServiceInfo copyInfo1; + QBluetoothServiceInfo copyInfo2; + + QVERIFY(!copyInfo1.isValid()); + QVERIFY(!copyInfo2.isValid()); + + copyInfo1 = copyInfo2 = serviceInfo; + + QVERIFY(copyInfo1.isValid()); + QVERIFY(copyInfo2.isValid()); + + QCOMPARE(copyInfo1.serviceName(), serviceName); + QCOMPARE(copyInfo2.serviceName(), serviceName); + QCOMPARE(copyInfo1.device().address(), deviceInfo.address()); + QCOMPARE(copyInfo2.device().address(), deviceInfo.address()); + } + + { + QBluetoothServiceInfo copyInfo; + QVERIFY(!copyInfo.isValid()); + copyInfo = serviceInfo; + + copyInfo.setAttribute(QBluetoothServiceInfo::ProtocolDescriptorList, uuid); + QVERIFY(copyInfo.contains(QBluetoothServiceInfo::ProtocolDescriptorList)); + QVERIFY(copyInfo.isComplete()); + QVERIFY(copyInfo.attributes().count() > 0); + + copyInfo.removeAttribute(QBluetoothServiceInfo::ProtocolDescriptorList); + QVERIFY(!copyInfo.contains(QBluetoothServiceInfo::ProtocolDescriptorList)); + QVERIFY(!copyInfo.isComplete()); + } + + { + QBluetoothServiceInfo copyInfo; + QVERIFY(!copyInfo.isValid()); + copyInfo = serviceInfo; + + QVERIFY(copyInfo.serverChannel() == -1); + QVERIFY(copyInfo.protocolServiceMultiplexer() == -1); + + QBluetoothServiceInfo::Sequence protocolDescriptorList; + QBluetoothServiceInfo::Sequence protocol; + protocol << QVariant::fromValue(QBluetoothUuid(protocolUuid)); + protocolDescriptorList.append(QVariant::fromValue(protocol)); + protocol.clear(); + + protocolDescriptorList.append(QVariant::fromValue(protocol)); + copyInfo.setAttribute(QBluetoothServiceInfo::ProtocolDescriptorList, + protocolDescriptorList); + QVERIFY(copyInfo.serverChannel() == -1); + QVERIFY(copyInfo.protocolServiceMultiplexer() != -1); + QVERIFY(copyInfo.socketProtocol() == serviceInfoProtocol); + } + + { + QBluetoothServiceInfo copyInfo; + QVERIFY(!copyInfo.isValid()); + copyInfo = serviceInfo; + QVERIFY(!copyInfo.isRegistered()); + + QVERIFY(copyInfo.registerService()); + QVERIFY(copyInfo.isRegistered()); + + QVERIFY(copyInfo.unregisterService()); + QVERIFY(!copyInfo.isRegistered()); + } +} + +QTEST_MAIN(tst_QBluetoothServiceInfo) + +#include "tst_qbluetoothserviceinfo.moc" diff --git a/tests/auto/qbluetoothsocket/README.txt b/tests/auto/qbluetoothsocket/README.txt new file mode 100644 index 00000000..1e92712d --- /dev/null +++ b/tests/auto/qbluetoothsocket/README.txt @@ -0,0 +1,14 @@ + +This test requires btclient to running on a linux machine, and for it to +be discoverable and connectable to the device under test. + +btclient is available in tests/btclient. It requires a linux machine +with bluez 4 installed. It does not depend on Qt. + +The unit test attempts to use service discovery to locate btclient. For quick +testing this can be time consuming. It will also check the environment variable +TESTSERVER for the mac address bluetooth adaptor of the system running +btclient. You can use hciconfig on the linux system to find it's mac address. +If TESTSERVER is set and btclient is not running the test will fail. + + diff --git a/tests/auto/qbluetoothsocket/qbluetoothsocket.pro b/tests/auto/qbluetoothsocket/qbluetoothsocket.pro new file mode 100644 index 00000000..740efcb3 --- /dev/null +++ b/tests/auto/qbluetoothsocket/qbluetoothsocket.pro @@ -0,0 +1,13 @@ +SOURCES += tst_qbluetoothsocket.cpp +TARGET = tst_qbluetoothsocket +CONFIG += testcase + +QT = core network bluetooth testlib + +INCLUDEPATH += ../../../tests/btclient +DEPENDPATH += ../../../tests/btclient + +symbian: TARGET.CAPABILITY = NetworkControl ReadDeviceData LocalServices WriteDeviceData + +OTHER_FILES += \ + README.txt diff --git a/tests/auto/qbluetoothsocket/tst_qbluetoothsocket.cpp b/tests/auto/qbluetoothsocket/tst_qbluetoothsocket.cpp new file mode 100644 index 00000000..8e848249 --- /dev/null +++ b/tests/auto/qbluetoothsocket/tst_qbluetoothsocket.cpp @@ -0,0 +1,782 @@ +/**************************************************************************** +** +** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the Qt Mobility Components. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include <QtTest/QtTest> + +#include <QDebug> + +#include <QProcessEnvironment> + +#include <qbluetoothsocket.h> +#include <qbluetoothdeviceinfo.h> +#include <qbluetoothserviceinfo.h> +#include <qbluetoothservicediscoveryagent.h> +#include <qbluetoothlocaldevice.h> + +#include <sys/utsname.h> + +#include <btclient.h> + +Q_DECLARE_METATYPE(QBluetoothSocket::SocketState) +Q_DECLARE_METATYPE(QBluetoothSocket::SocketType) + +//#define BTADDRESS "00:1A:9F:92:9E:5A" +char BTADDRESS[] = "00:00:00:00:00:00"; +#ifdef Q_OS_SYMBIAN +static const QString peerNameSymbian("Patagonia_bluetooth_client"); +#endif + +// Max time to wait for connection + +static const int MaxConnectTime = 60 * 1000; // 1 minute in ms +static const int MaxReadWriteTime = 60 * 1000; // 1 minute in ms + +class tst_QBluetoothSocket : public QObject +{ + Q_OBJECT + +public: + enum ClientConnectionShutdown { + Error, + Disconnect, + Close, + Abort, + }; + + tst_QBluetoothSocket(); + ~tst_QBluetoothSocket(); + +private slots: + void initTestCase(); + + void tst_construction_data(); + void tst_construction(); + + void tst_clientConnection_data(); + void tst_clientConnection(); + + void tst_serviceConnection_data(); + void tst_serviceConnection(); + + void tst_clientCommunication_data(); + void tst_clientCommunication(); + + void tst_localPeer_data(); + void tst_localPeer(); + + void tst_error(); + +public slots: + void serviceDiscovered(const QBluetoothServiceInfo &info); + void finished(); + void error(QBluetoothServiceDiscoveryAgent::Error error); +private: + bool done_discovery; + +}; + +Q_DECLARE_METATYPE(tst_QBluetoothSocket::ClientConnectionShutdown) + +tst_QBluetoothSocket::tst_QBluetoothSocket() +{ + qRegisterMetaType<QBluetoothSocket::SocketState>("QBluetoothSocket::SocketState"); + qRegisterMetaType<QBluetoothSocket::SocketError>("QBluetoothSocket::SocketError"); +} + +tst_QBluetoothSocket::~tst_QBluetoothSocket() +{ +} + +void tst_QBluetoothSocket::initTestCase() +{ + // start Bluetooth if not started + QBluetoothLocalDevice *device = new QBluetoothLocalDevice(); + device->powerOn(); + delete device; + + QProcessEnvironment pe = QProcessEnvironment::systemEnvironment(); + QLatin1String t("TESTSERVER"); + if (pe.contains(t)){ + qDebug() << pe.value(t); + strcpy(BTADDRESS, pe.value(t).toAscii()); + } + + if (QBluetoothAddress(BTADDRESS).isNull()){ + // Go find an echo server for BTADDRESS + QBluetoothServiceDiscoveryAgent *sda = new QBluetoothServiceDiscoveryAgent(this); + connect(sda, SIGNAL(serviceDiscovered(QBluetoothServiceInfo)), this, SLOT(serviceDiscovered(QBluetoothServiceInfo))); + connect(sda, SIGNAL(error(QBluetoothServiceDiscoveryAgent::Error)), this, SLOT(error(QBluetoothServiceDiscoveryAgent::Error))); + connect(sda, SIGNAL(finished()), this, SLOT(finished())); + + + qDebug() << "Starting discovery"; + done_discovery = false; + memset(BTADDRESS, 0, 18); + + sda->setUuidFilter(QBluetoothUuid(QString(ECHO_SERVICE_UUID))); + sda->start(QBluetoothServiceDiscoveryAgent::MinimalDiscovery); + + int connectTime = MaxConnectTime; + while (!done_discovery) { + QTest::qWait(1000); + connectTime -= 1000; + } + + sda->stop(); + + if (QBluetoothAddress(BTADDRESS).isNull()){ + QFAIL("Unable to find test service"); + } + delete sda; + sda = 0x0; + } + +} + +void tst_QBluetoothSocket::error(QBluetoothServiceDiscoveryAgent::Error error) +{ + qDebug() << "Received error" << error; +// done_discovery = true; +} + +void tst_QBluetoothSocket::finished() +{ + qDebug() << "Finished"; + done_discovery = true; +} + +void tst_QBluetoothSocket::serviceDiscovered(const QBluetoothServiceInfo &info) +{ + qDebug() << "Found: " << info.device().name() << info.serviceUuid(); + strcpy(BTADDRESS, info.device().address().toString().toAscii()); + done_discovery = true; +} + +void tst_QBluetoothSocket::tst_construction_data() +{ + QTest::addColumn<QBluetoothSocket::SocketType>("socketType"); + + QTest::newRow("unknown socket") << QBluetoothSocket::UnknownSocketType; + QTest::newRow("rfcomm socket") << QBluetoothSocket::RfcommSocket; + QTest::newRow("l2cap socket") << QBluetoothSocket::L2capSocket; +} + +void tst_QBluetoothSocket::tst_construction() +{ + QFETCH(QBluetoothSocket::SocketType, socketType); + + { + QBluetoothSocket socket; + + QCOMPARE(socket.socketType(), QBluetoothSocket::UnknownSocketType); + } + + { + QBluetoothSocket socket(socketType); + + QCOMPARE(socket.socketType(), socketType); + } +} + +void tst_QBluetoothSocket::tst_clientConnection_data() +{ + QTest::addColumn<QBluetoothSocket::SocketType>("sockettype"); + QTest::addColumn<ClientConnectionShutdown>("shutdown"); + QTest::addColumn<QBluetoothAddress>("address"); + QTest::addColumn<quint16>("port"); + QTest::addColumn<QByteArray>("data"); + + //QBluetoothAddress address("00:1E:3A:81:BA:69"); + QBluetoothAddress address(BTADDRESS); + quint16 port = 10; + + QTest::newRow("unavailable, error") << QBluetoothSocket::RfcommSocket + << Error << QBluetoothAddress("112233445566") << quint16(10) << QByteArray(); + + QTest::newRow("available, disconnect") << QBluetoothSocket::RfcommSocket + << Disconnect << address << port << QByteArray(); + QTest::newRow("available, disconnect with data") << QBluetoothSocket::RfcommSocket + << Disconnect << address << port << QByteArray("Test message\n"); + QTest::newRow("available, close") << QBluetoothSocket::RfcommSocket + << Close << address << port << QByteArray(); + QTest::newRow("available, abort") << QBluetoothSocket::RfcommSocket + << Abort << address << port << QByteArray(); + QTest::newRow("available, abort with data") << QBluetoothSocket::RfcommSocket + << Abort << address << port << QByteArray("Test message\n"); + + + port = 0x1011; + QTest::newRow("unavailable, error") << QBluetoothSocket::L2capSocket + << Error << QBluetoothAddress("112233445566") << quint16(10) << QByteArray(); + + QTest::newRow("available, disconnect") << QBluetoothSocket::L2capSocket + << Disconnect << address << port << QByteArray(); + QTest::newRow("available, disconnect with data") << QBluetoothSocket::L2capSocket + << Disconnect << address << port << QByteArray("Test message\n"); + QTest::newRow("available, close") << QBluetoothSocket::L2capSocket + << Close << address << port << QByteArray(); + QTest::newRow("available, abort") << QBluetoothSocket::L2capSocket + << Abort << address << port << QByteArray(); + QTest::newRow("available, abort with data") << QBluetoothSocket::L2capSocket + << Abort << address << port << QByteArray("Test message\n"); + +} + +void tst_QBluetoothSocket::tst_clientConnection() +{ + QFETCH(QBluetoothSocket::SocketType, sockettype); + QFETCH(ClientConnectionShutdown, shutdown); + QFETCH(QBluetoothAddress, address); + QFETCH(quint16, port); + QFETCH(QByteArray, data); + int loop = 5; + + tryagain: + /* Construction */ + QBluetoothSocket *socket = new QBluetoothSocket(sockettype); + + QSignalSpy stateSpy(socket, SIGNAL(stateChanged(QBluetoothSocket::SocketState))); + + QCOMPARE(socket->socketType(), sockettype); + QCOMPARE(socket->state(), QBluetoothSocket::UnconnectedState); + + /* Connection */ + QSignalSpy connectedSpy(socket, SIGNAL(connected())); + QSignalSpy errorSpy(socket, SIGNAL(error(QBluetoothSocket::SocketError))); + + socket->connectToService(address, port); + + QCOMPARE(stateSpy.count(), 1); + QCOMPARE(stateSpy.takeFirst().at(0).value<QBluetoothSocket::SocketState>(), QBluetoothSocket::ConnectingState); + QCOMPARE(socket->state(), QBluetoothSocket::ConnectingState); + + stateSpy.clear(); + + int connectTime = MaxConnectTime; + while (connectedSpy.count() == 0 && errorSpy.count() == 0 && connectTime > 0) { + QTest::qWait(1000); + connectTime -= 1000; + } + + if (shutdown == Error) { + QCOMPARE(connectedSpy.count(), 0); + QCOMPARE(errorSpy.count(), 1); + QCOMPARE(stateSpy.count(), 1); + QCOMPARE(stateSpy.takeFirst().at(0).value<QBluetoothSocket::SocketState>(), QBluetoothSocket::UnconnectedState); + QCOMPARE(socket->state(), QBluetoothSocket::UnconnectedState); + // The remote service needs time to close the connection and resume listening + QTest::qSleep(100); + return; + } else { + if (errorSpy.count() != 0) { + qDebug() << errorSpy.takeFirst().at(0).toInt(); + if (loop--) + goto tryagain; + QSKIP("Connection error", SkipSingle); + } + QCOMPARE(connectedSpy.count(), 1); + QCOMPARE(stateSpy.count(), 1); + QCOMPARE(stateSpy.takeFirst().at(0).value<QBluetoothSocket::SocketState>(), QBluetoothSocket::ConnectedState); + QCOMPARE(socket->state(), QBluetoothSocket::ConnectedState); + } + QVERIFY(shutdown != Error); + + stateSpy.clear(); + + /* Read / Write */ + QSignalSpy bytesWrittenSpy(socket, SIGNAL(bytesWritten(qint64))); + + if (!data.isEmpty()) { + // Write data but don't flush. + socket->write(data); + } + + /* Disconnection */ + QSignalSpy disconnectedSpy(socket, SIGNAL(disconnected())); + + if (shutdown == Abort) { + socket->abort(); + +// TODO: no buffereing, all data is sent on write + if (!data.isEmpty()) { + // Check that pending write did not complete. +// QEXPECT_FAIL("", "TODO: need to implement write buffering", Continue); + QCOMPARE(bytesWrittenSpy.count(), 0); + } + + QCOMPARE(disconnectedSpy.count(), 1); + QCOMPARE(stateSpy.count(), 1); + QCOMPARE(stateSpy.takeFirst().at(0).value<QBluetoothSocket::SocketState>(), QBluetoothSocket::UnconnectedState); + QCOMPARE(socket->state(), QBluetoothSocket::UnconnectedState); + } else { + if (shutdown == Disconnect) + socket->disconnectFromService(); + else if (shutdown == Close) + socket->close(); + + if (socket->state() == QBluetoothSocket::UnconnectedState){ + // Linux for example on close goes through closing and unconnected without stopping + QCOMPARE(stateSpy.count(), 2); // closing + unconnected + QCOMPARE(stateSpy.takeFirst().at(0).value<QBluetoothSocket::SocketState>(), QBluetoothSocket::ClosingState); + QCOMPARE(stateSpy.takeFirst().at(0).value<QBluetoothSocket::SocketState>(), QBluetoothSocket::UnconnectedState); + QCOMPARE(socket->state(), QBluetoothSocket::UnconnectedState); + + } + else { + QCOMPARE(stateSpy.count(), 1); + QCOMPARE(stateSpy.takeFirst().at(0).value<QBluetoothSocket::SocketState>(), QBluetoothSocket::ClosingState); + QCOMPARE(socket->state(), QBluetoothSocket::ClosingState); + + int disconnectTime = MaxConnectTime; + while (disconnectedSpy.count() == 0 && disconnectTime > 0) { + QTest::qWait(1000); + disconnectTime -= 1000; + } + QCOMPARE(disconnectedSpy.count(), 1); + QCOMPARE(stateSpy.count(), 1); + QCOMPARE(stateSpy.takeFirst().at(0).value<QBluetoothSocket::SocketState>(), QBluetoothSocket::UnconnectedState); + } + + if (!data.isEmpty()) { + // Check that pending write completed. + QCOMPARE(bytesWrittenSpy.count(), 1); + QCOMPARE(bytesWrittenSpy.at(0).at(0).toLongLong(), qint64(data.length())); + } + + } + + delete socket; + + // The remote service needs time to close the connection and resume listening + QTest::qSleep(100); +} + +void tst_QBluetoothSocket::tst_serviceConnection_data() +{ + QTest::addColumn<QBluetoothServiceInfo>("serviceInfo"); + + QBluetoothServiceInfo serviceInfo; + + //serviceInfo.setDevice(QBluetoothDeviceInfo(QBluetoothAddress("001167602023"), QString(), 0)); + QBluetoothAddress address(BTADDRESS); + serviceInfo.setDevice(QBluetoothDeviceInfo(address, QString(), 0)); + + QBluetoothServiceInfo::Sequence protocolDescriptorList; + QBluetoothServiceInfo::Sequence protocol; + + protocol << QVariant::fromValue(QBluetoothUuid(QBluetoothUuid::L2cap)); + protocolDescriptorList.append(QVariant::fromValue(protocol)); + + protocol.clear(); + protocol << QVariant::fromValue(QBluetoothUuid(QBluetoothUuid::Rfcomm)) << QVariant::fromValue(quint8(10)); + protocolDescriptorList.append(QVariant::fromValue(protocol)); + + serviceInfo.setAttribute(QBluetoothServiceInfo::ProtocolDescriptorList, protocolDescriptorList); + + QTest::newRow("service connection") << serviceInfo; +} + +void tst_QBluetoothSocket::tst_serviceConnection() +{ + QFETCH(QBluetoothServiceInfo, serviceInfo); + + /* Construction */ + QBluetoothSocket *socket = new QBluetoothSocket; + + QSignalSpy stateSpy(socket, SIGNAL(stateChanged(QBluetoothSocket::SocketState))); + + QCOMPARE(socket->socketType(), QBluetoothSocket::UnknownSocketType); + QCOMPARE(socket->state(), QBluetoothSocket::UnconnectedState); + + /* Connection */ + QSignalSpy connectedSpy(socket, SIGNAL(connected())); + QSignalSpy errorSpy(socket, SIGNAL(error(QBluetoothSocket::SocketError))); + + socket->connectToService(serviceInfo); + + QCOMPARE(stateSpy.count(), 1); + QCOMPARE(stateSpy.takeFirst().at(0).value<QBluetoothSocket::SocketState>(), QBluetoothSocket::ConnectingState); + QCOMPARE(socket->state(), QBluetoothSocket::ConnectingState); + + stateSpy.clear(); + + int connectTime = MaxConnectTime; + while (connectedSpy.count() == 0 && errorSpy.count() == 0 && connectTime > 0) { + QTest::qWait(1000); + connectTime -= 1000; + } + + if (errorSpy.count() != 0) { + qDebug() << errorSpy.takeFirst().at(0).toInt(); + QSKIP("Connection error", SkipSingle); + } + QCOMPARE(connectedSpy.count(), 1); + QCOMPARE(stateSpy.count(), 1); + QCOMPARE(stateSpy.takeFirst().at(0).value<QBluetoothSocket::SocketState>(), QBluetoothSocket::ConnectedState); + QCOMPARE(socket->state(), QBluetoothSocket::ConnectedState); + + stateSpy.clear(); + + /* Disconnection */ + QSignalSpy disconnectedSpy(socket, SIGNAL(disconnected())); + + socket->disconnectFromService(); + + QVERIFY(stateSpy.count() >= 1); + QCOMPARE(stateSpy.takeFirst().at(0).value<QBluetoothSocket::SocketState>(), QBluetoothSocket::ClosingState); + + int disconnectTime = MaxConnectTime; + while (disconnectedSpy.count() == 0 && disconnectTime > 0) { + QTest::qWait(1000); + disconnectTime -= 1000; + } + + QCOMPARE(disconnectedSpy.count(), 1); + QCOMPARE(stateSpy.count(), 1); + QCOMPARE(stateSpy.takeFirst().at(0).value<QBluetoothSocket::SocketState>(), QBluetoothSocket::UnconnectedState); + + delete socket; + + // The remote service needs time to close the connection and resume listening + QTest::qSleep(100); +} + +void tst_QBluetoothSocket::tst_clientCommunication_data() +{ + QTest::addColumn<QStringList>("data"); + + { + QStringList data; + data << QLatin1String("Test line one.\n"); + data << QLatin1String("Test line two, with longer data.\n"); + + QTest::newRow("two line test") << data; + } +} + +void tst_QBluetoothSocket::tst_clientCommunication() +{ + QFETCH(QStringList, data); + + /* Construction */ + QBluetoothSocket *socket = new QBluetoothSocket(QBluetoothSocket::RfcommSocket); + + QSignalSpy stateSpy(socket, SIGNAL(stateChanged(QBluetoothSocket::SocketState))); + + QCOMPARE(socket->socketType(), QBluetoothSocket::RfcommSocket); + QCOMPARE(socket->state(), QBluetoothSocket::UnconnectedState); + + /* Connection */ + QSignalSpy connectedSpy(socket, SIGNAL(connected())); + + socket->connectToService(QBluetoothAddress(BTADDRESS), 10); // echo service running on device 00:11:67:60:20:23 + + QCOMPARE(stateSpy.count(), 1); + QCOMPARE(qvariant_cast<QBluetoothSocket::SocketState>(stateSpy.takeFirst().at(0)), QBluetoothSocket::ConnectingState); + QCOMPARE(socket->state(), QBluetoothSocket::ConnectingState); + + stateSpy.clear(); + + int connectTime = MaxConnectTime; + while (connectedSpy.count() == 0 && connectTime > 0) { + QTest::qWait(1000); + connectTime -= 1000; + } + + QCOMPARE(connectedSpy.count(), 1); + QCOMPARE(stateSpy.count(), 1); + QCOMPARE(qvariant_cast<QBluetoothSocket::SocketState>(stateSpy.takeFirst().at(0)), QBluetoothSocket::ConnectedState); + QCOMPARE(socket->state(), QBluetoothSocket::ConnectedState); + + stateSpy.clear(); + + /* Read / Write */ + QCOMPARE(socket->bytesToWrite(), qint64(0)); + QCOMPARE(socket->bytesAvailable(), qint64(0)); + + { + /* Send line by line with event loop */ + foreach (const QString &line, data) { + QSignalSpy readyReadSpy(socket, SIGNAL(readyRead())); + QSignalSpy bytesWrittenSpy(socket, SIGNAL(bytesWritten(qint64))); + + socket->write(line.toUtf8()); + +// QEXPECT_FAIL("", "TODO: need to implement write buffering", Continue); + QCOMPARE(socket->bytesToWrite(), qint64(line.length())); + + int readWriteTime = MaxReadWriteTime; + while ((bytesWrittenSpy.count() == 0 || readyReadSpy.count() == 0) && readWriteTime > 0) { + QTest::qWait(1000); + readWriteTime -= 1000; + } + + QCOMPARE(bytesWrittenSpy.count(), 1); + QCOMPARE(bytesWrittenSpy.at(0).at(0).toLongLong(), qint64(line.length())); + + readWriteTime = MaxReadWriteTime; + while ((readyReadSpy.count() == 0) && readWriteTime > 0) { + QTest::qWait(1000); + readWriteTime -= 1000; + } + + QCOMPARE(readyReadSpy.count(), 1); + + QCOMPARE(socket->bytesAvailable(), qint64(line.length())); + + QVERIFY(socket->canReadLine()); + + QByteArray echoed = socket->readAll(); + + QCOMPARE(line.toUtf8(), echoed); + } + } + +#if 0 + { + /* Send line by line without event loop */ + QSignalSpy readyReadSpy(socket, SIGNAL(readyRead())); + QSignalSpy bytesWrittenSpy(socket, SIGNAL(bytesWritten(qint64))); + + qint64 bytesToWrite = 0; + foreach (const QString &line, data) { + socket->write(line.toUtf8()); + bytesToWrite += line.toUtf8().length(); + QCOMPARE(socket->bytesToWrite(), bytesToWrite); + } + + int readWriteTime = MaxReadWriteTime; + while (socket->bytesToWrite() != 0 && readyReadSpy.count() == 0 && readWriteTime > 0) { + QTest::qWait(1000); + readWriteTime -= 1000; + } + + QCOMPARE(bytesWrittenSpy.count(), 1); + QCOMPARE(bytesWrittenSpy.at(0).at(0).toLongLong(), bytesToWrite); + QCOMPARE(readyReadSpy.count(), 1); + + QCOMPARE(socket->bytesAvailable(), bytesToWrite); + + QVERIFY(socket->canReadLine()); + + QByteArray echoed = socket->readAll(); + + QCOMPARE(data.join(QString()).toUtf8(), echoed); + } +#endif + + { + /* Send all at once */ + QSignalSpy readyReadSpy(socket, SIGNAL(readyRead())); + QSignalSpy bytesWrittenSpy(socket, SIGNAL(bytesWritten(qint64))); + + QString joined = data.join(QString()); + socket->write(joined.toUtf8()); + +// QEXPECT_FAIL("", "TODO: need to implement write buffering", Continue); + QCOMPARE(socket->bytesToWrite(), qint64(joined.length())); + + int readWriteTime = MaxReadWriteTime; + while ((bytesWrittenSpy.count() == 0 || readyReadSpy.count() == 0) && readWriteTime > 0) { + QTest::qWait(1000); + readWriteTime -= 1000; + } + + QCOMPARE(bytesWrittenSpy.count(), 1); + QCOMPARE(bytesWrittenSpy.at(0).at(0).toLongLong(), qint64(joined.length())); + QCOMPARE(readyReadSpy.count(), 1); + + QCOMPARE(socket->bytesAvailable(), qint64(joined.length())); + + QVERIFY(socket->canReadLine()); + + QByteArray echoed = socket->readAll(); + + QCOMPARE(joined.toUtf8(), echoed); + } + + /* Disconnection */ + QSignalSpy disconnectedSpy(socket, SIGNAL(disconnected())); + + socket->disconnectFromService(); + + int disconnectTime = MaxConnectTime; + while (disconnectedSpy.count() == 0 && disconnectTime > 0) { + QTest::qWait(1000); + disconnectTime -= 1000; + } + + QCOMPARE(disconnectedSpy.count(), 1); + QCOMPARE(stateSpy.count(), 2); + QCOMPARE(qvariant_cast<QBluetoothSocket::SocketState>(stateSpy.takeFirst().at(0)), QBluetoothSocket::ClosingState); + QCOMPARE(qvariant_cast<QBluetoothSocket::SocketState>(stateSpy.takeFirst().at(0)), QBluetoothSocket::UnconnectedState); + + delete socket; + + // The remote service needs time to close the connection and resume listening + QTest::qSleep(100); + +} + +void tst_QBluetoothSocket::tst_localPeer_data() +{ +// QTest::addColumn<QString>("localName"); +// QTest::addColumn<QBluetoothAddress>("localAddress"); +// QTest::addColumn<quint16>("localPort"); + QTest::addColumn<QString>("peerName"); + QTest::addColumn<QBluetoothAddress>("peerAddress"); + QTest::addColumn<quint16>("peerPort"); + + struct utsname u; + uname(&u); + + QTest::newRow("test") //<< QString::fromLocal8Bit(u.nodename) << QBluetoothAddress(BTADDRESS) << quint16(10) + << QString(BTADDRESS) << QBluetoothAddress(BTADDRESS) << quint16(10); +} + +void tst_QBluetoothSocket::tst_localPeer() +{ +// QFETCH(QString, localName); +// QFETCH(QBluetoothAddress, localAddress); +// QFETCH(quint16, localPort); + QFETCH(QString, peerName); + QFETCH(QBluetoothAddress, peerAddress); + QFETCH(quint16, peerPort); + +#ifndef Q_OS_SYMBIAN + QStringList args; + args << "name" << peerAddress.toString(); + QProcess *hcitool = new QProcess(); + hcitool->start("hcitool", args); + hcitool->waitForReadyRead(); + QString peerNameHCI = hcitool->readLine().trimmed(); + hcitool->close(); + delete hcitool; +#endif + + + /* Construction */ + QBluetoothSocket *socket = new QBluetoothSocket(QBluetoothSocket::RfcommSocket); + + QSignalSpy stateSpy(socket, SIGNAL(stateChanged(QBluetoothSocket::SocketState))); + + QCOMPARE(socket->socketType(), QBluetoothSocket::RfcommSocket); + QCOMPARE(socket->state(), QBluetoothSocket::UnconnectedState); + + /* Connection */ + QSignalSpy connectedSpy(socket, SIGNAL(connected())); + + socket->connectToService(QBluetoothAddress(BTADDRESS), 11); + + QCOMPARE(stateSpy.count(), 1); + QCOMPARE(qvariant_cast<QBluetoothSocket::SocketState>(stateSpy.takeFirst().at(0)), QBluetoothSocket::ConnectingState); + QCOMPARE(socket->state(), QBluetoothSocket::ConnectingState); + + stateSpy.clear(); + + int connectTime = MaxConnectTime; + while (connectedSpy.count() == 0 && connectTime > 0) { + QTest::qWait(1000); + connectTime -= 1000; + } + + QCOMPARE(connectedSpy.count(), 1); + QCOMPARE(stateSpy.count(), 1); + QCOMPARE(qvariant_cast<QBluetoothSocket::SocketState>(stateSpy.takeFirst().at(0)), QBluetoothSocket::ConnectedState); + QCOMPARE(socket->state(), QBluetoothSocket::ConnectedState); + + QByteArray echoed = socket->readAll(); + QString data(echoed); + QStringList list = data.split(QChar(' '), QString::SkipEmptyParts); + // list is: + // [0]local mac, [1]local port, [2]local name, [3]peer mac, [4]peer port + + QCOMPARE(socket->peerAddress(), QBluetoothAddress(list[0])); + QCOMPARE(socket->peerPort(), list[1].toUShort()); + + QCOMPARE(socket->localName(), list[2]); + QCOMPARE(socket->localAddress(), QBluetoothAddress(list[3])); + QCOMPARE(socket->localPort(), list[4].toUShort()); +#ifndef Q_OS_SYMBIAN + QCOMPARE(socket->peerName(), peerNameHCI); +#else + QCOMPARE(socket->peerName(), peerNameSymbian); +#endif + + /* Disconnection */ + QSignalSpy disconnectedSpy(socket, SIGNAL(disconnected())); + + socket->disconnectFromService(); + + int disconnectTime = MaxConnectTime; + while (disconnectedSpy.count() == 0 && disconnectTime > 0) { + QTest::qWait(1000); + disconnectTime -= 1000; + } + + QCOMPARE(disconnectedSpy.count(), 1); + QCOMPARE(stateSpy.count(), 2); + QCOMPARE(qvariant_cast<QBluetoothSocket::SocketState>(stateSpy.takeFirst().at(0)), QBluetoothSocket::ClosingState); + QCOMPARE(qvariant_cast<QBluetoothSocket::SocketState>(stateSpy.takeFirst().at(0)), QBluetoothSocket::UnconnectedState); + + delete socket; +} + +void tst_QBluetoothSocket::tst_error() +{ + QBluetoothSocket socket; + QSignalSpy errorSpy(&socket, SIGNAL(error(QBluetoothSocket::SocketError))); + QCOMPARE(errorSpy.count(), 0); + + QVERIFY(socket.error() != (QBluetoothSocket::ConnectionRefusedError || + QBluetoothSocket::HostNotFoundError || + QBluetoothSocket::NetworkError || + QBluetoothSocket::RemoteHostClosedError || + QBluetoothSocket::ServiceNotFoundError || + QBluetoothSocket::UnknownSocketError)); + + QVERIFY(socket.errorString() == QString()); +} + +QTEST_MAIN(tst_QBluetoothSocket) + +#include "tst_qbluetoothsocket.moc" + diff --git a/tests/auto/qbluetoothtransfermanager/qbluetoothtransfermanager.pro b/tests/auto/qbluetoothtransfermanager/qbluetoothtransfermanager.pro new file mode 100644 index 00000000..37bab8c3 --- /dev/null +++ b/tests/auto/qbluetoothtransfermanager/qbluetoothtransfermanager.pro @@ -0,0 +1,10 @@ +SOURCES += tst_qbluetoothtransfermanager.cpp +TARGET=tst_qbluetoothtransfermanager +CONFIG += testcase + +QT = core bluetooth testlib + +INCLUDEPATH += ../../../tests/btclient +DEPENDPATH += ../../../tests/btclient + +symbian: TARGET.CAPABILITY = All-TCB #ReadDeviceData LocalServices WriteDeviceData diff --git a/tests/auto/qbluetoothtransfermanager/tst_qbluetoothtransfermanager.cpp b/tests/auto/qbluetoothtransfermanager/tst_qbluetoothtransfermanager.cpp new file mode 100644 index 00000000..76131764 --- /dev/null +++ b/tests/auto/qbluetoothtransfermanager/tst_qbluetoothtransfermanager.cpp @@ -0,0 +1,426 @@ +/**************************************************************************** +** +** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the Qt Mobility Components. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include <QtTest/QtTest> + +#include <QDebug> +#include <QMap> +#include <QTextStream> + +#include <qbluetoothtransferrequest.h> +#include <qbluetoothtransfermanager.h> +#include <qbluetoothtransferreply.h> +#include <qbluetoothaddress.h> +#include <qbluetoothlocaldevice.h> + +#include <qbluetoothdeviceinfo.h> +#include <qbluetoothserviceinfo.h> +#include <qbluetoothservicediscoveryagent.h> +#include <btclient.h> + + +typedef QMap<int,QVariant> tst_QBluetoothTransferManager_QParameterMap; +Q_DECLARE_METATYPE(tst_QBluetoothTransferManager_QParameterMap) + +#ifdef Q_OS_SYMBIAN +char BTADDRESS[] = "00:09:DD:50:93:DD"; +static const QString testfile("c:\\data\\testdata.txt"); +#else +char BTADDRESS[] = "00:00:00:00:00:00"; +#endif + +static const int MaxConnectTime = 60 * 1000; // 1 minute in ms + +class tst_QBluetoothTransferManager : public QObject +{ + Q_OBJECT + +public: + tst_QBluetoothTransferManager(); + ~tst_QBluetoothTransferManager(); + +private slots: + void initTestCase(); + + void tst_construction(); + + void tst_put_data(); + void tst_put(); + + void tst_putAbort_data(); + void tst_putAbort(); + + void tst_attribute_data(); + void tst_attribute(); + + void tst_operation_data(); + void tst_operation(); + + void tst_manager_data(); + void tst_manager(); + +public slots: + void serviceDiscovered(const QBluetoothServiceInfo &info); + void finished(); + void error(QBluetoothServiceDiscoveryAgent::Error error); +private: + bool done_discovery; +}; + +tst_QBluetoothTransferManager::tst_QBluetoothTransferManager() +{ +} + +tst_QBluetoothTransferManager::~tst_QBluetoothTransferManager() +{ +} + +void tst_QBluetoothTransferManager::initTestCase() +{ + // start Bluetooth if not started + QBluetoothLocalDevice *device = new QBluetoothLocalDevice(); + device->powerOn(); + delete device; + +#ifndef Q_OS_SYMBIAN + // Go find an echo server for BTADDRESS + QBluetoothServiceDiscoveryAgent *sda = new QBluetoothServiceDiscoveryAgent(this); + connect(sda, SIGNAL(serviceDiscovered(QBluetoothServiceInfo)), this, SLOT(serviceDiscovered(QBluetoothServiceInfo))); + connect(sda, SIGNAL(error(QBluetoothServiceDiscoveryAgent::Error)), this, SLOT(error(QBluetoothServiceDiscoveryAgent::Error))); + connect(sda, SIGNAL(finished()), this, SLOT(finished())); + + qDebug() << "Starting discovery"; + done_discovery = false; + memset(BTADDRESS, 0, 18); + + sda->setUuidFilter(QBluetoothUuid(QString(ECHO_SERVICE_UUID))); + sda->start(QBluetoothServiceDiscoveryAgent::MinimalDiscovery); + + int connectTime = MaxConnectTime; + while (!done_discovery) { + QTest::qWait(1000); + connectTime -= 1000; + } + + sda->stop(); + + if (BTADDRESS[0] == 0) { + QFAIL("Unable to find test service"); + } + delete sda; +#endif +} +void tst_QBluetoothTransferManager::error(QBluetoothServiceDiscoveryAgent::Error error) +{ + qDebug() << "Received error" << error; +// done_discovery = true; +} + +void tst_QBluetoothTransferManager::finished() +{ + qDebug() << "Finished"; + done_discovery = true; +} + +void tst_QBluetoothTransferManager::serviceDiscovered(const QBluetoothServiceInfo &info) +{ + qDebug() << "Found: " << info.device().name() << info.serviceUuid(); + strcpy(BTADDRESS, info.device().address().toString().toAscii()); + done_discovery = true; +} + +void tst_QBluetoothTransferManager::tst_construction() +{ + QBluetoothTransferManager *manager = new QBluetoothTransferManager(); + + QVERIFY(manager); + delete manager; +} + +void tst_QBluetoothTransferManager::tst_put_data() +{ + QTest::addColumn<QBluetoothAddress>("address"); + QTest::addColumn<QMap<int, QVariant> >("parameters"); + + QMap<int, QVariant> inparameters; + inparameters.insert((int)QBluetoothTransferRequest::DescriptionAttribute, "Desciption"); + inparameters.insert((int)QBluetoothTransferRequest::LengthAttribute, QVariant(1024)); + inparameters.insert((int)QBluetoothTransferRequest::TypeAttribute, "OPP"); + + QTest::newRow("0x000000 COD") << QBluetoothAddress(BTADDRESS) << inparameters; +} + +void tst_QBluetoothTransferManager::tst_put() +{ + QFETCH(QBluetoothAddress, address); + QFETCH(tst_QBluetoothTransferManager_QParameterMap, parameters); + + QBluetoothTransferRequest transferRequest(address); + + foreach (int key, parameters.keys()) { + transferRequest.setAttribute((QBluetoothTransferRequest::Attribute)key, parameters[key]); + } + + QBluetoothTransferManager manager; + +#ifdef Q_OS_SYMBIAN + { + QFile fileToWrite(testfile); + if (!fileToWrite.open(QIODevice::WriteOnly | QIODevice::Text)) + return; + + QTextStream out(&fileToWrite); + out << "This_is_testdata!!!"; + fileToWrite.close(); + } + + QFile file(testfile); + if (!file.exists()) + return; + + QBluetoothTransferReply *reply = manager.put(transferRequest, &file); + int connectTime = MaxConnectTime; + + QSignalSpy finishedSpy(&manager, SIGNAL(finished(QBluetoothTransferReply*))); + while (finishedSpy.count() == 0 && connectTime > 0) { + QTest::qWait(1000); + connectTime -= 1000; + } + QCOMPARE(finishedSpy.count(), 1); + + int error = reply->error(); + qDebug()<<"QtMobilityBtTester::SendData reply->error ="<<error; + QVERIFY(error == QBluetoothTransferReply::NoError); + + if (error != QBluetoothTransferReply::NoError) { + qDebug() << "Failed to send file"; + } + delete reply; + file.close(); +#endif +} + +void tst_QBluetoothTransferManager::tst_putAbort_data() +{ + QTest::addColumn<QBluetoothAddress>("address"); + QTest::addColumn<QMap<int, QVariant> >("parameters"); + + QMap<int, QVariant> inparameters; + inparameters.insert((int)QBluetoothTransferRequest::DescriptionAttribute, "Desciption"); + inparameters.insert((int)QBluetoothTransferRequest::LengthAttribute, QVariant(1024)); + inparameters.insert((int)QBluetoothTransferRequest::TypeAttribute, "OPP"); + + QTest::newRow("0x000000 COD") << QBluetoothAddress(BTADDRESS) << inparameters; +} + +void tst_QBluetoothTransferManager::tst_putAbort() +{ + QFETCH(QBluetoothAddress, address); + QFETCH(tst_QBluetoothTransferManager_QParameterMap, parameters); + + QBluetoothTransferRequest transferRequest(address); + + foreach (int key, parameters.keys()) { + transferRequest.setAttribute((QBluetoothTransferRequest::Attribute)key, parameters[key]); + } + + QBluetoothTransferManager manager; + +#ifdef Q_OS_SYMBIAN + { + QFile fileToWrite(testfile); + if (!fileToWrite.open(QIODevice::WriteOnly | QIODevice::Text)) + return; + + QTextStream out(&fileToWrite); + out << "This_is_testdata!!!"; + fileToWrite.close(); + } + + QFile file(testfile); + if (!file.exists()) + return; + + QBluetoothTransferReply *reply = manager.put(transferRequest, &file); + reply->abort(); + + int error = reply->error(); + qDebug()<<"QtMobilityBtTester::SendData reply->error ="<<error; + QVERIFY(error == QBluetoothTransferReply::NoError); + + if (error != QBluetoothTransferReply::NoError) { + qDebug() << "Failed to send file"; + } + delete reply; + file.close(); +#endif +} + +void tst_QBluetoothTransferManager::tst_attribute_data() +{ + QTest::addColumn<QBluetoothAddress>("address"); + QTest::addColumn<QMap<int, QVariant> >("parameters"); + + QMap<int, QVariant> inparameters; + inparameters.insert((int)QBluetoothTransferRequest::DescriptionAttribute, "Desciption"); + inparameters.insert((int)QBluetoothTransferRequest::LengthAttribute, QVariant(1024)); + inparameters.insert((int)QBluetoothTransferRequest::TypeAttribute, "OPP"); + + QTest::newRow("0x000000 COD") << QBluetoothAddress(BTADDRESS) << inparameters; +} + +void tst_QBluetoothTransferManager::tst_attribute() +{ + QFETCH(QBluetoothAddress, address); + QFETCH(tst_QBluetoothTransferManager_QParameterMap, parameters); + + QBluetoothTransferRequest transferRequest(address); + + foreach (int key, parameters.keys()) { + transferRequest.setAttribute((QBluetoothTransferRequest::Attribute)key, parameters[key]); + } + + QBluetoothTransferManager manager; + +#ifdef Q_OS_SYMBIAN + { + QFile fileToWrite(testfile); + if (!fileToWrite.open(QIODevice::WriteOnly | QIODevice::Text)) + return; + + QTextStream out(&fileToWrite); + out << "This_is_testdata!!!"; + fileToWrite.close(); + } + + QFile file(testfile); + if (!file.exists()) + return; + + QBluetoothTransferReply *reply = manager.put(transferRequest, &file); + reply->abort(); + + QVERIFY(reply->attribute(QBluetoothTransferRequest::DescriptionAttribute) == QVariant("Desciption")); + QVERIFY(reply->attribute(QBluetoothTransferRequest::LengthAttribute) == QVariant("1024")); + QVERIFY(reply->attribute(QBluetoothTransferRequest::TypeAttribute) == QVariant("OPP")); + + delete reply; + file.close(); +#endif +} + +void tst_QBluetoothTransferManager::tst_operation_data() +{ + QTest::addColumn<QBluetoothAddress>("address"); + + QTest::newRow("0x000000 COD") << QBluetoothAddress(BTADDRESS); +} + +void tst_QBluetoothTransferManager::tst_operation() +{ + QFETCH(QBluetoothAddress, address); + + QBluetoothTransferRequest transferRequest(address); + QBluetoothTransferManager manager; +#ifdef Q_OS_SYMBIAN + { + QFile fileToWrite(testfile); + if (!fileToWrite.open(QIODevice::WriteOnly | QIODevice::Text)) + return; + + QTextStream out(&fileToWrite); + out << "This_is_testdata!!!"; + fileToWrite.close(); + } + + QFile file(testfile); + if (!file.exists()) + return; + + QBluetoothTransferReply *reply = manager.put(transferRequest, &file); + + QVERIFY(reply->operation() == QBluetoothTransferManager::PutOperation); + + delete reply; + file.close(); +#endif +} + +void tst_QBluetoothTransferManager::tst_manager_data() +{ + QTest::addColumn<QBluetoothAddress>("address"); + + QTest::newRow("0x000000 COD") << QBluetoothAddress(BTADDRESS); +} + +void tst_QBluetoothTransferManager::tst_manager() +{ + QFETCH(QBluetoothAddress, address); + + QBluetoothTransferRequest transferRequest(address); + QBluetoothTransferManager manager; +#ifdef Q_OS_SYMBIAN + { + QFile fileToWrite(testfile); + if (!fileToWrite.open(QIODevice::WriteOnly | QIODevice::Text)) + return; + + QTextStream out(&fileToWrite); + out << "This_is_testdata!!!"; + fileToWrite.close(); + } + + QFile file(testfile); + if (!file.exists()) + return; + + QBluetoothTransferReply *reply = manager.put(transferRequest, &file); + + QVERIFY(reply->manager() == &manager); + + delete reply; + file.close(); +#endif +} + +QTEST_MAIN(tst_QBluetoothTransferManager) + +#include "tst_qbluetoothtransfermanager.moc" diff --git a/tests/auto/qbluetoothtransferrequest/qbluetoothtransferrequest.pro b/tests/auto/qbluetoothtransferrequest/qbluetoothtransferrequest.pro new file mode 100644 index 00000000..7b9ec0b0 --- /dev/null +++ b/tests/auto/qbluetoothtransferrequest/qbluetoothtransferrequest.pro @@ -0,0 +1,7 @@ +SOURCES += tst_qbluetoothtransferrequest.cpp +TARGET=tst_qbluetoothtransferrequest +CONFIG += testcase + +QT = core bluetooth testlib + +symbian: TARGET.CAPABILITY = ReadDeviceData LocalServices WriteDeviceData diff --git a/tests/auto/qbluetoothtransferrequest/tst_qbluetoothtransferrequest.cpp b/tests/auto/qbluetoothtransferrequest/tst_qbluetoothtransferrequest.cpp new file mode 100644 index 00000000..4805d794 --- /dev/null +++ b/tests/auto/qbluetoothtransferrequest/tst_qbluetoothtransferrequest.cpp @@ -0,0 +1,173 @@ +/**************************************************************************** +** +** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the Qt Mobility Components. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include <QtTest/QtTest> + +#include <QDebug> +#include <QMap> + +#include <qbluetoothtransferrequest.h> +#include <qbluetoothaddress.h> +#include <qbluetoothlocaldevice.h> + +typedef QMap<int,QVariant> tst_QBluetoothTransferRequest_QParameterMap; +Q_DECLARE_METATYPE(tst_QBluetoothTransferRequest_QParameterMap) + +class tst_QBluetoothTransferRequest : public QObject +{ + Q_OBJECT + +public: + tst_QBluetoothTransferRequest(); + ~tst_QBluetoothTransferRequest(); + +private slots: + void initTestCase(); + + void tst_construction_data(); + void tst_construction(); + + void tst_assignment_data(); + void tst_assignment(); +}; + +tst_QBluetoothTransferRequest::tst_QBluetoothTransferRequest() +{ +} + +tst_QBluetoothTransferRequest::~tst_QBluetoothTransferRequest() +{ +} + +void tst_QBluetoothTransferRequest::initTestCase() +{ + // start Bluetooth if not started + QBluetoothLocalDevice *device = new QBluetoothLocalDevice(); + device->powerOn(); + delete device; +} + +void tst_QBluetoothTransferRequest::tst_construction_data() +{ + QTest::addColumn<QBluetoothAddress>("address"); + QTest::addColumn<QMap<int, QVariant> >("parameters"); + + QMap<int, QVariant> inparameters; + inparameters.insert((int)QBluetoothTransferRequest::DescriptionAttribute, "Desciption"); + inparameters.insert((int)QBluetoothTransferRequest::LengthAttribute, QVariant(1024)); + inparameters.insert((int)QBluetoothTransferRequest::TypeAttribute, "OPP"); + + QTest::newRow("0x000000 COD") << QBluetoothAddress("000000000000") << inparameters; + QTest::newRow("0x000100 COD") << QBluetoothAddress("000000000000") << inparameters; + QTest::newRow("0x000104 COD") << QBluetoothAddress("000000000000") << inparameters; + QTest::newRow("0x000118 COD") << QBluetoothAddress("000000000000") << inparameters; + QTest::newRow("0x000200 COD") << QBluetoothAddress("000000000000") << inparameters; +} + +void tst_QBluetoothTransferRequest::tst_construction() +{ + QFETCH(QBluetoothAddress, address); + QFETCH(tst_QBluetoothTransferRequest_QParameterMap, parameters); + + QBluetoothTransferRequest transferRequest(address); + + foreach (int key, parameters.keys()) { + transferRequest.setAttribute((QBluetoothTransferRequest::Attribute)key, parameters[key]); + QCOMPARE(parameters[key], transferRequest.attribute((QBluetoothTransferRequest::Attribute)key)); + } + + QCOMPARE(transferRequest.address(), address); + + QBluetoothTransferRequest copyRequest(transferRequest); + + QCOMPARE(copyRequest.address(), address); + QCOMPARE(transferRequest, copyRequest); +} + +void tst_QBluetoothTransferRequest::tst_assignment_data() +{ + tst_construction_data(); +} + +void tst_QBluetoothTransferRequest::tst_assignment() +{ + QFETCH(QBluetoothAddress, address); + QFETCH(tst_QBluetoothTransferRequest_QParameterMap, parameters); + + QBluetoothTransferRequest transferRequest(address); + + foreach (int key, parameters.keys()) { + transferRequest.setAttribute((QBluetoothTransferRequest::Attribute)key, parameters[key]); + } + + { + QBluetoothTransferRequest copyRequest = transferRequest; + + QCOMPARE(copyRequest.address(), address); + QCOMPARE(transferRequest, copyRequest); + } + + { + QBluetoothTransferRequest copyRequest(QBluetoothAddress("000000000001")); + + copyRequest = transferRequest; + + QCOMPARE(copyRequest.address(), address); + QCOMPARE(transferRequest, copyRequest); + } + + { + QBluetoothTransferRequest copyRequest1(QBluetoothAddress("000000000001")); + QBluetoothTransferRequest copyRequest2(QBluetoothAddress("000000000001")); + + copyRequest1 = copyRequest2 = transferRequest; + + QCOMPARE(copyRequest1.address(), address); + QCOMPARE(copyRequest2.address(), address); + QCOMPARE(transferRequest, copyRequest1); + QCOMPARE(transferRequest, copyRequest2); + + } +} + +QTEST_MAIN(tst_QBluetoothTransferRequest) + +#include "tst_qbluetoothtransferrequest.moc" diff --git a/tests/auto/qbluetoothuuid/qbluetoothuuid.pro b/tests/auto/qbluetoothuuid/qbluetoothuuid.pro new file mode 100644 index 00000000..445940a8 --- /dev/null +++ b/tests/auto/qbluetoothuuid/qbluetoothuuid.pro @@ -0,0 +1,9 @@ +SOURCES += tst_qbluetoothuuid.cpp +TARGET = tst_qbluetoothuuid +CONFIG += testcase + +QT = core bluetooth testlib + +symbian: { + LIBS *= -lbluetooth +} diff --git a/tests/auto/qbluetoothuuid/tst_qbluetoothuuid.cpp b/tests/auto/qbluetoothuuid/tst_qbluetoothuuid.cpp new file mode 100644 index 00000000..0c4308da --- /dev/null +++ b/tests/auto/qbluetoothuuid/tst_qbluetoothuuid.cpp @@ -0,0 +1,437 @@ +/**************************************************************************** +** +** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the Qt Mobility Components. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include <QtTest/QtTest> +#include <QUuid> + +#include <QDebug> + +#include <qbluetoothuuid.h> + +#include <arpa/inet.h> +#include <netinet/in.h> +#ifdef Q_OS_SYMBIAN +//needed for symbian uuid conversion test +#include <bttypes.h> +#endif + +Q_DECLARE_METATYPE(quint128) + +class tst_QBluetoothUuid : public QObject +{ + Q_OBJECT + +public: + tst_QBluetoothUuid(); + ~tst_QBluetoothUuid(); + +private slots: + void initTestCase(); + + void tst_construction(); + void tst_assignment(); + void tst_conversion_data(); + void tst_conversion(); + void tst_comparison_data(); + void tst_comparison(); +#ifdef Q_OS_SYMBIAN + void tst_symbian_uuid_tranformation_data(); + void tst_symbian_uuid_tranformation(); +#endif +}; + +tst_QBluetoothUuid::tst_QBluetoothUuid() +{ + qRegisterMetaType<quint128>("quint128"); +} + +tst_QBluetoothUuid::~tst_QBluetoothUuid() +{ +} + +void tst_QBluetoothUuid::initTestCase() +{ +} + +void tst_QBluetoothUuid::tst_construction() +{ + { + QBluetoothUuid nullUuid; + + QVERIFY(nullUuid.isNull()); + } + + { + QBluetoothUuid uuid(QBluetoothUuid::PublicBrowseGroup); + + QVERIFY(!uuid.isNull()); + + bool ok; + quint16 uuid16; + + uuid16 = uuid.toUInt16(&ok); + + QVERIFY(ok); + QCOMPARE(uuid16, static_cast<quint16>(QBluetoothUuid::PublicBrowseGroup)); + } + + { + QBluetoothUuid uuid(QBluetoothUuid::PublicBrowseGroup); + + QBluetoothUuid copy(uuid); + + QCOMPARE(uuid.toUInt16(), copy.toUInt16()); + } + + { + QBluetoothUuid uuid(QBluetoothUuid::L2cap); + + QVERIFY(!uuid.isNull()); + + bool ok; + quint16 uuid16; + + uuid16 = uuid.toUInt16(&ok); + + QVERIFY(ok); + QCOMPARE(uuid16, static_cast<quint16>(QBluetoothUuid::L2cap)); + } + + { + QUuid uuid(0x67c8770b, 0x44f1, 0x410a, 0xab, 0x9a, 0xf9, 0xb5, 0x44, 0x6f, 0x13, 0xee); + QBluetoothUuid btUuid(uuid); + QVERIFY(!btUuid.isNull()); + + QString uuidString(btUuid.toString()); + QVERIFY(!uuidString.isEmpty()); + QCOMPARE(uuidString, QString("{67c8770b-44f1-410a-ab9a-f9b5446f13ee}")); + } + + { + QBluetoothUuid btUuid(QString("67c8770b-44f1-410a-ab9a-f9b5446f13ee")); + QVERIFY(!btUuid.isNull()); + + QString uuidString(btUuid.toString()); + QVERIFY(!uuidString.isEmpty()); + QCOMPARE(uuidString, QString("{67c8770b-44f1-410a-ab9a-f9b5446f13ee}")); + } + + { + QBluetoothUuid btUuid(QString("XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX")); + QVERIFY(btUuid.isNull()); + } +} + +void tst_QBluetoothUuid::tst_assignment() +{ + QBluetoothUuid uuid(QBluetoothUuid::PublicBrowseGroup); + + { + QBluetoothUuid copy = uuid; + + QCOMPARE(uuid.toUInt16(), copy.toUInt16()); + } + + { + QBluetoothUuid copy1; + QBluetoothUuid copy2; + + QVERIFY(copy1.isNull()); + QVERIFY(copy2.isNull()); + + copy1 = copy2 = uuid; + + QVERIFY(!copy1.isNull()); + QVERIFY(!copy2.isNull()); + + QCOMPARE(uuid.toUInt16(), copy1.toUInt16()); + QCOMPARE(uuid.toUInt16(), copy2.toUInt16()); + } +} + +#define BASEUUID "-0000-1000-8000-00805F9B34FB" + +#define UUID128_32(x, a, b, c, d) \ + quint128 x = { \ + { \ + a, b, c, d, \ + 0x00, 0x00, \ + 0x10, 0x00, \ + 0x80, 0x00, \ + 0x00, 0x80, 0x5F, 0x9B, 0x34, 0xFB \ + } \ + } + +#define UUID128_16(x, a, b) UUID128_32(x, 0, 0, a, b) + +#define NEWROW16(text, a, b, s) \ +do { \ + UUID128_16(uuid128, a, b); \ + quint32 uuid32 = a << 8 | b; \ + quint16 uuid16 = a << 8 | b; \ + QTest::newRow(text) << true << uuid16 << true << uuid32 << true << uuid128 \ + << (QLatin1Char('{') + QLatin1String(s) + QLatin1Char('}')); \ +} while (0) + +#define NEWROW32(text, a, b, c, d, s) \ +do { \ + UUID128_32(uuid128, a, b, c, d); \ + quint32 uuid32 = a << 24 | b << 16 | c << 8 | d; \ + quint16 uuid16; \ + bool constructUuid16 = (a == 0) && (b == 0); \ + if (constructUuid16) \ + uuid16 = c << 8 | d; \ + else \ + uuid16 = 0; \ + QTest::newRow(text) << constructUuid16 << uuid16 << true << uuid32 << true << uuid128 \ + << (QLatin1Char('{') + QLatin1String(s) + QLatin1Char('}')); \ +} while (0) + +void tst_QBluetoothUuid::tst_conversion_data() +{ + QTest::addColumn<bool>("constructUuid16"); + QTest::addColumn<quint16>("uuid16"); + QTest::addColumn<bool>("constructUuid32"); + QTest::addColumn<quint32>("uuid32"); + QTest::addColumn<bool>("constructUuid128"); + QTest::addColumn<quint128>("uuid128"); + QTest::addColumn<QString>("uuidS"); + + NEWROW32("base uuid", 0x00, 0x00, 0x00, 0x00, "00000000" BASEUUID); + NEWROW16("0x0001", 0x00, 0x01, "00000001" BASEUUID); + NEWROW16("0xffff", 0xff, 0xff, "0000FFFF" BASEUUID); + NEWROW32("0x00010000", 0x00, 0x01, 0x00, 0x00, "00010000" BASEUUID); + NEWROW32("0x0001ffff", 0x00, 0x01, 0xff, 0xff, "0001FFFF" BASEUUID); + NEWROW32("0xffff0000", 0xff, 0xff, 0x00, 0x00, "FFFF0000" BASEUUID); + NEWROW32("0xffffffff", 0xff, 0xff, 0xff, 0xff, "FFFFFFFF" BASEUUID); + + { + quint128 uuid128 = { + { + 0x00, 0x11, 0x22, 0x33, + 0x44, 0x55, + 0x66, 0x77, + 0x88, 0x99, + 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff + } + }; + + QTest::newRow("00112233-4455-6677-8899-AABBCCDDEEFF") + << false << quint16(0) << false << quint32(0) << true << uuid128 + << QString(QLatin1String("{00112233-4455-6677-8899-AABBCCDDEEFF}")); + } +} + +void tst_QBluetoothUuid::tst_conversion() +{ + QFETCH(bool, constructUuid16); + QFETCH(quint16, uuid16); + QFETCH(bool, constructUuid32); + QFETCH(quint32, uuid32); + QFETCH(bool, constructUuid128); + QFETCH(quint128, uuid128); + QFETCH(QString, uuidS); + + int minimumSize = 16; + if (constructUuid16) + minimumSize = 2; + else if (constructUuid32) + minimumSize = 4; + + if (constructUuid16) { + QBluetoothUuid uuid(uuid16); + + bool ok; + + QCOMPARE(uuid.toUInt16(&ok), uuid16); + QVERIFY(ok); + + QCOMPARE(uuid.toUInt32(&ok), uuid32); + QVERIFY(ok); + + QVERIFY(memcmp(uuid.toUInt128().data, uuid128.data, 16) == 0); + + QCOMPARE(uuid.toString().toUpper(), uuidS.toUpper()); + + QCOMPARE(uuid.minimumSize(), minimumSize); + } + + if (constructUuid32) { + QBluetoothUuid uuid(uuid32); + + bool ok; + + quint16 tmp = uuid.toUInt16(&ok); + QCOMPARE(ok, constructUuid16); + if (ok) { + QCOMPARE(tmp, uuid16); + } + + QCOMPARE(uuid.toUInt32(&ok), uuid32); + QVERIFY(ok); + + QVERIFY(memcmp(uuid.toUInt128().data, uuid128.data, 16) == 0); + + QCOMPARE(uuid.toString().toUpper(), uuidS.toUpper()); + + QCOMPARE(uuid.minimumSize(), minimumSize); + } + + if (constructUuid128) { + QBluetoothUuid uuid(uuid128); + + bool ok; + + quint16 tmpUuid16 = uuid.toUInt16(&ok); + QCOMPARE(ok, constructUuid16); + if (ok) + QCOMPARE(tmpUuid16, uuid16); + + quint32 tmpUuid32 = uuid.toUInt32(&ok); + QCOMPARE(ok, constructUuid32); + if (ok) + QCOMPARE(tmpUuid32, uuid32); + + QVERIFY(memcmp(uuid.toUInt128().data, uuid128.data, 16) == 0); + + QCOMPARE(uuid.toString().toUpper(), uuidS.toUpper()); + + QCOMPARE(uuid.minimumSize(), minimumSize); + } +} + +void tst_QBluetoothUuid::tst_comparison_data() +{ + tst_conversion_data(); +} + +void tst_QBluetoothUuid::tst_comparison() +{ + QFETCH(bool, constructUuid16); + QFETCH(quint16, uuid16); + QFETCH(bool, constructUuid32); + QFETCH(quint32, uuid32); + QFETCH(bool, constructUuid128); + QFETCH(quint128, uuid128); + + QVERIFY(QBluetoothUuid() == QBluetoothUuid()); + + if (constructUuid16) { + QBluetoothUuid quuid16(uuid16); + QBluetoothUuid quuid32(uuid32); + QBluetoothUuid quuid128(uuid128); + + QVERIFY(quuid16.toUInt16() == uuid16); + QVERIFY(quuid16.toUInt32() == uuid32); + + QVERIFY(quuid16 == quuid32); + QVERIFY(quuid16 == quuid128); + + QVERIFY(quuid32 == quuid16); + QVERIFY(quuid128 == quuid16); + } + + if (constructUuid32) { + QBluetoothUuid quuid32(uuid32); + QBluetoothUuid quuid128(uuid128); + + QVERIFY(quuid32.toUInt32() == uuid32); + QVERIFY(quuid32 == quuid128); + + QVERIFY(quuid128 == quuid32); + } + + if (constructUuid128) { + QBluetoothUuid quuid128(uuid128); + + for (int var = 0; var < 16; ++var) { + QVERIFY(quuid128.toUInt128().data[var] == uuid128.data[var]); + } + } +} +#ifdef Q_OS_SYMBIAN +void tst_QBluetoothUuid::tst_symbian_uuid_tranformation_data() +{ + tst_conversion_data(); +} + +void tst_QBluetoothUuid::tst_symbian_uuid_tranformation() +{ + QFETCH(quint128, uuid128); + + QBluetoothUuid quuid128(uuid128); + + for (int var = 0; var < 16; ++var) { + QVERIFY(quuid128.toUInt128().data[var] == uuid128.data[var]); + } + + if (quuid128.minimumSize() == 2) { + TUUID sUuid(quuid128.toUInt16()); + QBluetoothUuid fromSymbianUuid(ntohs(*reinterpret_cast<const quint16 *>(sUuid.Des().Ptr()))); + QCOMPARE(quuid128, fromSymbianUuid); + //qDebug()<<"sUuid size ="<<sUuid.Des().Length() ; + } else if (quuid128.minimumSize() == 4) { + TUUID sUuid(quuid128.toUInt32()); + QBluetoothUuid fromSymbianUuid(ntohl(*reinterpret_cast<const quint32 *>(sUuid.Des().Ptr()))); + QCOMPARE(quuid128, fromSymbianUuid); + //qDebug()<<"sUuid size ="<<sUuid.Des().Length() ; + } else if (quuid128.minimumSize()==16) { + + TUint32 *dataPointer = (TUint32*)quuid128.toUInt128().data; + TUint32 hH = qToBigEndian<quint32>(*(dataPointer++)); + TUint32 hL = qToBigEndian<quint32>(*(dataPointer++)); + TUint32 lH = qToBigEndian<quint32>(*(dataPointer++)); + TUint32 lL = qToBigEndian<quint32>(*(dataPointer)); + TUUID sUuid(hH, hL, lH, lL); + //qDebug()<<"sUuid size ="<<sUuid.Des().Length() ; + //qDebug()<<"sUuid longsize ="<<sUuid.LongForm().Length() ; + + for (int var = 0; var < sUuid.Des().Length(); ++var) { + //qDebug()<<"sUuid at ="<<var<<"="<<sUuid.Des()[var] ; + //qDebug()<<"quuid128 at ="<<var<<"="<<quuid128.toUInt128().data[var] ; + QVERIFY(quuid128.toUInt128().data[var] == sUuid.Des()[var]); + } + } +} +#endif //Q_OS_SYMBIAN +QTEST_MAIN(tst_QBluetoothUuid) + +#include "tst_qbluetoothuuid.moc" diff --git a/tests/auto/qconnectivitytestcommon.h b/tests/auto/qconnectivitytestcommon.h new file mode 100644 index 00000000..e2a6f748 --- /dev/null +++ b/tests/auto/qconnectivitytestcommon.h @@ -0,0 +1,100 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the Qt Mobility Components. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QCONNECTIVITYTESTCOMMON_H +#define QCONNECTIVITYTESTCOMMON_H + +// Wait for __expr to happen, while still allowing events to be processed. +#define QTRY_NOOP(__expr) \ + do { \ + const int __step = 50; \ + const int __timeout = 15000; \ + if (!(__expr)) { \ + QTest::qWait(0); \ + } \ + for (int __i = 0; __i < __timeout && !(__expr); __i+=__step) { \ + QTest::qWait(__step); \ + } \ + } while (0) + +// Will try to wait for the condition while allowing event processing +#define QTRY_VERIFY(__expr) \ + do { \ + const int __step = 50; \ + const int __timeout = 5000; \ + if (!(__expr)) { \ + QTest::qWait(0); \ + } \ + for (int __i = 0; __i < __timeout && !(__expr); __i+=__step) { \ + QTest::qWait(__step); \ + } \ + QVERIFY(__expr); \ + } while (0) + +// Will try to wait for the condition while allowing event processing +#define QTRY_VERIFY_TIMEOUT(__timeout, __expr) \ + do { \ + const int __step = 50; \ + if (!(__expr)) { \ + QTest::qWait(0); \ + } \ + for (int __i = 0; __i < __timeout && !(__expr); __i+=__step) { \ + QTest::qWait(__step); \ + } \ + QVERIFY(__expr); \ + } while (0) + +// Will try to wait for the condition while allowing event processing +#define QTRY_COMPARE(__expr, __expected) \ + do { \ + const int __step = 50; \ + const int __timeout = 5000; \ + if ((__expr) != (__expected)) { \ + QTest::qWait(0); \ + } \ + for (int __i = 0; __i < __timeout && ((__expr) != (__expected)); __i+=__step) { \ + QTest::qWait(__step); \ + } \ + QCOMPARE(__expr, __expected); \ + } while (0) + +#endif + diff --git a/tests/auto/ql2capserver/ql2capserver.pro b/tests/auto/ql2capserver/ql2capserver.pro new file mode 100644 index 00000000..ecd8cef3 --- /dev/null +++ b/tests/auto/ql2capserver/ql2capserver.pro @@ -0,0 +1,7 @@ +SOURCES += tst_ql2capserver.cpp +TARGET = tst_ql2capserver +CONFIG += testcase + +QT = core bluetooth testlib + +symbian: TARGET.CAPABILITY = LocalServices NetworkControl diff --git a/tests/auto/ql2capserver/tst_ql2capserver.cpp b/tests/auto/ql2capserver/tst_ql2capserver.cpp new file mode 100644 index 00000000..54d99117 --- /dev/null +++ b/tests/auto/ql2capserver/tst_ql2capserver.cpp @@ -0,0 +1,283 @@ +/**************************************************************************** +** +** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the Qt Mobility Components. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include <QtTest/QtTest> + +#include <QDebug> + +#include <ql2capserver.h> +#include <qbluetoothsocket.h> + +Q_DECLARE_METATYPE(QBluetooth::SecurityFlags); + +// Max time to wait for connection +static const int MaxConnectTime = 60 * 1000; // 1 minute in ms + +class tst_QL2capServer : public QObject +{ + Q_OBJECT + +public: + tst_QL2capServer(); + ~tst_QL2capServer(); + +private slots: + void initTestCase(); + + void tst_construction(); + + void tst_listen_data(); + void tst_listen(); + + void tst_pendingConnections_data(); + void tst_pendingConnections(); + + void tst_receive_data(); + void tst_receive(); + + void tst_secureFlags(); +}; + +tst_QL2capServer::tst_QL2capServer() +{ +} + +tst_QL2capServer::~tst_QL2capServer() +{ +} + +void tst_QL2capServer::initTestCase() +{ + qRegisterMetaType<QBluetooth::SecurityFlags>("QBluetooth::SecurityFlags"); +} + +void tst_QL2capServer::tst_construction() +{ + { + QL2capServer server; + + QVERIFY(!server.isListening()); + QCOMPARE(server.maxPendingConnections(), 1); + QVERIFY(!server.hasPendingConnections()); + QVERIFY(server.nextPendingConnection() == 0); + QVERIFY(server.serverAddress().isNull()); + QCOMPARE(server.serverPort(), quint16(24160)); + } +} + +void tst_QL2capServer::tst_listen_data() +{ + QTest::addColumn<QBluetoothAddress>("address"); + QTest::addColumn<quint16>("port"); + + QTest::newRow("default") << QBluetoothAddress() << quint16(0); + QTest::newRow("specified address") << QBluetoothAddress("00:11:B1:08:AD:B8") << quint16(0); + QTest::newRow("specified port") << QBluetoothAddress() << quint16(24160); + QTest::newRow("specified address/port") << QBluetoothAddress("00:11:B1:08:AD:B8") << quint16(10); +} + +void tst_QL2capServer::tst_listen() +{ + QFETCH(QBluetoothAddress, address); + QFETCH(quint16, port); + + { + QL2capServer server; + + bool result = server.listen(address, port); + + QVERIFY(result); + QVERIFY(server.isListening()); + + if (!address.isNull()) + QCOMPARE(server.serverAddress(), address); + else + QVERIFY(!server.serverAddress().isNull()); + + if (port != 0) + QCOMPARE(server.serverPort(), port); + else + QVERIFY(server.serverPort() != 0); + + QCOMPARE(server.maxPendingConnections(), 1); + + QVERIFY(!server.hasPendingConnections()); + QVERIFY(server.nextPendingConnection() == 0); + + server.close(); + + QVERIFY(!server.isListening()); + + QVERIFY(server.serverAddress().isNull()); + QVERIFY(server.serverPort() == 0); + + QVERIFY(!server.hasPendingConnections()); + QVERIFY(server.nextPendingConnection() == 0); + } +} + +void tst_QL2capServer::tst_pendingConnections_data() +{ + QTest::addColumn<int>("maxConnections"); + + QTest::newRow("1 connection") << 1; + //QTest::newRow("2 connections") << 2; +} + +void tst_QL2capServer::tst_pendingConnections() +{ + QFETCH(int, maxConnections); + + { + QL2capServer server; + + server.setMaxPendingConnections(maxConnections); + + bool result = server.listen(); + + QVERIFY(result); + QVERIFY(server.isListening()); + + qDebug() << "Listening on L2CAP channel:" << server.serverPort(); + + QCOMPARE(server.maxPendingConnections(), maxConnections); + + QVERIFY(!server.hasPendingConnections()); + QVERIFY(server.nextPendingConnection() == 0); + + { + /* wait for maxConnections simultaneous connections */ + qDebug() << "Waiting for" << maxConnections << "simultaneous connections."; + + QSignalSpy connectionSpy(&server, SIGNAL(newConnection())); + + int connectTime = MaxConnectTime; + while (connectionSpy.count() < maxConnections && connectTime > 0) { + QTest::qWait(1000); + connectTime -= 1000; + } + + QList<QBluetoothSocket *> sockets; + while (server.hasPendingConnections()) + sockets.append(server.nextPendingConnection()); + + QCOMPARE(connectionSpy.count(), maxConnections); + QCOMPARE(sockets.count(), maxConnections); + + foreach (QBluetoothSocket *socket, sockets) { + qDebug() << socket->state(); + QVERIFY(socket->state() == QBluetoothSocket::ConnectedState); + QVERIFY(socket->openMode() == QIODevice::ReadWrite); + } + + QVERIFY(!server.hasPendingConnections()); + QVERIFY(server.nextPendingConnection() == 0); + + while (!sockets.isEmpty()) { + QBluetoothSocket *socket = sockets.takeFirst(); + socket->close(); + delete socket; + } + } + + server.close(); + } +} + +void tst_QL2capServer::tst_receive_data() +{ + QTest::addColumn<QByteArray>("expected"); + + QTest::newRow("test") << QByteArray("hello\r\n"); +} + +void tst_QL2capServer::tst_receive() +{ + QFETCH(QByteArray, expected); + + QL2capServer server; + + bool result = server.listen(); + + QVERIFY(result); + + qDebug() << "Listening on L2CAP channel:" << server.serverPort(); + + int connectTime = MaxConnectTime; + while (!server.hasPendingConnections() && connectTime > 0) { + QTest::qWait(1000); + connectTime -= 1000; + } + + QVERIFY(server.hasPendingConnections()); + + QBluetoothSocket *socket = server.nextPendingConnection(); + + QVERIFY(socket->state() == QBluetoothSocket::ConnectedState); + QVERIFY(socket->openMode() == QIODevice::ReadWrite); + + QSignalSpy readyReadSpy(socket, SIGNAL(readyRead())); + + int readyReadTime = 60000; + while (readyReadSpy.isEmpty() && readyReadTime > 0) { + QTest::qWait(1000); + readyReadTime -= 1000; + } + + QVERIFY(!readyReadSpy.isEmpty()); + + const QByteArray data = socket->readAll(); + + QCOMPARE(data, expected); +} + +void tst_QL2capServer::tst_secureFlags() +{ + QL2capServer server; + QCOMPARE(server.securityFlags(), QBluetooth::NoSecurity); + + server.setSecurityFlags(QBluetooth::Encryption); + QCOMPARE(server.securityFlags(), QBluetooth::Encryption); +} + +QTEST_MAIN(tst_QL2capServer) + +#include "tst_ql2capserver.moc" diff --git a/tests/auto/qndefmessage/qndefmessage.pro b/tests/auto/qndefmessage/qndefmessage.pro new file mode 100644 index 00000000..c1309387 --- /dev/null +++ b/tests/auto/qndefmessage/qndefmessage.pro @@ -0,0 +1,5 @@ +SOURCES += tst_qndefmessage.cpp +TARGET = tst_qndefmessage +CONFIG += testcase + +QT = core nfc testlib diff --git a/tests/auto/qndefmessage/tst_qndefmessage.cpp b/tests/auto/qndefmessage/tst_qndefmessage.cpp new file mode 100644 index 00000000..e33cc79c --- /dev/null +++ b/tests/auto/qndefmessage/tst_qndefmessage.cpp @@ -0,0 +1,419 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the Qt Mobility Components. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include <QtTest/QtTest> + +#include <qndefrecord.h> +#include <qndefmessage.h> +#include <qndefnfctextrecord.h> +#include <qndefnfcurirecord.h> + +Q_DECLARE_METATYPE(QNdefRecord) + +class tst_QNdefMessage : public QObject +{ + Q_OBJECT + +public: + tst_QNdefMessage(); + ~tst_QNdefMessage(); + +private slots: + void tst_parse_data(); + void tst_parse(); +}; + +tst_QNdefMessage::tst_QNdefMessage() +{ +} + +tst_QNdefMessage::~tst_QNdefMessage() +{ +} + +void tst_QNdefMessage::tst_parse_data() +{ + QTest::addColumn<QByteArray>("data"); + QTest::addColumn<QNdefMessage>("message"); + QTest::addColumn<QVariantList>("expectedData"); + + // empty message + { + QByteArray data; + data.append(char(0xc0)); // MB=1, ME=1 + data.append(char(0)); // TYPE LENGTH + data.append(char(0)); // PAYLOAD LENGTH 3 + data.append(char(0)); // PAYLOAD LENGTH 2 + data.append(char(0)); // PAYLOAD LENGTH 1 + data.append(char(0)); // PAYLOAD LENGTH 0 + QTest::newRow("empty") << data << QNdefMessage() << QVariantList(); + + QNdefRecord record; + record.setTypeNameFormat(QNdefRecord::Empty); + QTest::newRow("empty record") << data + << QNdefMessage(record) + << QVariantList(); + } + + // empty short message + { + QByteArray data; + data.append(char(0xd0)); // MB=1, ME=1, SR=1 + data.append(char(0)); // TYPE LENGTH + data.append(char(0)); // PAYLOAD LENGTH + QTest::newRow("empty") << data << QNdefMessage() << QVariantList(); + + QNdefRecord record; + record.setTypeNameFormat(QNdefRecord::Empty); + QTest::newRow("empty record") << data + << QNdefMessage(record) + << QVariantList(); + } + + // unknown message + { + QByteArray type("type"); + QByteArray id("id"); + QByteArray payload("payload"); + + QByteArray data; + data.append(char(0xcd)); // MB=1, ME=1, IL=1, TNF=5 + data.append(char(type.length())); // TYPE LENGTH + data.append(char((payload.length() >> 24) & 0xff)); // PAYLOAD LENGTH 3 + data.append(char((payload.length() >> 16) & 0xff)); // PAYLOAD LENGTH 2 + data.append(char((payload.length() >> 8) & 0xff)); // PAYLOAD LENGTH 1 + data.append(char((payload.length() >> 0) & 0xff)); // PAYLOAD LENGTH 0 + data.append(char(id.length())); // ID LENGTH + data.append(type); + data.append(id); + data.append(payload); + + QNdefRecord record; + record.setTypeNameFormat(QNdefRecord::Unknown); + record.setType(type); + record.setId(id); + record.setPayload(payload); + QList<QNdefRecord> recordList; + recordList.append(record); + QTest::newRow("unknown") << data << QNdefMessage(recordList) << QVariantList(); + } + + // chunked message + { + QByteArray type("type"); + QByteArray id("id"); + QByteArray payload("payload"); + + QByteArray data; + data.append(char(0xbd)); // MB=1, CF=1, SR=1, IL=1, TNF=5 + data.append(char(type.length())); // TYPE LENGTH + data.append(char(1)); // PAYLOAD LENGTH + data.append(char(id.length())); // ID LENGTH + data.append(type); // TYPE + data.append(id); // ID + data.append(payload.at(0)); // PAYLOAD[0] + + for (int i = 1; i < payload.length() - 1; ++i) { + data.append(char(0x36)); // CF=1, SR=1, TNF=6 + data.append(char(0)); // TYPE LENGTH + data.append(char(1)); // PAYLOAD LENGTH + data.append(payload.at(i)); // PAYLOAD[i] + } + + data.append(char(0x56)); // ME=1, SR=1, TNF=6 + data.append(char(0)); // TYPE LENGTH + data.append(char(1)); // PAYLOAD LENGTH + data.append(payload.at(payload.length() - 1)); // PAYLOAD[length - 1] + + QNdefRecord record; + record.setTypeNameFormat(QNdefRecord::Unknown); + record.setType(type); + record.setId(id); + record.setPayload(payload); + QList<QNdefRecord> recordList; + recordList.append(record); + QTest::newRow("chunked") << data << QNdefMessage(recordList) << QVariantList(); + } + + // NFC-RTD Text + { + QByteArray type("T"); + QByteArray payload; + payload.append(char(0x02)); // UTF-8, 2 byte language code + payload.append("en"); + payload.append("Test String"); + + QByteArray data; + data.append(char(0xc1)); // MB=1, ME=1, IL=0, TNF=1 + data.append(char(type.length())); // TYPE LENGTH + data.append(char((payload.length() >> 24) & 0xff)); // PAYLOAD LENGTH 3 + data.append(char((payload.length() >> 16) & 0xff)); // PAYLOAD LENGTH 2 + data.append(char((payload.length() >> 8) & 0xff)); // PAYLOAD LENGTH 1 + data.append(char((payload.length() >> 0) & 0xff)); // PAYLOAD LENGTH 0 + data.append(type); + data.append(payload); + + QNdefRecord record; + record.setTypeNameFormat(QNdefRecord::NfcRtd); + record.setType("T"); + record.setPayload("\002enTest String"); + QList<QNdefRecord> recordList; + recordList.append(record); + QTest::newRow("nfc-rtd text") << data << QNdefMessage(recordList) + << (QVariantList() << QLatin1String("Test String") + << QLatin1String("en")); + } + + // NFC-RTD Text + { + QByteArray type("T"); + QByteArray payload; + payload.append(char(0x02)); // UTF-8, 2 byte language code + payload.append("ja"); + payload.append(QByteArray::fromHex("e38386e382b9e38388e69687e5ad97e58897")); + + QByteArray data; + data.append(char(0xc1)); // MB=1, ME=1, IL=0, TNF=1 + data.append(char(type.length())); // TYPE LENGTH + data.append(char((payload.length() >> 24) & 0xff)); // PAYLOAD LENGTH 3 + data.append(char((payload.length() >> 16) & 0xff)); // PAYLOAD LENGTH 2 + data.append(char((payload.length() >> 8) & 0xff)); // PAYLOAD LENGTH 1 + data.append(char((payload.length() >> 0) & 0xff)); // PAYLOAD LENGTH 0 + data.append(type); + data.append(payload); + + QNdefRecord record; + record.setTypeNameFormat(QNdefRecord::NfcRtd); + record.setType("T"); + record.setPayload("\002ja" + QByteArray::fromHex("e38386e382b9e38388e69687e5ad97e58897")); + QList<QNdefRecord> recordList; + recordList.append(record); + QTest::newRow("nfc-rtd text ja") + << data << QNdefMessage(recordList) + << (QVariantList() << QString::fromUtf8("\343\203\206\343\202\271\343\203\210\346\226" + "\207\345\255\227\345\210\227") + << QLatin1String("ja")); + } + + // NFC-RTD URI + { + QByteArray type("U"); + QByteArray payload; + payload.append(char(0x00)); + payload.append("http://qt.nokia.com/"); + + QByteArray data; + data.append(char(0xc1)); + data.append(char(type.length())); + data.append(char((payload.length() >> 24) & 0xff)); // PAYLOAD LENGTH 3 + data.append(char((payload.length() >> 16) & 0xff)); // PAYLOAD LENGTH 2 + data.append(char((payload.length() >> 8) & 0xff)); // PAYLOAD LENGTH 1 + data.append(char((payload.length() >> 0) & 0xff)); // PAYLOAD LENGTH 0 + data.append(type); + data.append(payload); + + QNdefRecord record; + record.setTypeNameFormat(QNdefRecord::NfcRtd); + record.setType("U"); + record.setPayload(QByteArray("\000http://qt.nokia.com/", 21)); + QList<QNdefRecord> recordList; + recordList.append(record); + QTest::newRow("nfc-rtd uri http://qt.nokia.com/") + << data << QNdefMessage(recordList) + << (QVariantList() << QUrl(QLatin1String("http://qt.nokia.com/"))); + } + + // NFC-RTD URI + { + QByteArray type("U"); + QByteArray payload; + payload.append(char(0x03)); + payload.append("qt.nokia.com/"); + + QByteArray data; + data.append(char(0xc1)); + data.append(char(type.length())); + data.append(char((payload.length() >> 24) & 0xff)); // PAYLOAD LENGTH 3 + data.append(char((payload.length() >> 16) & 0xff)); // PAYLOAD LENGTH 2 + data.append(char((payload.length() >> 8) & 0xff)); // PAYLOAD LENGTH 1 + data.append(char((payload.length() >> 0) & 0xff)); // PAYLOAD LENGTH 0 + data.append(type); + data.append(payload); + + QNdefRecord record; + record.setTypeNameFormat(QNdefRecord::NfcRtd); + record.setType("U"); + record.setPayload(QByteArray("\003qt.nokia.com/", 14)); + QList<QNdefRecord> recordList; + recordList.append(record); + QTest::newRow("nfc-rtd uri abbrev http://qt.nokia.com/") + << data << QNdefMessage(recordList) + << (QVariantList() << QUrl(QLatin1String("http://qt.nokia.com/"))); + } + + // NFC-RTD URI + { + QByteArray type("U"); + QByteArray payload; + payload.append(char(0x05)); + payload.append("+1234567890"); + + QByteArray data; + data.append(char(0xc1)); + data.append(char(type.length())); + data.append(char((payload.length() >> 24) & 0xff)); // PAYLOAD LENGTH 3 + data.append(char((payload.length() >> 16) & 0xff)); // PAYLOAD LENGTH 2 + data.append(char((payload.length() >> 8) & 0xff)); // PAYLOAD LENGTH 1 + data.append(char((payload.length() >> 0) & 0xff)); // PAYLOAD LENGTH 0 + data.append(type); + data.append(payload); + + QNdefRecord record; + record.setTypeNameFormat(QNdefRecord::NfcRtd); + record.setType("U"); + record.setPayload(QByteArray("\005+1234567890", 12)); + QList<QNdefRecord> recordList; + recordList.append(record); + QTest::newRow("nfc-rtd uri tel:+1234567890") + << data << QNdefMessage(recordList) + << (QVariantList() << QUrl(QLatin1String("tel:+1234567890"))); + } + + // Truncated message + { + QByteArray type("U"); + QByteArray id("Test ID"); + QByteArray payload; + payload.append(char(0x00)); + payload.append("http://qt.nokia.com/"); + QByteArray data; + data.append(char(0xc9)); // MB=1, ME=1, IL=1 + + QTest::newRow("truncated 1") << data << QNdefMessage() << QVariantList(); + + data.append(char(type.length())); // TYPE LENGTH + QTest::newRow("truncated 2") << data << QNdefMessage() << QVariantList(); + + data.append(char((payload.length() >> 24) & 0xff)); // PAYLOAD LENGTH 3 + QTest::newRow("truncated 3") << data << QNdefMessage() << QVariantList(); + + data.append(char((payload.length() >> 16) & 0xff)); // PAYLOAD LENGTH 2 + QTest::newRow("truncated 4") << data << QNdefMessage() << QVariantList(); + + data.append(char((payload.length() >> 8) & 0xff)); // PAYLOAD LENGTH 1 + QTest::newRow("truncated 5") << data << QNdefMessage() << QVariantList(); + + data.append(char((payload.length() >> 0) & 0xff)); // PAYLOAD LENGTH 0 + QTest::newRow("truncated 6") << data << QNdefMessage() << QVariantList(); + + data.append(char(id.length())); // ID LENGTH + QTest::newRow("truncated 7") << data << QNdefMessage() << QVariantList(); + + data.append(type); + QTest::newRow("truncated 8") << data << QNdefMessage() << QVariantList(); + + data.append(id); + QTest::newRow("truncated 9") << data << QNdefMessage() << QVariantList(); + + payload.chop(1); + data.append(payload); + QTest::newRow("truncated 10") << data << QNdefMessage() << QVariantList(); + } +} + +void tst_QNdefMessage::tst_parse() +{ + QFETCH(QByteArray, data); + QFETCH(QNdefMessage, message); + QFETCH(QVariantList, expectedData); + + if (QByteArray(QTest::currentDataTag()).startsWith("truncated ")) + QTest::ignoreMessage(QtWarningMsg, "Unexpected end of message"); + + QNdefMessage parsedMessage = QNdefMessage::fromByteArray(data); + + QVERIFY(parsedMessage == message); + QVERIFY(message == parsedMessage); + + QNdefMessage reparsedMessage = QNdefMessage::fromByteArray(message.toByteArray()); + + QVERIFY(message == reparsedMessage); + QVERIFY(reparsedMessage == message); + + for (int i = 0; i < message.count(); ++i) { + const QNdefRecord &record = message.at(i); + const QNdefRecord &parsedRecord = parsedMessage.at(i); + + QCOMPARE(record.typeNameFormat(), parsedRecord.typeNameFormat()); + QCOMPARE(record.type(), parsedRecord.type()); + QCOMPARE(record.id(), parsedRecord.id()); + QCOMPARE(record.payload(), parsedRecord.payload()); + QCOMPARE(record.isEmpty(), parsedRecord.isEmpty()); + + if (record.isRecordType<QNdefNfcTextRecord>()) { + QNdefNfcTextRecord textRecord(record); + QNdefNfcTextRecord parsedTextRecord(parsedRecord); + + QCOMPARE(textRecord.text(), parsedTextRecord.text()); + QCOMPARE(textRecord.locale(), parsedTextRecord.locale()); + + if (expectedData.count() == 2) { + QCOMPARE(parsedTextRecord.text(), expectedData.at(0).toString()); + QCOMPARE(parsedTextRecord.locale(), expectedData.at(1).toString()); + } + } else if (record.isRecordType<QNdefNfcUriRecord>()) { + QNdefNfcUriRecord uriRecord(record); + QNdefNfcUriRecord parsedUriRecord(parsedRecord); + + QCOMPARE(uriRecord.uri(), parsedUriRecord.uri()); + + if (expectedData.count() == 1) + QCOMPARE(parsedUriRecord.uri(), expectedData.at(0).toUrl()); + } else if (record.isRecordType<QNdefRecord>()) { + QVERIFY(record.isEmpty()); + } + } +} + +QTEST_MAIN(tst_QNdefMessage) + +#include "tst_qndefmessage.moc" + diff --git a/tests/auto/qndefrecord/qndefrecord.pro b/tests/auto/qndefrecord/qndefrecord.pro new file mode 100644 index 00000000..e87f8b62 --- /dev/null +++ b/tests/auto/qndefrecord/qndefrecord.pro @@ -0,0 +1,5 @@ +SOURCES += tst_qndefrecord.cpp +TARGET = tst_qndefrecord +CONFIG += testcase + +QT = core nfc testlib diff --git a/tests/auto/qndefrecord/tst_qndefrecord.cpp b/tests/auto/qndefrecord/tst_qndefrecord.cpp new file mode 100644 index 00000000..3388bdca --- /dev/null +++ b/tests/auto/qndefrecord/tst_qndefrecord.cpp @@ -0,0 +1,341 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the Qt Mobility Components. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include <QtTest/QtTest> + +#include <qndefrecord.h> +#include <qndefnfctextrecord.h> +#include <qndefnfcurirecord.h> + +class tst_QNdefRecord : public QObject +{ + Q_OBJECT + +public: + tst_QNdefRecord(); + ~tst_QNdefRecord(); + +private slots: + void tst_record(); + + void tst_textRecord_data(); + void tst_textRecord(); + + void tst_uriRecord_data(); + void tst_uriRecord(); +}; + +tst_QNdefRecord::tst_QNdefRecord() +{ +} + +tst_QNdefRecord::~tst_QNdefRecord() +{ +} + +void tst_QNdefRecord::tst_record() +{ + // test empty record + { + QNdefRecord record; + + QVERIFY(record.isEmpty()); + QCOMPARE(record.typeNameFormat(), QNdefRecord::Empty); + QVERIFY(record.type().isEmpty()); + QVERIFY(record.id().isEmpty()); + QVERIFY(record.payload().isEmpty()); + + QVERIFY(!record.isRecordType<QNdefNfcTextRecord>()); + QVERIFY(!record.isRecordType<QNdefNfcUriRecord>()); + + QCOMPARE(record, QNdefRecord()); + QVERIFY(!(record != QNdefRecord())); + } + + // test type name format + { + QNdefRecord record; + + record.setTypeNameFormat(QNdefRecord::Empty); + QCOMPARE(record.typeNameFormat(), QNdefRecord::Empty); + + record.setTypeNameFormat(QNdefRecord::NfcRtd); + QCOMPARE(record.typeNameFormat(), QNdefRecord::NfcRtd); + + record.setTypeNameFormat(QNdefRecord::Mime); + QCOMPARE(record.typeNameFormat(), QNdefRecord::Mime); + + record.setTypeNameFormat(QNdefRecord::Uri); + QCOMPARE(record.typeNameFormat(), QNdefRecord::Uri); + + record.setTypeNameFormat(QNdefRecord::ExternalRtd); + QCOMPARE(record.typeNameFormat(), QNdefRecord::ExternalRtd); + + record.setTypeNameFormat(QNdefRecord::Unknown); + QCOMPARE(record.typeNameFormat(), QNdefRecord::Unknown); + + record.setTypeNameFormat(QNdefRecord::TypeNameFormat(6)); + QCOMPARE(record.typeNameFormat(), QNdefRecord::Unknown); + + record.setTypeNameFormat(QNdefRecord::TypeNameFormat(7)); + QCOMPARE(record.typeNameFormat(), QNdefRecord::Unknown); + } + + // test type + { + QNdefRecord record; + + record.setType("test type"); + QCOMPARE(record.type(), QByteArray("test type")); + } + + // test id + { + QNdefRecord record; + + record.setId("test id"); + QCOMPARE(record.id(), QByteArray("test id")); + } + + // test payload + { + QNdefRecord record; + + record.setPayload("test payload"); + QVERIFY(!record.isEmpty()); + QVERIFY(!record.payload().isEmpty()); + QCOMPARE(record.payload(), QByteArray("test payload")); + } + + // test copy + { + QNdefRecord record; + record.setTypeNameFormat(QNdefRecord::ExternalRtd); + record.setType("qt.nokia.com:test-rtd"); + record.setId("test id"); + record.setPayload("test payload"); + + QNdefRecord ccopy(record); + + QCOMPARE(record.typeNameFormat(), ccopy.typeNameFormat()); + QCOMPARE(record.type(), ccopy.type()); + QCOMPARE(record.id(), ccopy.id()); + QCOMPARE(record.payload(), ccopy.payload()); + + QVERIFY(record == ccopy); + QVERIFY(!(record != ccopy)); + + QNdefRecord acopy; + acopy = record; + + QCOMPARE(record.typeNameFormat(), acopy.typeNameFormat()); + QCOMPARE(record.type(), acopy.type()); + QCOMPARE(record.id(), acopy.id()); + QCOMPARE(record.payload(), acopy.payload()); + + QVERIFY(record == acopy); + QVERIFY(!(record != acopy)); + + QVERIFY(record != QNdefRecord()); + } + + // test comparison + { + QNdefRecord record; + record.setTypeNameFormat(QNdefRecord::ExternalRtd); + record.setType("qt.nokia.com:test-rtd"); + record.setId("test id"); + record.setPayload("test payload"); + + QNdefRecord other; + other.setTypeNameFormat(QNdefRecord::ExternalRtd); + other.setType("qt.nokia.com:test-other-rtd"); + other.setId("test other id"); + other.setPayload("test other payload"); + + QVERIFY(record != other); + } +} + +void tst_QNdefRecord::tst_textRecord_data() +{ + QTest::addColumn<QString>("locale"); + QTest::addColumn<QString>("text"); + QTest::addColumn<bool>("utf8"); + QTest::addColumn<QByteArray>("payload"); + + + QTest::newRow("en_US utf8") << QString::fromLatin1("en_US") + << QString::fromLatin1("Test String") + << true + << QByteArray::fromHex("05656E5F55535465737420537472696E67"); + QTest::newRow("en_US utf16") << QString::fromLatin1("en_US") + << QString::fromLatin1("Test String") + << false + << QByteArray::fromHex("85656E5F5553FEFF005400650073007400200053007400720069006E0067"); + QTest::newRow("ja_JP utf8") << QString::fromLatin1("ja_JP") + << QString::fromUtf8("\343\203\206\343\202\271\343\203\210\346" + "\226\207\345\255\227\345\210\227") + << true + << QByteArray::fromHex("056A615F4A50E38386E382B9E38388E69687E5AD97E58897"); + QTest::newRow("ja_JP utf16") << QString::fromLatin1("ja_JP") + << QString::fromUtf8("\343\203\206\343\202\271\343\203\210\346" + "\226\207\345\255\227\345\210\227") + << false + << QByteArray::fromHex("856A615F4A50FEFF30C630B930C865875B575217"); +} + +void tst_QNdefRecord::tst_textRecord() +{ + QFETCH(QString, locale); + QFETCH(QString, text); + QFETCH(bool, utf8); + QFETCH(QByteArray, payload); + + // test setters + { + QNdefNfcTextRecord record; + record.setLocale(locale); + record.setText(text); + record.setEncoding(utf8 ? QNdefNfcTextRecord::Utf8 : QNdefNfcTextRecord::Utf16); + + QCOMPARE(record.payload(), payload); + + QVERIFY(record != QNdefRecord()); + } + + // test getters + { + QNdefNfcTextRecord record; + record.setPayload(payload); + + QCOMPARE(record.locale(), locale); + QCOMPARE(record.text(), text); + QCOMPARE(record.encoding() == QNdefNfcTextRecord::Utf8, utf8); + } + + // test copy + { + QNdefRecord record; + record.setTypeNameFormat(QNdefRecord::NfcRtd); + record.setType("T"); + record.setPayload(payload); + + QVERIFY(!record.isRecordType<QNdefRecord>()); + QVERIFY(record.isRecordType<QNdefNfcTextRecord>()); + QVERIFY(!record.isRecordType<QNdefNfcUriRecord>()); + + QNdefNfcTextRecord textRecord(record); + + QVERIFY(!textRecord.isEmpty()); + + QVERIFY(record == textRecord); + + QCOMPARE(textRecord.locale(), locale); + QCOMPARE(textRecord.text(), text); + QCOMPARE(textRecord.encoding() == QNdefNfcTextRecord::Utf8, utf8); + } +} + +void tst_QNdefRecord::tst_uriRecord_data() +{ + QTest::addColumn<QString>("url"); + QTest::addColumn<QByteArray>("payload"); + + + QTest::newRow("http") << QString::fromLatin1("http://qt.nokia.com/") + << QByteArray::fromHex("0371742E6E6F6B69612E636F6D2F"); + QTest::newRow("tel") << QString::fromLatin1("tel:+1234567890") + << QByteArray::fromHex("052B31323334353637383930"); + QTest::newRow("mailto") << QString::fromLatin1("mailto:test@example.com") + << QByteArray::fromHex("0674657374406578616D706C652E636F6D"); + QTest::newRow("urn") << QString::fromLatin1("urn:nfc:ext:qt.nokia.com:test") + << QByteArray::fromHex("136E66633A6578743A71742E6E6F6B69612E636F6D3A74657374"); +} + +void tst_QNdefRecord::tst_uriRecord() +{ + QFETCH(QString, url); + QFETCH(QByteArray, payload); + + // test setters + { + QNdefNfcUriRecord record; + record.setUri(QUrl(url)); + + QCOMPARE(record.payload(), payload); + + QVERIFY(record != QNdefRecord()); + } + + // test getters + { + QNdefNfcUriRecord record; + record.setPayload(payload); + + QCOMPARE(record.uri(), QUrl(url)); + } + + // test copy + { + QNdefRecord record; + record.setTypeNameFormat(QNdefRecord::NfcRtd); + record.setType("U"); + record.setPayload(payload); + + QVERIFY(!record.isRecordType<QNdefRecord>()); + QVERIFY(!record.isRecordType<QNdefNfcTextRecord>()); + QVERIFY(record.isRecordType<QNdefNfcUriRecord>()); + + QNdefNfcUriRecord uriRecord(record); + + QVERIFY(!uriRecord.isEmpty()); + + QVERIFY(record == uriRecord); + + QCOMPARE(uriRecord.uri(), QUrl(url)); + } +} + +QTEST_MAIN(tst_QNdefRecord) + +#include "tst_qndefrecord.moc" + diff --git a/tests/auto/qnearfieldmanager/qnearfieldmanager.pro b/tests/auto/qnearfieldmanager/qnearfieldmanager.pro new file mode 100644 index 00000000..2757d56a --- /dev/null +++ b/tests/auto/qnearfieldmanager/qnearfieldmanager.pro @@ -0,0 +1,9 @@ +SOURCES += tst_qnearfieldmanager.cpp +TARGET = tst_qnearfieldmanager +CONFIG += testcase + +QT = core nfc testlib + +DEFINES += SRCDIR=\\\"$$PWD/../nfcdata\\\" + +maemo*:CONFIG += insignificant_test diff --git a/tests/auto/qnearfieldmanager/tst_qnearfieldmanager.cpp b/tests/auto/qnearfieldmanager/tst_qnearfieldmanager.cpp new file mode 100644 index 00000000..1c156f76 --- /dev/null +++ b/tests/auto/qnearfieldmanager/tst_qnearfieldmanager.cpp @@ -0,0 +1,299 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the Qt Mobility Components. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include <QtTest/QtTest> + +#include "../qconnectivitytestcommon.h" +#include "qnearfieldmanager_emulator_p.h" + +#include <qnearfieldmanager.h> +#include <qndefnfctextrecord.h> +#include <qndefnfcurirecord.h> +#include <qndefmessage.h> +#include <qndefrecord.h> + +Q_DECLARE_METATYPE(QNearFieldTarget*) +Q_DECLARE_METATYPE(QNearFieldTarget::Type) +Q_DECLARE_METATYPE(QNdefFilter) +Q_DECLARE_METATYPE(QNdefRecord::TypeNameFormat) + +class tst_QNearFieldManager : public QObject +{ + Q_OBJECT + +public: + tst_QNearFieldManager(); + +private slots: + void initTestCase(); + + void targetDetected_data(); + void targetDetected(); + + void unregisterNdefMessageHandler(); + + void registerNdefMessageHandler(); + + void registerNdefMessageHandler_type_data(); + void registerNdefMessageHandler_type(); + + void registerNdefMessageHandler_filter_data(); + void registerNdefMessageHandler_filter(); +}; + +tst_QNearFieldManager::tst_QNearFieldManager() +{ +#ifndef Q_OS_SYMBIAN + QDir::setCurrent(QLatin1String(SRCDIR)); +#endif + + qRegisterMetaType<QNdefMessage>("QNdefMessage"); + qRegisterMetaType<QNearFieldTarget *>("QNearFieldTarget*"); +} + +void tst_QNearFieldManager::initTestCase() +{ + QNearFieldManagerPrivateImpl *emulatorBackend = new QNearFieldManagerPrivateImpl; + QNearFieldManager manager(emulatorBackend, 0); + + QVERIFY(manager.isAvailable()); +} + +void tst_QNearFieldManager::targetDetected_data() +{ + QTest::addColumn<QNearFieldTarget::Type>("type"); + QTest::addColumn<bool>("deleteTarget"); + + QTest::newRow("AnyTarget") << QNearFieldTarget::AnyTarget << false; + QTest::newRow("NfcTagType1") << QNearFieldTarget::NfcTagType1 << false; + QTest::newRow("Delete Target") << QNearFieldTarget::AnyTarget << true; +} + +void tst_QNearFieldManager::targetDetected() +{ + QFETCH(QNearFieldTarget::Type, type); + QFETCH(bool, deleteTarget); + + QNearFieldManagerPrivateImpl *emulatorBackend = new QNearFieldManagerPrivateImpl; + QNearFieldManager manager(emulatorBackend, 0); + + QSignalSpy targetDetectedSpy(&manager, SIGNAL(targetDetected(QNearFieldTarget*))); + QSignalSpy targetLostSpy(&manager, SIGNAL(targetLost(QNearFieldTarget*))); + + manager.startTargetDetection(type); + + QTRY_VERIFY(!targetDetectedSpy.isEmpty()); + + QNearFieldTarget *target = targetDetectedSpy.first().at(0).value<QNearFieldTarget *>(); + + QSignalSpy disconnectedSpy(target, SIGNAL(disconnected())); + + QVERIFY(target); + + QVERIFY(!target->uid().isEmpty()); + + if (!deleteTarget) { + QTRY_VERIFY(!targetLostSpy.isEmpty()); + + QNearFieldTarget *lostTarget = targetLostSpy.first().at(0).value<QNearFieldTarget *>(); + + QCOMPARE(target, lostTarget); + + QVERIFY(!disconnectedSpy.isEmpty()); + } else { + delete target; + + // wait for another targetDetected() without a targetLost() signal in between. + targetDetectedSpy.clear(); + targetLostSpy.clear(); + + QTRY_VERIFY(targetLostSpy.isEmpty() && !targetDetectedSpy.isEmpty()); + } + + manager.stopTargetDetection(); +} + +void tst_QNearFieldManager::unregisterNdefMessageHandler() +{ + QNearFieldManagerPrivateImpl *emulatorBackend = new QNearFieldManagerPrivateImpl; + QNearFieldManager manager(emulatorBackend, 0); + + QVERIFY(!manager.unregisterNdefMessageHandler(-1)); + QVERIFY(!manager.unregisterNdefMessageHandler(0)); +} + +class MessageListener : public QObject +{ + Q_OBJECT + +signals: + void matchedNdefMessage(const QNdefMessage &message, QNearFieldTarget *target); +}; + +void tst_QNearFieldManager::registerNdefMessageHandler() +{ + QNearFieldManagerPrivateImpl *emulatorBackend = new QNearFieldManagerPrivateImpl; + QNearFieldManager manager(emulatorBackend, 0); + + MessageListener listener; + QSignalSpy messageSpy(&listener, SIGNAL(matchedNdefMessage(QNdefMessage,QNearFieldTarget*))); + + int id = manager.registerNdefMessageHandler(&listener, + SIGNAL(matchedNdefMessage(QNdefMessage,QNearFieldTarget*))); + + QVERIFY(id != -1); + + QTRY_VERIFY(!messageSpy.isEmpty()); + + const QNdefMessage message = messageSpy.first().at(0).value<QNdefMessage>(); + QNearFieldTarget *target = messageSpy.first().at(1).value<QNearFieldTarget *>(); + + QVERIFY(target); + + QVERIFY(manager.unregisterNdefMessageHandler(id)); +} + +void tst_QNearFieldManager::registerNdefMessageHandler_type_data() +{ + QTest::addColumn<QNdefRecord::TypeNameFormat>("typeNameFormat"); + QTest::addColumn<QByteArray>("type"); + + QTest::newRow("Image") << QNdefRecord::Mime << QByteArray("image/png"); + QTest::newRow("URI") << QNdefRecord::NfcRtd << QByteArray("U"); + QTest::newRow("Text") << QNdefRecord::NfcRtd << QByteArray("T"); +} + +void tst_QNearFieldManager::registerNdefMessageHandler_type() +{ + QFETCH(QNdefRecord::TypeNameFormat, typeNameFormat); + QFETCH(QByteArray, type); + + QNearFieldManagerPrivateImpl *emulatorBackend = new QNearFieldManagerPrivateImpl; + QNearFieldManager manager(emulatorBackend, 0); + + MessageListener listener; + QSignalSpy messageSpy(&listener, SIGNAL(matchedNdefMessage(QNdefMessage,QNearFieldTarget*))); + + int id = manager.registerNdefMessageHandler(typeNameFormat, type, &listener, + SIGNAL(matchedNdefMessage(QNdefMessage,QNearFieldTarget*))); + + QVERIFY(id != -1); + + QTRY_VERIFY(!messageSpy.isEmpty()); + + const QNdefMessage message = messageSpy.first().at(0).value<QNdefMessage>(); + + bool hasRecord = false; + foreach (const QNdefRecord &record, message) { + if (record.typeNameFormat() == typeNameFormat && record.type() == type) { + hasRecord = true; + break; + } + } + + QVERIFY(hasRecord); + + QNearFieldTarget *target = messageSpy.first().at(1).value<QNearFieldTarget *>(); + + QVERIFY(target); +} + +void tst_QNearFieldManager::registerNdefMessageHandler_filter_data() +{ + QTest::addColumn<QNdefFilter>("filter"); + + QNdefFilter filter; + + QTest::newRow("Empty") << filter; + + filter.clear(); + filter.setOrderMatch(true); + filter.appendRecord(QNdefRecord::Mime, "image/png"); + filter.appendRecord<QNdefNfcTextRecord>(2, 10); + filter.appendRecord<QNdefNfcUriRecord>(1, 1); + QTest::newRow("Image + Multiple Text + URI") << filter; + + filter.clear(); + filter.setOrderMatch(true); + filter.appendRecord<QNdefNfcTextRecord>(1, 1); + filter.appendRecord<QNdefNfcUriRecord>(1, 1); + QTest::newRow("Text + URI") << filter; + + QNdefFilter::Record record; + + filter.clear(); + filter.setOrderMatch(false); + filter.appendRecord<QNdefNfcUriRecord>(1, 1); + record.typeNameFormat = QNdefRecord::NfcRtd; + record.type = "T"; + record.minimum = 1; + record.maximum = 1; + filter.appendRecord(record); + QTest::newRow("Unordered Text + URI") << filter; +} + +void tst_QNearFieldManager::registerNdefMessageHandler_filter() +{ + QFETCH(QNdefFilter, filter); + + QNearFieldManagerPrivateImpl *emulatorBackend = new QNearFieldManagerPrivateImpl; + QNearFieldManager manager(emulatorBackend, 0); + + MessageListener listener; + QSignalSpy messageSpy(&listener, SIGNAL(matchedNdefMessage(QNdefMessage,QNearFieldTarget*))); + + int id = manager.registerNdefMessageHandler(filter, &listener, + SIGNAL(matchedNdefMessage(QNdefMessage,QNearFieldTarget*))); + + QVERIFY(id != -1); + + QTRY_VERIFY(!messageSpy.isEmpty()); + + const QNdefMessage message = messageSpy.first().at(0).value<QNdefMessage>(); + + QNearFieldTarget *target = messageSpy.first().at(1).value<QNearFieldTarget *>(); + + QVERIFY(target); +} + +QTEST_MAIN(tst_QNearFieldManager); + +#include "tst_qnearfieldmanager.moc" diff --git a/tests/auto/qnearfieldtagtype1/qnearfieldtagtype1.pro b/tests/auto/qnearfieldtagtype1/qnearfieldtagtype1.pro new file mode 100644 index 00000000..1494c4c5 --- /dev/null +++ b/tests/auto/qnearfieldtagtype1/qnearfieldtagtype1.pro @@ -0,0 +1,10 @@ +SOURCES += tst_qnearfieldtagtype1.cpp +TARGET = tst_qnearfieldtagtype1 +CONFIG += testcase + +QT = core nfc testlib + + +DEFINES += SRCDIR=\\\"$$PWD/../nfcdata\\\" + +maemo*:CONFIG += insignificant_test diff --git a/tests/auto/qnearfieldtagtype1/tst_qnearfieldtagtype1.cpp b/tests/auto/qnearfieldtagtype1/tst_qnearfieldtagtype1.cpp new file mode 100644 index 00000000..9e27e94b --- /dev/null +++ b/tests/auto/qnearfieldtagtype1/tst_qnearfieldtagtype1.cpp @@ -0,0 +1,491 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the Qt Mobility Components. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include <QtTest/QtTest> + +#include "../qconnectivitytestcommon.h" +#include "qnearfieldmanager_emulator_p.h" + +#include <qnearfieldmanager.h> +#include <qndefmessage.h> +#include <qnearfieldtagtype1.h> +#include <qndefnfctextrecord.h> + +Q_DECLARE_METATYPE(QNearFieldTarget*) + +class tst_QNearFieldTagType1 : public QObject +{ + Q_OBJECT + +public: + tst_QNearFieldTagType1(); + +private slots: + void init(); + void cleanup(); + + void staticMemoryModel(); + void dynamicMemoryModel(); + + void ndefMessages(); + +private: + void waitForMatchingTarget(); + + QNearFieldManagerPrivateImpl *emulatorBackend; + QNearFieldManager *manager; + QNearFieldTagType1 *target; +}; + +tst_QNearFieldTagType1::tst_QNearFieldTagType1() +: emulatorBackend(0), manager(0), target(0) +{ +#ifndef Q_OS_SYMBIAN + QDir::setCurrent(QLatin1String(SRCDIR)); +#endif + + qRegisterMetaType<QNdefMessage>("QNdefMessage"); + qRegisterMetaType<QNearFieldTarget *>("QNearFieldTarget*"); +} + +void tst_QNearFieldTagType1::init() +{ + emulatorBackend = new QNearFieldManagerPrivateImpl; + manager = new QNearFieldManager(emulatorBackend, 0); +} + +void tst_QNearFieldTagType1::cleanup() +{ + emulatorBackend->reset(); + + delete manager; + manager = 0; + emulatorBackend = 0; + target = 0; +} + +void tst_QNearFieldTagType1::waitForMatchingTarget() +{ + QSignalSpy targetDetectedSpy(manager, SIGNAL(targetDetected(QNearFieldTarget*))); + + manager->startTargetDetection(QNearFieldTarget::NfcTagType1); + + QTRY_VERIFY(!targetDetectedSpy.isEmpty()); + + target = + qobject_cast<QNearFieldTagType1 *>(targetDetectedSpy.first().at(0).value<QNearFieldTarget *>()); + + manager->stopTargetDetection(); + + QVERIFY(target); + + QCOMPARE(target->type(), QNearFieldTarget::NfcTagType1); +} + +void tst_QNearFieldTagType1::staticMemoryModel() +{ + waitForMatchingTarget(); + + QVERIFY(target->accessMethods() & QNearFieldTarget::TagTypeSpecificAccess); + + QCOMPARE(target->version(), quint8(0x10)); + + // readIdentification() + { + QNearFieldTarget::RequestId id = target->readIdentification(); + QVERIFY(target->waitForRequestCompleted(id)); + + const QByteArray data = target->requestResponse(id).toByteArray(); + + QCOMPARE(data.length(), 6); + + quint8 hr0 = data.at(0); + //quint8 hr1 = data.at(1); + const QByteArray uid4 = data.mid(2, 4); + + // verify NfcTagType1 + QVERIFY(hr0 & 0x10); + + QCOMPARE(uid4, target->uid().left(4)); + } + + // readAll() + { + // read all reads the first 120 bytes, prepended with HR0 and HR1. + QNearFieldTarget::RequestId id = target->readAll(); + QVERIFY(target->waitForRequestCompleted(id)); + + const QByteArray data = target->requestResponse(id).toByteArray(); + QCOMPARE(data.length(), 122); + + // verify NfcTagType1. + QVERIFY(data.at(0) & 0x10); + + // NFC Magic Number means NDEF message present. + QCOMPARE(quint8(data.at(10)) == 0xe1, target->hasNdefMessage()); + } + + // readByte() + { + QNearFieldTarget::RequestId id = target->readAll(); + QVERIFY(target->waitForRequestCompleted(id)); + + const QByteArray data = target->requestResponse(id).toByteArray(); + + for (int i = 0; i < 120; ++i) { + id = target->readByte(i); + QVERIFY(target->waitForRequestCompleted(id)); + + quint8 byte = target->requestResponse(id).toUInt(); + + QCOMPARE(byte, quint8(data.at(i + 2))); + } + } + + // writeByte() + { + for (int i = 0; i < 8; ++i) { + QNearFieldTarget::RequestId id = target->readByte(i); + QVERIFY(target->waitForRequestCompleted(id)); + + quint8 byte = target->requestResponse(id).toUInt(); + + id = target->writeByte(i, 0x55); + QVERIFY(!target->waitForRequestCompleted(id)); + + QVERIFY(!target->requestResponse(id).isValid()); + + id = target->readByte(i); + QVERIFY(target->waitForRequestCompleted(id)); + + quint8 readByte = target->requestResponse(id).toUInt(); + QCOMPARE(readByte, byte); + } + + for (int i = 8; i < 104; ++i) { + // Write 0x55 + QNearFieldTarget::RequestId id = target->writeByte(i, 0x55); + QVERIFY(target->waitForRequestCompleted(id)); + QVERIFY(target->requestResponse(id).toBool()); + + id = target->readByte(i); + QVERIFY(target->waitForRequestCompleted(id)); + quint8 readByte = target->requestResponse(id).toUInt(); + QCOMPARE(readByte, quint8(0x55)); + + // Write 0xaa + id = target->writeByte(i, 0xaa); + QVERIFY(target->waitForRequestCompleted(id)); + QVERIFY(target->requestResponse(id).toBool()); + + id = target->readByte(i); + QVERIFY(target->waitForRequestCompleted(id)); + readByte = target->requestResponse(id).toUInt(); + QCOMPARE(readByte, quint8(0xaa)); + + // Write 0x55 without erase, result should be 0xff + id = target->writeByte(i, 0x55, QNearFieldTagType1::WriteOnly); + QVERIFY(target->waitForRequestCompleted(id)); + QVERIFY(target->requestResponse(id).toBool()); + + id = target->readByte(i); + QVERIFY(target->waitForRequestCompleted(id)); + readByte = target->requestResponse(id).toUInt(); + QCOMPARE(readByte, quint8(0xff)); + } + + for (int i = 104; i < 120; ++i) { + QNearFieldTarget::RequestId id = target->readByte(i); + QVERIFY(target->waitForRequestCompleted(id)); + + quint8 byte = target->requestResponse(id).toUInt(); + + id = target->writeByte(i, 0x55); + QVERIFY(!target->waitForRequestCompleted(id)); + + QVERIFY(!target->requestResponse(id).isValid()); + + id = target->readByte(i); + QVERIFY(target->waitForRequestCompleted(id)); + + quint8 readByte = target->requestResponse(id).toUInt(); + QCOMPARE(readByte, byte); + } + } +} + +void tst_QNearFieldTagType1::dynamicMemoryModel() +{ + bool testedStatic = false; + bool testedDynamic = false; + + QList<QByteArray> seenIds; + forever { + waitForMatchingTarget(); + + QNearFieldTarget::RequestId id = target->readIdentification(); + QVERIFY(target->waitForRequestCompleted(id)); + + const QByteArray data = target->requestResponse(id).toByteArray(); + if (seenIds.contains(data)) + break; + else + seenIds.append(data); + + quint8 hr0 = data.at(0); + bool dynamic = (((hr0 & 0xf0) == 0x10) && ((hr0 & 0x0f) != 0x01)); + + if (dynamic) { + testedDynamic = true; + + // block 0, UID is locked + { + QNearFieldTarget::RequestId id = target->readBlock(0x00); + QVERIFY(target->waitForRequestCompleted(id)); + + const QByteArray block = target->requestResponse(id).toByteArray(); + + QCOMPARE(target->uid(), block.left(7)); + QCOMPARE(quint8(block.at(7)), quint8(0x00)); + + id = target->writeBlock(0x00, QByteArray(8, quint8(0x55))); + QVERIFY(!target->waitForRequestCompleted(id)); + QVERIFY(!target->requestResponse(id).isValid()); + + QCOMPARE(target->uid(), block.left(7)); + QCOMPARE(quint8(block.at(7)), quint8(0x00)); + } + + // static data area + QNearFieldTarget::RequestId id = target->readSegment(0); + QVERIFY(target->waitForRequestCompleted(id)); + QByteArray segment = target->requestResponse(id).toByteArray(); + for (int i = 1; i < 0x0d; ++i) { + // Write 0x55 + id = target->writeBlock(i, QByteArray(8, quint8(0x55))); + QVERIFY(target->waitForRequestCompleted(id)); + QVERIFY(target->requestResponse(id).toBool()); + + id = target->readBlock(i); + QVERIFY(target->waitForRequestCompleted(id)); + QCOMPARE(target->requestResponse(id).toByteArray(), QByteArray(8, quint8(0x55))); + + segment.replace(i * 8, 8, QByteArray(8, quint8(0x55))); + + id = target->readSegment(0); + QVERIFY(target->waitForRequestCompleted(id)); + QCOMPARE(target->requestResponse(id).toByteArray(), segment); + + // Write 0xaa + id = target->writeBlock(i, QByteArray(8, quint8(0xaa))); + QVERIFY(target->waitForRequestCompleted(id)); + QVERIFY(target->requestResponse(id).toBool()); + + id = target->readBlock(i); + QVERIFY(target->waitForRequestCompleted(id)); + QCOMPARE(target->requestResponse(id).toByteArray(), QByteArray(8, quint8(0xaa))); + + segment.replace(i * 8, 8, QByteArray(8, quint8(0xaa))); + + id = target->readSegment(0); + QVERIFY(target->waitForRequestCompleted(id)); + QCOMPARE(target->requestResponse(id).toByteArray(), segment); + + // Write 0x55 without erase, result should be 0xff + id = target->writeBlock(i, QByteArray(8, quint8(0x55)), + QNearFieldTagType1::WriteOnly); + QVERIFY(target->waitForRequestCompleted(id)); + QVERIFY(target->requestResponse(id).toBool()); + + id = target->readBlock(i); + QVERIFY(target->waitForRequestCompleted(id)); + QCOMPARE(target->requestResponse(id).toByteArray(), QByteArray(8, quint8(0xff))); + + segment.replace(i * 8, 8, QByteArray(8, quint8(0xff))); + + id = target->readSegment(0); + QVERIFY(target->waitForRequestCompleted(id)); + QCOMPARE(target->requestResponse(id).toByteArray(), segment); + } + + // static / dynamic reserved lock area + for (int i = 0x0d; i < 0x10; ++i) { + id = target->readBlock(i); + QVERIFY(target->waitForRequestCompleted(id)); + QByteArray block = target->requestResponse(id).toByteArray(); + + id = target->writeBlock(i, QByteArray(8, quint8(0x55))); + QVERIFY(!target->waitForRequestCompleted(id)); + QVERIFY(!target->requestResponse(id).isValid()); + + id = target->readBlock(i); + QVERIFY(target->waitForRequestCompleted(id)); + QCOMPARE(target->requestResponse(id).toByteArray(), block); + } + } else { + testedStatic = true; + + for (int i = 0; i < 256; ++i) { + QNearFieldTarget::RequestId id = target->readBlock(i); + QVERIFY(!target->waitForRequestCompleted(id)); + + id = target->writeBlock(i, QByteArray(8, quint8(0x55))); + QVERIFY(!target->waitForRequestCompleted(id)); + } + for (int i = 0; i < 16; ++i) { + QNearFieldTarget::RequestId id = target->readSegment(i); + QVERIFY(!target->waitForRequestCompleted(id)); + } + } + } + + QVERIFY(testedStatic); + QVERIFY(testedDynamic); +} + +void tst_QNearFieldTagType1::ndefMessages() +{ + QByteArray firstId; + forever { + waitForMatchingTarget(); + + QNearFieldTarget::RequestId id = target->readIdentification(); + QVERIFY(target->waitForRequestCompleted(id)); + + const QByteArray uid = target->requestResponse(id).toByteArray(); + if (firstId.isEmpty()) + firstId = uid; + else if (firstId == uid) + break; + + QVERIFY(target->hasNdefMessage()); + + QSignalSpy ndefMessageReadSpy(target, SIGNAL(ndefMessageRead(QNdefMessage))); + QSignalSpy requestCompletedSpy(target, + SIGNAL(requestCompleted(QNearFieldTarget::RequestId))); + QSignalSpy errorSpy(target, + SIGNAL(error(QNearFieldTarget::Error,QNearFieldTarget::RequestId))); + + QNearFieldTarget::RequestId readId = target->readNdefMessages(); + + QVERIFY(readId.isValid()); + + QNearFieldTarget::RequestId completedId; + + while (completedId != readId) { + QTRY_VERIFY(!requestCompletedSpy.isEmpty() && errorSpy.isEmpty()); + + completedId = + requestCompletedSpy.takeFirst().first().value<QNearFieldTarget::RequestId>(); + } + + QList<QNdefMessage> ndefMessages; + for (int i = 0; i < ndefMessageReadSpy.count(); ++i) + ndefMessages.append(ndefMessageReadSpy.at(i).first().value<QNdefMessage>()); + + QList<QNdefMessage> messages; + QNdefNfcTextRecord textRecord; + textRecord.setText(QLatin1String("tst_QNearFieldTagType1::ndefMessages")); + + QNdefMessage message; + message.append(textRecord); + + if (target->memorySize() > 120) { + QNdefRecord record; + record.setTypeNameFormat(QNdefRecord::ExternalRtd); + record.setType("com.nokia.qt:ndefMessagesTest"); + record.setPayload(QByteArray(120, quint8(0x55))); + message.append(record); + } + + messages.append(message); + + requestCompletedSpy.clear(); + errorSpy.clear(); + + QSignalSpy ndefMessageWriteSpy(target, SIGNAL(ndefMessagesWritten())); + QNearFieldTarget::RequestId writeId = target->writeNdefMessages(messages); + + QVERIFY(writeId.isValid()); + + completedId = QNearFieldTarget::RequestId(); + + while (completedId != writeId) { + QTRY_VERIFY(!requestCompletedSpy.isEmpty() && errorSpy.isEmpty()); + + completedId = + requestCompletedSpy.takeFirst().first().value<QNearFieldTarget::RequestId>(); + } + + QVERIFY(!ndefMessageWriteSpy.isEmpty()); + + QVERIFY(target->hasNdefMessage()); + + ndefMessageReadSpy.clear(); + requestCompletedSpy.clear(); + errorSpy.clear(); + + readId = target->readNdefMessages(); + + QVERIFY(readId.isValid()); + + completedId = QNearFieldTarget::RequestId(); + + while (completedId != readId) { + QTRY_VERIFY(!requestCompletedSpy.isEmpty() && errorSpy.isEmpty()); + + completedId = + requestCompletedSpy.takeFirst().first().value<QNearFieldTarget::RequestId>(); + } + + QList<QNdefMessage> storedMessages; + for (int i = 0; i < ndefMessageReadSpy.count(); ++i) + storedMessages.append(ndefMessageReadSpy.at(i).first().value<QNdefMessage>()); + + QVERIFY(ndefMessages != storedMessages); + + QCOMPARE(messages, storedMessages); + } +} + +QTEST_MAIN(tst_QNearFieldTagType1); + +#include "tst_qnearfieldtagtype1.moc" diff --git a/tests/auto/qnearfieldtagtype2/Dynamic Empty Tag.nfc b/tests/auto/qnearfieldtagtype2/Dynamic Empty Tag.nfc new file mode 100644 index 00000000..30cf6b2d --- /dev/null +++ b/tests/auto/qnearfieldtagtype2/Dynamic Empty Tag.nfc @@ -0,0 +1,6 @@ +[Target] +Name=Dynamic Empty Tag +Type=TagType2 + +[TagType2] +Data=@ByteArray(333\0\x33\x33\x33\x33\0\0\0\0\0\x10\xff\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0) diff --git a/tests/auto/qnearfieldtagtype2/Empty Tag.nfc b/tests/auto/qnearfieldtagtype2/Empty Tag.nfc new file mode 100644 index 00000000..22b31b4a --- /dev/null +++ b/tests/auto/qnearfieldtagtype2/Empty Tag.nfc @@ -0,0 +1,6 @@ +[Target] +Name=Empty Tag +Type=TagType2 + +[TagType2] +Data=@ByteArray(\x11\x11\x11\0\x11\x11\x11\x11\0\0\0\0\xe1\x10\x6\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0) diff --git a/tests/auto/qnearfieldtagtype2/qnearfieldtagtype2.pro b/tests/auto/qnearfieldtagtype2/qnearfieldtagtype2.pro new file mode 100644 index 00000000..3f7db6c1 --- /dev/null +++ b/tests/auto/qnearfieldtagtype2/qnearfieldtagtype2.pro @@ -0,0 +1,9 @@ +SOURCES += tst_qnearfieldtagtype2.cpp +TARGET = tst_qnearfieldtagtype2 +CONFIG += testcase + +QT = core nfc testlib + +DEFINES += SRCDIR=\\\"$$PWD\\\" + +maemo*:CONFIG += insignificant_test diff --git a/tests/auto/qnearfieldtagtype2/tst_qnearfieldtagtype2.cpp b/tests/auto/qnearfieldtagtype2/tst_qnearfieldtagtype2.cpp new file mode 100644 index 00000000..bb545559 --- /dev/null +++ b/tests/auto/qnearfieldtagtype2/tst_qnearfieldtagtype2.cpp @@ -0,0 +1,358 @@ +/**************************************************************************** +** +** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the Qt Mobility Components. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include <QtTest/QtTest> + +#include "../qconnectivitytestcommon.h" +#include "qnearfieldmanager_emulator_p.h" + +#include <qnearfieldmanager.h> +#include <qndefmessage.h> +#include <qnearfieldtagtype2.h> +#include <qndefnfctextrecord.h> + +Q_DECLARE_METATYPE(QNearFieldTarget*) + +static const char * const deadbeef = "\xde\xad\xbe\xef"; + +class tst_QNearFieldTagType2 : public QObject +{ + Q_OBJECT + +public: + tst_QNearFieldTagType2(); + +private slots: + void init(); + void cleanup(); + + void staticMemoryModel(); + void dynamicMemoryModel(); + + void ndefMessages(); + +private: + void waitForMatchingTarget(); + + QNearFieldManagerPrivateImpl *emulatorBackend; + QNearFieldManager *manager; + QNearFieldTagType2 *target; +}; + +tst_QNearFieldTagType2::tst_QNearFieldTagType2() +: emulatorBackend(0), manager(0), target(0) +{ +#ifndef Q_OS_SYMBIAN + QDir::setCurrent(QLatin1String(SRCDIR)); +#endif + + qRegisterMetaType<QNdefMessage>("QNdefMessage"); + qRegisterMetaType<QNearFieldTarget *>("QNearFieldTarget*"); +} + +void tst_QNearFieldTagType2::init() +{ + emulatorBackend = new QNearFieldManagerPrivateImpl; + manager = new QNearFieldManager(emulatorBackend, 0); +} + +void tst_QNearFieldTagType2::cleanup() +{ + emulatorBackend->reset(); + + delete manager; + manager = 0; + emulatorBackend = 0; + target = 0; +} + +void tst_QNearFieldTagType2::waitForMatchingTarget() +{ + QSignalSpy targetDetectedSpy(manager, SIGNAL(targetDetected(QNearFieldTarget*))); + + manager->startTargetDetection(QNearFieldTarget::NfcTagType2); + + QTRY_VERIFY(!targetDetectedSpy.isEmpty()); + + target = qobject_cast<QNearFieldTagType2 *>(targetDetectedSpy.first().at(0).value<QNearFieldTarget *>()); + + manager->stopTargetDetection(); + + QVERIFY(target); + + QCOMPARE(target->type(), QNearFieldTarget::NfcTagType2); +} + +void tst_QNearFieldTagType2::staticMemoryModel() +{ + waitForMatchingTarget(); + + QVERIFY(target->accessMethods() & QNearFieldTarget::TagTypeSpecificAccess); + + QCOMPARE(target->version(), quint8(0x10)); + + // readBlock(), writeBlock() + { + for (int i = 0; i < 2; ++i) { + QNearFieldTarget::RequestId id = target->readBlock(i); + QVERIFY(target->waitForRequestCompleted(id)); + + const QByteArray block = target->requestResponse(id).toByteArray(); + + id = target->writeBlock(i, QByteArray(4, 0x55)); + QVERIFY(target->waitForRequestCompleted(id)); + QVERIFY(!target->requestResponse(id).toBool()); + + id = target->readBlock(i); + QVERIFY(target->waitForRequestCompleted(id)); + + const QByteArray readBlock = target->requestResponse(id).toByteArray(); + QCOMPARE(readBlock, block); + } + + for (int i = 3; i < 16; ++i) { + // Read initial data + QNearFieldTarget::RequestId id = target->readBlock(i); + QVERIFY(target->waitForRequestCompleted(id)); + QByteArray initialBlock = target->requestResponse(id).toByteArray(); + + // Write 0x55 + id = target->writeBlock(i, QByteArray(4, 0x55)); + QVERIFY(target->waitForRequestCompleted(id)); + QVERIFY(target->requestResponse(id).toBool()); + + id = target->readBlock(i); + QVERIFY(target->waitForRequestCompleted(id)); + QByteArray readBlock = target->requestResponse(id).toByteArray(); + QCOMPARE(readBlock, QByteArray(4, 0x55) + initialBlock.mid(4)); + + // Write 0xaa + id = target->writeBlock(i, QByteArray(4, 0xaa)); + QVERIFY(target->waitForRequestCompleted(id)); + QVERIFY(target->requestResponse(id).toBool()); + + id = target->readBlock(i); + QVERIFY(target->waitForRequestCompleted(id)); + readBlock = target->requestResponse(id).toByteArray(); + QCOMPARE(readBlock, QByteArray(4, 0xaa) + initialBlock.mid(4)); + } + } +} + +void tst_QNearFieldTagType2::dynamicMemoryModel() +{ + bool testedStatic = false; + bool testedDynamic = false; + + QList<QByteArray> seenIds; + forever { + waitForMatchingTarget(); + + QVERIFY(target->accessMethods() & QNearFieldTarget::TagTypeSpecificAccess); + + QNearFieldTarget::RequestId id = target->readBlock(0); + QVERIFY(target->waitForRequestCompleted(id)); + + const QByteArray data = target->requestResponse(id).toByteArray(); + const QByteArray uid = data.left(3) + data.mid(4, 4); + + if (seenIds.contains(uid)) + break; + else + seenIds.append(uid); + + QCOMPARE(target->version(), quint8(0x10)); + + bool dynamic = target->memorySize() > 1024; + + if (dynamic) { + testedDynamic = true; + + int totalBlocks = target->memorySize() / 4; + int sector1Blocks = qMin(totalBlocks - 256, 256); + + // default sector is sector 0 + for (int i = 3; i < 256; ++i) { + // Write 0x55 + QNearFieldTarget::RequestId id = target->writeBlock(i, deadbeef); + QVERIFY(target->waitForRequestCompleted(id)); + QVERIFY(target->requestResponse(id).toBool()); + } + + // change to sector 1 + { + QNearFieldTarget::RequestId id = target->selectSector(1); + QVERIFY(target->waitForRequestCompleted(id)); + QVERIFY(target->requestResponse(id).toBool()); + } + + for (int i = 0; i < sector1Blocks; ++i) { + QNearFieldTarget::RequestId id = target->readBlock(i); + QVERIFY(target->waitForRequestCompleted(id)); + QByteArray initialBlock = target->requestResponse(id).toByteArray(); + + QVERIFY(initialBlock.left(4) != deadbeef); + + // Write 0x55 + id = target->writeBlock(i, QByteArray(4, 0x55)); + QVERIFY(target->waitForRequestCompleted(id)); + QVERIFY(target->requestResponse(id).toBool()); + + id = target->readBlock(i); + QVERIFY(target->waitForRequestCompleted(id)); + QByteArray readBlock = target->requestResponse(id).toByteArray(); + QCOMPARE(readBlock, QByteArray(4, 0x55) + initialBlock.mid(4)); + + // Write 0xaa + id = target->writeBlock(i, QByteArray(4, 0xaa)); + QVERIFY(target->waitForRequestCompleted(id)); + QVERIFY(target->requestResponse(id).toBool()); + + id = target->readBlock(i); + QVERIFY(target->waitForRequestCompleted(id)); + readBlock = target->requestResponse(id).toByteArray(); + QCOMPARE(readBlock, QByteArray(4, 0xaa) + initialBlock.mid(4)); + } + + // change to sector 0 + { + QNearFieldTarget::RequestId id = target->selectSector(0); + QVERIFY(target->waitForRequestCompleted(id)); + QVERIFY(target->requestResponse(id).toBool()); + } + + for (int i = 3; i < 256; ++i) { + QNearFieldTarget::RequestId id = target->readBlock(i); + QVERIFY(target->waitForRequestCompleted(id)); + QByteArray readBlock = target->requestResponse(id).toByteArray(); + + QVERIFY(readBlock.left(4) == deadbeef); + } + } else { + testedStatic = true; + + QNearFieldTarget::RequestId id = target->selectSector(1); + QVERIFY(target->waitForRequestCompleted(id)); + QVERIFY(!target->requestResponse(id).toBool()); + } + } + + QVERIFY(testedStatic); + QVERIFY(testedDynamic); +} + +void tst_QNearFieldTagType2::ndefMessages() +{ + QSKIP("Not implemented", SkipAll); + + QByteArray firstId; + forever { + waitForMatchingTarget(); + + QNearFieldTarget::RequestId id = target->readBlock(0); + QVERIFY(target->waitForRequestCompleted(id)); + + QByteArray uid = target->requestResponse(id).toByteArray().left(3); + + id = target->readBlock(1); + QVERIFY(target->waitForRequestCompleted(id)); + uid.append(target->requestResponse(id).toByteArray()); + + if (firstId.isEmpty()) + firstId = uid; + else if (firstId == uid) + break; + + QVERIFY(target->hasNdefMessage()); + + QSignalSpy ndefMessageReadSpy(target, SIGNAL(ndefMessageRead(QNdefMessage))); + + target->readNdefMessages(); + + QTRY_VERIFY(!ndefMessageReadSpy.isEmpty()); + + QList<QNdefMessage> ndefMessages; + for (int i = 0; i < ndefMessageReadSpy.count(); ++i) + ndefMessages.append(ndefMessageReadSpy.at(i).first().value<QNdefMessage>()); + + QList<QNdefMessage> messages; + QNdefNfcTextRecord textRecord; + textRecord.setText(QLatin1String("tst_QNearFieldTagType2::ndefMessages")); + + QNdefMessage message; + message.append(textRecord); + + if (target->memorySize() > 120) { + QNdefRecord record; + record.setTypeNameFormat(QNdefRecord::ExternalRtd); + record.setType("com.nokia.qt:ndefMessagesTest"); + record.setPayload(QByteArray(120, quint8(0x55))); + message.append(record); + } + + messages.append(message); + + QSignalSpy ndefMessageWriteSpy(target, SIGNAL(ndefMessagesWritten())); + target->writeNdefMessages(messages); + + QTRY_VERIFY(!ndefMessageWriteSpy.isEmpty()); + + QVERIFY(target->hasNdefMessage()); + + ndefMessageReadSpy.clear(); + + target->readNdefMessages(); + + QTRY_VERIFY(!ndefMessageReadSpy.isEmpty()); + + QList<QNdefMessage> storedMessages; + for (int i = 0; i < ndefMessageReadSpy.count(); ++i) + storedMessages.append(ndefMessageReadSpy.at(i).first().value<QNdefMessage>()); + + QVERIFY(ndefMessages != storedMessages); + + QVERIFY(messages == storedMessages); + } +} + +QTEST_MAIN(tst_QNearFieldTagType2); + +#include "tst_qnearfieldtagtype2.moc" diff --git a/tests/auto/qrfcommserver/README.txt b/tests/auto/qrfcommserver/README.txt new file mode 100644 index 00000000..8f3d2ef8 --- /dev/null +++ b/tests/auto/qrfcommserver/README.txt @@ -0,0 +1,50 @@ +This test currently can not be run automatically. + +To make this test work, manual connections must be started from a client +machine. There are 2 options for doing this, either use the rfcommclient application in the subdirectory, +or run the test manually as described below. When using rfcommclient, start qrfcommserver first and then +start rfcommclient on the other device. There might be some timing issues, so beware. + +Steps to run this test manually: + +1. start tst_qrfcommserver + +2. Wait for test display: + +QDEBUG : tst_QRfcommServer::tst_pendingConnections(1 connection) Waiting for 1 simultaneous connections + +On a linux machine run: + +rfcomm connect hci0 00:1A:9F:92:9E:5A + +On the linux machine you will see: + +Connected /dev/rfcomm0 to 00:1A:9F:92:9E:5A on channel 1 +Press CTRL-C for hangup +Disconnected + +and the test will pass. + +3. Wait for the test to then display: + +QDEBUG : tst_QRfcommServer::tst_receive(test) Listening on RFCOMM channel: 1 + +On the linux machine run: + +rfcomm connect hci0 00:1A:9F:92:9E:5A + +You will see: + +Connected /dev/rfcomm0 to 00:1A:9F:92:9E:5A on channel 1 +Press CTRL-C for hangup + +now run: + +echo -en "hello\r\n" > /dev/rfcomm0 + +The test should then pass. + +A linux machine is not required, but simple used as an example for how to make +easy rfcomm connections. Any system that will connect to a device and rfcomm +port will work. The format of the string for the second test is very important +for the test to pass. diff --git a/tests/auto/qrfcommserver/qrfcommserver.pro b/tests/auto/qrfcommserver/qrfcommserver.pro new file mode 100644 index 00000000..75459b83 --- /dev/null +++ b/tests/auto/qrfcommserver/qrfcommserver.pro @@ -0,0 +1,12 @@ +SOURCES += tst_qrfcommserver.cpp +TARGET = tst_qrfcommserver +CONFIG += testcase + +QT = core bluetooth testlib + +symbian: TARGET.CAPABILITY = LocalServices NetworkControl WriteDeviceData + +OTHER_FILES += \ + README.txt + + diff --git a/tests/auto/qrfcommserver/rfcommclient/main.cpp b/tests/auto/qrfcommserver/rfcommclient/main.cpp new file mode 100644 index 00000000..ee6b8584 --- /dev/null +++ b/tests/auto/qrfcommserver/rfcommclient/main.cpp @@ -0,0 +1,111 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the Qt Mobility Components. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include <QCoreApplication> +#include <QStringList> +#include "rfcommclient.h" +#include <qbluetoothdeviceinfo.h> +//#include <qbluetoothlocaldevice.h> +//#include <QtTest/QtTest> + +int main(int argc, char *argv[]) +{ + QCoreApplication app(argc, argv); + RfCommClient client; + QBluetoothLocalDevice localDevice; + MyThread mythread; + + QObject::connect(&client, SIGNAL(done()), &app, SLOT(quit())); + + QString address; + QString port; + QStringList args = QCoreApplication::arguments(); + + if (args.length() >= 2){ + address = args.at(1); + if (args.length() >= 3){ + port = args.at(2); + } + } + + // use previous value for client, stored earlier +// if (address.isEmpty()){ +// QSettings settings("QtDF", "bttennis"); +// address = settings.value("lastclient").toString(); +// } + + // hard-code address and port number if not provided + if (address.isEmpty()){ + address = "6C:9B:02:0C:91:D3"; // "J C7-2" + port = QString("20"); + } + + if (!address.isEmpty()){ + qDebug() << "Connecting to" << address << port; + QBluetoothDeviceInfo device = QBluetoothDeviceInfo(QBluetoothAddress(address), "", + QBluetoothDeviceInfo::MiscellaneousDevice); + QBluetoothServiceInfo service; + if (!port.isEmpty()) { + QBluetoothServiceInfo::Sequence protocolDescriptorList; + QBluetoothServiceInfo::Sequence protocol; + protocol << QVariant::fromValue(QBluetoothUuid(QBluetoothUuid::Rfcomm)) + << QVariant::fromValue(port.toUShort()); + protocolDescriptorList.append(QVariant::fromValue(protocol)); + service.setAttribute(QBluetoothServiceInfo::ProtocolDescriptorList, + protocolDescriptorList); + qDebug() << "port" << port.toUShort() << service.protocolServiceMultiplexer(); + } + else { + service.setServiceUuid(QBluetoothUuid(serviceUuid)); + } + service.setDevice(device); + // delay so that server is in waiting state + qDebug() << "Starting sleep"; + mythread.sleep(10); // seconds + qDebug() << "Finished sleeping"; + client.startClient(service); + } else { + qDebug() << "failed because address and/or port is missing " << address << port; + } + + return app.exec(); +} + diff --git a/tests/auto/qrfcommserver/rfcommclient/rfcommclient.cpp b/tests/auto/qrfcommserver/rfcommclient/rfcommclient.cpp new file mode 100644 index 00000000..f3e33f56 --- /dev/null +++ b/tests/auto/qrfcommserver/rfcommclient/rfcommclient.cpp @@ -0,0 +1,210 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the Qt Mobility Components. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor +** the names of its contributors may be used to endorse or promote +** products derived from this software without specific prior written +** permission. +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "rfcommclient.h" + +#include <qbluetoothsocket.h> +#include <qbluetoothlocaldevice.h> + +#include <QtCore/QDataStream> +#include <QtCore/QByteArray> + +#include <QtCore/QStringList> + +void MyThread::sleep(int seconds) +{ + QThread::sleep(seconds); +} + +RfCommClient::RfCommClient(QObject *parent) +: QObject(parent), socket(0), stream(0), elapsed(new QTime), lagTimeout(0), state(listening) +{ + lagTimer.setSingleShot(true); + lagTimer.setInterval(5000); +} + +RfCommClient::~RfCommClient() +{ + stopClient(); +} + +bool RfCommClient::powerOn() +{ + qDebug() << __PRETTY_FUNCTION__ << ">>"; + // turn on BT in case it is not on + if (localDevice.hostMode() == QBluetoothLocalDevice::HostPoweredOff) { + connect(&localDevice, SIGNAL(hostModeStateChanged(QBluetoothLocalDevice::HostMode)), + this, SLOT(hostModeStateChanged(QBluetoothLocalDevice::HostMode))); +// connect(localDevice, SIGNAL(hostModeStateChanged(QBluetoothLocalDevice::HostMode)), +// this, SLOT(hostModeStateChanged(QBluetoothLocalDevice::HostMode))); + qDebug() << __PRETTY_FUNCTION__ << "Turning power on"; + localDevice.powerOn(); + } else { + qDebug() << __PRETTY_FUNCTION__ << "<< Power already on! returning true"; + return true; + } + qDebug() << __PRETTY_FUNCTION__ << "<< returning false"; + return false; +} + +void RfCommClient::hostModeStateChanged(QBluetoothLocalDevice::HostMode mode) +{ + qDebug() << __PRETTY_FUNCTION__ << mode; + if (mode != QBluetoothLocalDevice::HostPoweredOff) + startClient(serviceInfo); +} +//! [startClient] +void RfCommClient::startClient(const QBluetoothServiceInfo &remoteService) +{ + qDebug() << __PRETTY_FUNCTION__ << ">>"; + serviceInfo = remoteService; + + // make sure preconditions are met + if (!powerOn() || socket) { + qDebug() << __PRETTY_FUNCTION__ << "<< power not on or socket already exists!"; + return; + } + + // Connect to service + if (state == listening) + state = pendingConnections; + socket = new QBluetoothSocket(QBluetoothSocket::RfcommSocket); + qDebug() << "Create socket"; + socket->connectToService(remoteService); + qDebug() << "ConnecttoService done"; + + connect(socket, SIGNAL(readyRead()), this, SLOT(readSocket())); + connect(socket, SIGNAL(connected()), this, SLOT(connected())); + connect(socket, SIGNAL(disconnected()), this, SLOT(socketDisconnected())); + connect(socket, SIGNAL(error(QBluetoothSocket::SocketError)), this, SLOT(error(QBluetoothSocket::SocketError))); + + qDebug() << __PRETTY_FUNCTION__ << "<<"; +} +//! [startClient] + +//! [stopClient] +void RfCommClient::stopClient() +{ + qDebug() << __PRETTY_FUNCTION__ << "closing client!"; + + lagTimer.stop(); + + delete stream; + stream = 0; + + socket->deleteLater(); + socket = 0; +} +//! [stopClient] + +//! [socketDisconnected] +void RfCommClient::socketDisconnected() +{ + // Note: it seems that the "disconnected" signal is not emitted by the socket, so this never gets called + qDebug() << __PRETTY_FUNCTION__ << "Got socketDisconnected"; + emit disconnected(); + stopClient(); + + // now reconnect and send text string + startClient(serviceInfo); + connect(&lagTimer, SIGNAL(timeout()), this, SLOT(sendText())); + lagTimer.start(); +} +//! [socketDisconnected] + +//! [readSocket] +void RfCommClient::readSocket() +{ + if (!socket) + return; + QString str; + + while (socket->bytesAvailable()) { + *stream >> str; + } + qDebug() << __PRETTY_FUNCTION__ << "socket read=" << str; +} +//! [readSocket] + +//! [connected] +void RfCommClient::connected() +{ + qDebug() << __PRETTY_FUNCTION__ << "connected to " << socket->peerName(); + stream = new QDataStream(socket); + emit connected(socket->peerName()); +} +//! [connected] + +void RfCommClient::error(QBluetoothSocket::SocketError err) +{ + qDebug() << __PRETTY_FUNCTION__ << "Got socket error" << err; + // remote side has closed the socket, effectively disconnecting it + if (state == pendingConnections) { + state = dataTransfer; + emit disconnected(); + stopClient(); + + // now reconnect and send text string + MyThread mythread; + mythread.sleep(5); + startClient(serviceInfo); + connect(&lagTimer, SIGNAL(timeout()), this, SLOT(sendText())); + lagTimer.start(); + } else { + qDebug() << __PRETTY_FUNCTION__ << "emitting done"; + emit done(); + } +} + +void RfCommClient::sendText() +{ + qDebug() << __PRETTY_FUNCTION__ << ">>"; + lagTimer.stop(); + if (stream) { + buffer.clear(); + buffer.append(QString("hello\r\n")); // ideally we would use QDataStream here + socket->write(buffer); + } + // terminate client program + emit done(); + qDebug() << __PRETTY_FUNCTION__ << "<< Terminating program"; +} + + diff --git a/tests/auto/qrfcommserver/rfcommclient/rfcommclient.h b/tests/auto/qrfcommserver/rfcommclient/rfcommclient.h new file mode 100644 index 00000000..6825576a --- /dev/null +++ b/tests/auto/qrfcommserver/rfcommclient/rfcommclient.h @@ -0,0 +1,115 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the Qt Mobility Components. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor +** the names of its contributors may be used to endorse or promote +** products derived from this software without specific prior written +** permission. +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef RFCOMMCLIENT_H +#define RFCOMMCLIENT_H + +#include <qbluetoothserviceinfo.h> +#include <qbluetoothsocket.h> + +#include <QtCore/QObject> +#include <QtCore/QTime> +#include <QtCore/QTimer> +#include <QBluetoothLocalDevice.h> +#include <QThread> + +static const QLatin1String serviceUuid("e8e10f95-1a70-4b27-9ccf-02010264e9c9"); + +class QBluetoothSocket; + +class QDataStream; + +class MyThread : public QThread +{ +public: + void sleep(int seconds); +}; + + +//! [declaration] +class RfCommClient : public QObject +{ + Q_OBJECT + + enum States { + listening, + pendingConnections, + dataTransfer + }; +public: + explicit RfCommClient(QObject *parent = 0); + ~RfCommClient(); + + void startClient(const QBluetoothServiceInfo &remoteService); + void stopClient(); + +public slots: + void error(QBluetoothSocket::SocketError); + +signals: + void connected(const QString &name); + void disconnected(); + void done(); + void lag(int ms); + +private slots: + void readSocket(); + void connected(); + void sendText(); + void socketDisconnected(); + void hostModeStateChanged(QBluetoothLocalDevice::HostMode); + +private: + bool powerOn(); + +private: + QBluetoothSocket *socket; + QDataStream *stream; + QByteArray buffer; + QBluetoothServiceInfo serviceInfo; + QBluetoothLocalDevice localDevice; + QTime *elapsed; + QTimer lagTimer; + int lagTimeout; + RfCommClient::States state; +}; +//! [declaration] + +#endif // RFCOMMCLIENT_H diff --git a/tests/auto/qrfcommserver/rfcommclient/rfcommclient.pro b/tests/auto/qrfcommserver/rfcommclient/rfcommclient.pro new file mode 100644 index 00000000..7a1834c6 --- /dev/null +++ b/tests/auto/qrfcommserver/rfcommclient/rfcommclient.pro @@ -0,0 +1,7 @@ +TARGET = rfcommclient +SOURCES += main.cpp rfcommclient.cpp +HEADERS += rfcommclient.h + +QT = core + +symbian: TARGET.CAPABILITY = LocalServices NetworkControl WriteDeviceData diff --git a/tests/auto/qrfcommserver/tst_qrfcommserver.cpp b/tests/auto/qrfcommserver/tst_qrfcommserver.cpp new file mode 100644 index 00000000..df2a10bc --- /dev/null +++ b/tests/auto/qrfcommserver/tst_qrfcommserver.cpp @@ -0,0 +1,318 @@ +/**************************************************************************** +** +** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the Qt Mobility Components. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include <QtTest/QtTest> + +#include <QDebug> + +#include <qrfcommserver.h> +#include <qbluetoothsocket.h> +#include <qbluetoothlocaldevice.h> + +Q_DECLARE_METATYPE(QBluetooth::SecurityFlags); + +// Max time to wait for connection +static const int MaxConnectTime = 60 * 1000; // 1 minute in ms + +class tst_QRfcommServer : public QObject +{ + Q_OBJECT + +public: + tst_QRfcommServer(); + ~tst_QRfcommServer(); + +private slots: + void initTestCase(); + + void tst_construction(); + + void tst_listen_data(); + void tst_listen(); + + void tst_secureFlags(); + + void tst_pendingConnections_data(); + void tst_pendingConnections(); + + void tst_receive_data(); + void tst_receive(); + +private: + QBluetoothLocalDevice localDevice; +}; + +tst_QRfcommServer::tst_QRfcommServer() +{ +} + +tst_QRfcommServer::~tst_QRfcommServer() +{ +} + +void tst_QRfcommServer::initTestCase() +{ + qRegisterMetaType<QBluetooth::SecurityFlags>("QBluetooth::SecurityFlags"); + + // turn on BT in case it is not on + if (localDevice.hostMode() == QBluetoothLocalDevice::HostPoweredOff) { + QSignalSpy hostModeSpy(&localDevice, SIGNAL(hostModeStateChanged(QBluetoothLocalDevice::HostMode))); + QVERIFY(hostModeSpy.isEmpty()); + localDevice.powerOn(); + int connectTime = 5000; // ms + while (hostModeSpy.count() < 1 && connectTime > 0) { + QTest::qWait(500); + connectTime -= 500; + } + QVERIFY(hostModeSpy.count() > 0); + } + QBluetoothLocalDevice::HostMode hostMode= localDevice.hostMode(); + QVERIFY(hostMode == QBluetoothLocalDevice::HostConnectable + || hostMode == QBluetoothLocalDevice::HostDiscoverable + || hostMode == QBluetoothLocalDevice::HostDiscoverableLimitedInquiry); +} + +void tst_QRfcommServer::tst_construction() +{ + { + QRfcommServer server; + + QVERIFY(!server.isListening()); + QCOMPARE(server.maxPendingConnections(), 1); + QVERIFY(!server.hasPendingConnections()); + QVERIFY(server.nextPendingConnection() == 0); + QVERIFY(server.serverAddress().isNull()); + QCOMPARE(server.serverPort(), quint16(0)); + } +} + +void tst_QRfcommServer::tst_listen_data() +{ + QTest::addColumn<QBluetoothAddress>("address"); + QTest::addColumn<quint16>("port"); + + QTest::newRow("default") << QBluetoothAddress() << quint16(0); +#ifdef Q_OS_SYMBIAN + //use localdevice address for listen address. + QTest::newRow("specified address") << localDevice.address() << quint16(0); + QTest::newRow("specified port") << QBluetoothAddress() << quint16(20); + QTest::newRow("specified address/port") << localDevice.address() << quint16(27); // port 21 returns KErrInUse +#else + QTest::newRow("specified address") << QBluetoothAddress("00:11:B1:08:AD:B8") << quint16(0); + QTest::newRow("specified port") << QBluetoothAddress() << quint16(10); + QTest::newRow("specified address/port") << QBluetoothAddress("00:11:B1:08:AD:B8") << quint16(10); +#endif +} + +void tst_QRfcommServer::tst_listen() +{ + QFETCH(QBluetoothAddress, address); + QFETCH(quint16, port); + + { + QRfcommServer server; + qDebug() << "tst_listen() address=" << address.toString() << "port=" << port; + bool result = server.listen(address, port); + QTest::qWait(1000); + + QVERIFY(result); + QVERIFY(server.isListening()); + + if (!address.isNull()) + QCOMPARE(server.serverAddress(), address); + + qDebug()<<"Server Port="<<server.serverPort(); + if (port != 0) + QCOMPARE(server.serverPort(), port); + else + QVERIFY(server.serverPort() != 0); + + QCOMPARE(server.maxPendingConnections(), 1); + + QVERIFY(!server.hasPendingConnections()); + QVERIFY(server.nextPendingConnection() == 0); + + server.close(); + QTest::qWait(2000); + + QVERIFY(!server.isListening()); + + QVERIFY(server.serverAddress().isNull()); + QVERIFY(server.serverPort() == 0); + + QVERIFY(server.hasPendingConnections() == false); + QVERIFY(server.nextPendingConnection() == 0); + } +} + +void tst_QRfcommServer::tst_pendingConnections_data() +{ + QTest::addColumn<int>("maxConnections"); + + QTest::newRow("1 connection") << 1; + //QTest::newRow("2 connections") << 2; +} + +void tst_QRfcommServer::tst_pendingConnections() +{ + QFETCH(int, maxConnections); + + QRfcommServer server; + QBluetoothLocalDevice localDev; + + QBluetoothAddress address = localDev.address(); + server.setMaxPendingConnections(maxConnections); + bool result = server.listen(address, 20); // port == 20 + QTest::qWait(1000); + + QVERIFY(result); + QVERIFY(server.isListening()); + + qDebug() << "tst_pendingConnections() Listening on address " << address.toString() << "RFCOMM channel:" << server.serverPort(); + + QCOMPARE(server.maxPendingConnections(), maxConnections); + + QVERIFY(!server.hasPendingConnections()); + QVERIFY(server.nextPendingConnection() == 0); + + /* wait for maxConnections simultaneous connections */ + qDebug() << "Waiting for" << maxConnections << "simultaneous connections."; + + QSignalSpy connectionSpy(&server, SIGNAL(newConnection())); + + int connectTime = MaxConnectTime; + while (connectionSpy.count() < maxConnections && connectTime > 0) { + QTest::qWait(1000); + connectTime -= 1000; + } + + QList<QBluetoothSocket *> sockets; + while (server.hasPendingConnections()) + sockets.append(server.nextPendingConnection()); + + QCOMPARE(connectionSpy.count(), maxConnections); + QCOMPARE(sockets.count(), maxConnections); + + foreach (QBluetoothSocket *socket, sockets) { + qDebug() << socket->state(); + QVERIFY(socket->state() == QBluetoothSocket::ConnectedState); + QVERIFY(socket->openMode() == QIODevice::ReadWrite); + } + + QVERIFY(!server.hasPendingConnections()); + QVERIFY(server.nextPendingConnection() == 0); + + while (!sockets.isEmpty()) { + QBluetoothSocket *socket = sockets.takeFirst(); + socket->close(); + delete socket; + } + + server.close(); +} + +void tst_QRfcommServer::tst_receive_data() +{ + QTest::addColumn<QByteArray>("expected"); + + QTest::newRow("test") << QByteArray("hello\r\n"); +} + +void tst_QRfcommServer::tst_receive() +{ + QFETCH(QByteArray, expected); + + QRfcommServer server; + QBluetoothLocalDevice localDev; + + QBluetoothAddress address = localDev.address(); + bool result = server.listen(address, 20); // port == 20 + QTest::qWait(1000); + + QVERIFY(result); + QVERIFY(server.isListening()); + + qDebug() << "Listening on address " << address.toString() << "RFCOMM channel:" << server.serverPort(); + + int connectTime = MaxConnectTime; + while (!server.hasPendingConnections() && connectTime > 0) { + QTest::qWait(1000); + connectTime -= 1000; + } + + QVERIFY(server.hasPendingConnections()); + + qDebug() << "Got connection"; + + QBluetoothSocket *socket = server.nextPendingConnection(); + + QVERIFY(socket->state() == QBluetoothSocket::ConnectedState); + QVERIFY(socket->openMode() == QIODevice::ReadWrite); + + QSignalSpy readyReadSpy(socket, SIGNAL(readyRead())); + + int readyReadTime = 60000; + while (readyReadSpy.isEmpty() && readyReadTime > 0) { + QTest::qWait(1000); + readyReadTime -= 1000; + } + + QVERIFY(!readyReadSpy.isEmpty()); + + const QByteArray data = socket->readAll(); + + QCOMPARE(data, expected); +} + +void tst_QRfcommServer::tst_secureFlags() +{ + QRfcommServer server; + + server.setSecurityFlags(QBluetooth::NoSecurity); + QCOMPARE(server.securityFlags(), QBluetooth::NoSecurity); + + server.setSecurityFlags(QBluetooth::Encryption); + QCOMPARE(server.securityFlags(), QBluetooth::Encryption); +} + +QTEST_MAIN(tst_QRfcommServer) + +#include "tst_qrfcommserver.moc" diff --git a/tests/nfcsymbianbackend/nfcsymbianbackend.pro b/tests/nfcsymbianbackend/nfcsymbianbackend.pro index f8d7d8c1..5fac5448 100644 --- a/tests/nfcsymbianbackend/nfcsymbianbackend.pro +++ b/tests/nfcsymbianbackend/nfcsymbianbackend.pro @@ -2,5 +2,5 @@ TEMPLATE = subdirs symbian { - SUBDIRS += qnearfieldmanager qllcpserver qllcpsockettype2 qllcpsocketlocal qllcpsocketremote qnearfieldtagtype1 qnearfieldtagtype2 qnearfieldtagtype3 qnearfieldtagtype4 nfctestserviceprovider + SUBDIRS += qcontenthandler qnearfieldmanager qllcpserver qllcpsockettype2 qllcpsocketlocal qllcpsocketremote qnearfieldtagtype1 qnearfieldtagtype2 qnearfieldtagtype3 qnearfieldtagtype4 nfctestserviceprovider } diff --git a/tests/nfcsymbianbackend/qcontenthandler/qcontenthandler.pro b/tests/nfcsymbianbackend/qcontenthandler/qcontenthandler.pro index 58bf7d8f..b44dcef2 100644 --- a/tests/nfcsymbianbackend/qcontenthandler/qcontenthandler.pro +++ b/tests/nfcsymbianbackend/qcontenthandler/qcontenthandler.pro @@ -7,16 +7,9 @@ CONFIG += testcase TEMPLATE = app -INCLUDEPATH += ../../../src/nfc -DEPENDPATH += ../../../src/nfc INCLUDEPATH += ../common DEPENDPATH += ../common -INCLUDEPATH += ../../../src/global -DEPENDPATH += ../../../src/global - -QMAKE_LIBDIR += $$QT_MOBILITY_BUILD_TREE/lib - HEADERS += ../common/qautomsgbox.h SOURCES += tst_qcontenthandler.cpp \ ../common/qautomsgbox.cpp diff --git a/tests/nfcsymbianbackend/qcontenthandler/tst_qcontenthandler.cpp b/tests/nfcsymbianbackend/qcontenthandler/tst_qcontenthandler.cpp index 04e76ca8..7bbdcbda 100644 --- a/tests/nfcsymbianbackend/qcontenthandler/tst_qcontenthandler.cpp +++ b/tests/nfcsymbianbackend/qcontenthandler/tst_qcontenthandler.cpp @@ -54,8 +54,6 @@ #include <qndefmessage.h> #include <qndefrecord.h> -QTM_USE_NAMESPACE - Q_DECLARE_METATYPE(QNearFieldTarget*) Q_DECLARE_METATYPE(QNearFieldTarget::Type) Q_DECLARE_METATYPE(QNdefFilter) diff --git a/tests/tests.pro b/tests/tests.pro index b2ca6bf9..a10451f7 100644 --- a/tests/tests.pro +++ b/tests/tests.pro @@ -1,5 +1,5 @@ TEMPLATE = subdirs -SUBDIRS += nfctestserver +SUBDIRS += auto nfctestserver linux*:!linux-armcc:contains(bluez_enabled, yes):contains(QT_CONFIG, dbus) { SUBDIRS += btclient |