Debian Codegraph @

tests/auto/network/kernel/qhostinfo/tst_qhostinfo.cpp

raw
1 /****************************************************************************
2 **
3 ** Copyright (C) 2016 The Qt Company Ltd.
4 ** Copyright (C) 2016 Intel Corporation.
5 ** Contact: https://www.qt.io/licensing/
6 **
7 ** This file is part of the test suite of the Qt Toolkit.
8 **
9 ** $QT_BEGIN_LICENSE:GPL-EXCEPT$
10 ** Commercial License Usage
11 ** Licensees holding valid commercial Qt licenses may use this file in
12 ** accordance with the commercial license agreement provided with the
13 ** Software or, alternatively, in accordance with the terms contained in
14 ** a written agreement between you and The Qt Company. For licensing terms
15 ** and conditions see https://www.qt.io/terms-conditions. For further
16 ** information use the contact form at https://www.qt.io/contact-us.
17 **
18 ** GNU General Public License Usage
19 ** Alternatively, this file may be used under the terms of the GNU
20 ** General Public License version 3 as published by the Free Software
21 ** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
22 ** included in the packaging of this file. Please review the following
23 ** information to ensure the GNU General Public License requirements will
24 ** be met: https://www.gnu.org/licenses/gpl-3.0.html.
25 **
26 ** $QT_END_LICENSE$
27 **
28 ****************************************************************************/
29
30
31 // When using WinSock2 on Windows, it's the first thing that can be included
32 // (except qglobal.h), or else you'll get tons of compile errors
33 #include <qglobal.h>
34
35 // To prevent windows system header files from re-defining min/max
36 #define NOMINMAX 1
37
38 #if defined(Q_OS_WIN)
39 # include <winsock2.h>
40 # include <ws2tcpip.h>
41 #endif
42
43 #include <QtTest/QtTest>
44 #include <qcoreapplication.h>
45 #include <QDebug>
46 #include <QTcpSocket>
47 #include <private/qthread_p.h>
48 #include <QTcpServer>
49
50 #ifndef QT_NO_BEARERMANAGEMENT
51 #include <QtNetwork/qnetworkconfigmanager.h>
52 #include <QtNetwork/qnetworkconfiguration.h>
53 #include <QtNetwork/qnetworksession.h>
54 #endif
55
56 #include <time.h>
57 #if defined(Q_OS_WIN)
58 #include <windows.h>
59 #else
60 #include <unistd.h>
61 #include <signal.h>
62 #endif
63
64 #include <qhostinfo.h>
65 #include "private/qhostinfo_p.h"
66
67 #include <sys/types.h>
68 #if defined(Q_OS_UNIX)
69 # include <sys/socket.h>
70 # include <netdb.h>
71 #endif
72
73 #include "../../../network-settings.h"
74
75 #define TEST_DOMAIN ".test.qt-project.org"
76
77 class tst_QHostInfo : public QObject
78 {
79 Q_OBJECT
80
81 private slots:
82 void init();
83 void initTestCase();
84 void swapFunction();
85 void moveOperator();
86 void getSetCheck();
87 void staticInformation();
88 void lookupIPv4_data();
89 void lookupIPv4();
90 void lookupIPv6_data();
91 void lookupIPv6();
92 void lookupConnectToFunctionPointer_data();
93 void lookupConnectToFunctionPointer();
94 void lookupConnectToFunctionPointerDeleted();
95 void lookupConnectToLambda_data();
96 void lookupConnectToLambda();
97 void reverseLookup_data();
98 void reverseLookup();
99
100 void blockingLookup_data();
101 void blockingLookup();
102
103 void raceCondition();
104 void threadSafety();
105 void threadSafetyAsynchronousAPI();
106
107 void multipleSameLookups();
108 void multipleDifferentLookups_data();
109 void multipleDifferentLookups();
110
111 void cache();
112
113 void abortHostLookup();
114 protected slots:
115 void resultsReady(const QHostInfo &);
116
117 private:
118 bool ipv6LookupsAvailable;
119 bool ipv6Available;
120 bool lookupDone;
121 int lookupsDoneCounter;
122 QHostInfo lookupResults;
123 #ifndef QT_NO_BEARERMANAGEMENT
124 QNetworkConfigurationManager *netConfMan;
125 QNetworkConfiguration networkConfiguration;
126 QScopedPointer<QNetworkSession> networkSession;
127 #endif
128 };
129
130 void tst_QHostInfo::swapFunction()
131 {
132 QHostInfo obj1, obj2;
133 obj1.setError(QHostInfo::HostInfoError(0));
134 obj2.setError(QHostInfo::HostInfoError(1));
135 obj1.swap(obj2);
136 QCOMPARE(QHostInfo::HostInfoError(0), obj2.error());
137 QCOMPARE(QHostInfo::HostInfoError(1), obj1.error());
138 }
139
140 void tst_QHostInfo::moveOperator()
141 {
142 QHostInfo obj1, obj2, obj3(1);
143 obj1.setError(QHostInfo::HostInfoError(0));
144 obj2.setError(QHostInfo::HostInfoError(1));
145 obj1 = std::move(obj2);
146 obj2 = obj3;
147 QCOMPARE(QHostInfo::HostInfoError(1), obj1.error());
148 QCOMPARE(obj3.lookupId(), obj2.lookupId());
149 }
150
151
152
153 // Testing get/set functions
154 void tst_QHostInfo::getSetCheck()
155 {
156 QHostInfo obj1;
157 // HostInfoError QHostInfo::error()
158 // void QHostInfo::setError(HostInfoError)
159 obj1.setError(QHostInfo::HostInfoError(0));
160 QCOMPARE(QHostInfo::HostInfoError(0), obj1.error());
161 obj1.setError(QHostInfo::HostInfoError(1));
162 QCOMPARE(QHostInfo::HostInfoError(1), obj1.error());
163
164 // int QHostInfo::lookupId()
165 // void QHostInfo::setLookupId(int)
166 obj1.setLookupId(0);
167 QCOMPARE(0, obj1.lookupId());
168 obj1.setLookupId(INT_MIN);
169 QCOMPARE(INT_MIN, obj1.lookupId());
170 obj1.setLookupId(INT_MAX);
171 QCOMPARE(INT_MAX, obj1.lookupId());
172 }
173
174 void tst_QHostInfo::staticInformation()
175 {
176 qDebug() << "Hostname:" << QHostInfo::localHostName();
177 qDebug() << "Domain name:" << QHostInfo::localDomainName();
178 }
179
180 void tst_QHostInfo::initTestCase()
181 {
182 #ifndef QT_NO_BEARERMANAGEMENT
183 //start the default network
184 netConfMan = new QNetworkConfigurationManager(this);
185 networkConfiguration = netConfMan->defaultConfiguration();
186 networkSession.reset(new QNetworkSession(networkConfiguration));
187 if (!networkSession->isOpen()) {
188 networkSession->open();
189 networkSession->waitForOpened(30000);
190 }
191 #endif
192
193 ipv6Available = false;
194 ipv6LookupsAvailable = false;
195
196 QTcpServer server;
197 if (server.listen(QHostAddress("::1"))) {
198 // We have IPv6 support
199 ipv6Available = true;
200 }
201
202 // check if the system getaddrinfo can do IPv6 lookups
203 struct addrinfo hint, *result = 0;
204 memset(&hint, 0, sizeof hint);
205 hint.ai_family = AF_UNSPEC;
206 #ifdef AI_ADDRCONFIG
207 hint.ai_flags = AI_ADDRCONFIG;
208 #endif
209
210 int res = getaddrinfo("::1", "80", &hint, &result);
211 if (res == 0) {
212 // this test worked
213 freeaddrinfo(result);
214 res = getaddrinfo("aaaa-single" TEST_DOMAIN, "80", &hint, &result);
215 if (res == 0 && result != 0 && result->ai_family != AF_INET) {
216 freeaddrinfo(result);
217 ipv6LookupsAvailable = true;
218 }
219 }
220
221 // run each testcase with and without test enabled
222 QTest::addColumn<bool>("cache");
223 QTest::newRow("WithCache") << true;
224 QTest::newRow("WithoutCache") << false;
225 }
226
227 void tst_QHostInfo::init()
228 {
229 // delete the cache so inidividual testcase results are independent from each other
230 qt_qhostinfo_clear_cache();
231
232 QFETCH_GLOBAL(bool, cache);
233 qt_qhostinfo_enable_cache(cache);
234 }
235
236 void tst_QHostInfo::lookupIPv4_data()
237 {
238 QTest::addColumn<QString>("hostname");
239 QTest::addColumn<QString>("addresses");
240 QTest::addColumn<int>("err");
241
242 QTest::newRow("empty") << "" << "" << int(QHostInfo::HostNotFound);
243
244 QTest::newRow("single_ip4") << "a-single" TEST_DOMAIN << "192.0.2.1" << int(QHostInfo::NoError);
245 QTest::newRow("multiple_ip4") << "a-multi" TEST_DOMAIN << "192.0.2.1 192.0.2.2 192.0.2.3" << int(QHostInfo::NoError);
246 QTest::newRow("literal_ip4") << "192.0.2.1" << "192.0.2.1" << int(QHostInfo::NoError);
247
248 QTest::newRow("notfound") << "invalid" TEST_DOMAIN << "" << int(QHostInfo::HostNotFound);
249
250 QTest::newRow("idn-ace") << "a-single.xn--alqualond-34a" TEST_DOMAIN << "192.0.2.1" << int(QHostInfo::NoError);
251 QTest::newRow("idn-unicode") << QString::fromLatin1("a-single.alqualond\353" TEST_DOMAIN) << "192.0.2.1" << int(QHostInfo::NoError);
252 }
253
254 void tst_QHostInfo::lookupIPv4()
255 {
256 QFETCH(QString, hostname);
257 QFETCH(int, err);
258 QFETCH(QString, addresses);
259
260 lookupDone = false;
261 QHostInfo::lookupHost(hostname, this, SLOT(resultsReady(QHostInfo)));
262
263 QTestEventLoop::instance().enterLoop(10);
264 QVERIFY(!QTestEventLoop::instance().timeout());
265 QVERIFY(lookupDone);
266
267 if ((int)lookupResults.error() != (int)err) {
268 qWarning() << hostname << "=>" << lookupResults.errorString();
269 }
270 QCOMPARE((int)lookupResults.error(), (int)err);
271
272 QStringList tmp;
273 for (int i = 0; i < lookupResults.addresses().count(); ++i)
274 tmp.append(lookupResults.addresses().at(i).toString());
275 tmp.sort();
276
277 QStringList expected = addresses.split(' ');
278 expected.sort();
279
280 QCOMPARE(tmp.join(' '), expected.join(' '));
281 }
282
283 void tst_QHostInfo::lookupIPv6_data()
284 {
285 QTest::addColumn<QString>("hostname");
286 QTest::addColumn<QString>("addresses");
287 QTest::addColumn<int>("err");
288
289 QTest::newRow("aaaa-single") << "aaaa-single" TEST_DOMAIN << "2001:db8::1" << int(QHostInfo::NoError);
290 QTest::newRow("aaaa-multi") << "aaaa-multi" TEST_DOMAIN << "2001:db8::1 2001:db8::2 2001:db8::3" << int(QHostInfo::NoError);
291 QTest::newRow("a-plus-aaaa") << "a-plus-aaaa" TEST_DOMAIN << "198.51.100.1 2001:db8::1:1" << int(QHostInfo::NoError);
292
293 // avoid using real IPv6 addresses here because this will do a DNS query
294 // real addresses are between 2000:: and 3fff:ffff:ffff:ffff:ffff:ffff:ffff
295 QTest::newRow("literal_ip6") << "f001:6b0:1:ea:202:a5ff:fecd:13a6" << "f001:6b0:1:ea:202:a5ff:fecd:13a6" << int(QHostInfo::NoError);
296 QTest::newRow("literal_shortip6") << "f001:618:1401::4" << "f001:618:1401::4" << int(QHostInfo::NoError);
297 }
298
299 void tst_QHostInfo::lookupIPv6()
300 {
301 QFETCH(QString, hostname);
302 QFETCH(int, err);
303 QFETCH(QString, addresses);
304
305 if (!ipv6LookupsAvailable)
306 QSKIP("This platform does not support IPv6 lookups");
307
308 lookupDone = false;
309 QHostInfo::lookupHost(hostname, this, SLOT(resultsReady(QHostInfo)));
310
311 QTestEventLoop::instance().enterLoop(10);
312 QVERIFY(!QTestEventLoop::instance().timeout());
313 QVERIFY(lookupDone);
314
315 QCOMPARE((int)lookupResults.error(), (int)err);
316
317 QStringList tmp;
318 for (int i = 0; i < lookupResults.addresses().count(); ++i)
319 tmp.append(lookupResults.addresses().at(i).toString());
320 tmp.sort();
321
322 QStringList expected = addresses.split(' ');
323 expected.sort();
324
325 QCOMPARE(tmp.join(' ').toLower(), expected.join(' ').toLower());
326 }
327
328 void tst_QHostInfo::lookupConnectToFunctionPointer_data()
329 {
330 lookupIPv4_data();
331 }
332
333 void tst_QHostInfo::lookupConnectToFunctionPointer()
334 {
335 QFETCH(QString, hostname);
336 QFETCH(int, err);
337 QFETCH(QString, addresses);
338
339 lookupDone = false;
340 QHostInfo::lookupHost(hostname, this, &tst_QHostInfo::resultsReady);
341
342 QTestEventLoop::instance().enterLoop(10);
343 QVERIFY(!QTestEventLoop::instance().timeout());
344 QVERIFY(lookupDone);
345
346 if (int(lookupResults.error()) != int(err))
347 qWarning() << hostname << "=>" << lookupResults.errorString();
348 QCOMPARE(int(lookupResults.error()), int(err));
349
350 QStringList tmp;
351 for (const auto &result : lookupResults.addresses())
352 tmp.append(result.toString());
353 tmp.sort();
354
355 QStringList expected = addresses.split(' ');
356 expected.sort();
357
358 QCOMPARE(tmp.join(' '), expected.join(' '));
359 }
360
361 void tst_QHostInfo::lookupConnectToFunctionPointerDeleted()
362 {
363 {
364 QObject contextObject;
365 QHostInfo::lookupHost("localhost", &contextObject, [](const QHostInfo){
366 QFAIL("This should never be called!");
367 });
368 }
369 QTestEventLoop::instance().enterLoop(3);
370 }
371
372 void tst_QHostInfo::lookupConnectToLambda_data()
373 {
374 lookupIPv4_data();
375 }
376
377 void tst_QHostInfo::lookupConnectToLambda()
378 {
379 QFETCH(QString, hostname);
380 QFETCH(int, err);
381 QFETCH(QString, addresses);
382
383 lookupDone = false;
384 QHostInfo::lookupHost(hostname, [=](const QHostInfo &hostInfo) {
385 resultsReady(hostInfo);
386 });
387
388 QTestEventLoop::instance().enterLoop(10);
389 QVERIFY(!QTestEventLoop::instance().timeout());
390 QVERIFY(lookupDone);
391
392 if (int(lookupResults.error()) != int(err))
393 qWarning() << hostname << "=>" << lookupResults.errorString();
394 QCOMPARE(int(lookupResults.error()), int(err));
395
396 QStringList tmp;
397 for (int i = 0; i < lookupResults.addresses().count(); ++i)
398 tmp.append(lookupResults.addresses().at(i).toString());
399 tmp.sort();
400
401 QStringList expected = addresses.split(' ');
402 expected.sort();
403
404 QCOMPARE(tmp.join(' '), expected.join(' '));
405 }
406
407 static QStringList reverseLookupHelper(const QString &ip)
408 {
409 QStringList results;
410
411 const QString pythonCode =
412 "import socket;"
413 "import sys;"
414 "print (socket.getnameinfo((sys.argv[1], 0), 0)[0]);";
415
416 QList<QByteArray> lines;
417 QProcess python;
418 python.setProcessChannelMode(QProcess::ForwardedErrorChannel);
419 python.start("python", QStringList() << QString("-c") << pythonCode << ip);
420 if (python.waitForFinished()) {
421 if (python.exitStatus() == QProcess::NormalExit && python.exitCode() == 0)
422 lines = python.readAllStandardOutput().split('\n');
423 for (QByteArray line : lines) {
424 if (!line.isEmpty())
425 results << line.trimmed();
426 }
427 if (!results.isEmpty())
428 return results;
429 }
430
431 qDebug() << "Python failed, falling back to nslookup";
432 QProcess lookup;
433 lookup.setProcessChannelMode(QProcess::ForwardedErrorChannel);
434 lookup.start("nslookup", QStringList(ip));
435 if (!lookup.waitForFinished()) {
436 results << "nslookup failure";
437 qDebug() << "nslookup failure";
438 return results;
439 }
440 lines = lookup.readAllStandardOutput().split('\n');
441
442 QByteArray name;
443
444 const QByteArray nameMarkerNix("name =");
445 const QByteArray nameMarkerWin("Name:");
446 const QByteArray addressMarkerWin("Address:");
447
448 for (QByteArray line : lines) {
449 int index = -1;
450 if ((index = line.indexOf(nameMarkerNix)) != -1) { // Linux and macOS
451 name = line.mid(index + nameMarkerNix.length()).chopped(1).trimmed();
452 results << name;
453 } else if (line.startsWith(nameMarkerWin)) { // Windows formatting
454 name = line.mid(line.lastIndexOf(" ")).trimmed();
455 } else if (line.startsWith(addressMarkerWin)) {
456 QByteArray address = line.mid(addressMarkerWin.length()).trimmed();
457 if (address == ip.toUtf8()) {
458 results << name;
459 }
460 }
461 }
462
463 if (results.isEmpty()) {
464 qDebug() << "Failure to parse nslookup output: " << lines;
465 }
466 return results;
467 }
468
469 void tst_QHostInfo::reverseLookup_data()
470 {
471 QTest::addColumn<QString>("address");
472 QTest::addColumn<QStringList>("hostNames");
473 QTest::addColumn<int>("err");
474 QTest::addColumn<bool>("ipv6");
475
476 QTest::newRow("dns.google") << QString("8.8.8.8") << reverseLookupHelper("8.8.8.8") << 0 << false;
477 QTest::newRow("one.one.one.one") << QString("1.1.1.1") << reverseLookupHelper("1.1.1.1") << 0 << false;
478 QTest::newRow("dns.google IPv6") << QString("2001:4860:4860::8888") << reverseLookupHelper("2001:4860:4860::8888") << 0 << true;
479 QTest::newRow("cloudflare IPv6") << QString("2606:4700:4700::1111") << reverseLookupHelper("2606:4700:4700::1111") << 0 << true;
480 QTest::newRow("bogus-name IPv6") << QString("1::2::3::4") << QStringList() << 1 << true;
481 }
482
483 void tst_QHostInfo::reverseLookup()
484 {
485 QFETCH(QString, address);
486 QFETCH(QStringList, hostNames);
487 QFETCH(int, err);
488 QFETCH(bool, ipv6);
489
490 if (ipv6 && !ipv6LookupsAvailable) {
491 QSKIP("IPv6 reverse lookups are not supported on this platform");
492 }
493
494 QHostInfo info = QHostInfo::fromName(address);
495
496 if (err == 0) {
497 if (!hostNames.contains(info.hostName()))
498 qDebug() << "Failure: expecting" << hostNames << ",got " << info.hostName();
499 QVERIFY(hostNames.contains(info.hostName()));
500 QCOMPARE(info.addresses().first(), QHostAddress(address));
501 } else {
502 QCOMPARE(info.hostName(), address);
503 QCOMPARE(info.error(), QHostInfo::HostNotFound);
504 }
505
506 }
507
508 void tst_QHostInfo::blockingLookup_data()
509 {
510 lookupIPv4_data();
511 if (ipv6LookupsAvailable)
512 lookupIPv6_data();
513 }
514
515 void tst_QHostInfo::blockingLookup()
516 {
517 QFETCH(QString, hostname);
518 QFETCH(int, err);
519 QFETCH(QString, addresses);
520
521 QHostInfo hostInfo = QHostInfo::fromName(hostname);
522 QStringList tmp;
523 for (int i = 0; i < hostInfo.addresses().count(); ++i)
524 tmp.append(hostInfo.addresses().at(i).toString());
525 tmp.sort();
526
527 if ((int)hostInfo.error() != (int)err) {
528 qWarning() << hostname << "=>" << lookupResults.errorString();
529 }
530 QCOMPARE((int)hostInfo.error(), (int)err);
531
532 QStringList expected = addresses.split(' ');
533 expected.sort();
534
535 QCOMPARE(tmp.join(' ').toUpper(), expected.join(' ').toUpper());
536 }
537
538 void tst_QHostInfo::raceCondition()
539 {
540 for (int i = 0; i < 1000; ++i) {
541 QTcpSocket socket;
542 socket.connectToHost("invalid" TEST_DOMAIN, 80);
543 }
544 }
545
546 class LookupThread : public QThread
547 {
548 protected:
549 inline void run()
550 {
551 QHostInfo info = QHostInfo::fromName("a-single" TEST_DOMAIN);
552 QCOMPARE(info.error(), QHostInfo::NoError);
553 QVERIFY(info.addresses().count() > 0);
554 QCOMPARE(info.addresses().at(0).toString(), QString("192.0.2.1"));
555 }
556 };
557
558 void tst_QHostInfo::threadSafety()
559 {
560 const int nattempts = 5;
561 const int runs = 100;
562 LookupThread thr[nattempts];
563 for (int j = 0; j < runs; ++j) {
564 for (int i = 0; i < nattempts; ++i)
565 thr[i].start();
566 for (int k = nattempts - 1; k >= 0; --k)
567 thr[k].wait();
568 }
569 }
570
571 class LookupReceiver : public QObject
572 {
573 Q_OBJECT
574 public slots:
575 void start();
576 void resultsReady(const QHostInfo&);
577 public:
578 QHostInfo result;
579 int numrequests;
580 };
581
582 void LookupReceiver::start()
583 {
584 for (int i=0;i<numrequests;i++)
585 QHostInfo::lookupHost(QString("a-single" TEST_DOMAIN), this, SLOT(resultsReady(QHostInfo)));
586 }
587
588 void LookupReceiver::resultsReady(const QHostInfo &info)
589 {
590 result = info;
591 numrequests--;
592 if (numrequests == 0 || info.error() != QHostInfo::NoError)
593 QThread::currentThread()->quit();
594 }
595
596 void tst_QHostInfo::threadSafetyAsynchronousAPI()
597 {
598 const int nattempts = 10;
599 const int lookupsperthread = 10;
600 QThread threads[nattempts];
601 LookupReceiver receivers[nattempts];
602 for (int i = 0; i < nattempts; ++i) {
603 QThread *thread = &threads[i];
604 LookupReceiver *receiver = &receivers[i];
605 receiver->numrequests = lookupsperthread;
606 receiver->moveToThread(thread);
607 connect(thread, SIGNAL(started()), receiver, SLOT(start()));
608 thread->start();
609 }
610 for (int k = nattempts - 1; k >= 0; --k)
611 QVERIFY(threads[k].wait(60000));
612 for (LookupReceiver &receiver : receivers) {
613 QCOMPARE(receiver.result.error(), QHostInfo::NoError);
614 QCOMPARE(receiver.result.addresses().at(0).toString(), QString("192.0.2.1"));
615 QCOMPARE(receiver.numrequests, 0);
616 }
617 }
618
619 // this test is for the multi-threaded QHostInfo rewrite. It is about getting results at all,
620 // not about getting correct IPs
621 void tst_QHostInfo::multipleSameLookups()
622 {
623 const int COUNT = 10;
624 lookupsDoneCounter = 0;
625
626 for (int i = 0; i < COUNT; i++)
627 QHostInfo::lookupHost("localhost", this, SLOT(resultsReady(QHostInfo)));
628
629 QElapsedTimer timer;
630 timer.start();
631 while (timer.elapsed() < 10000 && lookupsDoneCounter < COUNT) {
632 QTestEventLoop::instance().enterLoop(2);
633 }
634 QCOMPARE(lookupsDoneCounter, COUNT);
635 }
636
637 // this test is for the multi-threaded QHostInfo rewrite. It is about getting results at all,
638 // not about getting correct IPs
639 void tst_QHostInfo::multipleDifferentLookups_data()
640 {
641 QTest::addColumn<int>("repeats");
642 QTest::newRow("1") << 1;
643 QTest::newRow("2") << 2;
644 QTest::newRow("5") << 5;
645 QTest::newRow("10") << 10;
646 }
647
648 void tst_QHostInfo::multipleDifferentLookups()
649 {
650 QStringList hostnameList;
651 hostnameList << "a-single" TEST_DOMAIN
652 << "a-multi" TEST_DOMAIN
653 << "aaaa-single" TEST_DOMAIN
654 << "aaaa-multi" TEST_DOMAIN
655 << "a-plus-aaaa" TEST_DOMAIN
656 << "multi" TEST_DOMAIN
657 << "localhost" TEST_DOMAIN
658 << "cname" TEST_DOMAIN
659 << "127.0.0.1" << "----";
660
661 QFETCH(int, repeats);
662 const int COUNT = hostnameList.size();
663 lookupsDoneCounter = 0;
664
665 for (int i = 0; i < hostnameList.size(); i++)
666 for (int j = 0; j < repeats; ++j)
667 QHostInfo::lookupHost(hostnameList.at(i), this, SLOT(resultsReady(QHostInfo)));
668
669 QElapsedTimer timer;
670 timer.start();
671 while (timer.elapsed() < 60000 && lookupsDoneCounter < repeats*COUNT) {
672 QTestEventLoop::instance().enterLoop(2);
673 //qDebug() << "t:" << timer.elapsed();
674 }
675 QCOMPARE(lookupsDoneCounter, repeats*COUNT);
676 }
677
678 void tst_QHostInfo::cache()
679 {
680 QFETCH_GLOBAL(bool, cache);
681 if (!cache)
682 return; // test makes only sense when cache enabled
683
684 // reset slot counter
685 lookupsDoneCounter = 0;
686
687 // lookup once, wait in event loop, result should not come directly.
688 bool valid = true;
689 int id = -1;
690 QHostInfo result = qt_qhostinfo_lookup("localhost", this, SLOT(resultsReady(QHostInfo)), &valid, &id);
691 QTestEventLoop::instance().enterLoop(5);
692 QVERIFY(!QTestEventLoop::instance().timeout());
693 QVERIFY(!valid);
694 QVERIFY(result.addresses().isEmpty());
695
696 // loopkup second time, result should come directly
697 valid = false;
698 result = qt_qhostinfo_lookup("localhost", this, SLOT(resultsReady(QHostInfo)), &valid, &id);
699 QVERIFY(valid);
700 QVERIFY(!result.addresses().isEmpty());
701
702 // clear the cache
703 qt_qhostinfo_clear_cache();
704
705 // lookup third time, result should not come directly.
706 valid = true;
707 result = qt_qhostinfo_lookup("localhost", this, SLOT(resultsReady(QHostInfo)), &valid, &id);
708 QTestEventLoop::instance().enterLoop(5);
709 QVERIFY(!QTestEventLoop::instance().timeout());
710 QVERIFY(!valid);
711 QVERIFY(result.addresses().isEmpty());
712
713 // the slot should have been called 2 times.
714 QCOMPARE(lookupsDoneCounter, 2);
715 }
716
717 void tst_QHostInfo::resultsReady(const QHostInfo &hi)
718 {
719 QVERIFY(QThread::currentThread() == thread());
720 lookupDone = true;
721 lookupResults = hi;
722 lookupsDoneCounter++;
723 QTestEventLoop::instance().exitLoop();
724 }
725
726 void tst_QHostInfo::abortHostLookup()
727 {
728 //reset counter
729 lookupsDoneCounter = 0;
730 bool valid = false;
731 int id = -1;
732 QHostInfo result = qt_qhostinfo_lookup("a-single" TEST_DOMAIN, this, SLOT(resultsReady(QHostInfo)), &valid, &id);
733 QVERIFY(!valid);
734 //it is assumed that the DNS request/response in the backend is slower than it takes to call abort
735 QHostInfo::abortHostLookup(id);
736 QTestEventLoop::instance().enterLoop(5);
737 QCOMPARE(lookupsDoneCounter, 0);
738 }
739
740 class LookupAborter : public QObject
741 {
742 Q_OBJECT
743 public slots:
744 void abort()
745 {
746 QHostInfo::abortHostLookup(id);
747 QThread::currentThread()->quit();
748 }
749 public:
750 int id;
751 };
752
753 QTEST_MAIN(tst_QHostInfo)
754 #include "tst_qhostinfo.moc"