summaryrefslogtreecommitdiff
path: root/tests/auto/dbus/qdbusconnection/tst_qdbusconnection.cpp
blob: f8f632d667bd3af9b1f68cb6185baf4703a0e4b0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
/****************************************************************************
**
** 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 test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <qcoreapplication.h>
#include <qdebug.h>

#include <QtTest/QtTest>
#include <QtDBus/QtDBus>

class BaseObject: public QObject
{
    Q_OBJECT
    Q_CLASSINFO("D-Bus Interface", "local.BaseObject")
public:
    BaseObject(QObject *parent = 0) : QObject(parent) { }
public slots:
    void anotherMethod() { }
};

class MyObject: public BaseObject
{
    Q_OBJECT
public slots:
    void method(const QDBusMessage &msg);

public:
    static QString path;
    int callCount;
    MyObject(QObject *parent = 0) : BaseObject(parent), callCount(0) {}
};

void MyObject::method(const QDBusMessage &msg)
{
    path = msg.path();
    ++callCount;
    //qDebug() << msg;
}

class tst_QDBusConnection: public QObject
{
    Q_OBJECT

    int signalsReceived;
public slots:
    void oneSlot() { ++signalsReceived; }
    void exitLoop() { ++signalsReceived; QTestEventLoop::instance().exitLoop(); }
    void secondCallWithCallback();

private slots:
    void noConnection();
    void connectToBus();
    void connectToPeer();
    void connect();
    void send();
    void sendWithGui();
    void sendAsync();
    void sendSignal();

    void registerObject_data();
    void registerObject();
    void registerObjectPeer_data();
    void registerObjectPeer();
    void registerObject2();
    void registerObjectPeer2();

    void registerQObjectChildren();
    void registerQObjectChildrenPeer();

    void callSelf();
    void callSelfByAnotherName_data();
    void callSelfByAnotherName();
    void multipleInterfacesInQObject();

    void slotsWithLessParameters();
    void nestedCallWithCallback();

    void serviceRegistrationRaceCondition();

    void registerVirtualObject();
    void callVirtualObject();
    void callVirtualObjectLocal();

public:
    QString serviceName() const { return "com.trolltech.Qt.Autotests.QDBusConnection"; }
    bool callMethod(const QDBusConnection &conn, const QString &path);
    bool callMethodPeer(const QDBusConnection &conn, const QString &path);
};

class QDBusSpy: public QObject
{
    Q_OBJECT
public slots:
    void handlePing(const QString &str) { args.clear(); args << str; }
    void asyncReply(const QDBusMessage &msg) { args = msg.arguments(); }

public:
    QList<QVariant> args;
};

void tst_QDBusConnection::noConnection()
{
    QDBusConnection con = QDBusConnection::connectToBus("unix:path=/dev/null", "testconnection");
    QVERIFY(!con.isConnected());

    // try sending a message. This should fail
    QDBusMessage msg = QDBusMessage::createMethodCall("org.kde.selftest", "/org/kde/selftest",
                                                      "org.kde.selftest", "Ping");
    msg << QLatin1String("ping");

    QVERIFY(!con.send(msg));

    QDBusSpy spy;
    QVERIFY(con.callWithCallback(msg, &spy, SLOT(asyncReply)) == 0);

    QDBusMessage reply = con.call(msg);
    QVERIFY(reply.type() == QDBusMessage::ErrorMessage);

    QDBusReply<void> voidreply(reply);
    QVERIFY(!voidreply.isValid());

    QDBusConnection::disconnectFromBus("testconnection");
}

void tst_QDBusConnection::sendSignal()
{
    QDBusConnection con = QDBusConnection::sessionBus();

    QVERIFY(con.isConnected());

    QDBusMessage msg = QDBusMessage::createSignal("/org/kde/selftest", "org.kde.selftest",
                                                  "Ping");
    msg << QLatin1String("ping");

    QVERIFY(con.send(msg));

    QTest::qWait(1000);
}

void tst_QDBusConnection::send()
{
    QDBusConnection con = QDBusConnection::sessionBus();

    QVERIFY(con.isConnected());

    QDBusMessage msg = QDBusMessage::createMethodCall("org.freedesktop.DBus",
        "/org/freedesktop/DBus", "org.freedesktop.DBus", "ListNames");

    QDBusMessage reply = con.call(msg);

    QCOMPARE(reply.arguments().count(), 1);
    QCOMPARE(reply.arguments().at(0).typeName(), "QStringList");
    QVERIFY(reply.arguments().at(0).toStringList().contains(con.baseService()));
}

void tst_QDBusConnection::sendWithGui()
{
    QDBusConnection con = QDBusConnection::sessionBus();

    QVERIFY(con.isConnected());

    QDBusMessage msg = QDBusMessage::createMethodCall("org.freedesktop.DBus",
        "/org/freedesktop/DBus", "org.freedesktop.DBus", "ListNames");

    QDBusMessage reply = con.call(msg, QDBus::BlockWithGui);

    QCOMPARE(reply.arguments().count(), 1);
    QCOMPARE(reply.arguments().at(0).typeName(), "QStringList");
    QVERIFY(reply.arguments().at(0).toStringList().contains(con.baseService()));
}

void tst_QDBusConnection::sendAsync()
{
    QDBusConnection con = QDBusConnection::sessionBus();
    QVERIFY(con.isConnected());

    QDBusSpy spy;

    QDBusMessage msg = QDBusMessage::createMethodCall("org.freedesktop.DBus",
            "/org/freedesktop/DBus", "org.freedesktop.DBus", "ListNames");
    QVERIFY(con.callWithCallback(msg, &spy, SLOT(asyncReply(QDBusMessage))));

    QTest::qWait(1000);

    QCOMPARE(spy.args.value(0).typeName(), "QStringList");
    QVERIFY(spy.args.at(0).toStringList().contains(con.baseService()));
}

void tst_QDBusConnection::connect()
{
    QDBusSpy spy;

    QDBusConnection con = QDBusConnection::sessionBus();

    con.connect(con.baseService(), "/org/kde/selftest", "org.kde.selftest", "ping", &spy,
                 SLOT(handlePing(QString)));

    QDBusMessage msg = QDBusMessage::createSignal("/org/kde/selftest", "org.kde.selftest",
                                                  "ping");
    msg << QLatin1String("ping");

    QVERIFY(con.send(msg));

    QTest::qWait(1000);

    QCOMPARE(spy.args.count(), 1);
    QCOMPARE(spy.args.at(0).toString(), QString("ping"));
}

void tst_QDBusConnection::connectToBus()
{
    {
        QDBusConnection con = QDBusConnection::connectToBus(
                QDBusConnection::SessionBus, "bubu");

        QVERIFY(con.isConnected());
        QVERIFY(!con.lastError().isValid());

        QDBusConnection con2("foo");
        QVERIFY(!con2.isConnected());
        QVERIFY(!con2.lastError().isValid());

        con2 = con;
        QVERIFY(con.isConnected());
        QVERIFY(con2.isConnected());
        QVERIFY(!con.lastError().isValid());
        QVERIFY(!con2.lastError().isValid());
    }

    {
        QDBusConnection con("bubu");
        QVERIFY(con.isConnected());
        QVERIFY(!con.lastError().isValid());
    }

    QDBusConnection::disconnectFromPeer("bubu");

    {
        QDBusConnection con("bubu");
        QVERIFY(con.isConnected());
        QVERIFY(!con.lastError().isValid());
    }

    QDBusConnection::disconnectFromBus("bubu");

    {
        QDBusConnection con("bubu");
        QVERIFY(!con.isConnected());
        QVERIFY(!con.lastError().isValid());
    }

    QByteArray address = qgetenv("DBUS_SESSION_BUS_ADDRESS");
    if (!address.isEmpty()) {
        QDBusConnection con = QDBusConnection::connectToBus(address, "newconn");
        QVERIFY(con.isConnected());
        QVERIFY(!con.lastError().isValid());

        QDBusConnection::disconnectFromBus("newconn");
    }
}

void tst_QDBusConnection::connectToPeer()
{
    {
        QDBusConnection con = QDBusConnection::connectToPeer(
                "", "newconn");
        QVERIFY(!con.isConnected());
        QVERIFY(con.lastError().isValid());
    }

    QDBusServer server("unix:tmpdir=/tmp", 0);

    {
        QDBusConnection con = QDBusConnection::connectToPeer(
                "unix:abstract=/tmp/dbus-XXXXXXXXXX,guid=00000000000000000000000000000000", "newconn2");
        QVERIFY(!con.isConnected());
        QVERIFY(con.lastError().isValid());
    }

    {
        QDBusConnection con = QDBusConnection::connectToPeer(
                server.address(), "bubu");

        QVERIFY(con.isConnected());
        QVERIFY(!con.lastError().isValid());

        QDBusConnection con2("foo");
        QVERIFY(!con2.isConnected());
        QVERIFY(!con2.lastError().isValid());

        con2 = con;
        QVERIFY(con.isConnected());
        QVERIFY(con2.isConnected());
        QVERIFY(!con.lastError().isValid());
        QVERIFY(!con2.lastError().isValid());
    }

    {
        QDBusConnection con("bubu");
        QVERIFY(con.isConnected());
        QVERIFY(!con.lastError().isValid());
    }

    QDBusConnection::disconnectFromBus("bubu");

    {
        QDBusConnection con("bubu");
        QVERIFY(con.isConnected());
        QVERIFY(!con.lastError().isValid());
    }

    QDBusConnection::disconnectFromPeer("bubu");

    {
        QDBusConnection con("bubu");
        QVERIFY(!con.isConnected());
        QVERIFY(!con.lastError().isValid());
    }
}

void tst_QDBusConnection::registerObject_data()
{
    QTest::addColumn<QString>("path");

    QTest::newRow("/") << "/";
    QTest::newRow("/p1") << "/p1";
    QTest::newRow("/p2") << "/p2";
    QTest::newRow("/p1/q") << "/p1/q";
    QTest::newRow("/p1/q/r") << "/p1/q/r";
}

void tst_QDBusConnection::registerObject()
{
    QFETCH(QString, path);

    QDBusConnection con = QDBusConnection::sessionBus();
    QVERIFY(con.isConnected());

    //QVERIFY(!callMethod(con, path));
    {
        // register one object at root:
        MyObject obj;
        QVERIFY(con.registerObject(path, &obj, QDBusConnection::ExportAllSlots));
        QCOMPARE(con.objectRegisteredAt(path), static_cast<QObject *>(&obj));
        QVERIFY(callMethod(con, path));
        QCOMPARE(obj.path, path);
    }
    // make sure it's gone
    QVERIFY(!callMethod(con, path));
}

class MyServer : public QDBusServer
{
    Q_OBJECT
public:
    MyServer(QString path, QString addr, QObject* parent) : QDBusServer(addr, parent),
                                                            m_path(path),
                                                            m_conn("none")
    {
        connect(this, SIGNAL(newConnection(const QDBusConnection&)), SLOT(handleConnection(const QDBusConnection&)));
    }

    bool registerObject()
    {
        if( !m_conn.registerObject(m_path, &m_obj, QDBusConnection::ExportAllSlots) )
            return false;
        if(! (m_conn.objectRegisteredAt(m_path) == &m_obj))
            return false;
        return true;
    }

    void unregisterObject()
    {
        m_conn.unregisterObject(m_path);
    }

public slots:
    void handleConnection(const QDBusConnection& c)
    {
        m_conn = c;
        QVERIFY(isConnected());
        QVERIFY(m_conn.isConnected());
        QVERIFY(registerObject());
    }

private:
    MyObject m_obj;
    QString m_path;
    QDBusConnection m_conn;
};


void tst_QDBusConnection::registerObjectPeer_data()
{
    QTest::addColumn<QString>("path");

    QTest::newRow("/") << "/";
    QTest::newRow("/p1") << "/p1";
    QTest::newRow("/p2") << "/p2";
    QTest::newRow("/p1/q") << "/p1/q";
    QTest::newRow("/p1/q/r") << "/p1/q/r";
}

void tst_QDBusConnection::registerObjectPeer()
{
    QFETCH(QString, path);

    MyServer server(path, "unix:tmpdir=/tmp", 0);

    {
        QDBusConnection con = QDBusConnection::connectToPeer(server.address(), "foo");

        QCoreApplication::processEvents();
        QVERIFY(con.isConnected());

        MyObject obj;
        QVERIFY(callMethodPeer(con, path));
        QCOMPARE(obj.path, path);
    }

    {
        QDBusConnection con("foo");
        QVERIFY(con.isConnected());
        QVERIFY(callMethodPeer(con, path));
    }

    server.unregisterObject();

    {
        QDBusConnection con("foo");
        QVERIFY(con.isConnected());
        QVERIFY(!callMethodPeer(con, path));
    }

    server.registerObject();

    {
        QDBusConnection con("foo");
        QVERIFY(con.isConnected());
        QVERIFY(callMethodPeer(con, path));
    }

    QDBusConnection::disconnectFromPeer("foo");

    {
        QDBusConnection con("foo");
        QVERIFY(!con.isConnected());
        QVERIFY(!callMethodPeer(con, path));
    }
}

void tst_QDBusConnection::registerObject2()
{
    QDBusConnection con = QDBusConnection::sessionBus();
    QVERIFY(con.isConnected());

    // make sure nothing is using our paths:
     QVERIFY(!callMethod(con, "/"));
     QVERIFY(!callMethod(con, "/p1"));
     QVERIFY(!callMethod(con, "/p2"));
     QVERIFY(!callMethod(con, "/p1/q"));
     QVERIFY(!callMethod(con, "/p1/q/r"));

    {
        // register one object at root:
        MyObject obj;
        QVERIFY(con.registerObject("/", &obj, QDBusConnection::ExportAllSlots));
        QVERIFY(callMethod(con, "/"));
        qDebug() << obj.path;
        QCOMPARE(obj.path, QString("/"));
    }
    // make sure it's gone
    QVERIFY(!callMethod(con, "/"));

    {
        // register one at an element:
        MyObject obj;
        QVERIFY(con.registerObject("/p1", &obj, QDBusConnection::ExportAllSlots));
        QVERIFY(!callMethod(con, "/"));
        QVERIFY(callMethod(con, "/p1"));
        qDebug() << obj.path;
        QCOMPARE(obj.path, QString("/p1"));

        // re-register it somewhere else
        QVERIFY(con.registerObject("/p2", &obj, QDBusConnection::ExportAllSlots));
        QVERIFY(callMethod(con, "/p1"));
        QCOMPARE(obj.path, QString("/p1"));
        QVERIFY(callMethod(con, "/p2"));
        QCOMPARE(obj.path, QString("/p2"));
    }
    // make sure it's gone
    QVERIFY(!callMethod(con, "/p1"));
    QVERIFY(!callMethod(con, "/p2"));

    {
        // register at a deep path
        MyObject obj;
        QVERIFY(con.registerObject("/p1/q/r", &obj, QDBusConnection::ExportAllSlots));
        QVERIFY(!callMethod(con, "/"));
        QVERIFY(!callMethod(con, "/p1"));
        QVERIFY(!callMethod(con, "/p1/q"));
        QVERIFY(callMethod(con, "/p1/q/r"));
        QCOMPARE(obj.path, QString("/p1/q/r"));
    }
    // make sure it's gone
    QVERIFY(!callMethod(con, "/p1/q/r"));

    {
        MyObject obj;
        QVERIFY(con.registerObject("/p1/q2", &obj, QDBusConnection::ExportAllSlots));
        QVERIFY(callMethod(con, "/p1/q2"));
        QCOMPARE(obj.path, QString("/p1/q2"));

        // try unregistering
        con.unregisterObject("/p1/q2");
        QVERIFY(!callMethod(con, "/p1/q2"));

        // register it again
        QVERIFY(con.registerObject("/p1/q2", &obj, QDBusConnection::ExportAllSlots));
        QVERIFY(callMethod(con, "/p1/q2"));
        QCOMPARE(obj.path, QString("/p1/q2"));

        // now try removing things around it:
        con.unregisterObject("/p2");
        QVERIFY(callMethod(con, "/p1/q2")); // unrelated object shouldn't affect

        con.unregisterObject("/p1");
        QVERIFY(callMethod(con, "/p1/q2")); // unregistering just the parent shouldn't affect it

        con.unregisterObject("/p1/q2/r");
        QVERIFY(callMethod(con, "/p1/q2")); // unregistering non-existing child shouldn't affect it either

        con.unregisterObject("/p1/q");
        QVERIFY(callMethod(con, "/p1/q2")); // unregistering sibling (before) shouldn't affect

        con.unregisterObject("/p1/r");
        QVERIFY(callMethod(con, "/p1/q2")); // unregistering sibling (after) shouldn't affect

        // now remove it:
        con.unregisterObject("/p1", QDBusConnection::UnregisterTree);
        QVERIFY(!callMethod(con, "/p1/q2")); // we removed the full tree
    }
}

class MyServer2 : public QDBusServer
{
    Q_OBJECT
public:
    MyServer2(QString addr, QObject* parent) : QDBusServer(addr, parent),
                                               m_conn("none")
    {
        connect(this, SIGNAL(newConnection(const QDBusConnection&)), SLOT(handleConnection(const QDBusConnection&)));
    }

    QDBusConnection connection()
    {
        return m_conn;
    }

public slots:
    void handleConnection(const QDBusConnection& c)
    {
        m_conn = c;
        QVERIFY(isConnected());
        QVERIFY(m_conn.isConnected());
    }

private:
    MyObject m_obj;
    QDBusConnection m_conn;
};

void tst_QDBusConnection::registerObjectPeer2()
{
    MyServer2 server("unix:tmpdir=/tmp", 0);
    QDBusConnection con = QDBusConnection::connectToPeer(server.address(), "foo");
    QCoreApplication::processEvents();
    QVERIFY(con.isConnected());

    QDBusConnection srv_con = server.connection();

    // make sure nothing is using our paths:
    QVERIFY(!callMethodPeer(srv_con, "/"));
    QVERIFY(!callMethodPeer(srv_con, "/p1"));
    QVERIFY(!callMethodPeer(srv_con, "/p2"));
    QVERIFY(!callMethodPeer(srv_con, "/p1/q"));
    QVERIFY(!callMethodPeer(srv_con, "/p1/q/r"));

    {
        // register one object at root:
        MyObject obj;
        QVERIFY(con.registerObject("/", &obj, QDBusConnection::ExportAllSlots));
        QVERIFY(callMethodPeer(srv_con, "/"));
        qDebug() << obj.path;
        QCOMPARE(obj.path, QString("/"));
    }
    // make sure it's gone
    QVERIFY(!callMethodPeer(srv_con, "/"));

    {
        // register one at an element:
        MyObject obj;
        QVERIFY(con.registerObject("/p1", &obj, QDBusConnection::ExportAllSlots));
        QVERIFY(!callMethodPeer(srv_con, "/"));
        QVERIFY(callMethodPeer(srv_con, "/p1"));
        qDebug() << obj.path;
        QCOMPARE(obj.path, QString("/p1"));

        // re-register it somewhere else
        QVERIFY(con.registerObject("/p2", &obj, QDBusConnection::ExportAllSlots));
        QVERIFY(callMethodPeer(srv_con, "/p1"));
        QCOMPARE(obj.path, QString("/p1"));
        QVERIFY(callMethodPeer(srv_con, "/p2"));
        QCOMPARE(obj.path, QString("/p2"));
    }
    // make sure it's gone
    QVERIFY(!callMethodPeer(srv_con, "/p1"));
    QVERIFY(!callMethodPeer(srv_con, "/p2"));

    {
        // register at a deep path
        MyObject obj;
        QVERIFY(con.registerObject("/p1/q/r", &obj, QDBusConnection::ExportAllSlots));
        QVERIFY(!callMethodPeer(srv_con, "/"));
        QVERIFY(!callMethodPeer(srv_con, "/p1"));
        QVERIFY(!callMethodPeer(srv_con, "/p1/q"));
        QVERIFY(callMethodPeer(srv_con, "/p1/q/r"));
        QCOMPARE(obj.path, QString("/p1/q/r"));
    }
    // make sure it's gone
    QVERIFY(!callMethodPeer(srv_con, "/p1/q/r"));

    {
        MyObject obj;
        QVERIFY(con.registerObject("/p1/q2", &obj, QDBusConnection::ExportAllSlots));
        QVERIFY(callMethodPeer(srv_con, "/p1/q2"));
        QCOMPARE(obj.path, QString("/p1/q2"));

        // try unregistering
        con.unregisterObject("/p1/q2");
        QVERIFY(!callMethodPeer(srv_con, "/p1/q2"));

        // register it again
        QVERIFY(con.registerObject("/p1/q2", &obj, QDBusConnection::ExportAllSlots));
        QVERIFY(callMethodPeer(srv_con, "/p1/q2"));
        QCOMPARE(obj.path, QString("/p1/q2"));

        // now try removing things around it:
        con.unregisterObject("/p2");
        QVERIFY(callMethodPeer(srv_con, "/p1/q2")); // unrelated object shouldn't affect

        con.unregisterObject("/p1");
        QVERIFY(callMethodPeer(srv_con, "/p1/q2")); // unregistering just the parent shouldn't affect it

        con.unregisterObject("/p1/q2/r");
        QVERIFY(callMethodPeer(srv_con, "/p1/q2")); // unregistering non-existing child shouldn't affect it either

        con.unregisterObject("/p1/q");
        QVERIFY(callMethodPeer(srv_con, "/p1/q2")); // unregistering sibling (before) shouldn't affect

        con.unregisterObject("/p1/r");
        QVERIFY(callMethodPeer(srv_con, "/p1/q2")); // unregistering sibling (after) shouldn't affect

        // now remove it:
        con.unregisterObject("/p1", QDBusConnection::UnregisterTree);
        QVERIFY(!callMethodPeer(srv_con, "/p1/q2")); // we removed the full tree
    }

    QDBusConnection::disconnectFromPeer("foo");
}


void tst_QDBusConnection::registerQObjectChildren()
{
    // make sure no one is there
    QDBusConnection con = QDBusConnection::sessionBus();
    QVERIFY(!callMethod(con, "/p1"));

    {
        MyObject obj, *a, *b, *c, *cc;

        a = new MyObject(&obj);
        a->setObjectName("a");

        b = new MyObject(&obj);
        b->setObjectName("b");

        c = new MyObject(&obj);
        c->setObjectName("c");

        cc = new MyObject(c);
        cc->setObjectName("cc");

        con.registerObject("/p1", &obj, QDBusConnection::ExportAllSlots |
                           QDBusConnection::ExportChildObjects);

        // make calls
        QVERIFY(callMethod(con, "/p1"));
        QCOMPARE(obj.callCount, 1);
        QVERIFY(callMethod(con, "/p1/a"));
        QCOMPARE(a->callCount, 1);
        QVERIFY(callMethod(con, "/p1/b"));
        QCOMPARE(b->callCount, 1);
        QVERIFY(callMethod(con, "/p1/c"));
        QCOMPARE(c->callCount, 1);
        QVERIFY(callMethod(con, "/p1/c/cc"));
        QCOMPARE(cc->callCount, 1);

        QVERIFY(!callMethod(con, "/p1/d"));
        QVERIFY(!callMethod(con, "/p1/c/abc"));

        // pull an object, see if it goes away:
        delete b;
        QVERIFY(!callMethod(con, "/p1/b"));

        delete c;
        QVERIFY(!callMethod(con, "/p1/c"));
        QVERIFY(!callMethod(con, "/p1/c/cc"));
    }

    QVERIFY(!callMethod(con, "/p1"));
    QVERIFY(!callMethod(con, "/p1/a"));
    QVERIFY(!callMethod(con, "/p1/b"));
    QVERIFY(!callMethod(con, "/p1/c"));
    QVERIFY(!callMethod(con, "/p1/c/cc"));
}

void tst_QDBusConnection::registerQObjectChildrenPeer()
{
    MyServer2 server("unix:tmpdir=/tmp", 0);
    QDBusConnection con = QDBusConnection::connectToPeer(server.address(), "foo");
    QCoreApplication::processEvents();
    QVERIFY(con.isConnected());

    QDBusConnection srv_con = server.connection();

    QVERIFY(!callMethodPeer(srv_con, "/p1"));

    {
        MyObject obj, *a, *b, *c, *cc;

        a = new MyObject(&obj);
        a->setObjectName("a");

        b = new MyObject(&obj);
        b->setObjectName("b");

        c = new MyObject(&obj);
        c->setObjectName("c");

        cc = new MyObject(c);
        cc->setObjectName("cc");

        con.registerObject("/p1", &obj, QDBusConnection::ExportAllSlots |
                           QDBusConnection::ExportChildObjects);

        // make calls
        QVERIFY(callMethodPeer(srv_con, "/p1"));
        QCOMPARE(obj.callCount, 1);
        QVERIFY(callMethodPeer(srv_con, "/p1/a"));
        QCOMPARE(a->callCount, 1);
        QVERIFY(callMethodPeer(srv_con, "/p1/b"));
        QCOMPARE(b->callCount, 1);
        QVERIFY(callMethodPeer(srv_con, "/p1/c"));
        QCOMPARE(c->callCount, 1);
        QVERIFY(callMethodPeer(srv_con, "/p1/c/cc"));
        QCOMPARE(cc->callCount, 1);

        QVERIFY(!callMethodPeer(srv_con, "/p1/d"));
        QVERIFY(!callMethodPeer(srv_con, "/p1/c/abc"));

        // pull an object, see if it goes away:
        delete b;
        QVERIFY(!callMethodPeer(srv_con, "/p1/b"));

        delete c;
        QVERIFY(!callMethodPeer(srv_con, "/p1/c"));
        QVERIFY(!callMethodPeer(srv_con, "/p1/c/cc"));
    }

    QVERIFY(!callMethodPeer(srv_con, "/p1"));
    QVERIFY(!callMethodPeer(srv_con, "/p1/a"));
    QVERIFY(!callMethodPeer(srv_con, "/p1/b"));
    QVERIFY(!callMethodPeer(srv_con, "/p1/c"));
    QVERIFY(!callMethodPeer(srv_con, "/p1/c/cc"));

    QDBusConnection::disconnectFromPeer("foo");
}

bool tst_QDBusConnection::callMethod(const QDBusConnection &conn, const QString &path)
{
    QDBusMessage msg = QDBusMessage::createMethodCall(conn.baseService(), path, "", "method");
    QDBusMessage reply = conn.call(msg, QDBus::Block/*WithGui*/);
    if (reply.type() != QDBusMessage::ReplyMessage)
        return false;
    if (MyObject::path == path) {
        QTest::compare_helper(true, "COMPARE()", __FILE__, __LINE__);
    } else {
        QTest::compare_helper(false, "Compared values are not the same",
                              QTest::toString(MyObject::path), QTest::toString(path),
                              "MyObject::path", "path", __FILE__, __LINE__);
        return false;
    }

    return true;
}

bool tst_QDBusConnection::callMethodPeer(const QDBusConnection &conn, const QString &path)
{
    QDBusMessage msg = QDBusMessage::createMethodCall("", path, "", "method");
    QDBusMessage reply = conn.call(msg, QDBus::BlockWithGui);

    if (reply.type() != QDBusMessage::ReplyMessage)
        return false;
    if (MyObject::path == path) {
        QTest::compare_helper(true, "COMPARE()", __FILE__, __LINE__);
    } else {
        QTest::compare_helper(false, "Compared values are not the same",
                              QTest::toString(MyObject::path), QTest::toString(path),
                              "MyObject::path", "path", __FILE__, __LINE__);
        return false;
    }

    return true;
}

class TestObject : public QObject
{
Q_OBJECT
public:
    TestObject(QObject *parent = 0) : QObject(parent) {}
    ~TestObject() {}

    QString func;

public slots:
    void test0() { func = "test0"; }
    void test1(int i) { func = "test1 " + QString::number(i); }
    int test2() { func = "test2"; return 43; }
    int test3(int i) { func = "test2"; return i + 1; }
};

void tst_QDBusConnection::callSelf()
{
    TestObject testObject;
    QDBusConnection connection = QDBusConnection::sessionBus();
    QVERIFY(connection.registerObject("/test", &testObject,
            QDBusConnection::ExportAllContents));
    QCOMPARE(connection.objectRegisteredAt("/test"), static_cast<QObject *>(&testObject));
    QVERIFY(connection.registerService(serviceName()));
    QDBusInterface interface(serviceName(), "/test");
    QVERIFY(interface.isValid());

    interface.call(QDBus::Block, "test0");
    QCOMPARE(testObject.func, QString("test0"));
    interface.call(QDBus::Block, "test1", 42);
    QCOMPARE(testObject.func, QString("test1 42"));
    QDBusMessage reply = interface.call(QDBus::Block, "test2");
    QCOMPARE(testObject.func, QString("test2"));
    QCOMPARE(reply.arguments().value(0).toInt(), 43);

    QDBusMessage msg = QDBusMessage::createMethodCall(serviceName(), "/test",
                                                      QString(), "test3");
    msg << 44;
    reply = connection.call(msg);
    QCOMPARE(reply.arguments().value(0).toInt(), 45);
}

void tst_QDBusConnection::callSelfByAnotherName_data()
{
    QTest::addColumn<int>("registerMethod");
    QTest::newRow("connection") << 0;
    QTest::newRow("connection-interface") << 1;
    QTest::newRow("direct") << 2;
}

void tst_QDBusConnection::callSelfByAnotherName()
{
    static int counter = 0;
    QString sname = serviceName() + QString::number(counter++);

    QDBusConnection con = QDBusConnection::sessionBus();
    QVERIFY(con.isConnected());

    TestObject testObject;
    QVERIFY(con.registerObject("/test", &testObject,
            QDBusConnection::ExportAllContents));
    con.connect("org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", "NameOwnerChanged",
                QStringList() << sname << "",
                QString(), &QTestEventLoop::instance(), SLOT(exitLoop()));

    // register the name
    QFETCH(int, registerMethod);
    switch (registerMethod) {
    case 0:
        QVERIFY(con.registerService(sname));
        break;

    case 1:
        QVERIFY(con.interface()->registerService(sname).value() == QDBusConnectionInterface::ServiceRegistered);
        break;

    case 2: {
            // flag is DBUS_NAME_FLAG_DO_NOT_QUEUE = 0x04
            // reply is DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER = 1
            QDBusReply<uint> reply = con.interface()->call("RequestName", sname, 4u);
            QVERIFY(reply.value() == 1);
        }
    }

    struct Deregisterer {
        QDBusConnection con;
        QString sname;
        Deregisterer(const QDBusConnection &con, const QString &sname) : con(con), sname(sname) {}
        ~Deregisterer() { con.interface()->unregisterService(sname); }
    } deregisterer(con, sname);

    // give the connection a chance to find out that we're good to go
    QTestEventLoop::instance().enterLoop(2);
    con.disconnect("org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", "NameOwnerChanged",
                 QStringList() << sname << "",
                 QString(), &QTestEventLoop::instance(), SLOT(exitLoop()));
    QVERIFY(!QTestEventLoop::instance().timeout());

    // make the call
    QDBusMessage msg = QDBusMessage::createMethodCall(sname, "/test",
                                                      QString(), "test0");
    QDBusMessage reply = con.call(msg, QDBus::Block, 1000);

    QVERIFY(reply.type() == QDBusMessage::ReplyMessage);
}

void tst_QDBusConnection::multipleInterfacesInQObject()
{
    QDBusConnection con = QDBusConnection::sessionBus();
    QVERIFY(!callMethod(con, "/p1"));

    MyObject obj;
    con.registerObject("/p1", &obj, QDBusConnection::ExportAllSlots);

    // check if we can call the BaseObject's interface
    QDBusMessage msg = QDBusMessage::createMethodCall(con.baseService(), "/p1",
                                                      "local.BaseObject", "anotherMethod");
    QDBusMessage reply = con.call(msg, QDBus::Block);
    QCOMPARE(reply.type(), QDBusMessage::ReplyMessage);
    QVERIFY(reply.arguments().count() == 0);
}

void tst_QDBusConnection::slotsWithLessParameters()
{
    QDBusConnection con = QDBusConnection::sessionBus();

    QDBusMessage signal = QDBusMessage::createSignal("/", "com.trolltech.TestCase",
                                                     "oneSignal");
    signal << "one parameter";

    signalsReceived = 0;
    QVERIFY(con.connect(con.baseService(), signal.path(), signal.interface(),
                        signal.member(), this, SLOT(oneSlot())));
    QVERIFY(con.send(signal));
    QTest::qWait(100);
    QCOMPARE(signalsReceived, 1);

    // disconnect and try with a signature
    signalsReceived = 0;
    QVERIFY(con.disconnect(con.baseService(), signal.path(), signal.interface(),
                           signal.member(), this, SLOT(oneSlot())));
    QVERIFY(con.connect(con.baseService(), signal.path(), signal.interface(),
                        signal.member(), "s", this, SLOT(oneSlot())));
    QVERIFY(con.send(signal));
    QTest::qWait(100);
    QCOMPARE(signalsReceived, 1);
}

void tst_QDBusConnection::secondCallWithCallback()
{
    qDebug("Hello");
    QDBusConnection con = QDBusConnection::sessionBus();
    QDBusMessage msg = QDBusMessage::createMethodCall(con.baseService(), "/test", QString(),
                                                      "test0");
    con.callWithCallback(msg, this, SLOT(exitLoop()), SLOT(secondCallWithCallback()));
}

void tst_QDBusConnection::nestedCallWithCallback()
{
    TestObject testObject;
    QDBusConnection connection = QDBusConnection::sessionBus();
    QVERIFY(connection.registerObject("/test", &testObject,
            QDBusConnection::ExportAllContents));

    QDBusMessage msg = QDBusMessage::createMethodCall(connection.baseService(), "/test", QString(),
                                                      "ThisFunctionDoesntExist");
    signalsReceived = 0;

    connection.callWithCallback(msg, this, SLOT(exitLoop()), SLOT(secondCallWithCallback()), 10);
    QTestEventLoop::instance().enterLoop(15);
    QVERIFY(!QTestEventLoop::instance().timeout());
    QCOMPARE(signalsReceived, 1);
}

class RaceConditionSignalWaiter : public QObject
{
    Q_OBJECT
public:
    int count;
    RaceConditionSignalWaiter() : count (0) {}
    virtual ~RaceConditionSignalWaiter() {}

public slots:
    void countUp() { ++count; emit done(); }
signals:
    void done();
};

void tst_QDBusConnection::serviceRegistrationRaceCondition()
{
    // There was a race condition in the updating of list of name owners in
    // QtDBus. When the user connects to a signal coming from a given
    // service, we must listen for NameOwnerChanged signals relevant to that
    // name and update when the owner changes. However, it's possible that we
    // receive in one chunk from the server both the NameOwnerChanged signal
    // about the service and the signal we're interested in. Since QtDBus
    // posts events in order to handle the incoming signals, the update
    // happens too late.

    const QString connectionName = "testConnectionName";
    const QString serviceName = "org.example.SecondaryName";

    QDBusConnection session = QDBusConnection::sessionBus();
    QVERIFY(!session.interface()->isServiceRegistered(serviceName));

    // connect to the signal:
    RaceConditionSignalWaiter recv;
    session.connect(serviceName, "/", "com.trolltech.TestCase", "oneSignal", &recv, SLOT(countUp()));

    // create a secondary connection and register a name
    QDBusConnection connection = QDBusConnection::connectToBus(QDBusConnection::SessionBus, connectionName);
    QDBusConnection::disconnectFromBus(connectionName); // disconnection happens when "connection" goes out of scope
    QVERIFY(connection.isConnected());
    QVERIFY(connection.registerService(serviceName));

    // send a signal
    QDBusMessage msg = QDBusMessage::createSignal("/", "com.trolltech.TestCase", "oneSignal");
    connection.send(msg);

    // make a blocking call just to be sure that the buffer was flushed
    msg = QDBusMessage::createMethodCall("org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus",
                                         "NameHasOwner");
    msg << connectionName;
    connection.call(msg); // ignore result

    // Now here's the race condition (more info on task QTBUG-15651):
    // the bus has most likely queued three signals for us to work on:
    // 1) NameOwnerChanged for the connection we created above
    // 2) NameOwnerChanged for the service we registered above
    // 3) The "oneSignal" signal we sent
    //
    // We'll most likely receive all three in one go from the server. We must
    // update the owner of serviceName before we start processing the
    // "oneSignal" signal.

    QTestEventLoop::instance().connect(&recv, SIGNAL(done()), SLOT(exitLoop()));
    QTestEventLoop::instance().enterLoop(1);
    QVERIFY(!QTestEventLoop::instance().timeout());
    QCOMPARE(recv.count, 1);
}

class VirtualObject: public QDBusVirtualObject
{
    Q_OBJECT
public:
    VirtualObject() :success(true) {}

    QString introspect(const QString & /* path */) const
    {
        return QString();
    }

    bool handleMessage(const QDBusMessage &message, const QDBusConnection &connection) {
        ++callCount;
        lastMessage = message;

        if (success) {
            QDBusMessage reply = message.createReply(replyArguments);
            connection.send(reply);
        }
        emit messageReceived(message);
        return success;
    }
signals:
    void messageReceived(const QDBusMessage &message) const;

public:
    mutable QDBusMessage lastMessage;
    QVariantList replyArguments;
    mutable int callCount;
    bool success;
};


void tst_QDBusConnection::registerVirtualObject()
{
    QDBusConnection con = QDBusConnection::sessionBus();
    QVERIFY(con.isConnected());

    QString path = "/tree/node";
    QString childPath = "/tree/node/child";
    QString childChildPath = "/tree/node/child/another";

    {
        // Register VirtualObject that handles child paths. Unregister by going out of scope.
        VirtualObject obj;
        QVERIFY(con.registerVirtualObject(path, &obj, QDBusConnection::SubPath));
        QCOMPARE(con.objectRegisteredAt(path), static_cast<QObject *>(&obj));
        QCOMPARE(con.objectRegisteredAt(childPath), static_cast<QObject *>(&obj));
        QCOMPARE(con.objectRegisteredAt(childChildPath), static_cast<QObject *>(&obj));
    }
    QCOMPARE(con.objectRegisteredAt(path), static_cast<QObject *>(0));
    QCOMPARE(con.objectRegisteredAt(childPath), static_cast<QObject *>(0));

    {
        // Register VirtualObject that handles child paths. Unregister by calling unregister.
        VirtualObject obj;
        QVERIFY(con.registerVirtualObject(path, &obj, QDBusConnection::SubPath));
        QCOMPARE(con.objectRegisteredAt(path), static_cast<QObject *>(&obj));
        QCOMPARE(con.objectRegisteredAt(childPath), static_cast<QObject *>(&obj));
        QCOMPARE(con.objectRegisteredAt(childChildPath), static_cast<QObject *>(&obj));
        con.unregisterObject(path);
        QCOMPARE(con.objectRegisteredAt(path), static_cast<QObject *>(0));
        QCOMPARE(con.objectRegisteredAt(childPath), static_cast<QObject *>(0));
    }

    {
        // Single node has no sub path handling.
        VirtualObject obj;
        QVERIFY(con.registerVirtualObject(path, &obj, QDBusConnection::SingleNode));
        QCOMPARE(con.objectRegisteredAt(path), static_cast<QObject *>(&obj));
        QCOMPARE(con.objectRegisteredAt(childPath), static_cast<QObject *>(0));
    }

    {
        // Register VirtualObject that handles child paths. Try to register an object on a child path of that.
        VirtualObject obj;
        QVERIFY(con.registerVirtualObject(path, &obj, QDBusConnection::SubPath));
        QCOMPARE(con.objectRegisteredAt(path), static_cast<QObject *>(&obj));

        QObject objectAtSubPath;
        QVERIFY(!con.registerObject(path, &objectAtSubPath));
        QVERIFY(!con.registerObject(childPath, &objectAtSubPath));
        QCOMPARE(con.objectRegisteredAt(childPath), static_cast<QObject *>(&obj));
    }

    {
        // Register object, make sure no SubPath handling object can be registered on a parent path.
        QObject objectAtSubPath;
        QVERIFY(con.registerObject(childPath, &objectAtSubPath));
        QCOMPARE(con.objectRegisteredAt(childPath), static_cast<QObject *>(&objectAtSubPath));

        VirtualObject obj;
        QVERIFY(!con.registerVirtualObject(path, &obj, QDBusConnection::SubPath));
        QCOMPARE(con.objectRegisteredAt(path), static_cast<QObject *>(0));
    }
    QCOMPARE(con.objectRegisteredAt(path), static_cast<QObject *>(0));
    QCOMPARE(con.objectRegisteredAt(childPath), static_cast<QObject *>(0));
    QCOMPARE(con.objectRegisteredAt(childChildPath), static_cast<QObject *>(0));
}

void tst_QDBusConnection::callVirtualObject()
{
    QDBusConnection con = QDBusConnection::sessionBus();
    QVERIFY(con.isConnected());

    QDBusConnection con2 = QDBusConnection::connectToBus(QDBusConnection::SessionBus, "con2");

    QString path = "/tree/node";
    QString childPath = "/tree/node/child";

    // register one object at root:
    VirtualObject obj;
    QVERIFY(con.registerVirtualObject(path, &obj, QDBusConnection::SubPath));
    obj.callCount = 0;
    obj.replyArguments << 42 << 47u;

    QObject::connect(&obj, SIGNAL(messageReceived(QDBusMessage)), &QTestEventLoop::instance(), SLOT(exitLoop()));

    QDBusMessage message = QDBusMessage::createMethodCall(con.baseService(), path, QString(), "hello");
    QDBusPendingCall reply = con2.asyncCall(message);

    QTestEventLoop::instance().enterLoop(5);
    QVERIFY(!QTestEventLoop::instance().timeout());

    QCOMPARE(obj.callCount, 1);
    QCOMPARE(obj.lastMessage.service(), con2.baseService());
    QCOMPARE(obj.lastMessage.interface(), QString());
    QCOMPARE(obj.lastMessage.path(), path);
    reply.waitForFinished();
    QVERIFY(reply.isValid());
    QCOMPARE(reply.reply().arguments(), obj.replyArguments);

    // call sub path
    QDBusMessage childMessage = QDBusMessage::createMethodCall(con.baseService(), childPath, QString(), "helloChild");
    obj.replyArguments.clear();
    obj.replyArguments << 99;
    QDBusPendingCall childReply = con2.asyncCall(childMessage);

    QTestEventLoop::instance().enterLoop(5);
    QVERIFY(!QTestEventLoop::instance().timeout());

    QCOMPARE(obj.callCount, 2);
    QCOMPARE(obj.lastMessage.service(), con2.baseService());
    QCOMPARE(obj.lastMessage.interface(), QString());
    QCOMPARE(obj.lastMessage.path(), childPath);

    childReply.waitForFinished();
    QVERIFY(childReply.isValid());
    QCOMPARE(childReply.reply().arguments(), obj.replyArguments);

    // let the call fail by having the virtual object return false
    obj.success = false;
    QDBusMessage errorMessage = QDBusMessage::createMethodCall(con.baseService(), childPath, QString(), "someFunc");
    QDBusPendingCall errorReply = con2.asyncCall(errorMessage);

    QTestEventLoop::instance().enterLoop(5);
    QVERIFY(!QTestEventLoop::instance().timeout());
    QTest::qWait(100);
    QVERIFY(errorReply.isError());
    qDebug() << errorReply.reply().arguments();
    QCOMPARE(errorReply.reply().errorName(), QString("org.freedesktop.DBus.Error.UnknownObject"));

    QDBusConnection::disconnectFromBus("con2");
}

void tst_QDBusConnection::callVirtualObjectLocal()
{
    QDBusConnection con = QDBusConnection::sessionBus();
    QVERIFY(con.isConnected());

    QString path = "/tree/node";
    QString childPath = "/tree/node/child";

    // register one object at root:
    VirtualObject obj;
    QVERIFY(con.registerVirtualObject(path, &obj, QDBusConnection::SubPath));
    obj.callCount = 0;
    obj.replyArguments << 42 << 47u;

    QDBusMessage message = QDBusMessage::createMethodCall(con.baseService(), path, QString(), "hello");
    QDBusMessage reply = con.call(message, QDBus::Block, 5000);
    QCOMPARE(obj.callCount, 1);
    QCOMPARE(obj.lastMessage.service(), con.baseService());
    QCOMPARE(obj.lastMessage.interface(), QString());
    QCOMPARE(obj.lastMessage.path(), path);
    QCOMPARE(obj.replyArguments, reply.arguments());

    obj.replyArguments << QString("alien abduction");
    QDBusMessage subPathMessage = QDBusMessage::createMethodCall(con.baseService(), childPath, QString(), "hello");
    QDBusMessage subPathReply = con.call(subPathMessage , QDBus::Block, 5000);
    QCOMPARE(obj.callCount, 2);
    QCOMPARE(obj.lastMessage.service(), con.baseService());
    QCOMPARE(obj.lastMessage.interface(), QString());
    QCOMPARE(obj.lastMessage.path(), childPath);
    QCOMPARE(obj.replyArguments, subPathReply.arguments());
}

QString MyObject::path;
QTEST_MAIN(tst_QDBusConnection)

#include "tst_qdbusconnection.moc"