diff options
author | Michael Zanetti <michael.zanetti@nokia.com> | 2011-08-24 14:09:22 +1000 |
---|---|---|
committer | Rohan McGovern <rohan.mcgovern@nokia.com> | 2011-08-24 14:10:36 +1000 |
commit | 29ba8297443cf76d4f647bde329d62c2a567c709 (patch) | |
tree | 88875199053cd88b3b3521c829277f209e815159 /tests |
Initial commit.
From qt5connectivity.tar.gz, md5 317c149d6f8c07d09632353188582834
Diffstat (limited to 'tests')
56 files changed, 8856 insertions, 0 deletions
diff --git a/tests/btclient/btclient.c b/tests/btclient/btclient.c new file mode 100644 index 00000000..2d52718f --- /dev/null +++ b/tests/btclient/btclient.c @@ -0,0 +1,581 @@ +/**************************************************************************** +** +** 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 <stdio.h> +#include <sys/types.h> +#include <sys/stat.h> +#include <sys/utsname.h> +#include <sys/wait.h> +#include <fcntl.h> +#include <errno.h> +#include <sys/socket.h> +#include <stdlib.h> +#include <unistd.h> +#include <poll.h> +#include <assert.h> +#include <fcntl.h> +#include <limits.h> + +#include <bluetooth/bluetooth.h> +#include <bluetooth/rfcomm.h> +#include <bluetooth/l2cap.h> + +#include <dbus/dbus.h> + +#include "btclient.h" + +#define UNUSED(x) do { (void)x; } while(0) + +const char *xmldefn = + "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n" + "\n" + "<record>\n" + " <attribute id=\"0x0000\">\n" + " <uint32 value=\"0x00010010\" />\n" + " </attribute>\n" + " <attribute id=\"0x0001\">\n" + " <sequence>\n" + " <uuid value=\"" ECHO_SERVICE_UUID "\" />\n" + " </sequence>\n" + " </attribute>\n" + " <attribute id=\"0x0003\">\n" + " <uuid value=\"" ECHO_SERVICE_UUID "\" />\n" + " </attribute>\n" + " <attribute id=\"0x0004\">\n" + " <sequence>\n" + " <sequence>\n" + " <uuid value=\"0x0100\" />\n" + " </sequence>\n" + " <sequence>\n" + " <uuid value=\"0x0003\" />\n" + " <uint8 value=\"0x0a\" />\n" + " </sequence>\n" + " </sequence>\n" + " </attribute>\n" + " <attribute id=\"0x0005\">\n" + " <sequence>\n" + " <uuid value=\"0x1002\" />\n" + " </sequence>\n" + " </attribute>\n" + " <attribute id=\"0x0100\">\n" + " <text value=\"QtConnectivity Test Echo Server\" />\n" + " </attribute>\n" + " <attribute id=\"0x0101\">\n" + " <text value=\"QtConnectivity test echo server\" />\n" + " </attribute>\n" + " <attribute id=\"0x0102\">\n" + " <text value=\"Nokia, QtDF\" />\n" + " </attribute>\n" + "</record>\n"; + +typedef void (*actionhandler_t)(int, short, void *); + +struct fdlist { + struct fdlist *next; + int fd; + short events; + actionhandler_t hanlder; + void *ptr; +}; + +struct fdlist *head = 0; + +void removefd(struct fdlist *fdl, int fd){ + struct fdlist *prev = fdl; + while(fdl && fdl->fd != fd) { + prev = fdl; + fdl = fdl->next; + } + assert(fdl); + + prev->next = fdl->next; + free(fdl); +} + +struct fdlist *addfd(struct fdlist *fdl, int fd, short events, actionhandler_t hanlder, void *data){ + struct fdlist *n = malloc(sizeof(struct fdlist)); + if(fdl){ + while(fdl->next) + fdl = fdl->next; + fdl->next = n; + } + + n->next = 0; + n->fd = fd; + n->events = events; + n->hanlder = hanlder; + n->ptr = data; + + return n; + +} + +int mkpoll(struct fdlist *fdl, struct pollfd *fds, int max){ + int num = 0; + while(fdl && num < max){ + fds[num].events = fdl->events; + fds[num].fd = fdl->fd; + fdl = fdl->next; + num++; + } + assert(num <= max); + return num; +} + +int createListening(int channel){ + struct sockaddr_rc addr; + int flags; + socklen_t addrLength = sizeof(addr); + int sk, opt = 1; + + /* Create echo socket on bt channel 10 */ + sk = socket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM); + + addr.rc_family = AF_BLUETOOTH; + addr.rc_channel = channel; + memset(&addr.rc_bdaddr, 0, sizeof(bdaddr_t)); + + if (bind(sk, (struct sockaddr *)&addr, addrLength) < 0) { + perror("Failed to bind to Bluetooth socket"); + return -1; + } + + if(setsockopt(sk, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) < 0){ + perror("Warning: Failed to set SO_REUSEADDR options"); + } + + // ensure that O_NONBLOCK is set on new connections. + flags = fcntl(sk, F_GETFL, 0); + if (!(flags & O_NONBLOCK)) + fcntl(sk, F_SETFL, flags | O_NONBLOCK); + + if (listen(sk, 10) < 0){ + perror("Can't start listening on bluetooth socket"); + return -1; + } + printf("Got socket: %d\n", sk); + return sk; +} + +int createListeningL2cap(int psm){ + struct sockaddr_l2 addr; + int flags; + socklen_t addrLength = sizeof(struct sockaddr_l2); + int sk, opt = 1; + + sk = socket(AF_BLUETOOTH, SOCK_SEQPACKET, BTPROTO_L2CAP); + + memset(&addr,0, addrLength); + addr.l2_family = AF_BLUETOOTH; + addr.l2_psm = htobs(psm); + memset(&addr.l2_bdaddr, 0, sizeof(bdaddr_t)); + + if (bind(sk, (struct sockaddr *)&addr, addrLength) < 0) { + perror("Failed to bind to Bluetooth socket"); + return -1; + } + + if(setsockopt(sk, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) < 0){ + perror("Warning: Failed to set SO_REUSEADDR options"); + } + + // ensure that O_NONBLOCK is set on new connections. + flags = fcntl(sk, F_GETFL, 0); + if (!(flags & O_NONBLOCK)) + fcntl(sk, F_SETFL, flags | O_NONBLOCK); + + if (listen(sk, 10) < 0){ + perror("Can't start listening on bluetooth socket"); + return -1; + } + printf("Got L2cap socket: %d\n", sk); + return sk; +} + +void echo_process(int fd, short revents, void *data){ + char buff[1024]; + + UNUSED(data); + + if(revents&POLLHUP || revents&POLLNVAL){ + close(fd); + removefd(head, fd); + return; + } + int size = read(fd, buff, 1024); + printf("%d: Read: %d bytes\n", fd, size); + size = write(fd, buff, size); + printf("%d: Wrote: %d bytes\n", fd, size); +} + +void echo_connect(int fd, short revents, void *data){ + + struct sockaddr_rc addr; + unsigned char *a; + socklen_t length = sizeof(struct sockaddr_rc); + + UNUSED(data); + UNUSED(revents); + + printf("Echo connect started\n"); + + int sk = accept(fd, (struct sockaddr *)&addr, &length); + + a = addr.rc_bdaddr.b; + printf("Connect from: %02x:%02x:%02x:%02x:%02x:%02x port %d\n", a[5], a[4], a[3], a[2], a[1], a[0], addr.rc_channel); + addfd(head, sk, POLLIN|POLLHUP|POLLNVAL, echo_process, 0); + +} + +struct connectioninfo { + int socket; + FILE *pipe; + struct sockaddr_rc addr_them; +}; + +void id_greeting(int fd, short revents, void *data){ + int err; + unsigned char *a, *b; + struct sockaddr_rc addr; + char buffer[1024]; + char name[100]; + socklen_t addrLength = sizeof(addr); + struct connectioninfo *ci; + + if(revents&POLLHUP || revents&POLLNVAL){ + close(fd); + removefd(head, fd); + return; + } + + ci = (struct connectioninfo *)data; + + err = getsockname(ci->socket, (struct sockaddr *)&addr, &addrLength); + if(err < 0){ + perror("failed to get socket name"); + exit(-1); + } + a = addr.rc_bdaddr.b; + + b = ci->addr_them.rc_bdaddr.b; + + err = fscanf(ci->pipe, "%s", name); + removefd(head, fd); + pclose(ci->pipe); + + sprintf(buffer, "%02x:%02x:%02x:%02x:%02x:%02x %d %s %02x:%02x:%02x:%02x:%02x:%02x %d\n", + a[5], a[4], a[3], a[2], a[1], a[0], addr.rc_channel, name, + b[5], b[4], b[3], b[2], b[1], b[0], ci->addr_them.rc_channel); + if(write(ci->socket, buffer, strlen(buffer)) < 0){ + perror("Failed to write greeting"); + } + printf("%s", buffer); + free(ci); + +} + +void id_process(int fd, short revents, void *data){ + int err; + unsigned char *b; + struct sockaddr_rc addr_them; + char cmd[100]; + socklen_t addrLength = sizeof(addr_them); + struct connectioninfo *ci; + + UNUSED(data); + + if(revents&POLLHUP || revents&POLLNVAL){ + close(fd); + removefd(head, fd); + return; + } + + err = getpeername(fd, (struct sockaddr *)&addr_them, &addrLength); + if(err < 0){ + perror("failed to get socket name"); + exit(-1); + } + b = addr_them.rc_bdaddr.b; + + sprintf(cmd, "hcitool name %02x:%02x:%02x:%02x:%02x:%02x", b[5], b[4], b[3], b[2], b[1], b[0]); + + FILE *f = popen(cmd, "r"); + ci = malloc(sizeof(struct connectioninfo)); + ci->socket = fd; + ci->pipe = f; + memcpy(&ci->addr_them, &addr_them, sizeof(struct sockaddr_rc)); + + addfd(head, fileno(f), POLLIN, id_greeting, ci); + +} + +void id_connect(int fd, short revents, void *data){ + + struct sockaddr_rc addr; + unsigned char *a; + socklen_t length = sizeof(struct sockaddr_rc); + + UNUSED(revents); + UNUSED(data); + + printf("ID connect started\n"); + + int sk = accept(fd, (struct sockaddr *)&addr, &length); + + a = addr.rc_bdaddr.b; + printf("Connect from: %02x:%02x:%02x:%02x:%02x:%02x port %d\n", a[5], a[4], a[3], a[2], a[1], a[0], addr.rc_channel); + addfd(head, sk, POLLIN|POLLHUP|POLLNVAL, id_process, 0); + id_process(sk, POLLIN, 0x0); +} + +void id_print(int socket){ + + int err; + unsigned char *a; + struct sockaddr_rc addr; + socklen_t addrLength = sizeof(addr); + + err = getsockname(socket, (struct sockaddr *)&addr, &addrLength); + if(err < 0){ + perror("failed to get socket name"); + exit(-1); + } + a = addr.rc_bdaddr.b; + printf("We are: %d:%d:%d:%d:%d:%d port %d\n", a[0], a[1], a[2], a[3], a[4], a[5], addr.rc_channel); +} + +void l2_process(int fd, short revents, void *data){ + char buff[1024]; + + UNUSED(data); + + if(revents&POLLHUP || revents&POLLNVAL){ + close(fd); + removefd(head, fd); + return; + } + int size = read(fd, buff, 1024); + printf("%d: Read: %d bytes\n", fd, size); + size = write(fd, buff, size); + printf("%d: Wrote: %d bytes\n", fd, size); +} + +void l2_connect(int fd, short revents, void *data){ + + struct sockaddr_l2 addr; + unsigned char *a; + socklen_t length = sizeof(struct sockaddr_l2); + + UNUSED(revents); + UNUSED(data); + + printf("L2 connect started\n"); + + int sk = accept(fd, (struct sockaddr *)&addr, &length); + + a = addr.l2_bdaddr.b; + printf("Connect from: %02x:%02x:%02x:%02x:%02x:%02x port %d\n", a[5], a[4], a[3], a[2], a[1], a[0], addr.l2_psm); + addfd(head, sk, POLLIN|POLLHUP|POLLNVAL, l2_process, 0); + l2_process(sk, POLLIN, 0x0); +} + +void dbus_error(int fd, short revents, void *data){ + UNUSED(fd); + UNUSED(data); + if(revents&POLLHUP || revents&POLLNVAL){ + printf("dBus connection failed, shutting down\n"); + exit(-1); + } +} + +void registerService() +{ + DBusMessage* msg; + DBusMessageIter args; + DBusConnection* conn; + DBusError err; + DBusPendingCall* pending; + dbus_uint32_t level; + int fd; + + char path[PATH_MAX]; + const char *ret_string = 0; + + // initialiset the errors + dbus_error_init(&err); + conn = dbus_bus_get(DBUS_BUS_SYSTEM, &err); + if (dbus_error_is_set(&err)) { + fprintf(stderr, "Connection Error (%s)\n", err.message); + dbus_error_free(&err); + return; + } + + // create a new method call and check for errors + msg = dbus_message_new_method_call("org.bluez", // target for the method call + "/", // object to call on + "org.bluez.Manager", // interface to call on + "DefaultAdapter"); // method name + + if (!dbus_connection_send_with_reply (conn, msg, &pending, -1)) { + fprintf(stderr, "dbus-send failed: Out Of Memory!\n"); + return; + } + + dbus_connection_flush(conn); + + dbus_message_unref(msg); + dbus_pending_call_block(pending); + msg = dbus_pending_call_steal_reply(pending); + dbus_pending_call_unref(pending); + + if (!dbus_message_iter_init(msg, &args)) + fprintf(stderr, "Message has no arguments!\n"); + else if (DBUS_TYPE_OBJECT_PATH != dbus_message_iter_get_arg_type(&args)) + fprintf(stderr, "Argument is not an object path!\n"); + else + dbus_message_iter_get_basic(&args, &ret_string); + + if(!ret_string){ + fprintf(stderr, "Failed to get bluez path\n"); + return; + } + + strcpy(path, ret_string); + // change path to use any + strcpy(rindex(path, '/'), "/any"); + + printf("Using path: %s\n", path); + + dbus_message_unref(msg); + + // create a new method call and check for errors + msg = dbus_message_new_method_call("org.bluez", // target for the method call + path, // object to call on + "org.bluez.Service", // interface to call on + "AddRecord"); // method name + + if(!dbus_message_append_args(msg, DBUS_TYPE_STRING, &xmldefn, DBUS_TYPE_INVALID)){ + fprintf(stderr, "Failed to append args\n"); + return; + } + + // send message and get a handle for a reply + if (!dbus_connection_send_with_reply (conn, msg, &pending, -1)) { // -1 is default timeout + fprintf(stderr, "Out Of Memory!\n"); + exit(1); + } + dbus_connection_flush(conn); + + // free message + dbus_message_unref(msg); + + // block until we receive a reply + dbus_pending_call_block(pending); + + // get the reply message + msg = dbus_pending_call_steal_reply(pending); + if (NULL == msg) { + fprintf(stderr, "Reply Null\n"); + return; + } + // free the pending message handle + dbus_pending_call_unref(pending); + + // read the parameters + if (!dbus_message_iter_init(msg, &args)) + fprintf(stderr, "Message has no arguments!\n"); + else if (DBUS_TYPE_UINT32 != dbus_message_iter_get_arg_type(&args)) + fprintf(stderr, "Argument is not int!\n"); + else + dbus_message_iter_get_basic(&args, &level); + + printf("Got handle: 0x%x\n", level); + + // free reply + dbus_message_unref(msg); + + dbus_connection_get_socket(conn, &fd); + addfd(head, fd, POLLHUP|POLLNVAL, dbus_error, 0x0); +} + +int main(int argc, char **argv) +{ + int socket; +#define MAX_POLL 256 + struct pollfd fds[MAX_POLL]; + + UNUSED(argc); + UNUSED(argv); + + registerService(); + + socket = createListening(10); + head = addfd(head, socket, POLLIN, echo_connect, 0); // first creation + + socket = createListening(11); + addfd(head, socket, POLLIN, id_connect, 0); + + socket = createListeningL2cap(0x1011); // must be > 0x1001 and odd + addfd(head, socket, POLLIN, l2_connect, 0); + + while(1){ + int n = mkpoll(head, fds, MAX_POLL); + if(poll(fds, n, -1)){ + struct fdlist *fdl = head; + int i; + + for(i = 0; i < n; i++){ + if(fds[i].revents){ + while(fdl && fdl->fd != fds[i].fd) + fdl = fdl->next; + assert(fdl); + fdl->hanlder(fds[i].fd, fds[i].revents, fdl->ptr); + } + } + } + else { + perror("Poll failed"); + exit(-1); + } + } + + return 0; +} diff --git a/tests/btclient/btclient.h b/tests/btclient/btclient.h new file mode 100644 index 00000000..d6ab932c --- /dev/null +++ b/tests/btclient/btclient.h @@ -0,0 +1,47 @@ +/**************************************************************************** +** +** 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$ +** +****************************************************************************/ + +#ifndef BTCLIENT_H +#define BTCLIENT_H + +#define ECHO_SERVICE_UUID "90aaac86-8fa8-489c-ba6c-d540392c2da5" + +#endif // BTCLIENT_H diff --git a/tests/btclient/btclient.pro b/tests/btclient/btclient.pro new file mode 100644 index 00000000..1a96b99b --- /dev/null +++ b/tests/btclient/btclient.pro @@ -0,0 +1,8 @@ +include(../../staticconfig.pri) +TARGET = btclient +CONFIG += link_pkgconfig +PKGCONFIG += dbus-1 +QT -= gui \ + core +SOURCES = btclient.c +HEADERS += btclient.h diff --git a/tests/nfcsymbianbackend/common/qautomsgbox.cpp b/tests/nfcsymbianbackend/common/qautomsgbox.cpp new file mode 100644 index 00000000..c6576ea4 --- /dev/null +++ b/tests/nfcsymbianbackend/common/qautomsgbox.cpp @@ -0,0 +1,62 @@ +/**************************************************************************** +** +** 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 "qautomsgbox.h" + +QAutoMsgBox::QAutoMsgBox(QWidget *parent) : + QMessageBox(parent),m_timer(0),m_spy(0),m_signalCount(0) +{ + +} + +QAutoMsgBox::~QAutoMsgBox() +{ + delete m_timer; +} +bool QAutoMsgBox::event(QEvent *e) +{ + if (e->type() == QEvent::Close) + { + this->close(); + return true; + } + return false; +} diff --git a/tests/nfcsymbianbackend/common/qautomsgbox.h b/tests/nfcsymbianbackend/common/qautomsgbox.h new file mode 100644 index 00000000..ec27e77b --- /dev/null +++ b/tests/nfcsymbianbackend/common/qautomsgbox.h @@ -0,0 +1,107 @@ +/**************************************************************************** +** +** 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$ +** +****************************************************************************/ + +#ifndef QAUTOMSGBOX_H +#define QAUTOMSGBOX_H + +#include <QMessageBox> +#include <QTimer> +#include <QtTest/QtTest> +#include <QSignalSpy> +#include <QCloseEvent> + +class QAutoMsgBox : public QMessageBox +{ + Q_OBJECT + +public: + explicit QAutoMsgBox(QWidget *parent = 0); + ~QAutoMsgBox(); + /*! + * Call this method when you want to make the dialog dismissed + * when the signalspy's count is equal to the \a count + */ + void setSignalSpy(QSignalSpy* spy, int count) + { + if (spy == 0) + return; + m_spy = spy; + m_signalCount = count; + if (m_timer) + delete m_timer; + m_timer = new QTimer; + m_timer->setInterval(50); + connect(m_timer, SIGNAL(timeout()), this, SLOT(timeOutFired())); + m_timer->start(); + } + /*! + * Call this method when you want to make the dialog dismissed + * after /a timeout(ms) period + */ + void setDismissTimeOut(int timeout) + { + QTimer::singleShot(timeout, this, SLOT(singleShotSlot())); + } +private slots: + void timeOutFired() + { + if(m_spy->count() >= m_signalCount) + { + QApplication::postEvent(this, new QCloseEvent); + m_timer->stop(); + delete m_timer; + m_timer = 0; + } + } + void singleShotSlot() + { + QApplication::postEvent(this, new QCloseEvent); + } + +private: + bool event(QEvent *e); + QTimer *m_timer; + + QSignalSpy *m_spy;//not own + int m_signalCount; +}; + +#endif // QAUTOMSGBOX_H diff --git a/tests/nfcsymbianbackend/common/qdummyslot.cpp b/tests/nfcsymbianbackend/common/qdummyslot.cpp new file mode 100644 index 00000000..8503c244 --- /dev/null +++ b/tests/nfcsymbianbackend/common/qdummyslot.cpp @@ -0,0 +1,73 @@ +/**************************************************************************** +** +** 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 "qdummyslot.h" +#include "qnfctagtestcommon.h" + +QDummySlot::QDummySlot(QObject *parent) : + QObject(parent) +{ +} + +void QDummySlot::errorHandling(QNearFieldTarget::Error error, const QNearFieldTarget::RequestId& id) +{ + if (id == iReqId) + { + qDebug()<<"get the error signal, wait for dummy request"<<endl; + iOp->run(); + // iOp must use wait + iOp->checkSignal(); + iOp->checkResponse(); + qDebug()<<"waited request completed"<<endl; + } +} + +void QDummySlot::requestCompletedHandling(const QNearFieldTarget::RequestId& id) +{ + if (id == iReqId) + { + qDebug()<<"get the requestCompleted signal, wait for dummy request"<<endl; + iOp->run(); + // iOp must use wait + iOp->checkSignal(); + iOp->checkResponse(); + qDebug()<<"waited request completed"<<endl; + } +} diff --git a/tests/nfcsymbianbackend/common/qdummyslot.h b/tests/nfcsymbianbackend/common/qdummyslot.h new file mode 100644 index 00000000..92f58008 --- /dev/null +++ b/tests/nfcsymbianbackend/common/qdummyslot.h @@ -0,0 +1,67 @@ +/**************************************************************************** +** +** 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 DUMMYSLOT_H +#define DUMMYSLOT_H + +#include <QObject> +#include <QtTest/QtTest> +#include "qnearfieldtarget.h" +#include "qnfctestcommon.h" +#include "qnfctestutil.h" + +class MNfcTagOperation; + +class QDummySlot : public QObject +{ + Q_OBJECT +public: + explicit QDummySlot(QObject *parent = 0); + +public slots: + void errorHandling(QNearFieldTarget::Error error, const QNearFieldTarget::RequestId& id); + void requestCompletedHandling(const QNearFieldTarget::RequestId& id); +public: + QNearFieldTarget::RequestId iReqId; + MNfcTagOperation * iOp; +}; + +#endif // DUMMYSLOT_H + diff --git a/tests/nfcsymbianbackend/common/qnfctagtestcommon.h b/tests/nfcsymbianbackend/common/qnfctagtestcommon.h new file mode 100644 index 00000000..5dc389d8 --- /dev/null +++ b/tests/nfcsymbianbackend/common/qnfctagtestcommon.h @@ -0,0 +1,614 @@ +/**************************************************************************** +** +** 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 QNFCTAGTESTCOMMON_H +#define QNFCTAGTESTCOMMON_H + +#include <qnearfieldmanager.h> +#include <qnearfieldtarget.h> +#include <QtTest/QtTest> +#include <qndefmessage.h> +#include <qndefnfctextrecord.h> +#include <qndefnfcurirecord.h> +#include <qnearfieldtagtype1.h> +#include <qnearfieldtagtype2.h> +#include <qnearfieldtagtype3.h> +#include <qnearfieldtagtype4.h> +#include "qdummyslot.h" +#include "qnfctestcommon.h" +#include "qnfctestutil.h" + +template<typename TAG> +struct TagTrait +{ + static QNearFieldTarget::Type type() { return QNearFieldTarget::ProprietaryTag; } + static QString info(){ return QString("unknow tag"); } +}; + +template<> +struct TagTrait<QNearFieldTagType1> +{ + static QNearFieldTarget::Type type() { return QNearFieldTarget::NfcTagType1; } + static QString info(){ return QString("tag type 1"); } +}; + +template<> +struct TagTrait<QNearFieldTagType2> +{ + static QNearFieldTarget::Type type() { return QNearFieldTarget::NfcTagType2; } + static QString info(){ return QString("tag type 2"); } +}; + +template<> +struct TagTrait<QNearFieldTagType3> +{ + static QNearFieldTarget::Type type() { return QNearFieldTarget::NfcTagType3; } + static QString info(){ return QString("tag type 3"); } +}; + +template<> +struct TagTrait<QNearFieldTagType4> +{ + static QNearFieldTarget::Type type() { return QNearFieldTarget::NfcTagType4; } + static QString info(){ return QString("tag type 4"); } +}; + + + +class MNfcTagOperation +{ +public: + MNfcTagOperation(QNearFieldTarget * tag) + { + mTarget = tag; + } + virtual void run() = 0; + virtual void checkSignal() = 0; + virtual void checkResponse() = 0; + virtual ~MNfcTagOperation(){}; +protected: + // Not own + QNearFieldTarget * mTarget; +}; + +class NfcTagRawCommandOperationCommon : public MNfcTagOperation +{ +public: + enum Wait + { + ENoWait, + EWaitTrue, + EWaitFalse + }; + + enum Signal + { + ENoSignal, + EErrorSignal, + ECompleteSignal + }; +public: + inline NfcTagRawCommandOperationCommon(QNearFieldTarget * tag); + + ~NfcTagRawCommandOperationCommon() + { + delete okSpy; + delete errSpy; + } + + void checkSignal() + { + qDebug()<<"checkSignal begin"; + qDebug()<<"checking signal type "<<mSignalType; + // check signal + switch (mSignalType) + { + case EErrorSignal: + { + int findRequest = 0; + for (int i = 0; i < errSpy->count(); ++i) + { + if (mId == errSpy->at(i).at(1).value<QNearFieldTarget::RequestId>()) + { + qDebug()<<"real err code "<<(int)(errSpy->at(i).at(0).value<QNearFieldTarget::Error>()); + qDebug()<<"expect err code "<<(int)(mExpectedErrCode); + QCOMPARE(errSpy->at(i).at(0).value<QNearFieldTarget::Error>(), mExpectedErrCode); + ++findRequest; + } + } + qDebug()<<"find "<<findRequest<<" errSignal"; + QCOMPARE(findRequest, 1); + + findRequest = 0; + for (int i = 0; i < okSpy->count(); ++i) + { + if (mId == okSpy->at(i).at(0).value<QNearFieldTarget::RequestId>()) + { + ++findRequest; + } + } + qDebug()<<"find "<<findRequest<<" okSignal"; + QCOMPARE(findRequest, 0); + break; + } + + case ECompleteSignal: + { + int findResult = 0; + for (int i = 0; i < okSpy->count(); ++i) + { + if (mId == okSpy->at(i).at(0).value<QNearFieldTarget::RequestId>()) + { + ++findResult; + } + } + QCOMPARE(findResult, 1); + + findResult = 0; + for (int i = 0; i < errSpy->count(); ++i) + { + if (mId == errSpy->at(i).at(1).value<QNearFieldTarget::RequestId>()) + { + ++findResult; + } + } + QTRY_COMPARE(findResult, 0); + break; + } + + default: + { + int findRequest = 0; + for (int i = 0; i < errSpy->count(); ++i) + { + if (mId == errSpy->at(i).at(1).value<QNearFieldTarget::RequestId>()) + { + ++findRequest; + } + } + QTRY_COMPARE(findRequest, 0); + + findRequest = 0; + for (int i = 0; i < okSpy->count(); ++i) + { + if (mId == okSpy->at(i).at(0).value<QNearFieldTarget::RequestId>()) + { + ++findRequest; + } + } + QTRY_COMPARE(findRequest, 0); + } + } + qDebug()<<"checkSignal end"; + } + + void checkResponse() + { + qDebug()<<"checkResponse begin"; + QTRY_COMPARE(mTarget->requestResponse(mId), mExpectedResult); + qDebug()<<"checkResponse end"; + } + + void setWaitOperation(NfcTagRawCommandOperationCommon::Wait waitOp) { mWaitOp = waitOp; } + void setExpectedErrorSignal(QNearFieldTarget::Error error) { mExpectedErrCode = error; mSignalType = EErrorSignal; } + void setExpectedOkSignal() { mSignalType = ECompleteSignal; } + void setExpectedResponse(QVariant expected){ mExpectedResult = expected; } + void setIfExpectInvalidId() { mInvalidId = true; } + void checkInvalidId() { if (mInvalidId) QVERIFY(!mId.isValid()); } + void waitRequest() + { + if (mWaitOp == NfcTagRawCommandOperationCommon::EWaitFalse) + { + QVERIFY(!mTarget->waitForRequestCompleted(mId)); + } + else if (mWaitOp == NfcTagRawCommandOperationCommon::EWaitTrue) + { + QVERIFY(mTarget->waitForRequestCompleted(mId)); + } + } + + QNearFieldTarget::RequestId mId; +protected: + QSignalSpy * okSpy; + QSignalSpy * errSpy; + Wait mWaitOp; + Signal mSignalType; + QNearFieldTarget::Error mExpectedErrCode; + QVariant mExpectedResult; + bool mInvalidId; +}; + +NfcTagRawCommandOperationCommon::NfcTagRawCommandOperationCommon(QNearFieldTarget * tag) : MNfcTagOperation(tag) + { + mWaitOp = ENoWait; + mSignalType = ENoSignal; + mInvalidId = false; + okSpy = new QSignalSpy(mTarget, SIGNAL(requestCompleted(const QNearFieldTarget::RequestId&))); + errSpy = new QSignalSpy(mTarget, SIGNAL(error(QNearFieldTarget::Error, const QNearFieldTarget::RequestId&))); + } + +// Ndef signal count check has limit. Use Ndef operation only once so far. +class NfcTagNdefOperationCommon : public MNfcTagOperation +{ +public: + enum Signal + { + ENoSignal, + EErrorSignal, + EReadSignal, + EWriteSignal + }; +public: + inline NfcTagNdefOperationCommon(QNearFieldTarget * tag); + + ~NfcTagNdefOperationCommon() + { + delete errSpy; + delete ndefMessageReadSpy; + delete ndefMessagesWrittenSpy; + } + + void run() + { + if (readNdefMessages) + { + (mTarget->*readNdefMessages)(); + } + + if (writeNdefMessages) + { + (mTarget->*writeNdefMessages)(mInputMessages); + } + } + + void checkSignal() + { + // check signal + switch (mSignalType) + { + case NfcTagNdefOperationCommon::EErrorSignal: + { + for (int i = 0; i < errSpy->count(); ++i) + { + if (!(errSpy->at(i).at(0).value<QNearFieldTarget::RequestId>().isValid())) + { + QTRY_COMPARE(errSpy->at(i).at(1).value<QNearFieldTarget::Error>(), mExpectedErrCode); + break; + } + } + + break; + } + + case NfcTagNdefOperationCommon::EReadSignal: + { + QVERIFY(ndefMessageReadSpy->count()>0); + for (int i = 0; i < ndefMessageReadSpy->count(); ++i) + { + mReceivedMessages.push_back(ndefMessageReadSpy->at(i).at(0).value<QNdefMessage>()); + } + break; + } + + case NfcTagNdefOperationCommon::EWriteSignal: + { + QTRY_COMPARE(ndefMessagesWrittenSpy->count(), 1); + break; + } + + default: + { + QTRY_COMPARE(errSpy->count(), 0); + QTRY_COMPARE(ndefMessageReadSpy->count(), 0); + QTRY_COMPARE(ndefMessagesWrittenSpy->count(), 0); + } + } + } + void checkResponse() + { + if (!mExpectedMessages.isEmpty()) + { + QTRY_COMPARE(mReceivedMessages, mExpectedMessages); + } + } + + void setExpectedErrorSignal(QNearFieldTarget::Error error) { mExpectedErrCode = error; mSignalType = NfcTagNdefOperationCommon::EErrorSignal; } + void setExpectedNdefReadSignal() { mSignalType = NfcTagNdefOperationCommon::EReadSignal; } + void setExpectedNdefWriteSignal() { mSignalType = NfcTagNdefOperationCommon::EWriteSignal; } + + void setReadNdefOperation() { readNdefMessages = &QNearFieldTarget::readNdefMessages; } + void setWriteNdefOperation(const QList<QNdefMessage> &messages) { mInputMessages = messages; writeNdefMessages = &QNearFieldTarget::writeNdefMessages; } + +protected: + QSignalSpy * errSpy; + QSignalSpy * ndefMessageReadSpy; + QSignalSpy * ndefMessagesWrittenSpy; + NfcTagNdefOperationCommon::Signal mSignalType; + QNearFieldTarget::Error mExpectedErrCode; + QList<QNdefMessage> mInputMessages; + QList<QNdefMessage> mExpectedMessages; + QList<QNdefMessage> mReceivedMessages; + QNearFieldTarget::RequestId (QNearFieldTarget::*readNdefMessages)(); + QNearFieldTarget::RequestId (QNearFieldTarget::*writeNdefMessages)(const QList<QNdefMessage> &messages); +}; + +NfcTagNdefOperationCommon::NfcTagNdefOperationCommon(QNearFieldTarget * tag) : MNfcTagOperation(tag) +{ + QSignalSpy * errSpy = new QSignalSpy(mTarget, SIGNAL(error(QNearFieldTarget::Error, const QNearFieldTarget::RequestId&))); + QSignalSpy * ndefMessageReadSpy = new QSignalSpy(mTarget, SIGNAL(ndefMessageRead(QNdefMessage))); + QSignalSpy * ndefMessagesWrittenSpy = new QSignalSpy(mTarget, SIGNAL(ndefMessagesWritten())); + mSignalType = ENoSignal; + readNdefMessages = 0; + writeNdefMessages = 0; +} + +class NfcTagSendCommandsCommon : public NfcTagRawCommandOperationCommon +{ +public: + inline NfcTagSendCommandsCommon(QNearFieldTarget * tag); +public: + void run() + { + mId = mTarget->sendCommands(mCommands); + checkInvalidId(); + waitRequest(); + } + void checkResponse() + { + QTRY_COMPARE(mTarget->requestResponse(mId).value<QVariantList>(), mExpectedResponse); + } +public: + void SetCommandLists(QList<QByteArray> commands) { mCommands = commands; } + void SetExpectedResponse(QVariantList response) { mExpectedResponse = response; } +protected: + QList<QByteArray> mCommands; + QVariantList mExpectedResponse; +}; + +NfcTagSendCommandsCommon::NfcTagSendCommandsCommon(QNearFieldTarget * tag) : NfcTagRawCommandOperationCommon(tag) +{ +} + +typedef QList<MNfcTagOperation *> OperationList; + +Q_DECLARE_METATYPE(QNearFieldTarget*) +Q_DECLARE_METATYPE(QNearFieldTarget::Type) +Q_DECLARE_METATYPE(QNearFieldTarget::AccessMethod) +Q_DECLARE_METATYPE(MNfcTagOperation *) +Q_DECLARE_METATYPE(OperationList) + +template <typename TAG> +class QNfcTagTestCommon +{ +public: + QNfcTagTestCommon(); + ~QNfcTagTestCommon(); + void touchTarget(QString info = QString("")); + void removeTarget(); + void testSequence(OperationList& operations); + void testWaitInSlot(MNfcTagOperation * op1, NfcTagRawCommandOperationCommon * op2WithWait, MNfcTagOperation * op3, MNfcTagOperation * waitOpInSlot); + void testDeleteOperationBeforeAsyncRequestComplete(OperationList& operations); + void testRemoveTagBeforeAsyncRequestComplete(OperationList& operations1, OperationList& operations2); + void testCancelNdefOperation(); +public: + QNearFieldManager manager; + TAG* target; +}; + +template<typename TAG> +QNfcTagTestCommon<TAG>::QNfcTagTestCommon() +{ + target = 0; + qRegisterMetaType<QNdefMessage>("QNdefMessage"); + qRegisterMetaType<QNearFieldTarget *>("QNearFieldTarget*"); + qRegisterMetaType<QNearFieldTarget::Error>("QNearFieldTarget::Error"); + qRegisterMetaType<QNearFieldTarget::RequestId>("QNearFieldTarget::RequestId"); + qRegisterMetaType<MNfcTagOperation *>("MNfcTagOperation *"); + qRegisterMetaType<OperationList>("OperatoinList"); +} + + +template<typename TAG> +QNfcTagTestCommon<TAG>::~QNfcTagTestCommon() +{ + if (target) + { + delete target; + } +} + +template<typename TAG> +void QNfcTagTestCommon<TAG>::touchTarget(QString info) +{ + if (target) + { + delete target; + target = 0; + } + QSignalSpy targetDetectedSpy(&manager, SIGNAL(targetDetected(QNearFieldTarget*))); + QSignalSpy targetLostSpy(&manager, SIGNAL(targetLost(QNearFieldTarget*))); + + qDebug()<<"start detect tag type "<<TagTrait<TAG>::type()<<endl; + manager.startTargetDetection(TagTrait<TAG>::type()); + + QString hint("please touch "); + hint += TagTrait<TAG>::info(); + hint += info; + QNfcTestUtil::ShowAutoMsg(hint, &targetDetectedSpy); + + QTRY_VERIFY(!targetDetectedSpy.isEmpty()); + target = qobject_cast<TAG *>(targetDetectedSpy.at(targetDetectedSpy.count()-1).at(0).value<QNearFieldTarget *>()); + // make sure target can be detected + QVERIFY(target); + + // make sure target uid is not empty + QVERIFY(!target->uid().isEmpty()); + + QCOMPARE(target->type(), TagTrait<TAG>::type()); +} + +template<typename TAG> +void QNfcTagTestCommon<TAG>::removeTarget() +{ + QVERIFY(target); + + QSignalSpy targetLostSpy(&manager, SIGNAL(targetLost(QNearFieldTarget*))); + QSignalSpy disconnectedSpy(target, SIGNAL(disconnected())); + + QNfcTestUtil::ShowAutoMsg("please remove the tag", &targetLostSpy); + QTRY_VERIFY(!targetLostSpy.isEmpty()); + + TAG *lostTarget = qobject_cast<TAG*>(targetLostSpy.first().at(0).value<QNearFieldTarget *>()); + + QCOMPARE(target, lostTarget); + + QVERIFY(!disconnectedSpy.isEmpty()); + + manager.stopTargetDetection(); +} + +template<typename TAG> +void QNfcTagTestCommon<TAG>::testSequence(OperationList& operations) +{ + qDebug()<<"_testSequence begin"; + for (int i = 0; i < operations.count(); ++i) + { + operations.at(i)->run(); + } + + QTest::qWait(10000); + for (int i = 0; i < operations.count(); ++i) + { + operations.at(i)->checkSignal(); + operations.at(i)->checkResponse(); + } + + qDebug()<<"_testSequence end"; +} + +template <typename TAG> +void QNfcTagTestCommon<TAG>::testWaitInSlot(MNfcTagOperation * op1, NfcTagRawCommandOperationCommon * op2WithWait, MNfcTagOperation * op3, MNfcTagOperation * waitOpInSlot) +{ + QDummySlot waitSlot; + QObject::connect(target, SIGNAL(requestCompleted(const QNearFieldTarget::RequestId&)), + &waitSlot, SLOT(requestCompletedHandling(const QNearFieldTarget::RequestId&))); + QObject::connect(target, SIGNAL(error(QNearFieldTarget::Error, const QNearFieldTarget::RequestId&)), + &waitSlot, SLOT(errorHandling(QNearFieldTarget::Error, const QNearFieldTarget::RequestId&))); + + waitSlot.iOp = waitOpInSlot; + + op1->run(); + op2WithWait->run(); + QVERIFY(!target->waitForRequestCompleted(op2WithWait->mId)); + op3->run(); + + QTest::qWait(10000); + op1->checkSignal(); + op1->checkResponse(); + + op2WithWait->checkSignal(); + op2WithWait->checkResponse(); + + op3->checkSignal(); + op3->checkResponse(); +} + +template <typename TAG> +void QNfcTagTestCommon<TAG>::testDeleteOperationBeforeAsyncRequestComplete(OperationList& operations) +{ + for (int i = 0; i < operations.count(); ++i) + { + operations.at(i)->run(); + } + delete target; + target = 0; + + QNfcTestUtil::ShowMessage("Remove tag and press ok"); +} + +template <typename TAG> +void QNfcTagTestCommon<TAG>::testRemoveTagBeforeAsyncRequestComplete(OperationList& operations1, OperationList& operations2) +{ + for (int i = 0; i < operations1.count(); ++i) + { + operations1.at(i)->run(); + } + + QSignalSpy targetLostSpy(&manager, SIGNAL(targetLost(QNearFieldTarget*))); + + QNfcTestUtil::ShowAutoMsg("please remove the tag", &targetLostSpy); + QTRY_VERIFY(!targetLostSpy.isEmpty()); + + for (int i = 0; i < operations2.count(); ++i) + { + operations2.at(i)->run(); + } + delete target; + target = 0; +} + +template<typename TAG> +void QNfcTagTestCommon<TAG>::testCancelNdefOperation() +{ + target->readNdefMessages(); + delete target; + target = 0; + + QNfcTestUtil::ShowMessage("please remove tag and press ok"); + + touchTarget(); + + QNdefMessage message; + QNdefNfcTextRecord textRecord; + textRecord.setText(QLatin1String("nfc")); + + message.append(textRecord); + + QList<QNdefMessage> messages; + messages.append(message); + + target->writeNdefMessages(messages); + delete target; + target = 0; + + QNfcTestUtil::ShowMessage("please remove tag and press ok"); +} +#endif // QNFCTAGTESTCOMMON_H diff --git a/tests/nfcsymbianbackend/common/qnfctagutil.cpp b/tests/nfcsymbianbackend/common/qnfctagutil.cpp new file mode 100644 index 00000000..67d88339 --- /dev/null +++ b/tests/nfcsymbianbackend/common/qnfctagutil.cpp @@ -0,0 +1,97 @@ +/**************************************************************************** +** +** 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 "qnfctagutil.h" + +bool QNfcTagUtil::WriteTextNdef2Tag(QNearFieldTarget& target, QString text) +{ + QSignalSpy ndefMessageWriteSpy(&target, SIGNAL(ndefMessagesWritten())); + QNdefMessage message; + QNdefNfcTextRecord textRecord; + textRecord.setText(text); + + message.append(textRecord); + + QList<QNdefMessage> messages; + messages.append(message); + target.writeNdefMessages(messages); + QTest::qWait(5000); + return (ndefMessageWriteSpy.count() > 0); +} + +bool QNfcTagUtil::WriteTextUriNdef2Tag(QNearFieldTarget& target, QUrl uri, QString text) +{ + QSignalSpy ndefMessageWriteSpy(&target, SIGNAL(ndefMessagesWritten())); + QNdefMessage message; + + QNdefNfcTextRecord textRecord; + textRecord.setText(text); + + message.append(textRecord); + + QNdefNfcUriRecord uriRecord; + uriRecord.setUri(uri); + message.append(uriRecord); + + QList<QNdefMessage> messages; + messages.append(message); + + target.writeNdefMessages(messages); + QTest::qWait(5000); + return (ndefMessageWriteSpy.count() > 0); +} + +bool QNfcTagUtil::WriteUriNdef2Tag(QNearFieldTarget& target, QUrl uri) +{ + QSignalSpy ndefMessageWriteSpy(&target, SIGNAL(ndefMessagesWritten())); + QNdefMessage message; + + QNdefNfcUriRecord uriRecord; + uriRecord.setUri(uri); + message.append(uriRecord); + + QList<QNdefMessage> messages; + messages.append(message); + + target.writeNdefMessages(messages); + QTest::qWait(5000); + return (ndefMessageWriteSpy.count() > 0); +} diff --git a/tests/nfcsymbianbackend/common/qnfctagutil.h b/tests/nfcsymbianbackend/common/qnfctagutil.h new file mode 100644 index 00000000..0a78c6ae --- /dev/null +++ b/tests/nfcsymbianbackend/common/qnfctagutil.h @@ -0,0 +1,63 @@ +/**************************************************************************** +** +** 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$ +** +****************************************************************************/ + +#ifndef QNFCTAGUTIL_H +#define QNFCTAGUTIL_H +#include <qnearfieldmanager.h> +#include <qnearfieldtarget.h> +#include <QtTest/QtTest> +#include "qnfctestcommon.h" +#include "qnfctestutil.h" +#include <qndefmessage.h> +#include <qndefnfctextrecord.h> +#include <qndefnfcurirecord.h> +#include <qnearfieldtagtype1.h> +#include <qnearfieldtagtype2.h> +#include <qnearfieldtagtype3.h> +#include <qnearfieldtagtype4.h> + +struct QNfcTagUtil +{ + static bool WriteTextNdef2Tag(QNearFieldTarget& target, QString text = QString("nfc tag test")); + static bool WriteUriNdef2Tag(QNearFieldTarget& target, QUrl uri = QUrl("http://qt.nokia.com")); + static bool WriteTextUriNdef2Tag(QNearFieldTarget& target, QUrl uri = QUrl("http://qt.nokia.com"), QString text = QString("nfc tag test")); +}; +#endif diff --git a/tests/nfcsymbianbackend/common/qnfctestcommon.h b/tests/nfcsymbianbackend/common/qnfctestcommon.h new file mode 100644 index 00000000..19c90333 --- /dev/null +++ b/tests/nfcsymbianbackend/common/qnfctestcommon.h @@ -0,0 +1,87 @@ +/**************************************************************************** +** +** 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$ +** +****************************************************************************/ + +#ifndef QNFCTESTCOMMON_H +#define QNFCTESTCOMMON_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 = 4000; \ + 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/nfcsymbianbackend/common/qnfctestutil.h b/tests/nfcsymbianbackend/common/qnfctestutil.h new file mode 100644 index 00000000..cf22dfa8 --- /dev/null +++ b/tests/nfcsymbianbackend/common/qnfctestutil.h @@ -0,0 +1,80 @@ +/**************************************************************************** +** +** 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$ +** +****************************************************************************/ +#ifndef QNFCTESTUTIL_H +#define QNFCTESTUTIL_H +#include <QMessageBox> +#include "qautomsgbox.h" + +const int MsgBoxTimeOutTime = 3*1000; +class QNfcTestUtil : public QObject +{ + Q_OBJECT +public: + static void ShowMessage(const QString& message) + { + QMessageBox b(QMessageBox::Information, QObject::tr("NFC symbian backend test"), + message, QMessageBox::Ok); + b.exec(); + } + static void ShowAutoMsg(const QString& message, QSignalSpy* spy, int count = 1) + { + QAutoMsgBox w; + w.addButton(QMessageBox::Ok); + w.setIcon(QMessageBox::Information); + w.setText(message); + w.setWindowTitle(QObject::tr("NFC symbian backend test")); + w.setSignalSpy(spy, count); + + w.exec(); + } + static void ShowAutoMsg(const QString& message, int mseconds = MsgBoxTimeOutTime) + { + QAutoMsgBox w; + w.addButton(QMessageBox::Ok); + w.setIcon(QMessageBox::Information); + w.setText(message); + w.setWindowTitle(QObject::tr("NFC symbian backend test")); + w.setDismissTimeOut(mseconds); + + w.exec(); + } +}; +#endif diff --git a/tests/nfcsymbianbackend/nfcsymbianbackend.pro b/tests/nfcsymbianbackend/nfcsymbianbackend.pro new file mode 100644 index 00000000..f8d7d8c1 --- /dev/null +++ b/tests/nfcsymbianbackend/nfcsymbianbackend.pro @@ -0,0 +1,6 @@ +TEMPLATE = subdirs + +symbian { + + SUBDIRS += qnearfieldmanager qllcpserver qllcpsockettype2 qllcpsocketlocal qllcpsocketremote qnearfieldtagtype1 qnearfieldtagtype2 qnearfieldtagtype3 qnearfieldtagtype4 nfctestserviceprovider +} diff --git a/tests/nfcsymbianbackend/nfctestserviceprovider/main.cpp b/tests/nfcsymbianbackend/nfctestserviceprovider/main.cpp new file mode 100644 index 00000000..b519b03e --- /dev/null +++ b/tests/nfcsymbianbackend/nfctestserviceprovider/main.cpp @@ -0,0 +1,164 @@ +/**************************************************************************** +** +** 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 "nfctestserviceprovider.h" + +#include <QtGui> +#include <QApplication> +#include <qremoteserviceregister.h> +#include <qservicemanager.h> + +#include <QDebug> +#include <qnearfieldmanager.h> +#include <qndefmessage.h> +#include <qnearfieldtarget.h> + +#include <iostream> +#include <fstream> + +using namespace std; + +#include <unistd.h> +#include <sys/types.h> +#include <sys/stat.h> +#include <fcntl.h> + +void MyOutputHandler(QtMsgType type, const char *msg) { + static int fd = -1; + if (fd == -1) + fd = ::open("E:\\nfctestserviceprovider.log", O_WRONLY | O_CREAT); + + ::write(fd, msg, strlen(msg)); + ::write(fd, "\n", 1); + ::fsync(fd); + + switch (type) { + case QtFatalMsg: + abort(); + } +} + +nfctestserviceprovider* w; + +class MyContentHandler : public QObject +{ + Q_OBJECT + + +signals: + void userHandleMessage(const QNdefMessage& msg, QNearFieldTarget* target); + +public slots: + void handleMessage(const QNdefMessage& msg, QNearFieldTarget* target) + { + QFile m_file("E:\\testserviceprovider.dat"); + m_file.open(QIODevice::ReadWrite | QIODevice::Append); + QDataStream *m_dataStream = new QDataStream(&m_file); + QByteArray msgArray = msg.toByteArray(); + (*m_dataStream) << msgArray; + delete m_dataStream; + + w->close(); + } + +public: + MyContentHandler(QObject* parent = 0) + : QObject(parent) + { + qDebug() << " MyContentHandler constructed !!!!!" << endl; + connect(this, SIGNAL(userHandleMessage(const QNdefMessage& , QNearFieldTarget* )), + this, SLOT(handleMessage(const QNdefMessage& , QNearFieldTarget* ))); + } + +}; + +void unregisterExampleService() +{ + QServiceManager m; + m.removeService("nfctestserviceprovider"); +} + +void registerExampleService() +{ + unregisterExampleService(); + QServiceManager m; + const QString path = QCoreApplication::applicationDirPath() + "/xmldata/nfctestserviceprovider.xml"; + qWarning() << "xml path:" << path; + if (!m.addService(path)) + { + qWarning() << "Cannot register service provider" << path; + } + else + { + qDebug() << " Register ok" << endl; + } +} + +Q_DECLARE_METATYPE(QMetaType::Type); + + + +int main(int argc, char *argv[]) +{ + QApplication app(argc, argv); + + w = new nfctestserviceprovider(); + w->setWindowTitle( "nfc test service provider" ); + w->showMaximized(); + + //qInstallMsgHandler(MyOutputHandler); + + qRegisterMetaType<QNearFieldTarget*>("QNearFieldTarget*"); + qRegisterMetaType<QNdefMessage>("QNdefMessage"); + + registerExampleService(); + + MyContentHandler handler; + QNearFieldManager manager; + + int handle = manager.registerNdefMessageHandler(&handler, SIGNAL(userHandleMessage(QNdefMessage, QNearFieldTarget*))); + int ret = app.exec(); + manager.unregisterNdefMessageHandler(handle); + delete w; + return ret; +} + +#include "main.moc" diff --git a/tests/nfcsymbianbackend/nfctestserviceprovider/makesis.bat b/tests/nfcsymbianbackend/nfctestserviceprovider/makesis.bat new file mode 100644 index 00000000..d4b7ee28 --- /dev/null +++ b/tests/nfcsymbianbackend/nfctestserviceprovider/makesis.bat @@ -0,0 +1,49 @@ +::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:: +:: 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$ +:: +::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: + +set EPOC_TOOLS_ROOT=\epoc32\tools +set CERTIFICATE_PATH=\\begrp101\groups6\PCCONN\Tools\RnD_certs + +%EPOC_TOOLS_ROOT%\makesis nfctestserviceprovider_template.pkg nfctestserviceprovider_unsigned.sis + +%EPOC_TOOLS_ROOT%\signsis -s nfctestserviceprovider_unsigned.sis nfctestserviceprovider.sisx %CERTIFICATE_PATH%\Nokia_RnDCert_02.der %CERTIFICATE_PATH%\Nokia_RnDCert_02.key + +del nfctestserviceprovider_unsigned.sis diff --git a/tests/nfcsymbianbackend/nfctestserviceprovider/nfctestserviceprovider.cpp b/tests/nfcsymbianbackend/nfctestserviceprovider/nfctestserviceprovider.cpp new file mode 100644 index 00000000..b6477fc4 --- /dev/null +++ b/tests/nfcsymbianbackend/nfctestserviceprovider/nfctestserviceprovider.cpp @@ -0,0 +1,53 @@ +/**************************************************************************** +** +** 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 "nfctestserviceprovider.h" + +nfctestserviceprovider::nfctestserviceprovider(QWidget *parent) + : QMainWindow(parent) +{ + ui.setupUi(this); +} + +nfctestserviceprovider::~nfctestserviceprovider() +{ + +} diff --git a/tests/nfcsymbianbackend/nfctestserviceprovider/nfctestserviceprovider.h b/tests/nfcsymbianbackend/nfctestserviceprovider/nfctestserviceprovider.h new file mode 100644 index 00000000..31123adf --- /dev/null +++ b/tests/nfcsymbianbackend/nfctestserviceprovider/nfctestserviceprovider.h @@ -0,0 +1,60 @@ +/**************************************************************************** +** +** 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 nfctestserviceprovider_H +#define nfctestserviceprovider_H + +#include <QtGui/QMainWindow> +#include "ui_nfctestserviceprovider.h" + +class nfctestserviceprovider : public QMainWindow +{ + Q_OBJECT + +public: + nfctestserviceprovider(QWidget *parent = 0); + ~nfctestserviceprovider(); + +private: + Ui::nfctestserviceprovider ui; +}; + +#endif // nfctestserviceprovider_H diff --git a/tests/nfcsymbianbackend/nfctestserviceprovider/nfctestserviceprovider.pro b/tests/nfcsymbianbackend/nfctestserviceprovider/nfctestserviceprovider.pro new file mode 100644 index 00000000..2d2a5ac1 --- /dev/null +++ b/tests/nfcsymbianbackend/nfctestserviceprovider/nfctestserviceprovider.pro @@ -0,0 +1,52 @@ +TEMPLATE = app +TARGET = nfctestserviceprovider + +QT += core gui serviceframework + +CONFIG += no_icon + +INCLUDEPATH += ../../../src/nfc +DEPENDPATH += ../../../src/nfc +INCLUDEPATH += ../common +DEPENDPATH += ../common + +INCLUDEPATH += ../../../src/global +DEPENDPATH += ../../../src/global + +HEADERS += nfctestserviceprovider.h +SOURCES += nfctestserviceprovider_reg.rss \ + main.cpp \ + nfctestserviceprovider.cpp +FORMS += nfctestserviceprovider.ui +RESOURCES += + +symbian: { + TARGET.UID3 = 0xe347d948 + MMP_RULES += DEBUGGABLE_UDEBONLY +} + + +wince*|symbian*: { + addFiles.sources = nfctestserviceprovider.xml + addFiles.path = xmldata + addFiles2.sources = nfctestserviceprovider.xml + addFiles2.path = /private/2002AC7F/import/ + DEPLOYMENT += addFiles addFiles2 +} + +symbian { + TARGET.UID3 = 0xe347d949 + TARGET.CAPABILITY = LocalServices + } + + +wince* { + DEFINES+= TESTDATA_DIR=\\\".\\\" +} else:!symbian { + DEFINES += TESTDATA_DIR=\\\"$$PWD/\\\" +} + +xml.path = $$QT_MOBILITY_EXAMPLES/xmldata +xml.files = nfctestserviceprovider.xml +INSTALLS += xml + diff --git a/tests/nfcsymbianbackend/nfctestserviceprovider/nfctestserviceprovider.ui b/tests/nfcsymbianbackend/nfctestserviceprovider/nfctestserviceprovider.ui new file mode 100644 index 00000000..33683597 --- /dev/null +++ b/tests/nfcsymbianbackend/nfctestserviceprovider/nfctestserviceprovider.ui @@ -0,0 +1,30 @@ +<ui version="4.0" > + <class>nfctestserviceprovider</class> + <widget class="QMainWindow" name="nfctestserviceprovider" > + <property name="geometry" > + <rect> + <x>0</x> + <y>0</y> + <width>800</width> + <height>600</height> + </rect> + </property> + <property name="windowTitle" > + <string>nfctestserviceprovider</string> + </property> + <widget class="QWidget" name="centralwidget" /> + <widget class="QMenuBar" name="menubar" > + <property name="geometry" > + <rect> + <x>0</x> + <y>0</y> + <width>800</width> + <height>21</height> + </rect> + </property> + </widget> + <widget class="QStatusBar" name="statusbar" /> + </widget> + <resources/> + <connections/> +</ui> diff --git a/tests/nfcsymbianbackend/nfctestserviceprovider/nfctestserviceprovider.xml b/tests/nfcsymbianbackend/nfctestserviceprovider/nfctestserviceprovider.xml new file mode 100644 index 00000000..5b6d9f37 --- /dev/null +++ b/tests/nfcsymbianbackend/nfctestserviceprovider/nfctestserviceprovider.xml @@ -0,0 +1,15 @@ +<?xml version="1.0" encoding="UTF-8"?> +<SFW version="1.1"> +<service> + <name>nfctestserviceprovider</name> + <ipcaddress>nfctestserviceprovider</ipcaddress> + <description>NFC serive provider</description> + <interface> + <name>com.nokia.qt.nfc.NdefMessageHandler</name> + <version>1.0</version> + <description>nfc service provider</description> + <capabilities></capabilities> + <customproperty key="datatype">urn:nfc:ext:R||abc</customproperty> + </interface> +</service> +</SFW> diff --git a/tests/nfcsymbianbackend/nfctestserviceprovider2/main.cpp b/tests/nfcsymbianbackend/nfctestserviceprovider2/main.cpp new file mode 100644 index 00000000..9dc4e1b1 --- /dev/null +++ b/tests/nfcsymbianbackend/nfctestserviceprovider2/main.cpp @@ -0,0 +1,170 @@ +/**************************************************************************** +** +** 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 "nfctestserviceprovider2.h" + +#include <QtGui> +#include <QApplication> +#include <qremoteserviceregister.h> +#include <qservicemanager.h> + +#include <QDebug> +#include <qnearfieldmanager.h> +#include <qndefmessage.h> +#include <qnearfieldtarget.h> + +#include <iostream> +#include <fstream> + +using namespace std; + +#include <unistd.h> +#include <sys/types.h> +#include <sys/stat.h> +#include <fcntl.h> + +void MyOutputHandler(QtMsgType type, const char *msg) { + static int fd = -1; + if (fd == -1) + fd = ::open("E:\\nfctestserviceprovider2.log", O_WRONLY | O_CREAT); + + ::write(fd, msg, strlen(msg)); + ::write(fd, "\n", 1); + ::fsync(fd); + + switch (type) { + case QtFatalMsg: + abort(); + } +} + +nfctestserviceprovider2* w; + +class MyContentHandler : public QObject +{ + Q_OBJECT + + +signals: + void userHandleMessage(const QNdefMessage& msg, QNearFieldTarget* target); + +public slots: + void handleMessage(const QNdefMessage& msg, QNearFieldTarget* target) + { + QFile m_file("E:\\testserviceprovider2.dat"); + m_file.open(QIODevice::ReadWrite | QIODevice::Append); + QDataStream m_dataStream(&m_file); + QByteArray msgArray = msg.toByteArray(); + m_dataStream << msgArray; + + w->close(); + } + +public: + MyContentHandler(QObject* parent = 0) + : QObject(parent) + { + qDebug() << " MyContentHandler constructed !!!!!" << endl; + connect(this, SIGNAL(userHandleMessage(const QNdefMessage& , QNearFieldTarget* )), + this, SLOT(handleMessage(const QNdefMessage& , QNearFieldTarget* ))); + } + +}; + +void unregisterExampleService() +{ + QServiceManager m; + m.removeService("nfctestserviceprovider2"); +} + +void registerExampleService() +{ + unregisterExampleService(); + QServiceManager m; + const QString path = QCoreApplication::applicationDirPath() + "/xmldata/nfctestserviceprovider2.xml"; + qWarning() << "xml path:" << path; + if (!m.addService(path)) + { + qWarning() << "Cannot register service provider" << path; + } + else + { + qDebug() << " Register ok" << endl; + } +} + +Q_DECLARE_METATYPE(QMetaType::Type); + + + +int main(int argc, char *argv[]) +{ + QApplication app(argc, argv); + + w = new nfctestserviceprovider2(); + w->setWindowTitle( "nfc test service provider 2" ); + w->showMaximized(); + + qInstallMsgHandler(MyOutputHandler); + + qRegisterMetaType<QNearFieldTarget*>("QNearFieldTarget*"); + qRegisterMetaType<QNdefMessage>("QNdefMessage"); + + registerExampleService(); + + MyContentHandler handler; + QNearFieldManager manager; + + int handle = manager.registerNdefMessageHandler(&handler, SIGNAL(userHandleMessage(QNdefMessage, QNearFieldTarget*))); + + QFile m_file("E:\\testserviceprovider2.dat"); + m_file.open(QIODevice::ReadWrite | QIODevice::Append); + QTextStream m_textStream(&m_file); + m_textStream << "register handle return " << QString::number(handle); + + int ret = app.exec(); + + manager.unregisterNdefMessageHandler(handle); + delete w; + return ret; +} + +#include "main.moc" diff --git a/tests/nfcsymbianbackend/nfctestserviceprovider2/makesis.bat b/tests/nfcsymbianbackend/nfctestserviceprovider2/makesis.bat new file mode 100644 index 00000000..7e57ddc8 --- /dev/null +++ b/tests/nfcsymbianbackend/nfctestserviceprovider2/makesis.bat @@ -0,0 +1,48 @@ +::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:: +:: 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$ +:: +::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +set EPOC_TOOLS_ROOT=\epoc32\tools +set CERTIFICATE_PATH=\\begrp101\groups6\PCCONN\Tools\RnD_certs + +%EPOC_TOOLS_ROOT%\makesis nfctestserviceprovider2_template.pkg nfctestserviceprovider2_unsigned.sis + +%EPOC_TOOLS_ROOT%\signsis -s nfctestserviceprovider2_unsigned.sis nfctestserviceprovider2.sisx %CERTIFICATE_PATH%\Nokia_RnDCert_02.der %CERTIFICATE_PATH%\Nokia_RnDCert_02.key + +del nfctestserviceprovider2_unsigned.sis diff --git a/tests/nfcsymbianbackend/nfctestserviceprovider2/nfctestserviceprovider2.cpp b/tests/nfcsymbianbackend/nfctestserviceprovider2/nfctestserviceprovider2.cpp new file mode 100644 index 00000000..8b1d34ec --- /dev/null +++ b/tests/nfcsymbianbackend/nfctestserviceprovider2/nfctestserviceprovider2.cpp @@ -0,0 +1,53 @@ +/**************************************************************************** +** +** 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 "nfctestserviceprovider2.h" + +nfctestserviceprovider2::nfctestserviceprovider2(QWidget *parent) + : QMainWindow(parent) +{ + ui.setupUi(this); +} + +nfctestserviceprovider2::~nfctestserviceprovider2() +{ + +} diff --git a/tests/nfcsymbianbackend/nfctestserviceprovider2/nfctestserviceprovider2.h b/tests/nfcsymbianbackend/nfctestserviceprovider2/nfctestserviceprovider2.h new file mode 100644 index 00000000..50c05f94 --- /dev/null +++ b/tests/nfcsymbianbackend/nfctestserviceprovider2/nfctestserviceprovider2.h @@ -0,0 +1,60 @@ +/**************************************************************************** +** +** 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 nfctestserviceprovider2_H +#define nfctestserviceprovider2_H + +#include <QtGui/QMainWindow> +#include "ui_nfctestserviceprovider2.h" + +class nfctestserviceprovider2 : public QMainWindow +{ + Q_OBJECT + +public: + nfctestserviceprovider2(QWidget *parent = 0); + ~nfctestserviceprovider2(); + +private: + Ui::nfctestserviceprovider2 ui; +}; + +#endif // nfctestserviceprovider2_H diff --git a/tests/nfcsymbianbackend/nfctestserviceprovider2/nfctestserviceprovider2.pro b/tests/nfcsymbianbackend/nfctestserviceprovider2/nfctestserviceprovider2.pro new file mode 100644 index 00000000..82161c33 --- /dev/null +++ b/tests/nfcsymbianbackend/nfctestserviceprovider2/nfctestserviceprovider2.pro @@ -0,0 +1,50 @@ +TEMPLATE = app +TARGET = nfctestserviceprovider2 + +QT += core gui serviceframework + +CONFIG += no_icon + +INCLUDEPATH += ../../../src/connectivity/nfc +DEPENDPATH += ../../../src/connectivity/nfc +INCLUDEPATH += ../common +DEPENDPATH += ../common + +INCLUDEPATH += ../../../src/global +DEPENDPATH += ../../../src/global + +QMAKE_LIBDIR += $$QT_MOBILITY_BUILD_TREE/lib + +HEADERS += nfctestserviceprovider2.h +SOURCES += nfctestserviceprovider2_reg.rss \ + main.cpp \ + nfctestserviceprovider2.cpp +FORMS += nfctestserviceprovider2.ui +RESOURCES += + + + +wince*|symbian*: { + addFiles.sources = nfctestserviceprovider2.xml + addFiles.path = xmldata + addFiles2.sources = nfctestserviceprovider2.xml + addFiles2.path = /private/2002AC7F/import/ + DEPLOYMENT += addFiles addFiles2 +} + +symbian { + TARGET.UID3 = 0xe347d950 + TARGET.CAPABILITY = LocalServices + } + + +wince* { + DEFINES+= TESTDATA_DIR=\\\".\\\" +} else:!symbian { + DEFINES += TESTDATA_DIR=\\\"$$PWD/\\\" +} + +xml.path = $$QT_MOBILITY_EXAMPLES/xmldata +xml.files = nfctestserviceprovider2.xml +INSTALLS += xml + diff --git a/tests/nfcsymbianbackend/nfctestserviceprovider2/nfctestserviceprovider2.ui b/tests/nfcsymbianbackend/nfctestserviceprovider2/nfctestserviceprovider2.ui new file mode 100644 index 00000000..516affe0 --- /dev/null +++ b/tests/nfcsymbianbackend/nfctestserviceprovider2/nfctestserviceprovider2.ui @@ -0,0 +1,31 @@ +<?xml version="1.0" encoding="UTF-8"?> +<ui version="4.0"> + <class>nfctestserviceprovider2</class> + <widget class="QMainWindow" name="nfctestserviceprovider2"> + <property name="geometry"> + <rect> + <x>0</x> + <y>0</y> + <width>800</width> + <height>600</height> + </rect> + </property> + <property name="windowTitle"> + <string>nfctestserviceprovider</string> + </property> + <widget class="QWidget" name="centralwidget"/> + <widget class="QMenuBar" name="menubar"> + <property name="geometry"> + <rect> + <x>0</x> + <y>0</y> + <width>800</width> + <height>26</height> + </rect> + </property> + </widget> + <widget class="QStatusBar" name="statusbar"/> + </widget> + <resources/> + <connections/> +</ui> diff --git a/tests/nfcsymbianbackend/nfctestserviceprovider2/nfctestserviceprovider2.xml b/tests/nfcsymbianbackend/nfctestserviceprovider2/nfctestserviceprovider2.xml new file mode 100644 index 00000000..9d22644b --- /dev/null +++ b/tests/nfcsymbianbackend/nfctestserviceprovider2/nfctestserviceprovider2.xml @@ -0,0 +1,15 @@ +<?xml version="1.0" encoding="UTF-8"?> +<SFW version="1.1"> +<service> + <name>nfctestserviceprovider3</name> + <ipcaddress>nfctestserviceprovider2</ipcaddress> + <description>NFC serive provider</description> + <interface> + <name>com.nokia.qt.nfc.NdefMessageHandler</name> + <version>1.0</version> + <description>nfc service provider</description> + <capabilities></capabilities> + <customproperty key="datatype">urn:nfc:ext:S||abc</customproperty> + </interface> +</service> +</SFW> diff --git a/tests/nfcsymbianbackend/qcontenthandler/makesis.bat b/tests/nfcsymbianbackend/qcontenthandler/makesis.bat new file mode 100644 index 00000000..82b29ae2 --- /dev/null +++ b/tests/nfcsymbianbackend/qcontenthandler/makesis.bat @@ -0,0 +1,48 @@ +::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:: +:: 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$ +:: +::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +set EPOC_TOOLS_ROOT=\epoc32\tools +set CERTIFICATE_PATH=\\begrp101\groups6\PCCONN\Tools\RnD_certs + +%EPOC_TOOLS_ROOT%\makesis tst_qcontenthandler_template.pkg tst_qcontenthandler_unsigned.sis + +%EPOC_TOOLS_ROOT%\signsis -s tst_qcontenthandler_unsigned.sis tst_qcontenthandler.sisx %CERTIFICATE_PATH%\Nokia_RnDCert_02.der %CERTIFICATE_PATH%\Nokia_RnDCert_02.key + +del tst_qcontenthandler_unsigned.sis diff --git a/tests/nfcsymbianbackend/qcontenthandler/qcontenthandler.pro b/tests/nfcsymbianbackend/qcontenthandler/qcontenthandler.pro new file mode 100644 index 00000000..58bf7d8f --- /dev/null +++ b/tests/nfcsymbianbackend/qcontenthandler/qcontenthandler.pro @@ -0,0 +1,23 @@ +QT += testlib + +TARGET = tst_qcontenthandler +CONFIG += console +CONFIG -= app_bundle +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 +symbian:TARGET.CAPABILITY = LocalServices ReadUserData WriteUserData NetworkServices UserEnvironment Location SwEvent ReadDeviceData WriteDeviceData diff --git a/tests/nfcsymbianbackend/qcontenthandler/tst_qcontenthandler.cpp b/tests/nfcsymbianbackend/qcontenthandler/tst_qcontenthandler.cpp new file mode 100644 index 00000000..04e76ca8 --- /dev/null +++ b/tests/nfcsymbianbackend/qcontenthandler/tst_qcontenthandler.cpp @@ -0,0 +1,333 @@ +/**************************************************************************** +** +** 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 <QtCore/QString> +#include <QtTest/QtTest> +#include <QtCore/QCoreApplication> + +#include "qnfctestcommon.h" +#include "qnfctestutil.h" + +#include <qnearfieldmanager.h> +#include <qnearfieldtarget.h> +#include <qnearfieldtagtype1.h> +#include <qndefnfctextrecord.h> +#include <qndefnfcurirecord.h> +#include <qndefmessage.h> +#include <qndefrecord.h> + +QTM_USE_NAMESPACE + +Q_DECLARE_METATYPE(QNearFieldTarget*) +Q_DECLARE_METATYPE(QNearFieldTarget::Type) +Q_DECLARE_METATYPE(QNdefFilter) + + +static const QString& logFileName = "E:\\testserviceprovider.dat"; +static const QString& logDirName = "E:\\"; + +static const QString& logFileName_negative = "E:\\testserviceprovider2.dat"; +static const QString& expectedLog = "register handle return -1"; + + +class MessageListener : public QObject +{ + Q_OBJECT + +signals: + void matchedNdefMessage(const QNdefMessage &message, QNearFieldTarget *target); +}; + +class tst_QContentHandler : public QObject +{ + Q_OBJECT + +public: + tst_QContentHandler(); + +private Q_SLOTS: + void initTestCase(); + void cleanupTestCase(); + void testcase_01(); + void testcase_02(); + void testcase_03_negative(); + + +private: + QNearFieldManager m_manager; + QNdefMessage m_message; +}; + +tst_QContentHandler::tst_QContentHandler() +{ + qRegisterMetaType<QNdefMessage>("QNdefMessage"); + qRegisterMetaType<QNearFieldTarget *>("QNearFieldTarget*"); +} + +void tst_QContentHandler::initTestCase() +{ + +} + +void tst_QContentHandler::cleanupTestCase() +{ +} + +/*! + Description: Unit test for NFC content handler + + TestScenario: Write a Ndef Message into tag type 1, read the tag again to ensure corresponding service provider + being invoked + Note: This case need nfctestserviceprovider sis to be installed + +*/ +void tst_QContentHandler::testcase_01() +{ + //first step, delete the log file generated by nfctestserviceprovider if any + QFile m_file(logFileName); + if (m_file.exists()) + { + QDir(logDirName).remove(logFileName); + } + QVERIFY(m_file.exists() == false); + + //second step, write the ndef message into the tag + QNearFieldTagType1* target; + QSignalSpy targetDetectedSpy(&m_manager, SIGNAL(targetDetected(QNearFieldTarget*))); + + m_manager.startTargetDetection(QNearFieldTarget::NfcTagType1); + + QString hint("please touch a writable tag of type 1"); + QNfcTestUtil::ShowAutoMsg(hint, &targetDetectedSpy); + + QTRY_VERIFY(!targetDetectedSpy.isEmpty()); + + target = qobject_cast<QNearFieldTagType1 *>(targetDetectedSpy.at(targetDetectedSpy.count()-1).at(0).value<QNearFieldTarget *>()); + // make sure target can be detected + QVERIFY(target); + + // make sure target uid is not empty + QVERIFY(!target->uid().isEmpty()); + + QNdefRecord record; + record.setTypeNameFormat(QNdefRecord::ExternalRtd); + record.setType("R"); + record.setPayload(QByteArray(2, quint8(0x55))); + m_message.append(record); + + QList<QNdefMessage> messages; + messages.append(m_message); + + QSignalSpy ndefMessageReadSpy(target, SIGNAL(ndefMessageRead(QNdefMessage))); + QSignalSpy ndefMessageWriteSpy(target, SIGNAL(ndefMessagesWritten())); + + target->writeNdefMessages(messages); + QTRY_VERIFY(!ndefMessageWriteSpy.isEmpty()); + + target->readNdefMessages(); + QTRY_VERIFY(!ndefMessageReadSpy.isEmpty()); + + const QNdefMessage& ndefMessage_new(ndefMessageReadSpy.first().at(0).value<QNdefMessage>()); + QVERIFY(messages.at(0) == ndefMessage_new); + + QSignalSpy targetLostSpy(&m_manager, SIGNAL(targetLost(QNearFieldTarget*))); + QNfcTestUtil::ShowAutoMsg("please remove the tag", &targetLostSpy); + QTRY_VERIFY(!targetLostSpy.isEmpty()); + + delete target; + + //third step: stop target detection(so that the ndef message can be routed to service provider) + // and touch the tag again to invoke service provider, if the service provider being + // invoked successfully, the log file contains the message content will be generated + // compare the message in the log file with the message writen to the tag + m_manager.stopTargetDetection(); + + hint = "please touch the tag just be writen successfully"; + QNfcTestUtil::ShowMessage(hint); + + QVERIFY(m_file.exists()); + m_file.open(QIODevice::ReadOnly); + QDataStream fileInData (&m_file); + QByteArray msgByteArray; + fileInData >> msgByteArray; + QNdefMessage msgFromLog = QNdefMessage::fromByteArray(msgByteArray); + + QVERIFY(m_message == msgFromLog); + + hint = "please remove tag"; + QNfcTestUtil::ShowMessage(hint); +} + +/*! + Description: Unit test for NFC content handler + + TestScenario: Read the tag again to ensure if an application registered for the ndef message, + the ndef message can't be routed to service provider + Note: This case need nfctestserviceprovider sis to be installed + +*/ +void tst_QContentHandler::testcase_02() +{ + //first step, delete the log file generated by nfctestserviceprovider if any + QFile m_file(logFileName); + if (m_file.exists()) + { + QDir(logDirName).remove(logFileName); + } + QVERIFY(m_file.exists() == false); + + //second step, register for the ndef message, so that the test case itself + // is the application registered for the ndef message + QNdefFilter filter; + filter.appendRecord(QNdefRecord::ExternalRtd, "R"); + MessageListener listener; + QSignalSpy messageSpy(&listener, SIGNAL(matchedNdefMessage(QNdefMessage,QNearFieldTarget*))); + int id = m_manager.registerNdefMessageHandler(filter, &listener, + SIGNAL(matchedNdefMessage(QNdefMessage,QNearFieldTarget*))); + QVERIFY(id != -1); + + //third step, touch the tag with the ndef message, to verify the log file can't + // be generated because the service provider can't be invoked + QString hint("please touch again the tag just be writen successfully"); + QNfcTestUtil::ShowAutoMsg(hint, &messageSpy, 1); + + QVERIFY(m_file.exists() == false); + + m_manager.unregisterNdefMessageHandler(id); + + hint = "please remove tag"; + QNfcTestUtil::ShowMessage(hint); + +} + +/*! + Description: Unit test for NFC content handler + + TestScenario: Write a Ndef Message into tag type 1, read the tag again to ensure corresponding service provider + being invoked but the corresponding interface can't be invoked because user write xml file wrongly + Note: This case need nfctestserviceprovider2 sis to be installed + +*/ +void tst_QContentHandler::testcase_03_negative() +{ + //first step, delete the log file generated by nfctestserviceprovider2 if any + QFile m_file(logFileName_negative); + if (m_file.exists()) + { + QDir(logDirName).remove(logFileName_negative); + } + QVERIFY(!m_file.exists()); + + //second step, write the ndef message into the tag + QNearFieldTagType1* target; + QSignalSpy targetDetectedSpy(&m_manager, SIGNAL(targetDetected(QNearFieldTarget*))); + + m_manager.startTargetDetection(QNearFieldTarget::NfcTagType1); + + QString hint("please touch a writable tag of type 1"); + QNfcTestUtil::ShowAutoMsg(hint, &targetDetectedSpy); + + QTRY_VERIFY(!targetDetectedSpy.isEmpty()); + + target = qobject_cast<QNearFieldTagType1 *>(targetDetectedSpy.at(targetDetectedSpy.count()-1).at(0).value<QNearFieldTarget *>()); + // make sure target can be detected + QVERIFY(target); + + // make sure target uid is not empty + QVERIFY(!target->uid().isEmpty()); + + QNdefRecord record; + record.setTypeNameFormat(QNdefRecord::ExternalRtd); + record.setType("S"); + record.setPayload(QByteArray(2, quint8(0x55))); + m_message.clear(); + m_message.append(record); + + QList<QNdefMessage> messages; + messages.append(m_message); + + QSignalSpy ndefMessageReadSpy(target, SIGNAL(ndefMessageRead(QNdefMessage))); + QSignalSpy ndefMessageWriteSpy(target, SIGNAL(ndefMessagesWritten())); + + target->writeNdefMessages(messages); + QTRY_VERIFY(!ndefMessageWriteSpy.isEmpty()); + + target->readNdefMessages(); + QTRY_VERIFY(!ndefMessageReadSpy.isEmpty()); + + const QNdefMessage& ndefMessage_new(ndefMessageReadSpy.first().at(0).value<QNdefMessage>()); + QVERIFY(messages.at(0) == ndefMessage_new); + + QSignalSpy targetLostSpy(&m_manager, SIGNAL(targetLost(QNearFieldTarget*))); + QNfcTestUtil::ShowAutoMsg("please remove the tag", &targetLostSpy); + QTRY_VERIFY(!targetLostSpy.isEmpty()); + + delete target; + m_manager.stopTargetDetection(); + + //third step: stop target detection(so that the ndef message can be routed to service provider) + // and touch the tag again to invoke service provider, if the service provider being + // invoked successfully, the log file contains the register fail info will be generated + // compare the message in the log file with the expected info + + hint = "please touch the tag just be writen successfully"; + QNfcTestUtil::ShowMessage(hint); + + QVERIFY(m_file.exists()); + + m_file.open(QIODevice::ReadOnly | QIODevice::Text); + QTextStream fileInData(&m_file); + QString logMsg = fileInData.readAll() ; + + qDebug() << "log message: " << logMsg; + + QVERIFY(expectedLog == logMsg); + + hint = "please remove tag"; + QNfcTestUtil::ShowMessage(hint); +} + + + + +QTEST_MAIN(tst_QContentHandler); + +#include "tst_qcontenthandler.moc" diff --git a/tests/nfcsymbianbackend/qllcpserver/qllcpserver.pro b/tests/nfcsymbianbackend/qllcpserver/qllcpserver.pro new file mode 100644 index 00000000..47e9e96d --- /dev/null +++ b/tests/nfcsymbianbackend/qllcpserver/qllcpserver.pro @@ -0,0 +1,25 @@ +QT += testlib + +TARGET = tst_qllcpserver +CONFIG += console +CONFIG -= app_bundle +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_qllcpserver.cpp\ + ../common/qautomsgbox.cpp +symbian:TARGET.CAPABILITY = ALL -TCB + + diff --git a/tests/nfcsymbianbackend/qllcpserver/tst_qllcpserver.cpp b/tests/nfcsymbianbackend/qllcpserver/tst_qllcpserver.cpp new file mode 100644 index 00000000..4018a934 --- /dev/null +++ b/tests/nfcsymbianbackend/qllcpserver/tst_qllcpserver.cpp @@ -0,0 +1,464 @@ +/**************************************************************************** +** +** 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 <QtCore/QString> +#include <QtTest/QtTest> +#include <QtCore/QCoreApplication> +#include <qllcpserver.h> +#include <qllcpsocket.h> + +#include "qnfctestcommon.h" +#include "qnfctestutil.h" + +QString TestUri("urn:nfc:xsn:nokia:symbiantest"); + +static qint64 countBytesWritten(QSignalSpy& bytesWrittenSpy) + { + qint64 ret = 0; + for(int i = 0; i < bytesWrittenSpy.count(); i++) + { + ret+=bytesWrittenSpy[i].at(0).value<qint64>(); + } + return ret; + } + +Q_DECLARE_METATYPE(QLlcpSocket::SocketError) +class tst_QLlcpServer : public QObject +{ + Q_OBJECT + +public: + tst_QLlcpServer(); + +private Q_SLOTS: + void initTestCase(); + void cleanupTestCase(); + + + // basic acceptance test + void newConnection(); + void newConnection_data(); + void newConnection_wait(); + void newConnection_wait_data(); + void api_coverage(); + + //advance test case + void multiConnection(); + + // nagetive testcases + void negTestCase1(); +}; + +tst_QLlcpServer::tst_QLlcpServer() +{ +} + +void tst_QLlcpServer::initTestCase() +{ + qRegisterMetaType<QLlcpSocket::SocketError>("QLlcpSocket::SocketError"); +} + +void tst_QLlcpServer::cleanupTestCase() +{ +} +void tst_QLlcpServer::newConnection_data() +{ + QString hint = "handshake 1"; + QTest::addColumn<QString>("uri"); + QTest::addColumn<QString>("hint"); + QTest::newRow("0") << TestUri << hint; +} + +/*! + Description: Unit test for NFC LLCP server async functions + + TestScenario: 1. Server will listen to a pre-defined URI + 2. Wait client to connect. + 3. Read message from client. + 4. Echo the same message back to client + 5. Wait client disconnect event. + + TestExpectedResults: + 1. The listen successfully set up. + 2. The message has be received from client. + 3. The echoed message has been sent to client. + 4. Connection disconnected and NO error signals emitted. +*/ +void tst_QLlcpServer::newConnection() +{ + QFETCH(QString, uri); + QFETCH(QString, hint); + + QLlcpServer server; + qDebug() << "Create QLlcpServer completed"; + qDebug() << "Start listening..."; + QSignalSpy connectionSpy(&server, SIGNAL(newConnection())); + + bool ret = server.listen(uri); + QVERIFY(ret); + qDebug() << "Listen() return ok"; + + QNfcTestUtil::ShowAutoMsg(hint, &connectionSpy, 1); + + QTRY_VERIFY(!connectionSpy.isEmpty()); + qDebug() << "try to call nextPendingConnection()"; + QLlcpSocket *socket = server.nextPendingConnection(); + QVERIFY(socket != NULL); + QSignalSpy readyReadSpy(socket, SIGNAL(readyRead())); + QSignalSpy errorSpy(socket, SIGNAL(error(QLlcpSocket::SocketError))); + + //Get data from client + QTRY_VERIFY(!readyReadSpy.isEmpty()); + + qDebug() << "Bytes available = " << socket->bytesAvailable(); + quint16 blockSize = 0; + QDataStream in(socket); + in.setVersion(QDataStream::Qt_4_6); + while (socket->bytesAvailable() < (int)sizeof(quint16)){ + QSignalSpy readyRead(socket, SIGNAL(readyRead())); + QTRY_VERIFY(!readyRead.isEmpty()); + } + in >> blockSize; + qDebug()<<"Read blockSize from client: " << blockSize; + while (socket ->bytesAvailable() < blockSize){ + QSignalSpy readyRead(socket, SIGNAL(readyRead())); + QTRY_VERIFY(!readyRead.isEmpty()); + } + QString echo; + in >> echo; + qDebug() << "Read data from client:" << echo; + //Send data to client + QSignalSpy bytesWrittenSpy(socket, SIGNAL(bytesWritten(qint64))); + QByteArray block; + QDataStream out(&block, QIODevice::WriteOnly); + out.setVersion(QDataStream::Qt_4_6); + out << (quint16)0; + out << echo; + qDebug()<<"Write echoed data back to client"; + out.device()->seek(0); + out << (quint16)(block.size() - sizeof(quint16)); + qint64 val = socket->write(block); + qDebug("Write() return value = %d", val); + QVERIFY(val == 0); + + QTRY_VERIFY(!bytesWrittenSpy.isEmpty()); + qint64 written = countBytesWritten(bytesWrittenSpy); + qDebug()<<"Server::bytesWritten signal return value = " << written; + while (written < block.size()) + { + QSignalSpy bytesWrittenSpy(socket, SIGNAL(bytesWritten(qint64))); + QTRY_VERIFY(!bytesWrittenSpy.isEmpty()); + written += countBytesWritten(bytesWrittenSpy); + } + QVERIFY(written == block.size()); + //Now data has been sent,check the if existing error + QVERIFY(errorSpy.isEmpty()); + QTest::qWait(1500);//give some time to client to finish + server.close(); +} + +/*! + Description: Unit test for NFC LLCP server sync(waitXXX) functions + + TestScenario: 1. Server will listen to a pre-defined URI + 2. Wait client to connect. + 3. Read message from client. + 4. Echo the same message back to client + 5. Wait client disconnect event. + + TestExpectedResults: + 1. The listen successfully set up. + 2. The message has be received from client. + 3. The echoed message has been sent to client. + 4. Connection disconnected and NO error signals emitted. +*/ +void tst_QLlcpServer::newConnection_wait() + { + QFETCH(QString, uri); + QFETCH(QString, hint); + + QLlcpServer server; + qDebug() << "Create QLlcpServer completed"; + qDebug() << "Start listening..."; + bool ret = server.listen(uri); + QVERIFY(ret); + qDebug() << "Listen() return ok"; + QSignalSpy connectionSpy(&server, SIGNAL(newConnection())); + + QNfcTestUtil::ShowAutoMsg(hint, &connectionSpy, 1); + + QTRY_VERIFY(!connectionSpy.isEmpty()); + qDebug() << "try to call nextPendingConnection()"; + QLlcpSocket *socket = server.nextPendingConnection(); + QVERIFY(socket != NULL); + + QSignalSpy errorSpy(socket, SIGNAL(error(QLlcpSocket::SocketError))); + //Get data from client + const int Timeout = 10 * 1000; + + quint16 blockSize = 0; + QDataStream in(socket); + in.setVersion(QDataStream::Qt_4_6); + while (socket->bytesAvailable() < (int)sizeof(quint16)) { + bool ret = socket->waitForReadyRead(Timeout); + QVERIFY(ret); + } + + in >> blockSize; + qDebug()<<"Read blockSize from client: " << blockSize; + while (socket ->bytesAvailable() < blockSize){ + bool ret = socket->waitForReadyRead(Timeout); + QVERIFY(ret); + } + QString echo; + in >> echo; + qDebug() << "Read data from client:" << echo; + //Send data to client + QSignalSpy bytesWrittenSpy(socket, SIGNAL(bytesWritten(qint64))); + + QByteArray block; + QDataStream out(&block, QIODevice::WriteOnly); + out.setVersion(QDataStream::Qt_4_6); + out << (quint16)0; + out << echo; + qDebug()<<"Write echoed data back to client"; + out.device()->seek(0); + out << (quint16)(block.size() - sizeof(quint16)); + + qint64 val = socket->write(block); + qDebug("Write() return value = %d", val); + QVERIFY(val == 0); + + ret = socket->waitForBytesWritten(Timeout); + QVERIFY(ret); + + QTRY_VERIFY(!bytesWrittenSpy.isEmpty()); + qint64 written = countBytesWritten(bytesWrittenSpy); + + while (written < block.size()) + { + QSignalSpy bytesWrittenSpy(socket, SIGNAL(bytesWritten(qint64))); + bool ret = socket->waitForBytesWritten(Timeout); + QVERIFY(ret); + QTRY_VERIFY(!bytesWrittenSpy.isEmpty()); + written += countBytesWritten(bytesWrittenSpy); + } + QVERIFY(written == block.size()); + //Now data has been sent,check the if existing error + if (!errorSpy.isEmpty()) + { + QLlcpSocket::SocketError error = errorSpy.first().at(0).value<QLlcpSocket::SocketError>(); + qDebug("QLlcpSocket::SocketError =%d", error); + } + QVERIFY(errorSpy.isEmpty()); + QTest::qWait(1500);//give some time to client to finish + server.close(); + } + +void tst_QLlcpServer::newConnection_wait_data() + { + QTest::addColumn<QString>("uri"); + QTest::addColumn<QString>("hint"); + QTest::newRow("0") << TestUri + << "handshake 2"; + } + + + +/*! + Description: LLCP Server API test & Socket readDatagram API test + TestScenario: + 1) Read two datagrams from llcp client device + 2) Covered API: readDatagram(), serviceUri(), servicePort(), isListening(), serverError() + */ +void tst_QLlcpServer::api_coverage() +{ + QString uri = TestUri; + QLlcpServer server; + QSignalSpy connectionSpy(&server, SIGNAL(newConnection())); + bool ret = server.listen(uri); + QVERIFY(ret); + + QString message("api_coverage test"); + + QNfcTestUtil::ShowAutoMsg(message, &connectionSpy, 1); + QTRY_VERIFY(!connectionSpy.isEmpty()); + + bool hasPending = server.hasPendingConnections(); + QVERIFY(hasPending); + QLlcpSocket *socket = server.nextPendingConnection(); + QVERIFY(socket != NULL); + QSignalSpy readyReadSpy(socket, SIGNAL(readyRead())); + //Get data from client + QTRY_VERIFY(!readyReadSpy.isEmpty()); + + qint64 size = socket->bytesAvailable(); + QTRY_VERIFY(size > 0); + QByteArray datagram; + datagram.resize(size); + qint64 readSize = socket->readDatagram(datagram.data(), datagram.size()); + QVERIFY(readSize == size); + + qDebug()<<"Server Uri = " << server.serviceUri(); + QCOMPARE(uri,server.serviceUri()); + + quint8 unsupportedPort = 0; + QCOMPARE(unsupportedPort,server.serverPort()); + + QVERIFY(server.isListening() == true); + QVERIFY(server.serverError() == QLlcpSocket::UnknownSocketError); + server.close(); +} + + +/*! + Description: listen negative test - listen twice +*/ +void tst_QLlcpServer::negTestCase1() +{ + + QString uri = TestUri; + QLlcpServer server; + QSignalSpy connectionSpy(&server, SIGNAL(newConnection())); + bool ret = server.listen(uri); + QVERIFY(ret); + + QString message("negTestCase1 test"); + + QNfcTestUtil::ShowAutoMsg(message, &connectionSpy, 1); + + ret = server.listen(uri); + QVERIFY(ret == false); + QTest::qWait(1 * 1000);//give some time to wait new connection + server.close(); +} +/*! + Description: Add a llcp2 server which will always + run( actually run twice ), then a client in a device connect, + after the case finish, another device connect the + server again. + + CounterPart: tst_qllcpsockettype2 echo:"0" + run this case twice to test multiConnection() +*/ +void tst_QLlcpServer::multiConnection() + { + QString uri = TestUri; + QString hint ="multiConnection test"; + + QLlcpServer server; + qDebug() << "Create QLlcpServer completed"; + qDebug() << "Start listening..."; + QSignalSpy connectionSpy(&server, SIGNAL(newConnection())); + + bool ret = server.listen(uri); + QVERIFY(ret); + qDebug() << "Listen() return ok"; + const int KLoopCount = 2; + int loopCount = 0; + while(loopCount < KLoopCount) + { + qDebug() << "#########Loop count = " << loopCount <<" #########"; + QNfcTestUtil::ShowAutoMsg(hint, &connectionSpy, 1); + + QTRY_VERIFY(!connectionSpy.isEmpty()); + qDebug() << "try to call nextPendingConnection()"; + QLlcpSocket *socket = server.nextPendingConnection(); + QVERIFY(socket != NULL); + QSignalSpy readyReadSpy(socket, SIGNAL(readyRead())); + QSignalSpy errorSpy(socket, SIGNAL(error(QLlcpSocket::SocketError))); + + //Get data from client + QTRY_VERIFY(!readyReadSpy.isEmpty()); + + qDebug() << "Bytes available = " << socket->bytesAvailable(); + quint16 blockSize = 0; + QDataStream in(socket); + in.setVersion(QDataStream::Qt_4_6); + while (socket->bytesAvailable() < (int)sizeof(quint16)){ + QSignalSpy readyRead(socket, SIGNAL(readyRead())); + QTRY_VERIFY(!readyRead.isEmpty()); + } + in >> blockSize; + qDebug()<<"Read blockSize from client: " << blockSize; + while (socket ->bytesAvailable() < blockSize){ + QSignalSpy readyRead(socket, SIGNAL(readyRead())); + QTRY_VERIFY(!readyRead.isEmpty()); + } + QString echo; + in >> echo; + qDebug() << "Read data from client:" << echo; + //Send data to client + QSignalSpy bytesWrittenSpy(socket, SIGNAL(bytesWritten(qint64))); + QByteArray block; + QDataStream out(&block, QIODevice::WriteOnly); + out.setVersion(QDataStream::Qt_4_6); + out << (quint16)0; + out << echo; + qDebug()<<"Write echoed data back to client"; + out.device()->seek(0); + out << (quint16)(block.size() - sizeof(quint16)); + qint64 val = socket->write(block); + qDebug("Write() return value = %d", val); + QVERIFY(val == 0); + + QTRY_VERIFY(!bytesWrittenSpy.isEmpty()); + qint64 written = countBytesWritten(bytesWrittenSpy); + qDebug()<<"Server::bytesWritten signal return value = " << written; + while (written < block.size()) + { + QSignalSpy bytesWrittenSpy(socket, SIGNAL(bytesWritten(qint64))); + QTRY_VERIFY(!bytesWrittenSpy.isEmpty()); + written += countBytesWritten(bytesWrittenSpy); + } + QVERIFY(written == block.size()); + //Now data has been sent,check the if existing error + QVERIFY(errorSpy.isEmpty()); + + connectionSpy.removeFirst(); + loopCount++; + } + QTest::qWait(1500);//give some time to client to finish + server.close(); + } +QTEST_MAIN(tst_QLlcpServer); + +#include "tst_qllcpserver.moc" diff --git a/tests/nfcsymbianbackend/qllcpsocketlocal/qllcpsocketlocal.pro b/tests/nfcsymbianbackend/qllcpsocketlocal/qllcpsocketlocal.pro new file mode 100644 index 00000000..960388d9 --- /dev/null +++ b/tests/nfcsymbianbackend/qllcpsocketlocal/qllcpsocketlocal.pro @@ -0,0 +1,24 @@ + +QT += testlib + +TARGET = tst_qllcpsocketlocal +CONFIG += console +CONFIG -= app_bundle +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_qllcpsocketlocal.cpp \ + ../common/qautomsgbox.cpp +symbian:TARGET.CAPABILITY = ALL -TCB diff --git a/tests/nfcsymbianbackend/qllcpsocketlocal/tst_qllcpsocketlocal.cpp b/tests/nfcsymbianbackend/qllcpsocketlocal/tst_qllcpsocketlocal.cpp new file mode 100644 index 00000000..657f22e8 --- /dev/null +++ b/tests/nfcsymbianbackend/qllcpsocketlocal/tst_qllcpsocketlocal.cpp @@ -0,0 +1,954 @@ +/**************************************************************************** +** +** 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 <QtCore/QString> +#include <QtTest/QtTest> +#include <QtCore/QCoreApplication> + +#include <qllcpsocket.h> +#include <qnearfieldmanager.h> +#include <qnearfieldtarget.h> +#include "qnfctestcommon.h" +#include "qnfctestutil.h" + +Q_DECLARE_METATYPE(QNearFieldTarget*) +Q_DECLARE_METATYPE(QLlcpSocket::SocketError ) +Q_DECLARE_METATYPE(QLlcpSocket::SocketState ) + +class tst_qllcpsocketlocal : public QObject +{ + Q_OBJECT + +public: + tst_qllcpsocketlocal(); +private Q_SLOTS: + + + void multipleClient(); + void echoClient(); + void echoClient_data(); + void testCase2(); //work with tst_qllcpsocketremote testCase2 + void testCase3(); + void coverageTest1(); + //advanced test + void deleteSocketWhenInUse(); + void waitBytesWrittenInSlot(); + void multiSocketToOneServer(); + //negtive test + void negTestCase1(); + void negTestCase2(); + //void negTestCase3(); + //void negTestCase4(); + + void initTestCase(); + void cleanupTest(); + +private: + void writeMessage(QLlcpSocket& localSocket,QString& payLoad); +private: + QNearFieldTarget *m_target; // not own + quint8 m_port; +}; + +tst_qllcpsocketlocal::tst_qllcpsocketlocal() +{ + qRegisterMetaType<QNearFieldTarget *>("QNearFieldTarget*"); + qRegisterMetaType<QLlcpSocket::SocketError>("QLlcpSocket::SocketError"); + qRegisterMetaType<QLlcpSocket::SocketState>("QLlcpSocket::SocketState"); +} + +/*! + Description: Init test case for NFC LLCP connection-less mode socket - local peer + + TestScenario: + Touch a NFC device with LLCP connection-less service actived + + TestExpectedResults: + Signal of target detected has been found. +*/ +void tst_qllcpsocketlocal::initTestCase() +{ + qDebug()<<"tst_qllcpsocketlocal::initTestCase() Begin"; + QString message("Please touch a NFC device with llcp client enabled"); + QNearFieldManager nfcManager; + QSignalSpy targetDetectedSpy(&nfcManager, SIGNAL(targetDetected(QNearFieldTarget*))); + nfcManager.startTargetDetection(QNearFieldTarget::NfcForumDevice); + + QNfcTestUtil::ShowAutoMsg(message, &targetDetectedSpy, 1); + QTRY_VERIFY(!targetDetectedSpy.isEmpty()); + + m_target = targetDetectedSpy.at(targetDetectedSpy.count() - 1).at(0).value<QNearFieldTarget*>(); + QVERIFY(m_target != NULL); + QVERIFY(m_target->accessMethods() & QNearFieldTarget::LlcpAccess); + QVERIFY(m_target->uid() == QByteArray()); + QVERIFY(m_target->type() == QNearFieldTarget::NfcForumDevice); + + m_port = 35; + qDebug()<<"tst_qllcpsocketlocal::initTestCase() End"; +} + +/*! + Description: Send the message and Receive the acknowledged identical message + + TestScenario: + 1. Local peer temps to read datagram without bind + 2. Local peer binds to the remote peer + 3. Local peer sends the "testcase1 string" message to the remote peer + 4. Local peer receives the above message sending from the remote peer + + TestExpectedResults: + 1. Local peer fails to read datagram without bind + 2. Local peer binds to local port successfully. + 3. The message has be sent to remote peer. + 4. The message has been received from remote peer. +*/ +void tst_qllcpsocketlocal::echoClient() +{ + QFETCH(QString, echoPayload); + QLlcpSocket localSocket; + + // STEP 1. readDatagram must be called before bind + QByteArray tmpForReadArray; + tmpForReadArray.resize(127); + qint64 ret = localSocket.readDatagram(tmpForReadArray.data(), tmpForReadArray.size()); + QVERIFY(ret == -1); + + QCOMPARE(localSocket.state(), QLlcpSocket::UnconnectedState); + QSignalSpy stateChangedSpy(&localSocket, SIGNAL(stateChanged(QLlcpSocket::SocketState))); + + // STEP 2: bind the local port for current socket + QSignalSpy readyReadSpy(&localSocket, SIGNAL(readyRead())); + bool retBool = localSocket.bind(m_port); + QVERIFY(retBool); + QVERIFY(!stateChangedSpy.isEmpty()); + QCOMPARE(localSocket.state(), QLlcpSocket::BoundState); + + // Wait remote part bind + QString messageBox("Wait remote bind"); + QNfcTestUtil::ShowAutoMsg(messageBox); + + // STEP 3: Local peer sends the message to the remote peer + writeMessage(localSocket,echoPayload); + QSignalSpy errorSpy(&localSocket, SIGNAL(error(QLlcpSocket::SocketState))); + + // STEP 4: Start read payload from server + QString messageBox2("Wait remote send buffer"); + QNfcTestUtil::ShowAutoMsg(messageBox2, &readyReadSpy); + + QByteArray inPayload; + while(localSocket.hasPendingDatagrams()) { + QByteArray tempBuffer; + tempBuffer.resize(localSocket.pendingDatagramSize()); + quint8 remotePort = 0; + QSignalSpy readyRead(&localSocket, SIGNAL(readyRead())); + qint64 readSize = localSocket.readDatagram(tempBuffer.data() + , tempBuffer.size() + , &m_target, &remotePort); + QVERIFY(readSize != -1); + QVERIFY(remotePort > 0); + inPayload.append(tempBuffer); + qDebug() << "Client-- read inPayload size=" << inPayload.size(); + qDebug() << "Client-- read remotePort=" << remotePort; + if (inPayload.size() >= (int)sizeof(quint16)) { + break; + } + else + { + qDebug() << "Client-- not enough header"; + QTRY_VERIFY(!readyRead.isEmpty()); + } + } + + QDataStream in(inPayload); + in.setVersion(QDataStream::Qt_4_6); + quint16 headerSize = 0; // size of real echo payload + in >> headerSize; + qDebug() << "Client-- read headerSize=" << headerSize; + while (inPayload.size() < headerSize + (int)sizeof(quint16)){ + QSignalSpy readyRead(&localSocket, SIGNAL(readyRead())); + QTRY_VERIFY(!readyRead.isEmpty()); + if(localSocket.hasPendingDatagrams()) { + QByteArray tempBuffer; + tempBuffer.resize(localSocket.pendingDatagramSize()); + quint8 remotePort = 0; + qint64 readSize = localSocket.readDatagram(tempBuffer.data() + , tempBuffer.size() + , &m_target, &remotePort); + QVERIFY(readSize != -1); + QVERIFY(remotePort > 0); + inPayload.append(tempBuffer); + qDebug() << "Client-- read long blocksize=" << inPayload.size(); + } + } + + QDataStream in2(inPayload); + in2.setVersion(QDataStream::Qt_4_6); + in2 >> headerSize; + QString inEchoPayload; + in2 >> inEchoPayload; + qDebug() << "Client-- in echo string len:" << inEchoPayload.length(); + qDebug("Client-- in echo string = %s", qPrintable(inEchoPayload)); + //test the echoed string is same as the original string + QVERIFY(echoPayload == inEchoPayload); + // make sure the no error signal emitted + QVERIFY(errorSpy.isEmpty()); +} + +void tst_qllcpsocketlocal::echoClient_data() +{ + QTest::addColumn<QString>("echoPayload"); + QTest::newRow("0") << "test payload"; + QString longStr4k; + for (int i = 0; i < 4000; i++) + longStr4k.append((char)(i%26 + 'a')); + QTest::newRow("1") << longStr4k; +} + +void tst_qllcpsocketlocal::writeMessage( + QLlcpSocket& localSocket, + QString& payLoad) +{ + // STEP 2: Local peer sends the message to the remote peer + QSignalSpy errorSpy(&localSocket, SIGNAL(error(QLlcpSocket::SocketState))); + QSignalSpy bytesWrittenSpy(&localSocket, SIGNAL(bytesWritten(qint64))); + + //Prepare data to send + QByteArray outPayload; + QDataStream out(&outPayload, QIODevice::WriteOnly); + out.setVersion(QDataStream::Qt_4_6); + out << (quint16)0; + out << payLoad; + + qDebug("Client-- write quint16 length = %d", sizeof(quint16)); + qDebug("Client-- write echo string = %s", qPrintable(payLoad)); + qDebug("Client-- write echo string length= %d", payLoad.length()); + qDebug("Client-- write payload length = %d", outPayload.length()); + out.device()->seek(0); + out << (quint16)(outPayload.size() - sizeof(quint16)); + + qint64 ret = localSocket.writeDatagram(outPayload, m_target, m_port); + QVERIFY(ret == 0); + + QTRY_VERIFY(!bytesWrittenSpy.isEmpty()); + + qint64 written = 0; + qint32 lastSignalCount = 0; + while(true) + { + for(int i = lastSignalCount; i < bytesWrittenSpy.count(); i++) { + written += bytesWrittenSpy.at(i).at(0).value<qint64>(); + } + lastSignalCount = bytesWrittenSpy.count(); + qDebug() << "current signal count = " << lastSignalCount; + qDebug() << "written payload size = " << written; + if (written < outPayload.size()) { + QTRY_VERIFY(bytesWrittenSpy.count() > lastSignalCount); + } + else { + break; + } + } + qDebug() << "Overall bytesWritten = " << written; + qDebug() << "Overall block size = " << outPayload.size(); + QVERIFY(written == outPayload.size()); +} + + +/*! + Description: Send the message and Receive the acknowledged identical message + + TestScenario: + 1. Local peer sends the very long message to the remote peer + 2. Local peer sends the second very long message to the remote peer + + TestExpectedResults: + 1. The message has be sent to remote peer. + 2. The second message has been received from remote peer. +*/ +void tst_qllcpsocketlocal::multipleClient() +{ + QLlcpSocket localSocket; + QString longStr1k; + for (int i = 0; i < 1000; i++) + longStr1k.append((char)(i%26 + 'a')); + + QString longStr2k; + for (int i = 0; i < 2000; i++) + longStr2k.append((char)(i%26 + 'b')); + + QCOMPARE(localSocket.state(), QLlcpSocket::UnconnectedState); + QSignalSpy stateChangedSpy(&localSocket, SIGNAL(stateChanged(QLlcpSocket::SocketState))); + + // STEP 1: bind the local port for current socket + bool retBool = localSocket.bind(m_port); + QVERIFY(retBool); + QVERIFY(!stateChangedSpy.isEmpty()); + QCOMPARE(localSocket.state(), QLlcpSocket::BoundState); + + // Wait remote part bind + QString messageBox("Wait remote bind"); + QNfcTestUtil::ShowAutoMsg(messageBox); + + writeMessage(localSocket,longStr1k); + writeMessage(localSocket,longStr2k); +} + + +void tst_qllcpsocketlocal::testCase2() +{ + QLlcpSocket localSocket; + quint8 localPort = 38; + + // STEP 1: + //QSignalSpy bytesWrittenSpy(&localSocket, SIGNAL(bytesWritten(qint64))); + QString message("testcase2 string str1"); + QByteArray tmpArray(message.toAscii()); + const char* data = tmpArray.data(); + qint64 strSize = message.size(); + qint64 val = localSocket.writeDatagram(data, strSize, m_target, localPort); + QVERIFY(val != -1); + + // STEP 2: + QString message2("testcase2 string str2"); + QByteArray tmpArray2(message2.toAscii()); + const char* data2 = tmpArray2.data(); + qint64 strSize2 = message2.size(); + qint64 val2 = localSocket.writeDatagram(data2, strSize2, m_target, localPort); + QVERIFY(val2 != -1); + + // STEP 3: + const int Timeout = 2 * 1000; + bool ret = localSocket.waitForBytesWritten(Timeout); + QVERIFY(ret); + + // STEP 4: + ret = localSocket.waitForBytesWritten(Timeout); + QVERIFY(ret); + + QString messageBox("handshake 3"); + QNfcTestUtil::ShowAutoMsg(messageBox); + + // STEP 5: Try to cover waitForBytesWritten() in bound mode + const int Timeout1 = 1 * 1000; + localSocket.waitForBytesWritten(Timeout1); + QVERIFY(ret); +} + +/*! + Description: coverage testcase - targeted for sender doCancel +*/ +void tst_qllcpsocketlocal::testCase3() +{ + QLlcpSocket localSocket; + // STEP 1: + QString message("string1"); + QByteArray tmpArray(message.toAscii()); + const char* data = tmpArray.data(); + qint64 strSize = message.size(); + localSocket.writeDatagram(data,strSize,m_target, m_port); +} + +/*! + Description: coverage testcase - invalid usage of connection-oriented API +*/ +void tst_qllcpsocketlocal::coverageTest1() +{ + QLlcpSocket localSocket; + + QSignalSpy errorSpy(&localSocket, SIGNAL(error(QLlcpSocket::SocketError))); + localSocket.connectToService(m_target,"uri"); + QTRY_VERIFY(errorSpy.count() == 1); + QVERIFY(localSocket.error() == QLlcpSocket::UnknownSocketError); + + localSocket.disconnectFromService(); + QTRY_VERIFY(errorSpy.count() == 2); + + QVERIFY(localSocket.waitForConnected() == false); + QVERIFY(localSocket.waitForDisconnected() == false); + + QString message = "Oops, must follow a port parameter"; + QByteArray tmpArray(message.toAscii()); + const char* data = tmpArray.data(); + qint64 strSize = message.size(); + qint64 ret = localSocket.writeDatagram(data,strSize); + QVERIFY(ret == -1); +} + +class BytesWrittenSlot : public QObject +{ + Q_OBJECT +public: + BytesWrittenSlot(QLlcpSocket* s): m_socket(s) + { + connect(m_socket,SIGNAL(bytesWritten(qint64)),this,SLOT(gotBytesWritten(qint64))); + } +private slots: + void gotBytesWritten(qint64 w) + { + qDebug()<<"In BytesWrittenSlot: Delete the socket when still alive..."; + delete m_socket; + } +private: + QLlcpSocket* m_socket; +}; +/*! + Description: Add a case to test delete the socket in the slot when the transmission is still alive. + CounterPart test: tst_qllcpsocketremote::dumpServer() +*/ +void tst_qllcpsocketlocal::deleteSocketWhenInUse() + { + QString message("deleteSocketWhenInUse test"); + QNfcTestUtil::ShowAutoMsg(message); + + QLlcpSocket* socket = new QLlcpSocket; + + bool retBool = socket->bind(m_port); + QVERIFY(retBool); + + // STEP 3: Local peer sends the message to the remote peer + QSignalSpy errorSpy(socket, SIGNAL(error(QLlcpSocket::SocketState))); + + BytesWrittenSlot slot(socket); + + QString echo; + for (int i = 0; i < 2000; i++) + echo.append((char)(i%26 + 'a')); + //Prepare data to send + QByteArray outPayload; + QDataStream out(&outPayload, QIODevice::WriteOnly); + out.setVersion(QDataStream::Qt_4_6); + out << (quint16)0; + out << echo; + + out.device()->seek(0); + out << (quint16)(outPayload.size() - sizeof(quint16)); + + bool ret = socket->writeDatagram(outPayload, m_target, m_port); + QVERIFY(ret == 0); + + QTest::qWait(5 * 1000);//give some time to wait bytesWritten signal + QVERIFY(errorSpy.isEmpty()); + + } + +class WaitBytesWrittenSlot : public QObject +{ + Q_OBJECT +public: + WaitBytesWrittenSlot(QLlcpSocket& s): m_socket(s),m_signalCount(0) + { + connect(&m_socket,SIGNAL(bytesWritten(qint64)),this,SLOT(gotBytesWritten(qint64))); + } +private slots: +void gotBytesWritten(qint64 w) + { + m_signalCount++; + qDebug()<<"Got BytesWritten() signal number = "<<m_signalCount; + const int Timeout = 50;//3* 1000 seems too long, nfc server will panic spray signal + bool ret = m_socket.waitForBytesWritten(Timeout); + if (!ret) + { + qDebug()<<"WaitBytesWrittenSlot() in slot of ReadyRead signal return false"; + } + else + { + qDebug()<<"WaitBytesWrittenSlot() in slot of ReadyRead signal return true"; + } + } +private: + QLlcpSocket& m_socket; + int m_signalCount; +}; +/*! + Description: Test WaitForBytesWritten() in slot of + bytesWritten signal, make sure the signal will not + be emitted twice in the slot function. + CounterPart test: tst_qllcpsocketremote::echoServer() +*/ +void tst_qllcpsocketlocal::waitBytesWrittenInSlot() +{ + QLlcpSocket localSocket; + + QCOMPARE(localSocket.state(), QLlcpSocket::UnconnectedState); + QSignalSpy stateChangedSpy(&localSocket, SIGNAL(stateChanged(QLlcpSocket::SocketState))); + + QSignalSpy readyReadSpy(&localSocket, SIGNAL(readyRead())); + bool retBool = localSocket.bind(m_port); + QVERIFY(retBool); + QVERIFY(!stateChangedSpy.isEmpty()); + QCOMPARE(localSocket.state(), QLlcpSocket::BoundState); + + // Wait remote part bind + QString messageBox("Wait remote bind"); + QNfcTestUtil::ShowAutoMsg(messageBox); + + // STEP 3: Local peer sends the message to the remote peer + QSignalSpy errorSpy(&localSocket, SIGNAL(error(QLlcpSocket::SocketState))); + QSignalSpy bytesWrittenSpy(&localSocket, SIGNAL(bytesWritten(qint64))); + + WaitBytesWrittenSlot slot(localSocket); + + QString echoPayload; + for (int i = 0; i < 2000; i++) + echoPayload.append((char)(i%26 + 'a')); + //Prepare data to send + QByteArray outPayload; + QDataStream out(&outPayload, QIODevice::WriteOnly); + out.setVersion(QDataStream::Qt_4_6); + out << (quint16)0; + out << echoPayload; + + out.device()->seek(0); + out << (quint16)(outPayload.size() - sizeof(quint16)); + + bool ret = localSocket.writeDatagram(outPayload, m_target, m_port); + QVERIFY(ret == 0); + + QTRY_VERIFY(!bytesWrittenSpy.isEmpty()); + + qint64 written = 0; + qint32 lastSignalCount = 0; + while(true) + { + for(int i = lastSignalCount; i < bytesWrittenSpy.count(); i++) { + written += bytesWrittenSpy.at(i).at(0).value<qint64>(); + } + lastSignalCount = bytesWrittenSpy.count(); + qDebug() << "current signal count = " << lastSignalCount; + qDebug() << "written payload size = " << written; + if (written < outPayload.size()) { + QTRY_VERIFY(bytesWrittenSpy.count() > lastSignalCount); + } + else { + break; + } + } + qDebug() << "Overall bytesWritten = " << written; + qDebug() << "Overall block size = " << outPayload.size(); + QVERIFY(written == outPayload.size()); + + // STEP 4: Start read payload from server + QString messageBox2("Wait remote send buffer"); + QNfcTestUtil::ShowAutoMsg(messageBox2, &readyReadSpy); + + QByteArray inPayload; + while(localSocket.hasPendingDatagrams()) { + QByteArray tempBuffer; + tempBuffer.resize(localSocket.pendingDatagramSize()); + quint8 remotePort = 0; + QSignalSpy readyRead(&localSocket, SIGNAL(readyRead())); + qint64 readSize = localSocket.readDatagram(tempBuffer.data() + , tempBuffer.size() + , &m_target, &remotePort); + QVERIFY(readSize != -1); + QVERIFY(remotePort > 0); + inPayload.append(tempBuffer); + qDebug() << "Client-- read inPayload size=" << inPayload.size(); + qDebug() << "Client-- read remotePort=" << remotePort; + if (inPayload.size() >= (int)sizeof(quint16)) { + break; + } + else + { + qDebug() << "Client-- not enough header"; + QTRY_VERIFY(!readyRead.isEmpty()); + } + } + + QDataStream in(inPayload); + in.setVersion(QDataStream::Qt_4_6); + quint16 headerSize = 0; // size of real echo payload + in >> headerSize; + qDebug() << "Client-- read headerSize=" << headerSize; + while (inPayload.size() < headerSize + (int)sizeof(quint16)){ + QSignalSpy readyRead(&localSocket, SIGNAL(readyRead())); + QTRY_VERIFY(!readyRead.isEmpty()); + if(localSocket.hasPendingDatagrams()) { + QByteArray tempBuffer; + tempBuffer.resize(localSocket.pendingDatagramSize()); + quint8 remotePort = 0; + qint64 readSize = localSocket.readDatagram(tempBuffer.data() + , tempBuffer.size() + , &m_target, &remotePort); + QVERIFY(readSize != -1); + QVERIFY(remotePort > 0); + inPayload.append(tempBuffer); + qDebug() << "Client-- read long blocksize=" << inPayload.size(); + } + } + + QDataStream in2(inPayload); + in2.setVersion(QDataStream::Qt_4_6); + in2 >> headerSize; + QString inEchoPayload; + in2 >> inEchoPayload; + qDebug() << "Client-- in echo string len:" << inEchoPayload.length(); + qDebug("Client-- in echo string = %s", qPrintable(inEchoPayload)); + //test the echoed string is same as the original string + QVERIFY(echoPayload == inEchoPayload); + // make sure the no error signal emitted + QVERIFY(errorSpy.isEmpty()); +} +/*! + Description: writeDatagram negative testcase I - invalid port num & wait* functions +*/ +void tst_qllcpsocketlocal::negTestCase1() +{ + QLlcpSocket localSocket; + QString message = "Oops, Invalid port num for writeDatagram"; + QByteArray tmpArray(message.toAscii()); + const char* data = tmpArray.data(); + qint64 strSize = message.size(); + qint8 invalidPort = -1; + qint64 ret = localSocket.writeDatagram(data,strSize,m_target, invalidPort); + QVERIFY(ret == -1); + + const int Timeout = 1 * 500; + bool retBool = localSocket.waitForBytesWritten(Timeout); + QVERIFY(!retBool); + + //Cover QLLCPUnConnected::WaitForReadyRead + retBool = localSocket.waitForReadyRead(Timeout); + QVERIFY(!retBool); + + //Cover QLLCPBind::WaitForReadyRead() + retBool = localSocket.waitForReadyRead(Timeout); + QVERIFY(!retBool); +} + +/*! + Description: bind negative test - double bind +*/ +void tst_qllcpsocketlocal::negTestCase2() +{ + QLlcpSocket localSocket1; + QLlcpSocket localSocket2; + // bind again will cause failure + bool ret2 = localSocket1.bind(m_port); + QVERIFY(ret2); + ret2 = localSocket2.bind(m_port); + QVERIFY(!ret2); +} + +/*! + Description: bind negative test - invalid port num +*/ +/* +void tst_qllcpsocketlocal::negTestCase3() +{ + QLlcpSocket localSocket; + bool ret = localSocket.bind(65); + QVERIFY(ret == false); +} +*/ + +/*! + Description: bind negative test - invalid port num II +*/ +/* +void tst_qllcpsocketlocal::negTestCase4() +{ + QLlcpSocket localSocket; + int reservedPort = 15; + bool ret = localSocket.bind(reservedPort); + QVERIFY(ret == false); +} +*/ +void tst_qllcpsocketlocal::multiSocketToOneServer() +{ + QString echoPayload = "multiSocketToOneServer"; + { + QLlcpSocket localSocket; + + + QCOMPARE(localSocket.state(), QLlcpSocket::UnconnectedState); + QSignalSpy stateChangedSpy(&localSocket, SIGNAL(stateChanged(QLlcpSocket::SocketState))); + + // STEP 2: bind the local port for current socket + QSignalSpy readyReadSpy(&localSocket, SIGNAL(readyRead())); + bool retBool = localSocket.bind(m_port); + QVERIFY(retBool); + QVERIFY(!stateChangedSpy.isEmpty()); + QCOMPARE(localSocket.state(), QLlcpSocket::BoundState); + + // Wait remote part bind + QString messageBox("Wait remote bind"); + QNfcTestUtil::ShowAutoMsg(messageBox); + + // STEP 3: Local peer sends the message to the remote peer + QSignalSpy errorSpy(&localSocket, SIGNAL(error(QLlcpSocket::SocketState))); + QSignalSpy bytesWrittenSpy(&localSocket, SIGNAL(bytesWritten(qint64))); + + //Prepare data to send + QByteArray outPayload; + QDataStream out(&outPayload, QIODevice::WriteOnly); + out.setVersion(QDataStream::Qt_4_6); + out << (quint16)0; + out << echoPayload; + + qDebug("Client-- write quint16 length = %d", sizeof(quint16)); + qDebug("Client-- write echo string length= %d", echoPayload.length()); + qDebug("Client-- write payload length = %d", outPayload.length()); + out.device()->seek(0); + out << (quint16)(outPayload.size() - sizeof(quint16)); + + bool ret = localSocket.writeDatagram(outPayload, m_target, m_port); + QVERIFY(ret == 0); + + QTRY_VERIFY(!bytesWrittenSpy.isEmpty()); + + qint64 written = 0; + qint32 lastSignalCount = 0; + while(true) + { + for(int i = lastSignalCount; i < bytesWrittenSpy.count(); i++) { + written += bytesWrittenSpy.at(i).at(0).value<qint64>(); + } + lastSignalCount = bytesWrittenSpy.count(); + qDebug() << "current signal count = " << lastSignalCount; + qDebug() << "written payload size = " << written; + if (written < outPayload.size()) { + QTRY_VERIFY(bytesWrittenSpy.count() > lastSignalCount); + } + else { + break; + } + } + qDebug() << "Overall bytesWritten = " << written; + qDebug() << "Overall block size = " << outPayload.size(); + QVERIFY(written == outPayload.size()); + + // STEP 4: Start read payload from server + QString messageBox2("Wait remote send buffer"); + QNfcTestUtil::ShowAutoMsg(messageBox2, &readyReadSpy); + + QByteArray inPayload; + while(localSocket.hasPendingDatagrams()) { + QByteArray tempBuffer; + tempBuffer.resize(localSocket.pendingDatagramSize()); + quint8 remotePort = 0; + QSignalSpy readyRead(&localSocket, SIGNAL(readyRead())); + qint64 readSize = localSocket.readDatagram(tempBuffer.data() + , tempBuffer.size() + , &m_target, &remotePort); + QVERIFY(readSize != -1); + QVERIFY(remotePort > 0); + inPayload.append(tempBuffer); + qDebug() << "Client-- read inPayload size=" << inPayload.size(); + qDebug() << "Client-- read remotePort=" << remotePort; + if (inPayload.size() >= (int)sizeof(quint16)) { + break; + } + else + { + qDebug() << "Client-- not enough header"; + QTRY_VERIFY(!readyRead.isEmpty()); + } + } + + QDataStream in(inPayload); + in.setVersion(QDataStream::Qt_4_6); + quint16 headerSize = 0; // size of real echo payload + in >> headerSize; + qDebug() << "Client-- read headerSize=" << headerSize; + while (inPayload.size() < headerSize + (int)sizeof(quint16)){ + QSignalSpy readyRead(&localSocket, SIGNAL(readyRead())); + QTRY_VERIFY(!readyRead.isEmpty()); + if(localSocket.hasPendingDatagrams()) { + QByteArray tempBuffer; + tempBuffer.resize(localSocket.pendingDatagramSize()); + quint8 remotePort = 0; + qint64 readSize = localSocket.readDatagram(tempBuffer.data() + , tempBuffer.size() + , &m_target, &remotePort); + QVERIFY(readSize != -1); + QVERIFY(remotePort > 0); + inPayload.append(tempBuffer); + qDebug() << "Client-- read long blocksize=" << inPayload.size(); + } + } + + QDataStream in2(inPayload); + in2.setVersion(QDataStream::Qt_4_6); + in2 >> headerSize; + QString inEchoPayload; + in2 >> inEchoPayload; + qDebug() << "Client-- in echo string len:" << inEchoPayload.length(); + qDebug("Client-- in echo string = %s", qPrintable(inEchoPayload)); + //test the echoed string is same as the original string + QVERIFY(echoPayload == inEchoPayload); + // make sure the no error signal emitted + QVERIFY(errorSpy.isEmpty()); + + } + { + QLlcpSocket localSocket; + + + QCOMPARE(localSocket.state(), QLlcpSocket::UnconnectedState); + QSignalSpy stateChangedSpy(&localSocket, SIGNAL(stateChanged(QLlcpSocket::SocketState))); + + // STEP 2: bind the local port for current socket + QSignalSpy readyReadSpy(&localSocket, SIGNAL(readyRead())); + bool retBool = localSocket.bind(m_port); + QVERIFY(retBool); + QVERIFY(!stateChangedSpy.isEmpty()); + QCOMPARE(localSocket.state(), QLlcpSocket::BoundState); + + // Wait remote part bind + QString messageBox("Wait remote bind"); + QNfcTestUtil::ShowAutoMsg(messageBox); + + // STEP 3: Local peer sends the message to the remote peer + QSignalSpy errorSpy(&localSocket, SIGNAL(error(QLlcpSocket::SocketState))); + QSignalSpy bytesWrittenSpy(&localSocket, SIGNAL(bytesWritten(qint64))); + + //Prepare data to send + QByteArray outPayload; + QDataStream out(&outPayload, QIODevice::WriteOnly); + out.setVersion(QDataStream::Qt_4_6); + out << (quint16)0; + out << echoPayload; + + qDebug("Client-- write quint16 length = %d", sizeof(quint16)); + qDebug("Client-- write echo string length= %d", echoPayload.length()); + qDebug("Client-- write payload length = %d", outPayload.length()); + out.device()->seek(0); + out << (quint16)(outPayload.size() - sizeof(quint16)); + + bool ret = localSocket.writeDatagram(outPayload, m_target, m_port); + QVERIFY(ret == 0); + + QTRY_VERIFY(!bytesWrittenSpy.isEmpty()); + + qint64 written = 0; + qint32 lastSignalCount = 0; + while(true) + { + for(int i = lastSignalCount; i < bytesWrittenSpy.count(); i++) { + written += bytesWrittenSpy.at(i).at(0).value<qint64>(); + } + lastSignalCount = bytesWrittenSpy.count(); + qDebug() << "current signal count = " << lastSignalCount; + qDebug() << "written payload size = " << written; + if (written < outPayload.size()) { + QTRY_VERIFY(bytesWrittenSpy.count() > lastSignalCount); + } + else { + break; + } + } + qDebug() << "Overall bytesWritten = " << written; + qDebug() << "Overall block size = " << outPayload.size(); + QVERIFY(written == outPayload.size()); + + // STEP 4: Start read payload from server + QString messageBox2("Wait remote send buffer"); + QNfcTestUtil::ShowAutoMsg(messageBox2, &readyReadSpy); + + QByteArray inPayload; + while(localSocket.hasPendingDatagrams()) { + QByteArray tempBuffer; + tempBuffer.resize(localSocket.pendingDatagramSize()); + quint8 remotePort = 0; + QSignalSpy readyRead(&localSocket, SIGNAL(readyRead())); + qint64 readSize = localSocket.readDatagram(tempBuffer.data() + , tempBuffer.size() + , &m_target, &remotePort); + QVERIFY(readSize != -1); + QVERIFY(remotePort > 0); + inPayload.append(tempBuffer); + qDebug() << "Client-- read inPayload size=" << inPayload.size(); + qDebug() << "Client-- read remotePort=" << remotePort; + if (inPayload.size() >= (int)sizeof(quint16)) { + break; + } + else + { + qDebug() << "Client-- not enough header"; + QTRY_VERIFY(!readyRead.isEmpty()); + } + } + + QDataStream in(inPayload); + in.setVersion(QDataStream::Qt_4_6); + quint16 headerSize = 0; // size of real echo payload + in >> headerSize; + qDebug() << "Client-- read headerSize=" << headerSize; + while (inPayload.size() < headerSize + (int)sizeof(quint16)){ + QSignalSpy readyRead(&localSocket, SIGNAL(readyRead())); + QTRY_VERIFY(!readyRead.isEmpty()); + if(localSocket.hasPendingDatagrams()) { + QByteArray tempBuffer; + tempBuffer.resize(localSocket.pendingDatagramSize()); + quint8 remotePort = 0; + qint64 readSize = localSocket.readDatagram(tempBuffer.data() + , tempBuffer.size() + , &m_target, &remotePort); + QVERIFY(readSize != -1); + QVERIFY(remotePort > 0); + inPayload.append(tempBuffer); + qDebug() << "Client-- read long blocksize=" << inPayload.size(); + } + } + + QDataStream in2(inPayload); + in2.setVersion(QDataStream::Qt_4_6); + in2 >> headerSize; + QString inEchoPayload; + in2 >> inEchoPayload; + qDebug() << "Client-- in echo string len:" << inEchoPayload.length(); + qDebug("Client-- in echo string = %s", qPrintable(inEchoPayload)); + //test the echoed string is same as the original string + QVERIFY(echoPayload == inEchoPayload); + // make sure the no error signal emitted + QVERIFY(errorSpy.isEmpty()); + + } + +} +void tst_qllcpsocketlocal::cleanupTest() +{ +} + +QTEST_MAIN(tst_qllcpsocketlocal); + +#include "tst_qllcpsocketlocal.moc" diff --git a/tests/nfcsymbianbackend/qllcpsocketremote/qllcpsocketremote.pro b/tests/nfcsymbianbackend/qllcpsocketremote/qllcpsocketremote.pro new file mode 100644 index 00000000..71175303 --- /dev/null +++ b/tests/nfcsymbianbackend/qllcpsocketremote/qllcpsocketremote.pro @@ -0,0 +1,24 @@ + +QT += testlib + +TARGET = tst_qllcpsocketremote +CONFIG += console +CONFIG -= app_bundle +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_qllcpsocketremote.cpp \ + ../common/qautomsgbox.cpp +symbian:TARGET.CAPABILITY = ALL -TCB diff --git a/tests/nfcsymbianbackend/qllcpsocketremote/tst_qllcpsocketremote.cpp b/tests/nfcsymbianbackend/qllcpsocketremote/tst_qllcpsocketremote.cpp new file mode 100644 index 00000000..550c5458 --- /dev/null +++ b/tests/nfcsymbianbackend/qllcpsocketremote/tst_qllcpsocketremote.cpp @@ -0,0 +1,471 @@ +/**************************************************************************** +** +** 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 <QtCore/QString> +#include <QtTest/QtTest> +#include <QtCore/QCoreApplication> + +#include <qllcpsocket.h> +#include <qnearfieldmanager.h> +#include <qnearfieldtarget.h> +#include "qnfctestcommon.h" +#include "qnfctestutil.h" + +Q_DECLARE_METATYPE(QNearFieldTarget*) +Q_DECLARE_METATYPE(QLlcpSocket::SocketError); + +class tst_qllcpsocketremote : public QObject +{ + Q_OBJECT + +public: + tst_qllcpsocketremote(); + +private Q_SLOTS: + + void mulitpleServer(); + void echoServer(); + void testCase2(); + + void dumpServer(); + void multiConnection(); + + void initTestCase(); + void cleanupTest(); + + +private: + void readMessage(QLlcpSocket& remoteSocket,QByteArray& inPayload); + void verifyString(QString& longStr4k, QByteArray& inPayload); +private: + QNearFieldTarget *m_target; // Not own + quint8 m_port; +}; + +tst_qllcpsocketremote::tst_qllcpsocketremote() +{ + qRegisterMetaType<QNearFieldTarget *>("QNearFieldTarget*"); + qRegisterMetaType<QLlcpSocket::SocketError>("QLlcpSocket::SocketError"); +} + +/*! + Description: Init test case for NFC LLCP connection-less mode socket - local peer + + TestScenario: + Touch a NFC device with LLCP connection-less service actived + + TestExpectedResults: + Signal of target detected has been found. +*/ +void tst_qllcpsocketremote::initTestCase() +{ + QNearFieldManager nfcManager; + QSignalSpy targetDetectedSpy(&nfcManager, SIGNAL(targetDetected(QNearFieldTarget*))); + nfcManager.startTargetDetection(QNearFieldTarget::NfcForumDevice); + + QString message("Please touch a NFC device with llcp client enabled"); + QNfcTestUtil::ShowAutoMsg(message, &targetDetectedSpy, 1); + QTRY_VERIFY(!targetDetectedSpy.isEmpty()); + + m_target = targetDetectedSpy.at(targetDetectedSpy.count() - 1).at(0).value<QNearFieldTarget *>(); + QVERIFY(m_target!=NULL); + QVERIFY(m_target->accessMethods() & QNearFieldTarget::LlcpAccess); + QVERIFY(m_target->uid() == QByteArray()); + QVERIFY(m_target->type() == QNearFieldTarget::NfcForumDevice); + + m_port = 35; +} + + +void tst_qllcpsocketremote::readMessage( + QLlcpSocket& remoteSocket, + QByteArray& inPayload) +{ + // STEP 2: Receive data from the peer which send messages to + while(remoteSocket.hasPendingDatagrams()) { + QByteArray tempBuffer; + tempBuffer.resize(remoteSocket.pendingDatagramSize()); + quint8 remotePort = 0; + QSignalSpy readyRead(&remoteSocket, SIGNAL(readyRead())); + qint64 readSize = remoteSocket.readDatagram(tempBuffer.data() + , tempBuffer.size() + , &m_target, &remotePort); + QVERIFY(readSize != -1); + QVERIFY(remotePort > 0); + inPayload.append(tempBuffer); + qDebug() << "Server-- read inPayload size=" << inPayload.size(); + qDebug() << "Server-- read remotePort=" << remotePort; + if (inPayload.size() >= (int)sizeof(quint16)) { + break; + } + else { + qDebug() << "Server-- not enough header"; + QTRY_VERIFY(!readyRead.isEmpty()); + } + } + + QDataStream in(inPayload); + quint16 headerSize = 0; // size of real echo payload + in >> headerSize; + qDebug() << "Server-- read headerSize=" << headerSize; + while (inPayload.size() < headerSize + (int)sizeof(quint16)){ + QSignalSpy readyRead(&remoteSocket, SIGNAL(readyRead())); + QTRY_VERIFY(!readyRead.isEmpty()); + if(remoteSocket.hasPendingDatagrams()) { + QByteArray tempBuffer; + tempBuffer.resize(remoteSocket.pendingDatagramSize()); + quint8 remotePort = 0; + qint64 readSize = remoteSocket.readDatagram(tempBuffer.data() + , tempBuffer.size() + , &m_target, &remotePort); + QVERIFY(readSize != -1); + QVERIFY(remotePort > 0); + inPayload.append(tempBuffer); + qDebug() << "Server-- read long blocksize=" << inPayload.size(); + } + } +} + +void tst_qllcpsocketremote::verifyString( + QString& longStr, + QByteArray& inPayload) +{ + quint16 headerSize; + QDataStream in2(inPayload); + in2.setVersion(QDataStream::Qt_4_6); + in2 >> headerSize; + QString receivedLongStr; + in2 >> receivedLongStr; + qDebug() << "Client-- in received string len:" << receivedLongStr.length(); + qDebug("Client-- in received string = %s", qPrintable(receivedLongStr)); + //test the received string is same as the original string + QVERIFY(longStr == receivedLongStr); +} + + +/*! + Description: Description: Receive the message and send the acknowledged identical message + + TestScenario: 1. Remote peer binds to local port + 2. Remote peer receives the long message sending from the local peer + 3. Remote peer receives the other long message sending from the local peer + + TestExpectedResults: + 1. Remote peer binds to local port successfully. + 2. The 1st long message has been received from remote peer. + 3. The 2nd long message has been received from remote peer. +*/ +void tst_qllcpsocketremote::mulitpleServer() +{ + QLlcpSocket remoteSocket; + bool ret = remoteSocket.bind(m_port); + QVERIFY(ret); + + QString longStr1k; + for (int i = 0; i < 1000; i++) + longStr1k.append((char)(i%26 + 'a')); + + QString longStr2k; + for (int i = 0; i < 2000; i++) + longStr2k.append((char)(i%26 + 'b')); + + QSignalSpy readyReadSpy(&remoteSocket, SIGNAL(readyRead())); + QString message("mulitpleServer 1: Wait multiple msg coming"); + QNfcTestUtil::ShowAutoMsg(message, &readyReadSpy); + + QByteArray inPayload; + readMessage(remoteSocket,inPayload); + + QSignalSpy readyReadSpy2(&remoteSocket, SIGNAL(readyRead())); + QString message2("mulitpleServer 2: Wait multiple msg coming"); + QNfcTestUtil::ShowAutoMsg(message2, &readyReadSpy2); + + QByteArray inPayload2; + readMessage(remoteSocket,inPayload2); + + verifyString(longStr1k,inPayload); + verifyString(longStr2k,inPayload2); +} + +/*! + Description: Description: Receive the message and send the acknowledged identical message + + TestScenario: 1. Remote peer binds to local port + 2. Remote peer receives the message sending from the local peer + 3. Remote peer sends the echoed message to the local peer + + TestExpectedResults: + 1. Remote peer binds to local port successfully. + 2. The message has been received from remote peer. + 3. The message has be sent to local peer. +*/ +void tst_qllcpsocketremote::echoServer() +{ + QLlcpSocket remoteSocket; + // STEP 1: bind the local port for current socket + QSignalSpy readyReadSpy(&remoteSocket, SIGNAL(readyRead())); + bool ret = remoteSocket.bind(m_port); + QVERIFY(ret); + + QString message("Test 1: Wait client msg coming"); + QNfcTestUtil::ShowAutoMsg(message, &readyReadSpy); + + // STEP 2: Receive data from the peer which send messages to + QByteArray inPayload; + readMessage(remoteSocket,inPayload); + + // STEP 3: Send the received message back to the intiated device. + QSignalSpy errorSpy(&remoteSocket, SIGNAL(error(QLlcpSocket::SocketError))); + QSignalSpy bytesWrittenSpy(&remoteSocket, SIGNAL(bytesWritten(qint64))); + + qDebug("Server-- write payload length = %d", inPayload.length()); + qint64 val = remoteSocket.writeDatagram(inPayload, m_target, m_port); + QVERIFY(val != -1); + + QTRY_VERIFY(!bytesWrittenSpy.isEmpty()); + + qint64 written = 0; + qint32 lastSignalCount = 0; + while(true) + { + for(int i = lastSignalCount; i < bytesWrittenSpy.count(); i++) { + written += bytesWrittenSpy.at(i).at(0).value<qint64>(); + } + lastSignalCount = bytesWrittenSpy.count(); + qDebug() << "current signal count = " << lastSignalCount; + qDebug() << "written payload size = " << written; + if (written < inPayload.size()) { + QTRY_VERIFY(bytesWrittenSpy.count() > lastSignalCount); + } + else { + break; + } + } + + qDebug() << "Overall bytesWritten = " << written; + qDebug() << "Overall block size = " << inPayload.size(); + QVERIFY(written == inPayload.size()); + // make sure the no error signal emitted + QCOMPARE(errorSpy.count(), 0); +} + +/*! + Description: This server will all dump data received from client + To test some negtive case +*/ +void tst_qllcpsocketremote::dumpServer() + { + QLlcpSocket remoteSocket; + QSignalSpy readyReadSpy(&remoteSocket, SIGNAL(readyRead())); + bool ret = remoteSocket.bind(m_port); + QVERIFY(ret); + QString message("dumpServer test"); + QNfcTestUtil::ShowAutoMsg(message, &readyReadSpy); + + QTest::qWait(2 * 1000); + } +/*! + Description: Unit test for NFC LLCP connection-less mode socket - remote peer (passive) + + TestScenario: 1. Remote peer binds to local port ( already done in testCase1) + 2. Remote peer receive datagram twice + 3. Remote peer waitForReadyRead + + TestExpectedResults: + 1. Remote peer binds to local port successfully. + 2. Remote peer receive datagram twice successfully + 3. waitForReadyRead return true as long as readyReadSpy not empty +*/ +void tst_qllcpsocketremote::testCase2() +{ + QLlcpSocket remoteSocket; + quint8 localPort = 38; + QSignalSpy readyReadSpy(&remoteSocket, SIGNAL(readyRead())); + bool ret = remoteSocket.bind(localPort); + QVERIFY(ret); + + // STEP 1: bind the local port for current socket + QString expectedMessage1("testcase2 string str1"); + QString expectedMessage2("testcase2 string str2"); + + QString boxMessage("handshake 3"); + QNfcTestUtil::ShowAutoMsg(boxMessage,&readyReadSpy); + + QTRY_VERIFY(readyReadSpy.count() == 1); + + QByteArray datagram; + if (remoteSocket.hasPendingDatagrams()) + { + datagram.resize(remoteSocket.pendingDatagramSize()); + qint64 readSize = remoteSocket.readDatagram(datagram.data(), datagram.size()); + QVERIFY(readSize != -1); + } + + QString receivedMessage1 = datagram.data(); + qDebug() << "receivedMessage1: " << receivedMessage1; + QVERIFY(expectedMessage1 == receivedMessage1); + + QTRY_VERIFY(readyReadSpy.count() == 2); + + QByteArray datagram2; + if (remoteSocket.hasPendingDatagrams()) + { + datagram2.resize(remoteSocket.pendingDatagramSize()); + qint64 readSize = remoteSocket.readDatagram(datagram2.data(), datagram2.size()); + QVERIFY(readSize != -1); + } + QString receivedMessage2 = datagram2.data(); + qDebug() << "receivedMessage2: " << receivedMessage2; + QVERIFY(expectedMessage2 == receivedMessage2); + + const int Timeout = 10 * 1000; + ret = remoteSocket.waitForReadyRead(Timeout); + + QVERIFY(ret == false); + } +void tst_qllcpsocketremote::multiConnection() + { + QLlcpSocket remoteSocket; + // STEP 1: bind the local port for current socket + QSignalSpy readyReadSpy(&remoteSocket, SIGNAL(readyRead())); + bool ret = remoteSocket.bind(m_port); + QVERIFY(ret); + + const int KLoopCount = 2; + int loopCount = 0; + + while(loopCount < KLoopCount) + { + QString message("Test 1: Wait client msg coming"); + QNfcTestUtil::ShowAutoMsg(message, &readyReadSpy); + + // STEP 2: Receive data from the peer which send messages to + QByteArray inPayload; + while(remoteSocket.hasPendingDatagrams()) { + QByteArray tempBuffer; + tempBuffer.resize(remoteSocket.pendingDatagramSize()); + quint8 remotePort = 0; + QSignalSpy readyRead(&remoteSocket, SIGNAL(readyRead())); + qint64 readSize = remoteSocket.readDatagram(tempBuffer.data() + , tempBuffer.size() + , &m_target, &remotePort); + QVERIFY(readSize != -1); + QVERIFY(remotePort > 0); + inPayload.append(tempBuffer); + qDebug() << "Server-- read inPayload size=" << inPayload.size(); + qDebug() << "Server-- read remotePort=" << remotePort; + if (inPayload.size() >= (int)sizeof(quint16)) { + break; + } + else { + qDebug() << "Server-- not enough header"; + QTRY_VERIFY(!readyRead.isEmpty()); + } + } + + QDataStream in(inPayload); + quint16 headerSize = 0; // size of real echo payload + in >> headerSize; + qDebug() << "Server-- read headerSize=" << headerSize; + while (inPayload.size() < headerSize + (int)sizeof(quint16)){ + QSignalSpy readyRead(&remoteSocket, SIGNAL(readyRead())); + QTRY_VERIFY(!readyRead.isEmpty()); + if(remoteSocket.hasPendingDatagrams()) { + QByteArray tempBuffer; + tempBuffer.resize(remoteSocket.pendingDatagramSize()); + quint8 remotePort = 0; + qint64 readSize = remoteSocket.readDatagram(tempBuffer.data() + , tempBuffer.size() + , &m_target, &remotePort); + QVERIFY(readSize != -1); + QVERIFY(remotePort > 0); + inPayload.append(tempBuffer); + qDebug() << "Server-- read long blocksize=" << inPayload.size(); + } + } + + // STEP 3: Send the received message back to the intiated device. + QSignalSpy errorSpy(&remoteSocket, SIGNAL(error(QLlcpSocket::SocketError))); + QSignalSpy bytesWrittenSpy(&remoteSocket, SIGNAL(bytesWritten(qint64))); + + qDebug("Server-- write payload length = %d", inPayload.length()); + qint64 val = remoteSocket.writeDatagram(inPayload, m_target, m_port); + QVERIFY(val != -1); + + QTRY_VERIFY(!bytesWrittenSpy.isEmpty()); + + qint64 written = 0; + qint32 lastSignalCount = 0; + while(true) + { + for(int i = lastSignalCount; i < bytesWrittenSpy.count(); i++) { + written += bytesWrittenSpy.at(i).at(0).value<qint64>(); + } + lastSignalCount = bytesWrittenSpy.count(); + qDebug() << "current signal count = " << lastSignalCount; + qDebug() << "written payload size = " << written; + if (written < inPayload.size()) { + QTRY_VERIFY(bytesWrittenSpy.count() > lastSignalCount); + } + else { + break; + } + } + + qDebug() << "Overall bytesWritten = " << written; + qDebug() << "Overall block size = " << inPayload.size(); + QVERIFY(written == inPayload.size()); + // make sure the no error signal emitted + QCOMPARE(errorSpy.count(), 0); + //wait another socket to send data + loopCount++; + readyReadSpy.removeFirst(); + } + QTest::qWait(1500);//give some time to client to finish + + } +void tst_qllcpsocketremote::cleanupTest() +{ +} + +QTEST_MAIN(tst_qllcpsocketremote); + +#include "tst_qllcpsocketremote.moc" diff --git a/tests/nfcsymbianbackend/qllcpsockettype2/qllcpsockettype2.pro b/tests/nfcsymbianbackend/qllcpsockettype2/qllcpsockettype2.pro new file mode 100644 index 00000000..0f0cc4fa --- /dev/null +++ b/tests/nfcsymbianbackend/qllcpsockettype2/qllcpsockettype2.pro @@ -0,0 +1,23 @@ +QT += testlib + +TARGET = tst_qllcpsockettype2 +CONFIG += console +CONFIG -= app_bundle +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_qllcpsockettype2.cpp \ + ../common/qautomsgbox.cpp +symbian:TARGET.CAPABILITY = ALL -TCB diff --git a/tests/nfcsymbianbackend/qllcpsockettype2/tst_qllcpsockettype2.cpp b/tests/nfcsymbianbackend/qllcpsockettype2/tst_qllcpsockettype2.cpp new file mode 100644 index 00000000..cefdcd9f --- /dev/null +++ b/tests/nfcsymbianbackend/qllcpsockettype2/tst_qllcpsockettype2.cpp @@ -0,0 +1,1120 @@ +/**************************************************************************** +** +** 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 <QtCore/QString> +#include <QtTest/QtTest> +#include <QtCore/QCoreApplication> + +#include <qllcpsocket.h> +#include <qnearfieldmanager.h> +#include <qnearfieldtarget.h> +#include "qnfctestcommon.h" +#include "qnfctestutil.h" + +Q_DECLARE_METATYPE(QNearFieldTarget*) +Q_DECLARE_METATYPE(QLlcpSocket::SocketState) +Q_DECLARE_METATYPE(QLlcpSocket::SocketError) + +QString TestUri("urn:nfc:xsn:nokia:symbiantest"); +static qint64 countBytesWritten(QSignalSpy& bytesWrittenSpy) + { + qint64 ret = 0; + for(int i = 0; i < bytesWrittenSpy.count(); i++) + { + ret+=bytesWrittenSpy[i].at(0).value<qint64>(); + } + return ret; + } +class tst_qllcpsockettype2 : public QObject +{ + Q_OBJECT + +public: + tst_qllcpsockettype2(); + +private Q_SLOTS: + void initTestCase(); + void cleanupTestCase(); + + // basic acceptance testcases + void echo(); + void echo_data(); + void echo_wait(); + void echo_wait_data(); + void api_coverage(); + + void multipleWrite(); + void multipleWrite_data(); + // advanced testcases + void waitReadyReadInSlot(); + void deleteSocketWhenInUse(); + void multiSocketToOneServer(); + // nagetive testcases + void connectTest(); + void negTestCase1(); + void negTestCase2(); + void negTestCase3(); + + void sendEmptyData(); + + private: + QNearFieldTarget *m_target; // not own +}; + +tst_qllcpsockettype2::tst_qllcpsockettype2() +{ + qRegisterMetaType<QNearFieldTarget*>("QNearFieldTarget*"); + qRegisterMetaType<QLlcpSocket::SocketError>("QLlcpSocket::SocketError"); + qRegisterMetaType<QLlcpSocket::SocketState>("QLlcpSocket::SocketState"); +} + +void tst_qllcpsockettype2::initTestCase() +{ + qDebug()<<"tst_qllcpsockettype2::initTestCase() Begin"; + QString message("Please touch a NFC device with llcp client enabled"); + QNearFieldManager nfcManager; + QSignalSpy targetDetectedSpy(&nfcManager, SIGNAL(targetDetected(QNearFieldTarget*))); + nfcManager.startTargetDetection(QNearFieldTarget::NfcForumDevice); + + QNfcTestUtil::ShowAutoMsg(message, &targetDetectedSpy, 1); + QTRY_VERIFY(!targetDetectedSpy.isEmpty()); + + m_target = targetDetectedSpy.at(targetDetectedSpy.count() - 1).at(0).value<QNearFieldTarget*>(); + QVERIFY(m_target != NULL); + QVERIFY(m_target->accessMethods() & QNearFieldTarget::LlcpAccess); + QVERIFY(m_target->uid() == QByteArray()); + QVERIFY(m_target->type() == QNearFieldTarget::NfcForumDevice); + qDebug()<<"tst_qllcpsockettype2::initTestCase() End"; +} + + +void tst_qllcpsockettype2::cleanupTestCase() +{ +} + + +/*! + Description: Unit test for NFC LLCP socket async functions + + TestScenario: + 1. Echo client will connect to the Echo server + 2. Echo client will send the "echo" message to the server + 3. Echo client will receive the same message echoed from the server + 4. Echo client will disconnect the connection. + + TestExpectedResults: + 2. The message has be sent to server. + 3. The echoed message has been received from server. + 4. Connection disconnected and NO error signals emitted. + + CounterPart test: tst_QLlcpServer::newConnection() or newConnection_wait() +*/ +void tst_qllcpsockettype2::echo() +{ + QFETCH(QString, uri); + QFETCH(QString, echo); + + QString message("echo test"); + + QNfcTestUtil::ShowAutoMsg(message); + QLlcpSocket socket(this); + QSignalSpy connectedSpy(&socket, SIGNAL(connected())); + QSignalSpy errorSpy(&socket, SIGNAL(error(QLlcpSocket::SocketError))); + QSignalSpy readyReadSpy(&socket, SIGNAL(readyRead())); + + QSignalSpy bytesWrittenSpy(&socket, SIGNAL(bytesWritten(qint64))); + + socket.connectToService(m_target, uri); + + // coverage add: WaitForBytesWritten will fail when connecting + const int secs = 1 * 1000; + bool waitRet = socket.waitForBytesWritten(secs); + QVERIFY( waitRet == false); + + QTRY_VERIFY(!connectedSpy.isEmpty()); + + // coverage add: connect to Service again when already connected will cause fail + socket.connectToService(m_target, uri); + QTRY_VERIFY(!errorSpy.isEmpty()); + errorSpy.clear(); + + //Send data to server + QByteArray block; + QDataStream out(&block, QIODevice::WriteOnly); + out.setVersion(QDataStream::Qt_4_6); + out << (quint16)0; + out << echo; + + qDebug("Client-- write quint16 length = %d", sizeof(quint16)); + qDebug("Client-- write echo string = %s", qPrintable(echo)); + qDebug("Client-- write echo string length= %d", echo.length()); + qDebug("Client-- write data length = %d", block.length()); + out.device()->seek(0); + out << (quint16)(block.size() - sizeof(quint16)); + + qint64 val = socket.write(block); + QVERIFY( val == 0); + + QTRY_VERIFY(!bytesWrittenSpy.isEmpty()); + qint64 written = countBytesWritten(bytesWrittenSpy); + + qDebug()<<"bytesWritten signal return value = "<<written; + while (written < block.size()) + { + QSignalSpy bytesWrittenSpy(&socket, SIGNAL(bytesWritten(qint64))); + QTRY_VERIFY(!bytesWrittenSpy.isEmpty()); + qint64 w = countBytesWritten(bytesWrittenSpy); + qDebug()<<"got bytesWritten signal = "<<w; + written += w; + } + qDebug()<<"Overall bytesWritten = "<<written; + qDebug()<<"Overall block size = "<<block.size(); + QTRY_VERIFY(written == block.size()); + //Get the echoed data from server + QTRY_VERIFY(!readyReadSpy.isEmpty()); + quint16 blockSize = 0; + QDataStream in(&socket); + in.setVersion(QDataStream::Qt_4_6); + while (socket.bytesAvailable() < (int)sizeof(quint16)){ + QSignalSpy readyRead(&socket, SIGNAL(readyRead())); + QTRY_VERIFY(!readyRead.isEmpty()); + } + in >> blockSize; + qDebug() << "Client-- read blockSize=" << blockSize; + while (socket.bytesAvailable() < blockSize){ + QSignalSpy readyRead(&socket, SIGNAL(readyRead())); + QTRY_VERIFY(!readyRead.isEmpty()); + } + QString echoed; + in >> echoed; + + qDebug() << "Client-- read echoed string =" << echoed; + //test the echoed string is same as the original string + QVERIFY(echo == echoed); + + socket.disconnectFromService(); + + //Now data has been sent,check the if existing error + QVERIFY(errorSpy.isEmpty()); +} + +void tst_qllcpsockettype2::echo_data() +{ + QTest::addColumn<QString>("uri"); + QTest::addColumn<QString>("echo"); + QTest::newRow("0") << TestUri + << "echo"; + QString longStr4k; + for (int i = 0; i < 4000; i++) + longStr4k.append((char)(i%26 + 'a')); + QTest::newRow("1") << TestUri << longStr4k; +} + +/*! + Description: Unit test for NFC LLCP socket sync(waitXXX) functions + + TestScenario: 1. Touch a NFC device with LLCP Echo service actived + 2. Echo client will connect to the Echo server + 3. Echo client will send the "echo" message to the server + 4. Echo client will receive the same message echoed from the server + 5. Echo client will disconnect the connection. + + TestExpectedResults: + 1. The connection successfully set up. + 2. The message has be sent to server. + 3. The echoed message has been received from server. + 4. Connection disconnected and NO error signals emitted. + + CounterPart test: tst_QLlcpServer::newConnection() or newConnection_wait() +*/ +void tst_qllcpsockettype2::echo_wait() + { + QFETCH(QString, uri); + QFETCH(QString, echo); + + QString message("echo_wait test"); + + QNfcTestUtil::ShowAutoMsg(message); + QLlcpSocket socket(this); + const int Timeout = 10 * 1000; + + socket.connectToService(m_target, uri); + + bool ret = socket.waitForConnected(Timeout); + QVERIFY(ret); + + QSignalSpy errorSpy(&socket, SIGNAL(error(QLlcpSocket::SocketError))); + + //Send data to server + QSignalSpy bytesWrittenSpy(&socket, SIGNAL(bytesWritten(qint64))); + + //Send data to server + QByteArray block; + QDataStream out(&block, QIODevice::WriteOnly); + out.setVersion(QDataStream::Qt_4_6); + out << (quint16)0; + out << echo; + + qDebug("Client-- write quint16 length = %d", sizeof(quint16)); + qDebug("Client-- write echo string = %s", qPrintable(echo)); + qDebug("Client-- write echo string length= %d", echo.length()); + qDebug("Client-- write data length = %d", block.length()); + out.device()->seek(0); + out << (quint16)(block.size() - sizeof(quint16)); + + qint64 val = socket.write(block); + QVERIFY( val == 0); + + ret = socket.waitForBytesWritten(Timeout); + QVERIFY(ret); + + QTRY_VERIFY(!bytesWrittenSpy.isEmpty()); + qint64 written = countBytesWritten(bytesWrittenSpy); + + while (written < block.size()) + { + QSignalSpy bytesWrittenSpy(&socket, SIGNAL(bytesWritten(qint64))); + ret = socket.waitForBytesWritten(Timeout); + QVERIFY(ret); + QTRY_VERIFY(!bytesWrittenSpy.isEmpty()); + written += countBytesWritten(bytesWrittenSpy); + } + QVERIFY(written == block.size()); + //Get the echoed data from server + quint16 blockSize = 0; + QDataStream in(&socket); + in.setVersion(QDataStream::Qt_4_6); + while (socket.bytesAvailable() < (int)sizeof(quint16)){ + ret = socket.waitForReadyRead(Timeout); + QVERIFY(ret); + } + in >> blockSize; + qDebug() << "Client-- read blockSize=" << blockSize; + while (socket.bytesAvailable() < blockSize){ + ret = socket.waitForReadyRead(Timeout); + QVERIFY(ret); + } + QString echoed; + in >> echoed; + qDebug() << "Client-- read echoed string =" << echoed; + //test the echoed string is same as the original string + QVERIFY(echo == echoed); + + socket.disconnectFromService(); + ret = socket.waitForDisconnected(Timeout); + QVERIFY(ret); + //Now data has been sent,check the if existing error + QVERIFY(errorSpy.isEmpty()); + } + +void tst_qllcpsockettype2::echo_wait_data() +{ + QTest::addColumn<QString>("uri"); + QTest::addColumn<QString>("echo"); + QTest::newRow("0") << TestUri + << "echo"; + QString longStr4k; + for (int i = 0; i < 4000; i++) + longStr4k.append((char)(i%26 + 'a')); + QTest::newRow("1") << TestUri << longStr4k; +} + + + +/*! + Description: LLCP Socket API & State Machine test (ReadDatagram tested in server side) + TestScenario: + Covered API: state(), error(), writeDatagram(const char *data, qint64 size); + writeDatagram(const QByteArray &datagram); + + CounterPart test: tst_QLlcpServer::api_coverage() + */ +void tst_qllcpsockettype2::api_coverage() +{ + + QString message("api_coverage test"); + + QNfcTestUtil::ShowAutoMsg(message); + + QLlcpSocket socket(this); + QCOMPARE(socket.state(), QLlcpSocket::UnconnectedState); + QSignalSpy stateChangedSpy(&socket, SIGNAL(stateChanged(QLlcpSocket::SocketState))); + + QSignalSpy connectedSpy(&socket, SIGNAL(connected())); + socket.connectToService(m_target, TestUri); + QTRY_VERIFY(!connectedSpy.isEmpty()); + + QVERIFY(stateChangedSpy.count() == 2); + QLlcpSocket::SocketState state1 = stateChangedSpy.at(0).at(0).value<QLlcpSocket::SocketState>(); + QLlcpSocket::SocketState state2 = stateChangedSpy.at(1).at(0).value<QLlcpSocket::SocketState>(); + QCOMPARE(state1, QLlcpSocket::ConnectingState); + QCOMPARE(state2, QLlcpSocket::ConnectedState); + + QSignalSpy bytesWrittenSpy(&socket, SIGNAL(bytesWritten(qint64))); + message = "Connection oriented write test string"; + QByteArray array; + array.append(message); + qint64 ret = socket.writeDatagram(array.constData(),array.size()); + QVERIFY( ret == 0); + + QTRY_VERIFY(bytesWrittenSpy.count() == 1); + qint64 w = bytesWrittenSpy.first().at(0).value<qint64>(); + QVERIFY(w == array.size()); + stateChangedSpy.clear(); + socket.disconnectFromService(); + QVERIFY(stateChangedSpy.count() == 1); + state1 = stateChangedSpy.at(0).at(0).value<QLlcpSocket::SocketState>(); + QCOMPARE(state1, QLlcpSocket::UnconnectedState); + + QCOMPARE(socket.error(),QLlcpSocket::UnknownSocketError); + +} + + +/*! + Description: connect to Service testcases + TestScenario: 1) double connect cause failure + 2) disconnect the connecting socket should not cause failure + 3) readDatagram after disconnection will cause failure. + + CounterPart test: tst_QLlcpServer::negTestCase1() + */ +void tst_qllcpsockettype2::connectTest() +{ + QString message("connectTest"); + + QNfcTestUtil::ShowAutoMsg(message); + + QLlcpSocket socket(this); + QCOMPARE(socket.state(), QLlcpSocket::UnconnectedState); + QSignalSpy errorSpy(&socket, SIGNAL(error(QLlcpSocket::SocketError))); + + QSignalSpy connectedSpy(&socket, SIGNAL(connected())); + socket.connectToService(m_target, TestUri); + + //connect to the service again when previous one is connecting + socket.connectToService(m_target, TestUri); + QTRY_VERIFY(!errorSpy.isEmpty()); + + errorSpy.clear(); + // make sure it is still connecting + if(connectedSpy.isEmpty()) + { + socket.disconnectFromService(); + } + QTRY_VERIFY(errorSpy.isEmpty()); + + //double disconnect should not cause error + socket.disconnectFromService(); + QTRY_VERIFY(errorSpy.isEmpty()); + + // readDatagram must be called before successul connection to server + QByteArray datagram; + datagram.resize(127); + qint64 ret = socket.readDatagram(datagram.data(), datagram.size()); + QVERIFY(ret == -1); +} + +/*! + Description: Unit test for NFC LLCP socket write several times + + TestScenario: + 1. Echo client will connect to the Echo server + 2. Echo client will send the "echo" message to the server + 3. Echo client will receive the same message echoed from the server + 4. Echo client will disconnect the connection. + + TestExpectedResults: + 2. The message has be sent to server. + 3. The echoed message has been received from server. + 4. Connection disconnected and NO error signals emitted. + + CounterPart test: tst_QLlcpServer::newConnection() or newConnection_wait() +*/ +void tst_qllcpsockettype2::multipleWrite() + { + QFETCH(QString, uri); + QFETCH(QString, echo); + QString message("multipleWrite test"); + QNfcTestUtil::ShowAutoMsg(message); + + QLlcpSocket socket(this); + + QSignalSpy connectedSpy(&socket, SIGNAL(connected())); + socket.connectToService(m_target, uri); + QTRY_VERIFY(!connectedSpy.isEmpty()); + + QSignalSpy bytesWrittenSpy(&socket, SIGNAL(bytesWritten(qint64))); + + QByteArray block; + QDataStream out(&block, QIODevice::WriteOnly); + out.setVersion(QDataStream::Qt_4_6); + out << (quint16)0; + out << echo; + out.device()->seek(0); + out << (quint16)(block.size() - sizeof(quint16)); + qint64 ret = socket.writeDatagram(block.constData(), block.size()/2); + QVERIFY( ret == 0); + ret = socket.writeDatagram(block.constData() + block.size()/2, block.size() - block.size()/2); + QVERIFY( ret == 0); + + QTRY_VERIFY(!bytesWrittenSpy.isEmpty()); + qint64 written = countBytesWritten(bytesWrittenSpy);; + + qDebug()<<"bytesWritten signal return value = "<<written; + while (written < block.size()) + { + QSignalSpy bytesWrittenSpy(&socket, SIGNAL(bytesWritten(qint64))); + QTRY_VERIFY(!bytesWrittenSpy.isEmpty()); + qint64 w = countBytesWritten(bytesWrittenSpy); + qDebug()<<"got bytesWritten signal = "<<w; + written += w; + } + qDebug()<<"Overall bytesWritten = "<<written; + qDebug()<<"Overall block size = "<<block.size(); + QCOMPARE(written, (qint64)block.size()); + + //Get the echoed data from server + const int Timeout = 10 * 1000; + quint16 blockSize = 0; + QDataStream in(&socket); + in.setVersion(QDataStream::Qt_4_6); + while (socket.bytesAvailable() < (int)sizeof(quint16)){ + ret = socket.waitForReadyRead(Timeout); + QVERIFY(ret); + } + in >> blockSize; + qDebug() << "Client-- read blockSize=" << blockSize; + while (socket.bytesAvailable() < blockSize){ + ret = socket.waitForReadyRead(Timeout); + QVERIFY(ret); + } + QString echoed; + in >> echoed; + qDebug() << "Client-- read echoed string =" << echoed; + //test the echoed string is same as the original string + QCOMPARE(echoed, echo); + socket.disconnectFromService(); + ret = socket.waitForDisconnected(Timeout); + QVERIFY(ret); + } + +void tst_qllcpsockettype2::multipleWrite_data() +{ + QTest::addColumn<QString>("uri"); + QTest::addColumn<QString>("echo"); + QTest::newRow("0") << TestUri + << "1234567890"; + QString longStr4k; + for (int i = 0; i < 4000; i++) + longStr4k.append((char)(i%26 + 'a')); + QTest::newRow("1") << TestUri << longStr4k; +} +/*! + Description: coverage test - cover sender DoCancel() method + CounterPart test: tst_QLlcpServer::negTestCase1() +*/ +void tst_qllcpsockettype2::negTestCase1() +{ + QString message("negTestCase1 test"); + QNfcTestUtil::ShowAutoMsg(message); + + QLlcpSocket socket(this); + + QSignalSpy connectedSpy(&socket, SIGNAL(connected())); + socket.connectToService(m_target, TestUri); + QTRY_VERIFY(!connectedSpy.isEmpty()); + + QSignalSpy bytesWrittenSpy(&socket, SIGNAL(bytesWritten(qint64))); + message = "1234567890"; + QByteArray block; + QDataStream out(&block, QIODevice::WriteOnly); + out.setVersion(QDataStream::Qt_4_6); + out << (quint16)0; + out << message; + out.device()->seek(0); + out << (quint16)(block.size() - sizeof(quint16)); + qint64 ret = socket.writeDatagram(block.constData(), block.size()); + QVERIFY( ret != -1); + //cover SenderAO DoCancel() method +} + +/*! + Description: readDatagram/writeDatagram negative test - read/write without connectToService + + CounterPart test: No need counterpart in server side +*/ +void tst_qllcpsockettype2::negTestCase2() +{ + QLlcpSocket socket(this); + QByteArray datagram("Connection oriented negTestCase2"); + qint64 ret = socket.writeDatagram(datagram); + QTRY_VERIFY(ret == -1); + ret = socket.readDatagram(datagram.data(),datagram.size()); + QTRY_VERIFY(ret == -1); +} + + +/*! + Description: negative testcase II - invalid usage of connection-less API + CounterPart test: tst_QLlcpServer::negTestCase1() +*/ +void tst_qllcpsockettype2::negTestCase3() +{ + QLlcpSocket socket(this); + + QString message("negTestCase3 test"); + QNfcTestUtil::ShowAutoMsg(message); + + QSignalSpy errorSpy(&socket, SIGNAL(error(QLlcpSocket::SocketError))); + socket.connectToService(m_target, TestUri); + + bool ret = socket.bind(35); + QVERIFY(ret == false); + + ret = socket.hasPendingDatagrams(); + QVERIFY(ret == false); + + qint64 size = socket.pendingDatagramSize(); + QVERIFY(size == -1); + + message = "Oops, Invalid usage for writeDatagram"; + const char* data = (const char *) message.data(); + qint64 strSize = message.size(); + size = socket.writeDatagram(data,strSize,m_target, 35); + QVERIFY(size == -1); + QByteArray datagram(data); + size = socket.writeDatagram(datagram,m_target, 35); + QVERIFY(size == -1); + + quint8 port = 35; + size = socket.readDatagram(datagram.data(),datagram.size(),&m_target, &port); + QVERIFY(size == -1); + +} +/*! + Description: Send empty data to server + CounterPart test: tst_QLlcpServer::negTestCase1() +*/ +void tst_qllcpsockettype2::sendEmptyData() + { + + QString message("sendEmptyData test"); + + QNfcTestUtil::ShowAutoMsg(message); + QLlcpSocket socket(this); + QSignalSpy connectedSpy(&socket, SIGNAL(connected())); + QSignalSpy errorSpy(&socket, SIGNAL(error(QLlcpSocket::SocketError))); + QSignalSpy readyReadSpy(&socket, SIGNAL(readyRead())); + + QSignalSpy bytesWrittenSpy(&socket, SIGNAL(bytesWritten(qint64))); + + socket.connectToService(m_target, TestUri); + + QTRY_VERIFY(!connectedSpy.isEmpty()); + + //Send data to server + QByteArray block; + + qDebug("Client-- write data length = %d", block.length()); + + qint64 val = socket.write(block); + QVERIFY(val == -1); + + socket.disconnectFromService(); + + //Now data has been sent,check the if existing error + QVERIFY(errorSpy.isEmpty()); + } +class ReadyReadSlot : public QObject +{ + Q_OBJECT +public: + ReadyReadSlot(QLlcpSocket& s): m_socket(s),m_signalCount(0) + { + connect(&m_socket,SIGNAL(readyRead()),this,SLOT(gotReadyRead())); + } +private slots: + void gotReadyRead() + { + m_signalCount++; + qDebug()<<"Got ReadyRead() signal number = "<<m_signalCount; + const int Timeout = 50;//3* 1000 seems too long, nfc server will panic spray signal + bool ret = m_socket.waitForReadyRead(Timeout); + if (!ret) + { + qDebug()<<"WaitForReadyRead() in slot of ReadyRead signal return false"; + } + else + { + qDebug()<<"WaitForReadyRead() in slot of ReadyRead signal return true"; + } + } +private: + QLlcpSocket& m_socket; + int m_signalCount; +}; +/*! + Description: Test WaitForReadyRead() in slot of + ReadyRead signal, make sure the signal will not + be emitted twice in the slot function. + CounterPart test: tst_QLlcpServer::newConnection() +*/ +void tst_qllcpsockettype2::waitReadyReadInSlot() +{ + QString message("waitReadyReadInSlot test"); + + QNfcTestUtil::ShowAutoMsg(message); + QLlcpSocket socket(this); + QSignalSpy connectedSpy(&socket, SIGNAL(connected())); + QSignalSpy errorSpy(&socket, SIGNAL(error(QLlcpSocket::SocketError))); + + QSignalSpy readyReadSpy(&socket, SIGNAL(readyRead())); + ReadyReadSlot slot(socket); + + QSignalSpy bytesWrittenSpy(&socket, SIGNAL(bytesWritten(qint64))); + + socket.connectToService(m_target, TestUri); + + QTRY_VERIFY(!connectedSpy.isEmpty()); + + QString echo; + for (int i = 0; i < 2000; i++) + echo.append((char)(i%26 + 'a')); + //Send data to server + QByteArray block; + QDataStream out(&block, QIODevice::WriteOnly); + out.setVersion(QDataStream::Qt_4_6); + out << (quint16)0; + out << echo; + + qDebug("Client-- write quint16 length = %d", sizeof(quint16)); + qDebug("Client-- write echo string = %s", qPrintable(echo)); + qDebug("Client-- write echo string length= %d", echo.length()); + qDebug("Client-- write data length = %d", block.length()); + out.device()->seek(0); + out << (quint16)(block.size() - sizeof(quint16)); + + qint64 val = socket.write(block); + QVERIFY( val == 0); + + QTRY_VERIFY(!bytesWrittenSpy.isEmpty()); + qint64 written = countBytesWritten(bytesWrittenSpy); + + qDebug()<<"bytesWritten signal return value = "<<written; + while (written < block.size()) + { + QSignalSpy bytesWrittenSpy(&socket, SIGNAL(bytesWritten(qint64))); + QTRY_VERIFY(!bytesWrittenSpy.isEmpty()); + qint64 w = countBytesWritten(bytesWrittenSpy); + qDebug()<<"got bytesWritten signal = "<<w; + written += w; + } + qDebug()<<"Overall bytesWritten = "<<written; + qDebug()<<"Overall block size = "<<block.size(); + QTRY_VERIFY(written == block.size()); + //Get the echoed data from server + QTRY_VERIFY(!readyReadSpy.isEmpty()); + quint16 blockSize = 0; + QDataStream in(&socket); + in.setVersion(QDataStream::Qt_4_6); + while (socket.bytesAvailable() < (int)sizeof(quint16)){ + QSignalSpy readyRead(&socket, SIGNAL(readyRead())); + QTRY_VERIFY(!readyRead.isEmpty()); + } + in >> blockSize; + qDebug() << "Client-- read blockSize=" << blockSize; + while (socket.bytesAvailable() < blockSize){ + QSignalSpy readyRead(&socket, SIGNAL(readyRead())); + QTRY_VERIFY(!readyRead.isEmpty()); + } + QString echoed; + in >> echoed; + + qDebug() << "Client-- read echoed string =" << echoed; + //test the echoed string is same as the original string + QVERIFY(echo == echoed); + + socket.disconnectFromService(); + + //Now data has been sent,check the if existing error + QVERIFY(errorSpy.isEmpty()); +} + +class BytesWrittenSlot : public QObject +{ + Q_OBJECT +public: + BytesWrittenSlot(QLlcpSocket* s): m_socket(s) + { + connect(m_socket,SIGNAL(bytesWritten(qint64)),this,SLOT(gotBytesWritten(qint64))); + } +private slots: + void gotBytesWritten(qint64 w) + { + qDebug()<<"In BytesWrittenSlot: Delete the socket when still alive..."; + delete m_socket; + } +private: + QLlcpSocket* m_socket; +}; +/*! + Description: Add a case to test delete the socket in the slot when the transmission is still alive. + CounterPart test: tst_QLlcpServer::negTestCase1() +*/ +void tst_qllcpsockettype2::deleteSocketWhenInUse() + { + QString message("deleteSocketWhenInUse test"); + + QNfcTestUtil::ShowAutoMsg(message); + QLlcpSocket* socket = new QLlcpSocket; + QSignalSpy connectedSpy(socket, SIGNAL(connected())); + QSignalSpy errorSpy(socket, SIGNAL(error(QLlcpSocket::SocketError))); + + BytesWrittenSlot slot(socket); + QSignalSpy bytesWrittenSpy(socket, SIGNAL(bytesWritten(qint64))); + + socket->connectToService(m_target, TestUri); + + QTRY_VERIFY(!connectedSpy.isEmpty()); + + QString echo; + for (int i = 0; i < 2000; i++) + echo.append((char)(i%26 + 'a')); + //Send data to server + QByteArray block; + QDataStream out(&block, QIODevice::WriteOnly); + out.setVersion(QDataStream::Qt_4_6); + out << (quint16)0; + out << echo; + + qDebug("Client-- write quint16 length = %d", sizeof(quint16)); + qDebug("Client-- write echo string = %s", qPrintable(echo)); + qDebug("Client-- write echo string length= %d", echo.length()); + qDebug("Client-- write data length = %d", block.length()); + out.device()->seek(0); + out << (quint16)(block.size() - sizeof(quint16)); + + qint64 val = socket->write(block); + QVERIFY( val == 0); + QTest::qWait(5 * 1000);//give some time to wait bytesWritten signal + QVERIFY(errorSpy.isEmpty()); + } +/*! + Description: Add a server in one device, then two + client socket in another device to connect the server at same time + CounterPart test: tst_QLlcpServer::multiConnection() +*/ +void tst_qllcpsockettype2::multiSocketToOneServer() + { + QString message("multiSocketToOneServer test"); + + QNfcTestUtil::ShowAutoMsg(message); + QLlcpSocket* socket1 = new QLlcpSocket; + QLlcpSocket* socket2 = new QLlcpSocket; + QSignalSpy connectedSpy1(socket1, SIGNAL(connected())); + QSignalSpy errorSpy1(socket1, SIGNAL(error(QLlcpSocket::SocketError))); + QSignalSpy readyReadSpy1(socket1, SIGNAL(readyRead())); + QSignalSpy bytesWrittenSpy1(socket1, SIGNAL(bytesWritten(qint64))); + + QSignalSpy connectedSpy2(socket2, SIGNAL(connected())); + QSignalSpy errorSpy2(socket2, SIGNAL(error(QLlcpSocket::SocketError))); + QSignalSpy readyReadSpy2(socket2, SIGNAL(readyRead())); + QSignalSpy bytesWrittenSpy2(socket2, SIGNAL(bytesWritten(qint64))); + + socket1->connectToService(m_target, TestUri); + socket2->connectToService(m_target, TestUri); + + //test connect when some socket still processing data + QLlcpSocket* socket3 = new QLlcpSocket; + + QTRY_VERIFY(!connectedSpy1.isEmpty() || !connectedSpy2.isEmpty()); + if (!connectedSpy1.isEmpty()) + { + qDebug() << "socket 1 connected"; + QString echo1 = "aaaaaaa"; + //Send data to server + QByteArray block; + QDataStream out(&block, QIODevice::WriteOnly); + out.setVersion(QDataStream::Qt_4_6); + out << (quint16)0; + out << echo1; + + qDebug("Client-- write quint16 length = %d", sizeof(quint16)); + qDebug("Client-- write echo string = %s", qPrintable(echo1)); + qDebug("Client-- write echo string length= %d", echo1.length()); + qDebug("Client-- write data length = %d", block.length()); + out.device()->seek(0); + out << (quint16)(block.size() - sizeof(quint16)); + + qint64 val = socket1->write(block); + QVERIFY( val == 0); + + QTRY_VERIFY(!bytesWrittenSpy1.isEmpty()); + qint64 written = countBytesWritten(bytesWrittenSpy1); + + socket3->connectToService(m_target, TestUri); + + qDebug()<<"bytesWritten signal return value = "<<written; + while (written < block.size()) + { + QSignalSpy bytesWrittenSpy(socket1, SIGNAL(bytesWritten(qint64))); + QTRY_VERIFY(!bytesWrittenSpy.isEmpty()); + qint64 w = countBytesWritten(bytesWrittenSpy); + qDebug()<<"got bytesWritten signal = "<<w; + written += w; + } + qDebug()<<"Overall bytesWritten = "<<written; + qDebug()<<"Overall block size = "<<block.size(); + QTRY_VERIFY(written == block.size()); + //Get the echoed data from server + QTRY_VERIFY(!readyReadSpy1.isEmpty()); + quint16 blockSize = 0; + QDataStream in(socket1); + in.setVersion(QDataStream::Qt_4_6); + while (socket1->bytesAvailable() < (int)sizeof(quint16)){ + QSignalSpy readyRead(socket1, SIGNAL(readyRead())); + QTRY_VERIFY(!readyRead.isEmpty()); + } + in >> blockSize; + qDebug() << "Client-- read blockSize=" << blockSize; + while (socket1->bytesAvailable() < blockSize){ + QSignalSpy readyRead(socket1, SIGNAL(readyRead())); + QTRY_VERIFY(!readyRead.isEmpty()); + } + QString echoed; + in >> echoed; + + qDebug() << "Client-- read echoed string =" << echoed; + //test the echoed string is same as the original string + QCOMPARE(echo1, echoed); + + // + //try to handle the socket2 + // + QTRY_VERIFY(!connectedSpy2.isEmpty()); + qDebug() << "socket 2 connected"; + QString echo2 = "bbbbbbb"; + //Send data to server + QByteArray block2; + QDataStream out2(&block2, QIODevice::WriteOnly); + out2.setVersion(QDataStream::Qt_4_6); + out2 << (quint16)0; + out2 << echo2; + + qDebug("Client-- write quint16 length = %d", sizeof(quint16)); + qDebug("Client-- write echo string = %s", qPrintable(echo2)); + qDebug("Client-- write echo string length= %d", echo2.length()); + qDebug("Client-- write data length = %d", block2.length()); + out2.device()->seek(0); + out2 << (quint16)(block2.size() - sizeof(quint16)); + + qint64 val2 = socket2->write(block2); + QVERIFY( val2 == 0); + + QTRY_VERIFY(!bytesWrittenSpy2.isEmpty()); + qint64 written2 = countBytesWritten(bytesWrittenSpy2); + + qDebug()<<"bytesWritten signal return value = "<<written2; + while (written2 < block2.size()) + { + QSignalSpy bytesWrittenSpy(socket2, SIGNAL(bytesWritten(qint64))); + QTRY_VERIFY(!bytesWrittenSpy.isEmpty()); + qint64 w = countBytesWritten(bytesWrittenSpy); + qDebug()<<"got bytesWritten signal = "<<w; + written2 += w; + } + qDebug()<<"Overall bytesWritten = "<<written2; + qDebug()<<"Overall block size = "<<block2.size(); + QTRY_VERIFY(written2 == block2.size()); + //Get the echoed data from server + QTRY_VERIFY(!readyReadSpy2.isEmpty()); + quint16 blockSize2 = 0; + QDataStream in2(socket2); + in2.setVersion(QDataStream::Qt_4_6); + while (socket2->bytesAvailable() < (int)sizeof(quint16)){ + QSignalSpy readyRead(socket2, SIGNAL(readyRead())); + QTRY_VERIFY(!readyRead.isEmpty()); + } + in2 >> blockSize2; + qDebug() << "Client-- read blockSize=" << blockSize2; + while (socket2->bytesAvailable() < blockSize2){ + QSignalSpy readyRead(socket2, SIGNAL(readyRead())); + QTRY_VERIFY(!readyRead.isEmpty()); + } + QString echoed2; + in2 >> echoed2; + + qDebug() << "Client-- read echoed string =" << echoed; + //test the echoed string is same as the original string + QCOMPARE(echo2, echoed2); + } + else + { + + qDebug() << "socket 2 connected"; + QString echo2 = "bbbbbbb"; + //Send data to server + QByteArray block2; + QDataStream out2(&block2, QIODevice::WriteOnly); + out2.setVersion(QDataStream::Qt_4_6); + out2 << (quint16)0; + out2 << echo2; + + qDebug("Client-- write quint16 length = %d", sizeof(quint16)); + qDebug("Client-- write echo string = %s", qPrintable(echo2)); + qDebug("Client-- write echo string length= %d", echo2.length()); + qDebug("Client-- write data length = %d", block2.length()); + out2.device()->seek(0); + out2 << (quint16)(block2.size() - sizeof(quint16)); + + qint64 val2 = socket2->write(block2); + QVERIFY( val2 == 0); + + QTRY_VERIFY(!bytesWrittenSpy2.isEmpty()); + qint64 written2 = countBytesWritten(bytesWrittenSpy2); + + socket3->connectToService(m_target, TestUri); + + qDebug()<<"bytesWritten signal return value = "<<written2; + while (written2 < block2.size()) + { + QSignalSpy bytesWrittenSpy(socket2, SIGNAL(bytesWritten(qint64))); + QTRY_VERIFY(!bytesWrittenSpy.isEmpty()); + qint64 w = countBytesWritten(bytesWrittenSpy); + qDebug()<<"got bytesWritten signal = "<<w; + written2 += w; + } + qDebug()<<"Overall bytesWritten = "<<written2; + qDebug()<<"Overall block size = "<<block2.size(); + QTRY_VERIFY(written2 == block2.size()); + //Get the echoed data from server + QTRY_VERIFY(!readyReadSpy2.isEmpty()); + quint16 blockSize2 = 0; + QDataStream in2(socket2); + in2.setVersion(QDataStream::Qt_4_6); + while (socket2->bytesAvailable() < (int)sizeof(quint16)){ + QSignalSpy readyRead(socket2, SIGNAL(readyRead())); + QTRY_VERIFY(!readyRead.isEmpty()); + } + in2 >> blockSize2; + qDebug() << "Client-- read blockSize=" << blockSize2; + while (socket2->bytesAvailable() < blockSize2){ + QSignalSpy readyRead(socket2, SIGNAL(readyRead())); + QTRY_VERIFY(!readyRead.isEmpty()); + } + QString echoed2; + in2 >> echoed2; + + qDebug() << "Client-- read echoed string =" << echoed2; + //test the echoed string is same as the original string + QCOMPARE(echo2, echoed2); + + // + //try to handle the socket1 + // + QTRY_VERIFY(!connectedSpy1.isEmpty()); + qDebug() << "socket 1 connected"; + QString echo1 = "aaaaaaa"; + //Send data to server + QByteArray block; + QDataStream out(&block, QIODevice::WriteOnly); + out.setVersion(QDataStream::Qt_4_6); + out << (quint16)0; + out << echo1; + + qDebug("Client-- write quint16 length = %d", sizeof(quint16)); + qDebug("Client-- write echo string = %s", qPrintable(echo1)); + qDebug("Client-- write echo string length= %d", echo1.length()); + qDebug("Client-- write data length = %d", block.length()); + out.device()->seek(0); + out << (quint16)(block.size() - sizeof(quint16)); + + qint64 val = socket1->write(block); + QVERIFY( val == 0); + + QTRY_VERIFY(!bytesWrittenSpy1.isEmpty()); + qint64 written = countBytesWritten(bytesWrittenSpy1); + + qDebug()<<"bytesWritten signal return value = "<<written; + while (written < block.size()) + { + QSignalSpy bytesWrittenSpy(socket1, SIGNAL(bytesWritten(qint64))); + QTRY_VERIFY(!bytesWrittenSpy.isEmpty()); + qint64 w = countBytesWritten(bytesWrittenSpy); + qDebug()<<"got bytesWritten signal = "<<w; + written += w; + } + qDebug()<<"Overall bytesWritten = "<<written; + qDebug()<<"Overall block size = "<<block.size(); + QTRY_VERIFY(written == block.size()); + //Get the echoed data from server + QTRY_VERIFY(!readyReadSpy1.isEmpty()); + quint16 blockSize = 0; + QDataStream in(socket1); + in.setVersion(QDataStream::Qt_4_6); + while (socket1->bytesAvailable() < (int)sizeof(quint16)){ + QSignalSpy readyRead(socket1, SIGNAL(readyRead())); + QTRY_VERIFY(!readyRead.isEmpty()); + } + in >> blockSize; + qDebug() << "Client-- read blockSize=" << blockSize; + while (socket1->bytesAvailable() < blockSize){ + QSignalSpy readyRead(socket1, SIGNAL(readyRead())); + QTRY_VERIFY(!readyRead.isEmpty()); + } + QString echoed; + in >> echoed; + + qDebug() << "Client-- read echoed string =" << echoed; + //test the echoed string is same as the original string + QCOMPARE(echo1, echoed); + + } + QVERIFY(errorSpy1.isEmpty()); + QVERIFY(errorSpy2.isEmpty()); + delete socket1; + delete socket2; + delete socket3; + } +QTEST_MAIN(tst_qllcpsockettype2); + +#include "tst_qllcpsockettype2.moc" diff --git a/tests/nfcsymbianbackend/qnearfieldmanager/qnearfieldmanager.pro b/tests/nfcsymbianbackend/qnearfieldmanager/qnearfieldmanager.pro new file mode 100644 index 00000000..8efb8110 --- /dev/null +++ b/tests/nfcsymbianbackend/qnearfieldmanager/qnearfieldmanager.pro @@ -0,0 +1,25 @@ +QT += testlib + +TARGET = tst_qnearfieldmanager +CONFIG += console +CONFIG -= app_bundle +CONFIG += testcase + +TEMPLATE = app + +INCLUDEPATH += ../../../src/nfc +DEPENDPATH += ../../../src/nfc + +INCLUDEPATH += ../common +DEPENDPATH += ../common + +HEADERS += ../common/qautomsgbox.h +SOURCES += tst_qnearfieldmanager.cpp \ + ../common/qautomsgbox.cpp + +INCLUDEPATH += ../../../src/global +DEPENDPATH += ../../../src/global + +QMAKE_LIBDIR += $$QT_MOBILITY_BUILD_TREE/lib + +symbian:TARGET.CAPABILITY = ALL -TCB diff --git a/tests/nfcsymbianbackend/qnearfieldmanager/tst_qnearfieldmanager.cpp b/tests/nfcsymbianbackend/qnearfieldmanager/tst_qnearfieldmanager.cpp new file mode 100644 index 00000000..6fae1f38 --- /dev/null +++ b/tests/nfcsymbianbackend/qnearfieldmanager/tst_qnearfieldmanager.cpp @@ -0,0 +1,326 @@ +/**************************************************************************** +** +** 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 <QtCore/QString> +#include <QtTest/QtTest> +#include <QtCore/QCoreApplication> + +#include "qnfctestcommon.h" +#include "qnfctestutil.h" + +#include <qnearfieldmanager.h> +#include <qnearfieldtarget.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) + +class tst_QNearFieldManager : public QObject +{ + Q_OBJECT + +public: + tst_QNearFieldManager(); + +private Q_SLOTS: + void initTestCase(); + void cleanupTestCase(); + void targetDetected(); + void targetDetected_data(); + void unregisterNdefMessageHandler(); + void registerNdefMessageHandler(); + void registerNdefMessageHandler_filter_data(); + void registerNdefMessageHandler_filter(); + void registerNdefMessageHandler_filter_negtive(); + void registerNdefMessageHandler_filter_negtive_data(); +}; + +tst_QNearFieldManager::tst_QNearFieldManager() +{ + qRegisterMetaType<QNdefMessage>("QNdefMessage"); + qRegisterMetaType<QNearFieldTarget *>("QNearFieldTarget*"); +} + +void tst_QNearFieldManager::initTestCase() +{ + qRegisterMetaType<QNearFieldTarget *>("QNearFieldTarget *"); +} + +void tst_QNearFieldManager::cleanupTestCase() +{ +} + +/*! + Description: Unit test for NFC target detected and lost + + TestScenario: 1. Touch and remove llcp device/Type1/Type2/Type3/Type4 tag one by one + + TestExpectedResults: 1. llcp device/Type1/Type2/Type3/Type4 tag detected/lost signal can be received +*/ + +void tst_QNearFieldManager::targetDetected() +{ + QFETCH(QNearFieldTarget::Type, type); + QFETCH(QString, hint); + + QNearFieldManager nfcManager; + + QSignalSpy targetDetectedSpy(&nfcManager, SIGNAL(targetDetected(QNearFieldTarget*))); + QSignalSpy targetLostSpy(&nfcManager, SIGNAL(targetLost(QNearFieldTarget*))); + + nfcManager.startTargetDetection(type); + + QNfcTestUtil::ShowAutoMsg(hint, &targetDetectedSpy, 1); + QTRY_VERIFY(!targetDetectedSpy.isEmpty()); + + QNearFieldTarget *target = targetDetectedSpy.at(targetDetectedSpy.count()-1).at(0).value<QNearFieldTarget *>(); + + QSignalSpy disconnectedSpy(target, SIGNAL(disconnected())); + QVERIFY(target); + + if (type != QNearFieldTarget::NfcForumDevice) + { + QVERIFY(!target->uid().isEmpty()); + QCOMPARE(target->type(), type); + } + + QNfcTestUtil::ShowAutoMsg("please remove the target", &disconnectedSpy, 1); + QTRY_VERIFY(!targetLostSpy.isEmpty()); + + QNearFieldTarget *lostTarget = targetLostSpy.first().at(0).value<QNearFieldTarget *>(); + + QCOMPARE(target, lostTarget); + + QVERIFY(!disconnectedSpy.isEmpty()); + + nfcManager.stopTargetDetection(); +} + +void tst_QNearFieldManager::targetDetected_data() +{ + QTest::addColumn<QNearFieldTarget::Type>("type"); + QTest::addColumn<QString>("hint"); + QTest::newRow("llcp device") << QNearFieldTarget::NfcForumDevice << "Please touch llcp device"; + QTest::newRow("NfcTagType1") << QNearFieldTarget::NfcTagType1 << "Please touch tag type1"; + QTest::newRow("NfcTagType2") << QNearFieldTarget::NfcTagType2 << "Please touch tag type2"; + QTest::newRow("NfcTagType3") << QNearFieldTarget::NfcTagType3 << "Please touch tag type3"; + QTest::newRow("NfcTagType4") << QNearFieldTarget::NfcTagType4 << "Please touch tag type4"; +} + +/*! + Description: Unit test for NFC unregisterNdefMessageHandler function + + TestScenario: 1. + + TestExpectedResults: 1. return false +*/ + +void tst_QNearFieldManager::unregisterNdefMessageHandler() +{ + QNearFieldManager manager; + + QVERIFY(!manager.unregisterNdefMessageHandler(-1)); + QVERIFY(!manager.unregisterNdefMessageHandler(0)); +} + +class MessageListener : public QObject +{ + Q_OBJECT + +signals: + void matchedNdefMessage(const QNdefMessage &message, QNearFieldTarget *target); +}; + +/*! + Description: Unit test for NFC registerNdefMessageHandler function + + TestScenario: 1. Symbian backend does not support registerNdefMessageHandler without a QNdefFilter + + TestExpectedResults: 1. return -1 +*/ +void tst_QNearFieldManager::registerNdefMessageHandler() +{ + QNearFieldManager manager; + + MessageListener listener; + QSignalSpy messageSpy(&listener, SIGNAL(matchedNdefMessage(QNdefMessage,QNearFieldTarget*))); + + int id = manager.registerNdefMessageHandler(&listener, + SIGNAL(matchedNdefMessage(QNdefMessage,QNearFieldTarget*))); + + QVERIFY(id == -1);//symbian backend does not support registerNdefMessageHandler without QNdefFilter +} + +void tst_QNearFieldManager::registerNdefMessageHandler_filter_data() +{ + QTest::addColumn<QNdefFilter>("filter"); + QTest::addColumn<QString>("hint"); + + QNdefFilter filter; + + filter.appendRecord(QNdefRecord::NfcRtd, "Sp"); + QTest::newRow("SP") << filter << "Please touch a tag with 'SP' NDef message"; + + filter.clear(); + filter.setOrderMatch(true); + filter.appendRecord<QNdefNfcTextRecord>(1, 1); + filter.appendRecord<QNdefNfcUriRecord>(1, 1); + QTest::newRow("Text + URI") << filter << "Please touch a tag with 'Text + URI' NDef message"; + + filter.clear(); + filter.appendRecord<QNdefNfcUriRecord>(1, 1); + QTest::newRow("URI") << filter << "Please touch a tag with 'URI' NDef message"; + + filter.clear(); + filter.setOrderMatch(true); + filter.appendRecord<QNdefNfcUriRecord>(1, 1); + QTest::newRow("URI") << filter << "Please touch a tag with only one 'URI' NDef record"; + +} + +/*! + Description: Unit test for NFC registerNdefMessageHandler with a NDef filter + + TestScenario: 1. Touch a tag with random NDef message/with 'Image + Multiple Text + URI' NDef message/with 'Text + URI' NDef message + + TestExpectedResults: 1. matchedNdefMessage signal will be emitted +*/ +void tst_QNearFieldManager::registerNdefMessageHandler_filter() +{ + QFETCH(QNdefFilter, filter); + QFETCH(QString, hint); + + QNearFieldManager manager; + + MessageListener listener; + QSignalSpy messageSpy(&listener, SIGNAL(matchedNdefMessage(QNdefMessage,QNearFieldTarget*))); + + int id = manager.registerNdefMessageHandler(filter, &listener, + SIGNAL(matchedNdefMessage(QNdefMessage,QNearFieldTarget*))); + + QVERIFY(id != -1); + + QNfcTestUtil::ShowAutoMsg(hint, &messageSpy, 1); + + QTRY_VERIFY(!messageSpy.isEmpty()); + + const QNdefMessage message = messageSpy.first().at(0).value<QNdefMessage>(); + + QNearFieldTarget *target = messageSpy.first().at(1).value<QNearFieldTarget *>(); + + QVERIFY(target == NULL);//symbain backend always return NULL target + QCOMPARE(filter.recordCount(), message.count()); + qDebug()<<"message.count()="<<message.count(); + for (int i = 0; i < filter.recordCount(); ++i) + { + if (filter.orderMatch()) + { + QCOMPARE(filter.recordAt(i).typeNameFormat, message.at(i).typeNameFormat()); + QCOMPARE(filter.recordAt(i).type, message.at(i).type()); + } + else + { + bool matched = false; + for (int j = 0; j < filter.recordCount(); ++j) + { + if (message.at(i).typeNameFormat() == filter.recordAt(i).typeNameFormat && message.at(i).type() == filter.recordAt(i).type) + { + matched = true; + break; + } + } + QVERIFY(matched); + } + } + + QVERIFY(manager.unregisterNdefMessageHandler(id)); +} + +void tst_QNearFieldManager::registerNdefMessageHandler_filter_negtive_data() +{ + QTest::addColumn<QNdefFilter>("filter"); + QTest::addColumn<QString>("hint"); + //negtive test + QNdefFilter filter; + + QTest::newRow("Empty") << filter << "Please touch a tag without NDef message"; + + filter.clear(); + filter.appendRecord<QNdefNfcUriRecord>(1, 1); + QTest::newRow("URI") << filter << "Please touch a tag without 'URI' NDef message"; + +} + +/*! + Description: Unit test for NFC registerNdefMessageHandler with a NDef filter + + TestScenario: 1. Touch a tag without filter expected NDef message + + TestExpectedResults: 1. matchedNdefMessage signal will NOT be emitted +*/ +void tst_QNearFieldManager::registerNdefMessageHandler_filter_negtive() +{ + QFETCH(QNdefFilter, filter); + QFETCH(QString, hint); + + QNearFieldManager manager; + + MessageListener listener; + QSignalSpy messageSpy(&listener, SIGNAL(matchedNdefMessage(QNdefMessage,QNearFieldTarget*))); + + int id = manager.registerNdefMessageHandler(filter, &listener, + SIGNAL(matchedNdefMessage(QNdefMessage,QNearFieldTarget*))); + + QVERIFY(id != -1); + + QNfcTestUtil::ShowAutoMsg(hint); + + QTRY_VERIFY(messageSpy.isEmpty()); + QVERIFY(manager.unregisterNdefMessageHandler(id)); +} + +QTEST_MAIN(tst_QNearFieldManager); + +#include "tst_qnearfieldmanager.moc" diff --git a/tests/nfcsymbianbackend/qnearfieldtagtype1/qnearfieldtagtype1.pro b/tests/nfcsymbianbackend/qnearfieldtagtype1/qnearfieldtagtype1.pro new file mode 100644 index 00000000..5f136db1 --- /dev/null +++ b/tests/nfcsymbianbackend/qnearfieldtagtype1/qnearfieldtagtype1.pro @@ -0,0 +1,31 @@ +QT += testlib + +TARGET = tst_qnearfieldtagtype1 +CONFIG += console +CONFIG -= app_bundle +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/qnfctagtestcommon.h \ + ../common/qdummyslot.h \ + ../common/qautomsgbox.h \ + ../common/qnfctagutil.h + +SOURCES += tst_qnearfieldtagtype1.cpp \ + ../common/qdummyslot.cpp \ + ../common/qautomsgbox.cpp \ + ../common/qnfctagutil.cpp + + +symbian:TARGET.CAPABILITY = LocalServices diff --git a/tests/nfcsymbianbackend/qnearfieldtagtype1/tst_qnearfieldtagtype1.cpp b/tests/nfcsymbianbackend/qnearfieldtagtype1/tst_qnearfieldtagtype1.cpp new file mode 100644 index 00000000..962adf07 --- /dev/null +++ b/tests/nfcsymbianbackend/qnearfieldtagtype1/tst_qnearfieldtagtype1.cpp @@ -0,0 +1,537 @@ +/**************************************************************************** +** +** 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 <QtCore/QString> +#include <QtTest/QtTest> +#include <QtCore/QCoreApplication> +#include <QVariant> +#include <QVariantList> +#include "qnfctagtestcommon.h" +#include <qnearfieldtagtype1.h> +#include "qnfctestcommon.h" + +class NfcTagRawCommandOperationType1 : public NfcTagRawCommandOperationCommon +{ +public: + NfcTagRawCommandOperationType1(QNearFieldTarget * tag); + + void setReadAllOp() { readAll = &QNearFieldTagType1::readAll; } + void setReadIdOp() { readIdentification = &QNearFieldTagType1::readIdentification; } + void setReadByteOp(quint8 addr) { mAddr = addr; readByte = &QNearFieldTagType1::readByte; } + void setWriteByteOp(quint8 addr, quint8 data, QNearFieldTagType1::WriteMode mode) + { + mAddr = addr; + mData = data; + mMode = mode; + writeByte = &QNearFieldTagType1::writeByte; + } + void setReadSegment(quint8 addr) { mAddr = addr; readSegment = &QNearFieldTagType1::readSegment; } + void setReadBlock(quint8 addr) { mAddr = addr; readBlock = &QNearFieldTagType1::readBlock; } + void setWriteBlock(quint8 addr, const QByteArray & data, QNearFieldTagType1::WriteMode mode) + { + mAddr = addr; + mDataArray = data; + mMode = mode; + writeBlock = &QNearFieldTagType1::writeBlock; + } + + void run() + { + if (readAll) + { + mId = (tagType1->*readAll)(); + } + + if (readIdentification) + { + mId = (tagType1->*readIdentification)(); + } + + if (readByte) + { + mId = (tagType1->*readByte)(mAddr); + } + + if (writeByte) + { + mId = (tagType1->*writeByte)(mAddr, mData, mMode); + } + + if (readBlock) + { + mId = (tagType1->*readBlock)(mAddr); + } + + if (writeBlock) + { + mId = (tagType1->*writeBlock)(mAddr, mDataArray, mMode); + } + + if (readSegment) + { + mId = (tagType1->*readSegment)(mAddr); + } + checkInvalidId(); + waitRequest(); + } + +protected: + QNearFieldTagType1 * tagType1; + QNearFieldTarget::RequestId (QNearFieldTagType1::*readAll)(); + QNearFieldTarget::RequestId (QNearFieldTagType1::*readIdentification)(); + + QNearFieldTarget::RequestId (QNearFieldTagType1::*readByte)(quint8 address); + QNearFieldTarget::RequestId (QNearFieldTagType1::*writeByte)(quint8 address, quint8 data, QNearFieldTagType1::WriteMode mode); + + // dynamic memory functions + QNearFieldTarget::RequestId (QNearFieldTagType1::*readSegment)(quint8 segmentAddress); + QNearFieldTarget::RequestId (QNearFieldTagType1::*readBlock)(quint8 blockAddress); + QNearFieldTarget::RequestId (QNearFieldTagType1::*writeBlock)(quint8 blockAddress, const QByteArray &data, + QNearFieldTagType1::WriteMode mode); + quint8 mAddr; + quint8 mData; + QByteArray mDataArray; + QNearFieldTagType1::WriteMode mMode; +}; + +NfcTagRawCommandOperationType1::NfcTagRawCommandOperationType1(QNearFieldTarget * tag):NfcTagRawCommandOperationCommon(tag) +{ + tagType1 = qobject_cast<QNearFieldTagType1 *>(mTarget); + QVERIFY(tagType1); + readAll = 0; + readIdentification = 0; + readByte = 0; + writeByte = 0; + readSegment = 0; + readBlock = 0; + writeBlock = 0; +} + +class tst_qnearfieldtagtype1 : public QObject +{ + Q_OBJECT + +public: + tst_qnearfieldtagtype1(); + void _testRawAccessAndNdefAccess(const QList<QNdefMessage> &messages); + +private Q_SLOTS: + void initTestCase(); + void testRawAndNdefAccess(); + void testSequence(); + void testWaitInSlot(); + void testDeleteOperationBeforeAsyncRequestComplete(); + void testRemoveTagBeforeAsyncRequestComplete(); + void testCancelNdefOperation(); + void cleanupTestCase(); +private: + QNfcTagTestCommon<QNearFieldTagType1> tester; +}; + + +tst_qnearfieldtagtype1::tst_qnearfieldtagtype1() +{ +} + +void tst_qnearfieldtagtype1::initTestCase() +{ +} + +void tst_qnearfieldtagtype1::cleanupTestCase() +{ +} + +void tst_qnearfieldtagtype1::testSequence() +{ + tester.touchTarget(" dynamic "); + QByteArray uid = tester.target->uid(); + QVERIFY(!uid.isEmpty()); + +//////////////////////////////////////////////////////////////////////////////////////////////// + qDebug()<<"========== Test readSeg, writeBlock, async and sync mix =========="; + OperationList rawCommandList; + const char data[] = {0,1,2,3,4,5,6,7}; + QByteArray blockData; + blockData.append(data, sizeof(data)); + QByteArray segmentData; + + for (int i = 0x10; i <= 0x1F; ++i) + { + NfcTagRawCommandOperationType1 * op1 = new NfcTagRawCommandOperationType1(tester.target); + op1->setWriteBlock(i, blockData, QNearFieldTagType1::EraseAndWrite); + op1->setExpectedOkSignal(); + op1->setExpectedResponse(QVariant(true)); + + if (i == 0x15) + { + op1->setWaitOperation(NfcTagRawCommandOperationCommon::EWaitTrue); + } + rawCommandList.append(op1); + segmentData.append(blockData); + } + + NfcTagRawCommandOperationType1 * op2 = new NfcTagRawCommandOperationType1(tester.target); + op2->setReadSegment(1); + op2->setExpectedOkSignal(); + op2->setWaitOperation(NfcTagRawCommandOperationCommon::EWaitTrue); + op2->setExpectedResponse(segmentData); + rawCommandList.append(op2); + + tester.testSequence(rawCommandList); + qDeleteAll(rawCommandList); + +////////////////////////////////////////////////////////////////////////////////////////////// + qDebug()<<"========== Test invalid readSeg, writeNE, writeBlockNE =========="; + rawCommandList.clear(); + NfcTagRawCommandOperationType1 * op6 = new NfcTagRawCommandOperationType1(tester.target); + op6->setReadSegment(0xf1); + op6->setIfExpectInvalidId(); + op6->setExpectedResponse(QVariant()); + rawCommandList.append(op6); + + NfcTagRawCommandOperationType1 * op3 = new NfcTagRawCommandOperationType1(tester.target); + op3->setWriteBlock(0x10, blockData, QNearFieldTagType1::WriteOnly); + op3->setExpectedOkSignal(); + op3->setExpectedResponse(QVariant(true)); + rawCommandList.append(op3); + + NfcTagRawCommandOperationType1 * op4 = new NfcTagRawCommandOperationType1(tester.target); + op4->setWriteByteOp(0x10, 0xff, QNearFieldTagType1::WriteOnly); + op4->setExpectedOkSignal(); + op4->setExpectedResponse(QVariant(true)); + rawCommandList.append(op4); + + QList<QByteArray> cmdList; + QByteArray command; + command.append(char(0x1a)); // WRITE-NE + command.append(char(0x10)); // Address + command.append(char(0x00)); // Data + command.append(uid.left(4)); // 4 bytes of UID + cmdList.append(command); + + command.clear(); + command.append(char(0xff)); // Invalid command + command.append(char(0xff)); + command.append(char(0xff)); + command.append(char(0xff)); + command.append(char(0xff)); + command.append(char(0xff)); + cmdList.append(command); + + QVariantList expectRsp; + expectRsp.push_back(QVariant(true)); + expectRsp.push_back(QVariant()); + + NfcTagSendCommandsCommon * op7 = new NfcTagSendCommandsCommon(tester.target); + op7->SetCommandLists(cmdList); + op7->setExpectedErrorSignal(QNearFieldTarget::InvalidParametersError); + op7->SetExpectedResponse(expectRsp); + op7->setWaitOperation(NfcTagRawCommandOperationCommon::EWaitFalse); + rawCommandList.append(op7); + + cmdList.clear(); + QByteArray command1; + command1.append(char(0x1a)); // WRITE-NE + command1.append(char(0x10)); // Address + command1.append(char(0x00)); // Data + command1.append(uid.left(4)); // 4 bytes of UID + cmdList.append(command1); + cmdList.append(command1); + + expectRsp.clear(); + expectRsp.push_back(QVariant(true)); + expectRsp.push_back(QVariant(true)); + + NfcTagSendCommandsCommon * op8 = new NfcTagSendCommandsCommon(tester.target); + op8->SetCommandLists(cmdList); + op8->setExpectedOkSignal(); + op8->SetExpectedResponse(expectRsp); + rawCommandList.append(op8); + + tester.testSequence(rawCommandList); + qDeleteAll(rawCommandList); + + tester.removeTarget(); +} + +void tst_qnearfieldtagtype1::testWaitInSlot() +{ + tester.touchTarget(" dynamic "); + + const char data[] = {0,1,2,3,4,5,6,7}; + QByteArray blockData; + blockData.append(data, sizeof(data)); + + NfcTagRawCommandOperationType1 * op1 = new NfcTagRawCommandOperationType1(tester.target); + op1->setWriteBlock(0x10, blockData, QNearFieldTagType1::EraseAndWrite); + op1->setExpectedOkSignal(); + op1->setExpectedResponse(QVariant(true)); + + NfcTagRawCommandOperationType1 * op2Wait = new NfcTagRawCommandOperationType1(tester.target); + op2Wait->setWriteBlock(0x11, blockData, QNearFieldTagType1::EraseAndWrite); + op2Wait->setExpectedOkSignal(); + op2Wait->setExpectedResponse(QVariant(true)); + op2Wait->setWaitOperation(NfcTagRawCommandOperationCommon::EWaitTrue); + + NfcTagRawCommandOperationType1 * op3 = new NfcTagRawCommandOperationType1(tester.target); + op3->setWriteBlock(0x12, blockData, QNearFieldTagType1::EraseAndWrite); + op3->setExpectedOkSignal(); + op3->setExpectedResponse(QVariant(true)); + + NfcTagRawCommandOperationType1 * op4WaitInSlot = new NfcTagRawCommandOperationType1(tester.target); + op4WaitInSlot->setWriteBlock(0x13, blockData, QNearFieldTagType1::EraseAndWrite); + op4WaitInSlot->setExpectedOkSignal(); + op4WaitInSlot->setExpectedResponse(QVariant(true)); + + tester.testWaitInSlot(op1, op2Wait, op3, op4WaitInSlot); + + delete op1; + delete op2Wait; + delete op3; + delete op4WaitInSlot; + + tester.removeTarget(); +} + +void tst_qnearfieldtagtype1::testDeleteOperationBeforeAsyncRequestComplete() +{ + tester.touchTarget(" dynamic "); + OperationList rawCommandList; + const char data[] = {0,1,2,3,4,5,6,7}; + QByteArray blockData; + blockData.append(data, sizeof(data)); + QByteArray segmentData; + + for (int i = 0x10; i <= 0x1F; ++i) + { + NfcTagRawCommandOperationType1 * op1 = new NfcTagRawCommandOperationType1(tester.target); + op1->setWriteBlock(i, blockData, QNearFieldTagType1::EraseAndWrite); + op1->setExpectedOkSignal(); + op1->setExpectedResponse(QVariant(true)); + + if (i == 0x15) + { + op1->setWaitOperation(NfcTagRawCommandOperationCommon::EWaitTrue); + } + rawCommandList.append(op1); + segmentData.append(blockData); + } + + NfcTagRawCommandOperationType1 * op2 = new NfcTagRawCommandOperationType1(tester.target); + op2->setReadSegment(1); + op2->setExpectedOkSignal(); + op2->setWaitOperation(NfcTagRawCommandOperationCommon::EWaitTrue); + op2->setExpectedResponse(segmentData); + rawCommandList.append(op2); + tester.testDeleteOperationBeforeAsyncRequestComplete(rawCommandList); + + qDeleteAll(rawCommandList); +} + +void tst_qnearfieldtagtype1::testRemoveTagBeforeAsyncRequestComplete() +{ + tester.touchTarget(" dynamic "); + OperationList rawCommandList; + const char data[] = {0,1,2,3,4,5,6,7}; + QByteArray blockData; + blockData.append(data, sizeof(data)); + QByteArray segmentData; + + for (int i = 0x10; i <= 0x1F; ++i) + { + NfcTagRawCommandOperationType1 * op1 = new NfcTagRawCommandOperationType1(tester.target); + op1->setWriteBlock(i, blockData, QNearFieldTagType1::EraseAndWrite); + op1->setExpectedOkSignal(); + op1->setExpectedResponse(QVariant(true)); + + rawCommandList.append(op1); + segmentData.append(blockData); + } + + NfcTagRawCommandOperationType1 * op2 = new NfcTagRawCommandOperationType1(tester.target); + op2->setReadSegment(1); + op2->setExpectedOkSignal(); + op2->setExpectedResponse(segmentData); + rawCommandList.append(op2); + + OperationList rawCommandList1; + + segmentData.clear(); + + for (int i = 0x10; i <= 0x1F; ++i) + { + NfcTagRawCommandOperationType1 * op1 = new NfcTagRawCommandOperationType1(tester.target); + op1->setWriteBlock(i, blockData, QNearFieldTagType1::EraseAndWrite); + op1->setExpectedOkSignal(); + op1->setExpectedResponse(QVariant(true)); + + rawCommandList1.append(op1); + segmentData.append(blockData); + } + + NfcTagRawCommandOperationType1 * op3 = new NfcTagRawCommandOperationType1(tester.target); + op3->setReadSegment(1); + op3->setExpectedOkSignal(); + op3->setWaitOperation(NfcTagRawCommandOperationCommon::EWaitFalse); + op3->setExpectedResponse(segmentData); + rawCommandList1.append(op3); + + tester.testRemoveTagBeforeAsyncRequestComplete(rawCommandList, rawCommandList1); + qDeleteAll(rawCommandList); + qDeleteAll(rawCommandList1); +} + +void tst_qnearfieldtagtype1::testCancelNdefOperation() +{ + tester.touchTarget(" static "); + tester.testCancelNdefOperation(); +} + +void tst_qnearfieldtagtype1::_testRawAccessAndNdefAccess(const QList<QNdefMessage> &messages) +{ + QSignalSpy okSpy(tester.target, SIGNAL(requestCompleted(const QNearFieldTarget::RequestId&))); + QSignalSpy errSpy(tester.target, SIGNAL(error(QNearFieldTarget::Error, const QNearFieldTarget::RequestId&))); + QSignalSpy ndefMessageReadSpy(tester.target, SIGNAL(ndefMessageRead(QNdefMessage))); + QSignalSpy ndefMessageWriteSpy(tester.target, SIGNAL(ndefMessagesWritten())); + + int okCount = 0; + int errCount = 0; + int ndefReadCount = 0; + int ndefWriteCount = 0; + qDebug()<<"okSpy.count()"<<okSpy.count(); + + // write ndef first + tester.target->writeNdefMessages(messages); + ++ndefWriteCount; + QTRY_COMPARE(ndefMessageWriteSpy.count(), ndefWriteCount); + qDebug()<<"okSpy.count()"<<okSpy.count(); + + // has Ndef message check + QVERIFY(tester.target->hasNdefMessage()); + qDebug()<<"okSpy.count()"<<okSpy.count(); + + QNearFieldTarget::RequestId id = tester.target->readAll(); + QVERIFY(tester.target->waitForRequestCompleted(id)); + QByteArray allBlocks = tester.target->requestResponse(id).toByteArray(); + ++okCount; + QCOMPARE(okSpy.count(), okCount); + + // Verify readByte + QNearFieldTarget::RequestId id1 = tester.target->readByte(0x08); + QVERIFY(tester.target->waitForRequestCompleted(id1)); + quint8 cc0 = tester.target->requestResponse(id1).value<quint8>(); + QCOMPARE(cc0, quint8(0xE1)); + ++okCount; + QCOMPARE(okSpy.count(), okCount); + + QNearFieldTarget::RequestId id2 = tester.target->readByte(0x0d); + QVERIFY(tester.target->waitForRequestCompleted(id2)); + quint8 len = tester.target->requestResponse(id2).value<quint8>(); + QCOMPARE(int(len), messages.at(0).toByteArray().count()); + ++okCount; + QCOMPARE(okSpy.count(), okCount); + + QCOMPARE(allBlocks.mid(16, len), messages.at(0).toByteArray()); + + // Write NDEF with raw command + QNdefMessage message; + QNdefNfcTextRecord textRecord; + textRecord.setText("nfc"); + + message.append(textRecord); + + QByteArray newNdefMessageContent = message.toByteArray(); + quint8 ndefMessageContentLen = newNdefMessageContent.count(); + + QNearFieldTarget::RequestId id3 = tester.target->writeByte(0x0d, ndefMessageContentLen); + QVERIFY(tester.target->waitForRequestCompleted(id3)); + QVERIFY(tester.target->requestResponse(id3).toBool()); + ++okCount; + QCOMPARE(okSpy.count(), okCount); + + quint8 block = 1; + quint8 byte = 6; + for (int i = 0; i < ndefMessageContentLen; ++i) + { + quint8 addr = (block & 0x0F); + addr <<= 3; + addr |= (byte & 0x07); + QNearFieldTarget::RequestId tempId = tester.target->writeByte(addr, newNdefMessageContent.at(i)); + QVERIFY(tester.target->waitForRequestCompleted(tempId)); + QVERIFY(tester.target->requestResponse(tempId).toBool()); + byte = (7 == byte) ? 0 : (byte+1); + block = (0 == byte) ? (block+1) : block; + ++okCount; + QCOMPARE(okSpy.count(), okCount); + } + + // read ndef with ndef access + tester.target->readNdefMessages(); + ++ndefReadCount; + QTRY_COMPARE(ndefMessageReadSpy.count(), ndefReadCount); + + const QNdefMessage& ndefMessage_new(ndefMessageReadSpy.first().at(0).value<QNdefMessage>()); + + QCOMPARE(newNdefMessageContent, ndefMessage_new.toByteArray()); + QCOMPARE(errSpy.count(), errCount); +} + +void tst_qnearfieldtagtype1::testRawAndNdefAccess() +{ + tester.touchTarget(" static "); + QByteArray uid = tester.target->uid(); + QVERIFY(!uid.isEmpty()); + + QNdefMessage message; + QNdefNfcUriRecord uriRecord; + uriRecord.setUri(QUrl("http://qt.nokia.com")); + message.append(uriRecord); + + QList<QNdefMessage> messages; + messages.append(message); + + _testRawAccessAndNdefAccess(messages); + tester.removeTarget(); +} + +QTEST_MAIN(tst_qnearfieldtagtype1); + +#include "tst_qnearfieldtagtype1.moc" diff --git a/tests/nfcsymbianbackend/qnearfieldtagtype2/qnearfieldtagtype2.pro b/tests/nfcsymbianbackend/qnearfieldtagtype2/qnearfieldtagtype2.pro new file mode 100644 index 00000000..2001993d --- /dev/null +++ b/tests/nfcsymbianbackend/qnearfieldtagtype2/qnearfieldtagtype2.pro @@ -0,0 +1,31 @@ +QT += testlib + +TARGET = tst_qnearfieldtagtype2 +CONFIG += console +CONFIG -= app_bundle +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/qnfctagtestcommon.h \ + ../common/qdummyslot.h \ + ../common/qautomsgbox.h \ + ../common/qnfctagutil.h + +SOURCES += tst_qnearfieldtagtype2.cpp \ + ../common/qdummyslot.cpp \ + ../common/qautomsgbox.cpp \ + ../common/qnfctagutil.cpp + +symbian:TARGET.CAPABILITY = LocalServices + diff --git a/tests/nfcsymbianbackend/qnearfieldtagtype2/tst_qnearfieldtagtype2.cpp b/tests/nfcsymbianbackend/qnearfieldtagtype2/tst_qnearfieldtagtype2.cpp new file mode 100644 index 00000000..7f8ada31 --- /dev/null +++ b/tests/nfcsymbianbackend/qnearfieldtagtype2/tst_qnearfieldtagtype2.cpp @@ -0,0 +1,303 @@ +/**************************************************************************** +** +** 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 <QtCore/QString> +#include <QtTest/QtTest> +#include <QtCore/QCoreApplication> +#include <QVariant> +#include <QVariantList> +#include "qnfctagtestcommon.h" +#include <qnearfieldtagtype2.h> +#include "qnfctestcommon.h" + +class NfcTagRawCommandOperationType2: public NfcTagRawCommandOperationCommon +{ +public: + NfcTagRawCommandOperationType2(QNearFieldTarget * tag); + + void run() + { + if (readBlock) + { + mId = (tagType2->*readBlock)(mAddr); + } + + if (writeBlock) + { + mId = (tagType2->*writeBlock)(mAddr, mDataArray); + } + + if (selectSector) + { + mId = (tagType2->*selectSector)(mSector); + } + checkInvalidId(); + waitRequest(); + } + + void setReadBlock(quint8 blockAddress) + { + mAddr = blockAddress; + readBlock = &QNearFieldTagType2::readBlock; + } + + void setWriteBlock(quint8 blockAddress, const QByteArray &data) + { + mAddr = blockAddress; + mDataArray = data; + writeBlock = &QNearFieldTagType2::writeBlock; + } + + void setSelectSector(quint8 sector) + { + mSector = sector; + selectSector = &QNearFieldTagType2::selectSector; + } + +protected: + QNearFieldTagType2 * tagType2; + QNearFieldTarget::RequestId (QNearFieldTagType2::*readBlock)(quint8 blockAddress); + QNearFieldTarget::RequestId (QNearFieldTagType2::*writeBlock)(quint8 blockAddress, const QByteArray &data); + QNearFieldTarget::RequestId (QNearFieldTagType2::*selectSector)(quint8 sector); + + quint8 mAddr; + quint8 mSector; + QByteArray mDataArray; +}; + +NfcTagRawCommandOperationType2::NfcTagRawCommandOperationType2(QNearFieldTarget * tag):NfcTagRawCommandOperationCommon(tag) +{ + tagType2 = qobject_cast<QNearFieldTagType2 *>(mTarget); + QVERIFY(tagType2); + readBlock = 0; + writeBlock = 0; + selectSector = 0; +} + +class tst_qnearfieldtagtype2: public QObject +{ + Q_OBJECT + +public: + tst_qnearfieldtagtype2(); + + void testRawAccessAndNdefAccess(const QList<QNdefMessage> &messages); + +private Q_SLOTS: + void initTestCase(); + void testRawAndNdefAccess(); + void testSequence(); + void cleanupTestCase(){} +private: + QNfcTagTestCommon<QNearFieldTagType2> tester; +}; + + +tst_qnearfieldtagtype2::tst_qnearfieldtagtype2() +{ +} + +void tst_qnearfieldtagtype2::initTestCase() +{ +} + +void tst_qnearfieldtagtype2::testSequence() +{ + tester.touchTarget(); + QByteArray uid = tester.target->uid(); + QVERIFY(!uid.isEmpty()); + + OperationList rawCommandList; + const char data[] = {0,1,2,3}; + QByteArray blockData; + blockData.append(data, sizeof(data)); + + for (int i = 4; i < 8; ++i) + { + NfcTagRawCommandOperationType2 * op1 = new NfcTagRawCommandOperationType2(tester.target); + op1->setWriteBlock(i, blockData); + op1->setExpectedOkSignal(); + op1->setExpectedResponse(QVariant(true)); + + if (i == 6) + { + op1->setWaitOperation(NfcTagRawCommandOperationCommon::EWaitTrue); + } + rawCommandList.append(op1); + } + + QList<QByteArray> cmdList; + QByteArray command; + command.append(char(0xff)); // Invalid command + command.append(char(0xff)); + command.append(char(0xff)); + command.append(char(0xff)); + command.append(char(0xff)); + command.append(char(0xff)); + cmdList.append(command); + cmdList.append(command); + + QVariantList expectRsp; + expectRsp.push_back(QVariant()); + expectRsp.push_back(QVariant()); + + NfcTagSendCommandsCommon * op7 = new NfcTagSendCommandsCommon(tester.target); + op7->SetCommandLists(cmdList); + op7->setExpectedErrorSignal(QNearFieldTarget::InvalidParametersError); + op7->SetExpectedResponse(expectRsp); + op7->setWaitOperation(NfcTagRawCommandOperationCommon::EWaitFalse); + rawCommandList.append(op7); + + tester.testSequence(rawCommandList); + qDeleteAll(rawCommandList); + + tester.removeTarget(); +} + +void tst_qnearfieldtagtype2::testRawAccessAndNdefAccess(const QList<QNdefMessage> &messages) +{ + QSignalSpy okSpy(tester.target, SIGNAL(requestCompleted(const QNearFieldTarget::RequestId&))); + QSignalSpy errSpy(tester.target, SIGNAL(error(QNearFieldTarget::Error, const QNearFieldTarget::RequestId&))); + QSignalSpy ndefMessageReadSpy(tester.target, SIGNAL(ndefMessageRead(QNdefMessage))); + QSignalSpy ndefMessageWriteSpy(tester.target, SIGNAL(ndefMessagesWritten())); + + int okCount = 0; + int errCount = 0; + int ndefReadCount = 0; + int ndefWriteCount = 0; + + // write ndef first + tester.target->writeNdefMessages(messages); + ++ndefWriteCount; + QTRY_COMPARE(ndefMessageWriteSpy.count(), ndefWriteCount); + + QNearFieldTarget::RequestId id = tester.target->readBlock(3); + QVERIFY(tester.target->waitForRequestCompleted(id, 50000)); + ++okCount; + QCOMPARE(okSpy.count(), okCount); + // check if NDEF existed + QByteArray cc = tester.target->requestResponse(id).toByteArray(); + QCOMPARE((char)(cc.at(0)), (char)0xE1); + + // try to find NDEF tlv + QByteArray blocks; + int NdefLen = -1; + for(int i = 4; i < 15; i+=4) + { + QNearFieldTarget::RequestId id1 = tester.target->readBlock(i); + QVERIFY(tester.target->waitForRequestCompleted(id1, 50000)); + QByteArray tlv = tester.target->requestResponse(id1).toByteArray(); + blocks.append(tlv); + ++okCount; + QCOMPARE(okSpy.count(), okCount); + } + + QByteArray ndefContent; + for (int i = 0; i < blocks.count(); ++i) + { + if ((blocks.at(i) == 0x03) && (i < blocks.count() - 1)) + { + // find ndef tlv + NdefLen = blocks.at(i+1); + qDebug()<<"NDefLen is "<<NdefLen; + ndefContent = blocks.mid(i+2, NdefLen); + break; + } + } + + QCOMPARE(ndefContent, messages.at(0).toByteArray()); + // update the ndef meesage with raw command + QNdefMessage message; + QNdefNfcTextRecord textRecord; + textRecord.setText("nfc"); + message.append(textRecord); + + QByteArray newNdefMessage = message.toByteArray(); + NdefLen = newNdefMessage.count(); + qDebug()<<"NDefLen is "<<NdefLen; + qDebug()<<"new Ndef len is "<<NdefLen; + newNdefMessage.push_front((char)NdefLen); + newNdefMessage.push_front((char)0x03); + + for(int i = 0; i < 16 - NdefLen; ++i) + { + // append padding + newNdefMessage.append((char)0); + } + + for(int i = 4; i < 8; ++i) + { + QNearFieldTarget::RequestId id2 = tester.target->writeBlock(i, newNdefMessage.left(4)); + QVERIFY(tester.target->waitForRequestCompleted(id2)); + ++okCount; + QCOMPARE(okSpy.count(), okCount); + newNdefMessage.remove(0,4); + } + + // read ndef with ndef access + tester.target->readNdefMessages(); + ++ndefReadCount; + QTRY_COMPARE(ndefMessageReadSpy.count(), ndefReadCount); + + const QNdefMessage& ndefMessage_new(ndefMessageReadSpy.first().at(0).value<QNdefMessage>()); + + QCOMPARE(message.toByteArray(), ndefMessage_new.toByteArray()); + QCOMPARE(errSpy.count(), errCount); +} + +void tst_qnearfieldtagtype2::testRawAndNdefAccess() +{ + tester.touchTarget(); + QNdefMessage message; + QNdefNfcUriRecord uriRecord; + uriRecord.setUri(QUrl("http://qt")); + message.append(uriRecord); + + QList<QNdefMessage> messages; + messages.append(message); + + testRawAccessAndNdefAccess(messages); + tester.removeTarget(); +} + +QTEST_MAIN(tst_qnearfieldtagtype2); + +#include "tst_qnearfieldtagtype2.moc" diff --git a/tests/nfcsymbianbackend/qnearfieldtagtype3/qnearfieldtagtype3.pro b/tests/nfcsymbianbackend/qnearfieldtagtype3/qnearfieldtagtype3.pro new file mode 100644 index 00000000..1a654dcc --- /dev/null +++ b/tests/nfcsymbianbackend/qnearfieldtagtype3/qnearfieldtagtype3.pro @@ -0,0 +1,32 @@ +QT += testlib + +TARGET = tst_qnearfieldtagtype3 +CONFIG += console +CONFIG -= app_bundle +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/qnfctagtestcommon.h \ + ../common/qdummyslot.h \ + ../common/qautomsgbox.h \ + ../common/qnfctagutil.h + +SOURCES += tst_qnearfieldtagtype3.cpp \ + ../common/qdummyslot.cpp \ + ../common/qautomsgbox.cpp \ + ../common/qnfctagutil.cpp + + +symbian:TARGET.CAPABILITY = LocalServices + diff --git a/tests/nfcsymbianbackend/qnearfieldtagtype3/tst_qnearfieldtagtype3.cpp b/tests/nfcsymbianbackend/qnearfieldtagtype3/tst_qnearfieldtagtype3.cpp new file mode 100644 index 00000000..36417c8c --- /dev/null +++ b/tests/nfcsymbianbackend/qnearfieldtagtype3/tst_qnearfieldtagtype3.cpp @@ -0,0 +1,295 @@ +/**************************************************************************** +** +** 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 <QtCore/QString> +#include <QtTest/QtTest> +#include <QtCore/QCoreApplication> +#include <QVariant> +#include <QVariantList> +#include "qnfctagtestcommon.h" +#include <qnearfieldtagtype3.h> +#include "qnfctestcommon.h" + +typedef QMap<quint16,QByteArray> checkResponseType; +Q_DECLARE_METATYPE(checkResponseType) + +class NfcTagRawCommandOperationType3: public NfcTagRawCommandOperationCommon +{ +public: + NfcTagRawCommandOperationType3(QNearFieldTarget * tag); + + void run() + { + if (check) + { + mId = (tagType3->*check)(mSerivceBlockList); + } + + if (update) + { + mId = (tagType3->*update)(mSerivceBlockList, mDataArray); + } + + checkInvalidId(); + waitRequest(); + } + + void setCheck(const QMap<quint16, QList<quint16> > &serviceBlockList) + { + check = &QNearFieldTagType3::check; + mSerivceBlockList = serviceBlockList; + } + + void setUpdate(const QMap<quint16, QList<quint16> > &serviceBlockList, + const QByteArray &data) + { + update = &QNearFieldTagType3::update; + mSerivceBlockList = serviceBlockList; + mDataArray = data; + } + + void checkResponse() + { + qDebug()<<"checkResponse begin"; + if (check) + { + // response is QMap<quint16, QByteArray> + checkResponseType e = mExpectedResult.value<checkResponseType>(); + checkResponseType r = mTarget->requestResponse(mId).value<checkResponseType>(); + QCOMPARE(e, r); + } + else + { + QTRY_COMPARE(mTarget->requestResponse(mId), mExpectedResult); + } + qDebug()<<"checkResponse end"; + } + +protected: + QNearFieldTagType3 * tagType3; + QNearFieldTarget::RequestId (QNearFieldTagType3::*check)(const QMap<quint16, QList<quint16> > &serviceBlockList); + QNearFieldTarget::RequestId (QNearFieldTagType3::*update)(const QMap<quint16, QList<quint16> > &serviceBlockList, + const QByteArray &data); + QMap<quint16, QList<quint16> > mSerivceBlockList; + QByteArray mDataArray; +}; + +NfcTagRawCommandOperationType3::NfcTagRawCommandOperationType3(QNearFieldTarget * tag):NfcTagRawCommandOperationCommon(tag) +{ + tagType3 = qobject_cast<QNearFieldTagType3 *>(mTarget); + QVERIFY(tagType3); + check = 0; + update = 0; +} + +class tst_qnearfieldtagtype3 : public QObject +{ + Q_OBJECT + +public: + tst_qnearfieldtagtype3(); + void testRawAccessAndNdefAccess(const QList<QNdefMessage> &messages); + +private Q_SLOTS: + void initTestCase(); + void testRawAndNdefAccess(); + void cleanupTestCase(){} +private: + QNfcTagTestCommon<QNearFieldTagType3> tester; +}; + + +tst_qnearfieldtagtype3::tst_qnearfieldtagtype3() +{ +} + +void tst_qnearfieldtagtype3::initTestCase() +{ + +} + +void tst_qnearfieldtagtype3::testRawAccessAndNdefAccess(const QList<QNdefMessage> &messages) +{ + QSignalSpy okSpy(tester.target, SIGNAL(requestCompleted(const QNearFieldTarget::RequestId&))); + QSignalSpy errSpy(tester.target, SIGNAL(error(QNearFieldTarget::Error, const QNearFieldTarget::RequestId&))); + QSignalSpy ndefMessageReadSpy(tester.target, SIGNAL(ndefMessageRead(QNdefMessage))); + QSignalSpy ndefMessageWriteSpy(tester.target, SIGNAL(ndefMessagesWritten())); + + int okCount = 0; + int errCount = 0; + int ndefReadCount = 0; + int ndefWriteCount = 0; + + // write ndef first + tester.target->writeNdefMessages(messages); + ++ndefWriteCount; + QTRY_COMPARE(ndefMessageWriteSpy.count(), ndefWriteCount); + + QList<quint16> blockList; + // first block + blockList.append(0); + // NDEF service + quint16 serviceCode = 0x0B; + + QMap<quint16, QList<quint16> > serviceBlockList; + serviceBlockList.insert(serviceCode, blockList); + + QNearFieldTarget::RequestId id = tester.target->check(serviceBlockList); + + QVERIFY(tester.target->waitForRequestCompleted(id)); + ++okCount; + QCOMPARE(okSpy.count(), okCount); + + QMap<quint16, QByteArray> result = tester.target->requestResponse(id).value<QMap<quint16, QByteArray> >(); + QVERIFY(result.contains(serviceCode)); + + const QByteArray& attribInfo = result.value(serviceCode); + QVERIFY(!attribInfo.isEmpty()); + + quint32 len = attribInfo.at(11); + len<<=8; + len |= attribInfo.at(12); + len<<=8; + len |= attribInfo.at(13); + + QCOMPARE(len, (quint32)(messages.at(0).toByteArray().count())); + + // read NDEF with RAW command + int Nbc = (0 == len%16)?(len/16):(len/16+1); + qDebug()<<"Nbc = "<<Nbc; + + serviceBlockList.clear(); + blockList.clear(); + for(int i = 1; i <= Nbc; ++i) + { + blockList.append(i); + } + serviceBlockList.insert(serviceCode, blockList); + + QNearFieldTarget::RequestId id1 = tester.target->check(serviceBlockList); + + QVERIFY(tester.target->waitForRequestCompleted(id1)); + ++okCount; + QCOMPARE(okSpy.count(), okCount); + + QMap<quint16, QByteArray> ndefContent = tester.target->requestResponse(id1).value<QMap<quint16, QByteArray> >(); + + QVERIFY(ndefContent.contains(serviceCode)); + QCOMPARE(ndefContent.value(serviceCode).left(len), messages.at(0).toByteArray()); + + // update the ndef meesage with raw command + QNdefMessage message; + QNdefNfcTextRecord textRecord; + textRecord.setText("nfc"); + message.append(textRecord); + + QByteArray expectedNdefContent = message.toByteArray(); + len = expectedNdefContent.count(); + serviceCode = 0x0009; + + // use previous attribute information block data, just update the len + QByteArray newAttribInfo = attribInfo; + newAttribInfo[13] = len&0xFF; + newAttribInfo[12] = (len>>8)&0xFF; + newAttribInfo[11] = (len>>16)&0xFF; + newAttribInfo[9] = 0x0F; + + QByteArray ndefData; + ndefData.append(newAttribInfo); + ndefData.append(expectedNdefContent); + + qDebug()<<"updated ndef len = "<<len; + + for (int i = 0; i < 16 - ndefData.count()%16; ++i) + { + // appending padding data + ndefData.append((char)0); + } + qDebug()<<"raw ndefData len = "<<ndefData.count(); + + QList<quint16> updatedBlockList; + + int blockNumber = (len%16 == 0)?len/16:(len/16+1); + qDebug()<<"updated block number = "<<blockNumber; + + for(int i = 0; i <= blockNumber; ++i) + { + updatedBlockList.append((char)i); + } + + qDebug()<<"updatedBlockList len = "<<updatedBlockList.count(); + serviceBlockList.clear(); + serviceBlockList.insert(serviceCode, updatedBlockList); + QNearFieldTarget::RequestId id2 = tester.target->update(serviceBlockList, ndefData); + QVERIFY(tester.target->waitForRequestCompleted(id2)); + QVERIFY(tester.target->requestResponse(id2).toBool()); + ++okCount; + QCOMPARE(okSpy.count(), okCount); + + // read ndef with ndef access + tester.target->readNdefMessages(); + ++ndefReadCount; + QTRY_COMPARE(ndefMessageReadSpy.count(), ndefReadCount); + + const QNdefMessage& ndefMessage_new(ndefMessageReadSpy.first().at(0).value<QNdefMessage>()); + + QCOMPARE(expectedNdefContent, ndefMessage_new.toByteArray()); + QCOMPARE(errSpy.count(), errCount); +} + + +void tst_qnearfieldtagtype3::testRawAndNdefAccess() +{ + tester.touchTarget(); + QNdefMessage message; + QNdefNfcUriRecord uriRecord; + uriRecord.setUri(QUrl("http://qt.nokia.com")); + message.append(uriRecord); + + QList<QNdefMessage> messages; + messages.append(message); + + testRawAccessAndNdefAccess(messages); + tester.removeTarget(); +} +QTEST_MAIN(tst_qnearfieldtagtype3); + +#include "tst_qnearfieldtagtype3.moc" diff --git a/tests/nfcsymbianbackend/qnearfieldtagtype4/qnearfieldtagtype4.pro b/tests/nfcsymbianbackend/qnearfieldtagtype4/qnearfieldtagtype4.pro new file mode 100644 index 00000000..8dab49e6 --- /dev/null +++ b/tests/nfcsymbianbackend/qnearfieldtagtype4/qnearfieldtagtype4.pro @@ -0,0 +1,32 @@ +QT += testlib + +TARGET = tst_qnearfieldtagtype4 +CONFIG += console +CONFIG -= app_bundle +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/qnfctagtestcommon.h \ + ../common/qdummyslot.h \ + ../common/qautomsgbox.h \ + ../common/qnfctagutil.h + +SOURCES += tst_qnearfieldtagtype4.cpp \ + ../common/qdummyslot.cpp \ + ../common/qautomsgbox.cpp \ + ../common/qnfctagutil.cpp + + +symbian:TARGET.CAPABILITY = LocalServices + diff --git a/tests/nfcsymbianbackend/qnearfieldtagtype4/tst_qnearfieldtagtype4.cpp b/tests/nfcsymbianbackend/qnearfieldtagtype4/tst_qnearfieldtagtype4.cpp new file mode 100644 index 00000000..49f46adb --- /dev/null +++ b/tests/nfcsymbianbackend/qnearfieldtagtype4/tst_qnearfieldtagtype4.cpp @@ -0,0 +1,326 @@ +/**************************************************************************** +** +** 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 <QtCore/QString> +#include <QtTest/QtTest> +#include <QtCore/QCoreApplication> +#include <QVariant> +#include <QVariantList> +#include <QtEndian> +#include <qnearfieldtagtype4.h> +#include "qnfctagtestcommon.h" +#include "qnfctestcommon.h" + +class NfcTagRawCommandOperationType4: public NfcTagRawCommandOperationCommon +{ +public: + NfcTagRawCommandOperationType4(QNearFieldTarget * tag); + + void run() + { + if (selectByName) + { + mId = (mTagType4->*selectByName)(mName); + } + + if (selectById) + { + mId = (mTagType4->*selectById)(mFileId); + } + + if (read) + { + mId = (mTagType4->*read)(mLength, mStartOffset); + } + + if (write) + { + mId = (mTagType4->*write)(mDataArray, mStartOffset); + } + checkInvalidId(); + waitRequest(); + } + + void setRead(quint16 length, quint16 startOffset) + { + mLength = length; + mStartOffset = startOffset; + read = &QNearFieldTagType4::read; + } + + void setWrite(const QByteArray &data, quint16 startOffset) + { + mDataArray = data; + mStartOffset = startOffset; + write = &QNearFieldTagType4::write; + } + + void setSelectByName(const QByteArray &name) + { + mName = name; + selectByName = &QNearFieldTagType4::select; + } + + void setSelectById(quint16 fileId) + { + mFileId = fileId; + selectById = &QNearFieldTagType4::select; + } + +protected: + QNearFieldTagType4 * mTagType4; + QNearFieldTarget::RequestId (QNearFieldTagType4::*selectByName)(const QByteArray &name); + QNearFieldTarget::RequestId (QNearFieldTagType4::*selectById)(quint16 fileIdentifier); + QNearFieldTarget::RequestId (QNearFieldTagType4::*write)(const QByteArray &data, quint16 startOffset); + QNearFieldTarget::RequestId (QNearFieldTagType4::*read)(quint16 length, quint16 startOffset); + + QByteArray mDataArray; + QByteArray mName; + quint16 mLength; + quint16 mFileId; + quint16 mStartOffset; +}; + +NfcTagRawCommandOperationType4::NfcTagRawCommandOperationType4(QNearFieldTarget * tag):NfcTagRawCommandOperationCommon(tag) +{ + mTagType4 = qobject_cast<QNearFieldTagType4 *>(mTarget); + QVERIFY(mTagType4); + selectByName = 0; + selectById = 0; + write = 0; + read = 0; +} + + +class tst_qnearfieldtagtype4 : public QObject +{ + Q_OBJECT + +public: + tst_qnearfieldtagtype4(); + void testRawAccessAndNdefAccess(const QList<QNdefMessage> &messages); + +private Q_SLOTS: + void initTestCase(); + void testRawAndNdefAccess(); + void cleanupTestCase(){} +private: + QNfcTagTestCommon<QNearFieldTagType4> mTester; +}; + + +tst_qnearfieldtagtype4::tst_qnearfieldtagtype4() +{ +} + +void tst_qnearfieldtagtype4::initTestCase() +{ +} + +void tst_qnearfieldtagtype4::testRawAccessAndNdefAccess(const QList<QNdefMessage> &messages) +{ + QSignalSpy okSpy(mTester.target, SIGNAL(requestCompleted(const QNearFieldTarget::RequestId&))); + QSignalSpy errSpy(mTester.target, SIGNAL(error(QNearFieldTarget::Error, const QNearFieldTarget::RequestId&))); + QSignalSpy ndefMessageReadSpy(mTester.target, SIGNAL(ndefMessageRead(QNdefMessage))); + QSignalSpy ndefMessageWriteSpy(mTester.target, SIGNAL(ndefMessagesWritten())); + + int okCount = 0; + int errCount = 0; + int ndefReadCount = 0; + int ndefWriteCount = 0; + + // write ndef first + mTester.target->writeNdefMessages(messages); + ++ndefWriteCount; + QTRY_COMPARE(ndefMessageWriteSpy.count(), ndefWriteCount); + + // has Ndef message check + QVERIFY(mTester.target->hasNdefMessage()); + + // read NDEF with RAW command + QByteArray resp; // correct response + resp.append(char(0x90)); + resp.append(char(0x00)); + + qDebug()<<"select NDEF application"; + QByteArray command; + command.append(char(0xD2)); + command.append(char(0x76)); + command.append(char(0x00)); + command.append(char(0x00)); + command.append(char(0x85)); + command.append(char(0x01)); + command.append(char(0x00)); + QNearFieldTarget::RequestId id = mTester.target->select(command); + QVERIFY(mTester.target->waitForRequestCompleted(id)); + ++okCount; + QCOMPARE(okSpy.count(), okCount); + QVERIFY(mTester.target->requestResponse(id).toBool()); + + qDebug()<<"select CC"; + QNearFieldTarget::RequestId id1 = mTester.target->select(0xe103); + QVERIFY(mTester.target->waitForRequestCompleted(id1)); + ++okCount; + QCOMPARE(okSpy.count(), okCount); + QVERIFY(mTester.target->requestResponse(id1).toBool()); + + qDebug()<<"read CC"; + QNearFieldTarget::RequestId id2 = mTester.target->read(0x000F,0x0000); + QVERIFY(mTester.target->waitForRequestCompleted(id2)); + ++okCount; + QCOMPARE(okSpy.count(), okCount); + QByteArray ccContent = mTester.target->requestResponse(id2).toByteArray(); + QCOMPARE(ccContent.right(2), resp); + QCOMPARE(ccContent.count(), int(17)); + QCOMPARE(ccContent.at(1), char(0x0F)); + + quint16 ndefFileId = 0; + quint8 temp = ccContent.at(9); + ndefFileId |= temp; + ndefFileId <<= 8; + + temp = ccContent.at(10); + ndefFileId |= temp; + + quint16 maxNdefLen = 0; + temp = ccContent.at(11); + maxNdefLen |= temp; + maxNdefLen <<= 8; + + temp = ccContent.at(12); + maxNdefLen |= temp; + + qDebug()<<"ndefFileId is "<<ndefFileId; + qDebug()<<"maxNdefLen is "<<maxNdefLen; + + qDebug()<<"select NDEF"; + QNearFieldTarget::RequestId id3 = mTester.target->select(ndefFileId); + QVERIFY(mTester.target->waitForRequestCompleted(id3)); + ++okCount; + QCOMPARE(okSpy.count(), okCount); + QVERIFY(mTester.target->requestResponse(id3).toBool()); + + qDebug()<<"read NDEF message length"; + QNearFieldTarget::RequestId id4 = mTester.target->read(0x0002, 0x0000); + QVERIFY(mTester.target->waitForRequestCompleted(id4)); + ++okCount; + QCOMPARE(okSpy.count(), okCount); + QByteArray ndefLenResult = mTester.target->requestResponse(id4).toByteArray(); + QCOMPARE(ndefLenResult.right(2), resp); + + temp = ndefLenResult.at(0); + quint16 nLen = 0; + nLen |= temp; + nLen <<= 8; + + temp = ndefLenResult.at(1); + nLen |= temp; + + qDebug()<<"ndef length is "<<nLen; + QVERIFY( nLen > 0 ); + QVERIFY( nLen < maxNdefLen - 2 ); + + + qDebug()<<"read NDEF message"; + QNearFieldTarget::RequestId id5 = mTester.target->read(nLen + 2, 0x0000); + QVERIFY(mTester.target->waitForRequestCompleted(id5)); + ++okCount; + QCOMPARE(okSpy.count(), okCount); + QByteArray ndefContent = mTester.target->requestResponse(id5).toByteArray(); + QCOMPARE(ndefContent.right(2), resp); + + + QByteArray ndefMessageContent = ndefContent.mid(2, nLen); + QByteArray inputNdefMessageContent = messages.at(0).toByteArray(); + QCOMPARE(ndefMessageContent, inputNdefMessageContent); + + QCOMPARE(errSpy.count(), errCount); + + // Write NDEF with raw command + QNdefMessage message; + QNdefNfcTextRecord textRecord; + textRecord.setText("nfc"); + + message.append(textRecord); + + QByteArray newNdefMessageContent = message.toByteArray(); + quint16 ndefMessageContentLen = newNdefMessageContent.count(); + temp = ndefMessageContentLen & 0x00FF; + newNdefMessageContent.push_front((char)temp); + temp = (ndefMessageContentLen >> 8) & 0x00FF; + newNdefMessageContent.push_front((char)temp); + + // ndef file is selected + QNearFieldTarget::RequestId id6 = mTester.target->write(newNdefMessageContent, 0); + QVERIFY(mTester.target->waitForRequestCompleted(id6)); + ++okCount; + QCOMPARE(okSpy.count(), okCount); + QVERIFY(mTester.target->requestResponse(id6).toBool()); + + // read ndef with ndef access + mTester.target->readNdefMessages(); + ++ndefReadCount; + QTRY_COMPARE(ndefMessageReadSpy.count(), ndefReadCount); + + const QNdefMessage& ndefMessage_new(ndefMessageReadSpy.first().at(0).value<QNdefMessage>()); + + QCOMPARE(newNdefMessageContent.right(newNdefMessageContent.count() - 2), ndefMessage_new.toByteArray()); + QCOMPARE(errSpy.count(), errCount); +} + +void tst_qnearfieldtagtype4::testRawAndNdefAccess() +{ + mTester.touchTarget(); + QNdefMessage message; + QNdefNfcUriRecord uriRecord; + uriRecord.setUri(QUrl("http://qt.nokia.com")); + message.append(uriRecord); + + QList<QNdefMessage> messages; + messages.append(message); + + testRawAccessAndNdefAccess(messages); + mTester.removeTarget(); +} + +QTEST_MAIN(tst_qnearfieldtagtype4); + +#include "tst_qnearfieldtagtype4.moc" diff --git a/tests/nfctestserver/main.cpp b/tests/nfctestserver/main.cpp new file mode 100644 index 00000000..9e02f4f3 --- /dev/null +++ b/tests/nfctestserver/main.cpp @@ -0,0 +1,62 @@ +/**************************************************************************** +** +** 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 <QtCore/QCoreApplication> + +#include "socketcontroller.h" +#include "servercontroller.h" + +int main(int argc, char *argv[]) +{ + QCoreApplication app(argc, argv); + + // Connection oriented sockets + new ServerController(ServerController::StreamConnection, &app); + new ServerController(ServerController::DatagramConnection, &app); + new SocketController(SocketController::StreamConnection, &app); + new SocketController(SocketController::DatagramConnection, &app); + + // Connectionless sockets + new SocketController(SocketController::BoundSocket, &app); + new SocketController(SocketController::ConnectionlessSocket, &app); + + return app.exec(); +} diff --git a/tests/nfctestserver/nfctestserver.pro b/tests/nfctestserver/nfctestserver.pro new file mode 100644 index 00000000..c307c30b --- /dev/null +++ b/tests/nfctestserver/nfctestserver.pro @@ -0,0 +1,27 @@ + +INCLUDEPATH += $$PWD/../../src/nfc +DEPENDPATH += $$PWD/../../src/nfc + + +TARGET = nfctestserver + +CONFIG += qt debug warn_on console depend_includepath testcase +CONFIG += console strict_flags +CONFIG -= app_bundle + +QMAKE_LIBS += -Wl,-rpath,$${QT.nfc.libs} + +QT = core nfc connectivity +qtAddLibrary(QtTest) + + +TEMPLATE = app + +SOURCES += main.cpp \ + socketcontroller.cpp \ + servercontroller.cpp + +HEADERS += \ + socketcontroller.h \ + servercontroller.h \ + servicenames.h diff --git a/tests/nfctestserver/servercontroller.cpp b/tests/nfctestserver/servercontroller.cpp new file mode 100644 index 00000000..aafb82d4 --- /dev/null +++ b/tests/nfctestserver/servercontroller.cpp @@ -0,0 +1,159 @@ +/**************************************************************************** +** +** 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 "servercontroller.h" +#include "servicenames.h" + +ServerController::ServerController(ConnectionType type, QObject *parent) +: QObject(parent), m_server(new QLlcpServer(this)), m_socket(0), m_connectionType(type) +{ + connect(m_server, SIGNAL(newConnection()), this, SLOT(newConnection())); + + switch (m_connectionType) { + case StreamConnection: + m_service = commandServer + streamSuffix; + break; + case DatagramConnection: + m_service = commandServer + datagramSuffix; + break; + } + + m_server->listen(m_service); + + if (m_server->isListening()) + qDebug() << "Server listening on" << m_service; +} + +ServerController::~ServerController() +{ + delete m_socket; + delete m_server; +} + +void ServerController::newConnection() +{ + m_socket = m_server->nextPendingConnection(); + + qDebug() << "Server got new connection"; + + connect(m_socket, SIGNAL(readyRead()), this, SLOT(socketReadyRead())); + connect(m_socket, SIGNAL(bytesWritten(qint64)), this, SLOT(socketBytesWritten(qint64))); + connect(m_socket, SIGNAL(disconnected()), this, SLOT(socketDisconnected())); +} + +void ServerController::socketReadyRead() +{ + switch (m_connectionType) { + case StreamConnection: + while (m_socket->canReadLine()) { + const QByteArray line = m_socket->readLine().trimmed(); + + qDebug() << "Server read line:" << line; + + QByteArray command; + QByteArray parameter; + + int index = line.indexOf(' '); + if (index >= 0) { + command = line.left(index); + parameter = line.mid(index + 1); + } else { + command = line; + } + + if (command == "ECHO") { + m_socket->write(parameter + '\n'); + } else if (command == "DISCONNECT") { + m_socket->disconnectFromService(); + break; + } else if (command == "CLOSE") { + m_socket->close(); + break; + } else if (command == "URI") { + m_socket->write(m_service.toLatin1()); + m_socket->write("\n"); + } + } + break; + case DatagramConnection: + while (m_socket->hasPendingDatagrams()) { + qint64 size = m_socket->pendingDatagramSize(); + QByteArray data; + data.resize(size); + m_socket->readDatagram(data.data(), data.size()); + + QByteArray command; + QByteArray parameter; + + int index = data.indexOf(' '); + if (index >= 0) { + command = data.left(index); + parameter = data.mid(index + 1); + } else { + command = data; + } + + if (command == "ECHO") { + m_socket->writeDatagram(parameter); + } else if (command == "DISCONNECT") { + m_socket->disconnectFromService(); + break; + } else if (command == "CLOSE") { + m_socket->close(); + break; + } else if (command == "URI") { + m_socket->writeDatagram(m_service.toLatin1()); + } + } + break; + } +} + +void ServerController::socketBytesWritten(qint64 bytes) +{ + Q_UNUSED(bytes); +} + +void ServerController::socketDisconnected() +{ + m_socket->deleteLater(); + m_socket = 0; +} diff --git a/tests/nfctestserver/servercontroller.h b/tests/nfctestserver/servercontroller.h new file mode 100644 index 00000000..8cb6ca12 --- /dev/null +++ b/tests/nfctestserver/servercontroller.h @@ -0,0 +1,76 @@ +/**************************************************************************** +** +** 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 SERVERCONTROLLER_H +#define SERVERCONTROLLER_H + +#include <QtCore/QObject> + +#include <qllcpserver.h> + +class ServerController : public QObject +{ + Q_OBJECT + +public: + enum ConnectionType { + StreamConnection, + DatagramConnection + }; + + ServerController(ConnectionType type, QObject *parent = 0); + ~ServerController(); + +private slots: + void newConnection(); + + void socketReadyRead(); + void socketBytesWritten(qint64 bytes); + void socketDisconnected(); + +private: + QLlcpServer *m_server; + QLlcpSocket *m_socket; + ConnectionType m_connectionType; + QString m_service; +}; + +#endif // SERVERCONTROLLER_H diff --git a/tests/nfctestserver/servicenames.h b/tests/nfctestserver/servicenames.h new file mode 100644 index 00000000..c90fa7b3 --- /dev/null +++ b/tests/nfctestserver/servicenames.h @@ -0,0 +1,52 @@ +/**************************************************************************** +** +** 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 SERVICENAMES_H +#define SERVICENAMES_H + +static const QLatin1String commandServer("urn:nfc:sn:com.nokia.qt.commandserver"); +static const QLatin1String helloServer("urn:nfc:sn:com.nokia.qt.helloserver"); +static const QLatin1String streamSuffix(".stream"); +static const QLatin1String datagramSuffix(".datagram"); + +static const quint8 boundSocketPort = 63; + +#endif // SERVICENAMES_H diff --git a/tests/nfctestserver/socketcontroller.cpp b/tests/nfctestserver/socketcontroller.cpp new file mode 100644 index 00000000..e16f53eb --- /dev/null +++ b/tests/nfctestserver/socketcontroller.cpp @@ -0,0 +1,195 @@ +/**************************************************************************** +** +** 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 "socketcontroller.h" +#include "servicenames.h" + +SocketController::SocketController(ConnectionType type, QObject *parent) +: QObject(parent), m_manager(0), m_socket(new QLlcpSocket(this)), m_connectionType(type), + m_timerId(-1) +{ + connect(m_socket, SIGNAL(connected()), this, SLOT(connected())); + connect(m_socket, SIGNAL(disconnected()), this, SLOT(disconnected())); + connect(m_socket, SIGNAL(error(QLlcpSocket::SocketError)), + this, SLOT(error(QLlcpSocket::SocketError))); + connect(m_socket, SIGNAL(stateChanged(QLlcpSocket::SocketState)), + this, SLOT(stateChanged(QLlcpSocket::SocketState))); + connect(m_socket, SIGNAL(readyRead()), this, SLOT(readyRead())); + + switch (m_connectionType) { + case StreamConnection: + m_service = helloServer + streamSuffix; + qDebug() << "Client connecting to" << m_service; + m_socket->connectToService(0, m_service); + break; + case DatagramConnection: + m_service = helloServer + datagramSuffix; + qDebug() << "Client connecting to" << m_service; + m_socket->connectToService(0, m_service); + break; + case BoundSocket: + m_port = boundSocketPort; + qDebug() << "Client binding to" << m_port; + if (!m_socket->bind(m_port)) + qDebug() << "Failed to bind to port" << m_port; + break; + case ConnectionlessSocket: + qDebug() << "Client binding to arbitrary port"; + if (!m_socket->bind(0)) { + qDebug() << "Failed to bind to arbitrary port"; + } else { + m_manager = new QNearFieldManager(this); + connect(m_manager, SIGNAL(targetDetected(QNearFieldTarget*)), + this, SLOT(targetDetected(QNearFieldTarget*))); + connect(m_manager, SIGNAL(targetLost(QNearFieldTarget*)), + this, SLOT(targetLost(QNearFieldTarget*))); + m_manager->startTargetDetection(QNearFieldTarget::NfcForumDevice); + } + break; + default: + qFatal("Unknown connection type"); + } +} + +SocketController::~SocketController() +{ + delete m_socket; +} + +void SocketController::connected() +{ + qDebug() << "Client connected"; + const QString data = QLatin1String("HELLO ") + m_service; + switch (m_connectionType) { + case StreamConnection: + m_socket->write(data.toUtf8() + '\n'); + break; + case DatagramConnection: + m_socket->writeDatagram(data.toUtf8()); + break; + default: + ; + } +} + +void SocketController::disconnected() +{ + qDebug() << "Client disconnected, reconnecting"; + + m_socket->connectToService(0, m_service); +} + +void SocketController::error(QLlcpSocket::SocketError socketError) +{ + qDebug() << "Client got error:" << socketError; +} + +void SocketController::stateChanged(QLlcpSocket::SocketState socketState) +{ + qDebug() << "Client state changed to" << socketState; +} + +void SocketController::readyRead() +{ + switch (m_connectionType) { + case StreamConnection: + while (m_socket->canReadLine()) { + const QByteArray line = m_socket->readLine().trimmed(); + + qDebug() << "Client read line:" << line; + + if (line == "DISCONNECT") { + m_socket->disconnectFromService(); + break; + } else if (line == "CLOSE") { + m_socket->close(); + break; + } + } + break; + case DatagramConnection: + while (m_socket->hasPendingDatagrams()) { + qint64 size = m_socket->pendingDatagramSize(); + QByteArray data; + data.resize(size); + m_socket->readDatagram(data.data(), data.size()); + + if (data == "DISCONNECT") { + m_socket->disconnectFromService(); + break; + } else if (data == "CLOSE") { + m_socket->close(); + break; + } + } + case BoundSocket: + case ConnectionlessSocket: + while (m_socket->hasPendingDatagrams()) { + qint64 size = m_socket->pendingDatagramSize(); + QByteArray data; + data.resize(size); + m_socket->readDatagram(data.data(), data.size()); + + qDebug() << data; + } + } +} + +void SocketController::targetDetected(QNearFieldTarget *target) +{ + Q_UNUSED(target); + + m_timerId = startTimer(500); +} + +void SocketController::targetLost(QNearFieldTarget *target) +{ + Q_UNUSED(target); + + killTimer(m_timerId); +} + +void SocketController::timerEvent(QTimerEvent *event) +{ + Q_UNUSED(event); + + m_socket->writeDatagram("Test message", 12, 0, boundSocketPort); +} diff --git a/tests/nfctestserver/socketcontroller.h b/tests/nfctestserver/socketcontroller.h new file mode 100644 index 00000000..d6273233 --- /dev/null +++ b/tests/nfctestserver/socketcontroller.h @@ -0,0 +1,86 @@ +/**************************************************************************** +** +** 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 SOCKETCONTROLLER_H +#define SOCKETCONTROLLER_H + +#include <QtCore/QObject> + +#include <qnearfieldmanager.h> +#include <qllcpsocket.h> + +class SocketController : public QObject +{ + Q_OBJECT + +public: + enum ConnectionType { + StreamConnection, + DatagramConnection, + BoundSocket, + ConnectionlessSocket + }; + + SocketController(ConnectionType type, QObject *parent = 0); + ~SocketController(); + +public slots: + void connected(); + void disconnected(); + void error(QLlcpSocket::SocketError socketError); + void stateChanged(QLlcpSocket::SocketState socketState); + void readyRead(); + void targetDetected(QNearFieldTarget *target); + void targetLost(QNearFieldTarget *target); + +protected: + void timerEvent(QTimerEvent *event); + +private: + QNearFieldManager *m_manager; + QLlcpSocket *m_socket; + ConnectionType m_connectionType; + QString m_service; + quint8 m_port; + int m_timerId; +}; + +#endif // SOCKETCONTROLLER_H diff --git a/tests/tests.pro b/tests/tests.pro new file mode 100644 index 00000000..b2ca6bf9 --- /dev/null +++ b/tests/tests.pro @@ -0,0 +1,10 @@ +TEMPLATE = subdirs +SUBDIRS += nfctestserver + +linux*:!linux-armcc:contains(bluez_enabled, yes):contains(QT_CONFIG, dbus) { + SUBDIRS += btclient +} + +symbian { + SUBDIRS += nfcsymbianbackend +} |