| 1 |
/**************************************************************************** |
| 2 |
** |
| 3 |
** Copyright (C) 2016 The Qt Company Ltd. |
| 4 |
** Contact: https://www.qt.io/licensing/ |
| 5 |
** |
| 6 |
** This file is part of the test suite of the Qt Toolkit. |
| 7 |
** |
| 8 |
** $QT_BEGIN_LICENSE:GPL-EXCEPT$ |
| 9 |
** Commercial License Usage |
| 10 |
** Licensees holding valid commercial Qt licenses may use this file in |
| 11 |
** accordance with the commercial license agreement provided with the |
| 12 |
** Software or, alternatively, in accordance with the terms contained in |
| 13 |
** a written agreement between you and The Qt Company. For licensing terms |
| 14 |
** and conditions see https://www.qt.io/terms-conditions. For further |
| 15 |
** information use the contact form at https://www.qt.io/contact-us. |
| 16 |
** |
| 17 |
** GNU General Public License Usage |
| 18 |
** Alternatively, this file may be used under the terms of the GNU |
| 19 |
** General Public License version 3 as published by the Free Software |
| 20 |
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT |
| 21 |
** included in the packaging of this file. Please review the following |
| 22 |
** information to ensure the GNU General Public License requirements will |
| 23 |
** be met: https://www.gnu.org/licenses/gpl-3.0.html. |
| 24 |
** |
| 25 |
** $QT_END_LICENSE$ |
| 26 |
** |
| 27 |
****************************************************************************/ |
| 28 |
|
| 29 |
|
| 30 |
#include <QtTest/QtTest> |
| 31 |
#include <QtCore/QCryptographicHash> |
| 32 |
#include <QtCore/QDataStream> |
| 33 |
#include <QtCore/QUrl> |
| 34 |
#include <QtCore/QEventLoop> |
| 35 |
#include <QtCore/QElapsedTimer> |
| 36 |
#include <QtCore/QFile> |
| 37 |
#include <QtCore/QRandomGenerator> |
| 38 |
#include <QtCore/QRegularExpression> |
| 39 |
#include <QtCore/QRegularExpressionMatch> |
| 40 |
#include <QtCore/QSharedPointer> |
| 41 |
#include <QtCore/QScopedPointer> |
| 42 |
#include <QtCore/QTemporaryFile> |
| 43 |
#include <QtNetwork/QTcpServer> |
| 44 |
#include <QtNetwork/QTcpSocket> |
| 45 |
#include <QtNetwork/QLocalSocket> |
| 46 |
#include <QtNetwork/QLocalServer> |
| 47 |
#include <QtNetwork/QHostInfo> |
| 48 |
#include <QtNetwork/QNetworkAccessManager> |
| 49 |
#include <QtNetwork/QNetworkRequest> |
| 50 |
#include <QtNetwork/QNetworkReply> |
| 51 |
#include <QtNetwork/QAbstractNetworkCache> |
| 52 |
#include <QtNetwork/qauthenticator.h> |
| 53 |
#include <QtNetwork/qnetworkaccessmanager.h> |
| 54 |
#include <QtNetwork/qnetworkdiskcache.h> |
| 55 |
#include <QtNetwork/qnetworkrequest.h> |
| 56 |
#include <QtNetwork/qnetworkreply.h> |
| 57 |
#include <QtNetwork/qnetworkcookie.h> |
| 58 |
#include <QtNetwork/QNetworkCookieJar> |
| 59 |
#include <QtNetwork/QHttpPart> |
| 60 |
#include <QtNetwork/QHttpMultiPart> |
| 61 |
#include <QtNetwork/QNetworkProxyQuery> |
| 62 |
#ifndef QT_NO_SSL |
| 63 |
#include <QtNetwork/qsslerror.h> |
| 64 |
#include <QtNetwork/qsslconfiguration.h> |
| 65 |
#ifdef QT_BUILD_INTERNAL |
| 66 |
#include <QtNetwork/private/qsslconfiguration_p.h> |
| 67 |
#endif |
| 68 |
#endif |
| 69 |
#ifndef QT_NO_BEARERMANAGEMENT |
| 70 |
#include <QtNetwork/qnetworkconfigmanager.h> |
| 71 |
#include <QtNetwork/qnetworkconfiguration.h> |
| 72 |
#include <QtNetwork/qnetworksession.h> |
| 73 |
#include <QtNetwork/private/qnetworksession_p.h> |
| 74 |
#endif |
| 75 |
#ifdef QT_BUILD_INTERNAL |
| 76 |
#include <QtNetwork/private/qnetworkreplyimpl_p.h> // implicitly included by qnetworkaccessmanager_p.h currently, but don't rely on that being true forever |
| 77 |
#include <QtNetwork/private/qnetworkaccessmanager_p.h> |
| 78 |
#else |
| 79 |
Q_DECLARE_METATYPE(QSharedPointer<char>) |
| 80 |
#endif |
| 81 |
|
| 82 |
#ifdef Q_OS_UNIX |
| 83 |
# include <sys/types.h> |
| 84 |
# include <unistd.h> // for getuid() |
| 85 |
#endif |
| 86 |
#include <time.h> |
| 87 |
|
| 88 |
#include "../../../network-settings.h" |
| 89 |
|
| 90 |
// Non-OpenSSL backends are not able to report a specific error code |
| 91 |
// for self-signed certificates. |
| 92 |
#ifndef QT_NO_OPENSSL |
| 93 |
#define FLUKE_CERTIFICATE_ERROR QSslError::SelfSignedCertificate |
| 94 |
#else |
| 95 |
#define FLUKE_CERTIFICATE_ERROR QSslError::CertificateUntrusted |
| 96 |
#endif |
| 97 |
|
| 98 |
Q_DECLARE_METATYPE(QAuthenticator*) |
| 99 |
#ifndef QT_NO_NETWORKPROXY |
| 100 |
Q_DECLARE_METATYPE(QNetworkProxyQuery) |
| 101 |
#endif |
| 102 |
|
| 103 |
#include "emulationdetector.h" |
| 104 |
|
| 105 |
typedef QSharedPointer<QNetworkReply> QNetworkReplyPtr; |
| 106 |
|
| 107 |
#ifndef QT_NO_OPENSSL |
| 108 |
QT_BEGIN_NAMESPACE |
| 109 |
void qt_ForceTlsSecurityLevel(); |
| 110 |
QT_END_NAMESPACE |
| 111 |
#endif |
| 112 |
|
| 113 |
class MyCookieJar; |
| 114 |
class tst_QNetworkReply: public QObject |
| 115 |
{ |
| 116 |
Q_OBJECT |
| 117 |
|
| 118 |
#ifndef QT_NO_NETWORKPROXY |
| 119 |
struct ProxyData |
| 120 |
{ |
| 121 |
ProxyData(const QNetworkProxy &p, const QByteArray &t, bool auth) |
| 122 |
: tag(t), proxy(p), requiresAuthentication(auth) {} |
| 123 |
QByteArray tag; |
| 124 |
QNetworkProxy proxy; |
| 125 |
bool requiresAuthentication; |
| 126 |
}; |
| 127 |
#endif // !QT_NO_NETWORKPROXY |
| 128 |
|
| 129 |
static bool seedCreated; |
| 130 |
static QString createUniqueExtension() |
| 131 |
{ |
| 132 |
if (!seedCreated) { |
| 133 |
seedCreated = true; // not thread-safe, but who cares |
| 134 |
} |
| 135 |
return QString::number(QTime::currentTime().msecsSinceStartOfDay()) |
| 136 |
+ QLatin1Char('-') + QString::number(QCoreApplication::applicationPid()) |
| 137 |
+ QLatin1Char('-') + QString::number(QRandomGenerator::global()->generate()); |
| 138 |
} |
| 139 |
|
| 140 |
static QString tempRedirectReplyStr() { |
| 141 |
QString s = "HTTP/1.1 307 Temporary Redirect\r\n" |
| 142 |
"Content-Type: text/plain\r\n" |
| 143 |
"location: %1\r\n" |
| 144 |
"\r\n"; |
| 145 |
return s; |
| 146 |
} |
| 147 |
|
| 148 |
static const QByteArray httpEmpty200Response; |
| 149 |
static const QString filePermissionFileName; |
| 150 |
|
| 151 |
QEventLoop *loop; |
| 152 |
enum RunSimpleRequestReturn { Timeout = 0, Success, Failure }; |
| 153 |
int returnCode; |
| 154 |
QString testFileName; |
| 155 |
QString echoProcessDir; |
| 156 |
#if !defined Q_OS_WIN |
| 157 |
QString wronlyFileName; |
| 158 |
#endif |
| 159 |
QString uniqueExtension; |
| 160 |
#ifndef QT_NO_NETWORKPROXY |
| 161 |
QList<ProxyData> proxies; |
| 162 |
#endif |
| 163 |
QNetworkAccessManager manager; |
| 164 |
MyCookieJar *cookieJar; |
| 165 |
#ifndef QT_NO_SSL |
| 166 |
QSslConfiguration storedSslConfiguration; |
| 167 |
QList<QSslError> storedExpectedSslErrors; |
| 168 |
static const QString certsFilePath; |
| 169 |
#endif |
| 170 |
#ifndef QT_NO_BEARERMANAGEMENT |
| 171 |
QNetworkConfigurationManager *netConfMan; |
| 172 |
QNetworkConfiguration networkConfiguration; |
| 173 |
QScopedPointer<QNetworkSession> networkSession; |
| 174 |
#endif |
| 175 |
|
| 176 |
using QObject::connect; |
| 177 |
static bool connect(const QNetworkReplyPtr &ptr, const char *signal, const QObject *receiver, const char *slot, Qt::ConnectionType ct = Qt::AutoConnection) |
| 178 |
{ return connect(ptr.data(), signal, receiver, slot, ct); } |
| 179 |
bool connect(const QNetworkReplyPtr &ptr, const char *signal, const char *slot, Qt::ConnectionType ct = Qt::AutoConnection) |
| 180 |
{ return connect(ptr.data(), signal, slot, ct); } |
| 181 |
|
| 182 |
public: |
| 183 |
tst_QNetworkReply(); |
| 184 |
~tst_QNetworkReply(); |
| 185 |
QString runSimpleRequest(QNetworkAccessManager::Operation op, const QNetworkRequest &request, |
| 186 |
QNetworkReplyPtr &reply, const QByteArray &data = QByteArray()); |
| 187 |
QString runMultipartRequest(const QNetworkRequest &request, QNetworkReplyPtr &reply, |
| 188 |
QHttpMultiPart *multiPart, const QByteArray &verb); |
| 189 |
|
| 190 |
QString runCustomRequest(const QNetworkRequest &request, QNetworkReplyPtr &reply, |
| 191 |
const QByteArray &verb, QIODevice *data); |
| 192 |
int waitForFinish(QNetworkReplyPtr &reply); |
| 193 |
|
| 194 |
public Q_SLOTS: |
| 195 |
void finished(); |
| 196 |
void gotError(); |
| 197 |
void authenticationRequired(QNetworkReply*,QAuthenticator*); |
| 198 |
void proxyAuthenticationRequired(const QNetworkProxy &,QAuthenticator*); |
| 199 |
void pipeliningHelperSlot(); |
| 200 |
void emitErrorForAllRepliesSlot(); |
| 201 |
|
| 202 |
#ifndef QT_NO_SSL |
| 203 |
void sslErrors(QNetworkReply*,const QList<QSslError> &); |
| 204 |
void storeSslConfiguration(); |
| 205 |
void ignoreSslErrorListSlot(QNetworkReply *reply, const QList<QSslError> &); |
| 206 |
#ifdef QT_BUILD_INTERNAL |
| 207 |
void sslSessionSharingHelperSlot(); |
| 208 |
#endif |
| 209 |
#endif |
| 210 |
|
| 211 |
protected Q_SLOTS: |
| 212 |
void nestedEventLoops_slot(); |
| 213 |
void notEnoughData(); |
| 214 |
|
| 215 |
private Q_SLOTS: |
| 216 |
void cleanup() { cleanupTestData(); } |
| 217 |
void initTestCase(); |
| 218 |
void cleanupTestCase(); |
| 219 |
|
| 220 |
void stateChecking(); |
| 221 |
void invalidProtocol(); |
| 222 |
void getFromData_data(); |
| 223 |
void getFromData(); |
| 224 |
void getFromFile_data(); |
| 225 |
void getFromFile(); |
| 226 |
void getFromFileSpecial_data(); |
| 227 |
void getFromFileSpecial(); |
| 228 |
void getFromFtp_data(); |
| 229 |
void getFromFtp(); |
| 230 |
void getFromFtpAfterError(); // QTBUG-40797 |
| 231 |
void getFromHttp_data(); |
| 232 |
void getFromHttp(); |
| 233 |
void getErrors_data(); |
| 234 |
void getErrors(); |
| 235 |
#ifndef QT_NO_NETWORKPROXY |
| 236 |
void headFromHttp_data(); |
| 237 |
void headFromHttp(); |
| 238 |
#endif // !QT_NO_NETWORKPROXY |
| 239 |
void putToFile_data(); |
| 240 |
void putToFile(); |
| 241 |
void putToFtp_data(); |
| 242 |
void putToFtp(); |
| 243 |
void putToFtpWithInvalidCredentials(); // QTBUG-40622 |
| 244 |
void putToHttp_data(); |
| 245 |
void putToHttp(); |
| 246 |
void putToHttpSynchronous_data(); |
| 247 |
void putToHttpSynchronous(); |
| 248 |
void putToHttpMultipart_data(); |
| 249 |
void putToHttpMultipart(); |
| 250 |
void postToHttp_data(); |
| 251 |
void postToHttp(); |
| 252 |
void postToHttpSynchronous_data(); |
| 253 |
void postToHttpSynchronous(); |
| 254 |
void postToHttpMultipart_data(); |
| 255 |
void postToHttpMultipart(); |
| 256 |
void multipartSkipIndices(); // QTBUG-32534 |
| 257 |
#ifndef QT_NO_SSL |
| 258 |
void putToHttps_data(); |
| 259 |
void putToHttps(); |
| 260 |
void putToHttpsSynchronous_data(); |
| 261 |
void putToHttpsSynchronous(); |
| 262 |
void postToHttps_data(); |
| 263 |
void postToHttps(); |
| 264 |
void postToHttpsSynchronous_data(); |
| 265 |
void postToHttpsSynchronous(); |
| 266 |
void postToHttpsMultipart_data(); |
| 267 |
void postToHttpsMultipart(); |
| 268 |
#endif |
| 269 |
void deleteFromHttp_data(); |
| 270 |
void deleteFromHttp(); |
| 271 |
void putGetDeleteGetFromHttp_data(); |
| 272 |
void putGetDeleteGetFromHttp(); |
| 273 |
void sendCustomRequestToHttp_data(); |
| 274 |
void sendCustomRequestToHttp(); |
| 275 |
void connectToIPv6Address_data(); |
| 276 |
void connectToIPv6Address(); |
| 277 |
|
| 278 |
void ioGetFromData_data(); |
| 279 |
void ioGetFromData(); |
| 280 |
void ioGetFromFileSpecial_data(); |
| 281 |
void ioGetFromFileSpecial(); |
| 282 |
void ioGetFromFile_data(); |
| 283 |
void ioGetFromFile(); |
| 284 |
void ioGetFromFileUrl(); |
| 285 |
void ioGetFromFtp_data(); |
| 286 |
void ioGetFromFtp(); |
| 287 |
void ioGetFromFtpWithReuse(); |
| 288 |
void ioGetFromHttp(); |
| 289 |
|
| 290 |
void ioGetFromBuiltinHttp_data(); |
| 291 |
void ioGetFromBuiltinHttp(); |
| 292 |
void ioGetFromHttpWithReuseParallel(); |
| 293 |
void ioGetFromHttpWithReuseSequential(); |
| 294 |
void ioGetFromHttpWithAuth_data(); |
| 295 |
void ioGetFromHttpWithAuth(); |
| 296 |
void ioGetFromHttpWithAuthSynchronous(); |
| 297 |
#ifndef QT_NO_NETWORKPROXY |
| 298 |
void ioGetFromHttpWithProxyAuth(); |
| 299 |
void ioGetFromHttpWithProxyAuthSynchronous(); |
| 300 |
void ioGetFromHttpWithSocksProxy(); |
| 301 |
#endif // !QT_NO_NETWORKPROXY |
| 302 |
#ifndef QT_NO_SSL |
| 303 |
void ioGetFromHttpsWithSslErrors(); |
| 304 |
void ioGetFromHttpsWithIgnoreSslErrors(); |
| 305 |
void ioGetFromHttpsWithSslHandshakeError(); |
| 306 |
#endif |
| 307 |
void ioGetFromHttpBrokenServer_data(); |
| 308 |
void ioGetFromHttpBrokenServer(); |
| 309 |
void ioGetFromHttpStatus100_data(); |
| 310 |
void ioGetFromHttpStatus100(); |
| 311 |
void ioGetFromHttpNoHeaders_data(); |
| 312 |
void ioGetFromHttpNoHeaders(); |
| 313 |
void ioGetFromHttpWithCache_data(); |
| 314 |
void ioGetFromHttpWithCache(); |
| 315 |
|
| 316 |
#ifndef QT_NO_NETWORKPROXY |
| 317 |
void ioGetWithManyProxies_data(); |
| 318 |
void ioGetWithManyProxies(); |
| 319 |
#endif // !QT_NO_NETWORKPROXY |
| 320 |
|
| 321 |
void ioPutToFileFromFile_data(); |
| 322 |
void ioPutToFileFromFile(); |
| 323 |
void ioPutToFileFromSocket_data(); |
| 324 |
void ioPutToFileFromSocket(); |
| 325 |
void ioPutToFileFromLocalSocket_data(); |
| 326 |
void ioPutToFileFromLocalSocket(); |
| 327 |
void ioPutToFileFromProcess_data(); |
| 328 |
void ioPutToFileFromProcess(); |
| 329 |
void ioPutToFtpFromFile_data(); |
| 330 |
void ioPutToFtpFromFile(); |
| 331 |
void ioPutToHttpFromFile_data(); |
| 332 |
void ioPutToHttpFromFile(); |
| 333 |
void ioPostToHttpFromFile_data(); |
| 334 |
void ioPostToHttpFromFile(); |
| 335 |
#ifndef QT_NO_NETWORKPROXY |
| 336 |
void ioPostToHttpFromSocket_data(); |
| 337 |
void ioPostToHttpFromSocket(); |
| 338 |
void ioPostToHttpFromSocketSynchronous(); |
| 339 |
void ioPostToHttpFromSocketSynchronous_data(); |
| 340 |
#endif // !QT_NO_NETWORKPROXY |
| 341 |
void ioPostToHttpFromMiddleOfFileToEnd(); |
| 342 |
void ioPostToHttpFromMiddleOfFileFiveBytes(); |
| 343 |
void ioPostToHttpFromMiddleOfQBufferFiveBytes(); |
| 344 |
void ioPostToHttpNoBufferFlag(); |
| 345 |
void ioPostToHttpUploadProgress(); |
| 346 |
void emitAllUploadProgressSignals(); |
| 347 |
void ioPostToHttpEmptyUploadProgress(); |
| 348 |
|
| 349 |
void lastModifiedHeaderForFile(); |
| 350 |
void lastModifiedHeaderForHttp(); |
| 351 |
|
| 352 |
void httpCanReadLine(); |
| 353 |
|
| 354 |
#ifdef QT_BUILD_INTERNAL |
| 355 |
void rateControl_data(); |
| 356 |
void rateControl(); |
| 357 |
#endif |
| 358 |
|
| 359 |
void downloadProgress_data(); |
| 360 |
void downloadProgress(); |
| 361 |
#ifdef QT_BUILD_INTERNAL |
| 362 |
void uploadProgress_data(); |
| 363 |
void uploadProgress(); |
| 364 |
#endif |
| 365 |
|
| 366 |
void chaining_data(); |
| 367 |
void chaining(); |
| 368 |
|
| 369 |
void receiveCookiesFromHttp_data(); |
| 370 |
void receiveCookiesFromHttp(); |
| 371 |
void receiveCookiesFromHttpSynchronous_data(); |
| 372 |
void receiveCookiesFromHttpSynchronous(); |
| 373 |
void sendCookies_data(); |
| 374 |
void sendCookies(); |
| 375 |
void sendCookiesSynchronous_data(); |
| 376 |
void sendCookiesSynchronous(); |
| 377 |
|
| 378 |
void nestedEventLoops(); |
| 379 |
|
| 380 |
#ifndef QT_NO_NETWORKPROXY |
| 381 |
void httpProxyCommands_data(); |
| 382 |
void httpProxyCommands(); |
| 383 |
void httpProxyCommandsSynchronous_data(); |
| 384 |
void httpProxyCommandsSynchronous(); |
| 385 |
void proxyChange(); |
| 386 |
#endif // !QT_NO_NETWORKPROXY |
| 387 |
void authorizationError_data(); |
| 388 |
void authorizationError(); |
| 389 |
|
| 390 |
void httpConnectionCount(); |
| 391 |
|
| 392 |
void httpReUsingConnectionSequential_data(); |
| 393 |
void httpReUsingConnectionSequential(); |
| 394 |
void httpReUsingConnectionFromFinishedSlot_data(); |
| 395 |
void httpReUsingConnectionFromFinishedSlot(); |
| 396 |
|
| 397 |
void httpRecursiveCreation(); |
| 398 |
|
| 399 |
#ifndef QT_NO_SSL |
| 400 |
void ioPostToHttpsUploadProgress(); |
| 401 |
void ignoreSslErrorsList_data(); |
| 402 |
void ignoreSslErrorsList(); |
| 403 |
void ignoreSslErrorsListWithSlot_data(); |
| 404 |
void ignoreSslErrorsListWithSlot(); |
| 405 |
void encrypted(); |
| 406 |
void abortOnEncrypted(); |
| 407 |
void sslConfiguration_data(); |
| 408 |
void sslConfiguration(); |
| 409 |
#ifdef QT_BUILD_INTERNAL |
| 410 |
void sslSessionSharing_data(); |
| 411 |
void sslSessionSharing(); |
| 412 |
void sslSessionSharingFromPersistentSession_data(); |
| 413 |
void sslSessionSharingFromPersistentSession(); |
| 414 |
#endif |
| 415 |
#endif |
| 416 |
|
| 417 |
void getAndThenDeleteObject_data(); |
| 418 |
void getAndThenDeleteObject(); |
| 419 |
|
| 420 |
void symbianOpenCDataUrlCrash(); |
| 421 |
|
| 422 |
void getFromHttpIntoBuffer_data(); |
| 423 |
void getFromHttpIntoBuffer(); |
| 424 |
void getFromHttpIntoBuffer2_data(); |
| 425 |
void getFromHttpIntoBuffer2(); |
| 426 |
void getFromHttpIntoBufferCanReadLine(); |
| 427 |
|
| 428 |
void ioGetFromHttpWithoutContentLength(); |
| 429 |
|
| 430 |
void ioGetFromHttpBrokenChunkedEncoding(); |
| 431 |
void qtbug12908compressedHttpReply(); |
| 432 |
void compressedHttpReplyBrokenGzip(); |
| 433 |
|
| 434 |
void getFromUnreachableIp(); |
| 435 |
|
| 436 |
void qtbug4121unknownAuthentication(); |
| 437 |
|
| 438 |
void qtbug13431replyThrottling(); |
| 439 |
|
| 440 |
void httpWithNoCredentialUsage(); |
| 441 |
|
| 442 |
void qtbug15311doubleContentLength(); |
| 443 |
|
| 444 |
void qtbug18232gzipContentLengthZero(); |
| 445 |
void qtbug22660gzipNoContentLengthEmptyContent(); |
| 446 |
|
| 447 |
void qtbug27161httpHeaderMayBeDamaged_data(); |
| 448 |
void qtbug27161httpHeaderMayBeDamaged(); |
| 449 |
|
| 450 |
void qtbug28035browserDoesNotLoadQtProjectOrgCorrectly(); |
| 451 |
|
| 452 |
void qtbug45581WrongReplyStatusCode(); |
| 453 |
|
| 454 |
void synchronousRequest_data(); |
| 455 |
void synchronousRequest(); |
| 456 |
#ifndef QT_NO_SSL |
| 457 |
void synchronousRequestSslFailure(); |
| 458 |
#endif |
| 459 |
|
| 460 |
void httpAbort(); |
| 461 |
|
| 462 |
void dontInsertPartialContentIntoTheCache(); |
| 463 |
|
| 464 |
void httpUserAgent(); |
| 465 |
#ifndef QT_NO_NETWORKPROXY |
| 466 |
void authenticationCacheAfterCancel_data(); |
| 467 |
void authenticationCacheAfterCancel(); |
| 468 |
void authenticationWithDifferentRealm(); |
| 469 |
#endif // !QT_NO_NETWORKPROXY |
| 470 |
void synchronousAuthenticationCache(); |
| 471 |
void pipelining(); |
| 472 |
|
| 473 |
void closeDuringDownload_data(); |
| 474 |
void closeDuringDownload(); |
| 475 |
|
| 476 |
void ftpAuthentication_data(); |
| 477 |
void ftpAuthentication(); |
| 478 |
|
| 479 |
void emitErrorForAllReplies(); // QTBUG-36890 |
| 480 |
|
| 481 |
#ifdef QT_BUILD_INTERNAL |
| 482 |
void backgroundRequest_data(); |
| 483 |
void backgroundRequest(); |
| 484 |
void backgroundRequestInterruption_data(); |
| 485 |
void backgroundRequestInterruption(); |
| 486 |
void backgroundRequestConnectInBackground_data(); |
| 487 |
void backgroundRequestConnectInBackground(); |
| 488 |
#endif |
| 489 |
|
| 490 |
void putWithRateLimiting(); |
| 491 |
|
| 492 |
void ioHttpSingleRedirect(); |
| 493 |
void ioHttpChangeMaxRedirects(); |
| 494 |
void ioHttpRedirectErrors_data(); |
| 495 |
void ioHttpRedirectErrors(); |
| 496 |
void ioHttpRedirectPolicy_data(); |
| 497 |
void ioHttpRedirectPolicy(); |
| 498 |
void ioHttpRedirectPolicyErrors_data(); |
| 499 |
void ioHttpRedirectPolicyErrors(); |
| 500 |
void ioHttpUserVerifiedRedirect_data(); |
| 501 |
void ioHttpUserVerifiedRedirect(); |
| 502 |
void ioHttpCookiesDuringRedirect(); |
| 503 |
void ioHttpRedirect_data(); |
| 504 |
void ioHttpRedirect(); |
| 505 |
void ioHttpRedirectWithCache(); |
| 506 |
void ioHttpRedirectFromLocalToRemote(); |
| 507 |
void ioHttpRedirectPostPut_data(); |
| 508 |
void ioHttpRedirectPostPut(); |
| 509 |
void ioHttpRedirectMultipartPost_data(); |
| 510 |
void ioHttpRedirectMultipartPost(); |
| 511 |
void ioHttpRedirectDelete(); |
| 512 |
void ioHttpRedirectCustom(); |
| 513 |
void ioHttpRedirectWithUploadDevice_data(); |
| 514 |
void ioHttpRedirectWithUploadDevice(); |
| 515 |
#ifndef QT_NO_SSL |
| 516 |
void putWithServerClosingConnectionImmediately(); |
| 517 |
#endif |
| 518 |
|
| 519 |
void autoDeleteRepliesAttribute_data(); |
| 520 |
void autoDeleteRepliesAttribute(); |
| 521 |
void autoDeleteReplies_data(); |
| 522 |
void autoDeleteReplies(); |
| 523 |
|
| 524 |
void getWithTimeout(); |
| 525 |
void postWithTimeout(); |
| 526 |
// NOTE: This test must be last! |
| 527 |
void parentingRepliesToTheApp(); |
| 528 |
private: |
| 529 |
void cleanupTestData(); |
| 530 |
|
| 531 |
QString testDataDir; |
| 532 |
bool notEnoughDataForFastSender; |
| 533 |
}; |
| 534 |
|
| 535 |
const QByteArray tst_QNetworkReply::httpEmpty200Response = |
| 536 |
"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n"; |
| 537 |
const QString tst_QNetworkReply::filePermissionFileName = "/etc/shadow"; |
| 538 |
|
| 539 |
bool tst_QNetworkReply::seedCreated = false; |
| 540 |
|
| 541 |
#define RUN_REQUEST(call) \ |
| 542 |
do { \ |
| 543 |
QString errorMsg = call; \ |
| 544 |
if (!errorMsg.isEmpty()) \ |
| 545 |
QFAIL(qPrintable(errorMsg)); \ |
| 546 |
} while (0) |
| 547 |
|
| 548 |
static bool validateRedirectedResponseHeaders(QNetworkReplyPtr reply) |
| 549 |
{ |
| 550 |
// QTBUG-61300: previously we were mixing 'raw' headers from all responses |
| 551 |
// along the redirect chain. The simplest test is to check/verify we have |
| 552 |
// no 'location' header anymore. |
| 553 |
Q_ASSERT(reply.data()); |
| 554 |
|
| 555 |
return !reply->hasRawHeader("location") |
| 556 |
&& !reply->header(QNetworkRequest::LocationHeader).isValid(); |
| 557 |
} |
| 558 |
|
| 559 |
#ifndef QT_NO_SSL |
| 560 |
static void setupSslServer(QSslSocket* serverSocket) |
| 561 |
{ |
| 562 |
QString testDataDir = QFileInfo(QFINDTESTDATA("rfc3252.txt")).absolutePath(); |
| 563 |
if (testDataDir.isEmpty()) |
| 564 |
testDataDir = QCoreApplication::applicationDirPath(); |
| 565 |
|
| 566 |
serverSocket->setProtocol(QSsl::AnyProtocol); |
| 567 |
serverSocket->setLocalCertificate(testDataDir + "/certs/server.pem"); |
| 568 |
serverSocket->setPrivateKey(testDataDir + "/certs/server.key"); |
| 569 |
serverSocket->startServerEncryption(); |
| 570 |
} |
| 571 |
|
| 572 |
#ifdef QT_TEST_SERVER |
| 573 |
#ifdef QT_TEST_SERVER_NAME |
| 574 |
// In this case, each server is assigned a unique hostname. Use the wildcard SSL |
| 575 |
// certificate (*.test-net.qt.local). |
| 576 |
const QString tst_QNetworkReply::certsFilePath = "/certs/qt-test-net-cacert.pem"; |
| 577 |
#else |
| 578 |
// Otherwise, select the single-name SSL certificate (qt-test-server.local) instead. |
| 579 |
const QString tst_QNetworkReply::certsFilePath = "/certs/qt-test-server-host-network-cacert.pem"; |
| 580 |
#endif // QT_TEST_SERVER_NAME |
| 581 |
#else |
| 582 |
const QString tst_QNetworkReply::certsFilePath = "/certs/qt-test-server-cacert.pem"; |
| 583 |
#endif |
| 584 |
|
| 585 |
#endif // !QT_NO_SSL |
| 586 |
|
| 587 |
// NOTE: MiniHttpServer has a very limited support of PUT/POST requests! Make |
| 588 |
// sure you understand the server's code before PUTting/POSTing data (and |
| 589 |
// probably you'll have to update the logic). |
| 590 |
class MiniHttpServer: public QTcpServer |
| 591 |
{ |
| 592 |
Q_OBJECT |
| 593 |
public: |
| 594 |
QPointer<QTcpSocket> client; // always the last one that was received |
| 595 |
QByteArray dataToTransmit; |
| 596 |
QByteArray receivedData; |
| 597 |
QSemaphore ready; |
| 598 |
bool doClose; |
| 599 |
bool doSsl; |
| 600 |
bool ipv6; |
| 601 |
bool multiple; |
| 602 |
int totalConnections; |
| 603 |
|
| 604 |
bool stopTransfer = false; |
| 605 |
bool hasContent = false; |
| 606 |
int contentRead = 0; |
| 607 |
int contentLength = 0; |
| 608 |
|
| 609 |
MiniHttpServer(const QByteArray &data, bool ssl = false, QThread *thread = 0, bool useipv6 = false) |
| 610 |
: dataToTransmit(data), doClose(true), doSsl(ssl), ipv6(useipv6), |
| 611 |
multiple(false), totalConnections(0) |
| 612 |
{ |
| 613 |
if (useipv6) { |
| 614 |
if (!listen(QHostAddress::AnyIPv6)) |
| 615 |
qWarning() << "listen() IPv6 failed" << errorString(); |
| 616 |
} else { |
| 617 |
if (!listen(QHostAddress::AnyIPv4)) |
| 618 |
qWarning() << "listen() IPv4 failed" << errorString(); |
| 619 |
} |
| 620 |
if (thread) { |
| 621 |
connect(thread, SIGNAL(started()), this, SLOT(threadStartedSlot())); |
| 622 |
moveToThread(thread); |
| 623 |
thread->start(); |
| 624 |
ready.acquire(); |
| 625 |
} |
| 626 |
} |
| 627 |
|
| 628 |
void setDataToTransmit(const QByteArray &data) |
| 629 |
{ |
| 630 |
dataToTransmit = data; |
| 631 |
} |
| 632 |
|
| 633 |
void clearHeaderParserState() |
| 634 |
{ |
| 635 |
contentLength = 0; |
| 636 |
receivedData.clear(); |
| 637 |
} |
| 638 |
|
| 639 |
protected: |
| 640 |
void incomingConnection(qintptr socketDescriptor) |
| 641 |
{ |
| 642 |
//qDebug() << "incomingConnection" << socketDescriptor << "doSsl:" << doSsl << "ipv6:" << ipv6; |
| 643 |
#ifndef QT_NO_SSL |
| 644 |
if (doSsl) { |
| 645 |
QSslSocket *serverSocket = new QSslSocket(this); |
| 646 |
if (!serverSocket->setSocketDescriptor(socketDescriptor)) { |
| 647 |
delete serverSocket; |
| 648 |
return; |
| 649 |
} |
| 650 |
connect(serverSocket, SIGNAL(sslErrors(QList<QSslError>)), this, SLOT(slotSslErrors(QList<QSslError>))); |
| 651 |
// connect(serverSocket, &QSslSocket::encrypted, this, &SslServer::ready); ? |
| 652 |
setupSslServer(serverSocket); |
| 653 |
client = serverSocket; |
| 654 |
} else |
| 655 |
#endif |
| 656 |
{ |
| 657 |
client = new QTcpSocket; |
| 658 |
client->setSocketDescriptor(socketDescriptor); |
| 659 |
} |
| 660 |
connectSocketSignals(); |
| 661 |
client->setParent(this); |
| 662 |
++totalConnections; |
| 663 |
} |
| 664 |
|
| 665 |
virtual void reply() |
| 666 |
{ |
| 667 |
Q_ASSERT(!client.isNull()); |
| 668 |
// we need to emulate the bytesWrittenSlot call if the data is empty. |
| 669 |
if (dataToTransmit.size() == 0) { |
| 670 |
emit client->bytesWritten(0); |
| 671 |
} else if (!stopTransfer) { |
| 672 |
client->write(dataToTransmit); |
| 673 |
// FIXME: For SSL connections, if we don't flush the socket, the |
| 674 |
// client never receives the data and since we're doing a disconnect |
| 675 |
// immediately afterwards, it causes a RemoteHostClosedError for the |
| 676 |
// client |
| 677 |
client->flush(); |
| 678 |
} |
| 679 |
} |
| 680 |
private: |
| 681 |
void connectSocketSignals() |
| 682 |
{ |
| 683 |
Q_ASSERT(!client.isNull()); |
| 684 |
//qDebug() << "connectSocketSignals" << client; |
| 685 |
connect(client.data(), SIGNAL(readyRead()), this, SLOT(readyReadSlot())); |
| 686 |
connect(client.data(), SIGNAL(bytesWritten(qint64)), this, SLOT(bytesWrittenSlot())); |
| 687 |
connect(client.data(), SIGNAL(errorOccurred(QAbstractSocket::SocketError)), |
| 688 |
this, SLOT(slotError(QAbstractSocket::SocketError))); |
| 689 |
} |
| 690 |
|
| 691 |
void parseContentLength() |
| 692 |
{ |
| 693 |
int index = receivedData.indexOf("Content-Length:"); |
| 694 |
index += sizeof("Content-Length:") - 1; |
| 695 |
const auto end = std::find(receivedData.cbegin() + index, receivedData.cend(), '\r'); |
| 696 |
auto num = receivedData.mid(index, std::distance(receivedData.cbegin() + index, end)); |
| 697 |
bool ok; |
| 698 |
contentLength = num.toInt(&ok); |
| 699 |
if (!ok) |
| 700 |
contentLength = -1; |
| 701 |
} |
| 702 |
|
| 703 |
private slots: |
| 704 |
#ifndef QT_NO_SSL |
| 705 |
void slotSslErrors(const QList<QSslError>& errors) |
| 706 |
{ |
| 707 |
QTcpSocket *currentClient = qobject_cast<QTcpSocket *>(sender()); |
| 708 |
Q_ASSERT(currentClient); |
| 709 |
qDebug() << "slotSslErrors" << currentClient->errorString() << errors; |
| 710 |
} |
| 711 |
#endif |
| 712 |
void slotError(QAbstractSocket::SocketError err) |
| 713 |
{ |
| 714 |
QTcpSocket *currentClient = qobject_cast<QTcpSocket *>(sender()); |
| 715 |
Q_ASSERT(currentClient); |
| 716 |
qDebug() << "slotError" << err << currentClient->errorString(); |
| 717 |
} |
| 718 |
|
| 719 |
public slots: |
| 720 |
|
| 721 |
void readyReadSlot() |
| 722 |
{ |
| 723 |
QTcpSocket *currentClient = qobject_cast<QTcpSocket *>(sender()); |
| 724 |
Q_ASSERT(currentClient); |
| 725 |
if (currentClient != client) |
| 726 |
client = currentClient; |
| 727 |
if (stopTransfer) |
| 728 |
return; |
| 729 |
receivedData += client->readAll(); |
| 730 |
const int doubleEndlPos = receivedData.indexOf("\r\n\r\n"); |
| 731 |
|
| 732 |
if (doubleEndlPos != -1) { |
| 733 |
const int endOfHeader = doubleEndlPos + 4; |
| 734 |
hasContent = receivedData.startsWith("POST") || receivedData.startsWith("PUT") |
| 735 |
|| receivedData.startsWith("CUSTOM_WITH_PAYLOAD"); |
| 736 |
if (hasContent && contentLength == 0) |
| 737 |
parseContentLength(); |
| 738 |
contentRead = receivedData.length() - endOfHeader; |
| 739 |
if (hasContent && contentRead < contentLength) |
| 740 |
return; |
| 741 |
|
| 742 |
// multiple requests incoming. remove the bytes of the current one |
| 743 |
if (multiple) |
| 744 |
receivedData.remove(0, endOfHeader); |
| 745 |
|
| 746 |
reply(); |
| 747 |
} |
| 748 |
} |
| 749 |
|
| 750 |
void bytesWrittenSlot() |
| 751 |
{ |
| 752 |
Q_ASSERT(!client.isNull()); |
| 753 |
// Disconnect and delete in next cycle (else Windows clients will fail with RemoteHostClosedError). |
| 754 |
if (doClose && client->bytesToWrite() == 0) { |
| 755 |
disconnect(client, 0, this, 0); |
| 756 |
client->deleteLater(); |
| 757 |
} |
| 758 |
} |
| 759 |
|
| 760 |
void threadStartedSlot() |
| 761 |
{ |
| 762 |
ready.release(); |
| 763 |
} |
| 764 |
}; |
| 765 |
|
| 766 |
class MyCookieJar: public QNetworkCookieJar |
| 767 |
{ |
| 768 |
public: |
| 769 |
inline QList<QNetworkCookie> allCookies() const |
| 770 |
{ return QNetworkCookieJar::allCookies(); } |
| 771 |
inline void setAllCookies(const QList<QNetworkCookie> &cookieList) |
| 772 |
{ QNetworkCookieJar::setAllCookies(cookieList); } |
| 773 |
}; |
| 774 |
|
| 775 |
#ifndef QT_NO_NETWORKPROXY |
| 776 |
class MyProxyFactory: public QNetworkProxyFactory |
| 777 |
{ |
| 778 |
public: |
| 779 |
int callCount; |
| 780 |
QList<QNetworkProxy> toReturn; |
| 781 |
QNetworkProxyQuery lastQuery; |
| 782 |
inline MyProxyFactory() { clear(); } |
| 783 |
|
| 784 |
inline void clear() |
| 785 |
{ |
| 786 |
callCount = 0; |
| 787 |
toReturn = QList<QNetworkProxy>() << QNetworkProxy::DefaultProxy; |
| 788 |
lastQuery = QNetworkProxyQuery(); |
| 789 |
} |
| 790 |
|
| 791 |
virtual QList<QNetworkProxy> queryProxy(const QNetworkProxyQuery &query) |
| 792 |
{ |
| 793 |
lastQuery = query; |
| 794 |
++callCount; |
| 795 |
return toReturn; |
| 796 |
} |
| 797 |
}; |
| 798 |
#endif // !QT_NO_NETWORKPROXY |
| 799 |
|
| 800 |
class MyMemoryCache: public QAbstractNetworkCache |
| 801 |
{ |
| 802 |
public: |
| 803 |
typedef QPair<QNetworkCacheMetaData, QByteArray> CachedContent; |
| 804 |
typedef QHash<QByteArray, CachedContent> CacheData; |
| 805 |
CacheData cache; |
| 806 |
|
| 807 |
MyMemoryCache(QObject *parent) : QAbstractNetworkCache(parent) {} |
| 808 |
|
| 809 |
QNetworkCacheMetaData metaData(const QUrl &url) |
| 810 |
{ |
| 811 |
return cache.value(url.toEncoded()).first; |
| 812 |
} |
| 813 |
|
| 814 |
void updateMetaData(const QNetworkCacheMetaData &metaData) |
| 815 |
{ |
| 816 |
cache[metaData.url().toEncoded()].first = metaData; |
| 817 |
} |
| 818 |
|
| 819 |
QIODevice *data(const QUrl &url) |
| 820 |
{ |
| 821 |
CacheData::ConstIterator it = cache.find(url.toEncoded()); |
| 822 |
if (it == cache.constEnd()) |
| 823 |
return 0; |
| 824 |
QBuffer *io = new QBuffer(this); |
| 825 |
io->setData(it->second); |
| 826 |
io->open(QIODevice::ReadOnly); |
| 827 |
io->seek(0); |
| 828 |
return io; |
| 829 |
} |
| 830 |
|
| 831 |
bool remove(const QUrl &url) |
| 832 |
{ |
| 833 |
cache.remove(url.toEncoded()); |
| 834 |
return true; |
| 835 |
} |
| 836 |
|
| 837 |
qint64 cacheSize() const |
| 838 |
{ |
| 839 |
qint64 total = 0; |
| 840 |
foreach (const CachedContent &entry, cache) |
| 841 |
total += entry.second.size(); |
| 842 |
return total; |
| 843 |
} |
| 844 |
|
| 845 |
QIODevice *prepare(const QNetworkCacheMetaData &) |
| 846 |
{ |
| 847 |
qFatal("%s: Should not have tried to add to the cache", Q_FUNC_INFO); |
| 848 |
return 0; |
| 849 |
} |
| 850 |
void insert(QIODevice *) |
| 851 |
{ |
| 852 |
qFatal("%s: Should not have tried to add to the cache", Q_FUNC_INFO); |
| 853 |
} |
| 854 |
|
| 855 |
void clear() { cache.clear(); } |
| 856 |
}; |
| 857 |
Q_DECLARE_METATYPE(MyMemoryCache::CachedContent) |
| 858 |
Q_DECLARE_METATYPE(MyMemoryCache::CacheData) |
| 859 |
|
| 860 |
class MySpyMemoryCache: public QAbstractNetworkCache |
| 861 |
{ |
| 862 |
public: |
| 863 |
MySpyMemoryCache(QObject *parent) : QAbstractNetworkCache(parent) {} |
| 864 |
~MySpyMemoryCache() |
| 865 |
{ |
| 866 |
qDeleteAll(m_buffers); |
| 867 |
m_buffers.clear(); |
| 868 |
} |
| 869 |
|
| 870 |
QHash<QUrl, QIODevice*> m_buffers; |
| 871 |
QList<QUrl> m_insertedUrls; |
| 872 |
|
| 873 |
QNetworkCacheMetaData metaData(const QUrl &) |
| 874 |
{ |
| 875 |
return QNetworkCacheMetaData(); |
| 876 |
} |
| 877 |
|
| 878 |
void updateMetaData(const QNetworkCacheMetaData &) |
| 879 |
{ |
| 880 |
} |
| 881 |
|
| 882 |
QIODevice *data(const QUrl &) |
| 883 |
{ |
| 884 |
return 0; |
| 885 |
} |
| 886 |
|
| 887 |
bool remove(const QUrl &url) |
| 888 |
{ |
| 889 |
delete m_buffers.take(url); |
| 890 |
return m_insertedUrls.removeAll(url) > 0; |
| 891 |
} |
| 892 |
|
| 893 |
qint64 cacheSize() const |
| 894 |
{ |
| 895 |
return 0; |
| 896 |
} |
| 897 |
|
| 898 |
QIODevice *prepare(const QNetworkCacheMetaData &metaData) |
| 899 |
{ |
| 900 |
QBuffer* buffer = new QBuffer; |
| 901 |
buffer->open(QIODevice::ReadWrite); |
| 902 |
buffer->setProperty("url", metaData.url()); |
| 903 |
m_buffers.insert(metaData.url(), buffer); |
| 904 |
return buffer; |
| 905 |
} |
| 906 |
|
| 907 |
void insert(QIODevice *buffer) |
| 908 |
{ |
| 909 |
QUrl url = buffer->property("url").toUrl(); |
| 910 |
m_insertedUrls << url; |
| 911 |
delete m_buffers.take(url); |
| 912 |
} |
| 913 |
|
| 914 |
void clear() { m_insertedUrls.clear(); } |
| 915 |
}; |
| 916 |
|
| 917 |
class DataReader: public QObject |
| 918 |
{ |
| 919 |
Q_OBJECT |
| 920 |
public: |
| 921 |
qint64 totalBytes; |
| 922 |
QByteArray data; |
| 923 |
QIODevice *device; |
| 924 |
bool accumulate; |
| 925 |
DataReader(const QNetworkReplyPtr &dev, bool acc = true) : totalBytes(0), device(dev.data()), accumulate(acc) |
| 926 |
{ connect(device, SIGNAL(readyRead()), SLOT(doRead()) ); } |
| 927 |
DataReader(QIODevice *dev, bool acc = true) : totalBytes(0), device(dev), accumulate(acc) |
| 928 |
{ |
| 929 |
connect(device, SIGNAL(readyRead()), SLOT(doRead())); |
| 930 |
} |
| 931 |
|
| 932 |
public slots: |
| 933 |
void doRead() |
| 934 |
{ |
| 935 |
QByteArray buffer; |
| 936 |
buffer.resize(device->bytesAvailable()); |
| 937 |
qint64 bytesRead = device->read(buffer.data(), device->bytesAvailable()); |
| 938 |
if (bytesRead == -1) { |
| 939 |
QTestEventLoop::instance().exitLoop(); |
| 940 |
return; |
| 941 |
} |
| 942 |
buffer.truncate(bytesRead); |
| 943 |
totalBytes += bytesRead; |
| 944 |
|
| 945 |
if (accumulate) |
| 946 |
data += buffer; |
| 947 |
} |
| 948 |
}; |
| 949 |
|
| 950 |
|
| 951 |
class SocketPair: public QObject |
| 952 |
{ |
| 953 |
Q_OBJECT |
| 954 |
public: |
| 955 |
QIODevice *endPoints[2]; |
| 956 |
|
| 957 |
SocketPair(QObject *parent = 0) |
| 958 |
: QObject(parent) |
| 959 |
{ |
| 960 |
endPoints[0] = endPoints[1] = 0; |
| 961 |
} |
| 962 |
|
| 963 |
bool create() |
| 964 |
{ |
| 965 |
QTcpServer server; |
| 966 |
server.listen(); |
| 967 |
|
| 968 |
QTcpSocket *active = new QTcpSocket(this); |
| 969 |
active->connectToHost("127.0.0.1", server.serverPort()); |
| 970 |
|
| 971 |
// need more time as working with embedded |
| 972 |
// device and testing from emualtor |
| 973 |
// things tend to get slower |
| 974 |
if (!active->waitForConnected(1000)) |
| 975 |
return false; |
| 976 |
|
| 977 |
if (!server.waitForNewConnection(1000)) |
| 978 |
return false; |
| 979 |
|
| 980 |
QTcpSocket *passive = server.nextPendingConnection(); |
| 981 |
passive->setParent(this); |
| 982 |
|
| 983 |
endPoints[0] = active; |
| 984 |
endPoints[1] = passive; |
| 985 |
return true; |
| 986 |
} |
| 987 |
}; |
| 988 |
|
| 989 |
// A blocking tcp server (must be used in a thread) which supports SSL. |
| 990 |
class BlockingTcpServer : public QTcpServer |
| 991 |
{ |
| 992 |
Q_OBJECT |
| 993 |
public: |
| 994 |
BlockingTcpServer(bool ssl) : doSsl(ssl), sslSocket(0) {} |
| 995 |
|
| 996 |
QTcpSocket* waitForNextConnectionSocket() |
| 997 |
{ |
| 998 |
waitForNewConnection(-1); |
| 999 |
if (doSsl) { |
| 1000 |
if (!sslSocket) |
| 1001 |
qFatal("%s: sslSocket should not be null after calling waitForNewConnection()", |
| 1002 |
Q_FUNC_INFO); |
| 1003 |
return sslSocket; |
| 1004 |
} else { |
| 1005 |
//qDebug() << "returning nextPendingConnection"; |
| 1006 |
return nextPendingConnection(); |
| 1007 |
} |
| 1008 |
} |
| 1009 |
virtual void incomingConnection(qintptr socketDescriptor) |
| 1010 |
{ |
| 1011 |
#ifndef QT_NO_SSL |
| 1012 |
if (doSsl) { |
| 1013 |
QSslSocket *serverSocket = new QSslSocket; |
| 1014 |
serverSocket->setParent(this); |
| 1015 |
serverSocket->setSocketDescriptor(socketDescriptor); |
| 1016 |
connect(serverSocket, SIGNAL(sslErrors(QList<QSslError>)), this, SLOT(slotSslErrors(QList<QSslError>))); |
| 1017 |
setupSslServer(serverSocket); |
| 1018 |
sslSocket = serverSocket; |
| 1019 |
} else |
| 1020 |
#endif |
| 1021 |
{ |
| 1022 |
QTcpServer::incomingConnection(socketDescriptor); |
| 1023 |
} |
| 1024 |
} |
| 1025 |
private slots: |
| 1026 |
|
| 1027 |
#ifndef QT_NO_SSL |
| 1028 |
void slotSslErrors(const QList<QSslError>& errors) |
| 1029 |
{ |
| 1030 |
qDebug() << "slotSslErrors" << sslSocket->errorString() << errors; |
| 1031 |
} |
| 1032 |
#endif |
| 1033 |
|
| 1034 |
private: |
| 1035 |
const bool doSsl; |
| 1036 |
QTcpSocket* sslSocket; |
| 1037 |
}; |
| 1038 |
|
| 1039 |
// This server tries to send data as fast as possible (like most servers) |
| 1040 |
// but it measures how fast it was able to send it, which shows at which |
| 1041 |
// rate the reader is processing the data. |
| 1042 |
class FastSender: public QThread |
| 1043 |
{ |
| 1044 |
Q_OBJECT |
| 1045 |
QSemaphore ready; |
| 1046 |
qint64 wantedSize; |
| 1047 |
int port; |
| 1048 |
enum Protocol { DebugPipe, ProvidedData }; |
| 1049 |
const Protocol protocol; |
| 1050 |
const bool doSsl; |
| 1051 |
const bool fillKernelBuffer; |
| 1052 |
public: |
| 1053 |
int transferRate; |
| 1054 |
QWaitCondition cond; |
| 1055 |
|
| 1056 |
QByteArray dataToTransmit; |
| 1057 |
int dataIndex; |
| 1058 |
|
| 1059 |
// a server that sends debugpipe data |
| 1060 |
FastSender(qint64 size) |
| 1061 |
: wantedSize(size), port(-1), protocol(DebugPipe), |
| 1062 |
doSsl(false), fillKernelBuffer(true), transferRate(-1), |
| 1063 |
dataIndex(0) |
| 1064 |
{ |
| 1065 |
start(); |
| 1066 |
ready.acquire(); |
| 1067 |
} |
| 1068 |
|
| 1069 |
// a server that sends the data provided at construction time, useful for HTTP |
| 1070 |
FastSender(const QByteArray& data, bool https, bool fillBuffer, tst_QNetworkReply *listener = 0) |
| 1071 |
: wantedSize(data.size()), port(-1), protocol(ProvidedData), |
| 1072 |
doSsl(https), fillKernelBuffer(fillBuffer), transferRate(-1), |
| 1073 |
dataToTransmit(data), dataIndex(0) |
| 1074 |
{ |
| 1075 |
if (listener) |
| 1076 |
connect(this, SIGNAL(notEnoughData()), listener, SLOT(notEnoughData())); |
| 1077 |
start(); |
| 1078 |
ready.acquire(); |
| 1079 |
} |
| 1080 |
|
| 1081 |
inline int serverPort() const { return port; } |
| 1082 |
|
| 1083 |
int writeNextData(QTcpSocket* socket, qint32 size) |
| 1084 |
{ |
| 1085 |
if (protocol == DebugPipe) { |
| 1086 |
QByteArray data; |
| 1087 |
QDataStream stream(&data, QIODevice::WriteOnly); |
| 1088 |
stream << QVariantMap() << QByteArray(size, 'a'); |
| 1089 |
socket->write((char*)&size, sizeof size); |
| 1090 |
socket->write(data); |
| 1091 |
dataIndex += size; |
| 1092 |
return size; |
| 1093 |
} else { |
| 1094 |
const QByteArray data = dataToTransmit.mid(dataIndex, size); |
| 1095 |
socket->write(data); |
| 1096 |
dataIndex += data.size(); |
| 1097 |
//qDebug() << "wrote" << dataIndex << "/" << dataToTransmit.size(); |
| 1098 |
return data.size(); |
| 1099 |
} |
| 1100 |
} |
| 1101 |
void writeLastData(QTcpSocket* socket) |
| 1102 |
{ |
| 1103 |
if (protocol == DebugPipe) { |
| 1104 |
QByteArray data; |
| 1105 |
QDataStream stream(&data, QIODevice::WriteOnly); |
| 1106 |
stream << QVariantMap() << QByteArray(); |
| 1107 |
const qint32 size = data.size(); |
| 1108 |
socket->write((char*)&size, sizeof size); |
| 1109 |
socket->write(data); |
| 1110 |
} |
| 1111 |
} |
| 1112 |
|
| 1113 |
protected: |
| 1114 |
void run() |
| 1115 |
{ |
| 1116 |
BlockingTcpServer server(doSsl); |
| 1117 |
server.listen(); |
| 1118 |
port = server.serverPort(); |
| 1119 |
ready.release(); |
| 1120 |
|
| 1121 |
QTcpSocket *client = server.waitForNextConnectionSocket(); |
| 1122 |
|
| 1123 |
// get the "request" packet |
| 1124 |
if (!client->waitForReadyRead(2000)) { |
| 1125 |
qDebug() << "FastSender:" << client->error() << "waiting for \"request\" packet"; |
| 1126 |
return; |
| 1127 |
} |
| 1128 |
client->readAll(); // we're not interested in the actual contents (e.g. HTTP request) |
| 1129 |
|
| 1130 |
enum { BlockSize = 1024 }; |
| 1131 |
|
| 1132 |
if (fillKernelBuffer) { |
| 1133 |
|
| 1134 |
// write a bunch of bytes to fill up the buffers |
| 1135 |
bool done = false; |
| 1136 |
do { |
| 1137 |
if (writeNextData(client, BlockSize) < BlockSize) { |
| 1138 |
qDebug() << "ERROR: FastSender: not enough data to write in order to fill buffers; or client is reading too fast"; |
| 1139 |
emit notEnoughData(); |
| 1140 |
return; |
| 1141 |
} |
| 1142 |
while (client->bytesToWrite() > 0) { |
| 1143 |
if (!client->waitForBytesWritten(0)) { |
| 1144 |
done = true; |
| 1145 |
break; |
| 1146 |
} |
| 1147 |
} |
| 1148 |
//qDebug() << "Filling kernel buffer: wrote" << dataIndex << "bytes"; |
| 1149 |
} while (!done); |
| 1150 |
|
| 1151 |
qDebug() << "FastSender: ok, kernel buffer is full after writing" << dataIndex << "bytes"; |
| 1152 |
} |
| 1153 |
|
| 1154 |
// Tell the client to start reading |
| 1155 |
emit dataReady(); |
| 1156 |
|
| 1157 |
// the kernel buffer is full |
| 1158 |
// clean up QAbstractSocket's residue: |
| 1159 |
while (client->bytesToWrite() > 0) { |
| 1160 |
qDebug() << "Still having" << client->bytesToWrite() << "bytes to write, doing that now"; |
| 1161 |
if (!client->waitForBytesWritten(10000)) { |
| 1162 |
qDebug() << "ERROR: FastSender:" << client->error() << "cleaning up residue"; |
| 1163 |
return; |
| 1164 |
} |
| 1165 |
} |
| 1166 |
|
| 1167 |
// now write in "blocking mode", this is where the rate measuring starts |
| 1168 |
QElapsedTimer timer; |
| 1169 |
timer.start(); |
| 1170 |
//const qint64 writtenBefore = dataIndex; |
| 1171 |
//qint64 measuredTotalBytes = wantedSize - writtenBefore; |
| 1172 |
qint64 measuredSentBytes = 0; |
| 1173 |
while (dataIndex < wantedSize) { |
| 1174 |
const int remainingBytes = wantedSize - measuredSentBytes; |
| 1175 |
const int bytesToWrite = qMin(remainingBytes, static_cast<int>(BlockSize)); |
| 1176 |
if (bytesToWrite <= 0) |
| 1177 |
qFatal("%s: attempt to write %d bytes", Q_FUNC_INFO, bytesToWrite); |
| 1178 |
measuredSentBytes += writeNextData(client, bytesToWrite); |
| 1179 |
|
| 1180 |
while (client->bytesToWrite() > 0) { |
| 1181 |
if (!client->waitForBytesWritten(10000)) { |
| 1182 |
qDebug() << "ERROR: FastSender:" << client->error() << "during blocking write"; |
| 1183 |
return; |
| 1184 |
} |
| 1185 |
} |
| 1186 |
/*qDebug() << "FastSender:" << bytesToWrite << "bytes written now;" |
| 1187 |
<< measuredSentBytes << "measured bytes" << measuredSentBytes + writtenBefore << "total (" |
| 1188 |
<< measuredSentBytes*100/measuredTotalBytes << "% complete);" |
| 1189 |
<< timer.elapsed() << "ms elapsed";*/ |
| 1190 |
} |
| 1191 |
|
| 1192 |
transferRate = measuredSentBytes * 1000 / timer.elapsed(); |
| 1193 |
qDebug() << "FastSender: flushed" << measuredSentBytes << "bytes in" << timer.elapsed() << "ms: rate =" << transferRate << "B/s"; |
| 1194 |
|
| 1195 |
// write a "close connection" packet, if the protocol needs it |
| 1196 |
writeLastData(client); |
| 1197 |
} |
| 1198 |
signals: |
| 1199 |
void dataReady(); |
| 1200 |
void notEnoughData(); |
| 1201 |
}; |
| 1202 |
|
| 1203 |
class RateControlledReader: public QObject |
| 1204 |
{ |
| 1205 |
Q_OBJECT |
| 1206 |
QIODevice *device; |
| 1207 |
int bytesToRead; |
| 1208 |
int interval; |
| 1209 |
int readBufferSize; |
| 1210 |
public: |
| 1211 |
QByteArray data; |
| 1212 |
qint64 totalBytesRead; |
| 1213 |
RateControlledReader(QObject& senderObj, QIODevice *dev, int kbPerSec, int maxBufferSize = 0) |
| 1214 |
: device(dev), readBufferSize(maxBufferSize), totalBytesRead(0) |
| 1215 |
{ |
| 1216 |
// determine how often we have to wake up |
| 1217 |
int timesPerSecond; |
| 1218 |
if (readBufferSize == 0) { |
| 1219 |
// The requirement is simply "N KB per seconds" |
| 1220 |
timesPerSecond = 20; |
| 1221 |
bytesToRead = kbPerSec * 1024 / timesPerSecond; |
| 1222 |
} else { |
| 1223 |
// The requirement also includes "<readBufferSize> bytes at a time" |
| 1224 |
bytesToRead = readBufferSize; |
| 1225 |
timesPerSecond = kbPerSec * 1024 / readBufferSize; |
| 1226 |
} |
| 1227 |
interval = 1000 / timesPerSecond; // in ms |
| 1228 |
|
| 1229 |
qDebug() << "RateControlledReader: going to read" << bytesToRead |
| 1230 |
<< "bytes every" << interval << "ms"; |
| 1231 |
qDebug() << "actual read rate will be" |
| 1232 |
<< (bytesToRead * 1000 / interval) << "bytes/sec (wanted" |
| 1233 |
<< kbPerSec * 1024 << "bytes/sec)"; |
| 1234 |
|
| 1235 |
// Wait for data to be readyRead |
| 1236 |
bool ok = connect(&senderObj, SIGNAL(dataReady()), this, SLOT(slotDataReady())); |
| 1237 |
if (!ok) |
| 1238 |
qFatal("%s: Cannot connect dataReady signal", Q_FUNC_INFO); |
| 1239 |
} |
| 1240 |
|
| 1241 |
void wrapUp() |
| 1242 |
{ |
| 1243 |
QByteArray someData = device->read(device->bytesAvailable()); |
| 1244 |
data += someData; |
| 1245 |
totalBytesRead += someData.size(); |
| 1246 |
qDebug() << "wrapUp: found" << someData.size() << "bytes left. progress" << data.size(); |
| 1247 |
//qDebug() << "wrapUp: now bytesAvailable=" << device->bytesAvailable(); |
| 1248 |
} |
| 1249 |
|
| 1250 |
private slots: |
| 1251 |
void slotDataReady() |
| 1252 |
{ |
| 1253 |
//qDebug() << "RateControlledReader: ready to go"; |
| 1254 |
startTimer(interval); |
| 1255 |
} |
| 1256 |
|
| 1257 |
protected: |
| 1258 |
void timerEvent(QTimerEvent *) |
| 1259 |
{ |
| 1260 |
//qDebug() << "RateControlledReader: timerEvent bytesAvailable=" << device->bytesAvailable(); |
| 1261 |
if (readBufferSize > 0 && device->bytesAvailable() > readBufferSize) { |
| 1262 |
// This passes all the time, except in the final flush. |
| 1263 |
//qFatal("%s: Too many bytes available", Q_FUNC_INFO); |
| 1264 |
} |
| 1265 |
|
| 1266 |
qint64 bytesRead = 0; |
| 1267 |
QElapsedTimer stopWatch; |
| 1268 |
stopWatch.start(); |
| 1269 |
do { |
| 1270 |
if (device->bytesAvailable() == 0) { |
| 1271 |
if (stopWatch.elapsed() > 20) { |
| 1272 |
qDebug() << "RateControlledReader: Not enough data available for reading, waited too much, timing out"; |
| 1273 |
break; |
| 1274 |
} |
| 1275 |
if (!device->waitForReadyRead(5)) { |
| 1276 |
qDebug() << "RateControlledReader: Not enough data available for reading, even after waiting 5ms, bailing out"; |
| 1277 |
break; |
| 1278 |
} |
| 1279 |
} |
| 1280 |
QByteArray someData = device->read(bytesToRead - bytesRead); |
| 1281 |
data += someData; |
| 1282 |
bytesRead += someData.size(); |
| 1283 |
//qDebug() << "RateControlledReader: successfully read" << someData.size() << "progress:" << data.size(); |
| 1284 |
} while (bytesRead < bytesToRead); |
| 1285 |
totalBytesRead += bytesRead; |
| 1286 |
|
| 1287 |
if (bytesRead < bytesToRead) |
| 1288 |
qWarning() << "RateControlledReader: WARNING:" << bytesToRead - bytesRead << "bytes not read"; |
| 1289 |
} |
| 1290 |
}; |
| 1291 |
|
| 1292 |
|
| 1293 |
tst_QNetworkReply::tst_QNetworkReply() |
| 1294 |
{ |
| 1295 |
qRegisterMetaType<QNetworkReply *>(); // for QSignalSpy |
| 1296 |
qRegisterMetaType<QAuthenticator *>(); |
| 1297 |
#ifndef QT_NO_NETWORKPROXY |
| 1298 |
qRegisterMetaType<QNetworkProxy>(); |
| 1299 |
#endif |
| 1300 |
#ifndef QT_NO_SSL |
| 1301 |
qRegisterMetaType<QList<QSslError> >(); |
| 1302 |
#endif |
| 1303 |
qRegisterMetaType<QNetworkReply::NetworkError>(); |
| 1304 |
|
| 1305 |
uniqueExtension = createUniqueExtension(); |
| 1306 |
testFileName = QDir::currentPath() + "/testfile" + uniqueExtension; |
| 1307 |
cookieJar = new MyCookieJar; |
| 1308 |
manager.setCookieJar(cookieJar); |
| 1309 |
|
| 1310 |
#ifndef QT_NO_NETWORKPROXY |
| 1311 |
QHostInfo hostInfo = QHostInfo::fromName(QtNetworkSettings::httpProxyServerName()); |
| 1312 |
|
| 1313 |
proxies << ProxyData(QNetworkProxy::NoProxy, "", false); |
| 1314 |
|
| 1315 |
if (hostInfo.error() == QHostInfo::NoError && !hostInfo.addresses().isEmpty()) { |
| 1316 |
QString httpProxy = QtNetworkSettings::httpProxyServerName(); |
| 1317 |
QString socksProxy = QtNetworkSettings::socksProxyServerName(); |
| 1318 |
proxies << ProxyData(QNetworkProxy(QNetworkProxy::HttpProxy, httpProxy, 3128), |
| 1319 |
"+proxy", false) |
| 1320 |
<< ProxyData(QNetworkProxy(QNetworkProxy::HttpProxy, httpProxy, 3129), |
| 1321 |
"+proxyauth", true) |
| 1322 |
// currently unsupported |
| 1323 |
// << ProxyData(QNetworkProxy(QNetworkProxy::HttpProxy, proxyserver, 3130), "+proxyauth-ntlm", true); |
| 1324 |
<< ProxyData(QNetworkProxy(QNetworkProxy::Socks5Proxy, socksProxy, 1080), |
| 1325 |
"+socks", false) |
| 1326 |
<< ProxyData(QNetworkProxy(QNetworkProxy::Socks5Proxy, socksProxy, 1081), |
| 1327 |
"+socksauth", true); |
| 1328 |
} else { |
| 1329 |
#endif // !QT_NO_NETWORKPROXY |
| 1330 |
fprintf(stderr, "==================================================================\n"); |
| 1331 |
fprintf(stderr, "Proxy could not be looked up. No proxy will be used while testing!\n"); |
| 1332 |
fprintf(stderr, "==================================================================\n"); |
| 1333 |
#ifndef QT_NO_NETWORKPROXY |
| 1334 |
} |
| 1335 |
#endif // !QT_NO_NETWORKPROXY |
| 1336 |
} |
| 1337 |
|
| 1338 |
tst_QNetworkReply::~tst_QNetworkReply() |
| 1339 |
{ |
| 1340 |
} |
| 1341 |
|
| 1342 |
|
| 1343 |
void tst_QNetworkReply::authenticationRequired(QNetworkReply*, QAuthenticator* auth) |
| 1344 |
{ |
| 1345 |
auth->setUser("httptest"); |
| 1346 |
auth->setPassword("httptest"); |
| 1347 |
} |
| 1348 |
|
| 1349 |
void tst_QNetworkReply::proxyAuthenticationRequired(const QNetworkProxy &, QAuthenticator* auth) |
| 1350 |
{ |
| 1351 |
auth->setUser("qsockstest"); |
| 1352 |
auth->setPassword("password"); |
| 1353 |
} |
| 1354 |
|
| 1355 |
#ifndef QT_NO_SSL |
| 1356 |
void tst_QNetworkReply::sslErrors(QNetworkReply *reply, const QList<QSslError> &errors) |
| 1357 |
{ |
| 1358 |
reply->ignoreSslErrors(); |
| 1359 |
QVERIFY(!errors.isEmpty()); |
| 1360 |
QVERIFY(!reply->sslConfiguration().isNull()); |
| 1361 |
} |
| 1362 |
|
| 1363 |
void tst_QNetworkReply::storeSslConfiguration() |
| 1364 |
{ |
| 1365 |
storedSslConfiguration = QSslConfiguration(); |
| 1366 |
QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender()); |
| 1367 |
if (reply) |
| 1368 |
storedSslConfiguration = reply->sslConfiguration(); |
| 1369 |
} |
| 1370 |
#endif |
| 1371 |
|
| 1372 |
QString tst_QNetworkReply::runMultipartRequest(const QNetworkRequest &request, |
| 1373 |
QNetworkReplyPtr &reply, |
| 1374 |
QHttpMultiPart *multiPart, |
| 1375 |
const QByteArray &verb) |
| 1376 |
{ |
| 1377 |
if (verb == "POST") |
| 1378 |
reply.reset(manager.post(request, multiPart)); |
| 1379 |
else |
| 1380 |
reply.reset(manager.put(request, multiPart)); |
| 1381 |
|
| 1382 |
// the code below is copied from tst_QNetworkReply::runSimpleRequest, see below |
| 1383 |
reply->setParent(this); |
| 1384 |
connect(reply, SIGNAL(finished()), SLOT(finished())); |
| 1385 |
connect(reply, SIGNAL(errorOccurred(QNetworkReply::NetworkError)), SLOT(gotError())); |
| 1386 |
multiPart->setParent(reply.data()); |
| 1387 |
|
| 1388 |
returnCode = Timeout; |
| 1389 |
loop = new QEventLoop; |
| 1390 |
QTimer::singleShot(25000, loop, SLOT(quit())); |
| 1391 |
int code = returnCode == Timeout ? loop->exec() : returnCode; |
| 1392 |
delete loop; |
| 1393 |
loop = 0; |
| 1394 |
|
| 1395 |
switch (code) { |
| 1396 |
case Failure: |
| 1397 |
return "Request failed: " + reply->errorString(); |
| 1398 |
case Timeout: |
| 1399 |
return "Network timeout"; |
| 1400 |
} |
| 1401 |
return QString(); |
| 1402 |
} |
| 1403 |
|
| 1404 |
QString tst_QNetworkReply::runSimpleRequest(QNetworkAccessManager::Operation op, |
| 1405 |
const QNetworkRequest &request, |
| 1406 |
QNetworkReplyPtr &reply, |
| 1407 |
const QByteArray &data) |
| 1408 |
{ |
| 1409 |
switch (op) { |
| 1410 |
case QNetworkAccessManager::HeadOperation: |
| 1411 |
reply.reset(manager.head(request)); |
| 1412 |
break; |
| 1413 |
|
| 1414 |
case QNetworkAccessManager::GetOperation: |
| 1415 |
reply.reset(manager.get(request)); |
| 1416 |
break; |
| 1417 |
|
| 1418 |
case QNetworkAccessManager::PutOperation: |
| 1419 |
reply.reset(manager.put(request, data)); |
| 1420 |
break; |
| 1421 |
|
| 1422 |
case QNetworkAccessManager::PostOperation: |
| 1423 |
reply.reset(manager.post(request, data)); |
| 1424 |
break; |
| 1425 |
|
| 1426 |
case QNetworkAccessManager::DeleteOperation: |
| 1427 |
reply.reset(manager.deleteResource(request)); |
| 1428 |
break; |
| 1429 |
|
| 1430 |
default: |
| 1431 |
qFatal("%s: Invalid/unknown operation requested", Q_FUNC_INFO); |
| 1432 |
} |
| 1433 |
reply->setParent(this); |
| 1434 |
|
| 1435 |
returnCode = Timeout; |
| 1436 |
int code = Success; |
| 1437 |
|
| 1438 |
if (request.attribute(QNetworkRequest::SynchronousRequestAttribute).toBool()) { |
| 1439 |
if (reply->isFinished()) |
| 1440 |
code = reply->error() != QNetworkReply::NoError ? Failure : Success; |
| 1441 |
else |
| 1442 |
code = Failure; |
| 1443 |
} else { |
| 1444 |
connect(reply, SIGNAL(finished()), SLOT(finished())); |
| 1445 |
connect(reply, SIGNAL(errorOccurred(QNetworkReply::NetworkError)), SLOT(gotError())); |
| 1446 |
|
| 1447 |
int count = 0; |
| 1448 |
loop = new QEventLoop; |
| 1449 |
QSignalSpy spy(reply.data(), SIGNAL(downloadProgress(qint64,qint64))); |
| 1450 |
while (!reply->isFinished()) { |
| 1451 |
QTimer::singleShot(20000, loop, SLOT(quit())); |
| 1452 |
code = loop->exec(); |
| 1453 |
if (count == spy.count() && !reply->isFinished()) { |
| 1454 |
code = Timeout; |
| 1455 |
break; |
| 1456 |
} |
| 1457 |
count = spy.count(); |
| 1458 |
} |
| 1459 |
delete loop; |
| 1460 |
loop = 0; |
| 1461 |
} |
| 1462 |
|
| 1463 |
switch (code) { |
| 1464 |
case Failure: |
| 1465 |
return "Request failed: " + reply->errorString(); |
| 1466 |
case Timeout: |
| 1467 |
return "Network timeout"; |
| 1468 |
} |
| 1469 |
return QString(); |
| 1470 |
} |
| 1471 |
|
| 1472 |
QString tst_QNetworkReply::runCustomRequest(const QNetworkRequest &request, |
| 1473 |
QNetworkReplyPtr &reply, |
| 1474 |
const QByteArray &verb, |
| 1475 |
QIODevice *data) |
| 1476 |
{ |
| 1477 |
reply.reset(manager.sendCustomRequest(request, verb, data)); |
| 1478 |
reply->setParent(this); |
| 1479 |
connect(reply, SIGNAL(finished()), SLOT(finished())); |
| 1480 |
connect(reply, SIGNAL(errorOccurred(QNetworkReply::NetworkError)), SLOT(gotError())); |
| 1481 |
|
| 1482 |
returnCode = Timeout; |
| 1483 |
loop = new QEventLoop; |
| 1484 |
QTimer::singleShot(20000, loop, SLOT(quit())); |
| 1485 |
int code = returnCode == Timeout ? loop->exec() : returnCode; |
| 1486 |
delete loop; |
| 1487 |
loop = 0; |
| 1488 |
|
| 1489 |
switch (code) { |
| 1490 |
case Failure: |
| 1491 |
return "Request failed: " + reply->errorString(); |
| 1492 |
case Timeout: |
| 1493 |
return "Network timeout"; |
| 1494 |
} |
| 1495 |
return QString(); |
| 1496 |
} |
| 1497 |
|
| 1498 |
static QByteArray msgWaitForFinished(QNetworkReplyPtr &reply) |
| 1499 |
{ |
| 1500 |
QString result; |
| 1501 |
QDebug debug(&result); |
| 1502 |
debug << reply->url(); |
| 1503 |
if (!reply->isFinished()) |
| 1504 |
debug << "timed out."; |
| 1505 |
else if (reply->error() == QNetworkReply::NoError) |
| 1506 |
debug << "finished."; |
| 1507 |
else |
| 1508 |
debug << "failed: #" << reply->error() << reply->errorString(); |
| 1509 |
return result.toLocal8Bit(); |
| 1510 |
} |
| 1511 |
|
| 1512 |
int tst_QNetworkReply::waitForFinish(QNetworkReplyPtr &reply) |
| 1513 |
{ |
| 1514 |
int count = 0; |
| 1515 |
|
| 1516 |
connect(reply, SIGNAL(finished()), SLOT(finished())); |
| 1517 |
connect(reply, SIGNAL(errorOccurred(QNetworkReply::NetworkError)), SLOT(gotError())); |
| 1518 |
returnCode = Success; |
| 1519 |
loop = new QEventLoop; |
| 1520 |
QSignalSpy spy(reply.data(), SIGNAL(downloadProgress(qint64,qint64))); |
| 1521 |
while (!reply->isFinished()) { |
| 1522 |
QTimer::singleShot(5000, loop, SLOT(quit())); |
| 1523 |
if (loop->exec() == Timeout && count == spy.count() && !reply->isFinished()) { |
| 1524 |
returnCode = Timeout; |
| 1525 |
break; |
| 1526 |
} |
| 1527 |
count = spy.count(); |
| 1528 |
} |
| 1529 |
delete loop; |
| 1530 |
loop = 0; |
| 1531 |
|
| 1532 |
return returnCode; |
| 1533 |
} |
| 1534 |
|
| 1535 |
void tst_QNetworkReply::finished() |
| 1536 |
{ |
| 1537 |
if (loop) |
| 1538 |
loop->exit(returnCode = Success); |
| 1539 |
} |
| 1540 |
|
| 1541 |
void tst_QNetworkReply::gotError() |
| 1542 |
{ |
| 1543 |
if (loop) |
| 1544 |
loop->exit(returnCode = Failure); |
| 1545 |
disconnect(QObject::sender(), SIGNAL(finished()), this, 0); |
| 1546 |
} |
| 1547 |
|
| 1548 |
void tst_QNetworkReply::initTestCase() |
| 1549 |
{ |
| 1550 |
testDataDir = QFileInfo(QFINDTESTDATA("rfc3252.txt")).absolutePath(); |
| 1551 |
if (testDataDir.isEmpty()) |
| 1552 |
testDataDir = QCoreApplication::applicationDirPath(); |
| 1553 |
|
| 1554 |
#if defined(QT_TEST_SERVER) |
| 1555 |
QVERIFY(QtNetworkSettings::verifyConnection(QtNetworkSettings::ftpServerName(), 21)); |
| 1556 |
QVERIFY(QtNetworkSettings::verifyConnection(QtNetworkSettings::ftpProxyServerName(), 2121)); |
| 1557 |
QVERIFY(QtNetworkSettings::verifyConnection(QtNetworkSettings::httpServerName(), 80)); |
| 1558 |
QVERIFY(QtNetworkSettings::verifyConnection(QtNetworkSettings::httpServerName(), 443)); |
| 1559 |
QVERIFY(QtNetworkSettings::verifyConnection(QtNetworkSettings::httpProxyServerName(), 3128)); |
| 1560 |
QVERIFY(QtNetworkSettings::verifyConnection(QtNetworkSettings::httpProxyServerName(), 3129)); |
| 1561 |
QVERIFY(QtNetworkSettings::verifyConnection(QtNetworkSettings::httpProxyServerName(), 3130)); |
| 1562 |
QVERIFY(QtNetworkSettings::verifyConnection(QtNetworkSettings::socksProxyServerName(), 1080)); |
| 1563 |
QVERIFY(QtNetworkSettings::verifyConnection(QtNetworkSettings::socksProxyServerName(), 1081)); |
| 1564 |
#else |
| 1565 |
if (!QtNetworkSettings::verifyTestNetworkSettings()) |
| 1566 |
QSKIP("No network test server available"); |
| 1567 |
#endif |
| 1568 |
#if !defined Q_OS_WIN |
| 1569 |
wronlyFileName = testDataDir + "/write-only" + uniqueExtension; |
| 1570 |
QFile wr(wronlyFileName); |
| 1571 |
QVERIFY(wr.open(QIODevice::WriteOnly | QIODevice::Truncate)); |
| 1572 |
wr.setPermissions(QFile::WriteOwner | QFile::WriteUser); |
| 1573 |
wr.close(); |
| 1574 |
#endif |
| 1575 |
|
| 1576 |
QDir::setSearchPaths("testdata", QStringList() << testDataDir); |
| 1577 |
#ifndef QT_NO_SSL |
| 1578 |
QSslConfiguration::defaultConfiguration().caCertificates(); //preload certificates |
| 1579 |
#endif |
| 1580 |
#ifndef QT_NO_BEARERMANAGEMENT |
| 1581 |
netConfMan = new QNetworkConfigurationManager(this); |
| 1582 |
networkConfiguration = netConfMan->defaultConfiguration(); |
| 1583 |
networkSession.reset(new QNetworkSession(networkConfiguration)); |
| 1584 |
if (!networkSession->isOpen()) { |
| 1585 |
networkSession->open(); |
| 1586 |
QVERIFY(networkSession->waitForOpened(30000)); |
| 1587 |
} |
| 1588 |
#endif |
| 1589 |
|
| 1590 |
echoProcessDir = QFINDTESTDATA("echo"); |
| 1591 |
QVERIFY2(!echoProcessDir.isEmpty(), qPrintable( |
| 1592 |
QString::fromLatin1("Couldn't find echo dir starting from %1.").arg(QDir::currentPath()))); |
| 1593 |
|
| 1594 |
cleanupTestData(); |
| 1595 |
#ifndef QT_NO_OPENSSL |
| 1596 |
QT_PREPEND_NAMESPACE(qt_ForceTlsSecurityLevel)(); |
| 1597 |
#endif // QT_NO_OPENSSL |
| 1598 |
|
| 1599 |
} |
| 1600 |
|
| 1601 |
void tst_QNetworkReply::cleanupTestCase() |
| 1602 |
{ |
| 1603 |
#if !defined Q_OS_WIN |
| 1604 |
if (!wronlyFileName.isNull()) |
| 1605 |
QFile::remove(wronlyFileName); |
| 1606 |
#endif |
| 1607 |
#ifndef QT_NO_BEARERMANAGEMENT |
| 1608 |
if (networkSession && networkSession->isOpen()) { |
| 1609 |
networkSession->close(); |
| 1610 |
} |
| 1611 |
#endif |
| 1612 |
} |
| 1613 |
|
| 1614 |
void tst_QNetworkReply::cleanupTestData() |
| 1615 |
{ |
| 1616 |
QFile file(testFileName); |
| 1617 |
QVERIFY(!file.exists() || file.remove()); |
| 1618 |
|
| 1619 |
// clear the internal cache |
| 1620 |
manager.clearAccessCache(); |
| 1621 |
#ifndef QT_NO_NETWORKPROXY |
| 1622 |
manager.setProxy(QNetworkProxy()); |
| 1623 |
#endif |
| 1624 |
manager.setCache(0); |
| 1625 |
|
| 1626 |
// clear cookies |
| 1627 |
cookieJar->setAllCookies(QList<QNetworkCookie>()); |
| 1628 |
|
| 1629 |
// disconnect manager signals |
| 1630 |
#ifndef QT_NO_SSL |
| 1631 |
manager.disconnect(SIGNAL(sslErrors(QNetworkReply*,QList<QSslError>))); |
| 1632 |
#endif |
| 1633 |
manager.disconnect(SIGNAL(authenticationRequired(QNetworkReply*,QAuthenticator*))); |
| 1634 |
manager.disconnect(SIGNAL(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*))); |
| 1635 |
} |
| 1636 |
|
| 1637 |
void tst_QNetworkReply::stateChecking() |
| 1638 |
{ |
| 1639 |
QUrl url = QUrl("file:///"); |
| 1640 |
QNetworkRequest req(url); // you can't open this file, I know |
| 1641 |
QNetworkReplyPtr reply(manager.get(req)); |
| 1642 |
|
| 1643 |
QVERIFY(reply.data()); |
| 1644 |
QVERIFY(reply->isOpen()); |
| 1645 |
QVERIFY(reply->isReadable()); |
| 1646 |
QVERIFY(!reply->isWritable()); |
| 1647 |
|
| 1648 |
// both behaviours are OK since we might change underlying behaviour again |
| 1649 |
if (!reply->isFinished()) |
| 1650 |
QCOMPARE(reply->errorString(), QString("Unknown error")); |
| 1651 |
else |
| 1652 |
QVERIFY(!reply->errorString().isEmpty()); |
| 1653 |
|
| 1654 |
|
| 1655 |
QCOMPARE(reply->manager(), &manager); |
| 1656 |
QCOMPARE(reply->request(), req); |
| 1657 |
QCOMPARE(int(reply->operation()), int(QNetworkAccessManager::GetOperation)); |
| 1658 |
// error and not error are OK since we might change underlying behaviour again |
| 1659 |
if (!reply->isFinished()) |
| 1660 |
QCOMPARE(reply->error(), QNetworkReply::NoError); |
| 1661 |
QCOMPARE(reply->url(), url); |
| 1662 |
|
| 1663 |
reply->abort(); |
| 1664 |
} |
| 1665 |
|
| 1666 |
void tst_QNetworkReply::invalidProtocol() |
| 1667 |
{ |
| 1668 |
QUrl url = QUrl::fromEncoded("not-a-known-protocol://foo/bar"); |
| 1669 |
QNetworkRequest req(url); |
| 1670 |
QNetworkReplyPtr reply; |
| 1671 |
|
| 1672 |
QString errorMsg = "Request failed: Protocol \"not-a-known-protocol\" is unknown"; |
| 1673 |
QString result = runSimpleRequest(QNetworkAccessManager::GetOperation, req, reply); |
| 1674 |
QCOMPARE(result, errorMsg); |
| 1675 |
|
| 1676 |
QCOMPARE(reply->url(), url); |
| 1677 |
QCOMPARE(reply->error(), QNetworkReply::ProtocolUnknownError); |
| 1678 |
} |
| 1679 |
|
| 1680 |
void tst_QNetworkReply::getFromData_data() |
| 1681 |
{ |
| 1682 |
QTest::addColumn<QString>("request"); |
| 1683 |
QTest::addColumn<QByteArray>("expected"); |
| 1684 |
QTest::addColumn<QString>("mimeType"); |
| 1685 |
|
| 1686 |
const QString defaultMimeType("text/plain;charset=US-ASCII"); |
| 1687 |
|
| 1688 |
//QTest::newRow("empty") << "data:" << QByteArray() << defaultMimeType; |
| 1689 |
QTest::newRow("empty2") << "data:," << QByteArray() << defaultMimeType; |
| 1690 |
QTest::newRow("just-charset_1") << "data:charset=iso-8859-1," |
| 1691 |
<< QByteArray() << "text/plain;charset=iso-8859-1"; |
| 1692 |
QTest::newRow("just-charset_2") << "data:charset = iso-8859-1 ," |
| 1693 |
<< QByteArray() << "text/plain;charset = iso-8859-1"; |
| 1694 |
//QTest::newRow("just-media") << "data:text/xml" << QByteArray() << "text/xml"; |
| 1695 |
QTest::newRow("just-media2") << "data:text/xml," << QByteArray() << "text/xml"; |
| 1696 |
|
| 1697 |
QTest::newRow("plain_1") << "data:,foo" << QByteArray("foo") << defaultMimeType; |
| 1698 |
QTest::newRow("plain_2") << "data:text/html,Hello World" << QByteArray("Hello World") |
| 1699 |
<< "text/html"; |
| 1700 |
QTest::newRow("plain_3") << "data:text/html;charset=utf-8,Hello World" |
| 1701 |
<< QByteArray("Hello World") << "text/html;charset=utf-8"; |
| 1702 |
|
| 1703 |
QTest::newRow("pct_1") << "data:,%3Cbody%20contentEditable%3Dtrue%3E%0D%0A" |
| 1704 |
<< QByteArray("<body contentEditable=true>\r\n") << defaultMimeType; |
| 1705 |
QTest::newRow("pct_2") << "data:text/html;charset=utf-8,%3Cbody%20contentEditable%3Dtrue%3E%0D%0A" |
| 1706 |
<< QByteArray("<body contentEditable=true>\r\n") |
| 1707 |
<< "text/html;charset=utf-8"; |
| 1708 |
|
| 1709 |
QTest::newRow("base64-empty_1") << "data:;base64," << QByteArray() << defaultMimeType; |
| 1710 |
QTest::newRow("base64-empty_2") << "data:charset=utf-8;base64," << QByteArray() |
| 1711 |
<< "text/plain;charset=utf-8"; |
| 1712 |
QTest::newRow("base64-empty_3") << "data:text/html;charset=utf-8;base64," |
| 1713 |
<< QByteArray() << "text/html;charset=utf-8"; |
| 1714 |
|
| 1715 |
QTest::newRow("base64_1") << "data:;base64,UXQgaXMgZ3JlYXQh" << QByteArray("Qt is great!") |
| 1716 |
<< defaultMimeType; |
| 1717 |
QTest::newRow("base64_2") << "data:charset=utf-8;base64,UXQgaXMgZ3JlYXQh" |
| 1718 |
<< QByteArray("Qt is great!") << "text/plain;charset=utf-8"; |
| 1719 |
QTest::newRow("base64_3") << "data:text/html;charset=utf-8;base64,UXQgaXMgZ3JlYXQh" |
| 1720 |
<< QByteArray("Qt is great!") << "text/html;charset=utf-8"; |
| 1721 |
|
| 1722 |
QTest::newRow("pct-nul") << "data:,a%00g" << QByteArray("a\0g", 3) << defaultMimeType; |
| 1723 |
QTest::newRow("base64-nul") << "data:;base64,YQBn" << QByteArray("a\0g", 3) << defaultMimeType; |
| 1724 |
QTest::newRow("pct-nonutf8") << "data:,a%E1g" << QByteArray("a\xE1g", 3) << defaultMimeType; |
| 1725 |
|
| 1726 |
QTest::newRow("base64") |
| 1727 |
<< QString::fromLatin1("data:application/xml;base64,PGUvPg==") |
| 1728 |
<< QByteArray("<e/>") |
| 1729 |
<< "application/xml"; |
| 1730 |
|
| 1731 |
QTest::newRow("base64, no media type") |
| 1732 |
<< QString::fromLatin1("data:;base64,PGUvPg==") |
| 1733 |
<< QByteArray("<e/>") |
| 1734 |
<< defaultMimeType; |
| 1735 |
|
| 1736 |
QTest::newRow("Percent encoding") |
| 1737 |
<< QString::fromLatin1("data:application/xml,%3Ce%2F%3E") |
| 1738 |
<< QByteArray("<e/>") |
| 1739 |
<< "application/xml"; |
| 1740 |
|
| 1741 |
QTest::newRow("Percent encoding, no media type") |
| 1742 |
<< QString::fromLatin1("data:,%3Ce%2F%3E") |
| 1743 |
<< QByteArray("<e/>") |
| 1744 |
<< defaultMimeType; |
| 1745 |
|
| 1746 |
QTest::newRow("querychars") |
| 1747 |
<< QString::fromLatin1("data:,foo?x=0&y=0") |
| 1748 |
<< QByteArray("foo?x=0&y=0") |
| 1749 |
<< defaultMimeType; |
| 1750 |
|
| 1751 |
QTest::newRow("css") << "data:text/css,div%20{%20border-right:%20solid;%20}" |
| 1752 |
<< QByteArray("div { border-right: solid; }") |
| 1753 |
<< "text/css"; |
| 1754 |
} |
| 1755 |
|
| 1756 |
void tst_QNetworkReply::getFromData() |
| 1757 |
{ |
| 1758 |
QFETCH(QString, request); |
| 1759 |
QFETCH(QByteArray, expected); |
| 1760 |
QFETCH(QString, mimeType); |
| 1761 |
|
| 1762 |
QUrl url = QUrl::fromEncoded(request.toLatin1()); |
| 1763 |
QNetworkRequest req(url); |
| 1764 |
QNetworkReplyPtr reply; |
| 1765 |
|
| 1766 |
RUN_REQUEST(runSimpleRequest(QNetworkAccessManager::GetOperation, req, reply)); |
| 1767 |
|
| 1768 |
QCOMPARE(reply->url(), url); |
| 1769 |
QCOMPARE(reply->error(), QNetworkReply::NoError); |
| 1770 |
|
| 1771 |
QCOMPARE(reply->header(QNetworkRequest::ContentTypeHeader).toString(), mimeType); |
| 1772 |
QCOMPARE(reply->header(QNetworkRequest::ContentLengthHeader).toLongLong(), qint64(expected.size())); |
| 1773 |
QCOMPARE(reply->readAll(), expected); |
| 1774 |
} |
| 1775 |
|
| 1776 |
void tst_QNetworkReply::getFromFile_data() |
| 1777 |
{ |
| 1778 |
QTest::addColumn<bool>("backgroundAttribute"); |
| 1779 |
|
| 1780 |
QTest::newRow("no-background-attribute") << false; |
| 1781 |
QTest::newRow("background-attribute") << true; |
| 1782 |
} |
| 1783 |
|
| 1784 |
void tst_QNetworkReply::getFromFile() |
| 1785 |
{ |
| 1786 |
QFETCH(bool, backgroundAttribute); |
| 1787 |
|
| 1788 |
// create the file: |
| 1789 |
QTemporaryFile file(QDir::currentPath() + "/temp-XXXXXX"); |
| 1790 |
file.setAutoRemove(true); |
| 1791 |
QVERIFY2(file.open(), qPrintable(file.errorString())); |
| 1792 |
|
| 1793 |
QNetworkRequest request(QUrl::fromLocalFile(file.fileName())); |
| 1794 |
if (backgroundAttribute) |
| 1795 |
request.setAttribute(QNetworkRequest::BackgroundRequestAttribute, QVariant::fromValue(true)); |
| 1796 |
QNetworkReplyPtr reply; |
| 1797 |
|
| 1798 |
static const char fileData[] = "This is some data that is in the file.\r\n"; |
| 1799 |
QByteArray data = QByteArray::fromRawData(fileData, sizeof fileData - 1); |
| 1800 |
QCOMPARE(file.write(data), data.size()); |
| 1801 |
file.flush(); |
| 1802 |
QCOMPARE(file.size(), qint64(data.size())); |
| 1803 |
|
| 1804 |
RUN_REQUEST(runSimpleRequest(QNetworkAccessManager::GetOperation, request, reply)); |
| 1805 |
QVERIFY(waitForFinish(reply) != Timeout); |
| 1806 |
|
| 1807 |
QCOMPARE(reply->url(), request.url()); |
| 1808 |
QCOMPARE(reply->error(), QNetworkReply::NoError); |
| 1809 |
|
| 1810 |
QCOMPARE(reply->header(QNetworkRequest::ContentLengthHeader).toLongLong(), file.size()); |
| 1811 |
QCOMPARE(reply->readAll(), data); |
| 1812 |
|
| 1813 |
// make the file bigger |
| 1814 |
file.resize(0); |
| 1815 |
const int multiply = (128 * 1024) / (sizeof fileData - 1); |
| 1816 |
for (int i = 0; i < multiply; ++i) |
| 1817 |
file.write(fileData, sizeof fileData - 1); |
| 1818 |
file.flush(); |
| 1819 |
|
| 1820 |
// run again |
| 1821 |
reply.clear(); |
| 1822 |
|
| 1823 |
RUN_REQUEST(runSimpleRequest(QNetworkAccessManager::GetOperation, request, reply)); |
| 1824 |
QCOMPARE(reply->url(), request.url()); |
| 1825 |
QCOMPARE(reply->error(), QNetworkReply::NoError); |
| 1826 |
|
| 1827 |
QCOMPARE(reply->header(QNetworkRequest::ContentLengthHeader).toLongLong(), file.size()); |
| 1828 |
QCOMPARE(qint64(reply->readAll().size()), file.size()); |
| 1829 |
} |
| 1830 |
|
| 1831 |
void tst_QNetworkReply::getFromFileSpecial_data() |
| 1832 |
{ |
| 1833 |
QTest::addColumn<QString>("fileName"); |
| 1834 |
QTest::addColumn<QString>("url"); |
| 1835 |
|
| 1836 |
QTest::newRow("resource") << ":/resource" << "qrc:/resource"; |
| 1837 |
QTest::newRow("search-path") << "testdata:/rfc3252.txt" << "testdata:/rfc3252.txt"; |
| 1838 |
QTest::newRow("bigfile-path") << "testdata:/bigfile" << "testdata:/bigfile"; |
| 1839 |
#ifdef Q_OS_WIN |
| 1840 |
QTest::newRow("smb-path") << "testdata:/smb-file.txt" << "file://" + QtNetworkSettings::winServerName() + "/testshare/test.pri"; |
| 1841 |
#endif |
| 1842 |
} |
| 1843 |
|
| 1844 |
void tst_QNetworkReply::getFromFileSpecial() |
| 1845 |
{ |
| 1846 |
#if defined(QT_TEST_SERVER) && defined(Q_OS_WIN) |
| 1847 |
if (qstrcmp(QTest::currentDataTag(), "smb-path") == 0) |
| 1848 |
QSKIP("Docker-based test server doesn't support smb protocol yet"); |
| 1849 |
#endif |
| 1850 |
|
| 1851 |
QFETCH(QString, fileName); |
| 1852 |
QFETCH(QString, url); |
| 1853 |
|
| 1854 |
// open the resource so we can find out its size |
| 1855 |
QFile resource(fileName); |
| 1856 |
QVERIFY(resource.open(QIODevice::ReadOnly)); |
| 1857 |
|
| 1858 |
QNetworkRequest request; |
| 1859 |
QNetworkReplyPtr reply; |
| 1860 |
request.setUrl(url); |
| 1861 |
RUN_REQUEST(runSimpleRequest(QNetworkAccessManager::GetOperation, request, reply)); |
| 1862 |
|
| 1863 |
QCOMPARE(reply->url(), request.url()); |
| 1864 |
QCOMPARE(reply->error(), QNetworkReply::NoError); |
| 1865 |
|
| 1866 |
QCOMPARE(reply->header(QNetworkRequest::ContentLengthHeader).toLongLong(), resource.size()); |
| 1867 |
QCOMPARE(reply->readAll(), resource.readAll()); |
| 1868 |
} |
| 1869 |
|
| 1870 |
void tst_QNetworkReply::getFromFtp_data() |
| 1871 |
{ |
| 1872 |
QTest::addColumn<QString>("referenceName"); |
| 1873 |
QTest::addColumn<QString>("url"); |
| 1874 |
|
| 1875 |
QTest::newRow("rfc3252.txt") |
| 1876 |
<< testDataDir + "/rfc3252.txt" |
| 1877 |
<< "ftp://" + QtNetworkSettings::ftpServerName() + "/qtest/rfc3252.txt"; |
| 1878 |
|
| 1879 |
QTest::newRow("bigfile") |
| 1880 |
<< testDataDir + "/bigfile" |
| 1881 |
<< "ftp://" + QtNetworkSettings::ftpServerName() + "/qtest/bigfile"; |
| 1882 |
} |
| 1883 |
|
| 1884 |
void tst_QNetworkReply::getFromFtp() |
| 1885 |
{ |
| 1886 |
QFETCH(QString, referenceName); |
| 1887 |
QFETCH(QString, url); |
| 1888 |
|
| 1889 |
QFile reference(referenceName); |
| 1890 |
QVERIFY(reference.open(QIODevice::ReadOnly)); |
| 1891 |
|
| 1892 |
QNetworkRequest request(url); |
| 1893 |
QNetworkReplyPtr reply; |
| 1894 |
RUN_REQUEST(runSimpleRequest(QNetworkAccessManager::GetOperation, request, reply)); |
| 1895 |
|
| 1896 |
QCOMPARE(reply->url(), request.url()); |
| 1897 |
QCOMPARE(reply->error(), QNetworkReply::NoError); |
| 1898 |
|
| 1899 |
QCOMPARE(reply->header(QNetworkRequest::ContentLengthHeader).toLongLong(), reference.size()); |
| 1900 |
QCOMPARE(reply->readAll(), reference.readAll()); |
| 1901 |
} |
| 1902 |
|
| 1903 |
void tst_QNetworkReply::getFromFtpAfterError() |
| 1904 |
{ |
| 1905 |
QNetworkRequest invalidRequest(QUrl("ftp://" + QtNetworkSettings::ftpServerName() + "/qtest/invalid.txt")); |
| 1906 |
QNetworkReplyPtr invalidReply; |
| 1907 |
invalidReply.reset(manager.get(invalidRequest)); |
| 1908 |
QSignalSpy spy(invalidReply.data(), SIGNAL(errorOccurred(QNetworkReply::NetworkError))); |
| 1909 |
QVERIFY(spy.wait()); |
| 1910 |
QCOMPARE(invalidReply->error(), QNetworkReply::ContentNotFoundError); |
| 1911 |
|
| 1912 |
QFile reference(testDataDir + "/rfc3252.txt"); |
| 1913 |
QVERIFY(reference.open(QIODevice::ReadOnly)); |
| 1914 |
QNetworkRequest validRequest(QUrl("ftp://" + QtNetworkSettings::ftpServerName() + "/qtest/rfc3252.txt")); |
| 1915 |
QNetworkReplyPtr validReply; |
| 1916 |
RUN_REQUEST(runSimpleRequest(QNetworkAccessManager::GetOperation, validRequest, validReply)); |
| 1917 |
QCOMPARE(validReply->url(), validRequest.url()); |
| 1918 |
QCOMPARE(validReply->error(), QNetworkReply::NoError); |
| 1919 |
QCOMPARE(validReply->header(QNetworkRequest::ContentLengthHeader).toLongLong(), reference.size()); |
| 1920 |
QCOMPARE(validReply->readAll(), reference.readAll()); |
| 1921 |
} |
| 1922 |
|
| 1923 |
void tst_QNetworkReply::getFromHttp_data() |
| 1924 |
{ |
| 1925 |
QTest::addColumn<QString>("referenceName"); |
| 1926 |
QTest::addColumn<QString>("url"); |
| 1927 |
|
| 1928 |
QTest::newRow("success-internal") |
| 1929 |
<< testDataDir + "/rfc3252.txt" |
| 1930 |
<< "http://" + QtNetworkSettings::httpServerName() + "/qtest/rfc3252.txt"; |
| 1931 |
|
| 1932 |
QTest::newRow("success-external") |
| 1933 |
<< testDataDir + "/rfc3252.txt" |
| 1934 |
<< "http://www.ietf.org/rfc/rfc3252.txt"; |
| 1935 |
|
| 1936 |
QTest::newRow("bigfile-internal") |
| 1937 |
<< testDataDir + "/bigfile" |
| 1938 |
<< "http://" + QtNetworkSettings::httpServerName() + "/qtest/bigfile"; |
| 1939 |
} |
| 1940 |
|
| 1941 |
void tst_QNetworkReply::getFromHttp() |
| 1942 |
{ |
| 1943 |
QFETCH(QString, referenceName); |
| 1944 |
QFETCH(QString, url); |
| 1945 |
|
| 1946 |
QFile reference(referenceName); |
| 1947 |
QVERIFY(reference.open(QIODevice::ReadOnly)); |
| 1948 |
|
| 1949 |
QNetworkRequest request(url); |
| 1950 |
QNetworkReplyPtr reply; |
| 1951 |
RUN_REQUEST(runSimpleRequest(QNetworkAccessManager::GetOperation, request, reply)); |
| 1952 |
|
| 1953 |
QCOMPARE(reply->url(), request.url()); |
| 1954 |
QCOMPARE(reply->error(), QNetworkReply::NoError); |
| 1955 |
QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200); |
| 1956 |
QCOMPARE(reply->size(), reference.size()); |
| 1957 |
// only compare when the header is set. |
| 1958 |
if (reply->header(QNetworkRequest::ContentLengthHeader).isValid()) |
| 1959 |
QCOMPARE(reply->header(QNetworkRequest::ContentLengthHeader).toLongLong(), reference.size()); |
| 1960 |
|
| 1961 |
// We know our internal server is apache.. |
| 1962 |
if (qstrcmp(QTest::currentDataTag(), "success-internal") == 0) |
| 1963 |
QVERIFY(reply->header(QNetworkRequest::ServerHeader).toString().contains("Apache")); |
| 1964 |
|
| 1965 |
QCOMPARE(reply->readAll(), reference.readAll()); |
| 1966 |
} |
| 1967 |
|
| 1968 |
#ifndef QT_NO_NETWORKPROXY |
| 1969 |
void tst_QNetworkReply::headFromHttp_data() |
| 1970 |
{ |
| 1971 |
QTest::addColumn<qint64>("referenceSize"); |
| 1972 |
QTest::addColumn<QUrl>("url"); |
| 1973 |
QTest::addColumn<QString>("contentType"); |
| 1974 |
QTest::addColumn<QNetworkProxy>("proxy"); |
| 1975 |
|
| 1976 |
qint64 rfcsize = QFileInfo(testDataDir + "/rfc3252.txt").size(); |
| 1977 |
qint64 bigfilesize = QFileInfo(testDataDir + "/bigfile").size(); |
| 1978 |
|
| 1979 |
#if defined(QT_TEST_SERVER) |
| 1980 |
qint64 indexsize = QFileInfo(testDataDir + "/testserver_index.html").size(); |
| 1981 |
#else |
| 1982 |
qint64 indexsize = QFileInfo(testDataDir + "/index.html").size(); |
| 1983 |
#endif |
| 1984 |
|
| 1985 |
QString httpServer = QtNetworkSettings::httpServerName(); |
| 1986 |
//testing proxies, mainly for the 407 response from http proxy |
| 1987 |
for (int i = 0; i < proxies.count(); ++i) { |
| 1988 |
QTest::newRow("rfc" + proxies.at(i).tag) |
| 1989 |
<< rfcsize |
| 1990 |
<< QUrl("http://" + httpServer + "/qtest/rfc3252.txt") |
| 1991 |
<< "text/plain" |
| 1992 |
<< proxies.at(i).proxy; |
| 1993 |
|
| 1994 |
QTest::newRow("bigfile" + proxies.at(i).tag) |
| 1995 |
<< bigfilesize |
| 1996 |
<< QUrl("http://" + httpServer + "/qtest/bigfile") |
| 1997 |
<< "text/plain" |
| 1998 |
<< proxies.at(i).proxy; |
| 1999 |
|
| 2000 |
QTest::newRow("index" + proxies.at(i).tag) |
| 2001 |
<< indexsize |
| 2002 |
<< QUrl("http://" + httpServer + "/qtest/") |
| 2003 |
<< "text/html" |
| 2004 |
<< proxies.at(i).proxy; |
| 2005 |
|
| 2006 |
QTest::newRow("with-authentication" + proxies.at(i).tag) |
| 2007 |
<< rfcsize |
| 2008 |
<< QUrl("http://" + httpServer + "/qtest/rfcs-auth/rfc3252.txt") |
| 2009 |
<< "text/plain" |
| 2010 |
<< proxies.at(i).proxy; |
| 2011 |
|
| 2012 |
QTest::newRow("cgi" + proxies.at(i).tag) |
| 2013 |
<< (qint64)-1 |
| 2014 |
<< QUrl("http://" + httpServer + "/qtest/cgi-bin/httpcachetest_expires500.cgi") |
| 2015 |
<< "text/html" |
| 2016 |
<< proxies.at(i).proxy; |
| 2017 |
} |
| 2018 |
} |
| 2019 |
|
| 2020 |
void tst_QNetworkReply::headFromHttp() |
| 2021 |
{ |
| 2022 |
QFETCH(qint64, referenceSize); |
| 2023 |
QFETCH(QUrl, url); |
| 2024 |
QFETCH(QString, contentType); |
| 2025 |
QFETCH(QNetworkProxy, proxy); |
| 2026 |
|
| 2027 |
QNetworkRequest request(url); |
| 2028 |
QNetworkReplyPtr reply; |
| 2029 |
|
| 2030 |
QElapsedTimer time; |
| 2031 |
time.start(); |
| 2032 |
|
| 2033 |
manager.setProxy(proxy); |
| 2034 |
connect(&manager, SIGNAL(authenticationRequired(QNetworkReply*,QAuthenticator*)), |
| 2035 |
SLOT(authenticationRequired(QNetworkReply*,QAuthenticator*))); |
| 2036 |
connect(&manager, SIGNAL(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)), |
| 2037 |
SLOT(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*))); |
| 2038 |
|
| 2039 |
RUN_REQUEST(runSimpleRequest(QNetworkAccessManager::HeadOperation, request, reply)); |
| 2040 |
|
| 2041 |
manager.disconnect(SIGNAL(authenticationRequired(QNetworkReply*,QAuthenticator*)), |
| 2042 |
this, SLOT(authenticationRequired(QNetworkReply*,QAuthenticator*))); |
| 2043 |
manager.disconnect(SIGNAL(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)), |
| 2044 |
this, SLOT(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*))); |
| 2045 |
|
| 2046 |
QVERIFY(time.elapsed() < 8000); //check authentication didn't wait for the server to timeout the http connection (15s on qt test server) |
| 2047 |
|
| 2048 |
QCOMPARE(reply->url(), request.url()); |
| 2049 |
QCOMPARE(reply->error(), QNetworkReply::NoError); |
| 2050 |
QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200); |
| 2051 |
// only compare when the header is set. |
| 2052 |
if (reply->header(QNetworkRequest::ContentLengthHeader).isValid() && referenceSize >= 0) |
| 2053 |
QCOMPARE(reply->header(QNetworkRequest::ContentLengthHeader).toLongLong(), referenceSize); |
| 2054 |
if (reply->header(QNetworkRequest::ContentTypeHeader).isValid()) |
| 2055 |
QCOMPARE(reply->header(QNetworkRequest::ContentTypeHeader).toString(), contentType); |
| 2056 |
} |
| 2057 |
#endif // !QT_NO_NETWORKPROXY |
| 2058 |
|
| 2059 |
void tst_QNetworkReply::getErrors_data() |
| 2060 |
{ |
| 2061 |
QTest::addColumn<QString>("url"); |
| 2062 |
QTest::addColumn<int>("error"); |
| 2063 |
QTest::addColumn<int>("httpStatusCode"); |
| 2064 |
QTest::addColumn<bool>("dataIsEmpty"); |
| 2065 |
|
| 2066 |
// empties |
| 2067 |
QTest::newRow("empty-url") << QString() << int(QNetworkReply::ProtocolUnknownError) << 0 << true; |
| 2068 |
QTest::newRow("empty-scheme-host") << (testDataDir + "/rfc3252.txt") << int(QNetworkReply::ProtocolUnknownError) << 0 << true; |
| 2069 |
QTest::newRow("empty-scheme") << "//" + QtNetworkSettings::winServerName() + "/testshare/test.pri" |
| 2070 |
<< int(QNetworkReply::ProtocolUnknownError) << 0 << true; |
| 2071 |
|
| 2072 |
// file: errors |
| 2073 |
QTest::newRow("file-host") << "file://invalid.test.qt-project.org/foo.txt" |
| 2074 |
#if !defined Q_OS_WIN |
| 2075 |
<< int(QNetworkReply::ProtocolInvalidOperationError) << 0 << true; |
| 2076 |
#else |
| 2077 |
<< int(QNetworkReply::ContentNotFoundError) << 0 << true; |
| 2078 |
#endif |
| 2079 |
QTest::newRow("file-no-path") << "file://localhost" |
| 2080 |
<< int(QNetworkReply::ContentOperationNotPermittedError) << 0 << true; |
| 2081 |
QTest::newRow("file-is-dir") << QUrl::fromLocalFile(QDir::currentPath()).toString() |
| 2082 |
<< int(QNetworkReply::ContentOperationNotPermittedError) << 0 << true; |
| 2083 |
QTest::newRow("file-exist") << QUrl::fromLocalFile(QDir::currentPath() + "/this-file-doesnt-exist.txt").toString() |
| 2084 |
<< int(QNetworkReply::ContentNotFoundError) << 0 << true; |
| 2085 |
#if !defined Q_OS_WIN |
| 2086 |
QTest::newRow("file-is-wronly") << QUrl::fromLocalFile(wronlyFileName).toString() |
| 2087 |
<< int(QNetworkReply::ContentAccessDenied) << 0 << true; |
| 2088 |
#endif |
| 2089 |
|
| 2090 |
|
| 2091 |
if (QFile::exists(filePermissionFileName)) |
| 2092 |
QTest::newRow("file-permissions") << "file:" + filePermissionFileName |
| 2093 |
<< int(QNetworkReply::ContentAccessDenied) << 0 << true; |
| 2094 |
|
| 2095 |
// ftp: errors |
| 2096 |
QTest::newRow("ftp-host") << "ftp://invalid.test.qt-project.org/foo.txt" |
| 2097 |
<< int(QNetworkReply::HostNotFoundError) << 0 << true; |
| 2098 |
QTest::newRow("ftp-no-path") << "ftp://" + QtNetworkSettings::ftpServerName() |
| 2099 |
<< int(QNetworkReply::ContentOperationNotPermittedError) << 0 << true; |
| 2100 |
QTest::newRow("ftp-is-dir") << "ftp://" + QtNetworkSettings::ftpServerName() + "/qtest" |
| 2101 |
<< int(QNetworkReply::ContentOperationNotPermittedError) << 0 << true; |
| 2102 |
QTest::newRow("ftp-dir-not-readable") << "ftp://" + QtNetworkSettings::ftpServerName() + "/pub/dir-not-readable/foo.txt" |
| 2103 |
<< int(QNetworkReply::ContentAccessDenied) << 0 << true; |
| 2104 |
QTest::newRow("ftp-file-not-readable") << "ftp://" + QtNetworkSettings::ftpServerName() + "/pub/file-not-readable.txt" |
| 2105 |
<< int(QNetworkReply::ContentAccessDenied) << 0 << true; |
| 2106 |
QTest::newRow("ftp-exist") << "ftp://" + QtNetworkSettings::ftpServerName() + "/pub/this-file-doesnt-exist.txt" |
| 2107 |
<< int(QNetworkReply::ContentNotFoundError) << 0 << true; |
| 2108 |
|
| 2109 |
// http: errors |
| 2110 |
QTest::newRow("http-host") << "http://invalid.test.qt-project.org/" |
| 2111 |
<< int(QNetworkReply::HostNotFoundError) << 0 << true; |
| 2112 |
QTest::newRow("http-exist") << "http://" + QtNetworkSettings::httpServerName() + "/this-file-doesnt-exist.txt" |
| 2113 |
<< int(QNetworkReply::ContentNotFoundError) << 404 << false; |
| 2114 |
QTest::newRow("http-authentication") << "http://" + QtNetworkSettings::httpServerName() + "/qtest/rfcs-auth" |
| 2115 |
<< int(QNetworkReply::AuthenticationRequiredError) << 401 << false; |
| 2116 |
} |
| 2117 |
|
| 2118 |
static QByteArray msgGetErrors(int waitResult, const QNetworkReplyPtr &reply) |
| 2119 |
{ |
| 2120 |
QByteArray result ="waitResult=" + QByteArray::number(waitResult); |
| 2121 |
if (reply->isFinished()) |
| 2122 |
result += ", finished"; |
| 2123 |
if (reply->error() != QNetworkReply::NoError) |
| 2124 |
result += ", error: " + QByteArray::number(int(reply->error())); |
| 2125 |
return result; |
| 2126 |
} |
| 2127 |
|
| 2128 |
void tst_QNetworkReply::getErrors() |
| 2129 |
{ |
| 2130 |
QFETCH(QString, url); |
| 2131 |
QNetworkRequest request(url); |
| 2132 |
|
| 2133 |
#ifdef Q_OS_UNIX |
| 2134 |
if ((qstrcmp(QTest::currentDataTag(), "file-is-wronly") == 0) || |
| 2135 |
(qstrcmp(QTest::currentDataTag(), "file-permissions") == 0)) { |
| 2136 |
if (::getuid() == 0) |
| 2137 |
QSKIP("Running this test as root doesn't make sense"); |
| 2138 |
|
| 2139 |
} |
| 2140 |
|
| 2141 |
if (EmulationDetector::isRunningArmOnX86() |
| 2142 |
&& qstrcmp(QTest::currentDataTag(), "file-permissions") == 0) { |
| 2143 |
QFileInfo filePermissionFile = QFileInfo(filePermissionFileName.toLatin1()); |
| 2144 |
if (filePermissionFile.ownerId() == ::geteuid()) { |
| 2145 |
QSKIP("Sysroot directories are owned by the current user"); |
| 2146 |
} |
| 2147 |
} |
| 2148 |
#endif |
| 2149 |
|
| 2150 |
QNetworkReplyPtr reply(manager.get(request)); |
| 2151 |
reply->setParent(this); // we have expect-fails |
| 2152 |
|
| 2153 |
if (!reply->isFinished()) |
| 2154 |
QCOMPARE(reply->error(), QNetworkReply::NoError); |
| 2155 |
|
| 2156 |
// now run the request: |
| 2157 |
const int waitResult = waitForFinish(reply); |
| 2158 |
QVERIFY2(waitResult != Timeout, msgGetErrors(waitResult, reply)); |
| 2159 |
|
| 2160 |
QFETCH(int, error); |
| 2161 |
QEXPECT_FAIL("ftp-is-dir", "QFtp cannot provide enough detail", Abort); |
| 2162 |
// the line below is not necessary |
| 2163 |
QEXPECT_FAIL("ftp-dir-not-readable", "QFtp cannot provide enough detail", Abort); |
| 2164 |
QCOMPARE(reply->error(), QNetworkReply::NetworkError(error)); |
| 2165 |
|
| 2166 |
QTEST(reply->readAll().isEmpty(), "dataIsEmpty"); |
| 2167 |
|
| 2168 |
QVERIFY(reply->isFinished()); |
| 2169 |
QVERIFY(!reply->isRunning()); |
| 2170 |
|
| 2171 |
QFETCH(int, httpStatusCode); |
| 2172 |
if (httpStatusCode != 0) { |
| 2173 |
QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), httpStatusCode); |
| 2174 |
} |
| 2175 |
} |
| 2176 |
|
| 2177 |
static inline QByteArray md5sum(const QByteArray &data) |
| 2178 |
{ |
| 2179 |
return QCryptographicHash::hash(data, QCryptographicHash::Md5); |
| 2180 |
} |
| 2181 |
|
| 2182 |
void tst_QNetworkReply::putToFile_data() |
| 2183 |
{ |
| 2184 |
QTest::addColumn<QByteArray>("data"); |
| 2185 |
QTest::addColumn<QByteArray>("md5sum"); |
| 2186 |
|
| 2187 |
QByteArray data; |
| 2188 |
data = ""; |
| 2189 |
QTest::newRow("empty") << data << md5sum(data); |
| 2190 |
|
| 2191 |
data = "This is a normal message."; |
| 2192 |
QTest::newRow("generic") << data << md5sum(data); |
| 2193 |
|
| 2194 |
data = "This is a message to show that Qt rocks!\r\n\n"; |
| 2195 |
QTest::newRow("small") << data << md5sum(data); |
| 2196 |
|
| 2197 |
data = QByteArray("abcd\0\1\2\abcd",12); |
| 2198 |
QTest::newRow("with-nul") << data << md5sum(data); |
| 2199 |
|
| 2200 |
data = QByteArray(4097, '\4'); |
| 2201 |
QTest::newRow("4k+1") << data << md5sum(data); |
| 2202 |
|
| 2203 |
data = QByteArray(128*1024+1, '\177'); |
| 2204 |
QTest::newRow("128k+1") << data << md5sum(data); |
| 2205 |
|
| 2206 |
data = QByteArray(2*1024*1024+1, '\177'); |
| 2207 |
QTest::newRow("2MB+1") << data << md5sum(data); |
| 2208 |
} |
| 2209 |
|
| 2210 |
void tst_QNetworkReply::putToFile() |
| 2211 |
{ |
| 2212 |
QFile file(testFileName); |
| 2213 |
|
| 2214 |
QUrl url = QUrl::fromLocalFile(file.fileName()); |
| 2215 |
QNetworkRequest request(url); |
| 2216 |
QNetworkReplyPtr reply; |
| 2217 |
|
| 2218 |
QFETCH(QByteArray, data); |
| 2219 |
|
| 2220 |
RUN_REQUEST(runSimpleRequest(QNetworkAccessManager::PutOperation, request, reply, data)); |
| 2221 |
|
| 2222 |
QCOMPARE(reply->url(), url); |
| 2223 |
QCOMPARE(reply->error(), QNetworkReply::NoError); |
| 2224 |
QCOMPARE(reply->header(QNetworkRequest::ContentLengthHeader).toLongLong(), Q_INT64_C(0)); |
| 2225 |
QVERIFY(reply->readAll().isEmpty()); |
| 2226 |
|
| 2227 |
QVERIFY(file.open(QIODevice::ReadOnly)); |
| 2228 |
QCOMPARE(file.size(), qint64(data.size())); |
| 2229 |
QByteArray contents = file.readAll(); |
| 2230 |
QCOMPARE(contents, data); |
| 2231 |
} |
| 2232 |
|
| 2233 |
void tst_QNetworkReply::putToFtp_data() |
| 2234 |
{ |
| 2235 |
putToFile_data(); |
| 2236 |
} |
| 2237 |
|
| 2238 |
void tst_QNetworkReply::putToFtp() |
| 2239 |
{ |
| 2240 |
QUrl url("ftp://" + QtNetworkSettings::ftpServerName()); |
| 2241 |
url.setPath(QString("/qtest/upload/qnetworkaccess-putToFtp-%1-%2") |
| 2242 |
.arg(QTest::currentDataTag()) |
| 2243 |
.arg(uniqueExtension)); |
| 2244 |
|
| 2245 |
QNetworkRequest request(url); |
| 2246 |
QNetworkReplyPtr reply; |
| 2247 |
|
| 2248 |
QFETCH(QByteArray, data); |
| 2249 |
|
| 2250 |
RUN_REQUEST(runSimpleRequest(QNetworkAccessManager::PutOperation, request, reply, data)); |
| 2251 |
|
| 2252 |
QCOMPARE(reply->url(), url); |
| 2253 |
QCOMPARE(reply->error(), QNetworkReply::NoError); |
| 2254 |
QCOMPARE(reply->header(QNetworkRequest::ContentLengthHeader).toLongLong(), Q_INT64_C(0)); |
| 2255 |
QVERIFY(reply->readAll().isEmpty()); |
| 2256 |
|
| 2257 |
// download the file again from FTP to make sure it was uploaded |
| 2258 |
// correctly |
| 2259 |
QNetworkAccessManager qnam; |
| 2260 |
QNetworkRequest req(url); |
| 2261 |
QNetworkReply *r = qnam.get(req); |
| 2262 |
|
| 2263 |
QObject::connect(r, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop())); |
| 2264 |
int count = 0; |
| 2265 |
QSignalSpy spy(r, SIGNAL(downloadProgress(qint64,qint64))); |
| 2266 |
while (!r->isFinished()) { |
| 2267 |
QTestEventLoop::instance().enterLoop(10); |
| 2268 |
if (count == spy.count() && !r->isFinished()) |
| 2269 |
break; |
| 2270 |
count = spy.count(); |
| 2271 |
} |
| 2272 |
QObject::disconnect(r, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop())); |
| 2273 |
|
| 2274 |
QByteArray uploaded = r->readAll(); |
| 2275 |
QCOMPARE(uploaded.size(), data.size()); |
| 2276 |
QCOMPARE(uploaded, data); |
| 2277 |
|
| 2278 |
r->close(); |
| 2279 |
QObject::connect(r, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop())); |
| 2280 |
QTestEventLoop::instance().enterLoop(10); |
| 2281 |
QObject::disconnect(r, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop())); |
| 2282 |
} |
| 2283 |
|
| 2284 |
void tst_QNetworkReply::putToFtpWithInvalidCredentials() |
| 2285 |
{ |
| 2286 |
QUrl url("ftp://" + QtNetworkSettings::ftpServerName()); |
| 2287 |
url.setPath(QString("/qtest/upload/qnetworkaccess-putToFtp-%1-%2") |
| 2288 |
.arg(QTest::currentDataTag()) |
| 2289 |
.arg(uniqueExtension)); |
| 2290 |
url.setUserName("invalidUser"); |
| 2291 |
url.setPassword("InvalidPassword"); |
| 2292 |
QNetworkRequest req(url); |
| 2293 |
QNetworkReplyPtr r; |
| 2294 |
|
| 2295 |
for (int i = 0; i < 2; i++) |
| 2296 |
{ |
| 2297 |
runSimpleRequest(QNetworkAccessManager::PutOperation, req, r, QByteArray()); |
| 2298 |
|
| 2299 |
QVERIFY(r->isFinished()); |
| 2300 |
QCOMPARE(r->url(), url); |
| 2301 |
QCOMPARE(r->error(), QNetworkReply::AuthenticationRequiredError); |
| 2302 |
r->close(); |
| 2303 |
} |
| 2304 |
} |
| 2305 |
|
| 2306 |
void tst_QNetworkReply::putToHttp_data() |
| 2307 |
{ |
| 2308 |
putToFile_data(); |
| 2309 |
} |
| 2310 |
|
| 2311 |
void tst_QNetworkReply::putToHttp() |
| 2312 |
{ |
| 2313 |
QUrl url("http://" + QtNetworkSettings::httpServerName()); |
| 2314 |
url.setPath(QString("/dav/qnetworkaccess-putToHttp-%1-%2") |
| 2315 |
.arg(QTest::currentDataTag()) |
| 2316 |
.arg(uniqueExtension)); |
| 2317 |
|
| 2318 |
QNetworkRequest request(url); |
| 2319 |
QNetworkReplyPtr reply; |
| 2320 |
|
| 2321 |
QFETCH(QByteArray, data); |
| 2322 |
|
| 2323 |
RUN_REQUEST(runSimpleRequest(QNetworkAccessManager::PutOperation, request, reply, data)); |
| 2324 |
|
| 2325 |
QCOMPARE(reply->url(), url); |
| 2326 |
QCOMPARE(reply->error(), QNetworkReply::NoError); |
| 2327 |
|
| 2328 |
QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 201); // 201 Created |
| 2329 |
|
| 2330 |
// download the file again from HTTP to make sure it was uploaded |
| 2331 |
// correctly. HTTP/0.9 is enough |
| 2332 |
QTcpSocket socket; |
| 2333 |
socket.connectToHost(QtNetworkSettings::httpServerName(), 80); |
| 2334 |
socket.write("GET " + url.toEncoded(QUrl::RemoveScheme | QUrl::RemoveAuthority) + "\r\n"); |
| 2335 |
if (!socket.waitForDisconnected(10000)) |
| 2336 |
QFAIL("Network timeout"); |
| 2337 |
|
| 2338 |
QByteArray uploadedData = socket.readAll(); |
| 2339 |
QCOMPARE(uploadedData, data); |
| 2340 |
} |
| 2341 |
|
| 2342 |
void tst_QNetworkReply::putToHttpSynchronous_data() |
| 2343 |
{ |
| 2344 |
uniqueExtension = createUniqueExtension(); |
| 2345 |
putToFile_data(); |
| 2346 |
} |
| 2347 |
|
| 2348 |
void tst_QNetworkReply::putToHttpSynchronous() |
| 2349 |
{ |
| 2350 |
QUrl url("http://" + QtNetworkSettings::httpServerName()); |
| 2351 |
url.setPath(QString("/dav/qnetworkaccess-putToHttp-%1-%2") |
| 2352 |
.arg(QTest::currentDataTag()) |
| 2353 |
.arg(uniqueExtension)); |
| 2354 |
|
| 2355 |
QNetworkRequest request(url); |
| 2356 |
QNetworkReplyPtr reply; |
| 2357 |
|
| 2358 |
QFETCH(QByteArray, data); |
| 2359 |
|
| 2360 |
request.setAttribute( |
| 2361 |
QNetworkRequest::SynchronousRequestAttribute, |
| 2362 |
true); |
| 2363 |
|
| 2364 |
RUN_REQUEST(runSimpleRequest(QNetworkAccessManager::PutOperation, request, reply, data)); |
| 2365 |
|
| 2366 |
QCOMPARE(reply->url(), url); |
| 2367 |
QCOMPARE(reply->error(), QNetworkReply::NoError); |
| 2368 |
|
| 2369 |
QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 201); // 201 Created |
| 2370 |
|
| 2371 |
// download the file again from HTTP to make sure it was uploaded |
| 2372 |
// correctly. HTTP/0.9 is enough |
| 2373 |
QTcpSocket socket; |
| 2374 |
socket.connectToHost(QtNetworkSettings::httpServerName(), 80); |
| 2375 |
socket.write("GET " + url.toEncoded(QUrl::RemoveScheme | QUrl::RemoveAuthority) + "\r\n"); |
| 2376 |
if (!socket.waitForDisconnected(10000)) |
| 2377 |
QFAIL("Network timeout"); |
| 2378 |
|
| 2379 |
QByteArray uploadedData = socket.readAll(); |
| 2380 |
QCOMPARE(uploadedData, data); |
| 2381 |
} |
| 2382 |
|
| 2383 |
void tst_QNetworkReply::postToHttp_data() |
| 2384 |
{ |
| 2385 |
putToFile_data(); |
| 2386 |
} |
| 2387 |
|
| 2388 |
void tst_QNetworkReply::postToHttp() |
| 2389 |
{ |
| 2390 |
QUrl url("http://" + QtNetworkSettings::httpServerName() + "/qtest/cgi-bin/md5sum.cgi"); |
| 2391 |
|
| 2392 |
QNetworkRequest request(url); |
| 2393 |
request.setRawHeader("Content-Type", "application/octet-stream"); |
| 2394 |
QNetworkReplyPtr reply; |
| 2395 |
|
| 2396 |
QFETCH(QByteArray, data); |
| 2397 |
|
| 2398 |
RUN_REQUEST(runSimpleRequest(QNetworkAccessManager::PostOperation, request, reply, data)); |
| 2399 |
|
| 2400 |
QCOMPARE(reply->url(), url); |
| 2401 |
QCOMPARE(reply->error(), QNetworkReply::NoError); |
| 2402 |
|
| 2403 |
QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200); // 200 Ok |
| 2404 |
|
| 2405 |
QFETCH(QByteArray, md5sum); |
| 2406 |
QByteArray uploadedData = reply->readAll().trimmed(); |
| 2407 |
QCOMPARE(uploadedData, md5sum.toHex()); |
| 2408 |
} |
| 2409 |
|
| 2410 |
void tst_QNetworkReply::postToHttpSynchronous_data() |
| 2411 |
{ |
| 2412 |
putToFile_data(); |
| 2413 |
} |
| 2414 |
|
| 2415 |
void tst_QNetworkReply::postToHttpSynchronous() |
| 2416 |
{ |
| 2417 |
QUrl url("http://" + QtNetworkSettings::httpServerName() + "/qtest/cgi-bin/md5sum.cgi"); |
| 2418 |
|
| 2419 |
QNetworkRequest request(url); |
| 2420 |
request.setRawHeader("Content-Type", "application/octet-stream"); |
| 2421 |
|
| 2422 |
request.setAttribute( |
| 2423 |
QNetworkRequest::SynchronousRequestAttribute, |
| 2424 |
true); |
| 2425 |
|
| 2426 |
QNetworkReplyPtr reply; |
| 2427 |
|
| 2428 |
QFETCH(QByteArray, data); |
| 2429 |
|
| 2430 |
RUN_REQUEST(runSimpleRequest(QNetworkAccessManager::PostOperation, request, reply, data)); |
| 2431 |
|
| 2432 |
QCOMPARE(reply->url(), url); |
| 2433 |
QCOMPARE(reply->error(), QNetworkReply::NoError); |
| 2434 |
|
| 2435 |
QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200); // 200 Ok |
| 2436 |
|
| 2437 |
QFETCH(QByteArray, md5sum); |
| 2438 |
QByteArray uploadedData = reply->readAll().trimmed(); |
| 2439 |
QCOMPARE(uploadedData, md5sum.toHex()); |
| 2440 |
} |
| 2441 |
|
| 2442 |
void tst_QNetworkReply::postToHttpMultipart_data() |
| 2443 |
{ |
| 2444 |
QTest::addColumn<QUrl>("url"); |
| 2445 |
QTest::addColumn<QHttpMultiPart *>("multiPart"); |
| 2446 |
QTest::addColumn<QByteArray>("expectedReplyData"); |
| 2447 |
QTest::addColumn<QByteArray>("contentType"); |
| 2448 |
|
| 2449 |
QUrl url("http://" + QtNetworkSettings::httpServerName() + "/qtest/cgi-bin/multipart.cgi"); |
| 2450 |
QByteArray expectedData; |
| 2451 |
|
| 2452 |
|
| 2453 |
// empty parts |
| 2454 |
|
| 2455 |
QHttpMultiPart *emptyMultiPart = new QHttpMultiPart; |
| 2456 |
QTest::newRow("empty") << url << emptyMultiPart << expectedData << QByteArray("mixed"); |
| 2457 |
|
| 2458 |
QHttpMultiPart *emptyRelatedMultiPart = new QHttpMultiPart; |
| 2459 |
emptyRelatedMultiPart->setContentType(QHttpMultiPart::RelatedType); |
| 2460 |
QTest::newRow("empty-related") << url << emptyRelatedMultiPart << expectedData << QByteArray("related"); |
| 2461 |
|
| 2462 |
QHttpMultiPart *emptyAlternativeMultiPart = new QHttpMultiPart; |
| 2463 |
emptyAlternativeMultiPart->setContentType(QHttpMultiPart::AlternativeType); |
| 2464 |
QTest::newRow("empty-alternative") << url << emptyAlternativeMultiPart << expectedData << QByteArray("alternative"); |
| 2465 |
|
| 2466 |
|
| 2467 |
// text-only parts |
| 2468 |
|
| 2469 |
QHttpPart textPart; |
| 2470 |
textPart.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("text/plain")); |
| 2471 |
textPart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"text\"")); |
| 2472 |
textPart.setBody("7 bytes"); |
| 2473 |
QHttpMultiPart *multiPart1 = new QHttpMultiPart; |
| 2474 |
multiPart1->setContentType(QHttpMultiPart::FormDataType); |
| 2475 |
multiPart1->append(textPart); |
| 2476 |
expectedData = "key: text, value: 7 bytes\n"; |
| 2477 |
QTest::newRow("text") << url << multiPart1 << expectedData << QByteArray("form-data"); |
| 2478 |
|
| 2479 |
QHttpMultiPart *customMultiPart = new QHttpMultiPart; |
| 2480 |
customMultiPart->append(textPart); |
| 2481 |
expectedData = "header: Content-Type, value: 'text/plain'\n" |
| 2482 |
"header: Content-Disposition, value: 'form-data; name=\"text\"'\n" |
| 2483 |
"content: 7 bytes\n" |
| 2484 |
"\n"; |
| 2485 |
QTest::newRow("text-custom") << url << customMultiPart << expectedData << QByteArray("custom"); |
| 2486 |
|
| 2487 |
QHttpPart textPart2; |
| 2488 |
textPart2.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("text/plain")); |
| 2489 |
textPart2.setRawHeader("myRawHeader", "myValue"); |
| 2490 |
textPart2.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"text2\"")); |
| 2491 |
textPart2.setBody("some more bytes"); |
| 2492 |
textPart2.setBodyDevice((QIODevice *) 1); // test whether setting and unsetting of the device works |
| 2493 |
textPart2.setBodyDevice(0); |
| 2494 |
QHttpMultiPart *multiPart2 = new QHttpMultiPart; |
| 2495 |
multiPart2->setContentType(QHttpMultiPart::FormDataType); |
| 2496 |
multiPart2->append(textPart); |
| 2497 |
multiPart2->append(textPart2); |
| 2498 |
#ifdef QT_TEST_SERVER |
| 2499 |
expectedData = "key: text, value: 7 bytes\n" |
| 2500 |
"key: text2, value: some more bytes\n"; |
| 2501 |
#else |
| 2502 |
expectedData = "key: text2, value: some more bytes\n" |
| 2503 |
"key: text, value: 7 bytes\n"; |
| 2504 |
#endif |
| 2505 |
QTest::newRow("text-text") << url << multiPart2 << expectedData << QByteArray("form-data"); |
| 2506 |
|
| 2507 |
|
| 2508 |
QHttpPart textPart3; |
| 2509 |
textPart3.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("text/plain")); |
| 2510 |
textPart3.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"text3\"")); |
| 2511 |
textPart3.setRawHeader("Content-Location", "http://my.test.location.tld"); |
| 2512 |
textPart3.setBody("even more bytes"); |
| 2513 |
QHttpMultiPart *multiPart3 = new QHttpMultiPart; |
| 2514 |
multiPart3->setContentType(QHttpMultiPart::AlternativeType); |
| 2515 |
multiPart3->append(textPart); |
| 2516 |
multiPart3->append(textPart2); |
| 2517 |
multiPart3->append(textPart3); |
| 2518 |
expectedData = "header: Content-Type, value: 'text/plain'\n" |
| 2519 |
"header: Content-Disposition, value: 'form-data; name=\"text\"'\n" |
| 2520 |
"content: 7 bytes\n" |
| 2521 |
"\n" |
| 2522 |
"header: Content-Type, value: 'text/plain'\n" |
| 2523 |
"header: myRawHeader, value: 'myValue'\n" |
| 2524 |
"header: Content-Disposition, value: 'form-data; name=\"text2\"'\n" |
| 2525 |
"content: some more bytes\n" |
| 2526 |
"\n" |
| 2527 |
"header: Content-Type, value: 'text/plain'\n" |
| 2528 |
"header: Content-Disposition, value: 'form-data; name=\"text3\"'\n" |
| 2529 |
"header: Content-Location, value: 'http://my.test.location.tld'\n" |
| 2530 |
"content: even more bytes\n\n"; |
| 2531 |
QTest::newRow("text-text-text") << url << multiPart3 << expectedData << QByteArray("alternative"); |
| 2532 |
|
| 2533 |
|
| 2534 |
|
| 2535 |
// text and image parts |
| 2536 |
|
| 2537 |
QHttpPart imagePart11; |
| 2538 |
imagePart11.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("image/jpeg")); |
| 2539 |
imagePart11.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"testImage\"")); |
| 2540 |
imagePart11.setRawHeader("Content-Location", "http://my.test.location.tld"); |
| 2541 |
imagePart11.setRawHeader("Content-ID", "[email protected]"); |
| 2542 |
QFile *file11 = new QFile(testDataDir + "/image1.jpg"); |
| 2543 |
file11->open(QIODevice::ReadOnly); |
| 2544 |
imagePart11.setBodyDevice(file11); |
| 2545 |
QHttpMultiPart *imageMultiPart1 = new QHttpMultiPart(QHttpMultiPart::FormDataType); |
| 2546 |
imageMultiPart1->append(imagePart11); |
| 2547 |
file11->setParent(imageMultiPart1); |
| 2548 |
expectedData = "key: testImage, value: 87ef3bb319b004ba9e5e9c9fa713776e\n"; // md5 sum of file |
| 2549 |
QTest::newRow("image") << url << imageMultiPart1 << expectedData << QByteArray("form-data"); |
| 2550 |
|
| 2551 |
QHttpPart imagePart21; |
| 2552 |
imagePart21.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("image/jpeg")); |
| 2553 |
imagePart21.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"testImage1\"")); |
| 2554 |
imagePart21.setRawHeader("Content-Location", "http://my.test.location.tld"); |
| 2555 |
imagePart21.setRawHeader("Content-ID", "[email protected]"); |
| 2556 |
QFile *file21 = new QFile(testDataDir + "/image1.jpg"); |
| 2557 |
file21->open(QIODevice::ReadOnly); |
| 2558 |
imagePart21.setBodyDevice(file21); |
| 2559 |
QHttpMultiPart *imageMultiPart2 = new QHttpMultiPart(); |
| 2560 |
imageMultiPart2->setContentType(QHttpMultiPart::FormDataType); |
| 2561 |
imageMultiPart2->append(textPart); |
| 2562 |
imageMultiPart2->append(imagePart21); |
| 2563 |
file21->setParent(imageMultiPart2); |
| 2564 |
QHttpPart imagePart22; |
| 2565 |
imagePart22.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("image/jpeg")); |
| 2566 |
imagePart22.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"testImage2\"")); |
| 2567 |
QFile *file22 = new QFile(testDataDir + "/image2.jpg"); |
| 2568 |
file22->open(QIODevice::ReadOnly); |
| 2569 |
imagePart22.setBodyDevice(file22); |
| 2570 |
imageMultiPart2->append(imagePart22); |
| 2571 |
file22->setParent(imageMultiPart2); |
| 2572 |
#ifdef QT_TEST_SERVER |
| 2573 |
expectedData = "key: text, value: 7 bytes\n" |
| 2574 |
"key: testImage1, value: 87ef3bb319b004ba9e5e9c9fa713776e\n" |
| 2575 |
"key: testImage2, value: 483761b893f7fb1bd2414344cd1f3dfb\n"; |
| 2576 |
#else |
| 2577 |
expectedData = "key: testImage1, value: 87ef3bb319b004ba9e5e9c9fa713776e\n" |
| 2578 |
"key: text, value: 7 bytes\n" |
| 2579 |
"key: testImage2, value: 483761b893f7fb1bd2414344cd1f3dfb\n"; |
| 2580 |
#endif |
| 2581 |
QTest::newRow("text-image-image") << url << imageMultiPart2 << expectedData << QByteArray("form-data"); |
| 2582 |
|
| 2583 |
|
| 2584 |
QHttpPart imagePart31; |
| 2585 |
imagePart31.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("image/jpeg")); |
| 2586 |
imagePart31.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"testImage1\"")); |
| 2587 |
imagePart31.setRawHeader("Content-Location", "http://my.test.location.tld"); |
| 2588 |
imagePart31.setRawHeader("Content-ID", "[email protected]"); |
| 2589 |
QFile *file31 = new QFile(testDataDir + "/image1.jpg"); |
| 2590 |
file31->open(QIODevice::ReadOnly); |
| 2591 |
imagePart31.setBodyDevice(file31); |
| 2592 |
QHttpMultiPart *imageMultiPart3 = new QHttpMultiPart(QHttpMultiPart::FormDataType); |
| 2593 |
imageMultiPart3->append(imagePart31); |
| 2594 |
file31->setParent(imageMultiPart3); |
| 2595 |
QHttpPart imagePart32; |
| 2596 |
imagePart32.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("image/jpeg")); |
| 2597 |
imagePart32.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"testImage2\"")); |
| 2598 |
QFile *file32 = new QFile(testDataDir + "/image2.jpg"); |
| 2599 |
file32->open(QIODevice::ReadOnly); |
| 2600 |
imagePart32.setBodyDevice(file31); // check that resetting works |
| 2601 |
imagePart32.setBodyDevice(file32); |
| 2602 |
imageMultiPart3->append(imagePart32); |
| 2603 |
file32->setParent(imageMultiPart3); |
| 2604 |
QHttpPart imagePart33; |
| 2605 |
imagePart33.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("image/jpeg")); |
| 2606 |
imagePart33.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"testImage3\"")); |
| 2607 |
QFile *file33 = new QFile(testDataDir + "/image3.jpg"); |
| 2608 |
file33->open(QIODevice::ReadOnly); |
| 2609 |
imagePart33.setBodyDevice(file33); |
| 2610 |
imageMultiPart3->append(imagePart33); |
| 2611 |
file33->setParent(imageMultiPart3); |
| 2612 |
expectedData = "key: testImage1, value: 87ef3bb319b004ba9e5e9c9fa713776e\n" |
| 2613 |
"key: testImage2, value: 483761b893f7fb1bd2414344cd1f3dfb\n" |
| 2614 |
"key: testImage3, value: ab0eb6fd4fcf8b4436254870b4513033\n"; |
| 2615 |
QTest::newRow("3-images") << url << imageMultiPart3 << expectedData << QByteArray("form-data"); |
| 2616 |
|
| 2617 |
|
| 2618 |
// note: nesting multiparts is not working currently; for that, the outputDevice would need to be public |
| 2619 |
|
| 2620 |
// QHttpPart imagePart41; |
| 2621 |
// imagePart41.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("image/jpeg")); |
| 2622 |
// QFile *file41 = new QFile(testDataDir + "/image1.jpg"); |
| 2623 |
// file41->open(QIODevice::ReadOnly); |
| 2624 |
// imagePart41.setBodyDevice(file41); |
| 2625 |
// |
| 2626 |
// QHttpMultiPart *innerMultiPart = new QHttpMultiPart(); |
| 2627 |
// innerMultiPart->setContentType(QHttpMultiPart::FormDataType); |
| 2628 |
// textPart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant()); |
| 2629 |
// innerMultiPart->append(textPart); |
| 2630 |
// innerMultiPart->append(imagePart41); |
| 2631 |
// textPart2.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant()); |
| 2632 |
// innerMultiPart->append(textPart2); |
| 2633 |
// |
| 2634 |
// QHttpPart nestedPart; |
| 2635 |
// nestedPart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"nestedMessage")); |
| 2636 |
// nestedPart.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("multipart/alternative; boundary=\"" + innerMultiPart->boundary() + "\"")); |
| 2637 |
// innerMultiPart->outputDevice()->open(QIODevice::ReadOnly); |
| 2638 |
// nestedPart.setBodyDevice(innerMultiPart->outputDevice()); |
| 2639 |
// |
| 2640 |
// QHttpMultiPart *outerMultiPart = new QHttpMultiPart; |
| 2641 |
// outerMultiPart->setContentType(QHttpMultiPart::FormDataType); |
| 2642 |
// outerMultiPart->append(textPart); |
| 2643 |
// outerMultiPart->append(nestedPart); |
| 2644 |
// outerMultiPart->append(textPart2); |
| 2645 |
// expectedData = "nothing"; // the CGI.pm module running on the test server does not understand nested multiparts |
| 2646 |
// openFiles.clear(); |
| 2647 |
// openFiles << file41; |
| 2648 |
// QTest::newRow("nested") << url << outerMultiPart << expectedData << openFiles; |
| 2649 |
|
| 2650 |
|
| 2651 |
// test setting large chunks of content with a byte array instead of a device (DISCOURAGED because of high memory consumption, |
| 2652 |
// but we need to test that the behavior is correct) |
| 2653 |
QHttpPart imagePart51; |
| 2654 |
imagePart51.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("image/jpeg")); |
| 2655 |
imagePart51.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"testImage\"")); |
| 2656 |
QFile *file51 = new QFile(testDataDir + "/image1.jpg"); |
| 2657 |
file51->open(QIODevice::ReadOnly); |
| 2658 |
QByteArray imageData = file51->readAll(); |
| 2659 |
file51->close(); |
| 2660 |
delete file51; |
| 2661 |
imagePart51.setBody("7 bytes"); // check that resetting works |
| 2662 |
imagePart51.setBody(imageData); |
| 2663 |
QHttpMultiPart *imageMultiPart5 = new QHttpMultiPart; |
| 2664 |
imageMultiPart5->setContentType(QHttpMultiPart::FormDataType); |
| 2665 |
imageMultiPart5->append(imagePart51); |
| 2666 |
expectedData = "key: testImage, value: 87ef3bb319b004ba9e5e9c9fa713776e\n"; // md5 sum of file |
| 2667 |
QTest::newRow("image-as-content") << url << imageMultiPart5 << expectedData << QByteArray("form-data"); |
| 2668 |
} |
| 2669 |
|
| 2670 |
void tst_QNetworkReply::postToHttpMultipart() |
| 2671 |
{ |
| 2672 |
QFETCH(QUrl, url); |
| 2673 |
|
| 2674 |
static QSet<QByteArray> boundaries; |
| 2675 |
|
| 2676 |
QNetworkRequest request(url); |
| 2677 |
QNetworkReplyPtr reply; |
| 2678 |
|
| 2679 |
QFETCH(QHttpMultiPart *, multiPart); |
| 2680 |
QFETCH(QByteArray, expectedReplyData); |
| 2681 |
QFETCH(QByteArray, contentType); |
| 2682 |
|
| 2683 |
// hack for testing the setting of the content-type header by hand: |
| 2684 |
if (contentType == "custom") { |
| 2685 |
QByteArray contentType("multipart/custom; boundary=\"" + multiPart->boundary() + "\""); |
| 2686 |
request.setHeader(QNetworkRequest::ContentTypeHeader, contentType); |
| 2687 |
} |
| 2688 |
|
| 2689 |
QVERIFY2(! boundaries.contains(multiPart->boundary()), "boundary '" + multiPart->boundary() + "' has been created twice"); |
| 2690 |
boundaries.insert(multiPart->boundary()); |
| 2691 |
|
| 2692 |
RUN_REQUEST(runMultipartRequest(request, reply, multiPart, "POST")); |
| 2693 |
multiPart->deleteLater(); |
| 2694 |
|
| 2695 |
QCOMPARE(reply->url(), url); |
| 2696 |
QCOMPARE(reply->error(), QNetworkReply::NoError); |
| 2697 |
|
| 2698 |
QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200); // 200 Ok |
| 2699 |
|
| 2700 |
QVERIFY(multiPart->boundary().count() > 20); // check that there is randomness after the "boundary_.oOo._" string |
| 2701 |
QVERIFY(multiPart->boundary().count() < 70); |
| 2702 |
QByteArray replyData = reply->readAll(); |
| 2703 |
|
| 2704 |
expectedReplyData.prepend("content type: multipart/" + contentType + "; boundary=\"" + multiPart->boundary() + "\"\n"); |
| 2705 |
// QEXPECT_FAIL("nested", "the server does not understand nested multipart messages", Continue); // see above |
| 2706 |
QCOMPARE(replyData, expectedReplyData); |
| 2707 |
} |
| 2708 |
|
| 2709 |
void tst_QNetworkReply::multipartSkipIndices() // QTBUG-32534 |
| 2710 |
{ |
| 2711 |
QHttpMultiPart *multiPart = new QHttpMultiPart(QHttpMultiPart::MixedType); |
| 2712 |
QUrl url("http://" + QtNetworkSettings::httpServerName() + "/qtest/cgi-bin/multipart.cgi"); |
| 2713 |
QNetworkRequest request(url); |
| 2714 |
QList<QByteArray> parts; |
| 2715 |
parts << QByteArray(56083, 'X') << QByteArray(468, 'X') << QByteArray(24952, 'X'); |
| 2716 |
|
| 2717 |
QHttpPart part1; |
| 2718 |
part1.setHeader(QNetworkRequest::ContentDispositionHeader, "form-data; name=\"field1\"; filename=\"aaaa.bin\""); |
| 2719 |
part1.setHeader(QNetworkRequest::ContentTypeHeader, "application/octet-stream"); |
| 2720 |
part1.setBody(parts.at(0)); |
| 2721 |
multiPart->append(part1); |
| 2722 |
|
| 2723 |
QHttpPart part2; |
| 2724 |
part2.setHeader(QNetworkRequest::ContentDispositionHeader, "form-data; name=\"field2\"; filename=\"bbbb.txt\""); |
| 2725 |
part2.setHeader(QNetworkRequest::ContentTypeHeader, "text/plain"); |
| 2726 |
part2.setBody(parts.at(1)); |
| 2727 |
multiPart->append(part2); |
| 2728 |
|
| 2729 |
QHttpPart part3; |
| 2730 |
part3.setHeader(QNetworkRequest::ContentDispositionHeader, "form-data; name=\"text-3\"; filename=\"cccc.txt\""); |
| 2731 |
part3.setHeader(QNetworkRequest::ContentTypeHeader, "text/plain"); |
| 2732 |
part3.setBody(parts.at(2)); |
| 2733 |
multiPart->append(part3); |
| 2734 |
|
| 2735 |
QNetworkReplyPtr reply; |
| 2736 |
RUN_REQUEST(runMultipartRequest(request, reply, multiPart, "POST")); |
| 2737 |
|
| 2738 |
QCOMPARE(reply->error(), QNetworkReply::NoError); |
| 2739 |
|
| 2740 |
QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200); // 200 Ok |
| 2741 |
QByteArray line; |
| 2742 |
int partIndex = 0; |
| 2743 |
while ((line = reply->readLine()) != QByteArray("")) { |
| 2744 |
if (line.startsWith("content:")) { |
| 2745 |
// before, the 3rd part would return garbled output at the end |
| 2746 |
QCOMPARE("content: " + parts[partIndex++] + "\n", line); |
| 2747 |
} |
| 2748 |
} |
| 2749 |
multiPart->deleteLater(); |
| 2750 |
} |
| 2751 |
|
| 2752 |
void tst_QNetworkReply::putToHttpMultipart_data() |
| 2753 |
{ |
| 2754 |
postToHttpMultipart_data(); |
| 2755 |
} |
| 2756 |
|
| 2757 |
void tst_QNetworkReply::putToHttpMultipart() |
| 2758 |
{ |
| 2759 |
QSKIP("test server script cannot handle PUT data yet"); |
| 2760 |
QFETCH(QUrl, url); |
| 2761 |
|
| 2762 |
static QSet<QByteArray> boundaries; |
| 2763 |
|
| 2764 |
QNetworkRequest request(url); |
| 2765 |
QNetworkReplyPtr reply; |
| 2766 |
|
| 2767 |
QFETCH(QHttpMultiPart *, multiPart); |
| 2768 |
QFETCH(QByteArray, expectedReplyData); |
| 2769 |
QFETCH(QByteArray, contentType); |
| 2770 |
|
| 2771 |
// hack for testing the setting of the content-type header by hand: |
| 2772 |
if (contentType == "custom") { |
| 2773 |
QByteArray contentType("multipart/custom; boundary=\"" + multiPart->boundary() + "\""); |
| 2774 |
request.setHeader(QNetworkRequest::ContentTypeHeader, contentType); |
| 2775 |
} |
| 2776 |
|
| 2777 |
QVERIFY2(! boundaries.contains(multiPart->boundary()), "boundary '" + multiPart->boundary() + "' has been created twice"); |
| 2778 |
boundaries.insert(multiPart->boundary()); |
| 2779 |
|
| 2780 |
RUN_REQUEST(runMultipartRequest(request, reply, multiPart, "PUT")); |
| 2781 |
multiPart->deleteLater(); |
| 2782 |
|
| 2783 |
QCOMPARE(reply->url(), url); |
| 2784 |
QCOMPARE(reply->error(), QNetworkReply::NoError); |
| 2785 |
|
| 2786 |
QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200); // 200 Ok |
| 2787 |
|
| 2788 |
QVERIFY(multiPart->boundary().count() > 20); // check that there is randomness after the "boundary_.oOo._" string |
| 2789 |
QVERIFY(multiPart->boundary().count() < 70); |
| 2790 |
QByteArray replyData = reply->readAll(); |
| 2791 |
|
| 2792 |
expectedReplyData.prepend("content type: multipart/" + contentType + "; boundary=\"" + multiPart->boundary() + "\"\n"); |
| 2793 |
// QEXPECT_FAIL("nested", "the server does not understand nested multipart messages", Continue); // see above |
| 2794 |
QCOMPARE(replyData, expectedReplyData); |
| 2795 |
} |
| 2796 |
|
| 2797 |
#ifndef QT_NO_SSL |
| 2798 |
void tst_QNetworkReply::putToHttps_data() |
| 2799 |
{ |
| 2800 |
uniqueExtension = createUniqueExtension(); |
| 2801 |
putToFile_data(); |
| 2802 |
} |
| 2803 |
|
| 2804 |
void tst_QNetworkReply::putToHttps() |
| 2805 |
{ |
| 2806 |
QUrl url("https://" + QtNetworkSettings::httpServerName()); |
| 2807 |
url.setPath(QString("/dav/qnetworkaccess-putToHttp-%1-%2") |
| 2808 |
.arg(QTest::currentDataTag()) |
| 2809 |
.arg(uniqueExtension)); |
| 2810 |
|
| 2811 |
QNetworkRequest request(url); |
| 2812 |
QList<QSslCertificate> certs = QSslCertificate::fromPath(testDataDir + certsFilePath); |
| 2813 |
QSslConfiguration conf; |
| 2814 |
conf.setCaCertificates(certs); |
| 2815 |
request.setSslConfiguration(conf); |
| 2816 |
QNetworkReplyPtr reply; |
| 2817 |
|
| 2818 |
QFETCH(QByteArray, data); |
| 2819 |
|
| 2820 |
RUN_REQUEST(runSimpleRequest(QNetworkAccessManager::PutOperation, request, reply, data)); |
| 2821 |
|
| 2822 |
QCOMPARE(reply->url(), url); |
| 2823 |
QCOMPARE(reply->error(), QNetworkReply::NoError); |
| 2824 |
|
| 2825 |
QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 201); // 201 Created |
| 2826 |
|
| 2827 |
// download the file again from HTTP to make sure it was uploaded |
| 2828 |
// correctly. HTTP/0.9 is enough |
| 2829 |
QTcpSocket socket; |
| 2830 |
socket.connectToHost(QtNetworkSettings::httpServerName(), 80); |
| 2831 |
socket.write("GET " + url.toEncoded(QUrl::RemoveScheme | QUrl::RemoveAuthority) + "\r\n"); |
| 2832 |
if (!socket.waitForDisconnected(10000)) |
| 2833 |
QFAIL("Network timeout"); |
| 2834 |
|
| 2835 |
QByteArray uploadedData = socket.readAll(); |
| 2836 |
QCOMPARE(uploadedData, data); |
| 2837 |
} |
| 2838 |
|
| 2839 |
void tst_QNetworkReply::putToHttpsSynchronous_data() |
| 2840 |
{ |
| 2841 |
uniqueExtension = createUniqueExtension(); |
| 2842 |
putToFile_data(); |
| 2843 |
} |
| 2844 |
|
| 2845 |
void tst_QNetworkReply::putToHttpsSynchronous() |
| 2846 |
{ |
| 2847 |
QUrl url("https://" + QtNetworkSettings::httpServerName()); |
| 2848 |
url.setPath(QString("/dav/qnetworkaccess-putToHttp-%1-%2") |
| 2849 |
.arg(QTest::currentDataTag()) |
| 2850 |
.arg(uniqueExtension)); |
| 2851 |
|
| 2852 |
QNetworkRequest request(url); |
| 2853 |
QList<QSslCertificate> certs = QSslCertificate::fromPath(testDataDir + certsFilePath); |
| 2854 |
QSslConfiguration conf; |
| 2855 |
conf.setCaCertificates(certs); |
| 2856 |
request.setSslConfiguration(conf); |
| 2857 |
QNetworkReplyPtr reply; |
| 2858 |
|
| 2859 |
QFETCH(QByteArray, data); |
| 2860 |
|
| 2861 |
request.setAttribute( |
| 2862 |
QNetworkRequest::SynchronousRequestAttribute, |
| 2863 |
true); |
| 2864 |
|
| 2865 |
RUN_REQUEST(runSimpleRequest(QNetworkAccessManager::PutOperation, request, reply, data)); |
| 2866 |
|
| 2867 |
QCOMPARE(reply->url(), url); |
| 2868 |
QCOMPARE(reply->error(), QNetworkReply::NoError); |
| 2869 |
|
| 2870 |
QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 201); // 201 Created |
| 2871 |
|
| 2872 |
// download the file again from HTTP to make sure it was uploaded |
| 2873 |
// correctly. HTTP/0.9 is enough |
| 2874 |
QTcpSocket socket; |
| 2875 |
socket.connectToHost(QtNetworkSettings::httpServerName(), 80); |
| 2876 |
socket.write("GET " + url.toEncoded(QUrl::RemoveScheme | QUrl::RemoveAuthority) + "\r\n"); |
| 2877 |
if (!socket.waitForDisconnected(10000)) |
| 2878 |
QFAIL("Network timeout"); |
| 2879 |
|
| 2880 |
QByteArray uploadedData = socket.readAll(); |
| 2881 |
QCOMPARE(uploadedData, data); |
| 2882 |
} |
| 2883 |
|
| 2884 |
void tst_QNetworkReply::postToHttps_data() |
| 2885 |
{ |
| 2886 |
putToFile_data(); |
| 2887 |
} |
| 2888 |
|
| 2889 |
void tst_QNetworkReply::postToHttps() |
| 2890 |
{ |
| 2891 |
QUrl url("https://" + QtNetworkSettings::httpServerName() + "/qtest/cgi-bin/md5sum.cgi"); |
| 2892 |
|
| 2893 |
QNetworkRequest request(url); |
| 2894 |
QList<QSslCertificate> certs = QSslCertificate::fromPath(testDataDir + certsFilePath); |
| 2895 |
QSslConfiguration conf; |
| 2896 |
conf.setCaCertificates(certs); |
| 2897 |
request.setSslConfiguration(conf); |
| 2898 |
request.setRawHeader("Content-Type", "application/octet-stream"); |
| 2899 |
QNetworkReplyPtr reply; |
| 2900 |
|
| 2901 |
QFETCH(QByteArray, data); |
| 2902 |
|
| 2903 |
RUN_REQUEST(runSimpleRequest(QNetworkAccessManager::PostOperation, request, reply, data)); |
| 2904 |
|
| 2905 |
QCOMPARE(reply->url(), url); |
| 2906 |
QCOMPARE(reply->error(), QNetworkReply::NoError); |
| 2907 |
|
| 2908 |
QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200); // 200 Ok |
| 2909 |
|
| 2910 |
QFETCH(QByteArray, md5sum); |
| 2911 |
QByteArray uploadedData = reply->readAll().trimmed(); |
| 2912 |
QCOMPARE(uploadedData, md5sum.toHex()); |
| 2913 |
} |
| 2914 |
|
| 2915 |
void tst_QNetworkReply::postToHttpsSynchronous_data() |
| 2916 |
{ |
| 2917 |
putToFile_data(); |
| 2918 |
} |
| 2919 |
|
| 2920 |
void tst_QNetworkReply::postToHttpsSynchronous() |
| 2921 |
{ |
| 2922 |
QUrl url("https://" + QtNetworkSettings::httpServerName() + "/qtest/cgi-bin/md5sum.cgi"); |
| 2923 |
|
| 2924 |
QNetworkRequest request(url); |
| 2925 |
QList<QSslCertificate> certs = QSslCertificate::fromPath(testDataDir + certsFilePath); |
| 2926 |
QSslConfiguration conf; |
| 2927 |
conf.setCaCertificates(certs); |
| 2928 |
request.setSslConfiguration(conf); |
| 2929 |
request.setRawHeader("Content-Type", "application/octet-stream"); |
| 2930 |
|
| 2931 |
request.setAttribute( |
| 2932 |
QNetworkRequest::SynchronousRequestAttribute, |
| 2933 |
true); |
| 2934 |
|
| 2935 |
QNetworkReplyPtr reply; |
| 2936 |
|
| 2937 |
QFETCH(QByteArray, data); |
| 2938 |
|
| 2939 |
RUN_REQUEST(runSimpleRequest(QNetworkAccessManager::PostOperation, request, reply, data)); |
| 2940 |
|
| 2941 |
QCOMPARE(reply->url(), url); |
| 2942 |
QCOMPARE(reply->error(), QNetworkReply::NoError); |
| 2943 |
|
| 2944 |
QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200); // 200 Ok |
| 2945 |
|
| 2946 |
QFETCH(QByteArray, md5sum); |
| 2947 |
QByteArray uploadedData = reply->readAll().trimmed(); |
| 2948 |
QCOMPARE(uploadedData, md5sum.toHex()); |
| 2949 |
} |
| 2950 |
|
| 2951 |
void tst_QNetworkReply::postToHttpsMultipart_data() |
| 2952 |
{ |
| 2953 |
postToHttpMultipart_data(); |
| 2954 |
} |
| 2955 |
|
| 2956 |
void tst_QNetworkReply::postToHttpsMultipart() |
| 2957 |
{ |
| 2958 |
QFETCH(QUrl, url); |
| 2959 |
url.setScheme("https"); |
| 2960 |
|
| 2961 |
static QSet<QByteArray> boundaries; |
| 2962 |
|
| 2963 |
QNetworkRequest request(url); |
| 2964 |
QList<QSslCertificate> certs = QSslCertificate::fromPath(testDataDir + certsFilePath); |
| 2965 |
QSslConfiguration conf; |
| 2966 |
conf.setCaCertificates(certs); |
| 2967 |
request.setSslConfiguration(conf); |
| 2968 |
QNetworkReplyPtr reply; |
| 2969 |
|
| 2970 |
QFETCH(QHttpMultiPart *, multiPart); |
| 2971 |
QFETCH(QByteArray, expectedReplyData); |
| 2972 |
QFETCH(QByteArray, contentType); |
| 2973 |
|
| 2974 |
// hack for testing the setting of the content-type header by hand: |
| 2975 |
if (contentType == "custom") { |
| 2976 |
QByteArray contentType("multipart/custom; boundary=\"" + multiPart->boundary() + '"'); |
| 2977 |
request.setHeader(QNetworkRequest::ContentTypeHeader, contentType); |
| 2978 |
} |
| 2979 |
|
| 2980 |
QVERIFY2(! boundaries.contains(multiPart->boundary()), "boundary '" + multiPart->boundary() + "' has been created twice"); |
| 2981 |
boundaries.insert(multiPart->boundary()); |
| 2982 |
|
| 2983 |
RUN_REQUEST(runMultipartRequest(request, reply, multiPart, "POST")); |
| 2984 |
multiPart->deleteLater(); |
| 2985 |
|
| 2986 |
QCOMPARE(reply->url(), url); |
| 2987 |
QCOMPARE(reply->error(), QNetworkReply::NoError); |
| 2988 |
|
| 2989 |
QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200); // 200 Ok |
| 2990 |
|
| 2991 |
QVERIFY(multiPart->boundary().count() > 20); // check that there is randomness after the "boundary_.oOo._" string |
| 2992 |
QVERIFY(multiPart->boundary().count() < 70); |
| 2993 |
QByteArray replyData = reply->readAll(); |
| 2994 |
|
| 2995 |
expectedReplyData.prepend("content type: multipart/" + contentType + "; boundary=\"" + multiPart->boundary() + "\"\n"); |
| 2996 |
QCOMPARE(replyData, expectedReplyData); |
| 2997 |
} |
| 2998 |
|
| 2999 |
#endif // QT_NO_SSL |
| 3000 |
|
| 3001 |
void tst_QNetworkReply::deleteFromHttp_data() |
| 3002 |
{ |
| 3003 |
QTest::addColumn<QUrl>("url"); |
| 3004 |
QTest::addColumn<int>("resultCode"); |
| 3005 |
QTest::addColumn<QNetworkReply::NetworkError>("error"); |
| 3006 |
|
| 3007 |
// for status codes to expect, see http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html |
| 3008 |
|
| 3009 |
QString httpServer = QtNetworkSettings::httpServerName(); |
| 3010 |
QTest::newRow("405-method-not-allowed") |
| 3011 |
<< QUrl("http://" + httpServer + "/index.html") |
| 3012 |
<< 405 << QNetworkReply::ContentOperationNotPermittedError; |
| 3013 |
|
| 3014 |
QTest::newRow("200-ok") |
| 3015 |
<< QUrl("http://" + httpServer + "/qtest/cgi-bin/http-delete.cgi?200-ok") |
| 3016 |
<< 200 << QNetworkReply::NoError; |
| 3017 |
|
| 3018 |
QTest::newRow("202-accepted") |
| 3019 |
<< QUrl("http://" + httpServer + "/qtest/cgi-bin/http-delete.cgi?202-accepted") |
| 3020 |
<< 202 << QNetworkReply::NoError; |
| 3021 |
|
| 3022 |
QTest::newRow("204-no-content") |
| 3023 |
<< QUrl("http://" + httpServer + "/qtest/cgi-bin/http-delete.cgi?204-no-content") |
| 3024 |
<< 204 << QNetworkReply::NoError; |
| 3025 |
|
| 3026 |
QTest::newRow("404-not-found") |
| 3027 |
<< QUrl("http://" + httpServer + "/qtest/cgi-bin/http-delete.cgi?404-not-found") |
| 3028 |
<< 404 << QNetworkReply::ContentNotFoundError; |
| 3029 |
} |
| 3030 |
|
| 3031 |
void tst_QNetworkReply::deleteFromHttp() |
| 3032 |
{ |
| 3033 |
QFETCH(QUrl, url); |
| 3034 |
QFETCH(int, resultCode); |
| 3035 |
QFETCH(QNetworkReply::NetworkError, error); |
| 3036 |
QNetworkRequest request(url); |
| 3037 |
QNetworkReplyPtr reply; |
| 3038 |
runSimpleRequest(QNetworkAccessManager::DeleteOperation, request, reply, 0); |
| 3039 |
QCOMPARE(reply->url(), url); |
| 3040 |
QCOMPARE(reply->error(), error); |
| 3041 |
QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), resultCode); |
| 3042 |
} |
| 3043 |
|
| 3044 |
void tst_QNetworkReply::putGetDeleteGetFromHttp_data() |
| 3045 |
{ |
| 3046 |
QTest::addColumn<QUrl>("putUrl"); |
| 3047 |
QTest::addColumn<int>("putResultCode"); |
| 3048 |
QTest::addColumn<QNetworkReply::NetworkError>("putError"); |
| 3049 |
QTest::addColumn<QUrl>("deleteUrl"); |
| 3050 |
QTest::addColumn<int>("deleteResultCode"); |
| 3051 |
QTest::addColumn<QNetworkReply::NetworkError>("deleteError"); |
| 3052 |
QTest::addColumn<QUrl>("get2Url"); |
| 3053 |
QTest::addColumn<int>("get2ResultCode"); |
| 3054 |
QTest::addColumn<QNetworkReply::NetworkError>("get2Error"); |
| 3055 |
|
| 3056 |
QUrl url("http://" + QtNetworkSettings::httpServerName()); |
| 3057 |
url.setPath(QString("/dav/qnetworkaccess-putToHttp-%1-%2") |
| 3058 |
.arg(QTest::currentDataTag()) |
| 3059 |
.arg(uniqueExtension)); |
| 3060 |
|
| 3061 |
// first use case: put, get (to check it is there), delete, get (to check it is not there anymore) |
| 3062 |
QTest::newRow("success") << url << 201 << QNetworkReply::NoError << url << 204 << QNetworkReply::NoError << url << 404 << QNetworkReply::ContentNotFoundError; |
| 3063 |
|
| 3064 |
QUrl wrongUrl("http://" + QtNetworkSettings::httpServerName()); |
| 3065 |
wrongUrl.setPath(QString("/dav/qnetworkaccess-thisURLisNotAvailable")); |
| 3066 |
|
| 3067 |
// second use case: put, get (to check it is there), delete wrong URL, get (to check it is still there) |
| 3068 |
QTest::newRow("delete-error") << url << 201 << QNetworkReply::NoError << wrongUrl << 404 << QNetworkReply::ContentNotFoundError << url << 200 << QNetworkReply::NoError; |
| 3069 |
|
| 3070 |
} |
| 3071 |
|
| 3072 |
void tst_QNetworkReply::putGetDeleteGetFromHttp() |
| 3073 |
{ |
| 3074 |
QFETCH(QUrl, putUrl); |
| 3075 |
QFETCH(int, putResultCode); |
| 3076 |
QFETCH(QNetworkReply::NetworkError, putError); |
| 3077 |
QFETCH(QUrl, deleteUrl); |
| 3078 |
QFETCH(int, deleteResultCode); |
| 3079 |
QFETCH(QNetworkReply::NetworkError, deleteError); |
| 3080 |
QFETCH(QUrl, get2Url); |
| 3081 |
QFETCH(int, get2ResultCode); |
| 3082 |
QFETCH(QNetworkReply::NetworkError, get2Error); |
| 3083 |
|
| 3084 |
QNetworkRequest putRequest(putUrl); |
| 3085 |
QNetworkRequest deleteRequest(deleteUrl); |
| 3086 |
QNetworkRequest get2Request(get2Url); |
| 3087 |
QNetworkReplyPtr reply; |
| 3088 |
|
| 3089 |
RUN_REQUEST(runSimpleRequest(QNetworkAccessManager::PutOperation, putRequest, reply, 0)); |
| 3090 |
QCOMPARE(reply->error(), putError); |
| 3091 |
QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), putResultCode); |
| 3092 |
|
| 3093 |
runSimpleRequest(QNetworkAccessManager::GetOperation, putRequest, reply, 0); |
| 3094 |
QCOMPARE(reply->error(), QNetworkReply::NoError); |
| 3095 |
QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200); |
| 3096 |
|
| 3097 |
runSimpleRequest(QNetworkAccessManager::DeleteOperation, deleteRequest, reply, 0); |
| 3098 |
QCOMPARE(reply->error(), deleteError); |
| 3099 |
QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), deleteResultCode); |
| 3100 |
|
| 3101 |
runSimpleRequest(QNetworkAccessManager::GetOperation, get2Request, reply, 0); |
| 3102 |
QCOMPARE(reply->error(), get2Error); |
| 3103 |
QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), get2ResultCode); |
| 3104 |
|
| 3105 |
} |
| 3106 |
|
| 3107 |
void tst_QNetworkReply::connectToIPv6Address_data() |
| 3108 |
{ |
| 3109 |
QTest::addColumn<QUrl>("url"); |
| 3110 |
QTest::addColumn<QNetworkReply::NetworkError>("error"); |
| 3111 |
QTest::addColumn<QByteArray>("dataToSend"); |
| 3112 |
QTest::addColumn<QByteArray>("hostfield"); |
| 3113 |
QTest::newRow("localhost") << QUrl(QByteArray("http://[::1]")) << QNetworkReply::NoError<< QByteArray("localhost") << QByteArray("[::1]"); |
| 3114 |
//QTest::newRow("ipv4localhost") << QUrl(QByteArray("http://127.0.0.1")) << QNetworkReply::NoError<< QByteArray("ipv4localhost") << QByteArray("127.0.0.1"); |
| 3115 |
//to add more test data here |
| 3116 |
} |
| 3117 |
|
| 3118 |
void tst_QNetworkReply::connectToIPv6Address() |
| 3119 |
{ |
| 3120 |
QFETCH(QUrl, url); |
| 3121 |
QFETCH(QNetworkReply::NetworkError, error); |
| 3122 |
QFETCH(QByteArray, dataToSend); |
| 3123 |
QFETCH(QByteArray, hostfield); |
| 3124 |
|
| 3125 |
if (!QtNetworkSettings::hasIPv6()) |
| 3126 |
QSKIP("system doesn't support ipv6!"); |
| 3127 |
|
| 3128 |
QByteArray httpResponse = QByteArray("HTTP/1.0 200 OK\r\nContent-Length: "); |
| 3129 |
httpResponse += QByteArray::number(dataToSend.size()); |
| 3130 |
httpResponse += "\r\n\r\n"; |
| 3131 |
httpResponse += dataToSend; |
| 3132 |
|
| 3133 |
MiniHttpServer server(httpResponse, false, NULL/*thread*/, true/*useipv6*/); |
| 3134 |
server.doClose = true; |
| 3135 |
|
| 3136 |
url.setPort(server.serverPort()); |
| 3137 |
QNetworkRequest request(url); |
| 3138 |
|
| 3139 |
QNetworkReplyPtr reply(manager.get(request)); |
| 3140 |
QVERIFY2(waitForFinish(reply) == Success, msgWaitForFinished(reply)); |
| 3141 |
QByteArray content = reply->readAll(); |
| 3142 |
//qDebug() << server.receivedData; |
| 3143 |
QByteArray hostinfo = "\r\nHost: " + hostfield + ':' + QByteArray::number(server.serverPort()) + "\r\n"; |
| 3144 |
QVERIFY(server.receivedData.contains(hostinfo)); |
| 3145 |
QCOMPARE(content, dataToSend); |
| 3146 |
QCOMPARE(reply->url(), request.url()); |
| 3147 |
QCOMPARE(reply->error(), error); |
| 3148 |
} |
| 3149 |
|
| 3150 |
void tst_QNetworkReply::sendCustomRequestToHttp_data() |
| 3151 |
{ |
| 3152 |
QTest::addColumn<QUrl>("url"); |
| 3153 |
QTest::addColumn<QByteArray>("verb"); |
| 3154 |
QTest::addColumn<QBuffer *>("device"); |
| 3155 |
QTest::addColumn<int>("resultCode"); |
| 3156 |
QTest::addColumn<QNetworkReply::NetworkError>("error"); |
| 3157 |
QTest::addColumn<QByteArray>("expectedContent"); |
| 3158 |
|
| 3159 |
QTest::newRow("options") << QUrl("http://" + QtNetworkSettings::httpServerName()) << |
| 3160 |
QByteArray("OPTIONS") << (QBuffer *) 0 << 200 << QNetworkReply::NoError << QByteArray(); |
| 3161 |
QTest::newRow("trace") << QUrl("http://" + QtNetworkSettings::httpServerName()) << |
| 3162 |
QByteArray("TRACE") << (QBuffer *) 0 << 200 << QNetworkReply::NoError << QByteArray(); |
| 3163 |
QTest::newRow("connect") << QUrl("http://" + QtNetworkSettings::httpServerName()) << |
| 3164 |
QByteArray("CONNECT") << (QBuffer *) 0 << 400 << QNetworkReply::ProtocolInvalidOperationError << QByteArray(); // 400 = Bad Request |
| 3165 |
QTest::newRow("nonsense") << QUrl("http://" + QtNetworkSettings::httpServerName()) << |
| 3166 |
QByteArray("NONSENSE") << (QBuffer *) 0 << 501 << QNetworkReply::OperationNotImplementedError << QByteArray(); // 501 = Method Not Implemented |
| 3167 |
|
| 3168 |
QByteArray ba("test"); |
| 3169 |
QBuffer *buffer = new QBuffer; |
| 3170 |
buffer->setData(ba); |
| 3171 |
buffer->open(QIODevice::ReadOnly); |
| 3172 |
QTest::newRow("post") << QUrl("http://" + QtNetworkSettings::httpServerName() + "/qtest/cgi-bin/md5sum.cgi") << QByteArray("POST") |
| 3173 |
<< buffer << 200 << QNetworkReply::NoError << QByteArray("098f6bcd4621d373cade4e832627b4f6\n"); |
| 3174 |
|
| 3175 |
QByteArray ba2("test"); |
| 3176 |
QBuffer *buffer2 = new QBuffer; |
| 3177 |
buffer2->setData(ba2); |
| 3178 |
buffer2->open(QIODevice::ReadOnly); |
| 3179 |
QTest::newRow("put") << QUrl("http://" + QtNetworkSettings::httpServerName() + "/qtest/cgi-bin/md5sum.cgi") << QByteArray("PUT") |
| 3180 |
<< buffer2 << 200 << QNetworkReply::NoError << QByteArray("098f6bcd4621d373cade4e832627b4f6\n"); |
| 3181 |
} |
| 3182 |
|
| 3183 |
void tst_QNetworkReply::sendCustomRequestToHttp() |
| 3184 |
{ |
| 3185 |
QFETCH(QUrl, url); |
| 3186 |
QNetworkRequest request(url); |
| 3187 |
QNetworkReplyPtr reply; |
| 3188 |
QFETCH(QByteArray, verb); |
| 3189 |
QFETCH(QBuffer *, device); |
| 3190 |
runCustomRequest(request, reply, verb, device); |
| 3191 |
QCOMPARE(reply->url(), url); |
| 3192 |
QFETCH(QNetworkReply::NetworkError, error); |
| 3193 |
QCOMPARE(reply->error(), error); |
| 3194 |
QFETCH(int, resultCode); |
| 3195 |
QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), resultCode); |
| 3196 |
QFETCH(QByteArray, expectedContent); |
| 3197 |
if (! expectedContent.isEmpty()) |
| 3198 |
QCOMPARE(reply->readAll(), expectedContent); |
| 3199 |
} |
| 3200 |
|
| 3201 |
void tst_QNetworkReply::ioGetFromData_data() |
| 3202 |
{ |
| 3203 |
QTest::addColumn<QString>("urlStr"); |
| 3204 |
QTest::addColumn<QByteArray>("data"); |
| 3205 |
|
| 3206 |
QTest::newRow("data-empty") << "data:," << QByteArray(); |
| 3207 |
QTest::newRow("data-literal") << "data:,foo" << QByteArray("foo"); |
| 3208 |
QTest::newRow("data-pct") << "data:,%3Cbody%20contentEditable%3Dtrue%3E%0D%0A" |
| 3209 |
<< QByteArray("<body contentEditable=true>\r\n"); |
| 3210 |
QTest::newRow("data-base64") << "data:;base64,UXQgaXMgZ3JlYXQh" << QByteArray("Qt is great!"); |
| 3211 |
} |
| 3212 |
|
| 3213 |
void tst_QNetworkReply::ioGetFromData() |
| 3214 |
{ |
| 3215 |
QFETCH(QString, urlStr); |
| 3216 |
|
| 3217 |
QUrl url = QUrl::fromEncoded(urlStr.toLatin1()); |
| 3218 |
QNetworkRequest request(url); |
| 3219 |
|
| 3220 |
QNetworkReplyPtr reply(manager.get(request)); |
| 3221 |
DataReader reader(reply); |
| 3222 |
|
| 3223 |
connect(reply, SIGNAL(finished()), |
| 3224 |
&QTestEventLoop::instance(), SLOT(exitLoop())); |
| 3225 |
QTestEventLoop::instance().enterLoop(10); |
| 3226 |
QVERIFY(!QTestEventLoop::instance().timeout()); |
| 3227 |
|
| 3228 |
QCOMPARE(reply->url(), request.url()); |
| 3229 |
QCOMPARE(reply->error(), QNetworkReply::NoError); |
| 3230 |
|
| 3231 |
QFETCH(QByteArray, data); |
| 3232 |
QCOMPARE(reply->header(QNetworkRequest::ContentLengthHeader).toInt(), data.size()); |
| 3233 |
QCOMPARE(reader.data.size(), data.size()); |
| 3234 |
QCOMPARE(reader.data, data); |
| 3235 |
} |
| 3236 |
|
| 3237 |
void tst_QNetworkReply::ioGetFromFileSpecial_data() |
| 3238 |
{ |
| 3239 |
getFromFileSpecial_data(); |
| 3240 |
} |
| 3241 |
|
| 3242 |
void tst_QNetworkReply::ioGetFromFileSpecial() |
| 3243 |
{ |
| 3244 |
#if defined(QT_TEST_SERVER) && defined(Q_OS_WIN) |
| 3245 |
if (qstrcmp(QTest::currentDataTag(), "smb-path") == 0) |
| 3246 |
QSKIP("Docker-based test server doesn't support smb protocol yet"); |
| 3247 |
#endif |
| 3248 |
|
| 3249 |
QFETCH(QString, fileName); |
| 3250 |
QFETCH(QString, url); |
| 3251 |
|
| 3252 |
QFile resource(fileName); |
| 3253 |
QVERIFY(resource.open(QIODevice::ReadOnly)); |
| 3254 |
|
| 3255 |
QNetworkRequest request; |
| 3256 |
request.setUrl(url); |
| 3257 |
QNetworkReplyPtr reply(manager.get(request)); |
| 3258 |
DataReader reader(reply); |
| 3259 |
|
| 3260 |
connect(reply, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop())); |
| 3261 |
QTestEventLoop::instance().enterLoop(10); |
| 3262 |
QVERIFY(!QTestEventLoop::instance().timeout()); |
| 3263 |
|
| 3264 |
QCOMPARE(reply->url(), request.url()); |
| 3265 |
QCOMPARE(reply->error(), QNetworkReply::NoError); |
| 3266 |
|
| 3267 |
QCOMPARE(reply->header(QNetworkRequest::ContentLengthHeader).toLongLong(), resource.size()); |
| 3268 |
QCOMPARE(qint64(reader.data.size()), resource.size()); |
| 3269 |
QCOMPARE(reader.data, resource.readAll()); |
| 3270 |
} |
| 3271 |
|
| 3272 |
void tst_QNetworkReply::ioGetFromFile_data() |
| 3273 |
{ |
| 3274 |
putToFile_data(); |
| 3275 |
} |
| 3276 |
|
| 3277 |
void tst_QNetworkReply::ioGetFromFile() |
| 3278 |
{ |
| 3279 |
QTemporaryFile file(QDir::currentPath() + "/temp-XXXXXX"); |
| 3280 |
file.setAutoRemove(true); |
| 3281 |
QVERIFY2(file.open(), qPrintable(file.errorString())); |
| 3282 |
|
| 3283 |
QFETCH(QByteArray, data); |
| 3284 |
QCOMPARE(file.write(data), data.size()); |
| 3285 |
file.flush(); |
| 3286 |
QCOMPARE(file.size(), qint64(data.size())); |
| 3287 |
|
| 3288 |
QNetworkRequest request(QUrl::fromLocalFile(file.fileName())); |
| 3289 |
QNetworkReplyPtr reply(manager.get(request)); |
| 3290 |
QVERIFY(reply->isFinished()); // a file should immediately be done |
| 3291 |
DataReader reader(reply); |
| 3292 |
|
| 3293 |
connect(reply, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop())); |
| 3294 |
QTestEventLoop::instance().enterLoop(10); |
| 3295 |
QVERIFY(!QTestEventLoop::instance().timeout()); |
| 3296 |
|
| 3297 |
QCOMPARE(reply->url(), request.url()); |
| 3298 |
QCOMPARE(reply->error(), QNetworkReply::NoError); |
| 3299 |
|
| 3300 |
QCOMPARE(reply->header(QNetworkRequest::ContentLengthHeader).toLongLong(), file.size()); |
| 3301 |
QCOMPARE(qint64(reader.data.size()), file.size()); |
| 3302 |
QCOMPARE(reader.data, data); |
| 3303 |
} |
| 3304 |
|
| 3305 |
void tst_QNetworkReply::ioGetFromFileUrl() |
| 3306 |
{ |
| 3307 |
// This immediately fails on non-windows platforms: |
| 3308 |
QNetworkRequest request(QUrl("file://unc-server/some/path")); |
| 3309 |
QNetworkReplyPtr reply(manager.get(request)); |
| 3310 |
QSignalSpy finishedSpy(reply.get(), &QNetworkReply::finished); |
| 3311 |
// QTBUG-105618: This would, on non-Windows platforms, never happen because the signal |
| 3312 |
// was emitted before the constructor finished, leaving no chance at all to connect to the |
| 3313 |
// signal |
| 3314 |
QVERIFY(finishedSpy.wait()); |
| 3315 |
} |
| 3316 |
|
| 3317 |
void tst_QNetworkReply::ioGetFromFtp_data() |
| 3318 |
{ |
| 3319 |
QTest::addColumn<QString>("fileName"); |
| 3320 |
QTest::addColumn<qint64>("expectedSize"); |
| 3321 |
|
| 3322 |
QTest::newRow("bigfile") << "bigfile" << Q_INT64_C(519240); |
| 3323 |
|
| 3324 |
QFile file(testDataDir + "/rfc3252.txt"); |
| 3325 |
QTest::newRow("rfc3252.txt") << "rfc3252.txt" << file.size(); |
| 3326 |
} |
| 3327 |
|
| 3328 |
void tst_QNetworkReply::ioGetFromFtp() |
| 3329 |
{ |
| 3330 |
QFETCH(QString, fileName); |
| 3331 |
QFile reference(fileName); |
| 3332 |
reference.open(QIODevice::ReadOnly); // will fail for bigfile |
| 3333 |
|
| 3334 |
QNetworkRequest request("ftp://" + QtNetworkSettings::ftpServerName() + "/qtest/" + fileName); |
| 3335 |
QNetworkReplyPtr reply(manager.get(request)); |
| 3336 |
DataReader reader(reply); |
| 3337 |
|
| 3338 |
QVERIFY2(waitForFinish(reply) == Success, msgWaitForFinished(reply)); |
| 3339 |
|
| 3340 |
QCOMPARE(reply->url(), request.url()); |
| 3341 |
QCOMPARE(reply->error(), QNetworkReply::NoError); |
| 3342 |
|
| 3343 |
QFETCH(qint64, expectedSize); |
| 3344 |
QCOMPARE(reply->header(QNetworkRequest::ContentLengthHeader).toLongLong(), expectedSize); |
| 3345 |
QCOMPARE(qint64(reader.data.size()), expectedSize); |
| 3346 |
|
| 3347 |
if (reference.isOpen()) |
| 3348 |
QCOMPARE(reader.data, reference.readAll()); |
| 3349 |
} |
| 3350 |
|
| 3351 |
void tst_QNetworkReply::ioGetFromFtpWithReuse() |
| 3352 |
{ |
| 3353 |
QString fileName = testDataDir + "/rfc3252.txt"; |
| 3354 |
QFile reference(fileName); |
| 3355 |
reference.open(QIODevice::ReadOnly); |
| 3356 |
|
| 3357 |
QNetworkRequest request(QUrl("ftp://" + QtNetworkSettings::ftpServerName() + "/qtest/rfc3252.txt")); |
| 3358 |
|
| 3359 |
// two concurrent (actually, consecutive) gets: |
| 3360 |
QNetworkReplyPtr reply1(manager.get(request)); |
| 3361 |
DataReader reader1(reply1); |
| 3362 |
QNetworkReplyPtr reply2(manager.get(request)); |
| 3363 |
DataReader reader2(reply2); |
| 3364 |
QSignalSpy spy(reply1.data(), SIGNAL(finished())); |
| 3365 |
|
| 3366 |
QCOMPARE(waitForFinish(reply1), int(Success)); |
| 3367 |
QCOMPARE(waitForFinish(reply2), int(Success)); |
| 3368 |
|
| 3369 |
QCOMPARE(reply1->url(), request.url()); |
| 3370 |
QCOMPARE(reply2->url(), request.url()); |
| 3371 |
QCOMPARE(reply1->error(), QNetworkReply::NoError); |
| 3372 |
QCOMPARE(reply2->error(), QNetworkReply::NoError); |
| 3373 |
|
| 3374 |
QCOMPARE(qint64(reader1.data.size()), reference.size()); |
| 3375 |
QCOMPARE(qint64(reader2.data.size()), reference.size()); |
| 3376 |
QCOMPARE(reply1->header(QNetworkRequest::ContentLengthHeader).toLongLong(), reference.size()); |
| 3377 |
QCOMPARE(reply2->header(QNetworkRequest::ContentLengthHeader).toLongLong(), reference.size()); |
| 3378 |
|
| 3379 |
QByteArray referenceData = reference.readAll(); |
| 3380 |
QCOMPARE(reader1.data, referenceData); |
| 3381 |
QCOMPARE(reader2.data, referenceData); |
| 3382 |
} |
| 3383 |
|
| 3384 |
void tst_QNetworkReply::ioGetFromHttp() |
| 3385 |
{ |
| 3386 |
QFile reference(testDataDir + "/rfc3252.txt"); |
| 3387 |
QVERIFY(reference.open(QIODevice::ReadOnly)); |
| 3388 |
|
| 3389 |
QNetworkRequest request(QUrl("http://" + QtNetworkSettings::httpServerName() + "/qtest/rfc3252.txt")); |
| 3390 |
QNetworkReplyPtr reply(manager.get(request)); |
| 3391 |
DataReader reader(reply); |
| 3392 |
|
| 3393 |
QVERIFY2(waitForFinish(reply) == Success, msgWaitForFinished(reply)); |
| 3394 |
|
| 3395 |
QCOMPARE(reply->url(), request.url()); |
| 3396 |
QCOMPARE(reply->error(), QNetworkReply::NoError); |
| 3397 |
QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200); |
| 3398 |
|
| 3399 |
QCOMPARE(reply->header(QNetworkRequest::ContentLengthHeader).toLongLong(), reference.size()); |
| 3400 |
QCOMPARE(qint64(reader.data.size()), reference.size()); |
| 3401 |
|
| 3402 |
QCOMPARE(reader.data, reference.readAll()); |
| 3403 |
} |
| 3404 |
|
| 3405 |
void tst_QNetworkReply::ioGetFromHttpWithReuseParallel() |
| 3406 |
{ |
| 3407 |
QFile reference(testDataDir + "/rfc3252.txt"); |
| 3408 |
QVERIFY(reference.open(QIODevice::ReadOnly)); |
| 3409 |
|
| 3410 |
QNetworkRequest request(QUrl("http://" + QtNetworkSettings::httpServerName() + "/qtest/rfc3252.txt")); |
| 3411 |
QNetworkReplyPtr reply1(manager.get(request)); |
| 3412 |
QNetworkReplyPtr reply2(manager.get(request)); |
| 3413 |
DataReader reader1(reply1); |
| 3414 |
DataReader reader2(reply2); |
| 3415 |
QSignalSpy spy(reply1.data(), SIGNAL(finished())); |
| 3416 |
|
| 3417 |
QCOMPARE(waitForFinish(reply2), int(Success)); |
| 3418 |
QCOMPARE(waitForFinish(reply1), int(Success)); |
| 3419 |
|
| 3420 |
QCOMPARE(reply1->url(), request.url()); |
| 3421 |
QCOMPARE(reply2->url(), request.url()); |
| 3422 |
QCOMPARE(reply1->error(), QNetworkReply::NoError); |
| 3423 |
QCOMPARE(reply2->error(), QNetworkReply::NoError); |
| 3424 |
QCOMPARE(reply1->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200); |
| 3425 |
QCOMPARE(reply2->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200); |
| 3426 |
|
| 3427 |
QCOMPARE(reply1->header(QNetworkRequest::ContentLengthHeader).toLongLong(), reference.size()); |
| 3428 |
QCOMPARE(reply2->header(QNetworkRequest::ContentLengthHeader).toLongLong(), reference.size()); |
| 3429 |
QCOMPARE(qint64(reader1.data.size()), reference.size()); |
| 3430 |
QCOMPARE(qint64(reader2.data.size()), reference.size()); |
| 3431 |
|
| 3432 |
QByteArray referenceData = reference.readAll(); |
| 3433 |
QCOMPARE(reader1.data, referenceData); |
| 3434 |
QCOMPARE(reader2.data, referenceData); |
| 3435 |
} |
| 3436 |
|
| 3437 |
void tst_QNetworkReply::ioGetFromHttpWithReuseSequential() |
| 3438 |
{ |
| 3439 |
QFile reference(testDataDir + "/rfc3252.txt"); |
| 3440 |
QVERIFY(reference.open(QIODevice::ReadOnly)); |
| 3441 |
|
| 3442 |
QNetworkRequest request(QUrl("http://" + QtNetworkSettings::httpServerName() + "/qtest/rfc3252.txt")); |
| 3443 |
{ |
| 3444 |
QNetworkReplyPtr reply(manager.get(request)); |
| 3445 |
DataReader reader(reply); |
| 3446 |
|
| 3447 |
QVERIFY2(waitForFinish(reply) == Success, msgWaitForFinished(reply)); |
| 3448 |
|
| 3449 |
QCOMPARE(reply->url(), request.url()); |
| 3450 |
QCOMPARE(reply->error(), QNetworkReply::NoError); |
| 3451 |
QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200); |
| 3452 |
|
| 3453 |
QCOMPARE(reply->header(QNetworkRequest::ContentLengthHeader).toLongLong(), reference.size()); |
| 3454 |
QCOMPARE(qint64(reader.data.size()), reference.size()); |
| 3455 |
|
| 3456 |
QCOMPARE(reader.data, reference.readAll()); |
| 3457 |
} |
| 3458 |
|
| 3459 |
reference.seek(0); |
| 3460 |
// rinse and repeat: |
| 3461 |
{ |
| 3462 |
QNetworkReplyPtr reply(manager.get(request)); |
| 3463 |
DataReader reader(reply); |
| 3464 |
|
| 3465 |
QVERIFY2(waitForFinish(reply) == Success, msgWaitForFinished(reply)); |
| 3466 |
|
| 3467 |
QCOMPARE(reply->url(), request.url()); |
| 3468 |
QCOMPARE(reply->error(), QNetworkReply::NoError); |
| 3469 |
QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200); |
| 3470 |
|
| 3471 |
QCOMPARE(reply->header(QNetworkRequest::ContentLengthHeader).toLongLong(), reference.size()); |
| 3472 |
QCOMPARE(qint64(reader.data.size()), reference.size()); |
| 3473 |
|
| 3474 |
QCOMPARE(reader.data, reference.readAll()); |
| 3475 |
} |
| 3476 |
} |
| 3477 |
|
| 3478 |
void tst_QNetworkReply::ioGetFromHttpWithAuth_data() |
| 3479 |
{ |
| 3480 |
QTest::addColumn<QUrl>("url"); |
| 3481 |
QTest::addColumn<QByteArray>("expectedData"); |
| 3482 |
QTest::addColumn<int>("expectedAuth"); |
| 3483 |
|
| 3484 |
QFile reference(testDataDir + "/rfc3252.txt"); |
| 3485 |
reference.open(QIODevice::ReadOnly); |
| 3486 |
QByteArray referenceData = reference.readAll(); |
| 3487 |
QString httpServer = QtNetworkSettings::httpServerName(); |
| 3488 |
QTest::newRow("basic") |
| 3489 |
<< QUrl("http://" + httpServer + "/qtest/rfcs-auth/rfc3252.txt") |
| 3490 |
<< referenceData << 1; |
| 3491 |
|
| 3492 |
QTest::newRow("digest") |
| 3493 |
<< QUrl("http://" + httpServer + "/qtest/auth-digest/") |
| 3494 |
<< QByteArray("digest authentication successful\n") << 1; |
| 3495 |
|
| 3496 |
//if url contains username & password, then it should be used |
| 3497 |
QTest::newRow("basic-in-url") |
| 3498 |
<< QUrl("http://httptest:httptest@" + httpServer + "/qtest/rfcs-auth/rfc3252.txt") |
| 3499 |
<< referenceData << 0; |
| 3500 |
|
| 3501 |
QTest::newRow("digest-in-url") |
| 3502 |
<< QUrl("http://httptest:httptest@" + httpServer + "/qtest/auth-digest/") |
| 3503 |
<< QByteArray("digest authentication successful\n") << 0; |
| 3504 |
|
| 3505 |
// if url contains incorrect credentials, expect QNAM to ask for good ones (even if cached - matches behaviour of browsers) |
| 3506 |
QTest::newRow("basic-bad-user-in-url") |
| 3507 |
<< QUrl("http://baduser:httptest@" + httpServer + "/qtest/rfcs-auth/rfc3252.txt") |
| 3508 |
<< referenceData << 3; |
| 3509 |
|
| 3510 |
QTest::newRow("basic-bad-password-in-url") |
| 3511 |
<< QUrl("http://httptest:wrong@" + httpServer + "/qtest/rfcs-auth/rfc3252.txt") |
| 3512 |
<< referenceData << 3; |
| 3513 |
|
| 3514 |
QTest::newRow("digest-bad-user-in-url") |
| 3515 |
<< QUrl("http://baduser:httptest@" + httpServer + "/qtest/auth-digest/") |
| 3516 |
<< QByteArray("digest authentication successful\n") << 3; |
| 3517 |
|
| 3518 |
QTest::newRow("digest-bad-password-in-url") |
| 3519 |
<< QUrl("http://httptest:wrong@" + httpServer + "/qtest/auth-digest/") |
| 3520 |
<< QByteArray("digest authentication successful\n") << 3; |
| 3521 |
} |
| 3522 |
|
| 3523 |
void tst_QNetworkReply::ioGetFromHttpWithAuth() |
| 3524 |
{ |
| 3525 |
// This test sends three requests |
| 3526 |
// The first two in parallel |
| 3527 |
// The third after the first two finished |
| 3528 |
|
| 3529 |
QFETCH(QUrl, url); |
| 3530 |
QFETCH(QByteArray, expectedData); |
| 3531 |
QFETCH(int, expectedAuth); |
| 3532 |
QNetworkRequest request(url); |
| 3533 |
{ |
| 3534 |
QNetworkReplyPtr reply1(manager.get(request)); |
| 3535 |
QUrl copy = url; |
| 3536 |
copy.setUserName(QString()); |
| 3537 |
copy.setPassword(QString()); |
| 3538 |
QNetworkRequest request2(copy); |
| 3539 |
QNetworkReplyPtr reply2(manager.get(request2)); |
| 3540 |
DataReader reader1(reply1); |
| 3541 |
DataReader reader2(reply2); |
| 3542 |
QSignalSpy finishedspy(reply1.data(), SIGNAL(finished())); |
| 3543 |
|
| 3544 |
QSignalSpy authspy(&manager, SIGNAL(authenticationRequired(QNetworkReply*,QAuthenticator*))); |
| 3545 |
connect(&manager, SIGNAL(authenticationRequired(QNetworkReply*,QAuthenticator*)), |
| 3546 |
SLOT(authenticationRequired(QNetworkReply*,QAuthenticator*))); |
| 3547 |
|
| 3548 |
QCOMPARE(waitForFinish(reply2), int(Success)); |
| 3549 |
QCOMPARE(waitForFinish(reply1), int(Success)); |
| 3550 |
|
| 3551 |
manager.disconnect(SIGNAL(authenticationRequired(QNetworkReply*,QAuthenticator*)), |
| 3552 |
this, SLOT(authenticationRequired(QNetworkReply*,QAuthenticator*))); |
| 3553 |
|
| 3554 |
QCOMPARE(reply1->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200); |
| 3555 |
QCOMPARE(reply2->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200); |
| 3556 |
QCOMPARE(reader1.data, expectedData); |
| 3557 |
QCOMPARE(reader2.data, expectedData); |
| 3558 |
|
| 3559 |
QCOMPARE(authspy.count(), (expectedAuth ? 1 : 0)); |
| 3560 |
expectedAuth = qMax(0, expectedAuth - 1); |
| 3561 |
} |
| 3562 |
|
| 3563 |
// rinse and repeat: |
| 3564 |
{ |
| 3565 |
QNetworkReplyPtr reply(manager.get(request)); |
| 3566 |
DataReader reader(reply); |
| 3567 |
|
| 3568 |
QSignalSpy authspy(&manager, SIGNAL(authenticationRequired(QNetworkReply*,QAuthenticator*))); |
| 3569 |
connect(&manager, SIGNAL(authenticationRequired(QNetworkReply*,QAuthenticator*)), |
| 3570 |
SLOT(authenticationRequired(QNetworkReply*,QAuthenticator*))); |
| 3571 |
|
| 3572 |
QVERIFY2(waitForFinish(reply) == Success, msgWaitForFinished(reply)); |
| 3573 |
|
| 3574 |
manager.disconnect(SIGNAL(authenticationRequired(QNetworkReply*,QAuthenticator*)), |
| 3575 |
this, SLOT(authenticationRequired(QNetworkReply*,QAuthenticator*))); |
| 3576 |
|
| 3577 |
QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200); |
| 3578 |
QCOMPARE(reader.data, expectedData); |
| 3579 |
|
| 3580 |
QCOMPARE(authspy.count(), (expectedAuth ? 1 : 0)); |
| 3581 |
expectedAuth = qMax(0, expectedAuth - 1); |
| 3582 |
} |
| 3583 |
|
| 3584 |
// now check with synchronous calls: |
| 3585 |
{ |
| 3586 |
request.setAttribute( |
| 3587 |
QNetworkRequest::SynchronousRequestAttribute, |
| 3588 |
true); |
| 3589 |
|
| 3590 |
QSignalSpy authspy(&manager, SIGNAL(authenticationRequired(QNetworkReply*,QAuthenticator*))); |
| 3591 |
QNetworkReplyPtr replySync(manager.get(request)); |
| 3592 |
QVERIFY(replySync->isFinished()); // synchronous |
| 3593 |
if (expectedAuth) { |
| 3594 |
// bad credentials in a synchronous request should just fail |
| 3595 |
QCOMPARE(replySync->error(), QNetworkReply::AuthenticationRequiredError); |
| 3596 |
} else { |
| 3597 |
QCOMPARE(authspy.count(), 0); |
| 3598 |
|
| 3599 |
// we cannot use a data reader here, since that connects to the readyRead signal, |
| 3600 |
// just use readAll() |
| 3601 |
|
| 3602 |
// the only thing we check here is that the auth cache was used when using synchronous requests |
| 3603 |
QCOMPARE(replySync->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200); |
| 3604 |
QCOMPARE(replySync->readAll(), expectedData); |
| 3605 |
} |
| 3606 |
} |
| 3607 |
|
| 3608 |
// check that credentials are used from cache if the same url is requested without credentials |
| 3609 |
{ |
| 3610 |
url.setUserInfo(QString()); |
| 3611 |
request.setUrl(url); |
| 3612 |
request.setAttribute( |
| 3613 |
QNetworkRequest::SynchronousRequestAttribute, |
| 3614 |
true); |
| 3615 |
|
| 3616 |
QSignalSpy authspy(&manager, SIGNAL(authenticationRequired(QNetworkReply*,QAuthenticator*))); |
| 3617 |
QNetworkReplyPtr replySync(manager.get(request)); |
| 3618 |
QVERIFY(replySync->isFinished()); // synchronous |
| 3619 |
if (expectedAuth) { |
| 3620 |
// bad credentials in a synchronous request should just fail |
| 3621 |
QCOMPARE(replySync->error(), QNetworkReply::AuthenticationRequiredError); |
| 3622 |
} else { |
| 3623 |
QCOMPARE(authspy.count(), 0); |
| 3624 |
|
| 3625 |
// we cannot use a data reader here, since that connects to the readyRead signal, |
| 3626 |
// just use readAll() |
| 3627 |
|
| 3628 |
// the only thing we check here is that the auth cache was used when using synchronous requests |
| 3629 |
QCOMPARE(replySync->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200); |
| 3630 |
QCOMPARE(replySync->readAll(), expectedData); |
| 3631 |
} |
| 3632 |
} |
| 3633 |
} |
| 3634 |
|
| 3635 |
void tst_QNetworkReply::ioGetFromHttpWithAuthSynchronous() |
| 3636 |
{ |
| 3637 |
// verify that we do not enter an endless loop with synchronous calls and wrong credentials |
| 3638 |
// the case when we succeed with the login is tested in ioGetFromHttpWithAuth() |
| 3639 |
|
| 3640 |
QNetworkRequest request(QUrl("http://" + QtNetworkSettings::httpServerName() + "/qtest/rfcs-auth/rfc3252.txt")); |
| 3641 |
request.setAttribute( |
| 3642 |
QNetworkRequest::SynchronousRequestAttribute, |
| 3643 |
true); |
| 3644 |
|
| 3645 |
QSignalSpy authspy(&manager, SIGNAL(authenticationRequired(QNetworkReply*,QAuthenticator*))); |
| 3646 |
QNetworkReplyPtr replySync(manager.get(request)); |
| 3647 |
QVERIFY(replySync->isFinished()); // synchronous |
| 3648 |
QCOMPARE(replySync->error(), QNetworkReply::AuthenticationRequiredError); |
| 3649 |
QCOMPARE(authspy.count(), 0); |
| 3650 |
QCOMPARE(replySync->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 401); |
| 3651 |
} |
| 3652 |
|
| 3653 |
#ifndef QT_NO_NETWORKPROXY |
| 3654 |
void tst_QNetworkReply::ioGetFromHttpWithProxyAuth() |
| 3655 |
{ |
| 3656 |
// This test sends three requests |
| 3657 |
// The first two in parallel |
| 3658 |
// The third after the first two finished |
| 3659 |
QFile reference(testDataDir + "/rfc3252.txt"); |
| 3660 |
QVERIFY(reference.open(QIODevice::ReadOnly)); |
| 3661 |
|
| 3662 |
QNetworkProxy proxy(QNetworkProxy::HttpCachingProxy, QtNetworkSettings::httpProxyServerName(), 3129); |
| 3663 |
QNetworkRequest request(QUrl("http://" + QtNetworkSettings::httpServerName() + "/qtest/rfc3252.txt")); |
| 3664 |
{ |
| 3665 |
manager.setProxy(proxy); |
| 3666 |
QNetworkReplyPtr reply1(manager.get(request)); |
| 3667 |
QNetworkReplyPtr reply2(manager.get(request)); |
| 3668 |
manager.setProxy(QNetworkProxy()); |
| 3669 |
|
| 3670 |
DataReader reader1(reply1); |
| 3671 |
DataReader reader2(reply2); |
| 3672 |
QSignalSpy finishedspy(reply1.data(), SIGNAL(finished())); |
| 3673 |
|
| 3674 |
QSignalSpy authspy(&manager, SIGNAL(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*))); |
| 3675 |
connect(&manager, SIGNAL(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)), |
| 3676 |
SLOT(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*))); |
| 3677 |
|
| 3678 |
QCOMPARE(waitForFinish(reply2), int(Success)); |
| 3679 |
QCOMPARE(waitForFinish(reply1), int(Success)); |
| 3680 |
|
| 3681 |
manager.disconnect(SIGNAL(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)), |
| 3682 |
this, SLOT(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*))); |
| 3683 |
|
| 3684 |
QCOMPARE(reply1->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200); |
| 3685 |
QCOMPARE(reply2->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200); |
| 3686 |
QByteArray referenceData = reference.readAll(); |
| 3687 |
QCOMPARE(reader1.data, referenceData); |
| 3688 |
QCOMPARE(reader2.data, referenceData); |
| 3689 |
|
| 3690 |
QCOMPARE(authspy.count(), 1); |
| 3691 |
} |
| 3692 |
|
| 3693 |
reference.seek(0); |
| 3694 |
// rinse and repeat: |
| 3695 |
{ |
| 3696 |
manager.setProxy(proxy); |
| 3697 |
QNetworkReplyPtr reply(manager.get(request)); |
| 3698 |
DataReader reader(reply); |
| 3699 |
manager.setProxy(QNetworkProxy()); |
| 3700 |
|
| 3701 |
QSignalSpy authspy(&manager, SIGNAL(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*))); |
| 3702 |
connect(&manager, SIGNAL(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)), |
| 3703 |
SLOT(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*))); |
| 3704 |
|
| 3705 |
QVERIFY2(waitForFinish(reply) == Success, msgWaitForFinished(reply)); |
| 3706 |
|
| 3707 |
manager.disconnect(SIGNAL(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)), |
| 3708 |
this, SLOT(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*))); |
| 3709 |
|
| 3710 |
QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200); |
| 3711 |
QCOMPARE(reader.data, reference.readAll()); |
| 3712 |
|
| 3713 |
QCOMPARE(authspy.count(), 0); |
| 3714 |
} |
| 3715 |
|
| 3716 |
// now check with synchronous calls: |
| 3717 |
reference.seek(0); |
| 3718 |
{ |
| 3719 |
request.setAttribute( |
| 3720 |
QNetworkRequest::SynchronousRequestAttribute, |
| 3721 |
true); |
| 3722 |
|
| 3723 |
QSignalSpy authspy(&manager, SIGNAL(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*))); |
| 3724 |
QNetworkReplyPtr replySync(manager.get(request)); |
| 3725 |
QVERIFY(replySync->isFinished()); // synchronous |
| 3726 |
QCOMPARE(authspy.count(), 0); |
| 3727 |
|
| 3728 |
// we cannot use a data reader here, since that connects to the readyRead signal, |
| 3729 |
// just use readAll() |
| 3730 |
|
| 3731 |
// the only thing we check here is that the proxy auth cache was used when using synchronous requests |
| 3732 |
QCOMPARE(replySync->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200); |
| 3733 |
QCOMPARE(replySync->readAll(), reference.readAll()); |
| 3734 |
} |
| 3735 |
} |
| 3736 |
|
| 3737 |
void tst_QNetworkReply::ioGetFromHttpWithProxyAuthSynchronous() |
| 3738 |
{ |
| 3739 |
// verify that we do not enter an endless loop with synchronous calls and wrong credentials |
| 3740 |
// the case when we succeed with the login is tested in ioGetFromHttpWithAuth() |
| 3741 |
|
| 3742 |
QNetworkProxy proxy(QNetworkProxy::HttpCachingProxy, QtNetworkSettings::httpProxyServerName(), 3129); |
| 3743 |
QNetworkRequest request(QUrl("http://" + QtNetworkSettings::httpServerName() + "/qtest/rfc3252.txt")); |
| 3744 |
manager.setProxy(proxy); |
| 3745 |
request.setAttribute( |
| 3746 |
QNetworkRequest::SynchronousRequestAttribute, |
| 3747 |
true); |
| 3748 |
|
| 3749 |
QSignalSpy authspy(&manager, SIGNAL(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*))); |
| 3750 |
QNetworkReplyPtr replySync(manager.get(request)); |
| 3751 |
manager.setProxy(QNetworkProxy()); // reset |
| 3752 |
QVERIFY(replySync->isFinished()); // synchronous |
| 3753 |
QCOMPARE(replySync->error(), QNetworkReply::ProxyAuthenticationRequiredError); |
| 3754 |
QCOMPARE(authspy.count(), 0); |
| 3755 |
QCOMPARE(replySync->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 407); |
| 3756 |
} |
| 3757 |
|
| 3758 |
void tst_QNetworkReply::ioGetFromHttpWithSocksProxy() |
| 3759 |
{ |
| 3760 |
// HTTP caching proxies are tested by the above function |
| 3761 |
// test SOCKSv5 proxies too |
| 3762 |
|
| 3763 |
QFile reference(testDataDir + "/rfc3252.txt"); |
| 3764 |
QVERIFY(reference.open(QIODevice::ReadOnly)); |
| 3765 |
|
| 3766 |
QNetworkProxy proxy(QNetworkProxy::Socks5Proxy, QtNetworkSettings::socksProxyServerName(), 1080); |
| 3767 |
QNetworkRequest request(QUrl("http://" + QtNetworkSettings::httpServerName() + "/qtest/rfc3252.txt")); |
| 3768 |
{ |
| 3769 |
manager.setProxy(proxy); |
| 3770 |
QNetworkReplyPtr reply(manager.get(request)); |
| 3771 |
DataReader reader(reply); |
| 3772 |
manager.setProxy(QNetworkProxy()); |
| 3773 |
|
| 3774 |
QSignalSpy authspy(&manager, SIGNAL(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*))); |
| 3775 |
connect(&manager, SIGNAL(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)), |
| 3776 |
SLOT(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*))); |
| 3777 |
|
| 3778 |
QVERIFY2(waitForFinish(reply) == Success, msgWaitForFinished(reply)); |
| 3779 |
|
| 3780 |
manager.disconnect(SIGNAL(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)), |
| 3781 |
this, SLOT(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*))); |
| 3782 |
|
| 3783 |
QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200); |
| 3784 |
QCOMPARE(reader.data, reference.readAll()); |
| 3785 |
|
| 3786 |
QCOMPARE(authspy.count(), 0); |
| 3787 |
} |
| 3788 |
|
| 3789 |
// set an invalid proxy just to make sure that we can't load |
| 3790 |
proxy = QNetworkProxy(QNetworkProxy::Socks5Proxy, QtNetworkSettings::socksProxyServerName(), 1079); |
| 3791 |
{ |
| 3792 |
manager.setProxy(proxy); |
| 3793 |
QNetworkReplyPtr reply(manager.get(request)); |
| 3794 |
DataReader reader(reply); |
| 3795 |
manager.setProxy(QNetworkProxy()); |
| 3796 |
|
| 3797 |
QSignalSpy authspy(&manager, SIGNAL(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*))); |
| 3798 |
connect(&manager, SIGNAL(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)), |
| 3799 |
SLOT(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*))); |
| 3800 |
|
| 3801 |
QCOMPARE(waitForFinish(reply), int(Failure)); |
| 3802 |
|
| 3803 |
manager.disconnect(SIGNAL(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)), |
| 3804 |
this, SLOT(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*))); |
| 3805 |
|
| 3806 |
QVERIFY(!reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).isValid()); |
| 3807 |
QVERIFY(reader.data.isEmpty()); |
| 3808 |
|
| 3809 |
QVERIFY(int(reply->error()) > 0); |
| 3810 |
QEXPECT_FAIL("", "QTcpSocket doesn't return enough information yet", Continue); |
| 3811 |
QCOMPARE(int(reply->error()), int(QNetworkReply::ProxyConnectionRefusedError)); |
| 3812 |
|
| 3813 |
QCOMPARE(authspy.count(), 0); |
| 3814 |
} |
| 3815 |
} |
| 3816 |
#endif // !QT_NO_NETWORKPROXY |
| 3817 |
|
| 3818 |
#ifndef QT_NO_SSL |
| 3819 |
void tst_QNetworkReply::ioGetFromHttpsWithSslErrors() |
| 3820 |
{ |
| 3821 |
QFile reference(testDataDir + "/rfc3252.txt"); |
| 3822 |
QVERIFY(reference.open(QIODevice::ReadOnly)); |
| 3823 |
|
| 3824 |
QNetworkRequest request(QUrl("https://" + QtNetworkSettings::httpServerName() + "/qtest/rfc3252.txt")); |
| 3825 |
QNetworkReplyPtr reply(manager.get(request)); |
| 3826 |
DataReader reader(reply); |
| 3827 |
|
| 3828 |
QSignalSpy sslspy(&manager, SIGNAL(sslErrors(QNetworkReply*,QList<QSslError>))); |
| 3829 |
connect(&manager, SIGNAL(sslErrors(QNetworkReply*,QList<QSslError>)), |
| 3830 |
SLOT(sslErrors(QNetworkReply*,QList<QSslError>))); |
| 3831 |
connect(reply, SIGNAL(metaDataChanged()), SLOT(storeSslConfiguration())); |
| 3832 |
|
| 3833 |
QVERIFY2(waitForFinish(reply) == Success, msgWaitForFinished(reply)); |
| 3834 |
|
| 3835 |
manager.disconnect(SIGNAL(sslErrors(QNetworkReply*,QList<QSslError>)), |
| 3836 |
this, SLOT(sslErrors(QNetworkReply*,QList<QSslError>))); |
| 3837 |
|
| 3838 |
QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200); |
| 3839 |
QCOMPARE(reader.data, reference.readAll()); |
| 3840 |
|
| 3841 |
QCOMPARE(sslspy.count(), 1); |
| 3842 |
|
| 3843 |
QVERIFY(!storedSslConfiguration.isNull()); |
| 3844 |
QVERIFY(!reply->sslConfiguration().isNull()); |
| 3845 |
} |
| 3846 |
|
| 3847 |
void tst_QNetworkReply::ioGetFromHttpsWithIgnoreSslErrors() |
| 3848 |
{ |
| 3849 |
// same as above, except that we call ignoreSslErrors and don't connect |
| 3850 |
// to the sslErrors() signal (which is *still* emitted) |
| 3851 |
|
| 3852 |
QFile reference(testDataDir + "/rfc3252.txt"); |
| 3853 |
QVERIFY(reference.open(QIODevice::ReadOnly)); |
| 3854 |
|
| 3855 |
QNetworkRequest request(QUrl("https://" + QtNetworkSettings::httpServerName() + "/qtest/rfc3252.txt")); |
| 3856 |
|
| 3857 |
QNetworkReplyPtr reply(manager.get(request)); |
| 3858 |
reply->ignoreSslErrors(); |
| 3859 |
DataReader reader(reply); |
| 3860 |
|
| 3861 |
QSignalSpy sslspy(&manager, SIGNAL(sslErrors(QNetworkReply*,QList<QSslError>))); |
| 3862 |
connect(reply, SIGNAL(metaDataChanged()), SLOT(storeSslConfiguration())); |
| 3863 |
|
| 3864 |
QVERIFY2(waitForFinish(reply) == Success, msgWaitForFinished(reply)); |
| 3865 |
|
| 3866 |
QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200); |
| 3867 |
QCOMPARE(reader.data, reference.readAll()); |
| 3868 |
|
| 3869 |
QCOMPARE(sslspy.count(), 1); |
| 3870 |
|
| 3871 |
QVERIFY(!storedSslConfiguration.isNull()); |
| 3872 |
QVERIFY(!reply->sslConfiguration().isNull()); |
| 3873 |
} |
| 3874 |
|
| 3875 |
void tst_QNetworkReply::ioGetFromHttpsWithSslHandshakeError() |
| 3876 |
{ |
| 3877 |
QFile reference(testDataDir + "/rfc3252.txt"); |
| 3878 |
QVERIFY(reference.open(QIODevice::ReadOnly)); |
| 3879 |
|
| 3880 |
QNetworkRequest request(QUrl("https://" + QtNetworkSettings::httpServerName() + ":80")); |
| 3881 |
|
| 3882 |
QNetworkReplyPtr reply(manager.get(request)); |
| 3883 |
reply->ignoreSslErrors(); |
| 3884 |
DataReader reader(reply); |
| 3885 |
|
| 3886 |
QSignalSpy sslspy(&manager, SIGNAL(sslErrors(QNetworkReply*,QList<QSslError>))); |
| 3887 |
connect(reply, SIGNAL(metaDataChanged()), SLOT(storeSslConfiguration())); |
| 3888 |
|
| 3889 |
QCOMPARE(waitForFinish(reply), int(Failure)); |
| 3890 |
|
| 3891 |
QCOMPARE(reply->error(), QNetworkReply::SslHandshakeFailedError); |
| 3892 |
QCOMPARE(sslspy.count(), 0); |
| 3893 |
} |
| 3894 |
#endif |
| 3895 |
|
| 3896 |
void tst_QNetworkReply::ioGetFromHttpBrokenServer_data() |
| 3897 |
{ |
| 3898 |
QTest::addColumn<QByteArray>("dataToSend"); |
| 3899 |
QTest::addColumn<bool>("doDisconnect"); |
| 3900 |
|
| 3901 |
QTest::newRow("no-newline") << QByteArray("Hello World") << false; |
| 3902 |
|
| 3903 |
// these are OK now, we just eat the lonely newlines |
| 3904 |
//QTest::newRow("just-newline") << QByteArray("\r\n") << false; |
| 3905 |
//QTest::newRow("just-2newline") << QByteArray("\r\n\r\n") << false; |
| 3906 |
|
| 3907 |
QTest::newRow("with-newlines") << QByteArray("Long first line\r\nLong second line") << false; |
| 3908 |
QTest::newRow("with-newlines2") << QByteArray("\r\nSecond line") << false; |
| 3909 |
QTest::newRow("with-newlines3") << QByteArray("ICY\r\nSecond line") << false; |
| 3910 |
QTest::newRow("invalid-version") << QByteArray("HTTP/123 200 \r\n") << false; |
| 3911 |
QTest::newRow("invalid-version2") << QByteArray("HTTP/a.\033 200 \r\n") << false; |
| 3912 |
QTest::newRow("invalid-reply-code") << QByteArray("HTTP/1.0 fuu \r\n") << false; |
| 3913 |
|
| 3914 |
QTest::newRow("empty+disconnect") << QByteArray() << true; |
| 3915 |
|
| 3916 |
QTest::newRow("no-newline+disconnect") << QByteArray("Hello World") << true; |
| 3917 |
QTest::newRow("just-newline+disconnect") << QByteArray("\r\n") << true; |
| 3918 |
QTest::newRow("just-2newline+disconnect") << QByteArray("\r\n\r\n") << true; |
| 3919 |
QTest::newRow("with-newlines+disconnect") << QByteArray("Long first line\r\nLong second line") << true; |
| 3920 |
QTest::newRow("with-newlines2+disconnect") << QByteArray("\r\nSecond line") << true; |
| 3921 |
QTest::newRow("with-newlines3+disconnect") << QByteArray("ICY\r\nSecond line") << true; |
| 3922 |
|
| 3923 |
QTest::newRow("invalid-version+disconnect") << QByteArray("HTTP/123 200 ") << true; |
| 3924 |
QTest::newRow("invalid-version2+disconnect") << QByteArray("HTTP/a.\033 200 ") << true; |
| 3925 |
QTest::newRow("invalid-reply-code+disconnect") << QByteArray("HTTP/1.0 fuu ") << true; |
| 3926 |
|
| 3927 |
QTest::newRow("immediate disconnect") << QByteArray("") << true; |
| 3928 |
QTest::newRow("justHalfStatus+disconnect") << QByteArray("HTTP/1.1") << true; |
| 3929 |
QTest::newRow("justStatus+disconnect") << QByteArray("HTTP/1.1 200 OK\r\n") << true; |
| 3930 |
QTest::newRow("justStatusAndHalfHeaders+disconnect") << QByteArray("HTTP/1.1 200 OK\r\nContent-L") << true; |
| 3931 |
|
| 3932 |
QTest::newRow("halfContent+disconnect") << QByteArray("HTTP/1.1 200 OK\r\nContent-Length: 4\r\n\r\nAB") << true; |
| 3933 |
|
| 3934 |
} |
| 3935 |
|
| 3936 |
void tst_QNetworkReply::ioGetFromHttpBrokenServer() |
| 3937 |
{ |
| 3938 |
QFETCH(QByteArray, dataToSend); |
| 3939 |
QFETCH(bool, doDisconnect); |
| 3940 |
MiniHttpServer server(dataToSend); |
| 3941 |
server.doClose = doDisconnect; |
| 3942 |
|
| 3943 |
QNetworkRequest request(QUrl("http://localhost:" + QString::number(server.serverPort()))); |
| 3944 |
QNetworkReplyPtr reply(manager.get(request)); |
| 3945 |
QSignalSpy spy(reply.data(), SIGNAL(errorOccurred(QNetworkReply::NetworkError))); |
| 3946 |
|
| 3947 |
QCOMPARE(waitForFinish(reply), int(Failure)); |
| 3948 |
|
| 3949 |
QCOMPARE(reply->url(), request.url()); |
| 3950 |
QCOMPARE(spy.count(), 1); |
| 3951 |
QVERIFY(reply->error() != QNetworkReply::NoError); |
| 3952 |
} |
| 3953 |
|
| 3954 |
void tst_QNetworkReply::ioGetFromHttpStatus100_data() |
| 3955 |
{ |
| 3956 |
QTest::addColumn<QByteArray>("dataToSend"); |
| 3957 |
QTest::addColumn<int>("statusCode"); |
| 3958 |
QTest::newRow("normal") << QByteArray("HTTP/1.1 100 Continue\r\n\r\nHTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n") << 200; |
| 3959 |
QTest::newRow("minimal") << QByteArray("HTTP/1.1 100 Continue\n\nHTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n") << 200; |
| 3960 |
QTest::newRow("minimal2") << QByteArray("HTTP/1.1 100 Continue\n\nHTTP/1.0 200 OK\r\n\r\n") << 200; |
| 3961 |
QTest::newRow("minimal3") << QByteArray("HTTP/1.1 100 Continue\n\nHTTP/1.0 200 OK\n\n") << 200; |
| 3962 |
QTest::newRow("minimal+404") << QByteArray("HTTP/1.1 100 Continue\n\nHTTP/1.0 204 No Content\r\n\r\n") << 204; |
| 3963 |
QTest::newRow("with_headers") << QByteArray("HTTP/1.1 100 Continue\r\nBla: x\r\n\r\nHTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n") << 200; |
| 3964 |
QTest::newRow("with_headers2") << QByteArray("HTTP/1.1 100 Continue\nBla: x\n\nHTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n") << 200; |
| 3965 |
} |
| 3966 |
|
| 3967 |
void tst_QNetworkReply::ioGetFromHttpStatus100() |
| 3968 |
{ |
| 3969 |
QFETCH(QByteArray, dataToSend); |
| 3970 |
QFETCH(int, statusCode); |
| 3971 |
MiniHttpServer server(dataToSend); |
| 3972 |
server.doClose = true; |
| 3973 |
|
| 3974 |
QNetworkRequest request(QUrl("http://localhost:" + QString::number(server.serverPort()))); |
| 3975 |
QNetworkReplyPtr reply(manager.get(request)); |
| 3976 |
|
| 3977 |
QVERIFY2(waitForFinish(reply) == Success, msgWaitForFinished(reply)); |
| 3978 |
|
| 3979 |
QCOMPARE(reply->url(), request.url()); |
| 3980 |
QCOMPARE(reply->error(), QNetworkReply::NoError); |
| 3981 |
QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), statusCode); |
| 3982 |
QVERIFY(reply->rawHeader("bla").isNull()); |
| 3983 |
} |
| 3984 |
|
| 3985 |
void tst_QNetworkReply::ioGetFromHttpNoHeaders_data() |
| 3986 |
{ |
| 3987 |
QTest::addColumn<QByteArray>("dataToSend"); |
| 3988 |
QTest::newRow("justStatus+noheaders+disconnect") << QByteArray("HTTP/1.0 200 OK\r\n\r\n"); |
| 3989 |
} |
| 3990 |
|
| 3991 |
void tst_QNetworkReply::ioGetFromHttpNoHeaders() |
| 3992 |
{ |
| 3993 |
QFETCH(QByteArray, dataToSend); |
| 3994 |
MiniHttpServer server(dataToSend); |
| 3995 |
server.doClose = true; |
| 3996 |
|
| 3997 |
QNetworkRequest request(QUrl("http://localhost:" + QString::number(server.serverPort()))); |
| 3998 |
QNetworkReplyPtr reply(manager.get(request)); |
| 3999 |
|
| 4000 |
QVERIFY2(waitForFinish(reply) == Success, msgWaitForFinished(reply)); |
| 4001 |
|
| 4002 |
QCOMPARE(reply->url(), request.url()); |
| 4003 |
QCOMPARE(reply->error(), QNetworkReply::NoError); |
| 4004 |
QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200); |
| 4005 |
} |
| 4006 |
|
| 4007 |
void tst_QNetworkReply::ioGetFromHttpWithCache_data() |
| 4008 |
{ |
| 4009 |
qRegisterMetaType<MyMemoryCache::CachedContent>(); |
| 4010 |
QTest::addColumn<QByteArray>("dataToSend"); |
| 4011 |
QTest::addColumn<QString>("body"); |
| 4012 |
QTest::addColumn<MyMemoryCache::CachedContent>("cachedReply"); |
| 4013 |
QTest::addColumn<int>("cacheMode"); |
| 4014 |
QTest::addColumn<QStringList>("extraHttpHeaders"); |
| 4015 |
QTest::addColumn<bool>("loadedFromCache"); |
| 4016 |
QTest::addColumn<bool>("networkUsed"); |
| 4017 |
|
| 4018 |
QByteArray reply200 = |
| 4019 |
"HTTP/1.0 200\r\n" |
| 4020 |
"Connection: keep-alive\r\n" |
| 4021 |
"Content-Type: text/plain\r\n" |
| 4022 |
"Cache-control: no-store\r\n" |
| 4023 |
"Content-length: 8\r\n" |
| 4024 |
"\r\n" |
| 4025 |
"Reloaded"; |
| 4026 |
QByteArray reply304 = |
| 4027 |
"HTTP/1.0 304 Use Cache\r\n" |
| 4028 |
"Connection: keep-alive\r\n" |
| 4029 |
"\r\n"; |
| 4030 |
|
| 4031 |
QTest::newRow("not-cached,always-network") |
| 4032 |
<< reply200 << "Reloaded" << MyMemoryCache::CachedContent() << int(QNetworkRequest::AlwaysNetwork) << QStringList() << false << true; |
| 4033 |
QTest::newRow("not-cached,prefer-network") |
| 4034 |
<< reply200 << "Reloaded" << MyMemoryCache::CachedContent() << int(QNetworkRequest::PreferNetwork) << QStringList() << false << true; |
| 4035 |
QTest::newRow("not-cached,prefer-cache") |
| 4036 |
<< reply200 << "Reloaded" << MyMemoryCache::CachedContent() << int(QNetworkRequest::PreferCache) << QStringList() << false << true; |
| 4037 |
|
| 4038 |
QDateTime present = QDateTime::currentDateTime().toUTC(); |
| 4039 |
QDateTime past = present.addSecs(-3600); |
| 4040 |
QDateTime future = present.addSecs(3600); |
| 4041 |
static const char dateFormat[] = "ddd, dd MMM yyyy hh:mm:ss 'GMT'"; |
| 4042 |
|
| 4043 |
QNetworkCacheMetaData::RawHeaderList rawHeaders; |
| 4044 |
MyMemoryCache::CachedContent content; |
| 4045 |
content.second = "Not-reloaded"; |
| 4046 |
content.first.setLastModified(past); |
| 4047 |
|
| 4048 |
// "no-cache" |
| 4049 |
rawHeaders.clear(); |
| 4050 |
rawHeaders << QNetworkCacheMetaData::RawHeader("Date", QLocale::c().toString(past, dateFormat).toLatin1()) |
| 4051 |
<< QNetworkCacheMetaData::RawHeader("Cache-control", "no-cache"); |
| 4052 |
content.first.setRawHeaders(rawHeaders); |
| 4053 |
content.first.setLastModified(past); |
| 4054 |
content.first.setExpirationDate(future); |
| 4055 |
|
| 4056 |
// "no-cache" does not mean "no cache", just that we must consult remote first |
| 4057 |
QTest::newRow("no-cache,200,always-network") |
| 4058 |
<< reply200 << "Reloaded" << content << int(QNetworkRequest::AlwaysNetwork) << QStringList() << false << true; |
| 4059 |
QTest::newRow("no-cache,200,prefer-network") |
| 4060 |
<< reply200 << "Reloaded" << content << int(QNetworkRequest::PreferNetwork) << QStringList() << false << true; |
| 4061 |
QTest::newRow("no-cache,200,prefer-cache") |
| 4062 |
<< reply200 << "Reloaded" << content << int(QNetworkRequest::PreferCache) << QStringList() << false << true; |
| 4063 |
// We're not allowed by the spec to deliver cached data without checking if it is still |
| 4064 |
// up-to-date. |
| 4065 |
QTest::newRow("no-cache,200,always-cache") |
| 4066 |
<< reply200 << QString() << content << int(QNetworkRequest::AlwaysCache) << QStringList() << false << false; |
| 4067 |
|
| 4068 |
QTest::newRow("no-cache,304,prefer-network") |
| 4069 |
<< reply304 << "Not-reloaded" << content << int(QNetworkRequest::PreferNetwork) << QStringList() << true << true; |
| 4070 |
QTest::newRow("no-cache,304,prefer-cache") |
| 4071 |
<< reply304 << "Not-reloaded" << content << int(QNetworkRequest::PreferCache) << QStringList() << true << true; |
| 4072 |
QTest::newRow("no-cache,304,always-cache") |
| 4073 |
<< reply304 << QString() << content << int(QNetworkRequest::AlwaysCache) << QStringList() << false << false; |
| 4074 |
|
| 4075 |
// |
| 4076 |
// Set to expired |
| 4077 |
// |
| 4078 |
rawHeaders.clear(); |
| 4079 |
rawHeaders << QNetworkCacheMetaData::RawHeader("Date", QLocale::c().toString(past, dateFormat).toLatin1()) |
| 4080 |
<< QNetworkCacheMetaData::RawHeader("Cache-control", "max-age=0"); // isn't used in cache loading |
| 4081 |
content.first.setRawHeaders(rawHeaders); |
| 4082 |
content.first.setLastModified(past); |
| 4083 |
content.first.setExpirationDate(past); |
| 4084 |
|
| 4085 |
QTest::newRow("expired,200,prefer-network") |
| 4086 |
<< reply200 << "Reloaded" << content << int(QNetworkRequest::PreferNetwork) << QStringList() << false << true; |
| 4087 |
QTest::newRow("expired,200,prefer-cache") |
| 4088 |
<< reply200 << "Reloaded" << content << int(QNetworkRequest::PreferCache) << QStringList() << false << true; |
| 4089 |
|
| 4090 |
QTest::newRow("expired,304,prefer-network") |
| 4091 |
<< reply304 << "Not-reloaded" << content << int(QNetworkRequest::PreferNetwork) << QStringList() << true << true; |
| 4092 |
QTest::newRow("expired,304,prefer-cache") |
| 4093 |
<< reply304 << "Not-reloaded" << content << int(QNetworkRequest::PreferCache) << QStringList() << true << true; |
| 4094 |
|
| 4095 |
// |
| 4096 |
// Set to not-expired |
| 4097 |
// |
| 4098 |
rawHeaders.clear(); |
| 4099 |
rawHeaders << QNetworkCacheMetaData::RawHeader("Date", QLocale::c().toString(past, dateFormat).toLatin1()) |
| 4100 |
<< QNetworkCacheMetaData::RawHeader("Cache-control", "max-age=7200"); // isn't used in cache loading |
| 4101 |
content.first.setRawHeaders(rawHeaders); |
| 4102 |
content.first.setExpirationDate(future); |
| 4103 |
|
| 4104 |
QTest::newRow("not-expired,200,always-network") |
| 4105 |
<< reply200 << "Reloaded" << content << int(QNetworkRequest::AlwaysNetwork) << QStringList() << false << true; |
| 4106 |
QTest::newRow("not-expired,200,prefer-network") |
| 4107 |
<< reply200 << "Not-reloaded" << content << int(QNetworkRequest::PreferNetwork) << QStringList() << true << false; |
| 4108 |
QTest::newRow("not-expired,200,prefer-cache") |
| 4109 |
<< reply200 << "Not-reloaded" << content << int(QNetworkRequest::PreferCache) << QStringList() << true << false; |
| 4110 |
QTest::newRow("not-expired,200,always-cache") |
| 4111 |
<< reply200 << "Not-reloaded" << content << int(QNetworkRequest::AlwaysCache) << QStringList() << true << false; |
| 4112 |
|
| 4113 |
QTest::newRow("not-expired,304,prefer-network") |
| 4114 |
<< reply304 << "Not-reloaded" << content << int(QNetworkRequest::PreferNetwork) << QStringList() << true << false; |
| 4115 |
QTest::newRow("not-expired,304,prefer-cache") |
| 4116 |
<< reply304 << "Not-reloaded" << content << int(QNetworkRequest::PreferCache) << QStringList() << true << false; |
| 4117 |
QTest::newRow("not-expired,304,always-cache") |
| 4118 |
<< reply304 << "Not-reloaded" << content << int(QNetworkRequest::AlwaysCache) << QStringList() << true << false; |
| 4119 |
|
| 4120 |
// |
| 4121 |
// Set must-revalidate now |
| 4122 |
// |
| 4123 |
rawHeaders.clear(); |
| 4124 |
rawHeaders << QNetworkCacheMetaData::RawHeader("Date", QLocale::c().toString(past, dateFormat).toLatin1()) |
| 4125 |
<< QNetworkCacheMetaData::RawHeader("Cache-control", "max-age=7200, must-revalidate"); // must-revalidate is used |
| 4126 |
content.first.setRawHeaders(rawHeaders); |
| 4127 |
|
| 4128 |
QTest::newRow("must-revalidate,200,always-network") |
| 4129 |
<< reply200 << "Reloaded" << content << int(QNetworkRequest::AlwaysNetwork) << QStringList() << false << true; |
| 4130 |
QTest::newRow("must-revalidate,200,prefer-network") |
| 4131 |
<< reply200 << "Reloaded" << content << int(QNetworkRequest::PreferNetwork) << QStringList() << false << true; |
| 4132 |
QTest::newRow("must-revalidate,200,prefer-cache") |
| 4133 |
<< reply200 << "Reloaded" << content << int(QNetworkRequest::PreferCache) << QStringList() << false << true; |
| 4134 |
QTest::newRow("must-revalidate,200,always-cache") |
| 4135 |
<< reply200 << "" << content << int(QNetworkRequest::AlwaysCache) << QStringList() << false << false; |
| 4136 |
|
| 4137 |
QTest::newRow("must-revalidate,304,prefer-network") |
| 4138 |
<< reply304 << "Not-reloaded" << content << int(QNetworkRequest::PreferNetwork) << QStringList() << true << true; |
| 4139 |
QTest::newRow("must-revalidate,304,prefer-cache") |
| 4140 |
<< reply304 << "Not-reloaded" << content << int(QNetworkRequest::PreferCache) << QStringList() << true << true; |
| 4141 |
QTest::newRow("must-revalidate,304,always-cache") |
| 4142 |
<< reply304 << "" << content << int(QNetworkRequest::AlwaysCache) << QStringList() << false << false; |
| 4143 |
|
| 4144 |
// |
| 4145 |
// Partial content |
| 4146 |
// |
| 4147 |
rawHeaders.clear(); |
| 4148 |
rawHeaders << QNetworkCacheMetaData::RawHeader("Date", QLocale::c().toString(past, dateFormat).toLatin1()) |
| 4149 |
<< QNetworkCacheMetaData::RawHeader("Cache-control", "max-age=7200"); // isn't used in cache loading |
| 4150 |
content.first.setRawHeaders(rawHeaders); |
| 4151 |
content.first.setExpirationDate(future); |
| 4152 |
|
| 4153 |
QByteArray reply206 = |
| 4154 |
"HTTP/1.0 206\r\n" |
| 4155 |
"Connection: keep-alive\r\n" |
| 4156 |
"Content-Type: text/plain\r\n" |
| 4157 |
"Cache-control: no-cache\r\n" |
| 4158 |
"Content-Range: bytes 2-6/8\r\n" |
| 4159 |
"Content-length: 4\r\n" |
| 4160 |
"\r\n" |
| 4161 |
"load"; |
| 4162 |
|
| 4163 |
QTest::newRow("partial,dontuse-cache") |
| 4164 |
<< reply206 << "load" << content << int(QNetworkRequest::PreferCache) << (QStringList() << "Range" << "bytes=2-6") << false << true; |
| 4165 |
} |
| 4166 |
|
| 4167 |
void tst_QNetworkReply::ioGetFromHttpWithCache() |
| 4168 |
{ |
| 4169 |
QFETCH(QByteArray, dataToSend); |
| 4170 |
MiniHttpServer server(dataToSend); |
| 4171 |
server.doClose = false; |
| 4172 |
|
| 4173 |
MyMemoryCache *memoryCache = new MyMemoryCache(&manager); |
| 4174 |
manager.setCache(memoryCache); |
| 4175 |
|
| 4176 |
QFETCH(MyMemoryCache::CachedContent, cachedReply); |
| 4177 |
QUrl url = "http://localhost:" + QString::number(server.serverPort()); |
| 4178 |
cachedReply.first.setUrl(url); |
| 4179 |
if (!cachedReply.second.isNull()) |
| 4180 |
memoryCache->cache.insert(url.toEncoded(), cachedReply); |
| 4181 |
|
| 4182 |
QFETCH(int, cacheMode); |
| 4183 |
QNetworkRequest request(url); |
| 4184 |
request.setAttribute(QNetworkRequest::CacheLoadControlAttribute, cacheMode); |
| 4185 |
request.setAttribute(QNetworkRequest::CacheSaveControlAttribute, false); |
| 4186 |
|
| 4187 |
QFETCH(QStringList, extraHttpHeaders); |
| 4188 |
QVERIFY(extraHttpHeaders.size() % 2 == 0); |
| 4189 |
for (auto it = extraHttpHeaders.cbegin(), end = extraHttpHeaders.cend(); it != end; /*double-stepping*/) { |
| 4190 |
QString header = *it++; |
| 4191 |
QString value = *it++; |
| 4192 |
request.setRawHeader(header.toLatin1(), value.toLatin1()); // To latin1? Deal with it! |
| 4193 |
} |
| 4194 |
|
| 4195 |
QNetworkReplyPtr reply(manager.get(request)); |
| 4196 |
|
| 4197 |
QVERIFY(waitForFinish(reply) != Timeout); |
| 4198 |
|
| 4199 |
QTEST(reply->attribute(QNetworkRequest::SourceIsFromCacheAttribute).toBool(), "loadedFromCache"); |
| 4200 |
QTEST(server.totalConnections > 0, "networkUsed"); |
| 4201 |
QFETCH(QString, body); |
| 4202 |
QCOMPARE(reply->readAll().constData(), qPrintable(body)); |
| 4203 |
} |
| 4204 |
|
| 4205 |
#ifndef QT_NO_NETWORKPROXY |
| 4206 |
void tst_QNetworkReply::ioGetWithManyProxies_data() |
| 4207 |
{ |
| 4208 |
QTest::addColumn<QList<QNetworkProxy> >("proxyList"); |
| 4209 |
QTest::addColumn<QNetworkProxy>("proxyUsed"); |
| 4210 |
QTest::addColumn<QString>("url"); |
| 4211 |
QTest::addColumn<QNetworkReply::NetworkError>("expectedError"); |
| 4212 |
|
| 4213 |
QList<QNetworkProxy> proxyList; |
| 4214 |
|
| 4215 |
// All of the other functions test DefaultProxy |
| 4216 |
// So let's test something else |
| 4217 |
|
| 4218 |
// Simple tests that work: |
| 4219 |
|
| 4220 |
// HTTP request with HTTP caching proxy |
| 4221 |
proxyList << QNetworkProxy(QNetworkProxy::HttpCachingProxy, QtNetworkSettings::httpProxyServerName(), 3129); |
| 4222 |
QTest::newRow("http-on-http") |
| 4223 |
<< proxyList << proxyList.at(0) |
| 4224 |
<< "http://" + QtNetworkSettings::httpServerName() + "/qtest/rfc3252.txt" |
| 4225 |
<< QNetworkReply::NoError; |
| 4226 |
|
| 4227 |
// HTTP request with HTTP transparent proxy |
| 4228 |
proxyList.clear(); |
| 4229 |
proxyList << QNetworkProxy(QNetworkProxy::HttpProxy, QtNetworkSettings::httpProxyServerName(), 3129); |
| 4230 |
QTest::newRow("http-on-http2") |
| 4231 |
<< proxyList << proxyList.at(0) |
| 4232 |
<< "http://" + QtNetworkSettings::httpServerName() + "/qtest/rfc3252.txt" |
| 4233 |
<< QNetworkReply::NoError; |
| 4234 |
|
| 4235 |
// HTTP request with SOCKS transparent proxy |
| 4236 |
proxyList.clear(); |
| 4237 |
proxyList << QNetworkProxy(QNetworkProxy::Socks5Proxy, QtNetworkSettings::socksProxyServerName(), 1081); |
| 4238 |
QTest::newRow("http-on-socks") |
| 4239 |
<< proxyList << proxyList.at(0) |
| 4240 |
<< "http://" + QtNetworkSettings::httpServerName() + "/qtest/rfc3252.txt" |
| 4241 |
<< QNetworkReply::NoError; |
| 4242 |
|
| 4243 |
// FTP request with FTP caching proxy |
| 4244 |
proxyList.clear(); |
| 4245 |
proxyList << QNetworkProxy(QNetworkProxy::FtpCachingProxy, QtNetworkSettings::ftpProxyServerName(), 2121); |
| 4246 |
QTest::newRow("ftp-on-ftp") |
| 4247 |
<< proxyList << proxyList.at(0) |
| 4248 |
<< "ftp://" + QtNetworkSettings::ftpServerName() + "/qtest/rfc3252.txt" |
| 4249 |
<< QNetworkReply::NoError; |
| 4250 |
|
| 4251 |
// The following test doesn't work because QFtp is too limited |
| 4252 |
// It can only talk to its own kind of proxies |
| 4253 |
|
| 4254 |
// FTP request with SOCKSv5 transparent proxy |
| 4255 |
proxyList.clear(); |
| 4256 |
proxyList << QNetworkProxy(QNetworkProxy::Socks5Proxy, QtNetworkSettings::socksProxyServerName(), 1081); |
| 4257 |
QTest::newRow("ftp-on-socks") |
| 4258 |
<< proxyList << proxyList.at(0) |
| 4259 |
<< "ftp://" + QtNetworkSettings::ftpServerName() + "/qtest/rfc3252.txt" |
| 4260 |
<< QNetworkReply::NoError; |
| 4261 |
|
| 4262 |
#ifndef QT_NO_SSL |
| 4263 |
// HTTPS with HTTP transparent proxy |
| 4264 |
proxyList.clear(); |
| 4265 |
proxyList << QNetworkProxy(QNetworkProxy::HttpProxy, QtNetworkSettings::httpProxyServerName(), 3129); |
| 4266 |
QTest::newRow("https-on-http") |
| 4267 |
<< proxyList << proxyList.at(0) |
| 4268 |
<< "https://" + QtNetworkSettings::httpServerName() + "/qtest/rfc3252.txt" |
| 4269 |
<< QNetworkReply::NoError; |
| 4270 |
|
| 4271 |
// HTTPS request with SOCKS transparent proxy |
| 4272 |
proxyList.clear(); |
| 4273 |
proxyList << QNetworkProxy(QNetworkProxy::Socks5Proxy, QtNetworkSettings::socksProxyServerName(), 1081); |
| 4274 |
QTest::newRow("https-on-socks") |
| 4275 |
<< proxyList << proxyList.at(0) |
| 4276 |
<< "https://" + QtNetworkSettings::httpServerName() + "/qtest/rfc3252.txt" |
| 4277 |
<< QNetworkReply::NoError; |
| 4278 |
#endif |
| 4279 |
|
| 4280 |
// Tests that fail: |
| 4281 |
|
| 4282 |
// HTTP request with FTP caching proxy |
| 4283 |
proxyList.clear(); |
| 4284 |
proxyList << QNetworkProxy(QNetworkProxy::FtpCachingProxy, QtNetworkSettings::ftpProxyServerName(), 2121); |
| 4285 |
QTest::newRow("http-on-ftp") |
| 4286 |
<< proxyList << QNetworkProxy() |
| 4287 |
<< "http://" + QtNetworkSettings::httpServerName() + "/qtest/rfc3252.txt" |
| 4288 |
<< QNetworkReply::ProxyNotFoundError; |
| 4289 |
|
| 4290 |
// FTP request with HTTP caching proxy |
| 4291 |
proxyList.clear(); |
| 4292 |
proxyList << QNetworkProxy(QNetworkProxy::HttpCachingProxy, QtNetworkSettings::httpProxyServerName(), 3129); |
| 4293 |
QTest::newRow("ftp-on-http") |
| 4294 |
<< proxyList << QNetworkProxy() |
| 4295 |
<< "ftp://" + QtNetworkSettings::ftpServerName() + "/qtest/rfc3252.txt" |
| 4296 |
<< QNetworkReply::ProxyNotFoundError; |
| 4297 |
|
| 4298 |
// FTP request with HTTP caching proxies |
| 4299 |
proxyList.clear(); |
| 4300 |
proxyList << QNetworkProxy(QNetworkProxy::HttpCachingProxy, QtNetworkSettings::httpProxyServerName(), 3129) |
| 4301 |
<< QNetworkProxy(QNetworkProxy::HttpCachingProxy, QtNetworkSettings::httpProxyServerName(), 3130); |
| 4302 |
QTest::newRow("ftp-on-multiple-http") |
| 4303 |
<< proxyList << QNetworkProxy() |
| 4304 |
<< "ftp://" + QtNetworkSettings::ftpServerName() + "/qtest/rfc3252.txt" |
| 4305 |
<< QNetworkReply::ProxyNotFoundError; |
| 4306 |
|
| 4307 |
#ifndef QT_NO_SSL |
| 4308 |
// HTTPS with HTTP caching proxy |
| 4309 |
proxyList.clear(); |
| 4310 |
proxyList << QNetworkProxy(QNetworkProxy::HttpCachingProxy, QtNetworkSettings::httpProxyServerName(), 3129); |
| 4311 |
QTest::newRow("https-on-httptransparent") |
| 4312 |
<< proxyList << QNetworkProxy() |
| 4313 |
<< "https://" + QtNetworkSettings::httpServerName() + "/qtest/rfc3252.txt" |
| 4314 |
<< QNetworkReply::ProxyNotFoundError; |
| 4315 |
|
| 4316 |
// HTTPS with FTP caching proxy |
| 4317 |
proxyList.clear(); |
| 4318 |
proxyList << QNetworkProxy(QNetworkProxy::FtpCachingProxy, QtNetworkSettings::ftpProxyServerName(), 2121); |
| 4319 |
QTest::newRow("https-on-ftp") |
| 4320 |
<< proxyList << QNetworkProxy() |
| 4321 |
<< "https://" + QtNetworkSettings::httpServerName() + "/qtest/rfc3252.txt" |
| 4322 |
<< QNetworkReply::ProxyNotFoundError; |
| 4323 |
#endif |
| 4324 |
|
| 4325 |
// Complex requests: |
| 4326 |
|
| 4327 |
// HTTP request with more than one HTTP proxy |
| 4328 |
proxyList.clear(); |
| 4329 |
proxyList << QNetworkProxy(QNetworkProxy::HttpCachingProxy, QtNetworkSettings::httpProxyServerName(), 3129) |
| 4330 |
<< QNetworkProxy(QNetworkProxy::HttpCachingProxy, QtNetworkSettings::httpProxyServerName(), 3130); |
| 4331 |
QTest::newRow("http-on-multiple-http") |
| 4332 |
<< proxyList << proxyList.at(0) |
| 4333 |
<< "http://" + QtNetworkSettings::httpServerName() + "/qtest/rfc3252.txt" |
| 4334 |
<< QNetworkReply::NoError; |
| 4335 |
|
| 4336 |
// HTTP request with HTTP + SOCKS |
| 4337 |
proxyList.clear(); |
| 4338 |
proxyList << QNetworkProxy(QNetworkProxy::HttpCachingProxy, QtNetworkSettings::httpProxyServerName(), 3129) |
| 4339 |
<< QNetworkProxy(QNetworkProxy::Socks5Proxy, QtNetworkSettings::socksProxyServerName(), 1081); |
| 4340 |
QTest::newRow("http-on-http+socks") |
| 4341 |
<< proxyList << proxyList.at(0) |
| 4342 |
<< "http://" + QtNetworkSettings::httpServerName() + "/qtest/rfc3252.txt" |
| 4343 |
<< QNetworkReply::NoError; |
| 4344 |
|
| 4345 |
// HTTP request with FTP + HTTP + SOCKS |
| 4346 |
proxyList.clear(); |
| 4347 |
proxyList << QNetworkProxy(QNetworkProxy::FtpCachingProxy, QtNetworkSettings::ftpProxyServerName(), 2121) |
| 4348 |
<< QNetworkProxy(QNetworkProxy::HttpCachingProxy, QtNetworkSettings::httpProxyServerName(), 3129) |
| 4349 |
<< QNetworkProxy(QNetworkProxy::Socks5Proxy, QtNetworkSettings::socksProxyServerName(), 1081); |
| 4350 |
QTest::newRow("http-on-ftp+http+socks") |
| 4351 |
<< proxyList << proxyList.at(1) // second proxy should be used |
| 4352 |
<< "http://" + QtNetworkSettings::httpServerName() + "/qtest/rfc3252.txt" |
| 4353 |
<< QNetworkReply::NoError; |
| 4354 |
|
| 4355 |
// HTTP request with NoProxy + HTTP |
| 4356 |
proxyList.clear(); |
| 4357 |
proxyList << QNetworkProxy(QNetworkProxy::NoProxy) |
| 4358 |
<< QNetworkProxy(QNetworkProxy::HttpCachingProxy, QtNetworkSettings::httpProxyServerName(), 3129); |
| 4359 |
QTest::newRow("http-on-noproxy+http") |
| 4360 |
<< proxyList << proxyList.at(0) |
| 4361 |
<< "http://" + QtNetworkSettings::httpServerName() + "/qtest/rfc3252.txt" |
| 4362 |
<< QNetworkReply::NoError; |
| 4363 |
|
| 4364 |
// HTTP request with FTP + NoProxy |
| 4365 |
proxyList.clear(); |
| 4366 |
proxyList << QNetworkProxy(QNetworkProxy::FtpCachingProxy, QtNetworkSettings::ftpProxyServerName(), 2121) |
| 4367 |
<< QNetworkProxy(QNetworkProxy::NoProxy); |
| 4368 |
QTest::newRow("http-on-ftp+noproxy") |
| 4369 |
<< proxyList << proxyList.at(1) // second proxy should be used |
| 4370 |
<< "http://" + QtNetworkSettings::httpServerName() + "/qtest/rfc3252.txt" |
| 4371 |
<< QNetworkReply::NoError; |
| 4372 |
|
| 4373 |
// FTP request with HTTP Caching + FTP |
| 4374 |
proxyList.clear(); |
| 4375 |
proxyList << QNetworkProxy(QNetworkProxy::HttpCachingProxy, QtNetworkSettings::httpProxyServerName(), 3129) |
| 4376 |
<< QNetworkProxy(QNetworkProxy::FtpCachingProxy, QtNetworkSettings::ftpProxyServerName(), 2121); |
| 4377 |
QTest::newRow("ftp-on-http+ftp") |
| 4378 |
<< proxyList << proxyList.at(1) // second proxy should be used |
| 4379 |
<< "ftp://" + QtNetworkSettings::ftpServerName() + "/qtest/rfc3252.txt" |
| 4380 |
<< QNetworkReply::NoError; |
| 4381 |
|
| 4382 |
#ifndef QT_NO_SSL |
| 4383 |
// HTTPS request with HTTP Caching + HTTP transparent |
| 4384 |
proxyList.clear(); |
| 4385 |
proxyList << QNetworkProxy(QNetworkProxy::HttpCachingProxy, QtNetworkSettings::httpProxyServerName(), 3129) |
| 4386 |
<< QNetworkProxy(QNetworkProxy::HttpProxy, QtNetworkSettings::httpProxyServerName(), 3129); |
| 4387 |
QTest::newRow("https-on-httpcaching+http") |
| 4388 |
<< proxyList << proxyList.at(1) // second proxy should be used |
| 4389 |
<< "https://" + QtNetworkSettings::httpServerName() + "/qtest/rfc3252.txt" |
| 4390 |
<< QNetworkReply::NoError; |
| 4391 |
|
| 4392 |
// HTTPS request with FTP + HTTP C + HTTP T |
| 4393 |
proxyList.clear(); |
| 4394 |
proxyList << QNetworkProxy(QNetworkProxy::FtpCachingProxy, QtNetworkSettings::ftpProxyServerName(), 2121) |
| 4395 |
<< QNetworkProxy(QNetworkProxy::HttpCachingProxy, QtNetworkSettings::httpProxyServerName(), 3129) |
| 4396 |
<< QNetworkProxy(QNetworkProxy::HttpProxy, QtNetworkSettings::httpProxyServerName(), 3129); |
| 4397 |
QTest::newRow("https-on-ftp+httpcaching+http") |
| 4398 |
<< proxyList << proxyList.at(2) // skip the first two |
| 4399 |
<< "https://" + QtNetworkSettings::httpServerName() + "/qtest/rfc3252.txt" |
| 4400 |
<< QNetworkReply::NoError; |
| 4401 |
#endif |
| 4402 |
} |
| 4403 |
|
| 4404 |
void tst_QNetworkReply::ioGetWithManyProxies() |
| 4405 |
{ |
| 4406 |
// Test proxy factories |
| 4407 |
|
| 4408 |
QFile reference(testDataDir + "/rfc3252.txt"); |
| 4409 |
QVERIFY(reference.open(QIODevice::ReadOnly)); |
| 4410 |
|
| 4411 |
// set the proxy factory: |
| 4412 |
QFETCH(QList<QNetworkProxy>, proxyList); |
| 4413 |
MyProxyFactory *proxyFactory = new MyProxyFactory; |
| 4414 |
proxyFactory->toReturn = proxyList; |
| 4415 |
manager.setProxyFactory(proxyFactory); |
| 4416 |
|
| 4417 |
QFETCH(QString, url); |
| 4418 |
QUrl theUrl(url); |
| 4419 |
QNetworkRequest request(theUrl); |
| 4420 |
QNetworkReplyPtr reply(manager.get(request)); |
| 4421 |
DataReader reader(reply); |
| 4422 |
|
| 4423 |
QSignalSpy authspy(&manager, SIGNAL(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*))); |
| 4424 |
connect(&manager, SIGNAL(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)), |
| 4425 |
SLOT(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*))); |
| 4426 |
#ifndef QT_NO_SSL |
| 4427 |
connect(&manager, SIGNAL(sslErrors(QNetworkReply*,QList<QSslError>)), |
| 4428 |
SLOT(sslErrors(QNetworkReply*,QList<QSslError>))); |
| 4429 |
#endif |
| 4430 |
|
| 4431 |
QVERIFY(waitForFinish(reply) != Timeout); |
| 4432 |
|
| 4433 |
manager.disconnect(SIGNAL(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)), |
| 4434 |
this, SLOT(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*))); |
| 4435 |
#ifndef QT_NO_SSL |
| 4436 |
manager.disconnect(SIGNAL(sslErrors(QNetworkReply*,QList<QSslError>)), |
| 4437 |
this, SLOT(sslErrors(QNetworkReply*,QList<QSslError>))); |
| 4438 |
#endif |
| 4439 |
|
| 4440 |
QFETCH(QNetworkReply::NetworkError, expectedError); |
| 4441 |
QEXPECT_FAIL("ftp-on-socks", "QFtp is too limited and won't accept non-FTP proxies", Abort); |
| 4442 |
QCOMPARE(reply->error(), expectedError); |
| 4443 |
|
| 4444 |
// Verify that the factory was called properly |
| 4445 |
QCOMPARE(proxyFactory->callCount, 1); |
| 4446 |
QCOMPARE(proxyFactory->lastQuery, QNetworkProxyQuery(theUrl)); |
| 4447 |
|
| 4448 |
if (expectedError == QNetworkReply::NoError) { |
| 4449 |
// request succeeded |
| 4450 |
QCOMPARE(reader.data, reference.readAll()); |
| 4451 |
|
| 4452 |
// now verify that the proxies worked: |
| 4453 |
QFETCH(QNetworkProxy, proxyUsed); |
| 4454 |
if (proxyUsed.type() == QNetworkProxy::NoProxy) { |
| 4455 |
QCOMPARE(authspy.count(), 0); |
| 4456 |
} else { |
| 4457 |
if (QByteArray(QTest::currentDataTag()).startsWith("ftp-")) |
| 4458 |
return; // No authentication with current FTP or with FTP proxies |
| 4459 |
QCOMPARE(authspy.count(), 1); |
| 4460 |
QCOMPARE(qvariant_cast<QNetworkProxy>(authspy.at(0).at(0)), proxyUsed); |
| 4461 |
} |
| 4462 |
} else { |
| 4463 |
// request failed |
| 4464 |
QCOMPARE(authspy.count(), 0); |
| 4465 |
} |
| 4466 |
} |
| 4467 |
#endif // !QT_NO_NETWORKPROXY |
| 4468 |
|
| 4469 |
void tst_QNetworkReply::ioPutToFileFromFile_data() |
| 4470 |
{ |
| 4471 |
QTest::addColumn<QString>("fileName"); |
| 4472 |
|
| 4473 |
QTest::newRow("empty") << (testDataDir + "/empty"); |
| 4474 |
QTest::newRow("real-file") << (testDataDir + "/rfc3252.txt"); |
| 4475 |
QTest::newRow("resource") << ":/resource"; |
| 4476 |
QTest::newRow("search-path") << "testdata:/rfc3252.txt"; |
| 4477 |
} |
| 4478 |
|
| 4479 |
void tst_QNetworkReply::ioPutToFileFromFile() |
| 4480 |
{ |
| 4481 |
QFETCH(QString, fileName); |
| 4482 |
QFile sourceFile(fileName); |
| 4483 |
QFile targetFile(testFileName); |
| 4484 |
|
| 4485 |
QVERIFY(sourceFile.open(QIODevice::ReadOnly)); |
| 4486 |
|
| 4487 |
QUrl url = QUrl::fromLocalFile(targetFile.fileName()); |
| 4488 |
QNetworkRequest request(url); |
| 4489 |
QNetworkReplyPtr reply(manager.put(request, &sourceFile)); |
| 4490 |
|
| 4491 |
QVERIFY2(waitForFinish(reply) == Success, msgWaitForFinished(reply)); |
| 4492 |
|
| 4493 |
QCOMPARE(reply->url(), url); |
| 4494 |
QCOMPARE(reply->error(), QNetworkReply::NoError); |
| 4495 |
QCOMPARE(reply->header(QNetworkRequest::ContentLengthHeader).toLongLong(), Q_INT64_C(0)); |
| 4496 |
QVERIFY(reply->readAll().isEmpty()); |
| 4497 |
|
| 4498 |
QVERIFY(sourceFile.atEnd()); |
| 4499 |
sourceFile.seek(0); // reset it to the beginning |
| 4500 |
|
| 4501 |
QVERIFY(targetFile.open(QIODevice::ReadOnly)); |
| 4502 |
QCOMPARE(targetFile.size(), sourceFile.size()); |
| 4503 |
QCOMPARE(targetFile.readAll(), sourceFile.readAll()); |
| 4504 |
} |
| 4505 |
|
| 4506 |
void tst_QNetworkReply::ioPutToFileFromSocket_data() |
| 4507 |
{ |
| 4508 |
putToFile_data(); |
| 4509 |
} |
| 4510 |
|
| 4511 |
void tst_QNetworkReply::ioPutToFileFromSocket() |
| 4512 |
{ |
| 4513 |
QFile file(testFileName); |
| 4514 |
|
| 4515 |
QUrl url = QUrl::fromLocalFile(file.fileName()); |
| 4516 |
QNetworkRequest request(url); |
| 4517 |
|
| 4518 |
QFETCH(QByteArray, data); |
| 4519 |
SocketPair socketpair; |
| 4520 |
QTRY_VERIFY(socketpair.create()); //QTRY_VERIFY as a workaround for QTBUG-24451 |
| 4521 |
|
| 4522 |
socketpair.endPoints[0]->write(data); |
| 4523 |
QNetworkReplyPtr reply(manager.put(QNetworkRequest(url), socketpair.endPoints[1])); |
| 4524 |
socketpair.endPoints[0]->close(); |
| 4525 |
|
| 4526 |
QVERIFY2(waitForFinish(reply) == Success, msgWaitForFinished(reply)); |
| 4527 |
QCOMPARE(reply->error(), QNetworkReply::NoError); |
| 4528 |
|
| 4529 |
QCOMPARE(reply->url(), url); |
| 4530 |
QCOMPARE(reply->error(), QNetworkReply::NoError); |
| 4531 |
QCOMPARE(reply->header(QNetworkRequest::ContentLengthHeader).toLongLong(), Q_INT64_C(0)); |
| 4532 |
QVERIFY(reply->readAll().isEmpty()); |
| 4533 |
|
| 4534 |
QVERIFY(file.open(QIODevice::ReadOnly)); |
| 4535 |
QCOMPARE(file.size(), qint64(data.size())); |
| 4536 |
QByteArray contents = file.readAll(); |
| 4537 |
QCOMPARE(contents, data); |
| 4538 |
} |
| 4539 |
|
| 4540 |
void tst_QNetworkReply::ioPutToFileFromLocalSocket_data() |
| 4541 |
{ |
| 4542 |
putToFile_data(); |
| 4543 |
} |
| 4544 |
|
| 4545 |
void tst_QNetworkReply::ioPutToFileFromLocalSocket() |
| 4546 |
{ |
| 4547 |
QString socketname = "networkreplytest"; |
| 4548 |
QLocalServer server; |
| 4549 |
if (!server.listen(socketname)) { |
| 4550 |
QLocalServer::removeServer(socketname); |
| 4551 |
QVERIFY(server.listen(socketname)); |
| 4552 |
} |
| 4553 |
QLocalSocket active; |
| 4554 |
active.connectToServer(socketname); |
| 4555 |
QVERIFY2(server.waitForNewConnection(10), server.errorString().toLatin1().constData()); |
| 4556 |
QVERIFY2(active.waitForConnected(10), active.errorString().toLatin1().constData()); |
| 4557 |
QVERIFY2(server.hasPendingConnections(), server.errorString().toLatin1().constData()); |
| 4558 |
QLocalSocket *passive = server.nextPendingConnection(); |
| 4559 |
|
| 4560 |
QFile file(testFileName); |
| 4561 |
QUrl url = QUrl::fromLocalFile(file.fileName()); |
| 4562 |
QNetworkRequest request(url); |
| 4563 |
|
| 4564 |
QFETCH(QByteArray, data); |
| 4565 |
active.write(data); |
| 4566 |
active.close(); |
| 4567 |
QNetworkReplyPtr reply(manager.put(QNetworkRequest(url), passive)); |
| 4568 |
passive->setParent(reply.data()); |
| 4569 |
|
| 4570 |
#ifdef Q_OS_WIN |
| 4571 |
if (!data.isEmpty()) |
| 4572 |
QEXPECT_FAIL("", "QTBUG-18385", Abort); |
| 4573 |
#endif |
| 4574 |
QVERIFY2(waitForFinish(reply) == Success, msgWaitForFinished(reply)); |
| 4575 |
QCOMPARE(reply->error(), QNetworkReply::NoError); |
| 4576 |
|
| 4577 |
QCOMPARE(reply->url(), url); |
| 4578 |
QCOMPARE(reply->error(), QNetworkReply::NoError); |
| 4579 |
QCOMPARE(reply->header(QNetworkRequest::ContentLengthHeader).toLongLong(), Q_INT64_C(0)); |
| 4580 |
QVERIFY(reply->readAll().isEmpty()); |
| 4581 |
|
| 4582 |
QVERIFY(file.open(QIODevice::ReadOnly)); |
| 4583 |
QCOMPARE(file.size(), qint64(data.size())); |
| 4584 |
QByteArray contents = file.readAll(); |
| 4585 |
QCOMPARE(contents, data); |
| 4586 |
} |
| 4587 |
|
| 4588 |
// Currently no stdin/out supported for Windows CE. |
| 4589 |
void tst_QNetworkReply::ioPutToFileFromProcess_data() |
| 4590 |
{ |
| 4591 |
#if QT_CONFIG(process) |
| 4592 |
putToFile_data(); |
| 4593 |
#endif |
| 4594 |
} |
| 4595 |
|
| 4596 |
void tst_QNetworkReply::ioPutToFileFromProcess() |
| 4597 |
{ |
| 4598 |
#if !QT_CONFIG(process) |
| 4599 |
QSKIP("No qprocess support", SkipAll); |
| 4600 |
#else |
| 4601 |
|
| 4602 |
#ifdef Q_OS_WIN |
| 4603 |
if (qstrcmp(QTest::currentDataTag(), "small") == 0) |
| 4604 |
QSKIP("When passing a CR-LF-LF sequence through Windows stdio, it gets converted, " |
| 4605 |
"so this test fails. Disabled on Windows"); |
| 4606 |
#endif |
| 4607 |
|
| 4608 |
QFile file(testFileName); |
| 4609 |
|
| 4610 |
QUrl url = QUrl::fromLocalFile(file.fileName()); |
| 4611 |
QNetworkRequest request(url); |
| 4612 |
|
| 4613 |
QFETCH(QByteArray, data); |
| 4614 |
QProcess process; |
| 4615 |
QString echoExe = echoProcessDir + "/echo"; |
| 4616 |
process.start(echoExe, QStringList("all")); |
| 4617 |
QVERIFY2(process.waitForStarted(), qPrintable( |
| 4618 |
QString::fromLatin1("Could not start %1: %2").arg(echoExe, process.errorString()))); |
| 4619 |
process.write(data); |
| 4620 |
process.closeWriteChannel(); |
| 4621 |
|
| 4622 |
QNetworkReplyPtr reply(manager.put(QNetworkRequest(url), &process)); |
| 4623 |
|
| 4624 |
QVERIFY2(waitForFinish(reply) == Success, msgWaitForFinished(reply)); |
| 4625 |
|
| 4626 |
QCOMPARE(reply->url(), url); |
| 4627 |
QCOMPARE(reply->error(), QNetworkReply::NoError); |
| 4628 |
QCOMPARE(reply->header(QNetworkRequest::ContentLengthHeader).toLongLong(), Q_INT64_C(0)); |
| 4629 |
QVERIFY(reply->readAll().isEmpty()); |
| 4630 |
|
| 4631 |
QVERIFY(file.open(QIODevice::ReadOnly)); |
| 4632 |
QCOMPARE(file.size(), qint64(data.size())); |
| 4633 |
QByteArray contents = file.readAll(); |
| 4634 |
QCOMPARE(contents, data); |
| 4635 |
|
| 4636 |
#endif // QT_CONFIG(process) |
| 4637 |
} |
| 4638 |
|
| 4639 |
void tst_QNetworkReply::ioPutToFtpFromFile_data() |
| 4640 |
{ |
| 4641 |
ioPutToFileFromFile_data(); |
| 4642 |
} |
| 4643 |
|
| 4644 |
void tst_QNetworkReply::ioPutToFtpFromFile() |
| 4645 |
{ |
| 4646 |
QFETCH(QString, fileName); |
| 4647 |
QFile sourceFile(fileName); |
| 4648 |
QVERIFY(sourceFile.open(QIODevice::ReadOnly)); |
| 4649 |
|
| 4650 |
QUrl url("ftp://" + QtNetworkSettings::ftpServerName()); |
| 4651 |
url.setPath(QString("/qtest/upload/qnetworkaccess-ioPutToFtpFromFile-%1-%2") |
| 4652 |
.arg(QTest::currentDataTag()) |
| 4653 |
.arg(uniqueExtension)); |
| 4654 |
|
| 4655 |
QNetworkRequest request(url); |
| 4656 |
QNetworkReplyPtr reply(manager.put(request, &sourceFile)); |
| 4657 |
|
| 4658 |
QVERIFY2(waitForFinish(reply) == Success, msgWaitForFinished(reply)); |
| 4659 |
|
| 4660 |
QCOMPARE(reply->url(), url); |
| 4661 |
QCOMPARE(reply->error(), QNetworkReply::NoError); |
| 4662 |
QCOMPARE(reply->header(QNetworkRequest::ContentLengthHeader).toLongLong(), Q_INT64_C(0)); |
| 4663 |
QVERIFY(reply->readAll().isEmpty()); |
| 4664 |
|
| 4665 |
QVERIFY(sourceFile.atEnd()); |
| 4666 |
sourceFile.seek(0); // reset it to the beginning |
| 4667 |
|
| 4668 |
// download the file again from FTP to make sure it was uploaded |
| 4669 |
// correctly |
| 4670 |
QNetworkAccessManager qnam; |
| 4671 |
QNetworkRequest req(url); |
| 4672 |
QNetworkReply *r = qnam.get(req); |
| 4673 |
|
| 4674 |
QObject::connect(r, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop())); |
| 4675 |
QTestEventLoop::instance().enterLoop(3); |
| 4676 |
QObject::disconnect(r, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop())); |
| 4677 |
|
| 4678 |
QByteArray uploaded = r->readAll(); |
| 4679 |
QCOMPARE(qint64(uploaded.size()), sourceFile.size()); |
| 4680 |
QCOMPARE(uploaded, sourceFile.readAll()); |
| 4681 |
|
| 4682 |
r->close(); |
| 4683 |
QObject::connect(r, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop())); |
| 4684 |
QTestEventLoop::instance().enterLoop(10); |
| 4685 |
QObject::disconnect(r, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop())); |
| 4686 |
} |
| 4687 |
|
| 4688 |
void tst_QNetworkReply::ioPutToHttpFromFile_data() |
| 4689 |
{ |
| 4690 |
ioPutToFileFromFile_data(); |
| 4691 |
} |
| 4692 |
|
| 4693 |
void tst_QNetworkReply::ioPutToHttpFromFile() |
| 4694 |
{ |
| 4695 |
QFETCH(QString, fileName); |
| 4696 |
QFile sourceFile(fileName); |
| 4697 |
QVERIFY(sourceFile.open(QIODevice::ReadOnly)); |
| 4698 |
|
| 4699 |
QUrl url("http://" + QtNetworkSettings::httpServerName()); |
| 4700 |
url.setPath(QString("/dav/qnetworkaccess-ioPutToHttpFromFile-%1-%2") |
| 4701 |
.arg(QTest::currentDataTag()) |
| 4702 |
.arg(uniqueExtension)); |
| 4703 |
|
| 4704 |
QNetworkRequest request(url); |
| 4705 |
QNetworkReplyPtr reply(manager.put(request, &sourceFile)); |
| 4706 |
|
| 4707 |
QVERIFY2(waitForFinish(reply) == Success, msgWaitForFinished(reply)); |
| 4708 |
|
| 4709 |
QCOMPARE(reply->url(), url); |
| 4710 |
QCOMPARE(reply->error(), QNetworkReply::NoError); |
| 4711 |
|
| 4712 |
// verify that the HTTP status code is 201 Created |
| 4713 |
QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 201); |
| 4714 |
|
| 4715 |
QVERIFY(sourceFile.atEnd()); |
| 4716 |
sourceFile.seek(0); // reset it to the beginning |
| 4717 |
|
| 4718 |
// download the file again from HTTP to make sure it was uploaded |
| 4719 |
// correctly |
| 4720 |
reply.reset(manager.get(request)); |
| 4721 |
|
| 4722 |
QVERIFY2(waitForFinish(reply) == Success, msgWaitForFinished(reply)); |
| 4723 |
|
| 4724 |
QCOMPARE(reply->url(), url); |
| 4725 |
QCOMPARE(reply->error(), QNetworkReply::NoError); |
| 4726 |
QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200); // 200 Ok |
| 4727 |
|
| 4728 |
QCOMPARE(reply->readAll(), sourceFile.readAll()); |
| 4729 |
} |
| 4730 |
|
| 4731 |
void tst_QNetworkReply::ioPostToHttpFromFile_data() |
| 4732 |
{ |
| 4733 |
ioPutToFileFromFile_data(); |
| 4734 |
} |
| 4735 |
|
| 4736 |
void tst_QNetworkReply::ioPostToHttpFromFile() |
| 4737 |
{ |
| 4738 |
QFETCH(QString, fileName); |
| 4739 |
QFile sourceFile(fileName); |
| 4740 |
QVERIFY(sourceFile.open(QIODevice::ReadOnly)); |
| 4741 |
|
| 4742 |
QUrl url("http://" + QtNetworkSettings::httpServerName() + "/qtest/cgi-bin/md5sum.cgi"); |
| 4743 |
QNetworkRequest request(url); |
| 4744 |
request.setRawHeader("Content-Type", "application/octet-stream"); |
| 4745 |
|
| 4746 |
QNetworkReplyPtr reply(manager.post(request, &sourceFile)); |
| 4747 |
|
| 4748 |
QVERIFY2(waitForFinish(reply) == Success, msgWaitForFinished(reply)); |
| 4749 |
|
| 4750 |
QCOMPARE(reply->url(), url); |
| 4751 |
QCOMPARE(reply->error(), QNetworkReply::NoError); |
| 4752 |
|
| 4753 |
// verify that the HTTP status code is 200 Ok |
| 4754 |
QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200); |
| 4755 |
|
| 4756 |
QVERIFY(sourceFile.atEnd()); |
| 4757 |
sourceFile.seek(0); // reset it to the beginning |
| 4758 |
|
| 4759 |
QCOMPARE(reply->readAll().trimmed(), md5sum(sourceFile.readAll()).toHex()); |
| 4760 |
} |
| 4761 |
|
| 4762 |
#ifndef QT_NO_NETWORKPROXY |
| 4763 |
void tst_QNetworkReply::ioPostToHttpFromSocket_data() |
| 4764 |
{ |
| 4765 |
QTest::addColumn<QByteArray>("data"); |
| 4766 |
QTest::addColumn<QByteArray>("md5sum"); |
| 4767 |
QTest::addColumn<QUrl>("url"); |
| 4768 |
QTest::addColumn<QNetworkProxy>("proxy"); |
| 4769 |
QTest::addColumn<int>("authenticationRequiredCount"); |
| 4770 |
QTest::addColumn<int>("proxyAuthenticationRequiredCount"); |
| 4771 |
|
| 4772 |
for (int i = 0; i < proxies.count(); ++i) |
| 4773 |
for (int auth = 0; auth < 2; ++auth) { |
| 4774 |
QUrl url; |
| 4775 |
if (auth) |
| 4776 |
url = "http://" + QtNetworkSettings::httpServerName() + "/qtest/protected/cgi-bin/md5sum.cgi"; |
| 4777 |
else |
| 4778 |
url = "http://" + QtNetworkSettings::httpServerName() + "/qtest/cgi-bin/md5sum.cgi"; |
| 4779 |
|
| 4780 |
QNetworkProxy proxy = proxies.at(i).proxy; |
| 4781 |
QByteArray testsuffix = QByteArray(auth ? "+auth" : "") + proxies.at(i).tag; |
| 4782 |
int proxyauthcount = proxies.at(i).requiresAuthentication; |
| 4783 |
|
| 4784 |
QByteArray data; |
| 4785 |
data = ""; |
| 4786 |
QTest::newRow("empty" + testsuffix) << data << md5sum(data) << url << proxy << auth << proxyauthcount; |
| 4787 |
|
| 4788 |
data = "This is a normal message."; |
| 4789 |
QTest::newRow("generic" + testsuffix) << data << md5sum(data) << url << proxy << auth << proxyauthcount; |
| 4790 |
|
| 4791 |
data = "This is a message to show that Qt rocks!\r\n\n"; |
| 4792 |
QTest::newRow("small" + testsuffix) << data << md5sum(data) << url << proxy << auth << proxyauthcount; |
| 4793 |
|
| 4794 |
data = QByteArray("abcd\0\1\2\abcd",12); |
| 4795 |
QTest::newRow("with-nul" + testsuffix) << data << md5sum(data) << url << proxy << auth << proxyauthcount; |
| 4796 |
|
| 4797 |
data = QByteArray(4097, '\4'); |
| 4798 |
QTest::newRow("4k+1" + testsuffix) << data << md5sum(data) << url << proxy << auth << proxyauthcount; |
| 4799 |
|
| 4800 |
data = QByteArray(128*1024+1, '\177'); |
| 4801 |
QTest::newRow("128k+1" + testsuffix) << data << md5sum(data) << url << proxy << auth << proxyauthcount; |
| 4802 |
} |
| 4803 |
} |
| 4804 |
|
| 4805 |
void tst_QNetworkReply::ioPostToHttpFromSocket() |
| 4806 |
{ |
| 4807 |
if (QTest::currentDataTag() == QByteArray("128k+1+proxyauth") |
| 4808 |
|| QTest::currentDataTag() == QByteArray("128k+1+auth+proxyauth")) |
| 4809 |
QSKIP("Squid cannot handle authentication with POST data >= 64K (QTBUG-33180)"); |
| 4810 |
|
| 4811 |
QFETCH(QByteArray, data); |
| 4812 |
QFETCH(QUrl, url); |
| 4813 |
QFETCH(QNetworkProxy, proxy); |
| 4814 |
|
| 4815 |
SocketPair socketpair; |
| 4816 |
QTRY_VERIFY(socketpair.create()); //QTRY_VERIFY as a workaround for QTBUG-24451 |
| 4817 |
|
| 4818 |
socketpair.endPoints[0]->write(data); |
| 4819 |
|
| 4820 |
QNetworkRequest request(url); |
| 4821 |
request.setRawHeader("Content-Type", "application/octet-stream"); |
| 4822 |
|
| 4823 |
manager.setProxy(proxy); |
| 4824 |
QNetworkReplyPtr reply(manager.post(request, socketpair.endPoints[1])); |
| 4825 |
socketpair.endPoints[0]->close(); |
| 4826 |
|
| 4827 |
connect(&manager, SIGNAL(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)), |
| 4828 |
SLOT(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*))); |
| 4829 |
connect(&manager, SIGNAL(authenticationRequired(QNetworkReply*,QAuthenticator*)), |
| 4830 |
SLOT(authenticationRequired(QNetworkReply*,QAuthenticator*))); |
| 4831 |
|
| 4832 |
QSignalSpy authenticationRequiredSpy(&manager, SIGNAL(authenticationRequired(QNetworkReply*,QAuthenticator*))); |
| 4833 |
QSignalSpy proxyAuthenticationRequiredSpy(&manager, SIGNAL(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*))); |
| 4834 |
|
| 4835 |
QVERIFY2(waitForFinish(reply) == Success, msgWaitForFinished(reply)); |
| 4836 |
|
| 4837 |
disconnect(&manager, SIGNAL(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)), |
| 4838 |
this, SLOT(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*))); |
| 4839 |
disconnect(&manager, SIGNAL(authenticationRequired(QNetworkReply*,QAuthenticator*)), |
| 4840 |
this, SLOT(authenticationRequired(QNetworkReply*,QAuthenticator*))); |
| 4841 |
QCOMPARE(reply->error(), QNetworkReply::NoError); |
| 4842 |
|
| 4843 |
QCOMPARE(reply->url(), url); |
| 4844 |
QCOMPARE(reply->error(), QNetworkReply::NoError); |
| 4845 |
// verify that the HTTP status code is 200 Ok |
| 4846 |
QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200); |
| 4847 |
|
| 4848 |
QCOMPARE(reply->readAll().trimmed(), md5sum(data).toHex()); |
| 4849 |
|
| 4850 |
QTEST(authenticationRequiredSpy.count(), "authenticationRequiredCount"); |
| 4851 |
QTEST(proxyAuthenticationRequiredSpy.count(), "proxyAuthenticationRequiredCount"); |
| 4852 |
} |
| 4853 |
|
| 4854 |
void tst_QNetworkReply::ioPostToHttpFromSocketSynchronous_data() |
| 4855 |
{ |
| 4856 |
QTest::addColumn<QByteArray>("data"); |
| 4857 |
QTest::addColumn<QByteArray>("md5sum"); |
| 4858 |
|
| 4859 |
QByteArray data; |
| 4860 |
data = ""; |
| 4861 |
QTest::newRow("empty") << data << md5sum(data); |
| 4862 |
|
| 4863 |
data = "This is a normal message."; |
| 4864 |
QTest::newRow("generic") << data << md5sum(data); |
| 4865 |
|
| 4866 |
data = "This is a message to show that Qt rocks!\r\n\n"; |
| 4867 |
QTest::newRow("small") << data << md5sum(data); |
| 4868 |
|
| 4869 |
data = QByteArray("abcd\0\1\2\abcd",12); |
| 4870 |
QTest::newRow("with-nul") << data << md5sum(data); |
| 4871 |
|
| 4872 |
data = QByteArray(4097, '\4'); |
| 4873 |
QTest::newRow("4k+1") << data << md5sum(data); |
| 4874 |
|
| 4875 |
data = QByteArray(128*1024+1, '\177'); |
| 4876 |
QTest::newRow("128k+1") << data << md5sum(data); |
| 4877 |
|
| 4878 |
data = QByteArray(2*1024*1024+1, '\177'); |
| 4879 |
QTest::newRow("2MB+1") << data << md5sum(data); |
| 4880 |
} |
| 4881 |
|
| 4882 |
void tst_QNetworkReply::ioPostToHttpFromSocketSynchronous() |
| 4883 |
{ |
| 4884 |
QFETCH(QByteArray, data); |
| 4885 |
|
| 4886 |
SocketPair socketpair; |
| 4887 |
QTRY_VERIFY(socketpair.create()); //QTRY_VERIFY as a workaround for QTBUG-24451 |
| 4888 |
socketpair.endPoints[0]->write(data); |
| 4889 |
socketpair.endPoints[0]->waitForBytesWritten(5000); |
| 4890 |
// ### for 4.8: make the socket pair unbuffered, to not read everything in one go in QNetworkReplyImplPrivate::setup() |
| 4891 |
QTestEventLoop::instance().enterLoop(3); |
| 4892 |
|
| 4893 |
QUrl url("http://" + QtNetworkSettings::httpServerName() + "/qtest/cgi-bin/md5sum.cgi"); |
| 4894 |
QNetworkRequest request(url); |
| 4895 |
request.setRawHeader("Content-Type", "application/octet-stream"); |
| 4896 |
request.setAttribute( |
| 4897 |
QNetworkRequest::SynchronousRequestAttribute, |
| 4898 |
true); |
| 4899 |
|
| 4900 |
QNetworkReplyPtr reply(manager.post(request, socketpair.endPoints[1])); |
| 4901 |
QVERIFY(reply->isFinished()); |
| 4902 |
socketpair.endPoints[0]->close(); |
| 4903 |
|
| 4904 |
QCOMPARE(reply->error(), QNetworkReply::NoError); |
| 4905 |
|
| 4906 |
QCOMPARE(reply->url(), url); |
| 4907 |
QCOMPARE(reply->error(), QNetworkReply::NoError); |
| 4908 |
// verify that the HTTP status code is 200 Ok |
| 4909 |
QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200); |
| 4910 |
|
| 4911 |
QCOMPARE(reply->readAll().trimmed(), md5sum(data).toHex()); |
| 4912 |
} |
| 4913 |
#endif // !QT_NO_NETWORKPROXY |
| 4914 |
|
| 4915 |
// this tests checks if rewinding the POST-data to some place in the middle |
| 4916 |
// worked. |
| 4917 |
void tst_QNetworkReply::ioPostToHttpFromMiddleOfFileToEnd() |
| 4918 |
{ |
| 4919 |
QFile sourceFile(testDataDir + "/rfc3252.txt"); |
| 4920 |
QVERIFY(sourceFile.open(QIODevice::ReadOnly)); |
| 4921 |
// seeking to the middle |
| 4922 |
sourceFile.seek(sourceFile.size() / 2); |
| 4923 |
|
| 4924 |
QUrl url = "http://" + QtNetworkSettings::httpServerName() + "/qtest/protected/cgi-bin/md5sum.cgi"; |
| 4925 |
QNetworkRequest request(url); |
| 4926 |
request.setRawHeader("Content-Type", "application/octet-stream"); |
| 4927 |
QNetworkReplyPtr reply(manager.post(request, &sourceFile)); |
| 4928 |
|
| 4929 |
connect(&manager, SIGNAL(authenticationRequired(QNetworkReply*,QAuthenticator*)), |
| 4930 |
SLOT(authenticationRequired(QNetworkReply*,QAuthenticator*))); |
| 4931 |
|
| 4932 |
QVERIFY2(waitForFinish(reply) == Success, msgWaitForFinished(reply)); |
| 4933 |
|
| 4934 |
disconnect(&manager, SIGNAL(authenticationRequired(QNetworkReply*,QAuthenticator*)), |
| 4935 |
this, SLOT(authenticationRequired(QNetworkReply*,QAuthenticator*))); |
| 4936 |
|
| 4937 |
// compare half data |
| 4938 |
sourceFile.seek(sourceFile.size() / 2); |
| 4939 |
QByteArray data = sourceFile.readAll(); |
| 4940 |
QCOMPARE(reply->readAll().trimmed(), md5sum(data).toHex()); |
| 4941 |
} |
| 4942 |
|
| 4943 |
void tst_QNetworkReply::ioPostToHttpFromMiddleOfFileFiveBytes() |
| 4944 |
{ |
| 4945 |
QFile sourceFile(testDataDir + "/rfc3252.txt"); |
| 4946 |
QVERIFY(sourceFile.open(QIODevice::ReadOnly)); |
| 4947 |
// seeking to the middle |
| 4948 |
sourceFile.seek(sourceFile.size() / 2); |
| 4949 |
|
| 4950 |
QUrl url = "http://" + QtNetworkSettings::httpServerName() + "/qtest/protected/cgi-bin/md5sum.cgi"; |
| 4951 |
QNetworkRequest request(url); |
| 4952 |
request.setRawHeader("Content-Type", "application/octet-stream"); |
| 4953 |
// only send 5 bytes |
| 4954 |
request.setHeader(QNetworkRequest::ContentLengthHeader, 5); |
| 4955 |
QVERIFY(request.header(QNetworkRequest::ContentLengthHeader).isValid()); |
| 4956 |
QNetworkReplyPtr reply(manager.post(request, &sourceFile)); |
| 4957 |
|
| 4958 |
connect(&manager, SIGNAL(authenticationRequired(QNetworkReply*,QAuthenticator*)), |
| 4959 |
SLOT(authenticationRequired(QNetworkReply*,QAuthenticator*))); |
| 4960 |
|
| 4961 |
QVERIFY2(waitForFinish(reply) == Success, msgWaitForFinished(reply)); |
| 4962 |
|
| 4963 |
disconnect(&manager, SIGNAL(authenticationRequired(QNetworkReply*,QAuthenticator*)), |
| 4964 |
this, SLOT(authenticationRequired(QNetworkReply*,QAuthenticator*))); |
| 4965 |
|
| 4966 |
// compare half data |
| 4967 |
sourceFile.seek(sourceFile.size() / 2); |
| 4968 |
QByteArray data = sourceFile.read(5); |
| 4969 |
QCOMPARE(reply->readAll().trimmed(), md5sum(data).toHex()); |
| 4970 |
} |
| 4971 |
|
| 4972 |
void tst_QNetworkReply::ioPostToHttpFromMiddleOfQBufferFiveBytes() |
| 4973 |
{ |
| 4974 |
// test needed since a QBuffer goes with a different codepath than the QFile |
| 4975 |
// tested in ioPostToHttpFromMiddleOfFileFiveBytes |
| 4976 |
QBuffer uploadBuffer; |
| 4977 |
uploadBuffer.open(QIODevice::ReadWrite); |
| 4978 |
uploadBuffer.write("1234567890"); |
| 4979 |
uploadBuffer.seek(5); |
| 4980 |
|
| 4981 |
QUrl url = "http://" + QtNetworkSettings::httpServerName() + "/qtest/protected/cgi-bin/md5sum.cgi"; |
| 4982 |
QNetworkRequest request(url); |
| 4983 |
request.setRawHeader("Content-Type", "application/octet-stream"); |
| 4984 |
QNetworkReplyPtr reply(manager.post(request, &uploadBuffer)); |
| 4985 |
|
| 4986 |
connect(&manager, SIGNAL(authenticationRequired(QNetworkReply*,QAuthenticator*)), |
| 4987 |
SLOT(authenticationRequired(QNetworkReply*,QAuthenticator*))); |
| 4988 |
|
| 4989 |
QVERIFY2(waitForFinish(reply) == Success, msgWaitForFinished(reply)); |
| 4990 |
|
| 4991 |
disconnect(&manager, SIGNAL(authenticationRequired(QNetworkReply*,QAuthenticator*)), |
| 4992 |
this, SLOT(authenticationRequired(QNetworkReply*,QAuthenticator*))); |
| 4993 |
|
| 4994 |
// compare half data |
| 4995 |
uploadBuffer.seek(5); |
| 4996 |
QByteArray data = uploadBuffer.read(5); |
| 4997 |
QCOMPARE(reply->readAll().trimmed(), md5sum(data).toHex()); |
| 4998 |
} |
| 4999 |
|
| 5000 |
|
| 5001 |
void tst_QNetworkReply::ioPostToHttpNoBufferFlag() |
| 5002 |
{ |
| 5003 |
QByteArray data = QByteArray("daaaaaaataaaaaaa"); |
| 5004 |
// create a sequential QIODevice by feeding the data into a local TCP server |
| 5005 |
SocketPair socketpair; |
| 5006 |
QTRY_VERIFY(socketpair.create()); //QTRY_VERIFY as a workaround for QTBUG-24451 |
| 5007 |
socketpair.endPoints[0]->write(data); |
| 5008 |
|
| 5009 |
QUrl url = "http://" + QtNetworkSettings::httpServerName() + "/qtest/protected/cgi-bin/md5sum.cgi"; |
| 5010 |
QNetworkRequest request(url); |
| 5011 |
request.setRawHeader("Content-Type", "application/octet-stream"); |
| 5012 |
// disallow buffering |
| 5013 |
request.setAttribute(QNetworkRequest::DoNotBufferUploadDataAttribute, true); |
| 5014 |
request.setHeader(QNetworkRequest::ContentLengthHeader, data.size()); |
| 5015 |
QNetworkReplyPtr reply(manager.post(request, socketpair.endPoints[1])); |
| 5016 |
socketpair.endPoints[0]->close(); |
| 5017 |
|
| 5018 |
connect(&manager, SIGNAL(authenticationRequired(QNetworkReply*,QAuthenticator*)), |
| 5019 |
SLOT(authenticationRequired(QNetworkReply*,QAuthenticator*))); |
| 5020 |
|
| 5021 |
QCOMPARE(waitForFinish(reply), int(Failure)); |
| 5022 |
|
| 5023 |
disconnect(&manager, SIGNAL(authenticationRequired(QNetworkReply*,QAuthenticator*)), |
| 5024 |
this, SLOT(authenticationRequired(QNetworkReply*,QAuthenticator*))); |
| 5025 |
|
| 5026 |
// verify: error code is QNetworkReply::ContentReSendError |
| 5027 |
QCOMPARE(reply->error(), QNetworkReply::ContentReSendError); |
| 5028 |
} |
| 5029 |
|
| 5030 |
#ifndef QT_NO_SSL |
| 5031 |
class SslServer : public QTcpServer |
| 5032 |
{ |
| 5033 |
Q_OBJECT |
| 5034 |
public: |
| 5035 |
SslServer() : socket(0), m_ssl(true) {} |
| 5036 |
void incomingConnection(qintptr socketDescriptor) |
| 5037 |
{ |
| 5038 |
QSslSocket *serverSocket = new QSslSocket; |
| 5039 |
serverSocket->setParent(this); |
| 5040 |
|
| 5041 |
if (serverSocket->setSocketDescriptor(socketDescriptor)) { |
| 5042 |
connect(serverSocket, SIGNAL(readyRead()), this, SLOT(readyReadSlot())); |
| 5043 |
if (!m_ssl) { |
| 5044 |
emit newPlainConnection(serverSocket); |
| 5045 |
return; |
| 5046 |
} |
| 5047 |
connect(serverSocket, SIGNAL(encrypted()), this, SLOT(encryptedSlot())); |
| 5048 |
connect(serverSocket, SIGNAL(sslErrors(QList<QSslError>)), serverSocket, SLOT(ignoreSslErrors())); |
| 5049 |
setupSslServer(serverSocket); |
| 5050 |
} else { |
| 5051 |
delete serverSocket; |
| 5052 |
} |
| 5053 |
} |
| 5054 |
signals: |
| 5055 |
void newEncryptedConnection(QSslSocket *s); |
| 5056 |
void newPlainConnection(QSslSocket *s); |
| 5057 |
public slots: |
| 5058 |
void encryptedSlot() |
| 5059 |
{ |
| 5060 |
socket = (QSslSocket*) sender(); |
| 5061 |
emit newEncryptedConnection(socket); |
| 5062 |
} |
| 5063 |
void readyReadSlot() |
| 5064 |
{ |
| 5065 |
// for the incoming sockets, not the server socket |
| 5066 |
//qDebug() << static_cast<QSslSocket*>(sender())->bytesAvailable() << static_cast<QSslSocket*>(sender())->encryptedBytesAvailable(); |
| 5067 |
} |
| 5068 |
|
| 5069 |
public: |
| 5070 |
QSslSocket *socket; |
| 5071 |
bool m_ssl; |
| 5072 |
}; |
| 5073 |
|
| 5074 |
// very similar to ioPostToHttpUploadProgress but for SSL |
| 5075 |
void tst_QNetworkReply::ioPostToHttpsUploadProgress() |
| 5076 |
{ |
| 5077 |
//QFile sourceFile(testDataDir + "/bigfile"); |
| 5078 |
//QVERIFY(sourceFile.open(QIODevice::ReadOnly)); |
| 5079 |
qint64 wantedSize = 2*1024*1024; // 2 MB |
| 5080 |
QByteArray sourceFile; |
| 5081 |
// And in the case of SSL, the compression can fool us and let the |
| 5082 |
// server send the data much faster than expected. |
| 5083 |
// So better provide random data that cannot be compressed. |
| 5084 |
for (int i = 0; i < wantedSize; ++i) |
| 5085 |
sourceFile += (char)QRandomGenerator::global()->generate(); |
| 5086 |
|
| 5087 |
// emulate a minimal https server |
| 5088 |
SslServer server; |
| 5089 |
server.listen(QHostAddress(QHostAddress::LocalHost), 0); |
| 5090 |
|
| 5091 |
// create the request |
| 5092 |
QUrl url = QUrl(QLatin1String("https://127.0.0.1:") + QString::number(server.serverPort()) + QLatin1Char('/')); |
| 5093 |
QNetworkRequest request(url); |
| 5094 |
|
| 5095 |
request.setRawHeader("Content-Type", "application/octet-stream"); |
| 5096 |
QNetworkReplyPtr reply(manager.post(request, sourceFile)); |
| 5097 |
|
| 5098 |
QSignalSpy spy(reply.data(), SIGNAL(uploadProgress(qint64,qint64))); |
| 5099 |
connect(&server, SIGNAL(newEncryptedConnection(QSslSocket*)), &QTestEventLoop::instance(), SLOT(exitLoop())); |
| 5100 |
connect(reply, SIGNAL(sslErrors(QList<QSslError>)), reply.data(), SLOT(ignoreSslErrors())); |
| 5101 |
|
| 5102 |
// get the request started and the incoming socket connected |
| 5103 |
QTestEventLoop::instance().enterLoop(10); |
| 5104 |
QVERIFY(!QTestEventLoop::instance().timeout()); |
| 5105 |
QTcpSocket *incomingSocket = server.socket; |
| 5106 |
QVERIFY(incomingSocket); |
| 5107 |
disconnect(&server, SIGNAL(newEncryptedConnection(QSslSocket*)), &QTestEventLoop::instance(), SLOT(exitLoop())); |
| 5108 |
|
| 5109 |
|
| 5110 |
incomingSocket->setReadBufferSize(1024); |
| 5111 |
// some progress should have been made |
| 5112 |
QTRY_VERIFY(!spy.isEmpty()); |
| 5113 |
QList<QVariant> args = spy.last(); |
| 5114 |
QVERIFY(args.at(0).toLongLong() > 0); |
| 5115 |
// but not everything! |
| 5116 |
QVERIFY(args.at(0).toLongLong() != sourceFile.size()); |
| 5117 |
|
| 5118 |
// set the read buffer to unlimited |
| 5119 |
incomingSocket->setReadBufferSize(0); |
| 5120 |
QTestEventLoop::instance().enterLoop(10); |
| 5121 |
// progress should be finished |
| 5122 |
QVERIFY(!spy.isEmpty()); |
| 5123 |
QList<QVariant> args3 = spy.last(); |
| 5124 |
QCOMPARE(args3.at(0).toLongLong(), args3.at(1).toLongLong()); |
| 5125 |
QCOMPARE(args3.at(0).toLongLong(), qint64(sourceFile.size())); |
| 5126 |
|
| 5127 |
// after sending this, the QNAM should emit finished() |
| 5128 |
incomingSocket->write("HTTP/1.0 200 OK\r\n"); |
| 5129 |
incomingSocket->write("Content-Length: 0\r\n"); |
| 5130 |
incomingSocket->write("\r\n"); |
| 5131 |
|
| 5132 |
QVERIFY2(waitForFinish(reply) == Success, msgWaitForFinished(reply)); |
| 5133 |
|
| 5134 |
incomingSocket->close(); |
| 5135 |
server.close(); |
| 5136 |
} |
| 5137 |
#endif |
| 5138 |
|
| 5139 |
void tst_QNetworkReply::ioGetFromBuiltinHttp_data() |
| 5140 |
{ |
| 5141 |
QTest::addColumn<bool>("https"); |
| 5142 |
QTest::addColumn<int>("bufferSize"); |
| 5143 |
QTest::newRow("http+unlimited") << false << 0; |
| 5144 |
QTest::newRow("http+limited") << false << 4096; |
| 5145 |
#ifndef QT_NO_SSL |
| 5146 |
QTest::newRow("https+unlimited") << true << 0; |
| 5147 |
QTest::newRow("https+limited") << true << 4096; |
| 5148 |
#endif |
| 5149 |
} |
| 5150 |
|
| 5151 |
void tst_QNetworkReply::ioGetFromBuiltinHttp() |
| 5152 |
{ |
| 5153 |
QFETCH(bool, https); |
| 5154 |
QFETCH(int, bufferSize); |
| 5155 |
|
| 5156 |
QByteArray testData; |
| 5157 |
// Make the data big enough so that it can fill the kernel buffer |
| 5158 |
// (which seems to hold 202 KB here) |
| 5159 |
const int wantedSize = 1200 * 1000; |
| 5160 |
testData.reserve(wantedSize); |
| 5161 |
// And in the case of SSL, the compression can fool us and let the |
| 5162 |
// server send the data much faster than expected. |
| 5163 |
// So better provide random data that cannot be compressed. |
| 5164 |
for (int i = 0; i < wantedSize; ++i) |
| 5165 |
testData += (char)QRandomGenerator::global()->generate(); |
| 5166 |
|
| 5167 |
QByteArray httpResponse = QByteArray("HTTP/1.0 200 OK\r\nContent-Length: "); |
| 5168 |
httpResponse += QByteArray::number(testData.size()); |
| 5169 |
httpResponse += "\r\n\r\n"; |
| 5170 |
httpResponse += testData; |
| 5171 |
|
| 5172 |
qDebug() << "Server will send" << (httpResponse.size()-testData.size()) << "bytes of header and" |
| 5173 |
<< testData.size() << "bytes of data"; |
| 5174 |
|
| 5175 |
const bool fillKernelBuffer = bufferSize > 0; |
| 5176 |
notEnoughDataForFastSender = false; |
| 5177 |
FastSender server(httpResponse, https, fillKernelBuffer, this); |
| 5178 |
|
| 5179 |
QUrl url(QString("%1://127.0.0.1:%2/qtest/rfc3252.txt") |
| 5180 |
.arg(https?"https":"http") |
| 5181 |
.arg(server.serverPort())); |
| 5182 |
QNetworkRequest request(url); |
| 5183 |
QNetworkReplyPtr reply(manager.get(request)); |
| 5184 |
reply->setReadBufferSize(bufferSize); |
| 5185 |
reply->ignoreSslErrors(); |
| 5186 |
const int rate = 200; // in kB per sec |
| 5187 |
RateControlledReader reader(server, reply.data(), rate, bufferSize); |
| 5188 |
|
| 5189 |
QElapsedTimer loopTimer; |
| 5190 |
loopTimer.start(); |
| 5191 |
|
| 5192 |
const int result = waitForFinish(reply); |
| 5193 |
if (notEnoughDataForFastSender) { |
| 5194 |
server.wait(); |
| 5195 |
QSKIP("kernel socket buffers are too big for this test to work"); |
| 5196 |
} |
| 5197 |
|
| 5198 |
QVERIFY2(result == Success, msgWaitForFinished(reply)); |
| 5199 |
|
| 5200 |
const int elapsedTime = loopTimer.elapsed(); |
| 5201 |
server.wait(); |
| 5202 |
reader.wrapUp(); |
| 5203 |
|
| 5204 |
qDebug() << "send rate:" << server.transferRate << "B/s"; |
| 5205 |
qDebug() << "receive rate:" << reader.totalBytesRead * 1000 / elapsedTime |
| 5206 |
<< "(it received" << reader.totalBytesRead << "bytes in" << elapsedTime << "ms)"; |
| 5207 |
|
| 5208 |
QCOMPARE(reply->url(), request.url()); |
| 5209 |
QCOMPARE(reply->error(), QNetworkReply::NoError); |
| 5210 |
QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200); |
| 5211 |
|
| 5212 |
QCOMPARE(reply->header(QNetworkRequest::ContentLengthHeader).toLongLong(), (qint64)testData.size()); |
| 5213 |
if (reader.data.size() < testData.size()) { // oops? |
| 5214 |
QCOMPARE(reader.data, testData.left(reader.data.size())); |
| 5215 |
qDebug() << "The data is incomplete, the last" << testData.size() - reader.data.size() << "bytes are missing"; |
| 5216 |
} |
| 5217 |
QCOMPARE(reader.data.size(), testData.size()); |
| 5218 |
QCOMPARE(reader.data, testData); |
| 5219 |
|
| 5220 |
// OK we got the file alright, but did setReadBufferSize work? |
| 5221 |
QVERIFY(server.transferRate != -1); |
| 5222 |
if (bufferSize > 0) { |
| 5223 |
const int allowedDeviation = 16; // TODO find out why the send rate is 13% faster currently |
| 5224 |
const int minRate = rate * 1024 * (100-allowedDeviation) / 100; |
| 5225 |
const int maxRate = rate * 1024 * (100+allowedDeviation) / 100; |
| 5226 |
qDebug() << minRate << "<="<< server.transferRate << "<=" << maxRate << '?'; |
| 5227 |
// The test takes too long to run if sending enough data to overwhelm the |
| 5228 |
// receiver's kernel buffers. |
| 5229 |
//QEXPECT_FAIL("http+limited", "Limiting is broken right now, check QTBUG-15065", Continue); |
| 5230 |
//QEXPECT_FAIL("https+limited", "Limiting is broken right now, check QTBUG-15065", Continue); |
| 5231 |
//QVERIFY(server.transferRate >= minRate && server.transferRate <= maxRate); |
| 5232 |
} |
| 5233 |
} |
| 5234 |
|
| 5235 |
void tst_QNetworkReply::ioPostToHttpUploadProgress() |
| 5236 |
{ |
| 5237 |
//test file must be larger than OS socket buffers (~830kB on MacOS 10.6) |
| 5238 |
QFile sourceFile(testDataDir + "/image1.jpg"); |
| 5239 |
QVERIFY(sourceFile.open(QIODevice::ReadOnly)); |
| 5240 |
const qint64 sourceFileSize = sourceFile.size(); |
| 5241 |
|
| 5242 |
// emulate a minimal http server |
| 5243 |
QTcpServer server; |
| 5244 |
server.listen(QHostAddress(QHostAddress::LocalHost), 0); |
| 5245 |
|
| 5246 |
// create the request |
| 5247 |
QUrl url = QUrl(QString("http://127.0.0.1:%1/").arg(server.serverPort())); |
| 5248 |
QNetworkRequest request(url); |
| 5249 |
request.setRawHeader("Content-Type", "application/octet-stream"); |
| 5250 |
QNetworkReplyPtr reply(manager.post(request, &sourceFile)); |
| 5251 |
QSignalSpy spy(reply.data(), SIGNAL(uploadProgress(qint64,qint64))); |
| 5252 |
connect(&server, SIGNAL(newConnection()), &QTestEventLoop::instance(), SLOT(exitLoop())); |
| 5253 |
|
| 5254 |
// get the request started and the incoming socket connected |
| 5255 |
QTestEventLoop::instance().enterLoop(10); |
| 5256 |
QVERIFY(!QTestEventLoop::instance().timeout()); |
| 5257 |
QTcpSocket *incomingSocket = server.nextPendingConnection(); |
| 5258 |
QVERIFY(incomingSocket); |
| 5259 |
disconnect(&server, SIGNAL(newConnection()), &QTestEventLoop::instance(), SLOT(exitLoop())); |
| 5260 |
|
| 5261 |
incomingSocket->setReadBufferSize(1024); |
| 5262 |
QTestEventLoop::instance().enterLoop(5); |
| 5263 |
// some progress should have been made |
| 5264 |
QVERIFY(!spy.isEmpty()); |
| 5265 |
const QList<QVariant> args = spy.last(); |
| 5266 |
QVERIFY(!args.isEmpty()); |
| 5267 |
const qint64 bufferedUploadProgress = args.at(0).toLongLong(); |
| 5268 |
QVERIFY(bufferedUploadProgress > 0); |
| 5269 |
// but not everything? - Note however, that under CI virtualization, |
| 5270 |
// particularly on Windows, it frequently happens that the whole file |
| 5271 |
// is uploaded in one chunk. |
| 5272 |
if (bufferedUploadProgress == sourceFileSize) { |
| 5273 |
qWarning() << QDir::toNativeSeparators(sourceFile.fileName()) |
| 5274 |
<< "of" << sourceFileSize << "bytes was uploaded in one go."; |
| 5275 |
} |
| 5276 |
|
| 5277 |
// set the read buffer to unlimited |
| 5278 |
incomingSocket->setReadBufferSize(0); |
| 5279 |
QTestEventLoop::instance().enterLoop(10); |
| 5280 |
// progress should be finished |
| 5281 |
QVERIFY(!spy.isEmpty()); |
| 5282 |
const QList<QVariant> args3 = spy.last(); |
| 5283 |
QVERIFY(!args3.isEmpty()); |
| 5284 |
// More progress than before |
| 5285 |
const qint64 unbufferedUploadProgress = args3.at(0).toLongLong(); |
| 5286 |
if (bufferedUploadProgress < sourceFileSize) |
| 5287 |
QVERIFY(unbufferedUploadProgress > bufferedUploadProgress); |
| 5288 |
QCOMPARE(unbufferedUploadProgress, args3.at(1).toLongLong()); |
| 5289 |
// And actually finished.. |
| 5290 |
QCOMPARE(unbufferedUploadProgress, sourceFileSize); |
| 5291 |
|
| 5292 |
// after sending this, the QNAM should emit finished() |
| 5293 |
connect(reply, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop())); |
| 5294 |
incomingSocket->write("HTTP/1.0 200 OK\r\n"); |
| 5295 |
incomingSocket->write("Content-Length: 0\r\n"); |
| 5296 |
incomingSocket->write("\r\n"); |
| 5297 |
QTestEventLoop::instance().enterLoop(10); |
| 5298 |
// not timeouted -> finished() was emitted |
| 5299 |
QVERIFY(!QTestEventLoop::instance().timeout()); |
| 5300 |
|
| 5301 |
incomingSocket->close(); |
| 5302 |
server.close(); |
| 5303 |
} |
| 5304 |
|
| 5305 |
void tst_QNetworkReply::emitAllUploadProgressSignals() |
| 5306 |
{ |
| 5307 |
QFile sourceFile(testDataDir + "/image1.jpg"); |
| 5308 |
QVERIFY(sourceFile.open(QIODevice::ReadOnly)); |
| 5309 |
|
| 5310 |
// emulate a minimal http server |
| 5311 |
QTcpServer server; |
| 5312 |
server.listen(QHostAddress(QHostAddress::LocalHost), 0); |
| 5313 |
connect(&server, SIGNAL(newConnection()), &QTestEventLoop::instance(), SLOT(exitLoop())); |
| 5314 |
|
| 5315 |
QUrl url = QUrl(QLatin1String("http://127.0.0.1:") + QString::number(server.serverPort()) + QLatin1Char('/')); |
| 5316 |
QNetworkRequest normalRequest(url); |
| 5317 |
normalRequest.setRawHeader("Content-Type", "application/octet-stream"); |
| 5318 |
|
| 5319 |
QNetworkRequest catchAllSignalsRequest(normalRequest); |
| 5320 |
catchAllSignalsRequest.setAttribute(QNetworkRequest::EmitAllUploadProgressSignalsAttribute, true); |
| 5321 |
|
| 5322 |
QList<QNetworkRequest> requests; |
| 5323 |
requests << normalRequest << catchAllSignalsRequest; |
| 5324 |
|
| 5325 |
QList<int> signalCount; |
| 5326 |
|
| 5327 |
foreach (const QNetworkRequest &request, requests) { |
| 5328 |
|
| 5329 |
sourceFile.seek(0); |
| 5330 |
QNetworkReplyPtr reply(manager.post(request, &sourceFile)); |
| 5331 |
QSignalSpy spy(reply.data(), SIGNAL(uploadProgress(qint64,qint64))); |
| 5332 |
|
| 5333 |
// get the request started and the incoming socket connected |
| 5334 |
QTestEventLoop::instance().enterLoop(10); |
| 5335 |
QVERIFY(!QTestEventLoop::instance().timeout()); |
| 5336 |
QTcpSocket *incomingSocket = server.nextPendingConnection(); |
| 5337 |
QVERIFY(incomingSocket); |
| 5338 |
QTestEventLoop::instance().enterLoop(10); |
| 5339 |
|
| 5340 |
connect(reply, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop())); |
| 5341 |
incomingSocket->write("HTTP/1.0 200 OK\r\n"); |
| 5342 |
incomingSocket->write("Content-Length: 0\r\n"); |
| 5343 |
incomingSocket->write("\r\n"); |
| 5344 |
QTestEventLoop::instance().enterLoop(10); |
| 5345 |
// not timeouted -> finished() was emitted |
| 5346 |
QVERIFY(!QTestEventLoop::instance().timeout()); |
| 5347 |
|
| 5348 |
incomingSocket->close(); |
| 5349 |
signalCount.append(spy.count()); |
| 5350 |
reply->deleteLater(); |
| 5351 |
} |
| 5352 |
server.close(); |
| 5353 |
|
| 5354 |
// verify that the normal request emitted less signals than the one emitting all signals |
| 5355 |
QVERIFY2(signalCount.at(0) < signalCount.at(1), "no upload signal was suppressed"); |
| 5356 |
} |
| 5357 |
|
| 5358 |
void tst_QNetworkReply::ioPostToHttpEmptyUploadProgress() |
| 5359 |
{ |
| 5360 |
QByteArray ba; |
| 5361 |
ba.resize(0); |
| 5362 |
QBuffer buffer(&ba,0); |
| 5363 |
QVERIFY(buffer.open(QIODevice::ReadOnly)); |
| 5364 |
|
| 5365 |
// emulate a minimal http server |
| 5366 |
QTcpServer server; |
| 5367 |
server.listen(QHostAddress(QHostAddress::LocalHost), 0); |
| 5368 |
|
| 5369 |
// create the request |
| 5370 |
QUrl url = QUrl(QLatin1String("http://127.0.0.1:") + QString::number(server.serverPort()) + QLatin1Char('/')); |
| 5371 |
QNetworkRequest request(url); |
| 5372 |
request.setRawHeader("Content-Type", "application/octet-stream"); |
| 5373 |
QNetworkReplyPtr reply(manager.post(request, &buffer)); |
| 5374 |
QSignalSpy spy(reply.data(), SIGNAL(uploadProgress(qint64,qint64))); |
| 5375 |
connect(&server, SIGNAL(newConnection()), &QTestEventLoop::instance(), SLOT(exitLoop())); |
| 5376 |
|
| 5377 |
|
| 5378 |
// get the request started and the incoming socket connected |
| 5379 |
QTestEventLoop::instance().enterLoop(10); |
| 5380 |
QVERIFY(!QTestEventLoop::instance().timeout()); |
| 5381 |
QTcpSocket *incomingSocket = server.nextPendingConnection(); |
| 5382 |
QVERIFY(incomingSocket); |
| 5383 |
|
| 5384 |
// after sending this, the QNAM should emit finished() |
| 5385 |
connect(reply, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop())); |
| 5386 |
incomingSocket->write("HTTP/1.0 200 OK\r\n"); |
| 5387 |
incomingSocket->write("Content-Length: 0\r\n"); |
| 5388 |
incomingSocket->write("\r\n"); |
| 5389 |
incomingSocket->flush(); |
| 5390 |
QTestEventLoop::instance().enterLoop(10); |
| 5391 |
// not timeouted -> finished() was emitted |
| 5392 |
QVERIFY(!QTestEventLoop::instance().timeout()); |
| 5393 |
|
| 5394 |
// final check: only 1 uploadProgress has been emitted |
| 5395 |
QCOMPARE(spy.length(), 1); |
| 5396 |
QList<QVariant> args = spy.last(); |
| 5397 |
QVERIFY(!args.isEmpty()); |
| 5398 |
QCOMPARE(args.at(0).toLongLong(), buffer.size()); |
| 5399 |
QCOMPARE(args.at(0).toLongLong(), buffer.size()); |
| 5400 |
|
| 5401 |
incomingSocket->close(); |
| 5402 |
server.close(); |
| 5403 |
} |
| 5404 |
|
| 5405 |
void tst_QNetworkReply::lastModifiedHeaderForFile() |
| 5406 |
{ |
| 5407 |
QFileInfo fileInfo(testDataDir + "/bigfile"); |
| 5408 |
QVERIFY(fileInfo.exists()); |
| 5409 |
|
| 5410 |
QUrl url = QUrl::fromLocalFile(fileInfo.filePath()); |
| 5411 |
|
| 5412 |
QNetworkRequest request(url); |
| 5413 |
QNetworkReplyPtr reply(manager.head(request)); |
| 5414 |
|
| 5415 |
QVERIFY2(waitForFinish(reply) == Success, msgWaitForFinished(reply)); |
| 5416 |
|
| 5417 |
QDateTime header = reply->header(QNetworkRequest::LastModifiedHeader).toDateTime(); |
| 5418 |
QCOMPARE(header, fileInfo.lastModified()); |
| 5419 |
} |
| 5420 |
|
| 5421 |
void tst_QNetworkReply::lastModifiedHeaderForHttp() |
| 5422 |
{ |
| 5423 |
// Tue, 22 May 2007 12:04:57 GMT according to webserver |
| 5424 |
QUrl url = "http://" + QtNetworkSettings::httpServerName() + "/qtest/fluke.gif"; |
| 5425 |
|
| 5426 |
QNetworkRequest request(url); |
| 5427 |
QNetworkReplyPtr reply(manager.head(request)); |
| 5428 |
|
| 5429 |
QVERIFY2(waitForFinish(reply) == Success, msgWaitForFinished(reply)); |
| 5430 |
|
| 5431 |
QDateTime header = reply->header(QNetworkRequest::LastModifiedHeader).toDateTime(); |
| 5432 |
QDateTime realDate = QDateTime::fromString("2007-05-22T12:04:57", Qt::ISODate); |
| 5433 |
realDate.setTimeSpec(Qt::UTC); |
| 5434 |
|
| 5435 |
QCOMPARE(header, realDate); |
| 5436 |
} |
| 5437 |
|
| 5438 |
void tst_QNetworkReply::httpCanReadLine() |
| 5439 |
{ |
| 5440 |
QNetworkRequest request(QUrl("http://" + QtNetworkSettings::httpServerName() + "/qtest/rfc3252.txt")); |
| 5441 |
QNetworkReplyPtr reply(manager.get(request)); |
| 5442 |
|
| 5443 |
QVERIFY2(waitForFinish(reply) == Success, msgWaitForFinished(reply)); |
| 5444 |
|
| 5445 |
QCOMPARE(reply->error(), QNetworkReply::NoError); |
| 5446 |
|
| 5447 |
QVERIFY(reply->canReadLine()); |
| 5448 |
QVERIFY(!reply->readAll().isEmpty()); |
| 5449 |
QVERIFY(!reply->canReadLine()); |
| 5450 |
} |
| 5451 |
|
| 5452 |
#ifdef QT_BUILD_INTERNAL |
| 5453 |
void tst_QNetworkReply::rateControl_data() |
| 5454 |
{ |
| 5455 |
QTest::addColumn<int>("rate"); |
| 5456 |
|
| 5457 |
QTest::newRow("15") << 15; |
| 5458 |
QTest::newRow("40") << 40; |
| 5459 |
QTest::newRow("73") << 73; |
| 5460 |
QTest::newRow("80") << 80; |
| 5461 |
QTest::newRow("125") << 125; |
| 5462 |
QTest::newRow("250") << 250; |
| 5463 |
QTest::newRow("1024") << 1024; |
| 5464 |
} |
| 5465 |
#endif |
| 5466 |
|
| 5467 |
#ifdef QT_BUILD_INTERNAL |
| 5468 |
void tst_QNetworkReply::rateControl() |
| 5469 |
{ |
| 5470 |
QSKIP("Test disabled -- only for manual purposes"); |
| 5471 |
// this function tests that we aren't reading from the network |
| 5472 |
// faster than the data is being consumed. |
| 5473 |
QFETCH(int, rate); |
| 5474 |
|
| 5475 |
// ask for 20 seconds worth of data |
| 5476 |
FastSender sender(20 * rate * 1024); |
| 5477 |
|
| 5478 |
QNetworkRequest request("debugpipe://localhost:" + QString::number(sender.serverPort())); |
| 5479 |
QNetworkReplyPtr reply(manager.get(request)); |
| 5480 |
reply->setReadBufferSize(32768); |
| 5481 |
QSignalSpy errorSpy(reply.data(), SIGNAL(errorOccurred(QNetworkReply::NetworkError))); |
| 5482 |
|
| 5483 |
RateControlledReader reader(sender, reply.data(), rate, 20); |
| 5484 |
|
| 5485 |
// this test is designed to run for 25 seconds at most |
| 5486 |
QElapsedTimer loopTimer; |
| 5487 |
loopTimer.start(); |
| 5488 |
|
| 5489 |
QVERIFY2(waitForFinish(reply) == Success, msgWaitForFinished(reply)); |
| 5490 |
|
| 5491 |
int elapsedTime = loopTimer.elapsed(); |
| 5492 |
|
| 5493 |
if (!errorSpy.isEmpty()) { |
| 5494 |
qDebug() << "ERROR!" << errorSpy[0][0] << reply->errorString(); |
| 5495 |
} |
| 5496 |
|
| 5497 |
qDebug() << "tst_QNetworkReply::rateControl" << "send rate:" << sender.transferRate; |
| 5498 |
qDebug() << "tst_QNetworkReply::rateControl" << "receive rate:" << reader.totalBytesRead * 1000 / elapsedTime |
| 5499 |
<< "(it received" << reader.totalBytesRead << "bytes in" << elapsedTime << "ms)"; |
| 5500 |
|
| 5501 |
sender.wait(); |
| 5502 |
|
| 5503 |
QCOMPARE(reply->url(), request.url()); |
| 5504 |
QCOMPARE(reply->error(), QNetworkReply::NoError); |
| 5505 |
|
| 5506 |
QVERIFY(sender.transferRate != -1); |
| 5507 |
int minRate = rate * 1024 * 9 / 10; |
| 5508 |
int maxRate = rate * 1024 * 11 / 10; |
| 5509 |
QVERIFY(sender.transferRate >= minRate); |
| 5510 |
QVERIFY(sender.transferRate <= maxRate); |
| 5511 |
} |
| 5512 |
#endif |
| 5513 |
|
| 5514 |
void tst_QNetworkReply::downloadProgress_data() |
| 5515 |
{ |
| 5516 |
QTest::addColumn<QUrl>("url"); |
| 5517 |
QTest::addColumn<int>("expectedSize"); |
| 5518 |
|
| 5519 |
QTest::newRow("empty") << QUrl::fromLocalFile(QFINDTESTDATA("empty")) << 0; |
| 5520 |
QTest::newRow("http:small") << QUrl("http://" + QtNetworkSettings::httpServerName() + "/qtest/rfc3252.txt") << 25962; |
| 5521 |
QTest::newRow("http:big") << QUrl("http://" + QtNetworkSettings::httpServerName() + "/qtest/bigfile") << 519240; |
| 5522 |
QTest::newRow("http:no-length") << QUrl("http://" + QtNetworkSettings::httpServerName() + "/qtest/deflate/rfc2616.html") << -1; |
| 5523 |
QTest::newRow("ftp:small") << QUrl("http://" + QtNetworkSettings::httpServerName() + "/qtest/rfc3252.txt") << 25962; |
| 5524 |
QTest::newRow("ftp:big") << QUrl("http://" + QtNetworkSettings::httpServerName() + "/qtest/bigfile") << 519240; |
| 5525 |
} |
| 5526 |
|
| 5527 |
class SlowReader : public QObject |
| 5528 |
{ |
| 5529 |
Q_OBJECT |
| 5530 |
public: |
| 5531 |
SlowReader(QIODevice *dev) |
| 5532 |
: device(dev) |
| 5533 |
{ |
| 5534 |
connect(device, SIGNAL(readyRead()), this, SLOT(deviceReady())); |
| 5535 |
} |
| 5536 |
private slots: |
| 5537 |
void deviceReady() |
| 5538 |
{ |
| 5539 |
QTimer::singleShot(100, this, SLOT(doRead())); |
| 5540 |
} |
| 5541 |
|
| 5542 |
void doRead() |
| 5543 |
{ |
| 5544 |
device->readAll(); |
| 5545 |
} |
| 5546 |
private: |
| 5547 |
QIODevice *device; |
| 5548 |
}; |
| 5549 |
|
| 5550 |
void tst_QNetworkReply::downloadProgress() |
| 5551 |
{ |
| 5552 |
QFETCH(QUrl, url); |
| 5553 |
QFETCH(int, expectedSize); |
| 5554 |
|
| 5555 |
QNetworkRequest request(url); |
| 5556 |
QNetworkReplyPtr reply(manager.get(request)); |
| 5557 |
//artificially slow down the test, otherwise only the final signal is emitted |
| 5558 |
reply->setReadBufferSize(qMax(20000, expectedSize / 4)); |
| 5559 |
SlowReader reader(reply.data()); |
| 5560 |
QSignalSpy spy(reply.data(), SIGNAL(downloadProgress(qint64,qint64))); |
| 5561 |
connect(reply, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop())); |
| 5562 |
QTestEventLoop::instance().enterLoop(30); |
| 5563 |
QVERIFY(!QTestEventLoop::instance().timeout()); |
| 5564 |
QVERIFY(reply->isFinished()); |
| 5565 |
|
| 5566 |
QVERIFY(spy.count() > 0); |
| 5567 |
|
| 5568 |
//final progress should have equal current & total |
| 5569 |
QList<QVariant> args = spy.takeLast(); |
| 5570 |
QCOMPARE(args.at(0).toInt(), args.at(1).toInt()); |
| 5571 |
|
| 5572 |
qint64 current = 0; |
| 5573 |
//intermediate progress ascending and has expected total |
| 5574 |
while (!spy.isEmpty()) { |
| 5575 |
args = spy.takeFirst(); |
| 5576 |
QVERIFY(args.at(0).toInt() >= current); |
| 5577 |
if (expectedSize >=0) |
| 5578 |
QCOMPARE(args.at(1).toInt(), expectedSize); |
| 5579 |
else |
| 5580 |
QVERIFY(args.at(1).toInt() == expectedSize || args.at(1).toInt() == args.at(0).toInt()); |
| 5581 |
current = args.at(0).toInt(); |
| 5582 |
} |
| 5583 |
} |
| 5584 |
|
| 5585 |
#ifdef QT_BUILD_INTERNAL |
| 5586 |
void tst_QNetworkReply::uploadProgress_data() |
| 5587 |
{ |
| 5588 |
putToFile_data(); |
| 5589 |
} |
| 5590 |
#endif |
| 5591 |
|
| 5592 |
#ifdef QT_BUILD_INTERNAL |
| 5593 |
void tst_QNetworkReply::uploadProgress() |
| 5594 |
{ |
| 5595 |
QFETCH(QByteArray, data); |
| 5596 |
QTcpServer server; |
| 5597 |
QVERIFY(server.listen()); |
| 5598 |
|
| 5599 |
QNetworkRequest request("debugpipe://127.0.0.1:" + QString::number(server.serverPort()) + "/?bare=1"); |
| 5600 |
QNetworkReplyPtr reply(manager.put(request, data)); |
| 5601 |
QSignalSpy spy(reply.data(), SIGNAL(uploadProgress(qint64,qint64))); |
| 5602 |
QSignalSpy finished(reply.data(), SIGNAL(finished())); |
| 5603 |
QVERIFY(spy.isValid()); |
| 5604 |
QVERIFY(finished.isValid()); |
| 5605 |
|
| 5606 |
QCoreApplication::instance()->processEvents(); |
| 5607 |
if (!server.hasPendingConnections()) |
| 5608 |
server.waitForNewConnection(1000); |
| 5609 |
QVERIFY(server.hasPendingConnections()); |
| 5610 |
|
| 5611 |
QTcpSocket *receiver = server.nextPendingConnection(); |
| 5612 |
if (finished.count() == 0) { |
| 5613 |
// it's not finished yet, so wait for it to be |
| 5614 |
QVERIFY2(waitForFinish(reply) == Success, msgWaitForFinished(reply)); |
| 5615 |
} |
| 5616 |
delete receiver; |
| 5617 |
|
| 5618 |
QVERIFY(finished.count() > 0); |
| 5619 |
QVERIFY(spy.count() > 0); |
| 5620 |
|
| 5621 |
QList<QVariant> args = spy.last(); |
| 5622 |
QCOMPARE(args.at(0).toInt(), data.size()); |
| 5623 |
QCOMPARE(args.at(1).toInt(), data.size()); |
| 5624 |
} |
| 5625 |
#endif |
| 5626 |
|
| 5627 |
void tst_QNetworkReply::chaining_data() |
| 5628 |
{ |
| 5629 |
putToFile_data(); |
| 5630 |
} |
| 5631 |
|
| 5632 |
void tst_QNetworkReply::chaining() |
| 5633 |
{ |
| 5634 |
QTemporaryFile sourceFile(QDir::currentPath() + "/temp-XXXXXX"); |
| 5635 |
sourceFile.setAutoRemove(true); |
| 5636 |
QVERIFY2(sourceFile.open(), qPrintable(sourceFile.errorString())); |
| 5637 |
|
| 5638 |
QFETCH(QByteArray, data); |
| 5639 |
QCOMPARE(sourceFile.write(data), data.size()); |
| 5640 |
sourceFile.flush(); |
| 5641 |
QCOMPARE(sourceFile.size(), qint64(data.size())); |
| 5642 |
|
| 5643 |
QNetworkRequest request(QUrl::fromLocalFile(sourceFile.fileName())); |
| 5644 |
QNetworkReplyPtr getReply(manager.get(request)); |
| 5645 |
|
| 5646 |
QFile targetFile(testFileName); |
| 5647 |
QUrl url = QUrl::fromLocalFile(targetFile.fileName()); |
| 5648 |
request.setUrl(url); |
| 5649 |
QNetworkReplyPtr putReply(manager.put(request, getReply.data())); |
| 5650 |
|
| 5651 |
QCOMPARE(waitForFinish(putReply), int(Success)); |
| 5652 |
|
| 5653 |
QCOMPARE(getReply->url(), QUrl::fromLocalFile(sourceFile.fileName())); |
| 5654 |
QCOMPARE(getReply->error(), QNetworkReply::NoError); |
| 5655 |
QCOMPARE(getReply->header(QNetworkRequest::ContentLengthHeader).toLongLong(), sourceFile.size()); |
| 5656 |
|
| 5657 |
QCOMPARE(putReply->url(), url); |
| 5658 |
QCOMPARE(putReply->error(), QNetworkReply::NoError); |
| 5659 |
QCOMPARE(putReply->header(QNetworkRequest::ContentLengthHeader).toLongLong(), Q_INT64_C(0)); |
| 5660 |
QVERIFY(putReply->readAll().isEmpty()); |
| 5661 |
|
| 5662 |
QVERIFY(sourceFile.atEnd()); |
| 5663 |
sourceFile.seek(0); // reset it to the beginning |
| 5664 |
|
| 5665 |
QVERIFY(targetFile.open(QIODevice::ReadOnly)); |
| 5666 |
QCOMPARE(targetFile.size(), sourceFile.size()); |
| 5667 |
QCOMPARE(targetFile.readAll(), sourceFile.readAll()); |
| 5668 |
} |
| 5669 |
|
| 5670 |
void tst_QNetworkReply::receiveCookiesFromHttp_data() |
| 5671 |
{ |
| 5672 |
QTest::addColumn<QString>("cookieString"); |
| 5673 |
QTest::addColumn<QList<QNetworkCookie> >("expectedCookiesFromHttp"); |
| 5674 |
QTest::addColumn<QList<QNetworkCookie> >("expectedCookiesInJar"); |
| 5675 |
|
| 5676 |
QTest::newRow("empty") << "" << QList<QNetworkCookie>() << QList<QNetworkCookie>(); |
| 5677 |
|
| 5678 |
QList<QNetworkCookie> header, jar; |
| 5679 |
QNetworkCookie cookie("a", "b"); |
| 5680 |
header << cookie; |
| 5681 |
cookie.setDomain(QtNetworkSettings::httpServerName()); |
| 5682 |
cookie.setPath("/qtest/cgi-bin/"); |
| 5683 |
jar << cookie; |
| 5684 |
QTest::newRow("simple-cookie") << "a=b" << header << jar; |
| 5685 |
|
| 5686 |
header << QNetworkCookie("c", "d"); |
| 5687 |
cookie.setName("c"); |
| 5688 |
cookie.setValue("d"); |
| 5689 |
jar << cookie; |
| 5690 |
QTest::newRow("two-cookies") << "a=b\nc=d" << header << jar; |
| 5691 |
|
| 5692 |
header.clear(); |
| 5693 |
jar.clear(); |
| 5694 |
header << QNetworkCookie("a", "b, c=d"); |
| 5695 |
cookie.setName("a"); |
| 5696 |
cookie.setValue("b, c=d"); |
| 5697 |
jar << cookie; |
| 5698 |
QTest::newRow("invalid-two-cookies") << "a=b, c=d" << header << jar; |
| 5699 |
|
| 5700 |
header.clear(); |
| 5701 |
jar.clear(); |
| 5702 |
cookie = QNetworkCookie("a", "b"); |
| 5703 |
cookie.setPath("/not/part-of-path"); |
| 5704 |
header << cookie; |
| 5705 |
cookie.setDomain(QtNetworkSettings::httpServerName()); |
| 5706 |
jar << cookie; |
| 5707 |
QTest::newRow("invalid-cookie-path") << "a=b; path=/not/part-of-path" << header << jar; |
| 5708 |
|
| 5709 |
jar.clear(); |
| 5710 |
cookie = QNetworkCookie("a", "b"); |
| 5711 |
cookie.setDomain(".example.com"); |
| 5712 |
header.clear(); |
| 5713 |
header << cookie; |
| 5714 |
QTest::newRow("invalid-cookie-domain") << "a=b; domain=.example.com" << header << jar; |
| 5715 |
} |
| 5716 |
|
| 5717 |
void tst_QNetworkReply::receiveCookiesFromHttp() |
| 5718 |
{ |
| 5719 |
QFETCH(QString, cookieString); |
| 5720 |
|
| 5721 |
QByteArray data = cookieString.toLatin1() + '\n'; |
| 5722 |
QUrl url("http://" + QtNetworkSettings::httpServerName() + "/qtest/cgi-bin/set-cookie.cgi"); |
| 5723 |
QNetworkRequest request(url); |
| 5724 |
request.setRawHeader("Content-Type", "application/octet-stream"); |
| 5725 |
QNetworkReplyPtr reply; |
| 5726 |
RUN_REQUEST(runSimpleRequest(QNetworkAccessManager::PostOperation, request, reply, data)); |
| 5727 |
|
| 5728 |
QCOMPARE(reply->url(), url); |
| 5729 |
QCOMPARE(reply->error(), QNetworkReply::NoError); |
| 5730 |
|
| 5731 |
QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200); // 200 Ok |
| 5732 |
|
| 5733 |
QList<QNetworkCookie> setCookies = |
| 5734 |
qvariant_cast<QList<QNetworkCookie> >(reply->header(QNetworkRequest::SetCookieHeader)); |
| 5735 |
QTEST(setCookies, "expectedCookiesFromHttp"); |
| 5736 |
QTEST(cookieJar->allCookies(), "expectedCookiesInJar"); |
| 5737 |
} |
| 5738 |
|
| 5739 |
void tst_QNetworkReply::receiveCookiesFromHttpSynchronous_data() |
| 5740 |
{ |
| 5741 |
tst_QNetworkReply::receiveCookiesFromHttp_data(); |
| 5742 |
} |
| 5743 |
|
| 5744 |
void tst_QNetworkReply::receiveCookiesFromHttpSynchronous() |
| 5745 |
{ |
| 5746 |
QFETCH(QString, cookieString); |
| 5747 |
|
| 5748 |
QByteArray data = cookieString.toLatin1() + '\n'; |
| 5749 |
QUrl url("http://" + QtNetworkSettings::httpServerName() + "/qtest/cgi-bin/set-cookie.cgi"); |
| 5750 |
|
| 5751 |
QNetworkRequest request(url); |
| 5752 |
request.setRawHeader("Content-Type", "application/octet-stream"); |
| 5753 |
request.setAttribute( |
| 5754 |
QNetworkRequest::SynchronousRequestAttribute, |
| 5755 |
true); |
| 5756 |
|
| 5757 |
QNetworkReplyPtr reply; |
| 5758 |
RUN_REQUEST(runSimpleRequest(QNetworkAccessManager::PostOperation, request, reply, data)); |
| 5759 |
|
| 5760 |
QCOMPARE(reply->url(), url); |
| 5761 |
QCOMPARE(reply->error(), QNetworkReply::NoError); |
| 5762 |
|
| 5763 |
QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200); // 200 Ok |
| 5764 |
|
| 5765 |
QList<QNetworkCookie> setCookies = |
| 5766 |
qvariant_cast<QList<QNetworkCookie> >(reply->header(QNetworkRequest::SetCookieHeader)); |
| 5767 |
QTEST(setCookies, "expectedCookiesFromHttp"); |
| 5768 |
QTEST(cookieJar->allCookies(), "expectedCookiesInJar"); |
| 5769 |
} |
| 5770 |
|
| 5771 |
void tst_QNetworkReply::sendCookies_data() |
| 5772 |
{ |
| 5773 |
QTest::addColumn<QList<QNetworkCookie> >("cookiesToSet"); |
| 5774 |
QTest::addColumn<QString>("expectedCookieString"); |
| 5775 |
|
| 5776 |
QList<QNetworkCookie> list; |
| 5777 |
QTest::newRow("empty") << list << ""; |
| 5778 |
|
| 5779 |
QNetworkCookie cookie("a", "b"); |
| 5780 |
cookie.setPath("/"); |
| 5781 |
cookie.setDomain("example.com"); |
| 5782 |
list << cookie; |
| 5783 |
QTest::newRow("no-match-domain") << list << ""; |
| 5784 |
|
| 5785 |
cookie.setDomain(QtNetworkSettings::httpServerName()); |
| 5786 |
cookie.setPath("/something/else"); |
| 5787 |
list << cookie; |
| 5788 |
QTest::newRow("no-match-path") << list << ""; |
| 5789 |
|
| 5790 |
cookie.setPath("/"); |
| 5791 |
list << cookie; |
| 5792 |
QTest::newRow("simple-cookie") << list << "a=b"; |
| 5793 |
|
| 5794 |
cookie.setPath("/qtest"); |
| 5795 |
cookie.setValue("longer"); |
| 5796 |
list << cookie; |
| 5797 |
QTest::newRow("two-cookies") << list << "a=longer; a=b"; |
| 5798 |
|
| 5799 |
list.clear(); |
| 5800 |
cookie = QNetworkCookie("a", "b"); |
| 5801 |
cookie.setPath("/"); |
| 5802 |
cookie.setDomain(QLatin1Char('.') + QtNetworkSettings::serverDomainName()); |
| 5803 |
list << cookie; |
| 5804 |
QTest::newRow("domain-match") << list << "a=b"; |
| 5805 |
|
| 5806 |
// but it shouldn't match this: |
| 5807 |
cookie.setDomain(QtNetworkSettings::serverDomainName()); |
| 5808 |
list << cookie; |
| 5809 |
QTest::newRow("domain-match-2") << list << "a=b"; |
| 5810 |
} |
| 5811 |
|
| 5812 |
void tst_QNetworkReply::sendCookies() |
| 5813 |
{ |
| 5814 |
QFETCH(QString, expectedCookieString); |
| 5815 |
QFETCH(QList<QNetworkCookie>, cookiesToSet); |
| 5816 |
cookieJar->setAllCookies(cookiesToSet); |
| 5817 |
|
| 5818 |
QUrl url("http://" + QtNetworkSettings::httpServerName() + "/qtest/cgi-bin/get-cookie.cgi"); |
| 5819 |
QNetworkRequest request(url); |
| 5820 |
QNetworkReplyPtr reply; |
| 5821 |
RUN_REQUEST(runSimpleRequest(QNetworkAccessManager::GetOperation, request, reply)); |
| 5822 |
|
| 5823 |
QCOMPARE(reply->url(), url); |
| 5824 |
QCOMPARE(reply->error(), QNetworkReply::NoError); |
| 5825 |
|
| 5826 |
QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200); // 200 Ok |
| 5827 |
|
| 5828 |
QCOMPARE(QString::fromLatin1(reply->readAll()).trimmed(), expectedCookieString); |
| 5829 |
} |
| 5830 |
|
| 5831 |
void tst_QNetworkReply::sendCookiesSynchronous_data() |
| 5832 |
{ |
| 5833 |
tst_QNetworkReply::sendCookies_data(); |
| 5834 |
} |
| 5835 |
|
| 5836 |
void tst_QNetworkReply::sendCookiesSynchronous() |
| 5837 |
{ |
| 5838 |
QFETCH(QString, expectedCookieString); |
| 5839 |
QFETCH(QList<QNetworkCookie>, cookiesToSet); |
| 5840 |
cookieJar->setAllCookies(cookiesToSet); |
| 5841 |
|
| 5842 |
QUrl url("http://" + QtNetworkSettings::httpServerName() + "/qtest/cgi-bin/get-cookie.cgi"); |
| 5843 |
QNetworkRequest request(url); |
| 5844 |
|
| 5845 |
request.setAttribute( |
| 5846 |
QNetworkRequest::SynchronousRequestAttribute, |
| 5847 |
true); |
| 5848 |
|
| 5849 |
QNetworkReplyPtr reply; |
| 5850 |
RUN_REQUEST(runSimpleRequest(QNetworkAccessManager::GetOperation, request, reply)); |
| 5851 |
|
| 5852 |
QCOMPARE(reply->url(), url); |
| 5853 |
QCOMPARE(reply->error(), QNetworkReply::NoError); |
| 5854 |
|
| 5855 |
QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200); // 200 Ok |
| 5856 |
|
| 5857 |
QCOMPARE(QString::fromLatin1(reply->readAll()).trimmed(), expectedCookieString); |
| 5858 |
} |
| 5859 |
|
| 5860 |
void tst_QNetworkReply::nestedEventLoops_slot() |
| 5861 |
{ |
| 5862 |
QEventLoop subloop; |
| 5863 |
|
| 5864 |
// 16 seconds: fluke times out in 15 seconds, which triggers a QTcpSocket error |
| 5865 |
QTimer::singleShot(16000, &subloop, SLOT(quit())); |
| 5866 |
subloop.exec(); |
| 5867 |
|
| 5868 |
QTestEventLoop::instance().exitLoop(); |
| 5869 |
} |
| 5870 |
|
| 5871 |
void tst_QNetworkReply::notEnoughData() |
| 5872 |
{ |
| 5873 |
notEnoughDataForFastSender = true; |
| 5874 |
} |
| 5875 |
|
| 5876 |
void tst_QNetworkReply::nestedEventLoops() |
| 5877 |
{ |
| 5878 |
// Slightly fragile test, it may not be testing anything |
| 5879 |
// This is certifying that we're not running into the same issue |
| 5880 |
// that QHttp had (task 200432): the QTcpSocket connection is |
| 5881 |
// closed by the remote end because of the kept-alive HTTP |
| 5882 |
// connection timed out. |
| 5883 |
// |
| 5884 |
// The exact time required for this to happen is not exactly |
| 5885 |
// defined. Our server (Apache httpd) times out after 15 |
| 5886 |
// seconds. (see above) |
| 5887 |
|
| 5888 |
qDebug("Takes 16 seconds to run, please wait"); |
| 5889 |
|
| 5890 |
QUrl url("http://" + QtNetworkSettings::httpServerName()); |
| 5891 |
QNetworkRequest request(url); |
| 5892 |
QNetworkReplyPtr reply(manager.get(request)); |
| 5893 |
|
| 5894 |
QSignalSpy finishedspy(reply.data(), SIGNAL(finished())); |
| 5895 |
QSignalSpy errorspy(reply.data(), SIGNAL(errorOccurred(QNetworkReply::NetworkError))); |
| 5896 |
|
| 5897 |
connect(reply, SIGNAL(finished()), SLOT(nestedEventLoops_slot())); |
| 5898 |
QTestEventLoop::instance().enterLoop(20); |
| 5899 |
QVERIFY2(!QTestEventLoop::instance().timeout(), "Network timeout"); |
| 5900 |
|
| 5901 |
QCOMPARE(finishedspy.count(), 1); |
| 5902 |
QCOMPARE(errorspy.count(), 0); |
| 5903 |
} |
| 5904 |
|
| 5905 |
#ifndef QT_NO_NETWORKPROXY |
| 5906 |
void tst_QNetworkReply::httpProxyCommands_data() |
| 5907 |
{ |
| 5908 |
QTest::addColumn<QUrl>("url"); |
| 5909 |
QTest::addColumn<QByteArray>("responseToSend"); |
| 5910 |
QTest::addColumn<QString>("expectedCommand"); |
| 5911 |
|
| 5912 |
QTest::newRow("http") |
| 5913 |
<< QUrl("http://0.0.0.0:4443/http-request") |
| 5914 |
<< QByteArray("HTTP/1.0 200 OK\r\nProxy-Connection: close\r\nContent-Length: 1\r\n\r\n1") |
| 5915 |
<< "GET http://0.0.0.0:4443/http-request HTTP/1."; |
| 5916 |
#ifndef QT_NO_SSL |
| 5917 |
QTest::newRow("https") |
| 5918 |
<< QUrl("https://0.0.0.0:4443/https-request") |
| 5919 |
<< QByteArray("HTTP/1.0 200 Connection Established\r\n\r\n") |
| 5920 |
<< "CONNECT 0.0.0.0:4443 HTTP/1."; |
| 5921 |
#endif |
| 5922 |
} |
| 5923 |
|
| 5924 |
void tst_QNetworkReply::httpProxyCommands() |
| 5925 |
{ |
| 5926 |
QFETCH(QUrl, url); |
| 5927 |
QFETCH(QByteArray, responseToSend); |
| 5928 |
QFETCH(QString, expectedCommand); |
| 5929 |
|
| 5930 |
MiniHttpServer proxyServer(responseToSend); |
| 5931 |
QNetworkProxy proxy(QNetworkProxy::HttpProxy, "127.0.0.1", proxyServer.serverPort()); |
| 5932 |
|
| 5933 |
manager.setProxy(proxy); |
| 5934 |
QNetworkRequest request(url); |
| 5935 |
request.setRawHeader("User-Agent", "QNetworkReplyAutoTest/1.0"); |
| 5936 |
QNetworkReplyPtr reply(manager.get(request)); |
| 5937 |
//clearing the proxy here causes the test to fail. |
| 5938 |
//the proxy isn't used until after the bearer has been started |
| 5939 |
//which is correct in general, because system proxy isn't known until that time. |
| 5940 |
//removing this line is safe, as the proxy is also reset by the cleanup() function |
| 5941 |
//manager.setProxy(QNetworkProxy()); |
| 5942 |
|
| 5943 |
// wait for the finished signal |
| 5944 |
QVERIFY(waitForFinish(reply) != Timeout); |
| 5945 |
|
| 5946 |
//qDebug() << reply->error() << reply->errorString(); |
| 5947 |
//qDebug() << proxyServer.receivedData; |
| 5948 |
|
| 5949 |
// we don't really care if the request succeeded |
| 5950 |
// especially since it won't succeed in the HTTPS case |
| 5951 |
// so just check that the command was correct |
| 5952 |
|
| 5953 |
QString receivedHeader = proxyServer.receivedData.left(expectedCommand.length()); |
| 5954 |
QCOMPARE(receivedHeader, expectedCommand); |
| 5955 |
|
| 5956 |
//QTBUG-17223 - make sure the user agent from the request is sent to proxy server even for CONNECT |
| 5957 |
int uapos = proxyServer.receivedData.indexOf("User-Agent"); |
| 5958 |
int uaend = proxyServer.receivedData.indexOf("\r\n", uapos); |
| 5959 |
QByteArray uaheader = proxyServer.receivedData.mid(uapos, uaend - uapos); |
| 5960 |
QCOMPARE(uaheader, QByteArray("User-Agent: QNetworkReplyAutoTest/1.0")); |
| 5961 |
} |
| 5962 |
|
| 5963 |
class ProxyChangeHelper : public QObject |
| 5964 |
{ |
| 5965 |
Q_OBJECT |
| 5966 |
public: |
| 5967 |
ProxyChangeHelper() : QObject(), signalCount(0) {}; |
| 5968 |
public slots: |
| 5969 |
void finishedSlot() |
| 5970 |
{ |
| 5971 |
signalCount++; |
| 5972 |
if (signalCount == 2) |
| 5973 |
QMetaObject::invokeMethod(&QTestEventLoop::instance(), "exitLoop", Qt::QueuedConnection); |
| 5974 |
} |
| 5975 |
private: |
| 5976 |
int signalCount; |
| 5977 |
}; |
| 5978 |
|
| 5979 |
void tst_QNetworkReply::httpProxyCommandsSynchronous_data() |
| 5980 |
{ |
| 5981 |
httpProxyCommands_data(); |
| 5982 |
} |
| 5983 |
#endif // !QT_NO_NETWORKPROXY |
| 5984 |
|
| 5985 |
struct QThreadCleanup |
| 5986 |
{ |
| 5987 |
static inline void cleanup(QThread *thread) |
| 5988 |
{ |
| 5989 |
thread->quit(); |
| 5990 |
if (thread->wait(3000)) |
| 5991 |
delete thread; |
| 5992 |
else |
| 5993 |
qWarning("thread hung, leaking memory so test can finish"); |
| 5994 |
} |
| 5995 |
}; |
| 5996 |
|
| 5997 |
struct QDeleteLaterCleanup |
| 5998 |
{ |
| 5999 |
static inline void cleanup(QObject *o) |
| 6000 |
{ |
| 6001 |
o->deleteLater(); |
| 6002 |
} |
| 6003 |
}; |
| 6004 |
|
| 6005 |
#ifndef QT_NO_NETWORKPROXY |
| 6006 |
void tst_QNetworkReply::httpProxyCommandsSynchronous() |
| 6007 |
{ |
| 6008 |
QFETCH(QUrl, url); |
| 6009 |
QFETCH(QByteArray, responseToSend); |
| 6010 |
QFETCH(QString, expectedCommand); |
| 6011 |
|
| 6012 |
// when using synchronous commands, we need a different event loop for |
| 6013 |
// the server thread, because the client is never returning to the |
| 6014 |
// event loop |
| 6015 |
QScopedPointer<QThread, QThreadCleanup> serverThread(new QThread); |
| 6016 |
QScopedPointer<MiniHttpServer, QDeleteLaterCleanup> proxyServer(new MiniHttpServer(responseToSend, false, serverThread.data())); |
| 6017 |
QNetworkProxy proxy(QNetworkProxy::HttpProxy, "127.0.0.1", proxyServer->serverPort()); |
| 6018 |
|
| 6019 |
manager.setProxy(proxy); |
| 6020 |
QNetworkRequest request(url); |
| 6021 |
|
| 6022 |
// send synchronous request |
| 6023 |
request.setAttribute( |
| 6024 |
QNetworkRequest::SynchronousRequestAttribute, |
| 6025 |
true); |
| 6026 |
|
| 6027 |
QNetworkReplyPtr reply(manager.get(request)); |
| 6028 |
QVERIFY(reply->isFinished()); // synchronous |
| 6029 |
manager.setProxy(QNetworkProxy()); |
| 6030 |
|
| 6031 |
//qDebug() << reply->error() << reply->errorString(); |
| 6032 |
|
| 6033 |
// we don't really care if the request succeeded |
| 6034 |
// especially since it won't succeed in the HTTPS case |
| 6035 |
// so just check that the command was correct |
| 6036 |
|
| 6037 |
QString receivedHeader = proxyServer->receivedData.left(expectedCommand.length()); |
| 6038 |
QCOMPARE(receivedHeader, expectedCommand); |
| 6039 |
} |
| 6040 |
|
| 6041 |
void tst_QNetworkReply::proxyChange() |
| 6042 |
{ |
| 6043 |
ProxyChangeHelper helper; |
| 6044 |
MiniHttpServer proxyServer( |
| 6045 |
"HTTP/1.0 200 OK\r\nProxy-Connection: keep-alive\r\n" |
| 6046 |
"Content-Length: 1\r\n\r\n1"); |
| 6047 |
QNetworkProxy dummyProxy(QNetworkProxy::HttpProxy, "127.0.0.1", proxyServer.serverPort()); |
| 6048 |
QNetworkRequest req(QUrl("http://" + QtNetworkSettings::httpServerName())); |
| 6049 |
proxyServer.doClose = false; |
| 6050 |
|
| 6051 |
{ |
| 6052 |
// Needed to initialize a network session in QNAM. Without an initialized session the GET |
| 6053 |
// will be deferred until later, and the proxy will be unset first. This caused the test to |
| 6054 |
// fail in standalone runs (it passed in CI because the same QNAM instance is used for the |
| 6055 |
// entire test). |
| 6056 |
QNetworkReplyPtr temporary(manager.get(req)); |
| 6057 |
waitForFinish(temporary); |
| 6058 |
} |
| 6059 |
|
| 6060 |
manager.setProxy(dummyProxy); |
| 6061 |
QNetworkReplyPtr reply1(manager.get(req)); |
| 6062 |
connect(reply1, SIGNAL(finished()), &helper, SLOT(finishedSlot())); |
| 6063 |
|
| 6064 |
manager.setProxy(QNetworkProxy()); |
| 6065 |
QNetworkReplyPtr reply2(manager.get(req)); |
| 6066 |
connect(reply2, SIGNAL(finished()), &helper, SLOT(finishedSlot())); |
| 6067 |
|
| 6068 |
QTestEventLoop::instance().enterLoop(20); |
| 6069 |
QVERIFY(!QTestEventLoop::instance().timeout()); |
| 6070 |
|
| 6071 |
// verify that the replies succeeded |
| 6072 |
QCOMPARE(reply1->error(), QNetworkReply::NoError); |
| 6073 |
QCOMPARE(reply1->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200); |
| 6074 |
QCOMPARE(reply1->size(), 1); |
| 6075 |
|
| 6076 |
QCOMPARE(reply2->error(), QNetworkReply::NoError); |
| 6077 |
QCOMPARE(reply2->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200); |
| 6078 |
QVERIFY(reply2->size() > 1); |
| 6079 |
|
| 6080 |
// now try again and get an error |
| 6081 |
// this verifies that we reuse the already-open connection |
| 6082 |
|
| 6083 |
proxyServer.doClose = true; |
| 6084 |
proxyServer.dataToTransmit = |
| 6085 |
"HTTP/1.0 403 Forbidden\r\nProxy-Connection: close\r\n" |
| 6086 |
"Content-Length: 1\r\n\r\n1"; |
| 6087 |
|
| 6088 |
manager.setProxy(dummyProxy); |
| 6089 |
QNetworkReplyPtr reply3(manager.get(req)); |
| 6090 |
|
| 6091 |
QCOMPARE(waitForFinish(reply3), int(Failure)); |
| 6092 |
|
| 6093 |
QVERIFY(int(reply3->error()) > 0); |
| 6094 |
} |
| 6095 |
#endif // !QT_NO_NETWORKPROXY |
| 6096 |
|
| 6097 |
void tst_QNetworkReply::authorizationError_data() |
| 6098 |
{ |
| 6099 |
|
| 6100 |
QTest::addColumn<QString>("url"); |
| 6101 |
QTest::addColumn<int>("errorSignalCount"); |
| 6102 |
QTest::addColumn<int>("finishedSignalCount"); |
| 6103 |
QTest::addColumn<int>("error"); |
| 6104 |
QTest::addColumn<int>("httpStatusCode"); |
| 6105 |
QTest::addColumn<QString>("httpBody"); |
| 6106 |
|
| 6107 |
QTest::newRow("unknown-authorization-method") |
| 6108 |
<< "http://" + QtNetworkSettings::httpServerName() |
| 6109 |
+ "/qtest/cgi-bin/http-unknown-authentication-method.cgi?401-authorization-required" |
| 6110 |
<< 1 << 1 << int(QNetworkReply::AuthenticationRequiredError) |
| 6111 |
<< 401 << "authorization required"; |
| 6112 |
|
| 6113 |
QTest::newRow("unknown-proxy-authorization-method") |
| 6114 |
<< "http://" + QtNetworkSettings::httpServerName() |
| 6115 |
+ "/qtest/cgi-bin/http-unknown-authentication-method.cgi?407-proxy-authorization-required" |
| 6116 |
<< 1 << 1 << int(QNetworkReply::ProxyAuthenticationRequiredError) |
| 6117 |
<< 407 << "authorization required"; |
| 6118 |
} |
| 6119 |
|
| 6120 |
void tst_QNetworkReply::authorizationError() |
| 6121 |
{ |
| 6122 |
QFETCH(QString, url); |
| 6123 |
QNetworkRequest request(url); |
| 6124 |
QNetworkReplyPtr reply(manager.get(request)); |
| 6125 |
|
| 6126 |
QCOMPARE(reply->error(), QNetworkReply::NoError); |
| 6127 |
|
| 6128 |
QSignalSpy errorSpy(reply.data(), SIGNAL(errorOccurred(QNetworkReply::NetworkError))); |
| 6129 |
QSignalSpy finishedSpy(reply.data(), SIGNAL(finished())); |
| 6130 |
// now run the request: |
| 6131 |
QCOMPARE(waitForFinish(reply), int(Failure)); |
| 6132 |
|
| 6133 |
QFETCH(int, errorSignalCount); |
| 6134 |
QCOMPARE(errorSpy.count(), errorSignalCount); |
| 6135 |
QFETCH(int, finishedSignalCount); |
| 6136 |
QCOMPARE(finishedSpy.count(), finishedSignalCount); |
| 6137 |
QFETCH(int, error); |
| 6138 |
QCOMPARE(reply->error(), QNetworkReply::NetworkError(error)); |
| 6139 |
|
| 6140 |
QFETCH(int, httpStatusCode); |
| 6141 |
QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), httpStatusCode); |
| 6142 |
|
| 6143 |
QFETCH(QString, httpBody); |
| 6144 |
QCOMPARE(qint64(reply->size()), qint64(httpBody.size())); |
| 6145 |
QCOMPARE(QString(reply->readAll()), httpBody); |
| 6146 |
} |
| 6147 |
|
| 6148 |
void tst_QNetworkReply::httpConnectionCount() |
| 6149 |
{ |
| 6150 |
QTcpServer server; |
| 6151 |
QVERIFY(server.listen()); |
| 6152 |
QCoreApplication::instance()->processEvents(); |
| 6153 |
|
| 6154 |
for (int i = 0; i < 10; i++) { |
| 6155 |
QNetworkRequest request (QUrl("http://127.0.0.1:" + QString::number(server.serverPort()) + QLatin1Char('/') + QString::number(i))); |
| 6156 |
QNetworkReply* reply = manager.get(request); |
| 6157 |
reply->setParent(&server); |
| 6158 |
} |
| 6159 |
|
| 6160 |
int pendingConnectionCount = 0; |
| 6161 |
QElapsedTimer timer; |
| 6162 |
timer.start(); |
| 6163 |
|
| 6164 |
while(pendingConnectionCount <= 20) { |
| 6165 |
QTestEventLoop::instance().enterLoop(1); |
| 6166 |
QTcpSocket *socket = server.nextPendingConnection(); |
| 6167 |
while (socket != 0) { |
| 6168 |
pendingConnectionCount++; |
| 6169 |
socket->setParent(&server); |
| 6170 |
socket = server.nextPendingConnection(); |
| 6171 |
} |
| 6172 |
|
| 6173 |
// at max. wait 10 sec |
| 6174 |
if (timer.elapsed() > 10000) |
| 6175 |
break; |
| 6176 |
} |
| 6177 |
|
| 6178 |
QCOMPARE(pendingConnectionCount, 6); |
| 6179 |
} |
| 6180 |
|
| 6181 |
void tst_QNetworkReply::httpReUsingConnectionSequential_data() |
| 6182 |
{ |
| 6183 |
QTest::addColumn<bool>("doDeleteLater"); |
| 6184 |
QTest::newRow("deleteLater") << true; |
| 6185 |
QTest::newRow("noDeleteLater") << false; |
| 6186 |
} |
| 6187 |
|
| 6188 |
void tst_QNetworkReply::httpReUsingConnectionSequential() |
| 6189 |
{ |
| 6190 |
QFETCH(bool, doDeleteLater); |
| 6191 |
|
| 6192 |
QByteArray response("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n"); |
| 6193 |
MiniHttpServer server(response); |
| 6194 |
server.multiple = true; |
| 6195 |
server.doClose = false; |
| 6196 |
|
| 6197 |
QUrl url; |
| 6198 |
url.setScheme("http"); |
| 6199 |
url.setPort(server.serverPort()); |
| 6200 |
url.setHost("127.0.0.1"); |
| 6201 |
// first request |
| 6202 |
QNetworkReply* reply1 = manager.get(QNetworkRequest(url)); |
| 6203 |
connect(reply1, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop())); |
| 6204 |
QTestEventLoop::instance().enterLoop(2); |
| 6205 |
QVERIFY(!QTestEventLoop::instance().timeout()); |
| 6206 |
QVERIFY(!reply1->error()); |
| 6207 |
int reply1port = server.client->peerPort(); |
| 6208 |
|
| 6209 |
if (doDeleteLater) |
| 6210 |
reply1->deleteLater(); |
| 6211 |
|
| 6212 |
// finished received, send the next one |
| 6213 |
QNetworkReply*reply2 = manager.get(QNetworkRequest(url)); |
| 6214 |
connect(reply2, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop())); |
| 6215 |
QTestEventLoop::instance().enterLoop(2); |
| 6216 |
QVERIFY(!QTestEventLoop::instance().timeout()); |
| 6217 |
QVERIFY(!reply2->error()); |
| 6218 |
int reply2port = server.client->peerPort(); // should still be the same object |
| 6219 |
|
| 6220 |
QVERIFY(reply1port > 0); |
| 6221 |
QCOMPARE(server.totalConnections, 1); |
| 6222 |
QCOMPARE(reply2port, reply1port); |
| 6223 |
|
| 6224 |
if (!doDeleteLater) |
| 6225 |
reply1->deleteLater(); // only do it if it was not done earlier |
| 6226 |
reply2->deleteLater(); |
| 6227 |
} |
| 6228 |
|
| 6229 |
class HttpReUsingConnectionFromFinishedSlot : public QObject |
| 6230 |
{ |
| 6231 |
Q_OBJECT |
| 6232 |
public: |
| 6233 |
QNetworkReply* reply1; |
| 6234 |
QNetworkReply* reply2; |
| 6235 |
QUrl url; |
| 6236 |
QNetworkAccessManager manager; |
| 6237 |
public slots: |
| 6238 |
void finishedSlot() |
| 6239 |
{ |
| 6240 |
QVERIFY(!reply1->error()); |
| 6241 |
|
| 6242 |
QFETCH(bool, doDeleteLater); |
| 6243 |
if (doDeleteLater) { |
| 6244 |
reply1->deleteLater(); |
| 6245 |
reply1 = 0; |
| 6246 |
} |
| 6247 |
|
| 6248 |
// kick off 2nd request and exit the loop when it is done |
| 6249 |
reply2 = manager.get(QNetworkRequest(url)); |
| 6250 |
reply2->setParent(this); |
| 6251 |
connect(reply2, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop())); |
| 6252 |
} |
| 6253 |
}; |
| 6254 |
|
| 6255 |
void tst_QNetworkReply::httpReUsingConnectionFromFinishedSlot_data() |
| 6256 |
{ |
| 6257 |
httpReUsingConnectionSequential_data(); |
| 6258 |
} |
| 6259 |
|
| 6260 |
void tst_QNetworkReply::httpReUsingConnectionFromFinishedSlot() |
| 6261 |
{ |
| 6262 |
QByteArray response("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n"); |
| 6263 |
MiniHttpServer server(response); |
| 6264 |
server.multiple = true; |
| 6265 |
server.doClose = false; |
| 6266 |
|
| 6267 |
HttpReUsingConnectionFromFinishedSlot helper; |
| 6268 |
helper.reply1 = 0; |
| 6269 |
helper.reply2 = 0; |
| 6270 |
helper.url.setScheme("http"); |
| 6271 |
helper.url.setPort(server.serverPort()); |
| 6272 |
helper.url.setHost("127.0.0.1"); |
| 6273 |
|
| 6274 |
// first request |
| 6275 |
helper.reply1 = helper.manager.get(QNetworkRequest(helper.url)); |
| 6276 |
helper.reply1->setParent(&helper); |
| 6277 |
connect(helper.reply1, SIGNAL(finished()), &helper, SLOT(finishedSlot())); |
| 6278 |
QTestEventLoop::instance().enterLoop(4); |
| 6279 |
QVERIFY(!QTestEventLoop::instance().timeout()); |
| 6280 |
|
| 6281 |
QVERIFY(helper.reply2); |
| 6282 |
QVERIFY(!helper.reply2->error()); |
| 6283 |
|
| 6284 |
QCOMPARE(server.totalConnections, 1); |
| 6285 |
} |
| 6286 |
|
| 6287 |
class HttpRecursiveCreationHelper : public QObject |
| 6288 |
{ |
| 6289 |
Q_OBJECT |
| 6290 |
public: |
| 6291 |
|
| 6292 |
HttpRecursiveCreationHelper(): |
| 6293 |
QObject(0), |
| 6294 |
requestsStartedCount_finished(0), |
| 6295 |
requestsStartedCount_readyRead(0), |
| 6296 |
requestsFinishedCount(0) |
| 6297 |
{ |
| 6298 |
} |
| 6299 |
QNetworkAccessManager manager; |
| 6300 |
int requestsStartedCount_finished; |
| 6301 |
int requestsStartedCount_readyRead; |
| 6302 |
int requestsFinishedCount; |
| 6303 |
public slots: |
| 6304 |
void finishedSlot() |
| 6305 |
{ |
| 6306 |
requestsFinishedCount++; |
| 6307 |
|
| 6308 |
QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender()); |
| 6309 |
QVERIFY(!reply->error()); |
| 6310 |
QCOMPARE(reply->bytesAvailable(), 27906); |
| 6311 |
|
| 6312 |
if (requestsFinishedCount == 60) { |
| 6313 |
QTestEventLoop::instance().exitLoop(); |
| 6314 |
return; |
| 6315 |
} |
| 6316 |
|
| 6317 |
if (requestsStartedCount_finished < 30) { |
| 6318 |
startOne(); |
| 6319 |
requestsStartedCount_finished++; |
| 6320 |
} |
| 6321 |
|
| 6322 |
reply->deleteLater(); |
| 6323 |
} |
| 6324 |
void readyReadSlot() |
| 6325 |
{ |
| 6326 |
QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender()); |
| 6327 |
QVERIFY(!reply->error()); |
| 6328 |
|
| 6329 |
if (requestsStartedCount_readyRead < 30 && reply->bytesAvailable() > 27906/2) { |
| 6330 |
startOne(); |
| 6331 |
requestsStartedCount_readyRead++; |
| 6332 |
} |
| 6333 |
} |
| 6334 |
void startOne() |
| 6335 |
{ |
| 6336 |
QUrl url = "http://" + QtNetworkSettings::httpServerName() + "/qtest/fluke.gif"; |
| 6337 |
QNetworkRequest request(url); |
| 6338 |
QNetworkReply *reply = manager.get(request); |
| 6339 |
reply->setParent(this); |
| 6340 |
connect(reply, SIGNAL(finished()), this, SLOT(finishedSlot())); |
| 6341 |
connect(reply, SIGNAL(readyRead()), this, SLOT(readyReadSlot())); |
| 6342 |
} |
| 6343 |
}; |
| 6344 |
|
| 6345 |
void tst_QNetworkReply::httpRecursiveCreation() |
| 6346 |
{ |
| 6347 |
// this test checks if creation of new requests to the same host properly works |
| 6348 |
// from readyRead() and finished() signals |
| 6349 |
HttpRecursiveCreationHelper helper; |
| 6350 |
helper.startOne(); |
| 6351 |
QTestEventLoop::instance().enterLoop(30); |
| 6352 |
QVERIFY(!QTestEventLoop::instance().timeout()); |
| 6353 |
} |
| 6354 |
|
| 6355 |
#ifndef QT_NO_SSL |
| 6356 |
void tst_QNetworkReply::ignoreSslErrorsList_data() |
| 6357 |
{ |
| 6358 |
QTest::addColumn<QList<QSslError> >("expectedSslErrors"); |
| 6359 |
QTest::addColumn<QNetworkReply::NetworkError>("expectedNetworkError"); |
| 6360 |
|
| 6361 |
QList<QSslError> expectedSslErrors; |
| 6362 |
QList<QSslCertificate> certs = QSslCertificate::fromPath(testDataDir + certsFilePath); |
| 6363 |
QSslError rightError(FLUKE_CERTIFICATE_ERROR, certs.at(0)); |
| 6364 |
QSslError wrongError(FLUKE_CERTIFICATE_ERROR); |
| 6365 |
|
| 6366 |
QTest::newRow("SSL-failure-empty-list") << expectedSslErrors << QNetworkReply::SslHandshakeFailedError; |
| 6367 |
expectedSslErrors.append(wrongError); |
| 6368 |
QTest::newRow("SSL-failure-wrong-error") << expectedSslErrors << QNetworkReply::SslHandshakeFailedError; |
| 6369 |
expectedSslErrors.append(rightError); |
| 6370 |
QTest::newRow("allErrorsInExpectedList1") << expectedSslErrors << QNetworkReply::NoError; |
| 6371 |
expectedSslErrors.removeAll(wrongError); |
| 6372 |
QTest::newRow("allErrorsInExpectedList2") << expectedSslErrors << QNetworkReply::NoError; |
| 6373 |
expectedSslErrors.removeAll(rightError); |
| 6374 |
QTest::newRow("SSL-failure-empty-list-again") << expectedSslErrors << QNetworkReply::SslHandshakeFailedError; |
| 6375 |
} |
| 6376 |
|
| 6377 |
void tst_QNetworkReply::ignoreSslErrorsList() |
| 6378 |
{ |
| 6379 |
QString url(QLatin1String("https://") + QtNetworkSettings::httpServerName() + QLatin1String("/index.html")); |
| 6380 |
QNetworkRequest request(url); |
| 6381 |
QNetworkReplyPtr reply(manager.get(request)); |
| 6382 |
|
| 6383 |
QFETCH(QList<QSslError>, expectedSslErrors); |
| 6384 |
reply->ignoreSslErrors(expectedSslErrors); |
| 6385 |
|
| 6386 |
QVERIFY(waitForFinish(reply) != Timeout); |
| 6387 |
|
| 6388 |
QFETCH(QNetworkReply::NetworkError, expectedNetworkError); |
| 6389 |
QCOMPARE(reply->error(), expectedNetworkError); |
| 6390 |
} |
| 6391 |
|
| 6392 |
void tst_QNetworkReply::ignoreSslErrorsListWithSlot_data() |
| 6393 |
{ |
| 6394 |
ignoreSslErrorsList_data(); |
| 6395 |
} |
| 6396 |
|
| 6397 |
// this is not a test, just a slot called in the test below |
| 6398 |
void tst_QNetworkReply::ignoreSslErrorListSlot(QNetworkReply *reply, const QList<QSslError> &) |
| 6399 |
{ |
| 6400 |
reply->ignoreSslErrors(storedExpectedSslErrors); |
| 6401 |
} |
| 6402 |
|
| 6403 |
// do the same as in ignoreSslErrorsList, but ignore the errors in the slot |
| 6404 |
void tst_QNetworkReply::ignoreSslErrorsListWithSlot() |
| 6405 |
{ |
| 6406 |
QString url(QLatin1String("https://") + QtNetworkSettings::httpServerName() + QLatin1String("/index.html")); |
| 6407 |
QNetworkRequest request(url); |
| 6408 |
QNetworkReplyPtr reply(manager.get(request)); |
| 6409 |
|
| 6410 |
QFETCH(QList<QSslError>, expectedSslErrors); |
| 6411 |
// store the errors to ignore them later in the slot connected below |
| 6412 |
storedExpectedSslErrors = expectedSslErrors; |
| 6413 |
connect(&manager, SIGNAL(sslErrors(QNetworkReply*,QList<QSslError>)), |
| 6414 |
this, SLOT(ignoreSslErrorListSlot(QNetworkReply*,QList<QSslError>))); |
| 6415 |
|
| 6416 |
|
| 6417 |
QVERIFY(waitForFinish(reply) != Timeout); |
| 6418 |
|
| 6419 |
QFETCH(QNetworkReply::NetworkError, expectedNetworkError); |
| 6420 |
QCOMPARE(reply->error(), expectedNetworkError); |
| 6421 |
} |
| 6422 |
|
| 6423 |
void tst_QNetworkReply::sslConfiguration_data() |
| 6424 |
{ |
| 6425 |
QTest::addColumn<QSslConfiguration>("configuration"); |
| 6426 |
QTest::addColumn<bool>("works"); |
| 6427 |
|
| 6428 |
QTest::newRow("empty") << QSslConfiguration() << false; |
| 6429 |
QSslConfiguration conf = QSslConfiguration::defaultConfiguration(); |
| 6430 |
QTest::newRow("default") << conf << false; // does not contain test server cert |
| 6431 |
QList<QSslCertificate> testServerCert = QSslCertificate::fromPath(testDataDir + certsFilePath); |
| 6432 |
conf.setCaCertificates(testServerCert); |
| 6433 |
QTest::newRow("set-root-cert") << conf << true; |
| 6434 |
conf.setProtocol(QSsl::SecureProtocols); |
| 6435 |
QTest::newRow("secure") << conf << true; |
| 6436 |
} |
| 6437 |
|
| 6438 |
void tst_QNetworkReply::encrypted() |
| 6439 |
{ |
| 6440 |
qDebug() << QtNetworkSettings::httpServerName(); |
| 6441 |
QUrl url("https://" + QtNetworkSettings::httpServerName()); |
| 6442 |
QNetworkRequest request(url); |
| 6443 |
QNetworkReply *reply = manager.get(request); |
| 6444 |
reply->ignoreSslErrors(); |
| 6445 |
|
| 6446 |
QSignalSpy spy(reply, SIGNAL(encrypted())); |
| 6447 |
connect(reply, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop())); |
| 6448 |
QTestEventLoop::instance().enterLoop(20); |
| 6449 |
QVERIFY(!QTestEventLoop::instance().timeout()); |
| 6450 |
|
| 6451 |
QCOMPARE(spy.count(), 1); |
| 6452 |
|
| 6453 |
reply->deleteLater(); |
| 6454 |
} |
| 6455 |
|
| 6456 |
void tst_QNetworkReply::abortOnEncrypted() |
| 6457 |
{ |
| 6458 |
SslServer server; |
| 6459 |
server.listen(); |
| 6460 |
if (!server.isListening()) |
| 6461 |
QSKIP("Server fails to listen. Skipping since QTcpServer is covered in another test."); |
| 6462 |
|
| 6463 |
server.connect(&server, &SslServer::newEncryptedConnection, [&server]() { |
| 6464 |
// MSVC 201X C4573-misunderstands connect() or QObject::connect(), so use server.connect(): |
| 6465 |
server.connect(server.socket, &QTcpSocket::readyRead, server.socket, []() { |
| 6466 |
// This slot must not be invoked! |
| 6467 |
QVERIFY(false); |
| 6468 |
}); |
| 6469 |
}); |
| 6470 |
|
| 6471 |
QNetworkAccessManager nm; |
| 6472 |
QNetworkReply *reply = nm.get(QNetworkRequest(QUrl(QString("https://localhost:%1").arg(server.serverPort())))); |
| 6473 |
reply->ignoreSslErrors(); |
| 6474 |
|
| 6475 |
connect(reply, &QNetworkReply::encrypted, [reply, &nm]() { |
| 6476 |
reply->abort(); |
| 6477 |
nm.clearConnectionCache(); |
| 6478 |
}); |
| 6479 |
|
| 6480 |
QSignalSpy spyEncrypted(reply, &QNetworkReply::encrypted); |
| 6481 |
QTRY_COMPARE(spyEncrypted.count(), 1); |
| 6482 |
|
| 6483 |
// Wait for the socket to be closed again in order to be sure QTcpSocket::readyRead would have been emitted. |
| 6484 |
QTRY_VERIFY(server.socket != nullptr); |
| 6485 |
QTRY_COMPARE(server.socket->state(), QAbstractSocket::UnconnectedState); |
| 6486 |
} |
| 6487 |
|
| 6488 |
void tst_QNetworkReply::sslConfiguration() |
| 6489 |
{ |
| 6490 |
QNetworkRequest request(QUrl("https://" + QtNetworkSettings::httpServerName() + "/index.html")); |
| 6491 |
QFETCH(QSslConfiguration, configuration); |
| 6492 |
request.setSslConfiguration(configuration); |
| 6493 |
QNetworkReplyPtr reply(manager.get(request)); |
| 6494 |
|
| 6495 |
QVERIFY(waitForFinish(reply) != Timeout); |
| 6496 |
|
| 6497 |
QFETCH(bool, works); |
| 6498 |
QNetworkReply::NetworkError expectedError = works ? QNetworkReply::NoError : QNetworkReply::SslHandshakeFailedError; |
| 6499 |
QCOMPARE(reply->error(), expectedError); |
| 6500 |
} |
| 6501 |
|
| 6502 |
#ifdef QT_BUILD_INTERNAL |
| 6503 |
|
| 6504 |
void tst_QNetworkReply::sslSessionSharing_data() |
| 6505 |
{ |
| 6506 |
QTest::addColumn<bool>("sessionSharingEnabled"); |
| 6507 |
QTest::newRow("enabled") << true; |
| 6508 |
QTest::newRow("disabled") << false; |
| 6509 |
} |
| 6510 |
|
| 6511 |
void tst_QNetworkReply::sslSessionSharing() |
| 6512 |
{ |
| 6513 |
#if QT_CONFIG(schannel) || defined(QT_SECURETRANSPORT) |
| 6514 |
QSKIP("Not implemented with SecureTransport/Schannel"); |
| 6515 |
#endif |
| 6516 |
|
| 6517 |
QString urlString("https://" + QtNetworkSettings::httpServerName()); |
| 6518 |
QList<QNetworkReplyPtr> replies; |
| 6519 |
|
| 6520 |
// warm up SSL session cache |
| 6521 |
QNetworkRequest warmupRequest(urlString); |
| 6522 |
QFETCH(bool, sessionSharingEnabled); |
| 6523 |
warmupRequest.setAttribute(QNetworkRequest::User, sessionSharingEnabled); // so we can read it from the slot |
| 6524 |
// Make sure the socket is closed when the request is finished to guarantee that |
| 6525 |
// the _socket_ is not reused, but rather the ssl session |
| 6526 |
warmupRequest.setRawHeader("Connection", "close"); |
| 6527 |
if (! sessionSharingEnabled) { |
| 6528 |
QSslConfiguration configuration(QSslConfiguration::defaultConfiguration()); |
| 6529 |
configuration.setSslOption(QSsl::SslOptionDisableSessionSharing, true); |
| 6530 |
warmupRequest.setSslConfiguration(configuration); |
| 6531 |
} |
| 6532 |
QNetworkReply *reply = manager.get(warmupRequest); |
| 6533 |
reply->ignoreSslErrors(); |
| 6534 |
connect(reply, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop())); |
| 6535 |
QTestEventLoop::instance().enterLoop(20); |
| 6536 |
QVERIFY(!QTestEventLoop::instance().timeout()); |
| 6537 |
QCOMPARE(reply->error(), QNetworkReply::NoError); |
| 6538 |
reply->deleteLater(); |
| 6539 |
|
| 6540 |
// now send several requests at the same time, so we open more sockets and reuse the SSL session |
| 6541 |
for (int a = 0; a < 6; a++) { |
| 6542 |
QNetworkRequest request(warmupRequest); |
| 6543 |
replies.append(QNetworkReplyPtr(manager.get(request))); |
| 6544 |
connect(replies.at(a), SIGNAL(finished()), this, SLOT(sslSessionSharingHelperSlot())); |
| 6545 |
} |
| 6546 |
QTestEventLoop::instance().enterLoop(20); |
| 6547 |
QVERIFY(!QTestEventLoop::instance().timeout()); |
| 6548 |
} |
| 6549 |
|
| 6550 |
void tst_QNetworkReply::sslSessionSharingHelperSlot() |
| 6551 |
{ |
| 6552 |
static int count = 0; |
| 6553 |
|
| 6554 |
// check that SSL session sharing was used in at least one of the replies |
| 6555 |
static bool sslSessionSharingWasUsed = false; |
| 6556 |
QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender()); |
| 6557 |
bool sslSessionSharingWasUsedInReply = QSslConfigurationPrivate::peerSessionWasShared(reply->sslConfiguration()); |
| 6558 |
if (sslSessionSharingWasUsedInReply) |
| 6559 |
sslSessionSharingWasUsed = true; |
| 6560 |
|
| 6561 |
QString urlQueryString = reply->url().query(); |
| 6562 |
QCOMPARE(reply->error(), QNetworkReply::NoError); |
| 6563 |
|
| 6564 |
count++; |
| 6565 |
|
| 6566 |
if (count == 6) { // all replies have finished |
| 6567 |
QTestEventLoop::instance().exitLoop(); |
| 6568 |
bool sessionSharingWasEnabled = reply->request().attribute(QNetworkRequest::User).toBool(); |
| 6569 |
QCOMPARE(sslSessionSharingWasUsed, sessionSharingWasEnabled); |
| 6570 |
count = 0; // reset for next row |
| 6571 |
sslSessionSharingWasUsed = false; // reset for next row |
| 6572 |
} |
| 6573 |
} |
| 6574 |
|
| 6575 |
void tst_QNetworkReply::sslSessionSharingFromPersistentSession_data() |
| 6576 |
{ |
| 6577 |
QTest::addColumn<bool>("sessionPersistenceEnabled"); |
| 6578 |
QTest::newRow("enabled") << true; |
| 6579 |
QTest::newRow("disabled") << false; |
| 6580 |
} |
| 6581 |
|
| 6582 |
void tst_QNetworkReply::sslSessionSharingFromPersistentSession() |
| 6583 |
{ |
| 6584 |
#if QT_CONFIG(schannel) || defined(QT_SECURETRANSPORT) |
| 6585 |
QSKIP("Not implemented with SecureTransport/Schannel"); |
| 6586 |
#endif |
| 6587 |
|
| 6588 |
QString urlString("https://" + QtNetworkSettings::httpServerName()); |
| 6589 |
|
| 6590 |
// warm up SSL session cache to get a working session |
| 6591 |
QNetworkRequest warmupRequest(urlString); |
| 6592 |
QFETCH(bool, sessionPersistenceEnabled); |
| 6593 |
if (sessionPersistenceEnabled) { |
| 6594 |
QSslConfiguration warmupConfiguration(QSslConfiguration::defaultConfiguration()); |
| 6595 |
warmupConfiguration.setSslOption(QSsl::SslOptionDisableSessionPersistence, false); |
| 6596 |
warmupRequest.setSslConfiguration(warmupConfiguration); |
| 6597 |
} |
| 6598 |
QNetworkReply *warmupReply = manager.get(warmupRequest); |
| 6599 |
warmupReply->ignoreSslErrors(); |
| 6600 |
connect(warmupReply, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop())); |
| 6601 |
QTestEventLoop::instance().enterLoop(20); |
| 6602 |
QVERIFY(!QTestEventLoop::instance().timeout()); |
| 6603 |
QCOMPARE(warmupReply->error(), QNetworkReply::NoError); |
| 6604 |
QByteArray sslSession = warmupReply->sslConfiguration().sessionTicket(); |
| 6605 |
QCOMPARE(!sslSession.isEmpty(), sessionPersistenceEnabled); |
| 6606 |
|
| 6607 |
// test server sends a life time hint of 0 (old server) or 300 (new server), |
| 6608 |
// without session ticket we get -1 |
| 6609 |
QList<int> expectedSessionTicketLifeTimeHint = sessionPersistenceEnabled |
| 6610 |
? QList<int>() << 0 << 300 : QList<int>() << -1; |
| 6611 |
QVERIFY2(expectedSessionTicketLifeTimeHint.contains( |
| 6612 |
warmupReply->sslConfiguration().sessionTicketLifeTimeHint()), |
| 6613 |
"server did not send expected session life time hint"); |
| 6614 |
|
| 6615 |
warmupReply->deleteLater(); |
| 6616 |
|
| 6617 |
// now send another request with a new QNAM and the persisted session, |
| 6618 |
// to verify it can be resumed without any internal state |
| 6619 |
QNetworkRequest request(warmupRequest); |
| 6620 |
if (sessionPersistenceEnabled) { |
| 6621 |
QSslConfiguration configuration = request.sslConfiguration(); |
| 6622 |
configuration.setSessionTicket(sslSession); |
| 6623 |
request.setSslConfiguration(configuration); |
| 6624 |
} |
| 6625 |
QNetworkAccessManager newManager; |
| 6626 |
QNetworkReply *reply = newManager.get(request); |
| 6627 |
reply->ignoreSslErrors(); |
| 6628 |
connect(reply, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop())); |
| 6629 |
QTestEventLoop::instance().enterLoop(20); |
| 6630 |
QVERIFY(!QTestEventLoop::instance().timeout()); |
| 6631 |
QCOMPARE(reply->error(), QNetworkReply::NoError); |
| 6632 |
|
| 6633 |
bool sslSessionSharingWasUsedInReply = QSslConfigurationPrivate::peerSessionWasShared( |
| 6634 |
reply->sslConfiguration()); |
| 6635 |
QCOMPARE(sessionPersistenceEnabled, sslSessionSharingWasUsedInReply); |
| 6636 |
} |
| 6637 |
|
| 6638 |
#endif // QT_BUILD_INTERNAL |
| 6639 |
#endif // QT_NO_SSL |
| 6640 |
|
| 6641 |
void tst_QNetworkReply::getAndThenDeleteObject_data() |
| 6642 |
{ |
| 6643 |
QTest::addColumn<bool>("replyFirst"); |
| 6644 |
|
| 6645 |
QTest::newRow("delete-reply-first") << true; |
| 6646 |
QTest::newRow("delete-qnam-first") << false; |
| 6647 |
} |
| 6648 |
|
| 6649 |
void tst_QNetworkReply::getAndThenDeleteObject() |
| 6650 |
{ |
| 6651 |
QSKIP("unstable test - reply may be finished too early"); |
| 6652 |
// yes, this will leak if the testcase fails. I don't care. It must not fail then :P |
| 6653 |
QNetworkAccessManager *manager = new QNetworkAccessManager(); |
| 6654 |
QNetworkRequest request("http://" + QtNetworkSettings::httpServerName() + "/qtest/bigfile"); |
| 6655 |
QNetworkReply *reply = manager->get(request); |
| 6656 |
reply->setReadBufferSize(1); |
| 6657 |
reply->setParent((QObject*)0); // must be 0 because else it is the manager |
| 6658 |
|
| 6659 |
QTRY_VERIFY_WITH_TIMEOUT(reply->bytesAvailable(), 30000); |
| 6660 |
QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200); |
| 6661 |
QVERIFY(!reply->isFinished()); // must not be finished |
| 6662 |
|
| 6663 |
QFETCH(bool, replyFirst); |
| 6664 |
|
| 6665 |
if (replyFirst) { |
| 6666 |
delete reply; |
| 6667 |
delete manager; |
| 6668 |
} else { |
| 6669 |
delete manager; |
| 6670 |
delete reply; |
| 6671 |
} |
| 6672 |
} |
| 6673 |
|
| 6674 |
// see https://bugs.webkit.org/show_bug.cgi?id=38935 |
| 6675 |
void tst_QNetworkReply::symbianOpenCDataUrlCrash() |
| 6676 |
{ |
| 6677 |
QString requestUrl("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABkAAAAWCAYAAAA1vze2AAAAB3RJTUUH2AUSEgolrgBvVQAAAAlwSFlzAAALEwAACxMBAJqcGAAAAARnQU1BAACxjwv8YQUAAAHlSURBVHja5VbNShxBEK6ZaXtnHTebQPA1gngNmfaeq+QNPIlIXkC9iQdJxJNvEHLN3VkxhxxE8gTmEhAVddXZ6Z3f9Ndriz89/sHmkBQUVVT1fB9d9c3uOERUKTunIdn3HzstxGpYBDS4wZk7TAJj/wlJ90J+jnuygqs8svSj+/rGHBos3rE18XBvfU3no7NzlJfUaY/5whAwl8Lr/WDUv4ODxTMb+P5xLExe5LmO559WqTX/MQR4WZYEAtSePS4pE0qSnuhnRUcBU5Gm2k9XljU4Z26I3NRxBrd80rj2fh+KNE0FY4xevRgTjREvPFpasAK8Xli6MUbbuKw3afAGgSBXozo5u4hkmncAlkl5wx8iMGbdyQjnCFEiEwGiosj1UQA/x2rVddiVoi+l4IxE0PTDnx+mrQBvvnx9cFz3krhVvuhzFn579/aq/n5rW8fbtTqiWhIQZEo17YBvbkxOXNVndnYpTvod7AtiuN2re0+siwcB9oH8VxxrNwQQAhzyRs30n7wTI2HIN2g2QtQwjjhJIQatOq7E8bIVCLwzpl83Lvtvl+NohWWlE8UZTWEMAGCcR77fHKhPnZF5tYie6dfdxCphACmLPM+j8bYfmTryg64kV9Vh3mV8jP0b/4wO/YUPiT/8i0MLf55lSQAAAABJRU5ErkJggg=="); |
| 6678 |
QUrl url = QUrl::fromEncoded(requestUrl.toLatin1()); |
| 6679 |
QNetworkRequest req(url); |
| 6680 |
QNetworkReplyPtr reply; |
| 6681 |
|
| 6682 |
RUN_REQUEST(runSimpleRequest(QNetworkAccessManager::GetOperation, req, reply)); |
| 6683 |
|
| 6684 |
QCOMPARE(reply->url(), url); |
| 6685 |
QCOMPARE(reply->error(), QNetworkReply::NoError); |
| 6686 |
|
| 6687 |
QCOMPARE(reply->header(QNetworkRequest::ContentLengthHeader).toLongLong(), qint64(598)); |
| 6688 |
} |
| 6689 |
|
| 6690 |
void tst_QNetworkReply::getFromHttpIntoBuffer_data() |
| 6691 |
{ |
| 6692 |
QTest::addColumn<QUrl>("url"); |
| 6693 |
|
| 6694 |
QTest::newRow("rfc-internal") << QUrl("http://" + QtNetworkSettings::httpServerName() + "/qtest/rfc3252.txt"); |
| 6695 |
} |
| 6696 |
|
| 6697 |
// Please note that the whole "zero copy" download buffer API is private right now. Do not use it. |
| 6698 |
void tst_QNetworkReply::getFromHttpIntoBuffer() |
| 6699 |
{ |
| 6700 |
QFETCH(QUrl, url); |
| 6701 |
QNetworkRequest request(url); |
| 6702 |
request.setAttribute(QNetworkRequest::MaximumDownloadBufferSizeAttribute, 1024*128); // 128 kB |
| 6703 |
|
| 6704 |
QNetworkAccessManager manager; |
| 6705 |
QNetworkReply *reply = manager.get(request); |
| 6706 |
connect(reply, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop())); |
| 6707 |
QTestEventLoop::instance().enterLoop(10); |
| 6708 |
QVERIFY(!QTestEventLoop::instance().timeout()); |
| 6709 |
QVERIFY(reply->isFinished()); |
| 6710 |
|
| 6711 |
QFile reference(testDataDir + "/rfc3252.txt"); |
| 6712 |
QVERIFY(reference.open(QIODevice::ReadOnly)); |
| 6713 |
|
| 6714 |
QCOMPARE(reference.bytesAvailable(), reply->bytesAvailable()); |
| 6715 |
QCOMPARE(reference.size(), reply->size()); |
| 6716 |
|
| 6717 |
// Compare the memory buffer |
| 6718 |
QVariant downloadBufferAttribute = reply->attribute(QNetworkRequest::DownloadBufferAttribute); |
| 6719 |
QVERIFY(downloadBufferAttribute.isValid()); |
| 6720 |
QSharedPointer<char> sharedPointer = downloadBufferAttribute.value<QSharedPointer<char> >(); |
| 6721 |
bool memoryComparison = |
| 6722 |
(0 == memcmp(static_cast<void*>(reference.readAll().data()), |
| 6723 |
sharedPointer.data(), reference.size())); |
| 6724 |
QVERIFY(memoryComparison); |
| 6725 |
|
| 6726 |
// Make sure the normal reading works |
| 6727 |
reference.seek(0); |
| 6728 |
QCOMPARE(reply->read(42), reference.read(42)); |
| 6729 |
QCOMPARE(reply->getChar(0), reference.getChar(0)); |
| 6730 |
QCOMPARE(reply->peek(23), reference.peek(23)); |
| 6731 |
QCOMPARE(reply->readLine(), reference.readLine()); |
| 6732 |
QCOMPARE(reference.bytesAvailable(), reply->bytesAvailable()); |
| 6733 |
QCOMPARE(reply->readAll(), reference.readAll()); |
| 6734 |
QVERIFY(reply->atEnd()); |
| 6735 |
} |
| 6736 |
|
| 6737 |
// FIXME we really need to consolidate all those server implementations |
| 6738 |
class GetFromHttpIntoBuffer2Server : QObject |
| 6739 |
{ |
| 6740 |
Q_OBJECT |
| 6741 |
qint64 dataSize; |
| 6742 |
qint64 dataSent; |
| 6743 |
QTcpServer server; |
| 6744 |
QTcpSocket *client; |
| 6745 |
bool serverSendsContentLength; |
| 6746 |
bool chunkedEncoding; |
| 6747 |
|
| 6748 |
public: |
| 6749 |
GetFromHttpIntoBuffer2Server (qint64 ds, bool sscl, bool ce) |
| 6750 |
: dataSize(ds), dataSent(0), client(0), |
| 6751 |
serverSendsContentLength(sscl), chunkedEncoding(ce) |
| 6752 |
{ |
| 6753 |
server.listen(); |
| 6754 |
connect(&server, SIGNAL(newConnection()), this, SLOT(newConnectionSlot())); |
| 6755 |
} |
| 6756 |
|
| 6757 |
int serverPort() { return server.serverPort(); } |
| 6758 |
|
| 6759 |
public slots: |
| 6760 |
|
| 6761 |
void newConnectionSlot() |
| 6762 |
{ |
| 6763 |
client = server.nextPendingConnection(); |
| 6764 |
client->setParent(this); |
| 6765 |
connect(client, SIGNAL(readyRead()), this, SLOT(readyReadSlot())); |
| 6766 |
connect(client, SIGNAL(bytesWritten(qint64)), this, SLOT(bytesWrittenSlot(qint64))); |
| 6767 |
} |
| 6768 |
|
| 6769 |
void readyReadSlot() |
| 6770 |
{ |
| 6771 |
client->readAll(); |
| 6772 |
client->write("HTTP/1.0 200 OK\n"); |
| 6773 |
if (serverSendsContentLength) |
| 6774 |
client->write(QString("Content-Length: " + QString::number(dataSize) + "\n").toLatin1()); |
| 6775 |
if (chunkedEncoding) |
| 6776 |
client->write(QString("Transfer-Encoding: chunked\n").toLatin1()); |
| 6777 |
client->write("Connection: close\n\n"); |
| 6778 |
} |
| 6779 |
|
| 6780 |
void bytesWrittenSlot(qint64 amount) |
| 6781 |
{ |
| 6782 |
Q_UNUSED(amount); |
| 6783 |
if (dataSent == dataSize && client) { |
| 6784 |
// close eventually |
| 6785 |
|
| 6786 |
// chunked encoding: we have to send a last "empty" chunk |
| 6787 |
if (chunkedEncoding) |
| 6788 |
client->write(QString("0\r\n\r\n").toLatin1()); |
| 6789 |
|
| 6790 |
client->disconnectFromHost(); |
| 6791 |
server.close(); |
| 6792 |
client = 0; |
| 6793 |
return; |
| 6794 |
} |
| 6795 |
|
| 6796 |
// send data |
| 6797 |
if (client && client->bytesToWrite() < 100*1024 && dataSent < dataSize) { |
| 6798 |
qint64 amount = qMin(qint64(16*1024), dataSize - dataSent); |
| 6799 |
QByteArray data(amount, '@'); |
| 6800 |
|
| 6801 |
if (chunkedEncoding) { |
| 6802 |
client->write(QByteArray::number(amount, 16).toUpper()); |
| 6803 |
client->write("\r\n"); |
| 6804 |
client->write(data.constData(), amount); |
| 6805 |
client->write("\r\n"); |
| 6806 |
} else { |
| 6807 |
client->write(data.constData(), amount); |
| 6808 |
} |
| 6809 |
|
| 6810 |
dataSent += amount; |
| 6811 |
} |
| 6812 |
} |
| 6813 |
}; |
| 6814 |
|
| 6815 |
class GetFromHttpIntoBuffer2Client : QObject |
| 6816 |
{ |
| 6817 |
Q_OBJECT |
| 6818 |
private: |
| 6819 |
bool useDownloadBuffer; |
| 6820 |
QNetworkReply *reply; |
| 6821 |
qint64 uploadSize; |
| 6822 |
QList<qint64> bytesAvailableList; |
| 6823 |
public: |
| 6824 |
GetFromHttpIntoBuffer2Client (QNetworkReply *reply, bool useDownloadBuffer, qint64 uploadSize) |
| 6825 |
: useDownloadBuffer(useDownloadBuffer), reply(reply), uploadSize(uploadSize) |
| 6826 |
{ |
| 6827 |
connect(reply, SIGNAL(metaDataChanged()), this, SLOT(metaDataChangedSlot())); |
| 6828 |
connect(reply, SIGNAL(readyRead()), this, SLOT(readyReadSlot())); |
| 6829 |
connect(reply, SIGNAL(finished()), this, SLOT(finishedSlot())); |
| 6830 |
} |
| 6831 |
|
| 6832 |
public slots: |
| 6833 |
void metaDataChangedSlot() |
| 6834 |
{ |
| 6835 |
if (useDownloadBuffer) { |
| 6836 |
QSharedPointer<char> sharedPointer = qvariant_cast<QSharedPointer<char> >(reply->attribute(QNetworkRequest::DownloadBufferAttribute)); |
| 6837 |
QVERIFY(!sharedPointer.isNull()); // It will be 0 if it failed |
| 6838 |
} |
| 6839 |
|
| 6840 |
// metaDataChanged needs to come before everything else |
| 6841 |
QVERIFY(bytesAvailableList.isEmpty()); |
| 6842 |
} |
| 6843 |
|
| 6844 |
void readyReadSlot() |
| 6845 |
{ |
| 6846 |
QVERIFY(!reply->isFinished()); |
| 6847 |
|
| 6848 |
qint64 bytesAvailable = reply->bytesAvailable(); |
| 6849 |
|
| 6850 |
// bytesAvailable must never be 0 |
| 6851 |
QVERIFY(bytesAvailable != 0); |
| 6852 |
|
| 6853 |
if (bytesAvailableList.length() < 5) { |
| 6854 |
// We assume that the first few times the bytes available must be less than the complete size, e.g. |
| 6855 |
// the bytesAvailable() function works correctly in case of a downloadBuffer. |
| 6856 |
QVERIFY(bytesAvailable < uploadSize); |
| 6857 |
} |
| 6858 |
if (!bytesAvailableList.isEmpty()) { |
| 6859 |
// Also check that the same bytesAvailable is not coming twice in a row |
| 6860 |
QVERIFY(bytesAvailableList.last() != bytesAvailable); |
| 6861 |
} |
| 6862 |
|
| 6863 |
bytesAvailableList.append(bytesAvailable); |
| 6864 |
// Add bytesAvailable to a list an parse |
| 6865 |
} |
| 6866 |
|
| 6867 |
void finishedSlot() |
| 6868 |
{ |
| 6869 |
// We should have already received all readyRead |
| 6870 |
QVERIFY(!bytesAvailableList.isEmpty()); |
| 6871 |
QCOMPARE(bytesAvailableList.last(), uploadSize); |
| 6872 |
} |
| 6873 |
}; |
| 6874 |
|
| 6875 |
void tst_QNetworkReply::getFromHttpIntoBuffer2_data() |
| 6876 |
{ |
| 6877 |
QTest::addColumn<bool>("useDownloadBuffer"); |
| 6878 |
|
| 6879 |
QTest::newRow("use-download-buffer") << true; |
| 6880 |
QTest::newRow("do-not-use-download-buffer") << false; |
| 6881 |
} |
| 6882 |
|
| 6883 |
// This test checks mostly that signal emissions are in correct order |
| 6884 |
// Please note that the whole "zero copy" download buffer API is private right now. Do not use it. |
| 6885 |
void tst_QNetworkReply::getFromHttpIntoBuffer2() |
| 6886 |
{ |
| 6887 |
QFETCH(bool, useDownloadBuffer); |
| 6888 |
|
| 6889 |
// On my Linux Desktop the results are already visible with 128 kB, however we use this to have good results. |
| 6890 |
enum {UploadSize = 32*1024*1024}; // 32 MB |
| 6891 |
|
| 6892 |
GetFromHttpIntoBuffer2Server server(UploadSize, true, false); |
| 6893 |
|
| 6894 |
QNetworkRequest request(QUrl("http://127.0.0.1:" + QString::number(server.serverPort()) + "/?bare=1")); |
| 6895 |
if (useDownloadBuffer) |
| 6896 |
request.setAttribute(QNetworkRequest::MaximumDownloadBufferSizeAttribute, 1024*1024*128); // 128 MB is max allowed |
| 6897 |
|
| 6898 |
QNetworkAccessManager manager; |
| 6899 |
QNetworkReplyPtr reply(manager.get(request)); |
| 6900 |
|
| 6901 |
GetFromHttpIntoBuffer2Client client(reply.data(), useDownloadBuffer, UploadSize); |
| 6902 |
|
| 6903 |
connect(reply, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop()), Qt::QueuedConnection); |
| 6904 |
QTestEventLoop::instance().enterLoop(40); |
| 6905 |
QCOMPARE(reply->error(), QNetworkReply::NoError); |
| 6906 |
QVERIFY(!QTestEventLoop::instance().timeout()); |
| 6907 |
} |
| 6908 |
|
| 6909 |
|
| 6910 |
void tst_QNetworkReply::getFromHttpIntoBufferCanReadLine() |
| 6911 |
{ |
| 6912 |
QString header("HTTP/1.0 200 OK\r\nContent-Length: 7\r\n\r\nxxx\nxxx"); |
| 6913 |
|
| 6914 |
MiniHttpServer server(header.toLatin1()); |
| 6915 |
server.doClose = true; |
| 6916 |
|
| 6917 |
QNetworkRequest request(QUrl("http://localhost:" + QString::number(server.serverPort()))); |
| 6918 |
request.setAttribute(QNetworkRequest::MaximumDownloadBufferSizeAttribute, 1024*1024*128); // 128 MB is max allowed |
| 6919 |
QNetworkReplyPtr reply(manager.get(request)); |
| 6920 |
|
| 6921 |
QVERIFY2(waitForFinish(reply) == Success, msgWaitForFinished(reply)); |
| 6922 |
|
| 6923 |
QCOMPARE(reply->error(), QNetworkReply::NoError); |
| 6924 |
QVERIFY(reply->canReadLine()); |
| 6925 |
QCOMPARE(reply->read(1), QByteArray("x")); |
| 6926 |
QVERIFY(reply->canReadLine()); |
| 6927 |
QCOMPARE(reply->read(3), QByteArray("xx\n")); |
| 6928 |
QVERIFY(!reply->canReadLine()); |
| 6929 |
QCOMPARE(reply->readAll(), QByteArray("xxx")); |
| 6930 |
QVERIFY(!reply->canReadLine()); |
| 6931 |
} |
| 6932 |
|
| 6933 |
|
| 6934 |
|
| 6935 |
// Is handled somewhere else too, introduced this special test to have it more accessible |
| 6936 |
void tst_QNetworkReply::ioGetFromHttpWithoutContentLength() |
| 6937 |
{ |
| 6938 |
QByteArray dataToSend("HTTP/1.0 200 OK\r\n\r\nHALLO! 123!"); |
| 6939 |
MiniHttpServer server(dataToSend); |
| 6940 |
server.doClose = true; |
| 6941 |
|
| 6942 |
QNetworkRequest request(QUrl("http://localhost:" + QString::number(server.serverPort()))); |
| 6943 |
QNetworkReplyPtr reply(manager.get(request)); |
| 6944 |
|
| 6945 |
QVERIFY2(waitForFinish(reply) == Success, msgWaitForFinished(reply)); |
| 6946 |
|
| 6947 |
QCOMPARE(reply->url(), request.url()); |
| 6948 |
QVERIFY(reply->isFinished()); |
| 6949 |
QCOMPARE(reply->error(), QNetworkReply::NoError); |
| 6950 |
} |
| 6951 |
|
| 6952 |
// Is handled somewhere else too, introduced this special test to have it more accessible |
| 6953 |
void tst_QNetworkReply::ioGetFromHttpBrokenChunkedEncoding() |
| 6954 |
{ |
| 6955 |
// This is wrong chunked encoding because of the X. What actually has to follow is \r\n |
| 6956 |
// and then the declaration of the final 0 chunk |
| 6957 |
QByteArray dataToSend("HTTP/1.0 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n3\r\nABCX"); |
| 6958 |
MiniHttpServer server(dataToSend); |
| 6959 |
server.doClose = false; // FIXME |
| 6960 |
|
| 6961 |
QNetworkRequest request(QUrl("http://localhost:" + QString::number(server.serverPort()))); |
| 6962 |
QNetworkReplyPtr reply(manager.get(request)); |
| 6963 |
|
| 6964 |
connect(reply, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop())); |
| 6965 |
QTestEventLoop::instance().enterLoop(10); |
| 6966 |
|
| 6967 |
QEXPECT_FAIL(0, "We should close the socket and not just do nothing", Continue); |
| 6968 |
QVERIFY(!QTestEventLoop::instance().timeout()); |
| 6969 |
QEXPECT_FAIL(0, "We should close the socket and not just do nothing", Continue); |
| 6970 |
QVERIFY(reply->isFinished()); |
| 6971 |
QCOMPARE(reply->error(), QNetworkReply::NoError); |
| 6972 |
} |
| 6973 |
|
| 6974 |
// TODO: |
| 6975 |
// Prepare a gzip that has one chunk that expands to the size mentioned in the bugreport. |
| 6976 |
// Then have a custom HTTP server that waits after this chunk so the returning gets |
| 6977 |
// triggered. |
| 6978 |
void tst_QNetworkReply::qtbug12908compressedHttpReply() |
| 6979 |
{ |
| 6980 |
QString header("HTTP/1.0 200 OK\r\nContent-Encoding: gzip\r\nContent-Length: 63\r\n\r\n"); |
| 6981 |
|
| 6982 |
// dd if=/dev/zero of=qtbug-12908 bs=16384 count=1 && gzip qtbug-12908 && base64 -w 0 qtbug-12908.gz |
| 6983 |
QString encodedFile("H4sICDdDaUwAA3F0YnVnLTEyOTA4AO3BMQEAAADCoPVPbQwfoAAAAAAAAAAAAAAAAAAAAIC3AYbSVKsAQAAA"); |
| 6984 |
QByteArray decodedFile = QByteArray::fromBase64(encodedFile.toLatin1()); |
| 6985 |
QCOMPARE(decodedFile.size(), 63); |
| 6986 |
|
| 6987 |
MiniHttpServer server(header.toLatin1() + decodedFile); |
| 6988 |
server.doClose = true; |
| 6989 |
|
| 6990 |
QNetworkRequest request(QUrl("http://localhost:" + QString::number(server.serverPort()))); |
| 6991 |
QNetworkReplyPtr reply(manager.get(request)); |
| 6992 |
|
| 6993 |
QVERIFY2(waitForFinish(reply) == Success, msgWaitForFinished(reply)); |
| 6994 |
|
| 6995 |
QCOMPARE(reply->error(), QNetworkReply::NoError); |
| 6996 |
QCOMPARE(reply->size(), qint64(16384)); |
| 6997 |
QCOMPARE(reply->readAll(), QByteArray(16384, '\0')); |
| 6998 |
} |
| 6999 |
|
| 7000 |
void tst_QNetworkReply::compressedHttpReplyBrokenGzip() |
| 7001 |
{ |
| 7002 |
QString header("HTTP/1.0 200 OK\r\nContent-Encoding: gzip\r\nContent-Length: 63\r\n\r\n"); |
| 7003 |
|
| 7004 |
// dd if=/dev/zero of=qtbug-12908 bs=16384 count=1 && gzip qtbug-12908 && base64 -w 0 qtbug-12908.gz |
| 7005 |
// Then change "BMQ" to "BMX" |
| 7006 |
QString encodedFile("H4sICDdDaUwAA3F0YnVnLTEyOTA4AO3BMXEAAADCoPVPbQwfoAAAAAAAAAAAAAAAAAAAAIC3AYbSVKsAQAAA"); |
| 7007 |
QByteArray decodedFile = QByteArray::fromBase64(encodedFile.toLatin1()); |
| 7008 |
QCOMPARE(decodedFile.size(), 63); |
| 7009 |
|
| 7010 |
MiniHttpServer server(header.toLatin1() + decodedFile); |
| 7011 |
server.doClose = true; |
| 7012 |
|
| 7013 |
QNetworkRequest request(QUrl("http://localhost:" + QString::number(server.serverPort()))); |
| 7014 |
QNetworkReplyPtr reply(manager.get(request)); |
| 7015 |
|
| 7016 |
QCOMPARE(waitForFinish(reply), int(Failure)); |
| 7017 |
|
| 7018 |
QCOMPARE(reply->error(), QNetworkReply::ProtocolFailure); |
| 7019 |
} |
| 7020 |
|
| 7021 |
// TODO add similar test for FTP |
| 7022 |
void tst_QNetworkReply::getFromUnreachableIp() |
| 7023 |
{ |
| 7024 |
QNetworkAccessManager manager; |
| 7025 |
|
| 7026 |
#ifdef Q_OS_WIN |
| 7027 |
// This test assumes that attempt to connect to 255.255.255.255 fails more |
| 7028 |
// or less fast/immediately. This is not what we observe on Windows: |
| 7029 |
// WSAConnect on non-blocking socket returns SOCKET_ERROR, WSAGetLastError |
| 7030 |
// returns WSAEWOULDBLOCK (expected) and getsockopt most of the time returns |
| 7031 |
// NOERROR; so socket engine starts a timer (30 s.) and waits for a timeout/ |
| 7032 |
// error/success. Unfortunately, the test itself is waiting only for 5 s. |
| 7033 |
// So we have to adjust the connection timeout or skip the test completely |
| 7034 |
// if the 'bearermanagement' feature is not available. |
| 7035 |
#if QT_CONFIG(bearermanagement) |
| 7036 |
class ConfigurationGuard |
| 7037 |
{ |
| 7038 |
public: |
| 7039 |
explicit ConfigurationGuard(QNetworkAccessManager *m) |
| 7040 |
: manager(m) |
| 7041 |
{ |
| 7042 |
Q_ASSERT(m); |
| 7043 |
auto conf = manager->configuration(); |
| 7044 |
previousTimeout = conf.connectTimeout(); |
| 7045 |
conf.setConnectTimeout(1500); |
| 7046 |
manager->setConfiguration(conf); |
| 7047 |
} |
| 7048 |
~ConfigurationGuard() |
| 7049 |
{ |
| 7050 |
Q_ASSERT(manager); |
| 7051 |
auto conf = manager->configuration(); |
| 7052 |
conf.setConnectTimeout(previousTimeout); |
| 7053 |
manager->setConfiguration(conf); |
| 7054 |
} |
| 7055 |
private: |
| 7056 |
QNetworkAccessManager *manager = nullptr; |
| 7057 |
int previousTimeout = 0; |
| 7058 |
|
| 7059 |
Q_DISABLE_COPY(ConfigurationGuard) |
| 7060 |
}; |
| 7061 |
|
| 7062 |
const ConfigurationGuard restorer(&manager); |
| 7063 |
#else // bearermanagement |
| 7064 |
QSKIP("This test is non-deterministic on Windows x86"); |
| 7065 |
#endif // !bearermanagement |
| 7066 |
#endif // Q_OS_WIN |
| 7067 |
|
| 7068 |
QNetworkRequest request(QUrl("http://255.255.255.255/42/23/narf/narf/narf")); |
| 7069 |
QNetworkReplyPtr reply(manager.get(request)); |
| 7070 |
|
| 7071 |
QCOMPARE(waitForFinish(reply), int(Failure)); |
| 7072 |
|
| 7073 |
QVERIFY(reply->error() != QNetworkReply::NoError); |
| 7074 |
} |
| 7075 |
|
| 7076 |
void tst_QNetworkReply::qtbug4121unknownAuthentication() |
| 7077 |
{ |
| 7078 |
MiniHttpServer server(QByteArray("HTTP/1.1 401 bla\r\nWWW-Authenticate: crap\r\nContent-Length: 0\r\n\r\n")); |
| 7079 |
server.doClose = false; |
| 7080 |
|
| 7081 |
QNetworkRequest request(QUrl("http://localhost:" + QString::number(server.serverPort()))); |
| 7082 |
QNetworkAccessManager manager; |
| 7083 |
QNetworkReplyPtr reply(manager.get(request)); |
| 7084 |
|
| 7085 |
QSignalSpy authSpy(&manager, SIGNAL(authenticationRequired(QNetworkReply*,QAuthenticator*))); |
| 7086 |
QSignalSpy finishedSpy(&manager, SIGNAL(finished(QNetworkReply*))); |
| 7087 |
QSignalSpy errorSpy(reply.data(), SIGNAL(errorOccurred(QNetworkReply::NetworkError))); |
| 7088 |
|
| 7089 |
connect(reply, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop()), Qt::QueuedConnection); |
| 7090 |
QTestEventLoop::instance().enterLoop(10); |
| 7091 |
QVERIFY(!QTestEventLoop::instance().timeout()); |
| 7092 |
|
| 7093 |
QCOMPARE(authSpy.count(), 0); |
| 7094 |
QCOMPARE(finishedSpy.count(), 1); |
| 7095 |
QCOMPARE(errorSpy.count(), 1); |
| 7096 |
|
| 7097 |
QCOMPARE(reply->error(), QNetworkReply::AuthenticationRequiredError); |
| 7098 |
} |
| 7099 |
|
| 7100 |
#ifndef QT_NO_NETWORKPROXY |
| 7101 |
void tst_QNetworkReply::authenticationCacheAfterCancel_data() |
| 7102 |
{ |
| 7103 |
QTest::addColumn<QNetworkProxy>("proxy"); |
| 7104 |
QTest::addColumn<bool>("proxyAuth"); |
| 7105 |
QTest::addColumn<QUrl>("url"); |
| 7106 |
for (int i = 0; i < proxies.count(); ++i) { |
| 7107 |
QTest::newRow("http" + proxies.at(i).tag) |
| 7108 |
<< proxies.at(i).proxy |
| 7109 |
<< proxies.at(i).requiresAuthentication |
| 7110 |
<< QUrl("http://" + QtNetworkSettings::httpServerName() + "/qtest/rfcs-auth/rfc3252.txt"); |
| 7111 |
#ifndef QT_NO_SSL |
| 7112 |
QTest::newRow("https" + proxies.at(i).tag) |
| 7113 |
<< proxies.at(i).proxy |
| 7114 |
<< proxies.at(i).requiresAuthentication |
| 7115 |
<< QUrl("https://" + QtNetworkSettings::httpServerName() + "/qtest/rfcs-auth/rfc3252.txt"); |
| 7116 |
#endif |
| 7117 |
} |
| 7118 |
} |
| 7119 |
|
| 7120 |
class AuthenticationCacheHelper : public QObject |
| 7121 |
{ |
| 7122 |
Q_OBJECT |
| 7123 |
public: |
| 7124 |
AuthenticationCacheHelper() |
| 7125 |
{} |
| 7126 |
public slots: |
| 7127 |
void proxyAuthenticationRequired(const QNetworkProxy &, QAuthenticator *auth) |
| 7128 |
{ |
| 7129 |
if (!proxyPassword.isNull()) { |
| 7130 |
auth->setUser(proxyUserName); |
| 7131 |
auth->setPassword(proxyPassword); |
| 7132 |
//clear credentials, if they are asked again, they were bad |
| 7133 |
proxyUserName.clear(); |
| 7134 |
proxyPassword.clear(); |
| 7135 |
} |
| 7136 |
} |
| 7137 |
void authenticationRequired(QNetworkReply*,QAuthenticator *auth) |
| 7138 |
{ |
| 7139 |
if (!httpPassword.isNull()) { |
| 7140 |
auth->setUser(httpUserName); |
| 7141 |
auth->setPassword(httpPassword); |
| 7142 |
//clear credentials, if they are asked again, they were bad |
| 7143 |
httpUserName.clear(); |
| 7144 |
httpPassword.clear(); |
| 7145 |
} |
| 7146 |
} |
| 7147 |
public: |
| 7148 |
QString httpUserName; |
| 7149 |
QString httpPassword; |
| 7150 |
QString proxyUserName; |
| 7151 |
QString proxyPassword; |
| 7152 |
}; |
| 7153 |
|
| 7154 |
/* Purpose of this test is to check credentials are cached correctly. |
| 7155 |
- If user cancels authentication dialog (i.e. nothing is set to the QAuthenticator by the callback) then this is not cached |
| 7156 |
- if user supplies a wrong password, then this is not cached |
| 7157 |
- if user supplies a correct user/password combination then this is cached |
| 7158 |
|
| 7159 |
Test is checking both the proxyAuthenticationRequired and authenticationRequired signals. |
| 7160 |
*/ |
| 7161 |
void tst_QNetworkReply::authenticationCacheAfterCancel() |
| 7162 |
{ |
| 7163 |
QFETCH(QNetworkProxy, proxy); |
| 7164 |
QFETCH(bool, proxyAuth); |
| 7165 |
QFETCH(QUrl, url); |
| 7166 |
QNetworkAccessManager manager; |
| 7167 |
#ifndef QT_NO_SSL |
| 7168 |
connect(&manager, SIGNAL(sslErrors(QNetworkReply*,QList<QSslError>)), |
| 7169 |
SLOT(sslErrors(QNetworkReply*,QList<QSslError>))); |
| 7170 |
#endif |
| 7171 |
manager.setProxy(proxy); |
| 7172 |
QSignalSpy authSpy(&manager, SIGNAL(authenticationRequired(QNetworkReply*,QAuthenticator*))); |
| 7173 |
QSignalSpy proxyAuthSpy(&manager, SIGNAL(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*))); |
| 7174 |
|
| 7175 |
AuthenticationCacheHelper helper; |
| 7176 |
connect(&manager, SIGNAL(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)), &helper, SLOT(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*))); |
| 7177 |
connect(&manager, SIGNAL(authenticationRequired(QNetworkReply*,QAuthenticator*)), &helper, SLOT(authenticationRequired(QNetworkReply*,QAuthenticator*))); |
| 7178 |
|
| 7179 |
QNetworkRequest request(url); |
| 7180 |
QNetworkReplyPtr reply; |
| 7181 |
if (proxyAuth) { |
| 7182 |
//should fail due to no credentials |
| 7183 |
reply.reset(manager.get(request)); |
| 7184 |
connect(reply, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop()), Qt::QueuedConnection); |
| 7185 |
QTestEventLoop::instance().enterLoop(10); |
| 7186 |
QVERIFY(!QTestEventLoop::instance().timeout()); |
| 7187 |
|
| 7188 |
QCOMPARE(reply->error(), QNetworkReply::ProxyAuthenticationRequiredError); |
| 7189 |
QCOMPARE(authSpy.count(), 0); |
| 7190 |
QCOMPARE(proxyAuthSpy.count(), 1); |
| 7191 |
proxyAuthSpy.clear(); |
| 7192 |
|
| 7193 |
//should fail due to bad credentials |
| 7194 |
helper.proxyUserName = "qsockstest"; |
| 7195 |
helper.proxyPassword = "badpassword"; |
| 7196 |
reply.reset(manager.get(request)); |
| 7197 |
connect(reply, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop()), Qt::QueuedConnection); |
| 7198 |
QTestEventLoop::instance().enterLoop(10); |
| 7199 |
QVERIFY(!QTestEventLoop::instance().timeout()); |
| 7200 |
|
| 7201 |
// Work round known quirk in the old test server (danted -v < v1.1.19): |
| 7202 |
if (reply->error() != QNetworkReply::HostNotFoundError) |
| 7203 |
QCOMPARE(reply->error(), QNetworkReply::ProxyAuthenticationRequiredError); |
| 7204 |
QCOMPARE(authSpy.count(), 0); |
| 7205 |
QVERIFY(proxyAuthSpy.count() > 0); |
| 7206 |
proxyAuthSpy.clear(); |
| 7207 |
|
| 7208 |
// QTBUG-23136 workaround (needed even with danted v1.1.19): |
| 7209 |
if (proxy.port() == 1081) { |
| 7210 |
#ifdef QT_BUILD_INTERNAL |
| 7211 |
QNetworkAccessManagerPrivate::clearAuthenticationCache(&manager); |
| 7212 |
QNetworkAccessManagerPrivate::clearConnectionCache(&manager); |
| 7213 |
#else |
| 7214 |
return; |
| 7215 |
#endif |
| 7216 |
} |
| 7217 |
|
| 7218 |
//next proxy auth should succeed, due to correct credentials |
| 7219 |
helper.proxyUserName = "qsockstest"; |
| 7220 |
helper.proxyPassword = "password"; |
| 7221 |
} |
| 7222 |
|
| 7223 |
//should fail due to no credentials |
| 7224 |
reply.reset(manager.get(request)); |
| 7225 |
connect(reply, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop()), Qt::QueuedConnection); |
| 7226 |
QTestEventLoop::instance().enterLoop(10); |
| 7227 |
QVERIFY(!QTestEventLoop::instance().timeout()); |
| 7228 |
|
| 7229 |
QCOMPARE(reply->error(), QNetworkReply::AuthenticationRequiredError); |
| 7230 |
QVERIFY(authSpy.count() > 0); |
| 7231 |
authSpy.clear(); |
| 7232 |
if (proxyAuth) { |
| 7233 |
QVERIFY(proxyAuthSpy.count() > 0); |
| 7234 |
proxyAuthSpy.clear(); |
| 7235 |
} |
| 7236 |
|
| 7237 |
//should fail due to bad credentials |
| 7238 |
helper.httpUserName = "baduser"; |
| 7239 |
helper.httpPassword = "badpassword"; |
| 7240 |
reply.reset(manager.get(request)); |
| 7241 |
connect(reply, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop()), Qt::QueuedConnection); |
| 7242 |
QTestEventLoop::instance().enterLoop(10); |
| 7243 |
QVERIFY(!QTestEventLoop::instance().timeout()); |
| 7244 |
|
| 7245 |
QCOMPARE(reply->error(), QNetworkReply::AuthenticationRequiredError); |
| 7246 |
QVERIFY(authSpy.count() > 0); |
| 7247 |
authSpy.clear(); |
| 7248 |
if (proxyAuth) { |
| 7249 |
//should be supplied from cache |
| 7250 |
QCOMPARE(proxyAuthSpy.count(), 0); |
| 7251 |
proxyAuthSpy.clear(); |
| 7252 |
} |
| 7253 |
|
| 7254 |
//next auth should succeed, due to correct credentials |
| 7255 |
helper.httpUserName = "httptest"; |
| 7256 |
helper.httpPassword = "httptest"; |
| 7257 |
|
| 7258 |
reply.reset(manager.get(request)); |
| 7259 |
connect(reply, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop()), Qt::QueuedConnection); |
| 7260 |
QTestEventLoop::instance().enterLoop(10); |
| 7261 |
QVERIFY(!QTestEventLoop::instance().timeout()); |
| 7262 |
|
| 7263 |
QCOMPARE(reply->error(), QNetworkReply::NoError); |
| 7264 |
QVERIFY(authSpy.count() > 0); |
| 7265 |
authSpy.clear(); |
| 7266 |
if (proxyAuth) { |
| 7267 |
//should be supplied from cache |
| 7268 |
QCOMPARE(proxyAuthSpy.count(), 0); |
| 7269 |
proxyAuthSpy.clear(); |
| 7270 |
} |
| 7271 |
|
| 7272 |
//next auth should use cached credentials |
| 7273 |
reply.reset(manager.get(request)); |
| 7274 |
connect(reply, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop()), Qt::QueuedConnection); |
| 7275 |
QTestEventLoop::instance().enterLoop(10); |
| 7276 |
QVERIFY(!QTestEventLoop::instance().timeout()); |
| 7277 |
|
| 7278 |
QCOMPARE(reply->error(), QNetworkReply::NoError); |
| 7279 |
//should be supplied from cache |
| 7280 |
QCOMPARE(authSpy.count(), 0); |
| 7281 |
authSpy.clear(); |
| 7282 |
if (proxyAuth) { |
| 7283 |
//should be supplied from cache |
| 7284 |
QCOMPARE(proxyAuthSpy.count(), 0); |
| 7285 |
proxyAuthSpy.clear(); |
| 7286 |
} |
| 7287 |
|
| 7288 |
} |
| 7289 |
|
| 7290 |
void tst_QNetworkReply::authenticationWithDifferentRealm() |
| 7291 |
{ |
| 7292 |
AuthenticationCacheHelper helper; |
| 7293 |
QNetworkAccessManager manager; |
| 7294 |
#ifndef QT_NO_SSL |
| 7295 |
connect(&manager, SIGNAL(sslErrors(QNetworkReply*,QList<QSslError>)), |
| 7296 |
SLOT(sslErrors(QNetworkReply*,QList<QSslError>))); |
| 7297 |
#endif |
| 7298 |
connect(&manager, SIGNAL(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)), &helper, SLOT(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*))); |
| 7299 |
connect(&manager, SIGNAL(authenticationRequired(QNetworkReply*,QAuthenticator*)), &helper, SLOT(authenticationRequired(QNetworkReply*,QAuthenticator*))); |
| 7300 |
|
| 7301 |
helper.httpUserName = "httptest"; |
| 7302 |
helper.httpPassword = "httptest"; |
| 7303 |
|
| 7304 |
QNetworkRequest request(QUrl("http://" + QtNetworkSettings::httpServerName() + "/qtest/rfcs-auth/rfc3252.txt")); |
| 7305 |
QNetworkReply* reply = manager.get(request); |
| 7306 |
connect(reply, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop()), Qt::QueuedConnection); |
| 7307 |
QTestEventLoop::instance().enterLoop(10); |
| 7308 |
QVERIFY(!QTestEventLoop::instance().timeout()); |
| 7309 |
QCOMPARE(reply->error(), QNetworkReply::NoError); |
| 7310 |
|
| 7311 |
helper.httpUserName = "httptest"; |
| 7312 |
helper.httpPassword = "httptest"; |
| 7313 |
|
| 7314 |
request.setUrl(QUrl("http://" + QtNetworkSettings::httpServerName() + "/qtest/auth-digest/")); |
| 7315 |
reply = manager.get(request); |
| 7316 |
connect(reply, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop()), Qt::QueuedConnection); |
| 7317 |
QTestEventLoop::instance().enterLoop(10); |
| 7318 |
QVERIFY(!QTestEventLoop::instance().timeout()); |
| 7319 |
QCOMPARE(reply->error(), QNetworkReply::NoError); |
| 7320 |
} |
| 7321 |
#endif // !QT_NO_NETWORKPROXY |
| 7322 |
|
| 7323 |
class QtBug13431Helper : public QObject |
| 7324 |
{ |
| 7325 |
Q_OBJECT |
| 7326 |
public: |
| 7327 |
QNetworkReply* m_reply; |
| 7328 |
QTimer m_dlTimer; |
| 7329 |
public slots: |
| 7330 |
void replyFinished(QNetworkReply*) { QTestEventLoop::instance().exitLoop(); } |
| 7331 |
|
| 7332 |
void onReadAndReschedule() |
| 7333 |
{ |
| 7334 |
const qint64 bytesReceived = m_reply->bytesAvailable(); |
| 7335 |
if (bytesReceived && m_reply->readBufferSize()) { |
| 7336 |
QByteArray data = m_reply->read(bytesReceived); |
| 7337 |
// reschedule read |
| 7338 |
const int millisecDelay = static_cast<int>(bytesReceived * 1000 / m_reply->readBufferSize()); |
| 7339 |
m_dlTimer.start(millisecDelay); |
| 7340 |
} |
| 7341 |
else { |
| 7342 |
// reschedule read |
| 7343 |
m_dlTimer.start(200); |
| 7344 |
} |
| 7345 |
} |
| 7346 |
}; |
| 7347 |
|
| 7348 |
void tst_QNetworkReply::qtbug13431replyThrottling() |
| 7349 |
{ |
| 7350 |
QtBug13431Helper helper; |
| 7351 |
|
| 7352 |
QNetworkAccessManager nam; |
| 7353 |
connect(&nam, SIGNAL(finished(QNetworkReply*)), &helper, SLOT(replyFinished(QNetworkReply*))); |
| 7354 |
|
| 7355 |
// Download a bigger file |
| 7356 |
QNetworkRequest netRequest(QUrl("http://" + QtNetworkSettings::httpServerName() + "/qtest/bigfile")); |
| 7357 |
helper.m_reply = nam.get(netRequest); |
| 7358 |
// Set the throttle |
| 7359 |
helper.m_reply->setReadBufferSize(36000); |
| 7360 |
|
| 7361 |
// Schedule a timer that tries to read |
| 7362 |
|
| 7363 |
connect(&helper.m_dlTimer, SIGNAL(timeout()), &helper, SLOT(onReadAndReschedule())); |
| 7364 |
helper.m_dlTimer.setSingleShot(true); |
| 7365 |
helper.m_dlTimer.start(0); |
| 7366 |
|
| 7367 |
QTestEventLoop::instance().enterLoop(30); |
| 7368 |
QVERIFY(!QTestEventLoop::instance().timeout()); |
| 7369 |
QVERIFY(helper.m_reply->isFinished()); |
| 7370 |
QCOMPARE(helper.m_reply->error(), QNetworkReply::NoError); |
| 7371 |
} |
| 7372 |
|
| 7373 |
void tst_QNetworkReply::httpWithNoCredentialUsage() |
| 7374 |
{ |
| 7375 |
QNetworkAccessManager manager; |
| 7376 |
|
| 7377 |
QSignalSpy authSpy(&manager, SIGNAL(authenticationRequired(QNetworkReply*,QAuthenticator*))); |
| 7378 |
QSignalSpy finishedSpy(&manager, SIGNAL(finished(QNetworkReply*))); |
| 7379 |
|
| 7380 |
// Get with credentials, to preload authentication cache |
| 7381 |
{ |
| 7382 |
QNetworkRequest request(QUrl("http://httptest:httptest@" + QtNetworkSettings::httpServerName() + "/qtest/protected/cgi-bin/md5sum.cgi")); |
| 7383 |
QNetworkReplyPtr reply(manager.get(request)); |
| 7384 |
QVERIFY2(waitForFinish(reply) == Success, msgWaitForFinished(reply)); |
| 7385 |
// credentials in URL, so don't expect authentication signal |
| 7386 |
QCOMPARE(authSpy.count(), 0); |
| 7387 |
QCOMPARE(finishedSpy.count(), 1); |
| 7388 |
finishedSpy.clear(); |
| 7389 |
} |
| 7390 |
|
| 7391 |
// Get with cached credentials (normal usage) |
| 7392 |
{ |
| 7393 |
QNetworkRequest request(QUrl("http://" + QtNetworkSettings::httpServerName() + "/qtest/protected/cgi-bin/md5sum.cgi")); |
| 7394 |
QNetworkReplyPtr reply(manager.get(request)); |
| 7395 |
QVERIFY2(waitForFinish(reply) == Success, msgWaitForFinished(reply)); |
| 7396 |
// credentials in cache, so don't expect authentication signal |
| 7397 |
QCOMPARE(authSpy.count(), 0); |
| 7398 |
QCOMPARE(finishedSpy.count(), 1); |
| 7399 |
finishedSpy.clear(); |
| 7400 |
} |
| 7401 |
|
| 7402 |
// Do not use cached credentials (webkit cross origin usage) |
| 7403 |
{ |
| 7404 |
QNetworkRequest request(QUrl("http://" + QtNetworkSettings::httpServerName() + "/qtest/protected/cgi-bin/md5sum.cgi")); |
| 7405 |
request.setAttribute(QNetworkRequest::AuthenticationReuseAttribute, QNetworkRequest::Manual); |
| 7406 |
QNetworkReplyPtr reply(manager.get(request)); |
| 7407 |
|
| 7408 |
QSignalSpy errorSpy(reply.data(), SIGNAL(errorOccurred(QNetworkReply::NetworkError))); |
| 7409 |
|
| 7410 |
connect(reply, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop()), Qt::QueuedConnection); |
| 7411 |
QTestEventLoop::instance().enterLoop(10); |
| 7412 |
QVERIFY(!QTestEventLoop::instance().timeout()); |
| 7413 |
|
| 7414 |
// We check if authenticationRequired was emitted, however we do not anything in it so it should be 401 |
| 7415 |
QCOMPARE(authSpy.count(), 1); |
| 7416 |
QCOMPARE(finishedSpy.count(), 1); |
| 7417 |
QCOMPARE(errorSpy.count(), 1); |
| 7418 |
|
| 7419 |
QCOMPARE(reply->error(), QNetworkReply::AuthenticationRequiredError); |
| 7420 |
} |
| 7421 |
} |
| 7422 |
|
| 7423 |
void tst_QNetworkReply::qtbug15311doubleContentLength() |
| 7424 |
{ |
| 7425 |
QByteArray response("HTTP/1.0 200 OK\r\nContent-Length: 3\r\nServer: bogus\r\nContent-Length: 3\r\n\r\nABC"); |
| 7426 |
MiniHttpServer server(response); |
| 7427 |
server.doClose = true; |
| 7428 |
|
| 7429 |
QNetworkRequest request(QUrl("http://localhost:" + QString::number(server.serverPort()))); |
| 7430 |
QNetworkReplyPtr reply(manager.get(request)); |
| 7431 |
|
| 7432 |
QVERIFY2(waitForFinish(reply) == Success, msgWaitForFinished(reply)); |
| 7433 |
|
| 7434 |
QVERIFY(reply->isFinished()); |
| 7435 |
QCOMPARE(reply->error(), QNetworkReply::NoError); |
| 7436 |
QCOMPARE(reply->size(), qint64(3)); |
| 7437 |
QCOMPARE(reply->header(QNetworkRequest::ContentLengthHeader).toLongLong(), qint64(3)); |
| 7438 |
QCOMPARE(reply->rawHeader("Content-length"), QByteArray("3, 3")); |
| 7439 |
QCOMPARE(reply->readAll(), QByteArray("ABC")); |
| 7440 |
} |
| 7441 |
|
| 7442 |
void tst_QNetworkReply::qtbug18232gzipContentLengthZero() |
| 7443 |
{ |
| 7444 |
QByteArray response("HTTP/1.0 200 OK\r\nContent-Encoding: gzip\r\nContent-Length: 0\r\n\r\n"); |
| 7445 |
MiniHttpServer server(response); |
| 7446 |
server.doClose = true; |
| 7447 |
|
| 7448 |
QNetworkRequest request(QUrl("http://localhost:" + QString::number(server.serverPort()))); |
| 7449 |
QNetworkReplyPtr reply(manager.get(request)); |
| 7450 |
|
| 7451 |
QVERIFY2(waitForFinish(reply) == Success, msgWaitForFinished(reply)); |
| 7452 |
|
| 7453 |
QVERIFY(reply->isFinished()); |
| 7454 |
QCOMPARE(reply->error(), QNetworkReply::NoError); |
| 7455 |
QCOMPARE(reply->size(), qint64(0)); |
| 7456 |
QCOMPARE(reply->header(QNetworkRequest::ContentLengthHeader).toLongLong(), qint64(0)); |
| 7457 |
QCOMPARE(reply->readAll(), QByteArray()); |
| 7458 |
} |
| 7459 |
|
| 7460 |
// Reproduced a crash in QHttpNetworkReplyPrivate::gunzipBodyPartiallyEnd |
| 7461 |
// where zlib inflateEnd was called for uninitialized zlib stream |
| 7462 |
void tst_QNetworkReply::qtbug22660gzipNoContentLengthEmptyContent() |
| 7463 |
{ |
| 7464 |
// Response with no Content-Length in header and empty content |
| 7465 |
QByteArray response("HTTP/1.0 200 OK\r\nContent-Encoding: gzip\r\n\r\n"); |
| 7466 |
MiniHttpServer server(response); |
| 7467 |
server.doClose = true; |
| 7468 |
|
| 7469 |
QNetworkRequest request(QUrl("http://localhost:" + QString::number(server.serverPort()))); |
| 7470 |
QNetworkReplyPtr reply(manager.get(request)); |
| 7471 |
|
| 7472 |
QVERIFY2(waitForFinish(reply) == Success, msgWaitForFinished(reply)); |
| 7473 |
|
| 7474 |
QVERIFY(reply->isFinished()); |
| 7475 |
QCOMPARE(reply->error(), QNetworkReply::NoError); |
| 7476 |
QCOMPARE(reply->size(), qint64(0)); |
| 7477 |
QVERIFY(!reply->header(QNetworkRequest::ContentLengthHeader).isValid()); |
| 7478 |
QCOMPARE(reply->readAll(), QByteArray()); |
| 7479 |
} |
| 7480 |
|
| 7481 |
class QtBug27161Helper : public QObject |
| 7482 |
{ |
| 7483 |
Q_OBJECT |
| 7484 |
public: |
| 7485 |
QtBug27161Helper(MiniHttpServer & server, const QByteArray & data): |
| 7486 |
m_server(server), |
| 7487 |
m_data(data) |
| 7488 |
{ |
| 7489 |
connect(&m_server, SIGNAL(newConnection()), this, SLOT(newConnectionSlot())); |
| 7490 |
} |
| 7491 |
public slots: |
| 7492 |
void newConnectionSlot() |
| 7493 |
{ |
| 7494 |
connect(m_server.client, SIGNAL(bytesWritten(qint64)), this, SLOT(bytesWrittenSlot())); |
| 7495 |
} |
| 7496 |
|
| 7497 |
void bytesWrittenSlot() |
| 7498 |
{ |
| 7499 |
disconnect(m_server.client, SIGNAL(bytesWritten(qint64)), this, SLOT(bytesWrittenSlot())); |
| 7500 |
m_Timer.singleShot(100, this, SLOT(timeoutSlot())); |
| 7501 |
} |
| 7502 |
|
| 7503 |
void timeoutSlot() |
| 7504 |
{ |
| 7505 |
m_server.doClose = true; |
| 7506 |
// we need to emulate the bytesWrittenSlot call if the data is empty. |
| 7507 |
if (m_data.size() == 0) |
| 7508 |
QMetaObject::invokeMethod(&m_server, "bytesWrittenSlot", Qt::QueuedConnection); |
| 7509 |
else |
| 7510 |
m_server.client->write(m_data); |
| 7511 |
} |
| 7512 |
|
| 7513 |
private: |
| 7514 |
MiniHttpServer & m_server; |
| 7515 |
QByteArray m_data; |
| 7516 |
QTimer m_Timer; |
| 7517 |
}; |
| 7518 |
|
| 7519 |
void tst_QNetworkReply::qtbug27161httpHeaderMayBeDamaged_data(){ |
| 7520 |
QByteArray response("HTTP/1.0 200 OK\r\nServer: bogus\r\nContent-Length: 3\r\n\r\nABC"); |
| 7521 |
QTest::addColumn<QByteArray>("firstPacket"); |
| 7522 |
QTest::addColumn<QByteArray>("secondPacket"); |
| 7523 |
|
| 7524 |
for (int i = 1; i < response.size(); i++){ |
| 7525 |
QByteArray dataTag("Iteration: "); |
| 7526 |
dataTag.append(QByteArray::number(i - 1)); |
| 7527 |
QTest::newRow(dataTag.constData()) << response.left(i) << response.mid(i); |
| 7528 |
} |
| 7529 |
} |
| 7530 |
|
| 7531 |
/* |
| 7532 |
* Purpose of this test is to check whether a content from server is parsed correctly |
| 7533 |
* if it is split into two parts. |
| 7534 |
*/ |
| 7535 |
void tst_QNetworkReply::qtbug27161httpHeaderMayBeDamaged(){ |
| 7536 |
QFETCH(QByteArray, firstPacket); |
| 7537 |
QFETCH(QByteArray, secondPacket); |
| 7538 |
MiniHttpServer server(firstPacket); |
| 7539 |
server.doClose = false; |
| 7540 |
QtBug27161Helper helper(server, secondPacket); |
| 7541 |
|
| 7542 |
QNetworkRequest request(QUrl("http://localhost:" + QString::number(server.serverPort()))); |
| 7543 |
QNetworkReplyPtr reply(manager.get(request)); |
| 7544 |
|
| 7545 |
QVERIFY2(waitForFinish(reply) == Success, msgWaitForFinished(reply)); |
| 7546 |
|
| 7547 |
QVERIFY(reply->isFinished()); |
| 7548 |
QCOMPARE(reply->error(), QNetworkReply::NoError); |
| 7549 |
QCOMPARE(reply->size(), qint64(3)); |
| 7550 |
QCOMPARE(reply->header(QNetworkRequest::ContentLengthHeader).toLongLong(), qint64(3)); |
| 7551 |
QCOMPARE(reply->rawHeader("Content-length"), QByteArray("3")); |
| 7552 |
QCOMPARE(reply->rawHeader("Server"), QByteArray("bogus")); |
| 7553 |
QCOMPARE(reply->readAll(), QByteArray("ABC")); |
| 7554 |
} |
| 7555 |
|
| 7556 |
void tst_QNetworkReply::qtbug28035browserDoesNotLoadQtProjectOrgCorrectly() { |
| 7557 |
QByteArray getReply = |
| 7558 |
"HTTP/1.1 200\r\n" |
| 7559 |
"Connection: keep-alive\r\n" |
| 7560 |
"Content-Type: text/plain\r\n" |
| 7561 |
"Cache-control: max-age = 6000\r\n" |
| 7562 |
"\r\n" |
| 7563 |
"GET"; |
| 7564 |
|
| 7565 |
QByteArray postReply = |
| 7566 |
"HTTP/1.1 200\r\n" |
| 7567 |
"Connection: keep-alive\r\n" |
| 7568 |
"Content-Type: text/plain\r\n" |
| 7569 |
"Cache-control: max-age = 6000\r\n" |
| 7570 |
"Content-length: 4\r\n" |
| 7571 |
"\r\n" |
| 7572 |
"POST"; |
| 7573 |
|
| 7574 |
QByteArray putReply = |
| 7575 |
"HTTP/1.1 201\r\n" |
| 7576 |
"Connection: keep-alive\r\n" |
| 7577 |
"Content-Type: text/plain\r\n" |
| 7578 |
"Cache-control: max-age = 6000\r\n" |
| 7579 |
"\r\n"; |
| 7580 |
|
| 7581 |
QByteArray postData = "ACT=100"; |
| 7582 |
|
| 7583 |
QTemporaryDir tempDir(QDir::tempPath() + "/tmp_cache_28035"); |
| 7584 |
QVERIFY2(tempDir.isValid(), qPrintable(tempDir.errorString())); |
| 7585 |
tempDir.setAutoRemove(true); |
| 7586 |
|
| 7587 |
QNetworkDiskCache *diskCache = new QNetworkDiskCache(); |
| 7588 |
diskCache->setCacheDirectory(tempDir.path()); |
| 7589 |
manager.setCache(diskCache); |
| 7590 |
|
| 7591 |
MiniHttpServer server(getReply); |
| 7592 |
|
| 7593 |
QNetworkRequest request(QUrl("http://localhost:" + QString::number(server.serverPort()))); |
| 7594 |
QNetworkReplyPtr reply(manager.get(request)); |
| 7595 |
|
| 7596 |
QVERIFY2(waitForFinish(reply) == Success, msgWaitForFinished(reply)); |
| 7597 |
|
| 7598 |
QVERIFY(reply->isFinished()); |
| 7599 |
QCOMPARE(reply->error(), QNetworkReply::NoError); |
| 7600 |
QCOMPARE(reply->readAll(), QByteArray("GET")); |
| 7601 |
QCOMPARE(reply->attribute(QNetworkRequest::SourceIsFromCacheAttribute).toBool(), false); |
| 7602 |
|
| 7603 |
server.clearHeaderParserState(); |
| 7604 |
server.setDataToTransmit(getReply); |
| 7605 |
reply.reset(manager.get(request)); |
| 7606 |
QVERIFY2(waitForFinish(reply) == Success, msgWaitForFinished(reply)); |
| 7607 |
|
| 7608 |
QVERIFY(reply->isFinished()); |
| 7609 |
QCOMPARE(reply->error(), QNetworkReply::NoError); |
| 7610 |
QCOMPARE(reply->readAll(), QByteArray("GET")); |
| 7611 |
QCOMPARE(reply->attribute(QNetworkRequest::SourceIsFromCacheAttribute).toBool(), true); |
| 7612 |
|
| 7613 |
server.clearHeaderParserState(); |
| 7614 |
server.setDataToTransmit(postReply); |
| 7615 |
request.setRawHeader("Content-Type", "text/plain"); |
| 7616 |
reply.reset(manager.post(request, postData)); |
| 7617 |
|
| 7618 |
QVERIFY2(waitForFinish(reply) == Success, msgWaitForFinished(reply)); |
| 7619 |
|
| 7620 |
QVERIFY(reply->isFinished()); |
| 7621 |
QCOMPARE(reply->error(), QNetworkReply::NoError); |
| 7622 |
QCOMPARE(reply->rawHeader("Content-length"), QByteArray("4")); |
| 7623 |
QCOMPARE(reply->readAll(), QByteArray("POST")); |
| 7624 |
QCOMPARE(reply->attribute(QNetworkRequest::SourceIsFromCacheAttribute).toBool(), false); |
| 7625 |
|
| 7626 |
server.clearHeaderParserState(); |
| 7627 |
server.setDataToTransmit(getReply); |
| 7628 |
reply.reset(manager.get(request)); |
| 7629 |
|
| 7630 |
QVERIFY2(waitForFinish(reply) == Success, msgWaitForFinished(reply)); |
| 7631 |
|
| 7632 |
QVERIFY(reply->isFinished()); |
| 7633 |
QCOMPARE(reply->error(), QNetworkReply::NoError); |
| 7634 |
QCOMPARE(reply->readAll(), QByteArray("GET")); |
| 7635 |
QCOMPARE(reply->attribute(QNetworkRequest::SourceIsFromCacheAttribute).toBool(), false); |
| 7636 |
|
| 7637 |
server.clearHeaderParserState(); |
| 7638 |
server.setDataToTransmit(getReply); |
| 7639 |
reply.reset(manager.get(request)); |
| 7640 |
|
| 7641 |
QVERIFY2(waitForFinish(reply) == Success, msgWaitForFinished(reply)); |
| 7642 |
|
| 7643 |
QVERIFY(reply->isFinished()); |
| 7644 |
QCOMPARE(reply->error(), QNetworkReply::NoError); |
| 7645 |
QCOMPARE(reply->readAll(), QByteArray("GET")); |
| 7646 |
QCOMPARE(reply->attribute(QNetworkRequest::SourceIsFromCacheAttribute).toBool(), true); |
| 7647 |
|
| 7648 |
server.clearHeaderParserState(); |
| 7649 |
server.setDataToTransmit(putReply); |
| 7650 |
reply.reset(manager.put(request, postData)); |
| 7651 |
|
| 7652 |
QVERIFY2(waitForFinish(reply) == Success, msgWaitForFinished(reply)); |
| 7653 |
|
| 7654 |
QVERIFY(reply->isFinished()); |
| 7655 |
QCOMPARE(reply->error(), QNetworkReply::NoError); |
| 7656 |
QCOMPARE(reply->attribute(QNetworkRequest::SourceIsFromCacheAttribute).toBool(), false); |
| 7657 |
|
| 7658 |
server.clearHeaderParserState(); |
| 7659 |
server.setDataToTransmit(getReply); |
| 7660 |
reply.reset(manager.get(request)); |
| 7661 |
|
| 7662 |
QVERIFY2(waitForFinish(reply) == Success, msgWaitForFinished(reply)); |
| 7663 |
|
| 7664 |
QVERIFY(reply->isFinished()); |
| 7665 |
QCOMPARE(reply->error(), QNetworkReply::NoError); |
| 7666 |
QCOMPARE(reply->readAll(), QByteArray("GET")); |
| 7667 |
QCOMPARE(reply->attribute(QNetworkRequest::SourceIsFromCacheAttribute).toBool(), false); |
| 7668 |
|
| 7669 |
server.clearHeaderParserState(); |
| 7670 |
server.setDataToTransmit(getReply); |
| 7671 |
reply.reset(manager.get(request)); |
| 7672 |
|
| 7673 |
QVERIFY2(waitForFinish(reply) == Success, msgWaitForFinished(reply)); |
| 7674 |
|
| 7675 |
QVERIFY(reply->isFinished()); |
| 7676 |
QCOMPARE(reply->error(), QNetworkReply::NoError); |
| 7677 |
QCOMPARE(reply->readAll(), QByteArray("GET")); |
| 7678 |
QCOMPARE(reply->attribute(QNetworkRequest::SourceIsFromCacheAttribute).toBool(), true); |
| 7679 |
} |
| 7680 |
|
| 7681 |
void tst_QNetworkReply::qtbug45581WrongReplyStatusCode() |
| 7682 |
{ |
| 7683 |
const QUrl url("file:" + testDataDir + "/element.xml"); |
| 7684 |
QNetworkRequest request(url); |
| 7685 |
|
| 7686 |
QNetworkReplyPtr reply; |
| 7687 |
QSignalSpy finishedSpy(&manager, SIGNAL(finished(QNetworkReply*))); |
| 7688 |
QSignalSpy sslErrorsSpy(&manager, SIGNAL(sslErrors(QNetworkReply*,QList<QSslError>))); |
| 7689 |
RUN_REQUEST(runSimpleRequest(QNetworkAccessManager::GetOperation, request, reply, 0)); |
| 7690 |
QVERIFY(reply->isFinished()); |
| 7691 |
|
| 7692 |
const QByteArray expectedContent = |
| 7693 |
"<root attr=\"value\" attr2=\"value2\">" |
| 7694 |
"<person /><fruit /></root>" |
| 7695 |
#ifdef Q_OS_WIN |
| 7696 |
"\r" |
| 7697 |
#endif |
| 7698 |
"\n"; |
| 7699 |
|
| 7700 |
QCOMPARE(reply->readAll(), expectedContent); |
| 7701 |
|
| 7702 |
QCOMPARE(finishedSpy.count(), 0); |
| 7703 |
QCOMPARE(sslErrorsSpy.count(), 0); |
| 7704 |
|
| 7705 |
QCOMPARE(reply->header(QNetworkRequest::ContentLengthHeader).toLongLong(), expectedContent.size()); |
| 7706 |
|
| 7707 |
QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200); |
| 7708 |
QCOMPARE(reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString(), QLatin1String("OK")); |
| 7709 |
|
| 7710 |
reply->deleteLater(); |
| 7711 |
} |
| 7712 |
|
| 7713 |
void tst_QNetworkReply::synchronousRequest_data() |
| 7714 |
{ |
| 7715 |
QTest::addColumn<QUrl>("url"); |
| 7716 |
QTest::addColumn<QString>("expected"); |
| 7717 |
QTest::addColumn<bool>("checkContentLength"); |
| 7718 |
QTest::addColumn<QString>("mimeType"); |
| 7719 |
|
| 7720 |
// ### cache, auth, proxies |
| 7721 |
|
| 7722 |
QTest::newRow("http") |
| 7723 |
<< QUrl("http://" + QtNetworkSettings::httpServerName() + "/qtest/rfc3252.txt") |
| 7724 |
<< QString("file:" + testDataDir + "/rfc3252.txt") |
| 7725 |
<< true |
| 7726 |
<< QString("text/plain"); |
| 7727 |
|
| 7728 |
QTest::newRow("http-gzip") |
| 7729 |
<< QUrl("http://" + QtNetworkSettings::httpServerName() + "/qtest/deflate/rfc3252.txt") |
| 7730 |
<< QString("file:" + testDataDir + "/rfc3252.txt") |
| 7731 |
<< false // don't check content length, because it's gzip encoded |
| 7732 |
// ### we would need to enflate (un-deflate) the file content and compare the sizes |
| 7733 |
<< QString("text/plain"); |
| 7734 |
|
| 7735 |
#ifndef QT_NO_SSL |
| 7736 |
QTest::newRow("https") |
| 7737 |
<< QUrl("https://" + QtNetworkSettings::httpServerName() + "/qtest/rfc3252.txt") |
| 7738 |
<< QString("file:" + testDataDir + "/rfc3252.txt") |
| 7739 |
<< true |
| 7740 |
<< QString("text/plain"); |
| 7741 |
#endif |
| 7742 |
|
| 7743 |
QTest::newRow("data") |
| 7744 |
<< QUrl(QString::fromLatin1("data:text/plain,hello world")) |
| 7745 |
<< QString("data:hello world") |
| 7746 |
<< true // check content length |
| 7747 |
<< QString("text/plain"); |
| 7748 |
|
| 7749 |
QTest::newRow("simple-file") |
| 7750 |
<< QUrl::fromLocalFile(testDataDir + "/rfc3252.txt") |
| 7751 |
<< QString("file:" + testDataDir + "/rfc3252.txt") |
| 7752 |
<< true |
| 7753 |
<< QString(); |
| 7754 |
} |
| 7755 |
|
| 7756 |
// FIXME add testcase for failing network etc |
| 7757 |
void tst_QNetworkReply::synchronousRequest() |
| 7758 |
{ |
| 7759 |
QFETCH(QUrl, url); |
| 7760 |
QFETCH(QString, expected); |
| 7761 |
QFETCH(bool, checkContentLength); |
| 7762 |
QFETCH(QString, mimeType); |
| 7763 |
|
| 7764 |
QNetworkRequest request(url); |
| 7765 |
|
| 7766 |
#ifndef QT_NO_SSL |
| 7767 |
// workaround for HTTPS requests: add self-signed server cert to list of CA certs, |
| 7768 |
// since we cannot react to the sslErrors() signal |
| 7769 |
// to fix this properly we would need to have an ignoreSslErrors() method in the |
| 7770 |
// QNetworkRequest, see QTBUG-14774 |
| 7771 |
if (url.scheme() == "https") { |
| 7772 |
QSslConfiguration sslConf; |
| 7773 |
QList<QSslCertificate> certs = QSslCertificate::fromPath(testDataDir + certsFilePath); |
| 7774 |
sslConf.setCaCertificates(certs); |
| 7775 |
request.setSslConfiguration(sslConf); |
| 7776 |
} |
| 7777 |
#endif |
| 7778 |
|
| 7779 |
request.setAttribute( |
| 7780 |
QNetworkRequest::SynchronousRequestAttribute, |
| 7781 |
true); |
| 7782 |
|
| 7783 |
QNetworkReplyPtr reply; |
| 7784 |
QSignalSpy finishedSpy(&manager, SIGNAL(finished(QNetworkReply*))); |
| 7785 |
QSignalSpy sslErrorsSpy(&manager, SIGNAL(sslErrors(QNetworkReply*,QList<QSslError>))); |
| 7786 |
RUN_REQUEST(runSimpleRequest(QNetworkAccessManager::GetOperation, request, reply, 0)); |
| 7787 |
QVERIFY(reply->isFinished()); |
| 7788 |
QCOMPARE(finishedSpy.count(), 0); |
| 7789 |
QCOMPARE(sslErrorsSpy.count(), 0); |
| 7790 |
|
| 7791 |
QCOMPARE(reply->header(QNetworkRequest::ContentTypeHeader).toString(), mimeType); |
| 7792 |
|
| 7793 |
QByteArray expectedContent; |
| 7794 |
|
| 7795 |
if (expected.startsWith("file:")) { |
| 7796 |
QString path = expected.mid(5); |
| 7797 |
QFile file(path); |
| 7798 |
file.open(QIODevice::ReadOnly); |
| 7799 |
expectedContent = file.readAll(); |
| 7800 |
} else if (expected.startsWith("data:")) { |
| 7801 |
expectedContent = expected.mid(5).toUtf8(); |
| 7802 |
} |
| 7803 |
|
| 7804 |
if (checkContentLength) |
| 7805 |
QCOMPARE(reply->header(QNetworkRequest::ContentLengthHeader).toLongLong(), qint64(expectedContent.size())); |
| 7806 |
QCOMPARE(reply->readAll(), expectedContent); |
| 7807 |
|
| 7808 |
reply->deleteLater(); |
| 7809 |
} |
| 7810 |
|
| 7811 |
#ifndef QT_NO_SSL |
| 7812 |
void tst_QNetworkReply::synchronousRequestSslFailure() |
| 7813 |
{ |
| 7814 |
// test that SSL won't be accepted with self-signed certificate, |
| 7815 |
// and that we do not emit the sslError signal (in the manager that is, |
| 7816 |
// in the reply we don't care) |
| 7817 |
|
| 7818 |
QUrl url("https://" + QtNetworkSettings::httpServerName() + "/qtest/rfc3252.txt"); |
| 7819 |
QNetworkRequest request(url); |
| 7820 |
request.setAttribute( |
| 7821 |
QNetworkRequest::SynchronousRequestAttribute, |
| 7822 |
true); |
| 7823 |
QNetworkReplyPtr reply; |
| 7824 |
QSignalSpy sslErrorsSpy(&manager, SIGNAL(sslErrors(QNetworkReply*,QList<QSslError>))); |
| 7825 |
runSimpleRequest(QNetworkAccessManager::GetOperation, request, reply, 0); |
| 7826 |
QVERIFY(reply->isFinished()); |
| 7827 |
QCOMPARE(reply->error(), QNetworkReply::SslHandshakeFailedError); |
| 7828 |
QCOMPARE(sslErrorsSpy.count(), 0); |
| 7829 |
} |
| 7830 |
#endif |
| 7831 |
|
| 7832 |
class HttpAbortHelper : public QObject |
| 7833 |
{ |
| 7834 |
Q_OBJECT |
| 7835 |
public: |
| 7836 |
HttpAbortHelper(QNetworkReply *parent) |
| 7837 |
: QObject(parent) |
| 7838 |
{ |
| 7839 |
mReply = parent; |
| 7840 |
connect(parent, SIGNAL(readyRead()), this, SLOT(readyRead())); |
| 7841 |
} |
| 7842 |
|
| 7843 |
~HttpAbortHelper() |
| 7844 |
{ |
| 7845 |
} |
| 7846 |
|
| 7847 |
public slots: |
| 7848 |
void readyRead() |
| 7849 |
{ |
| 7850 |
mReply->abort(); |
| 7851 |
QMetaObject::invokeMethod(&QTestEventLoop::instance(), "exitLoop", Qt::QueuedConnection); |
| 7852 |
} |
| 7853 |
|
| 7854 |
private: |
| 7855 |
QNetworkReply *mReply; |
| 7856 |
}; |
| 7857 |
|
| 7858 |
void tst_QNetworkReply::httpAbort() |
| 7859 |
{ |
| 7860 |
// FIXME Also implement one where we do a big upload and then abort(). |
| 7861 |
// It must not crash either. |
| 7862 |
|
| 7863 |
// Abort after the first readyRead() |
| 7864 |
QNetworkRequest request("http://" + QtNetworkSettings::httpServerName() + "/qtest/bigfile"); |
| 7865 |
QNetworkReplyPtr reply(manager.get(request)); |
| 7866 |
HttpAbortHelper replyHolder(reply.data()); |
| 7867 |
QTestEventLoop::instance().enterLoop(10); |
| 7868 |
QVERIFY(!QTestEventLoop::instance().timeout()); |
| 7869 |
QCOMPARE(reply->error(), QNetworkReply::OperationCanceledError); |
| 7870 |
QVERIFY(reply->isFinished()); |
| 7871 |
|
| 7872 |
// Abort immediately after the get() |
| 7873 |
QNetworkReplyPtr reply2(manager.get(request)); |
| 7874 |
connect(reply2, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop())); |
| 7875 |
reply2->abort(); |
| 7876 |
QCOMPARE(reply2->error(), QNetworkReply::OperationCanceledError); |
| 7877 |
QVERIFY(reply2->isFinished()); |
| 7878 |
|
| 7879 |
// Abort after the finished() |
| 7880 |
QNetworkRequest request3("http://" + QtNetworkSettings::httpServerName() + "/qtest/rfc3252.txt"); |
| 7881 |
QNetworkReplyPtr reply3(manager.get(request3)); |
| 7882 |
|
| 7883 |
QCOMPARE(waitForFinish(reply3), int(Success)); |
| 7884 |
|
| 7885 |
QVERIFY(reply3->isFinished()); |
| 7886 |
reply3->abort(); |
| 7887 |
QCOMPARE(reply3->error(), QNetworkReply::NoError); |
| 7888 |
} |
| 7889 |
|
| 7890 |
void tst_QNetworkReply::dontInsertPartialContentIntoTheCache() |
| 7891 |
{ |
| 7892 |
QByteArray reply206 = |
| 7893 |
"HTTP/1.0 206\r\n" |
| 7894 |
"Connection: keep-alive\r\n" |
| 7895 |
"Content-Type: text/plain\r\n" |
| 7896 |
"Cache-control: no-cache\r\n" |
| 7897 |
"Content-Range: bytes 2-6/8\r\n" |
| 7898 |
"Content-length: 4\r\n" |
| 7899 |
"\r\n" |
| 7900 |
"load"; |
| 7901 |
|
| 7902 |
MiniHttpServer server(reply206); |
| 7903 |
server.doClose = false; |
| 7904 |
|
| 7905 |
MySpyMemoryCache *memoryCache = new MySpyMemoryCache(&manager); |
| 7906 |
manager.setCache(memoryCache); |
| 7907 |
|
| 7908 |
QUrl url = "http://localhost:" + QString::number(server.serverPort()); |
| 7909 |
QNetworkRequest request(url); |
| 7910 |
request.setRawHeader("Range", "bytes=2-6"); |
| 7911 |
|
| 7912 |
QNetworkReplyPtr reply(manager.get(request)); |
| 7913 |
|
| 7914 |
QVERIFY2(waitForFinish(reply) == Success, msgWaitForFinished(reply)); |
| 7915 |
|
| 7916 |
QVERIFY(server.totalConnections > 0); |
| 7917 |
QCOMPARE(reply->readAll().constData(), "load"); |
| 7918 |
QCOMPARE(memoryCache->m_insertedUrls.count(), 0); |
| 7919 |
} |
| 7920 |
|
| 7921 |
void tst_QNetworkReply::httpUserAgent() |
| 7922 |
{ |
| 7923 |
QByteArray response("HTTP/1.0 200 OK\r\n\r\n"); |
| 7924 |
MiniHttpServer server(response); |
| 7925 |
server.doClose = true; |
| 7926 |
|
| 7927 |
QNetworkRequest request(QUrl("http://localhost:" + QString::number(server.serverPort()))); |
| 7928 |
request.setHeader(QNetworkRequest::UserAgentHeader, "abcDEFghi"); |
| 7929 |
QNetworkReplyPtr reply(manager.get(request)); |
| 7930 |
|
| 7931 |
QVERIFY2(waitForFinish(reply) == Success, msgWaitForFinished(reply)); |
| 7932 |
|
| 7933 |
QVERIFY(reply->isFinished()); |
| 7934 |
QCOMPARE(reply->error(), QNetworkReply::NoError); |
| 7935 |
QVERIFY(server.receivedData.contains("\r\nUser-Agent: abcDEFghi\r\n")); |
| 7936 |
} |
| 7937 |
|
| 7938 |
void tst_QNetworkReply::synchronousAuthenticationCache() |
| 7939 |
{ |
| 7940 |
class MiniAuthServer : public MiniHttpServer |
| 7941 |
{ |
| 7942 |
public: |
| 7943 |
MiniAuthServer(QThread *thread) : MiniHttpServer(QByteArray(), false, thread) {} |
| 7944 |
virtual void reply() |
| 7945 |
{ |
| 7946 |
|
| 7947 |
dataToTransmit = |
| 7948 |
"HTTP/1.0 401 Unauthorized\r\n" |
| 7949 |
"WWW-Authenticate: Basic realm=\"QNetworkAccessManager Test Realm\"\r\n" |
| 7950 |
"Content-Length: 4\r\n" |
| 7951 |
"Connection: close\r\n" |
| 7952 |
"Content-Type: text/plain\r\n" |
| 7953 |
"\r\n" |
| 7954 |
"auth"; |
| 7955 |
QRegularExpression rx("Authorization: Basic ([^\r\n]*)\r\n"); |
| 7956 |
QRegularExpressionMatch match = rx.match(receivedData); |
| 7957 |
if (match.hasMatch()) { |
| 7958 |
if (QByteArray::fromBase64(match.captured(1).toLatin1()) == "login:password") { |
| 7959 |
dataToTransmit = |
| 7960 |
"HTTP/1.0 200 OK\r\n" |
| 7961 |
"Content-Type: text/plain\r\n" |
| 7962 |
"Content-Length: 2\r\n" |
| 7963 |
"\r\n" |
| 7964 |
"OK"; |
| 7965 |
} |
| 7966 |
} |
| 7967 |
receivedData.clear(); |
| 7968 |
MiniHttpServer::reply(); |
| 7969 |
} |
| 7970 |
}; |
| 7971 |
|
| 7972 |
// when using synchronous commands, we need a different event loop for |
| 7973 |
// the server thread, because the client is never returning to the |
| 7974 |
// event loop |
| 7975 |
QScopedPointer<QThread, QThreadCleanup> serverThread(new QThread); |
| 7976 |
QScopedPointer<MiniHttpServer, QDeleteLaterCleanup> server(new MiniAuthServer(serverThread.data())); |
| 7977 |
server->doClose = true; |
| 7978 |
|
| 7979 |
//1) URL without credentials, we are not authenticated |
| 7980 |
{ |
| 7981 |
QUrl url = "http://localhost:" + QString::number(server->serverPort()) + "/path"; |
| 7982 |
QNetworkRequest request(url); |
| 7983 |
request.setAttribute(QNetworkRequest::SynchronousRequestAttribute, true); |
| 7984 |
|
| 7985 |
QNetworkReplyPtr reply(manager.get(request)); |
| 7986 |
QVERIFY(reply->isFinished()); |
| 7987 |
QCOMPARE(reply->error(), QNetworkReply::AuthenticationRequiredError); |
| 7988 |
} |
| 7989 |
|
| 7990 |
//2) URL with credentials, we are authenticated |
| 7991 |
{ |
| 7992 |
QUrl url = "http://login:password@localhost:" + QString::number(server->serverPort()) + "/path2"; |
| 7993 |
QNetworkRequest request(url); |
| 7994 |
request.setAttribute(QNetworkRequest::SynchronousRequestAttribute, true); |
| 7995 |
|
| 7996 |
QNetworkReplyPtr reply(manager.get(request)); |
| 7997 |
QVERIFY(reply->isFinished()); |
| 7998 |
QCOMPARE(reply->error(), QNetworkReply::NoError); |
| 7999 |
QCOMPARE(reply->readAll().constData(), "OK"); |
| 8000 |
} |
| 8001 |
|
| 8002 |
//3) URL without credentials, we are authenticated because they are cached |
| 8003 |
{ |
| 8004 |
QUrl url = "http://localhost:" + QString::number(server->serverPort()) + "/path3"; |
| 8005 |
QNetworkRequest request(url); |
| 8006 |
request.setAttribute(QNetworkRequest::SynchronousRequestAttribute, true); |
| 8007 |
|
| 8008 |
QNetworkReplyPtr reply(manager.get(request)); |
| 8009 |
QVERIFY(reply->isFinished()); |
| 8010 |
QCOMPARE(reply->error(), QNetworkReply::NoError); |
| 8011 |
QCOMPARE(reply->readAll().constData(), "OK"); |
| 8012 |
} |
| 8013 |
} |
| 8014 |
|
| 8015 |
void tst_QNetworkReply::pipelining() |
| 8016 |
{ |
| 8017 |
QString urlString("http://" + QtNetworkSettings::httpServerName() + "/qtest/cgi-bin/echo.cgi?"); |
| 8018 |
QList<QNetworkReplyPtr> replies; |
| 8019 |
for (int a = 0; a < 20; a++) { |
| 8020 |
QNetworkRequest request(urlString + QString::number(a)); |
| 8021 |
request.setAttribute(QNetworkRequest::HttpPipeliningAllowedAttribute, QVariant(true)); |
| 8022 |
replies.append(QNetworkReplyPtr(manager.get(request))); |
| 8023 |
connect(replies.at(a), SIGNAL(finished()), this, SLOT(pipeliningHelperSlot())); |
| 8024 |
} |
| 8025 |
QTestEventLoop::instance().enterLoop(20); |
| 8026 |
QVERIFY(!QTestEventLoop::instance().timeout()); |
| 8027 |
} |
| 8028 |
|
| 8029 |
void tst_QNetworkReply::pipeliningHelperSlot() { |
| 8030 |
static int a = 0; |
| 8031 |
|
| 8032 |
// check that pipelining was used in at least one of the replies |
| 8033 |
static bool pipeliningWasUsed = false; |
| 8034 |
QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender()); |
| 8035 |
bool pipeliningWasUsedInReply = reply->attribute(QNetworkRequest::HttpPipeliningWasUsedAttribute).toBool(); |
| 8036 |
if (pipeliningWasUsedInReply) |
| 8037 |
pipeliningWasUsed = true; |
| 8038 |
|
| 8039 |
// check that the contents match (the response to echo.cgi?3 should return 3 etc.) |
| 8040 |
QString urlQueryString = reply->url().query(); |
| 8041 |
QString content = reply->readAll(); |
| 8042 |
QVERIFY2(urlQueryString == content, "data corruption with pipelining detected"); |
| 8043 |
|
| 8044 |
a++; |
| 8045 |
|
| 8046 |
if (a == 20) { // all replies have finished |
| 8047 |
QTestEventLoop::instance().exitLoop(); |
| 8048 |
QVERIFY2(pipeliningWasUsed, "pipelining was not used in any of the replies when trying to test pipelining"); |
| 8049 |
} |
| 8050 |
} |
| 8051 |
|
| 8052 |
void tst_QNetworkReply::emitErrorForAllRepliesSlot() { |
| 8053 |
static int a = 0; |
| 8054 |
if (++a == 3) |
| 8055 |
QTestEventLoop::instance().exitLoop(); |
| 8056 |
} |
| 8057 |
|
| 8058 |
void tst_QNetworkReply::closeDuringDownload_data() |
| 8059 |
{ |
| 8060 |
QTest::addColumn<QUrl>("url"); |
| 8061 |
QTest::newRow("http") << QUrl("http://" + QtNetworkSettings::httpServerName() + "/bigfile"); |
| 8062 |
QTest::newRow("ftp") << QUrl("ftp://" + QtNetworkSettings::ftpServerName() + "/qtest/bigfile"); |
| 8063 |
} |
| 8064 |
|
| 8065 |
void tst_QNetworkReply::closeDuringDownload() |
| 8066 |
{ |
| 8067 |
QFETCH(QUrl, url); |
| 8068 |
QNetworkRequest request(url); |
| 8069 |
QNetworkReply* reply = manager.get(request); |
| 8070 |
QSignalSpy readyReadSpy(reply, &QNetworkReply::readyRead); |
| 8071 |
QVERIFY(readyReadSpy.wait(10000)); |
| 8072 |
QSignalSpy destroySpy(reply, &QObject::destroyed); |
| 8073 |
reply->close(); |
| 8074 |
reply->deleteLater(); |
| 8075 |
// Wait for destruction to avoid a warning caused by test's cleanup() |
| 8076 |
// destroying the connection cache before the abort is finished |
| 8077 |
QVERIFY(destroySpy.wait()); |
| 8078 |
} |
| 8079 |
|
| 8080 |
void tst_QNetworkReply::ftpAuthentication_data() |
| 8081 |
{ |
| 8082 |
QTest::addColumn<QString>("referenceName"); |
| 8083 |
QTest::addColumn<QString>("url"); |
| 8084 |
QTest::addColumn<int>("error"); |
| 8085 |
|
| 8086 |
QTest::newRow("invalidPassword") << (testDataDir + "/rfc3252.txt") << "ftp://ftptest:invalid@" + QtNetworkSettings::ftpServerName() + "/home/qt-test-server/ftp/qtest/rfc3252.txt" << int(QNetworkReply::AuthenticationRequiredError); |
| 8087 |
QTest::newRow("validPassword") << (testDataDir + "/rfc3252.txt") << "ftp://ftptest:password@" + QtNetworkSettings::ftpServerName() + "/home/qt-test-server/ftp/qtest/rfc3252.txt" << int(QNetworkReply::NoError); |
| 8088 |
} |
| 8089 |
|
| 8090 |
void tst_QNetworkReply::ftpAuthentication() |
| 8091 |
{ |
| 8092 |
QFETCH(QString, referenceName); |
| 8093 |
QFETCH(QString, url); |
| 8094 |
QFETCH(int, error); |
| 8095 |
|
| 8096 |
QFile reference(referenceName); |
| 8097 |
QVERIFY(reference.open(QIODevice::ReadOnly)); |
| 8098 |
|
| 8099 |
QNetworkRequest request(url); |
| 8100 |
QNetworkReplyPtr reply; |
| 8101 |
runSimpleRequest(QNetworkAccessManager::GetOperation, request, reply); |
| 8102 |
|
| 8103 |
QCOMPARE(reply->url(), request.url()); |
| 8104 |
QCOMPARE(reply->error(), QNetworkReply::NetworkError(error)); |
| 8105 |
} |
| 8106 |
|
| 8107 |
void tst_QNetworkReply::emitErrorForAllReplies() // QTBUG-36890 |
| 8108 |
{ |
| 8109 |
// port 100 is not well-known and should be closed |
| 8110 |
QList<QUrl> urls = QList<QUrl>() << QUrl("http://localhost:100/request1") |
| 8111 |
<< QUrl("http://localhost:100/request2") |
| 8112 |
<< QUrl("http://localhost:100/request3"); |
| 8113 |
QList<QNetworkReply *> replies; |
| 8114 |
QList<QSignalSpy *> errorSpies; |
| 8115 |
QList<QSignalSpy *> finishedSpies; |
| 8116 |
for (int a = 0; a < urls.count(); ++a) { |
| 8117 |
QNetworkRequest request(urls.at(a)); |
| 8118 |
QNetworkReply *reply = manager.get(request); |
| 8119 |
replies.append(reply); |
| 8120 |
QSignalSpy *errorSpy = new QSignalSpy(reply, SIGNAL(errorOccurred(QNetworkReply::NetworkError))); |
| 8121 |
errorSpies.append(errorSpy); |
| 8122 |
QSignalSpy *finishedSpy = new QSignalSpy(reply, SIGNAL(finished())); |
| 8123 |
finishedSpies.append(finishedSpy); |
| 8124 |
QObject::connect(reply, SIGNAL(finished()), SLOT(emitErrorForAllRepliesSlot())); |
| 8125 |
} |
| 8126 |
QTestEventLoop::instance().enterLoop(10); |
| 8127 |
QVERIFY(!QTestEventLoop::instance().timeout()); |
| 8128 |
for (int a = 0; a < urls.count(); ++a) { |
| 8129 |
QVERIFY(replies.at(a)->isFinished()); |
| 8130 |
QCOMPARE(errorSpies.at(a)->count(), 1); |
| 8131 |
errorSpies.at(a)->deleteLater(); |
| 8132 |
QCOMPARE(finishedSpies.at(a)->count(), 1); |
| 8133 |
finishedSpies.at(a)->deleteLater(); |
| 8134 |
replies.at(a)->deleteLater(); |
| 8135 |
} |
| 8136 |
} |
| 8137 |
|
| 8138 |
#ifdef QT_BUILD_INTERNAL |
| 8139 |
void tst_QNetworkReply::backgroundRequest_data() |
| 8140 |
{ |
| 8141 |
#ifndef QT_NO_BEARERMANAGEMENT |
| 8142 |
QTest::addColumn<QUrl>("url"); |
| 8143 |
QTest::addColumn<bool>("background"); |
| 8144 |
QTest::addColumn<int>("policy"); |
| 8145 |
QTest::addColumn<QNetworkReply::NetworkError>("error"); |
| 8146 |
|
| 8147 |
QUrl httpurl("http://" + QtNetworkSettings::httpServerName()); |
| 8148 |
QUrl httpsurl("https://" + QtNetworkSettings::httpServerName()); |
| 8149 |
QUrl ftpurl("ftp://" + QtNetworkSettings::ftpServerName() + "/qtest/rfc3252.txt"); |
| 8150 |
|
| 8151 |
QTest::newRow("http, fg, normal") << httpurl << false << (int)QNetworkSession::NoPolicy << QNetworkReply::NoError; |
| 8152 |
QTest::newRow("http, bg, normal") << httpurl << true << (int)QNetworkSession::NoPolicy << QNetworkReply::NoError; |
| 8153 |
QTest::newRow("http, fg, nobg") << httpurl << false << (int)QNetworkSession::NoBackgroundTrafficPolicy << QNetworkReply::NoError; |
| 8154 |
QTest::newRow("http, bg, nobg") << httpurl << true << (int)QNetworkSession::NoBackgroundTrafficPolicy << QNetworkReply::BackgroundRequestNotAllowedError; |
| 8155 |
|
| 8156 |
#ifndef QT_NO_SSL |
| 8157 |
QTest::newRow("https, fg, normal") << httpsurl << false << (int)QNetworkSession::NoPolicy << QNetworkReply::NoError; |
| 8158 |
QTest::newRow("https, bg, normal") << httpsurl << true << (int)QNetworkSession::NoPolicy << QNetworkReply::NoError; |
| 8159 |
QTest::newRow("https, fg, nobg") << httpsurl << false << (int)QNetworkSession::NoBackgroundTrafficPolicy << QNetworkReply::NoError; |
| 8160 |
QTest::newRow("https, bg, nobg") << httpsurl << true << (int)QNetworkSession::NoBackgroundTrafficPolicy << QNetworkReply::BackgroundRequestNotAllowedError; |
| 8161 |
#endif |
| 8162 |
|
| 8163 |
QTest::newRow("ftp, fg, normal") << ftpurl << false << (int)QNetworkSession::NoPolicy << QNetworkReply::NoError; |
| 8164 |
QTest::newRow("ftp, bg, normal") << ftpurl << true << (int)QNetworkSession::NoPolicy << QNetworkReply::NoError; |
| 8165 |
QTest::newRow("ftp, fg, nobg") << ftpurl << false << (int)QNetworkSession::NoBackgroundTrafficPolicy << QNetworkReply::NoError; |
| 8166 |
QTest::newRow("ftp, bg, nobg") << ftpurl << true << (int)QNetworkSession::NoBackgroundTrafficPolicy << QNetworkReply::BackgroundRequestNotAllowedError; |
| 8167 |
#endif // !QT_NO_BEARERMANAGEMENT |
| 8168 |
} |
| 8169 |
#endif |
| 8170 |
|
| 8171 |
//test purpose: background requests can't be started when not allowed |
| 8172 |
#ifdef QT_BUILD_INTERNAL |
| 8173 |
void tst_QNetworkReply::backgroundRequest() |
| 8174 |
{ |
| 8175 |
#ifndef QT_NO_BEARERMANAGEMENT |
| 8176 |
QFETCH(QUrl, url); |
| 8177 |
QFETCH(bool, background); |
| 8178 |
QFETCH(int, policy); |
| 8179 |
QFETCH(QNetworkReply::NetworkError, error); |
| 8180 |
|
| 8181 |
QNetworkRequest request(url); |
| 8182 |
|
| 8183 |
if (background) |
| 8184 |
request.setAttribute(QNetworkRequest::BackgroundRequestAttribute, QVariant::fromValue(true)); |
| 8185 |
|
| 8186 |
//this preconstructs the session so we can change policies in advance |
| 8187 |
manager.setConfiguration(networkConfiguration); |
| 8188 |
|
| 8189 |
#ifndef QT_NO_SSL |
| 8190 |
connect(&manager, SIGNAL(sslErrors(QNetworkReply*,QList<QSslError>)), |
| 8191 |
SLOT(sslErrors(QNetworkReply*,QList<QSslError>))); |
| 8192 |
#endif |
| 8193 |
|
| 8194 |
const QWeakPointer<const QNetworkSession> sessionWeakPtr = QNetworkAccessManagerPrivate::getNetworkSession(&manager); |
| 8195 |
QVERIFY(!sessionWeakPtr.isNull()); |
| 8196 |
auto session = const_cast<QNetworkSession *>(sessionWeakPtr.toStrongRef().data()); |
| 8197 |
QNetworkSession::UsagePolicies original = session->usagePolicies(); |
| 8198 |
QNetworkSessionPrivate::setUsagePolicies(*session, QNetworkSession::UsagePolicies(policy)); |
| 8199 |
|
| 8200 |
QNetworkReplyPtr reply(manager.get(request)); |
| 8201 |
|
| 8202 |
QVERIFY(waitForFinish(reply) != Timeout); |
| 8203 |
if (session) |
| 8204 |
QNetworkSessionPrivate::setUsagePolicies(*session, original); |
| 8205 |
|
| 8206 |
QVERIFY(reply->isFinished()); |
| 8207 |
QCOMPARE(reply->error(), error); |
| 8208 |
#endif |
| 8209 |
} |
| 8210 |
#endif |
| 8211 |
|
| 8212 |
#ifdef QT_BUILD_INTERNAL |
| 8213 |
void tst_QNetworkReply::backgroundRequestInterruption_data() |
| 8214 |
{ |
| 8215 |
QTest::addColumn<QUrl>("url"); |
| 8216 |
QTest::addColumn<bool>("background"); |
| 8217 |
QTest::addColumn<QNetworkReply::NetworkError>("error"); |
| 8218 |
|
| 8219 |
QUrl httpurl("http://" + QtNetworkSettings::httpServerName() + "/qtest/mediumfile"); |
| 8220 |
QUrl httpsurl("https://" + QtNetworkSettings::httpServerName() + "/qtest/mediumfile"); |
| 8221 |
QUrl ftpurl("ftp://" + QtNetworkSettings::ftpServerName() + "/qtest/bigfile"); |
| 8222 |
|
| 8223 |
QTest::newRow("http, fg, nobg") << httpurl << false << QNetworkReply::NoError; |
| 8224 |
QTest::newRow("http, bg, nobg") << httpurl << true << QNetworkReply::BackgroundRequestNotAllowedError; |
| 8225 |
|
| 8226 |
#ifndef QT_NO_SSL |
| 8227 |
QTest::newRow("https, fg, nobg") << httpsurl << false << QNetworkReply::NoError; |
| 8228 |
QTest::newRow("https, bg, nobg") << httpsurl << true << QNetworkReply::BackgroundRequestNotAllowedError; |
| 8229 |
#endif |
| 8230 |
|
| 8231 |
QTest::newRow("ftp, fg, nobg") << ftpurl << false << QNetworkReply::NoError; |
| 8232 |
QTest::newRow("ftp, bg, nobg") << ftpurl << true << QNetworkReply::BackgroundRequestNotAllowedError; |
| 8233 |
|
| 8234 |
} |
| 8235 |
#endif |
| 8236 |
|
| 8237 |
//test purpose: background requests in progress are aborted when policy changes to disallow them |
| 8238 |
#ifdef QT_BUILD_INTERNAL |
| 8239 |
void tst_QNetworkReply::backgroundRequestInterruption() |
| 8240 |
{ |
| 8241 |
#ifndef QT_NO_BEARERMANAGEMENT |
| 8242 |
if (QNetworkStatusMonitor::isEnabled() && QByteArray(QTest::currentDataTag()).startsWith("http")) |
| 8243 |
QSKIP("This test (currently) doesn't make any sense when QNetworkStatusMonitor is enabled"); |
| 8244 |
|
| 8245 |
QFETCH(QUrl, url); |
| 8246 |
QFETCH(bool, background); |
| 8247 |
QFETCH(QNetworkReply::NetworkError, error); |
| 8248 |
|
| 8249 |
QNetworkRequest request(url); |
| 8250 |
|
| 8251 |
if (background) |
| 8252 |
request.setAttribute(QNetworkRequest::BackgroundRequestAttribute, QVariant::fromValue(true)); |
| 8253 |
|
| 8254 |
//this preconstructs the session so we can change policies in advance |
| 8255 |
manager.setConfiguration(networkConfiguration); |
| 8256 |
|
| 8257 |
#ifndef QT_NO_SSL |
| 8258 |
connect(&manager, SIGNAL(sslErrors(QNetworkReply*,QList<QSslError>)), |
| 8259 |
SLOT(sslErrors(QNetworkReply*,QList<QSslError>))); |
| 8260 |
#endif |
| 8261 |
|
| 8262 |
const QWeakPointer<const QNetworkSession> sessionWeakPtr = QNetworkAccessManagerPrivate::getNetworkSession(&manager); |
| 8263 |
QVERIFY(!sessionWeakPtr.isNull()); |
| 8264 |
auto session = const_cast<QNetworkSession *>(sessionWeakPtr.toStrongRef().data()); |
| 8265 |
QNetworkSession::UsagePolicies original = session->usagePolicies(); |
| 8266 |
QNetworkSessionPrivate::setUsagePolicies(*session, QNetworkSession::NoPolicy); |
| 8267 |
|
| 8268 |
request.setAttribute(QNetworkRequest::MaximumDownloadBufferSizeAttribute, 8192); |
| 8269 |
QNetworkReplyPtr reply(manager.get(request)); |
| 8270 |
reply->setReadBufferSize(1024); |
| 8271 |
|
| 8272 |
QSignalSpy spy(reply.data(), SIGNAL(readyRead())); |
| 8273 |
QTRY_VERIFY(spy.count() > 0); |
| 8274 |
|
| 8275 |
QNetworkSessionPrivate::setUsagePolicies(*session, QNetworkSession::NoBackgroundTrafficPolicy); |
| 8276 |
|
| 8277 |
// After we have changed the policy we can download at full speed. |
| 8278 |
reply->setReadBufferSize(0); |
| 8279 |
|
| 8280 |
QVERIFY(waitForFinish(reply) != Timeout); |
| 8281 |
if (session) |
| 8282 |
QNetworkSessionPrivate::setUsagePolicies(*session, original); |
| 8283 |
|
| 8284 |
QVERIFY(reply->isFinished()); |
| 8285 |
QCOMPARE(reply->error(), error); |
| 8286 |
#endif |
| 8287 |
} |
| 8288 |
#endif |
| 8289 |
|
| 8290 |
#ifdef QT_BUILD_INTERNAL |
| 8291 |
void tst_QNetworkReply::backgroundRequestConnectInBackground_data() |
| 8292 |
{ |
| 8293 |
QTest::addColumn<QUrl>("url"); |
| 8294 |
QTest::addColumn<bool>("background"); |
| 8295 |
|
| 8296 |
QUrl httpurl("http://" + QtNetworkSettings::httpServerName()); |
| 8297 |
QUrl ftpurl("ftp://" + QtNetworkSettings::ftpServerName() + "/qtest/rfc3252.txt"); |
| 8298 |
|
| 8299 |
QTest::newRow("http, fg") << httpurl << false; |
| 8300 |
QTest::newRow("http, bg") << httpurl << true; |
| 8301 |
|
| 8302 |
QTest::newRow("ftp, fg") << ftpurl << false; |
| 8303 |
QTest::newRow("ftp, bg") << ftpurl << true; |
| 8304 |
} |
| 8305 |
#endif |
| 8306 |
|
| 8307 |
//test purpose: check that backgroundness is propagated to the network session |
| 8308 |
#ifdef QT_BUILD_INTERNAL |
| 8309 |
void tst_QNetworkReply::backgroundRequestConnectInBackground() |
| 8310 |
{ |
| 8311 |
#ifndef QT_NO_BEARERMANAGEMENT |
| 8312 |
QFETCH(QUrl, url); |
| 8313 |
QFETCH(bool, background); |
| 8314 |
|
| 8315 |
QNetworkRequest request(url); |
| 8316 |
|
| 8317 |
if (background) |
| 8318 |
request.setAttribute(QNetworkRequest::BackgroundRequestAttribute, QVariant::fromValue(true)); |
| 8319 |
|
| 8320 |
QWeakPointer<const QNetworkSession> session = QNetworkAccessManagerPrivate::getNetworkSession(&manager); |
| 8321 |
//force QNAM to reopen the session. |
| 8322 |
if (session && session.toStrongRef().data()->isOpen()) { |
| 8323 |
const_cast<QNetworkSession *>(session.toStrongRef().data())->close(); |
| 8324 |
QCoreApplication::processEvents(); //let signals propagate inside QNAM |
| 8325 |
} |
| 8326 |
|
| 8327 |
//this preconstructs the session so we can change policies in advance |
| 8328 |
manager.setConfiguration(networkConfiguration); |
| 8329 |
|
| 8330 |
session = QNetworkAccessManagerPrivate::getNetworkSession(&manager); |
| 8331 |
QVERIFY(session); |
| 8332 |
QNetworkSession::UsagePolicies original = session.toStrongRef().data()->usagePolicies(); |
| 8333 |
QNetworkSessionPrivate::setUsagePolicies(*const_cast<QNetworkSession *>(session.toStrongRef().data()), QNetworkSession::NoPolicy); |
| 8334 |
|
| 8335 |
QNetworkReplyPtr reply(manager.get(request)); |
| 8336 |
|
| 8337 |
QVERIFY(waitForFinish(reply) != Timeout); |
| 8338 |
session = QNetworkAccessManagerPrivate::getNetworkSession(&manager); |
| 8339 |
if (session) { |
| 8340 |
QVariant cib = session.toStrongRef().data()->sessionProperty(QStringLiteral("ConnectInBackground")); |
| 8341 |
if (!cib.isValid()) |
| 8342 |
QSKIP("inconclusive - ConnectInBackground session property not supported by the bearer plugin"); |
| 8343 |
QCOMPARE(cib.toBool(), background); |
| 8344 |
QNetworkSessionPrivate::setUsagePolicies(*const_cast<QNetworkSession *>(session.toStrongRef().data()), original); |
| 8345 |
} else { |
| 8346 |
QSKIP("inconclusive - network session has been destroyed"); |
| 8347 |
} |
| 8348 |
|
| 8349 |
QVERIFY(reply->isFinished()); |
| 8350 |
#endif |
| 8351 |
} |
| 8352 |
#endif |
| 8353 |
|
| 8354 |
class RateLimitedUploadDevice : public QIODevice |
| 8355 |
{ |
| 8356 |
Q_OBJECT |
| 8357 |
public: |
| 8358 |
QByteArray data; |
| 8359 |
QBuffer buffer; |
| 8360 |
qint64 read; |
| 8361 |
qint64 bandwidthQuota; |
| 8362 |
QTimer timer; |
| 8363 |
|
| 8364 |
RateLimitedUploadDevice(QByteArray d) : QIODevice(),data(d),read(0),bandwidthQuota(0) |
| 8365 |
{ |
| 8366 |
buffer.setData(data); |
| 8367 |
buffer.open(QIODevice::ReadOnly); |
| 8368 |
timer.setInterval(200); |
| 8369 |
QObject::connect(&timer, SIGNAL(timeout()), this, SLOT(timeoutSlot())); |
| 8370 |
timer.start(); |
| 8371 |
} |
| 8372 |
|
| 8373 |
virtual qint64 writeData(const char* , qint64 ) |
| 8374 |
{ |
| 8375 |
Q_ASSERT(false); |
| 8376 |
return 0; |
| 8377 |
} |
| 8378 |
|
| 8379 |
virtual qint64 readData(char* data, qint64 maxlen) |
| 8380 |
{ |
| 8381 |
//qDebug() << Q_FUNC_INFO << maxlen << bandwidthQuota; |
| 8382 |
maxlen = qMin(maxlen, buffer.bytesAvailable()); |
| 8383 |
maxlen = qMin(maxlen, bandwidthQuota); |
| 8384 |
if (maxlen <= 0) { // no quota or at end |
| 8385 |
return 0; |
| 8386 |
} |
| 8387 |
bandwidthQuota -= maxlen; // reduce quota |
| 8388 |
|
| 8389 |
qint64 ret = buffer.read(data, maxlen); |
| 8390 |
if (ret == -1) { |
| 8391 |
return -1; |
| 8392 |
} |
| 8393 |
read += ret; |
| 8394 |
//qDebug() << Q_FUNC_INFO << maxlen << bandwidthQuota << read << ret << buffer.bytesAvailable(); |
| 8395 |
return ret; |
| 8396 |
} |
| 8397 |
virtual bool atEnd() const { return buffer.atEnd(); } |
| 8398 |
virtual qint64 size() const { return data.length(); } |
| 8399 |
qint64 bytesAvailable() const |
| 8400 |
{ |
| 8401 |
return buffer.bytesAvailable() + QIODevice::bytesAvailable(); |
| 8402 |
} |
| 8403 |
virtual bool isSequential() const { return false; } // random access, we can seek |
| 8404 |
virtual bool seek (qint64 pos) { return buffer.seek(pos); } |
| 8405 |
protected slots: |
| 8406 |
void timeoutSlot() |
| 8407 |
{ |
| 8408 |
//qDebug() << Q_FUNC_INFO; |
| 8409 |
bandwidthQuota = 8*1024; // fill quota |
| 8410 |
emit readyRead(); |
| 8411 |
// Emitting readyRead() several times triggers a bug ("QIODevice::read: Called with maxSize < 0") we fix with this commit |
| 8412 |
emit readyRead(); |
| 8413 |
} |
| 8414 |
}; |
| 8415 |
|
| 8416 |
void tst_QNetworkReply::putWithRateLimiting() |
| 8417 |
{ |
| 8418 |
QFile reference(testDataDir + "/rfc3252.txt"); |
| 8419 |
reference.open(QIODevice::ReadOnly); |
| 8420 |
QByteArray data = reference.readAll(); |
| 8421 |
QVERIFY(data.length() > 0); |
| 8422 |
|
| 8423 |
QUrl url = QUrl::fromUserInput("http://" + QtNetworkSettings::httpServerName()+ "/qtest/cgi-bin/echo.cgi?"); |
| 8424 |
|
| 8425 |
QNetworkRequest request(url); |
| 8426 |
QNetworkReplyPtr reply; |
| 8427 |
|
| 8428 |
RateLimitedUploadDevice rateLimitedUploadDevice(data); |
| 8429 |
rateLimitedUploadDevice.open(QIODevice::ReadOnly); |
| 8430 |
|
| 8431 |
RUN_REQUEST(runCustomRequest(request, reply,QByteArray("POST"), &rateLimitedUploadDevice)); |
| 8432 |
QCOMPARE(reply->error(), QNetworkReply::NoError); |
| 8433 |
QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200); |
| 8434 |
|
| 8435 |
QByteArray uploadedData = reply->readAll(); |
| 8436 |
QCOMPARE(uploadedData.length(), data.length()); |
| 8437 |
QCOMPARE(uploadedData, data); |
| 8438 |
} |
| 8439 |
|
| 8440 |
void tst_QNetworkReply::ioHttpSingleRedirect() |
| 8441 |
{ |
| 8442 |
QUrl localhost = QUrl("http://localhost"); |
| 8443 |
|
| 8444 |
// Setup server to which the second server will redirect to |
| 8445 |
MiniHttpServer server2(httpEmpty200Response); |
| 8446 |
|
| 8447 |
QUrl redirectUrl = QUrl(localhost); |
| 8448 |
redirectUrl.setPort(server2.serverPort()); |
| 8449 |
|
| 8450 |
QByteArray tempRedirectReply = |
| 8451 |
tempRedirectReplyStr().arg(QString(redirectUrl.toEncoded())).toLatin1(); |
| 8452 |
|
| 8453 |
|
| 8454 |
// Setup redirect server |
| 8455 |
MiniHttpServer server(tempRedirectReply); |
| 8456 |
|
| 8457 |
localhost.setPort(server.serverPort()); |
| 8458 |
QNetworkRequest request(localhost); |
| 8459 |
request.setAttribute(QNetworkRequest::FollowRedirectsAttribute, true); |
| 8460 |
|
| 8461 |
QNetworkReplyPtr reply(manager.get(request)); |
| 8462 |
QSignalSpy redSpy(reply.data(), SIGNAL(redirected(QUrl))); |
| 8463 |
QSignalSpy finSpy(reply.data(), SIGNAL(finished())); |
| 8464 |
|
| 8465 |
QVERIFY2(waitForFinish(reply) == Success, msgWaitForFinished(reply)); |
| 8466 |
|
| 8467 |
// Redirected and finished should be emitted exactly once |
| 8468 |
QCOMPARE(redSpy.count(), 1); |
| 8469 |
QCOMPARE(finSpy.count(), 1); |
| 8470 |
|
| 8471 |
// Original URL should not be changed after redirect |
| 8472 |
QCOMPARE(request.url(), localhost); |
| 8473 |
|
| 8474 |
// Verify Redirect url |
| 8475 |
QList<QVariant> args = redSpy.takeFirst(); |
| 8476 |
QCOMPARE(args.at(0).toUrl(), redirectUrl); |
| 8477 |
|
| 8478 |
// Reply url is set to the redirect url |
| 8479 |
QCOMPARE(reply->url(), redirectUrl); |
| 8480 |
QCOMPARE(reply->error(), QNetworkReply::NoError); |
| 8481 |
QVERIFY(validateRedirectedResponseHeaders(reply)); |
| 8482 |
} |
| 8483 |
|
| 8484 |
void tst_QNetworkReply::ioHttpChangeMaxRedirects() |
| 8485 |
{ |
| 8486 |
QUrl localhost = QUrl("http://localhost"); |
| 8487 |
|
| 8488 |
MiniHttpServer server1(""); |
| 8489 |
MiniHttpServer server2(""); |
| 8490 |
MiniHttpServer server3(httpEmpty200Response); |
| 8491 |
|
| 8492 |
QUrl server2Url(localhost); |
| 8493 |
server2Url.setPort(server2.serverPort()); |
| 8494 |
server1.setDataToTransmit(tempRedirectReplyStr().arg( |
| 8495 |
QString(server2Url.toEncoded())).toLatin1()); |
| 8496 |
|
| 8497 |
QUrl server3Url(localhost); |
| 8498 |
server3Url.setPort(server3.serverPort()); |
| 8499 |
server2.setDataToTransmit(tempRedirectReplyStr().arg( |
| 8500 |
QString(server3Url.toEncoded())).toLatin1()); |
| 8501 |
|
| 8502 |
localhost.setPort(server1.serverPort()); |
| 8503 |
QNetworkRequest request(localhost); |
| 8504 |
request.setAttribute(QNetworkRequest::FollowRedirectsAttribute, true); |
| 8505 |
|
| 8506 |
// Set Max redirects to 1. This will cause TooManyRedirectsError |
| 8507 |
request.setMaximumRedirectsAllowed(1); |
| 8508 |
|
| 8509 |
QNetworkReplyPtr reply(manager.get(request)); |
| 8510 |
QSignalSpy redSpy(reply.data(), SIGNAL(redirected(QUrl))); |
| 8511 |
QSignalSpy spy(reply.data(), SIGNAL(errorOccurred(QNetworkReply::NetworkError))); |
| 8512 |
|
| 8513 |
QCOMPARE(waitForFinish(reply), int(Failure)); |
| 8514 |
|
| 8515 |
QCOMPARE(redSpy.count(), request.maximumRedirectsAllowed()); |
| 8516 |
QCOMPARE(spy.count(), 1); |
| 8517 |
QCOMPARE(reply->error(), QNetworkReply::TooManyRedirectsError); |
| 8518 |
|
| 8519 |
// Increase max redirects to allow successful completion |
| 8520 |
request.setMaximumRedirectsAllowed(3); |
| 8521 |
|
| 8522 |
QNetworkReplyPtr reply2(manager.get(request)); |
| 8523 |
QSignalSpy redSpy2(reply2.data(), SIGNAL(redirected(QUrl))); |
| 8524 |
|
| 8525 |
QVERIFY2(waitForFinish(reply2) == Success, msgWaitForFinished(reply2)); |
| 8526 |
|
| 8527 |
QCOMPARE(redSpy2.count(), 2); |
| 8528 |
QCOMPARE(reply2->url(), server3Url); |
| 8529 |
QCOMPARE(reply2->error(), QNetworkReply::NoError); |
| 8530 |
QVERIFY(validateRedirectedResponseHeaders(reply2)); |
| 8531 |
} |
| 8532 |
|
| 8533 |
void tst_QNetworkReply::ioHttpRedirectErrors_data() |
| 8534 |
{ |
| 8535 |
QTest::addColumn<QString>("url"); |
| 8536 |
QTest::addColumn<QString>("dataToSend"); |
| 8537 |
QTest::addColumn<QNetworkReply::NetworkError>("error"); |
| 8538 |
|
| 8539 |
QString tempRedirectReply = QString("HTTP/1.1 307 Temporary Redirect\r\n" |
| 8540 |
"Content-Type: text/plain\r\n" |
| 8541 |
"location: http://localhost:%1\r\n\r\n"); |
| 8542 |
|
| 8543 |
QTest::newRow("too-many-redirects") << "http://localhost" << tempRedirectReply << QNetworkReply::TooManyRedirectsError; |
| 8544 |
#if QT_CONFIG(ssl) |
| 8545 |
QTest::newRow("insecure-redirect") << "https://localhost" << tempRedirectReply << QNetworkReply::InsecureRedirectError; |
| 8546 |
#endif |
| 8547 |
QTest::newRow("unknown-redirect") << "http://localhost"<< tempRedirectReply.replace("http", "bad_protocol") << QNetworkReply::ProtocolUnknownError; |
| 8548 |
} |
| 8549 |
|
| 8550 |
void tst_QNetworkReply::ioHttpRedirectErrors() |
| 8551 |
{ |
| 8552 |
QFETCH(QString, url); |
| 8553 |
QFETCH(QString, dataToSend); |
| 8554 |
QFETCH(QNetworkReply::NetworkError, error); |
| 8555 |
|
| 8556 |
QUrl localhost(url); |
| 8557 |
MiniHttpServer server("", localhost.scheme() == QLatin1String("https")); |
| 8558 |
|
| 8559 |
localhost.setPort(server.serverPort()); |
| 8560 |
|
| 8561 |
QByteArray d2s = dataToSend.arg( |
| 8562 |
QString::number(server.serverPort())).toLatin1(); |
| 8563 |
server.setDataToTransmit(d2s); |
| 8564 |
|
| 8565 |
QNetworkRequest request(localhost); |
| 8566 |
request.setAttribute(QNetworkRequest::FollowRedirectsAttribute, true); |
| 8567 |
QNetworkReplyPtr reply(manager.get(request)); |
| 8568 |
if (localhost.scheme() == "https") |
| 8569 |
reply.data()->ignoreSslErrors(); |
| 8570 |
|
| 8571 |
QEventLoop eventLoop; |
| 8572 |
QTimer watchDog; |
| 8573 |
watchDog.setSingleShot(true); |
| 8574 |
|
| 8575 |
reply->connect(reply.data(), &QNetworkReply::errorOccurred, |
| 8576 |
[&eventLoop](QNetworkReply::NetworkError){ |
| 8577 |
eventLoop.exit(Failure); |
| 8578 |
}); |
| 8579 |
|
| 8580 |
watchDog.connect(&watchDog, &QTimer::timeout, [&eventLoop](){ |
| 8581 |
eventLoop.exit(Timeout); |
| 8582 |
}); |
| 8583 |
|
| 8584 |
watchDog.start(5000); |
| 8585 |
|
| 8586 |
QCOMPARE(eventLoop.exec(), int(Failure)); |
| 8587 |
QCOMPARE(reply->error(), error); |
| 8588 |
} |
| 8589 |
|
| 8590 |
struct SameOriginRedirector : MiniHttpServer |
| 8591 |
{ |
| 8592 |
SameOriginRedirector(const QByteArray &data, bool ssl = false) |
| 8593 |
: MiniHttpServer(data, ssl) |
| 8594 |
{ } |
| 8595 |
|
| 8596 |
std::vector<QByteArray> responses; |
| 8597 |
|
| 8598 |
void reply() override |
| 8599 |
{ |
| 8600 |
if (responses.empty()) { |
| 8601 |
dataToTransmit.clear(); |
| 8602 |
} else { |
| 8603 |
dataToTransmit = responses.back(); |
| 8604 |
responses.pop_back(); |
| 8605 |
} |
| 8606 |
|
| 8607 |
MiniHttpServer::reply(); |
| 8608 |
} |
| 8609 |
}; |
| 8610 |
|
| 8611 |
void tst_QNetworkReply::ioHttpRedirectPolicy_data() |
| 8612 |
{ |
| 8613 |
QTest::addColumn<QNetworkRequest::RedirectPolicy>("policy"); |
| 8614 |
QTest::addColumn<bool>("ssl"); |
| 8615 |
QTest::addColumn<int>("redirectCount"); |
| 8616 |
QTest::addColumn<int>("statusCode"); |
| 8617 |
|
| 8618 |
QTest::newRow("manual-nossl") << QNetworkRequest::ManualRedirectPolicy << false << 0 << 307; |
| 8619 |
QTest::newRow("nolesssafe-nossl") << QNetworkRequest::NoLessSafeRedirectPolicy << false << 1 << 200; |
| 8620 |
QTest::newRow("same-origin-nossl") << QNetworkRequest::SameOriginRedirectPolicy << false << 1 << 200; |
| 8621 |
#if QT_CONFIG(ssl) |
| 8622 |
QTest::newRow("manual-ssl") << QNetworkRequest::ManualRedirectPolicy << true << 0 << 307; |
| 8623 |
QTest::newRow("nolesssafe-ssl") << QNetworkRequest::NoLessSafeRedirectPolicy << true << 1 << 200; |
| 8624 |
QTest::newRow("same-origin-ssl") << QNetworkRequest::SameOriginRedirectPolicy << true << 1 << 200; |
| 8625 |
#endif |
| 8626 |
} |
| 8627 |
|
| 8628 |
void tst_QNetworkReply::ioHttpRedirectPolicy() |
| 8629 |
{ |
| 8630 |
QFETCH(const QNetworkRequest::RedirectPolicy, policy); |
| 8631 |
|
| 8632 |
QFETCH(const bool, ssl); |
| 8633 |
|
| 8634 |
QFETCH(const int, redirectCount); |
| 8635 |
QFETCH(const int, statusCode); |
| 8636 |
|
| 8637 |
// Setup HTTP server. |
| 8638 |
SameOriginRedirector redirectServer("", ssl); |
| 8639 |
|
| 8640 |
QUrl url(QLatin1String(ssl ? "https://localhost" : "http://localhost")); |
| 8641 |
|
| 8642 |
url.setPort(redirectServer.serverPort()); |
| 8643 |
redirectServer.responses.push_back(httpEmpty200Response); |
| 8644 |
redirectServer.responses.push_back(tempRedirectReplyStr().arg(QString(url.toEncoded())).toLatin1()); |
| 8645 |
|
| 8646 |
// This is the default one we preserve between tests. |
| 8647 |
QCOMPARE(manager.redirectPolicy(), QNetworkRequest::ManualRedirectPolicy); |
| 8648 |
|
| 8649 |
manager.setRedirectPolicy(policy); |
| 8650 |
QCOMPARE(manager.redirectPolicy(), policy); |
| 8651 |
QNetworkReplyPtr reply(manager.get(QNetworkRequest(url))); |
| 8652 |
if (ssl) |
| 8653 |
reply->ignoreSslErrors(); |
| 8654 |
|
| 8655 |
// Restore default: |
| 8656 |
manager.setRedirectPolicy(QNetworkRequest::ManualRedirectPolicy); |
| 8657 |
QSignalSpy redirectSpy(reply.data(), SIGNAL(redirected(QUrl))); |
| 8658 |
QSignalSpy finishedSpy(reply.data(), SIGNAL(finished())); |
| 8659 |
QVERIFY2(waitForFinish(reply) == Success, msgWaitForFinished(reply)); |
| 8660 |
QCOMPARE(finishedSpy.count(), 1); |
| 8661 |
QCOMPARE(redirectSpy.count(), redirectCount); |
| 8662 |
QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), statusCode); |
| 8663 |
QVERIFY(validateRedirectedResponseHeaders(reply) || statusCode != 200); |
| 8664 |
} |
| 8665 |
|
| 8666 |
void tst_QNetworkReply::ioHttpRedirectPolicyErrors_data() |
| 8667 |
{ |
| 8668 |
QTest::addColumn<QNetworkRequest::RedirectPolicy>("policy"); |
| 8669 |
QTest::addColumn<bool>("ssl"); |
| 8670 |
QTest::addColumn<QString>("location"); |
| 8671 |
QTest::addColumn<int>("maxRedirects"); |
| 8672 |
QTest::addColumn<QNetworkReply::NetworkError>("expectedError"); |
| 8673 |
|
| 8674 |
// 1. NoLessSafeRedirectsPolicy |
| 8675 |
QTest::newRow("nolesssafe-nossl-nossl-too-many") << QNetworkRequest::NoLessSafeRedirectPolicy |
| 8676 |
<< false << QString("http://localhost:%1") << 0 << QNetworkReply::TooManyRedirectsError; |
| 8677 |
#if QT_CONFIG(ssl) |
| 8678 |
QTest::newRow("nolesssafe-ssl-ssl-too-many") << QNetworkRequest::NoLessSafeRedirectPolicy |
| 8679 |
<< true << QString("https:/localhost:%1") << 0 << QNetworkReply::TooManyRedirectsError; |
| 8680 |
QTest::newRow("nolesssafe-ssl-nossl-insecure-redirect") << QNetworkRequest::NoLessSafeRedirectPolicy |
| 8681 |
<< true << QString("http://localhost:%1") << 50 << QNetworkReply::InsecureRedirectError; |
| 8682 |
#endif |
| 8683 |
// 2. SameOriginRedirectsPolicy |
| 8684 |
QTest::newRow("same-origin-nossl-nossl-too-many") << QNetworkRequest::SameOriginRedirectPolicy |
| 8685 |
<< false << QString("http://localhost:%1") << 0 << QNetworkReply::TooManyRedirectsError; |
| 8686 |
#if QT_CONFIG(ssl) |
| 8687 |
QTest::newRow("same-origin-ssl-ssl-too-many") << QNetworkRequest::SameOriginRedirectPolicy |
| 8688 |
<< true << QString("https://localhost:%1") << 0 << QNetworkReply::TooManyRedirectsError; |
| 8689 |
QTest::newRow("same-origin-https-http-wrong-protocol") << QNetworkRequest::SameOriginRedirectPolicy |
| 8690 |
<< true << QString("http://localhost:%1") << 50 << QNetworkReply::InsecureRedirectError; |
| 8691 |
#endif |
| 8692 |
QTest::newRow("same-origin-http-https-wrong-protocol") << QNetworkRequest::SameOriginRedirectPolicy |
| 8693 |
<< false << QString("https://localhost:%1") << 50 << QNetworkReply::InsecureRedirectError; |
| 8694 |
QTest::newRow("same-origin-http-http-wrong-host") << QNetworkRequest::SameOriginRedirectPolicy |
| 8695 |
<< false << QString("http://not-so-localhost:%1") << 50 << QNetworkReply::InsecureRedirectError; |
| 8696 |
#if QT_CONFIG(ssl) |
| 8697 |
QTest::newRow("same-origin-https-https-wrong-host") << QNetworkRequest::SameOriginRedirectPolicy |
| 8698 |
<< true << QString("https://not-so-localhost:%1") << 50 << QNetworkReply::InsecureRedirectError; |
| 8699 |
#endif |
| 8700 |
QTest::newRow("same-origin-http-http-wrong-port") << QNetworkRequest::SameOriginRedirectPolicy |
| 8701 |
<< false << QString("http://localhost/%1") << 50 << QNetworkReply::InsecureRedirectError; |
| 8702 |
#if QT_CONFIG(ssl) |
| 8703 |
QTest::newRow("same-origin-https-https-wrong-port") << QNetworkRequest::SameOriginRedirectPolicy |
| 8704 |
<< true << QString("https://localhost/%1") << 50 << QNetworkReply::InsecureRedirectError; |
| 8705 |
#endif |
| 8706 |
} |
| 8707 |
|
| 8708 |
void tst_QNetworkReply::ioHttpRedirectPolicyErrors() |
| 8709 |
{ |
| 8710 |
QFETCH(const QNetworkRequest::RedirectPolicy, policy); |
| 8711 |
// This should never happen: |
| 8712 |
QVERIFY(policy != QNetworkRequest::ManualRedirectPolicy); |
| 8713 |
|
| 8714 |
QFETCH(const bool, ssl); |
| 8715 |
QFETCH(const QString, location); |
| 8716 |
QFETCH(const int, maxRedirects); |
| 8717 |
QFETCH(const QNetworkReply::NetworkError, expectedError); |
| 8718 |
|
| 8719 |
// Setup the server. |
| 8720 |
MiniHttpServer server("", ssl); |
| 8721 |
server.setDataToTransmit(tempRedirectReplyStr().arg(location.arg(server.serverPort())).toLatin1()); |
| 8722 |
|
| 8723 |
QUrl url(QLatin1String(ssl ? "https://localhost" : "http://localhost")); |
| 8724 |
url.setPort(server.serverPort()); |
| 8725 |
|
| 8726 |
QNetworkRequest request(url); |
| 8727 |
request.setMaximumRedirectsAllowed(maxRedirects); |
| 8728 |
// We always reset the policy to the default one ('Manual') after any related |
| 8729 |
// test is finished: |
| 8730 |
QCOMPARE(manager.redirectPolicy(), QNetworkRequest::ManualRedirectPolicy); |
| 8731 |
manager.setRedirectPolicy(policy); |
| 8732 |
QCOMPARE(manager.redirectPolicy(), policy); |
| 8733 |
|
| 8734 |
QNetworkReplyPtr reply(manager.get(request)); |
| 8735 |
// Set it back to default: |
| 8736 |
manager.setRedirectPolicy(QNetworkRequest::ManualRedirectPolicy); |
| 8737 |
|
| 8738 |
if (ssl) |
| 8739 |
reply->ignoreSslErrors(); |
| 8740 |
|
| 8741 |
QSignalSpy spy(reply.data(), SIGNAL(errorOccurred(QNetworkReply::NetworkError))); |
| 8742 |
|
| 8743 |
QCOMPARE(waitForFinish(reply), int(Failure)); |
| 8744 |
QCOMPARE(spy.count(), 1); |
| 8745 |
QCOMPARE(reply->error(), expectedError); |
| 8746 |
} |
| 8747 |
|
| 8748 |
void tst_QNetworkReply::ioHttpUserVerifiedRedirect_data() |
| 8749 |
{ |
| 8750 |
QTest::addColumn<bool>("followRedirect"); |
| 8751 |
QTest::addColumn<int>("statusCode"); |
| 8752 |
|
| 8753 |
QTest::newRow("allow-redirect") << true << 200; |
| 8754 |
QTest::newRow("reject-redirect") << false << 307; |
| 8755 |
} |
| 8756 |
|
| 8757 |
void tst_QNetworkReply::ioHttpUserVerifiedRedirect() |
| 8758 |
{ |
| 8759 |
QFETCH(const bool, followRedirect); |
| 8760 |
QFETCH(const int, statusCode); |
| 8761 |
|
| 8762 |
// Setup HTTP server. |
| 8763 |
MiniHttpServer target(httpEmpty200Response, false); |
| 8764 |
QUrl url("http://localhost"); |
| 8765 |
url.setPort(target.serverPort()); |
| 8766 |
|
| 8767 |
MiniHttpServer redirectServer("", false); |
| 8768 |
redirectServer.setDataToTransmit(tempRedirectReplyStr().arg(QString(url.toEncoded())).toLatin1()); |
| 8769 |
url.setPort(redirectServer.serverPort()); |
| 8770 |
|
| 8771 |
QCOMPARE(manager.redirectPolicy(), QNetworkRequest::ManualRedirectPolicy); |
| 8772 |
manager.setRedirectPolicy(QNetworkRequest::UserVerifiedRedirectPolicy); |
| 8773 |
QCOMPARE(manager.redirectPolicy(), QNetworkRequest::UserVerifiedRedirectPolicy); |
| 8774 |
|
| 8775 |
QNetworkReplyPtr reply(manager.get(QNetworkRequest(url))); |
| 8776 |
reply->connect(reply.data(), &QNetworkReply::redirected, |
| 8777 |
[&](const QUrl &redirectUrl) { |
| 8778 |
qDebug() << "redirect to:" << redirectUrl; |
| 8779 |
if (followRedirect) { |
| 8780 |
qDebug() << "confirmed."; |
| 8781 |
emit reply->redirectAllowed(); |
| 8782 |
} else{ |
| 8783 |
qDebug() << "rejected."; |
| 8784 |
emit reply->abort(); |
| 8785 |
} |
| 8786 |
}); |
| 8787 |
|
| 8788 |
// Before any test failed, reset the policy to default: |
| 8789 |
manager.setRedirectPolicy(QNetworkRequest::ManualRedirectPolicy); |
| 8790 |
QCOMPARE(manager.redirectPolicy(), QNetworkRequest::ManualRedirectPolicy); |
| 8791 |
|
| 8792 |
QSignalSpy finishedSpy(reply.data(), SIGNAL(finished())); |
| 8793 |
waitForFinish(reply); |
| 8794 |
QCOMPARE(finishedSpy.count(), 1); |
| 8795 |
QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), statusCode); |
| 8796 |
QVERIFY(validateRedirectedResponseHeaders(reply) || statusCode != 200); |
| 8797 |
} |
| 8798 |
|
| 8799 |
void tst_QNetworkReply::ioHttpCookiesDuringRedirect() |
| 8800 |
{ |
| 8801 |
MiniHttpServer target(httpEmpty200Response, false); |
| 8802 |
|
| 8803 |
const QString cookieHeader = QStringLiteral("Set-Cookie: hello=world; Path=/;\r\n"); |
| 8804 |
QString redirect = tempRedirectReplyStr(); |
| 8805 |
// Insert 'cookieHeader' before the final \r\n |
| 8806 |
redirect.insert(redirect.length() - 2, cookieHeader); |
| 8807 |
|
| 8808 |
QUrl url("http://localhost/"); |
| 8809 |
url.setPort(target.serverPort()); |
| 8810 |
redirect = redirect.arg(url.toString()); |
| 8811 |
MiniHttpServer redirectServer(redirect.toLatin1(), false); |
| 8812 |
|
| 8813 |
url = QUrl("http://localhost/"); |
| 8814 |
url.setPort(redirectServer.serverPort()); |
| 8815 |
QNetworkRequest request(url); |
| 8816 |
auto oldRedirectPolicy = manager.redirectPolicy(); |
| 8817 |
manager.setRedirectPolicy(QNetworkRequest::RedirectPolicy::NoLessSafeRedirectPolicy); |
| 8818 |
QNetworkReplyPtr reply(manager.get(request)); |
| 8819 |
// Set policy back to whatever it was |
| 8820 |
manager.setRedirectPolicy(oldRedirectPolicy); |
| 8821 |
|
| 8822 |
QVERIFY(waitForFinish(reply) == Success); |
| 8823 |
QVERIFY(target.receivedData.contains("\r\nCookie: hello=world\r\n")); |
| 8824 |
QVERIFY(validateRedirectedResponseHeaders(reply)); |
| 8825 |
} |
| 8826 |
|
| 8827 |
void tst_QNetworkReply::ioHttpRedirect_data() |
| 8828 |
{ |
| 8829 |
QTest::addColumn<QString>("status"); |
| 8830 |
|
| 8831 |
QTest::addRow("301") << "301 Moved Permanently"; |
| 8832 |
QTest::addRow("302") << "302 Found"; |
| 8833 |
QTest::addRow("303") << "303 See Other"; |
| 8834 |
QTest::addRow("305") << "305 Use Proxy"; |
| 8835 |
QTest::addRow("307") << "307 Temporary Redirect"; |
| 8836 |
QTest::addRow("308") << "308 Permanent Redirect"; |
| 8837 |
} |
| 8838 |
|
| 8839 |
void tst_QNetworkReply::ioHttpRedirect() |
| 8840 |
{ |
| 8841 |
QFETCH(QString, status); |
| 8842 |
|
| 8843 |
MiniHttpServer target(httpEmpty200Response, false); |
| 8844 |
QUrl targetUrl("http://localhost/"); |
| 8845 |
targetUrl.setPort(target.serverPort()); |
| 8846 |
|
| 8847 |
QString redirectReply = QStringLiteral("HTTP/1.1 %1\r\n" |
| 8848 |
"Content-Type: text/plain\r\n" |
| 8849 |
"location: %2\r\n" |
| 8850 |
"\r\n").arg(status, targetUrl.toString()); |
| 8851 |
MiniHttpServer redirectServer(redirectReply.toLatin1(), false); |
| 8852 |
QUrl url("http://localhost/"); |
| 8853 |
url.setPort(redirectServer.serverPort()); |
| 8854 |
QNetworkRequest request(url); |
| 8855 |
auto oldRedirectPolicy = manager.redirectPolicy(); |
| 8856 |
manager.setRedirectPolicy(QNetworkRequest::RedirectPolicy::NoLessSafeRedirectPolicy); |
| 8857 |
QNetworkReplyPtr reply(manager.get(request)); |
| 8858 |
// Set policy back to what it was |
| 8859 |
manager.setRedirectPolicy(oldRedirectPolicy); |
| 8860 |
|
| 8861 |
QCOMPARE(waitForFinish(reply), int(Success)); |
| 8862 |
QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200); |
| 8863 |
QVERIFY(validateRedirectedResponseHeaders(reply)); |
| 8864 |
} |
| 8865 |
|
| 8866 |
/* |
| 8867 |
Test that, if we load a redirect from cache, we don't treat the request to |
| 8868 |
the destination of the redirect as a redirect. |
| 8869 |
|
| 8870 |
If it was treated as a redirect the finished() signal was never emitted! |
| 8871 |
*/ |
| 8872 |
void tst_QNetworkReply::ioHttpRedirectWithCache() |
| 8873 |
{ |
| 8874 |
// Disallow caching the result so that the second request must also send the request |
| 8875 |
QByteArray http200ResponseNoCache = "HTTP/1.1 200 OK\r\n" |
| 8876 |
"Content-Type: text/plain\r\n" |
| 8877 |
"Cache-Control: no-cache\r\n" |
| 8878 |
"\r\nHello"; |
| 8879 |
|
| 8880 |
MiniHttpServer target(http200ResponseNoCache, false); |
| 8881 |
QUrl targetUrl("http://localhost/"); |
| 8882 |
targetUrl.setPort(target.serverPort()); |
| 8883 |
|
| 8884 |
// A cache-able redirect reply |
| 8885 |
QString redirectReply = QStringLiteral("HTTP/1.1 308\r\n" |
| 8886 |
"Content-Type: text/plain\r\n" |
| 8887 |
"location: %1\r\n" |
| 8888 |
"Cache-Control: max-age=3600\r\n" |
| 8889 |
"\r\nYou're being redirected").arg(targetUrl.toString()); |
| 8890 |
MiniHttpServer redirectServer(redirectReply.toLatin1(), false); |
| 8891 |
QUrl url("http://localhost/"); |
| 8892 |
url.setPort(redirectServer.serverPort()); |
| 8893 |
|
| 8894 |
QTemporaryDir tempDir(QDir::tempPath() + "/tmp_cache_28035"); |
| 8895 |
QVERIFY2(tempDir.isValid(), qPrintable(tempDir.errorString())); |
| 8896 |
tempDir.setAutoRemove(true); |
| 8897 |
|
| 8898 |
QNetworkDiskCache *diskCache = new QNetworkDiskCache(); |
| 8899 |
diskCache->setCacheDirectory(tempDir.path()); |
| 8900 |
// Manager takes ownership of the cache: |
| 8901 |
manager.setCache(diskCache); |
| 8902 |
QCOMPARE(diskCache->cacheSize(), 0); |
| 8903 |
|
| 8904 |
// Send the first request, we end up caching the redirect reply |
| 8905 |
QNetworkRequest request(url); |
| 8906 |
request.setAttribute(QNetworkRequest::RedirectPolicyAttribute, |
| 8907 |
QNetworkRequest::NoLessSafeRedirectPolicy); |
| 8908 |
QNetworkReplyPtr reply(manager.get(request)); |
| 8909 |
|
| 8910 |
QCOMPARE(waitForFinish(reply), int(Success)); |
| 8911 |
QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200); |
| 8912 |
QVERIFY(validateRedirectedResponseHeaders(reply)); |
| 8913 |
|
| 8914 |
QVERIFY(diskCache->cacheSize() != 0); |
| 8915 |
|
| 8916 |
// Now for the second request, we will use the cache, and we test that the finished() |
| 8917 |
// signal is still emitted. |
| 8918 |
request.setAttribute(QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::PreferCache); |
| 8919 |
reply.reset(manager.get(request)); |
| 8920 |
|
| 8921 |
QCOMPARE(waitForFinish(reply), int(Success)); |
| 8922 |
QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200); |
| 8923 |
QVERIFY(validateRedirectedResponseHeaders(reply)); |
| 8924 |
} |
| 8925 |
|
| 8926 |
void tst_QNetworkReply::ioHttpRedirectFromLocalToRemote() |
| 8927 |
{ |
| 8928 |
QUrl targetUrl("http://" + QtNetworkSettings::httpServerName() + "/qtest/rfc3252.txt"); |
| 8929 |
|
| 8930 |
QString redirectReply = tempRedirectReplyStr().arg(targetUrl.toString()); |
| 8931 |
MiniHttpServer redirectServer(redirectReply.toLatin1(), false); |
| 8932 |
QUrl url("http://localhost/"); |
| 8933 |
url.setPort(redirectServer.serverPort()); |
| 8934 |
|
| 8935 |
QFile reference(testDataDir + "/rfc3252.txt"); |
| 8936 |
QVERIFY(reference.open(QIODevice::ReadOnly)); |
| 8937 |
QNetworkRequest request(url); |
| 8938 |
|
| 8939 |
auto oldRedirectPolicy = manager.redirectPolicy(); |
| 8940 |
manager.setRedirectPolicy(QNetworkRequest::RedirectPolicy::NoLessSafeRedirectPolicy); |
| 8941 |
QNetworkReplyPtr reply(manager.get(request)); |
| 8942 |
// Restore previous policy |
| 8943 |
manager.setRedirectPolicy(oldRedirectPolicy); |
| 8944 |
|
| 8945 |
QCOMPARE(waitForFinish(reply), int(Success)); |
| 8946 |
|
| 8947 |
QCOMPARE(reply->url(), targetUrl); |
| 8948 |
QCOMPARE(reply->error(), QNetworkReply::NoError); |
| 8949 |
QCOMPARE(reply->header(QNetworkRequest::ContentLengthHeader).toLongLong(), reference.size()); |
| 8950 |
QCOMPARE(reply->readAll(), reference.readAll()); |
| 8951 |
} |
| 8952 |
|
| 8953 |
void tst_QNetworkReply::ioHttpRedirectPostPut_data() |
| 8954 |
{ |
| 8955 |
QTest::addColumn<bool>("usePost"); |
| 8956 |
QTest::addColumn<QString>("status"); |
| 8957 |
QTest::addColumn<QByteArray>("data"); |
| 8958 |
QTest::addColumn<QString>("contentType"); |
| 8959 |
|
| 8960 |
QByteArray data; |
| 8961 |
data = "hello world"; |
| 8962 |
QTest::addRow("post-307") << true << "307 Temporary Redirect" << data << "text/plain"; |
| 8963 |
QTest::addRow("put-307") << false << "307 Temporary Redirect" << data << "text/plain"; |
| 8964 |
QString permanentRedirect = "308 Permanent Redirect"; |
| 8965 |
QTest::addRow("post-308") << true << permanentRedirect << data << "text/plain"; |
| 8966 |
QTest::addRow("put-308") << false << permanentRedirect << data << "text/plain"; |
| 8967 |
|
| 8968 |
// Some data from ::putToFile_data |
| 8969 |
data = ""; |
| 8970 |
QTest::newRow("post-empty") << true << permanentRedirect << data << "application/octet-stream"; |
| 8971 |
QTest::newRow("put-empty") << false << permanentRedirect << data << "application/octet-stream"; |
| 8972 |
|
| 8973 |
data = QByteArray("abcd\0\1\2\abcd",12); |
| 8974 |
QTest::newRow("post-with-nul") << true << permanentRedirect << data << "application/octet-stream"; |
| 8975 |
QTest::newRow("put-with-nul") << false << permanentRedirect << data << "application/octet-stream"; |
| 8976 |
|
| 8977 |
data = QByteArray(4097, '\4'); |
| 8978 |
QTest::newRow("post-4k+1") << true << permanentRedirect << data << "application/octet-stream"; |
| 8979 |
QTest::newRow("put-4k+1") << false << permanentRedirect << data << "application/octet-stream"; |
| 8980 |
|
| 8981 |
data = QByteArray(128*1024+1, '\177'); |
| 8982 |
QTest::newRow("post-128k+1") << true << permanentRedirect << data << "application/octet-stream"; |
| 8983 |
QTest::newRow("put-128k+1") << false << permanentRedirect << data << "application/octet-stream"; |
| 8984 |
|
| 8985 |
data = QByteArray(2*1024*1024+1, '\177'); |
| 8986 |
QTest::newRow("post-2MB+1") << true << permanentRedirect << data << "application/octet-stream"; |
| 8987 |
QTest::newRow("put-2MB+1") << false << permanentRedirect << data << "application/octet-stream"; |
| 8988 |
} |
| 8989 |
|
| 8990 |
void tst_QNetworkReply::ioHttpRedirectPostPut() |
| 8991 |
{ |
| 8992 |
QFETCH(bool, usePost); |
| 8993 |
QFETCH(QString, status); |
| 8994 |
QFETCH(QByteArray, data); |
| 8995 |
QFETCH(QString, contentType); |
| 8996 |
|
| 8997 |
QUrl targetUrl("http://" + QtNetworkSettings::httpServerName() + "/qtest/cgi-bin/md5sum.cgi"); |
| 8998 |
|
| 8999 |
QString redirectReply = QStringLiteral("HTTP/1.1 %1\r\n" |
| 9000 |
"Content-Type: text/plain\r\n" |
| 9001 |
"location: %2\r\n" |
| 9002 |
"\r\n").arg(status, targetUrl.toString()); |
| 9003 |
MiniHttpServer redirectServer(redirectReply.toLatin1()); |
| 9004 |
QUrl url("http://localhost/"); |
| 9005 |
url.setPort(redirectServer.serverPort()); |
| 9006 |
QNetworkRequest request(url); |
| 9007 |
request.setHeader(QNetworkRequest::KnownHeaders::ContentTypeHeader, contentType); |
| 9008 |
auto oldRedirectPolicy = manager.redirectPolicy(); |
| 9009 |
manager.setRedirectPolicy(QNetworkRequest::RedirectPolicy::NoLessSafeRedirectPolicy); |
| 9010 |
|
| 9011 |
QNetworkReplyPtr reply(usePost ? manager.post(request, data) : manager.put(request, data)); |
| 9012 |
// Restore previous policy: |
| 9013 |
manager.setRedirectPolicy(oldRedirectPolicy); |
| 9014 |
|
| 9015 |
QCOMPARE(waitForFinish(reply), int(Success)); |
| 9016 |
QCOMPARE(reply->readAll().trimmed(), md5sum(data).toHex()); |
| 9017 |
} |
| 9018 |
|
| 9019 |
void tst_QNetworkReply::ioHttpRedirectMultipartPost_data() |
| 9020 |
{ |
| 9021 |
postToHttpMultipart_data(); |
| 9022 |
} |
| 9023 |
|
| 9024 |
void tst_QNetworkReply::ioHttpRedirectMultipartPost() |
| 9025 |
{ |
| 9026 |
// Note: This code is heavily based on postToHttpMultipart |
| 9027 |
QFETCH(QUrl, url); |
| 9028 |
|
| 9029 |
static QSet<QByteArray> boundaries; |
| 9030 |
|
| 9031 |
QNetworkReplyPtr reply; |
| 9032 |
|
| 9033 |
QFETCH(QHttpMultiPart *, multiPart); |
| 9034 |
QFETCH(QByteArray, expectedReplyData); |
| 9035 |
QFETCH(QByteArray, contentType); |
| 9036 |
|
| 9037 |
QString redirectReply = tempRedirectReplyStr().arg(url.toString()); |
| 9038 |
MiniHttpServer redirectServer(redirectReply.toLatin1()); |
| 9039 |
QUrl redirectUrl("http://localhost/"); |
| 9040 |
redirectUrl.setPort(redirectServer.serverPort()); |
| 9041 |
QNetworkRequest request(redirectUrl); |
| 9042 |
|
| 9043 |
// Restore policy when we leave this scope: |
| 9044 |
struct PolicyRestorer |
| 9045 |
{ |
| 9046 |
QNetworkAccessManager &qnam; |
| 9047 |
QNetworkRequest::RedirectPolicy policy; |
| 9048 |
PolicyRestorer(QNetworkAccessManager &qnam) |
| 9049 |
: qnam(qnam), policy(qnam.redirectPolicy()) |
| 9050 |
{ qnam.setRedirectPolicy(QNetworkRequest::RedirectPolicy::NoLessSafeRedirectPolicy); } |
| 9051 |
~PolicyRestorer() { qnam.setRedirectPolicy(policy); } |
| 9052 |
} policyRestorer(manager); |
| 9053 |
|
| 9054 |
// hack for testing the setting of the content-type header by hand: |
| 9055 |
if (contentType == "custom") { |
| 9056 |
QByteArray contentType("multipart/custom; boundary=\"" + multiPart->boundary() + "\""); |
| 9057 |
request.setHeader(QNetworkRequest::ContentTypeHeader, contentType); |
| 9058 |
} |
| 9059 |
|
| 9060 |
QVERIFY2(! boundaries.contains(multiPart->boundary()), "boundary '" + multiPart->boundary() + "' has been created twice"); |
| 9061 |
boundaries.insert(multiPart->boundary()); |
| 9062 |
|
| 9063 |
RUN_REQUEST(runMultipartRequest(request, reply, multiPart, "POST")); |
| 9064 |
multiPart->deleteLater(); |
| 9065 |
|
| 9066 |
QCOMPARE(reply->url(), url); |
| 9067 |
QCOMPARE(reply->error(), QNetworkReply::NoError); |
| 9068 |
|
| 9069 |
QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200); // 200 OK |
| 9070 |
|
| 9071 |
QVERIFY(multiPart->boundary().count() > 20); // check that there is randomness after the "boundary_.oOo._" string |
| 9072 |
QVERIFY(multiPart->boundary().count() < 70); |
| 9073 |
QByteArray replyData = reply->readAll(); |
| 9074 |
|
| 9075 |
expectedReplyData.prepend("content type: multipart/" + contentType + "; boundary=\"" + multiPart->boundary() + "\"\n"); |
| 9076 |
// QEXPECT_FAIL("nested", "the server does not understand nested multipart messages", Continue); // see above |
| 9077 |
QCOMPARE(replyData, expectedReplyData); |
| 9078 |
} |
| 9079 |
|
| 9080 |
void tst_QNetworkReply::ioHttpRedirectDelete() |
| 9081 |
{ |
| 9082 |
MiniHttpServer target(httpEmpty200Response, false); |
| 9083 |
QUrl targetUrl("http://localhost/"); |
| 9084 |
targetUrl.setPort(target.serverPort()); |
| 9085 |
|
| 9086 |
QString redirectReply = tempRedirectReplyStr().arg(targetUrl.toString()); |
| 9087 |
MiniHttpServer redirectServer(redirectReply.toLatin1()); |
| 9088 |
QUrl url("http://localhost/"); |
| 9089 |
url.setPort(redirectServer.serverPort()); |
| 9090 |
QNetworkRequest request(url); |
| 9091 |
auto oldRedirectPolicy = manager.redirectPolicy(); |
| 9092 |
manager.setRedirectPolicy(QNetworkRequest::RedirectPolicy::NoLessSafeRedirectPolicy); |
| 9093 |
|
| 9094 |
QNetworkReplyPtr reply(manager.deleteResource(request)); |
| 9095 |
// Restore previous policy: |
| 9096 |
manager.setRedirectPolicy(oldRedirectPolicy); |
| 9097 |
|
| 9098 |
QCOMPARE(waitForFinish(reply), int(Success)); |
| 9099 |
QVERIFY2(target.receivedData.startsWith("DELETE"), "Target server called with the wrong method"); |
| 9100 |
} |
| 9101 |
|
| 9102 |
void tst_QNetworkReply::ioHttpRedirectCustom() |
| 9103 |
{ |
| 9104 |
MiniHttpServer target(httpEmpty200Response, false); |
| 9105 |
QUrl targetUrl("http://localhost/"); |
| 9106 |
targetUrl.setPort(target.serverPort()); |
| 9107 |
|
| 9108 |
QString redirectReply = tempRedirectReplyStr().arg(targetUrl.toString()); |
| 9109 |
MiniHttpServer redirectServer(redirectReply.toLatin1()); |
| 9110 |
QUrl url("http://localhost/"); |
| 9111 |
url.setPort(redirectServer.serverPort()); |
| 9112 |
QNetworkRequest request(url); |
| 9113 |
auto oldRedirectPolicy = manager.redirectPolicy(); |
| 9114 |
manager.setRedirectPolicy(QNetworkRequest::RedirectPolicy::NoLessSafeRedirectPolicy); |
| 9115 |
|
| 9116 |
QNetworkReplyPtr reply(manager.sendCustomRequest(request, QByteArrayLiteral("CUSTOM"))); |
| 9117 |
// Restore previous policy: |
| 9118 |
manager.setRedirectPolicy(oldRedirectPolicy); |
| 9119 |
|
| 9120 |
QCOMPARE(waitForFinish(reply), int(Success)); |
| 9121 |
QVERIFY2(target.receivedData.startsWith("CUSTOM"), "Target server called with the wrong method"); |
| 9122 |
} |
| 9123 |
|
| 9124 |
void tst_QNetworkReply::ioHttpRedirectWithUploadDevice_data() |
| 9125 |
{ |
| 9126 |
QTest::addColumn<QByteArray>("method"); |
| 9127 |
QTest::addColumn<QString>("status"); |
| 9128 |
QTest::addColumn<bool>("keepMethod"); |
| 9129 |
|
| 9130 |
QTest::addRow("post-301") << QByteArray("POST") << "301 Moved Permanently" << false; |
| 9131 |
QTest::addRow("post-307") << QByteArray("POST") << "307 Temporary Redirect" << true; |
| 9132 |
|
| 9133 |
const QByteArray customVerb = QByteArray("CUSTOM_WITH_PAYLOAD"); |
| 9134 |
QTest::addRow("custom-301") << customVerb << "301 Moved Permanently" << false; |
| 9135 |
QTest::addRow("custom-307") << customVerb << "307 Temporary Redirect" << true; |
| 9136 |
} |
| 9137 |
|
| 9138 |
/* |
| 9139 |
Tests that we properly disregard the upload device when redirecting |
| 9140 |
and changing method to GET, and that it gets reset properly when |
| 9141 |
redirecting (without changing method) for POST and a custom method. |
| 9142 |
*/ |
| 9143 |
void tst_QNetworkReply::ioHttpRedirectWithUploadDevice() |
| 9144 |
{ |
| 9145 |
QFETCH(QByteArray, method); |
| 9146 |
QFETCH(QString, status); |
| 9147 |
QFETCH(bool, keepMethod); |
| 9148 |
|
| 9149 |
MiniHttpServer target(httpEmpty200Response, false); |
| 9150 |
QUrl targetUrl("http://localhost/"); |
| 9151 |
targetUrl.setPort(target.serverPort()); |
| 9152 |
|
| 9153 |
QString redirectReply = QStringLiteral("HTTP/1.1 %1\r\n" |
| 9154 |
"Content-Type: text/plain\r\n" |
| 9155 |
"location: %2\r\n" |
| 9156 |
"\r\n").arg(status, targetUrl.toString()); |
| 9157 |
MiniHttpServer redirectServer(redirectReply.toLatin1()); |
| 9158 |
QUrl url("http://localhost/"); |
| 9159 |
url.setPort(redirectServer.serverPort()); |
| 9160 |
|
| 9161 |
QNetworkRequest request(url); |
| 9162 |
request.setHeader(QNetworkRequest::ContentTypeHeader, QByteArray("text/plain")); |
| 9163 |
auto oldRedirectPolicy = manager.redirectPolicy(); |
| 9164 |
manager.setRedirectPolicy(QNetworkRequest::RedirectPolicy::NoLessSafeRedirectPolicy); |
| 9165 |
|
| 9166 |
QByteArray data = "Hello world"; |
| 9167 |
QBuffer buffer(&data); |
| 9168 |
|
| 9169 |
QNetworkReplyPtr reply; |
| 9170 |
if (method == "POST") |
| 9171 |
reply.reset(manager.post(request, &buffer)); |
| 9172 |
else |
| 9173 |
reply.reset(manager.sendCustomRequest(request, method, &buffer)); |
| 9174 |
// Restore previous policy: |
| 9175 |
manager.setRedirectPolicy(oldRedirectPolicy); |
| 9176 |
|
| 9177 |
QCOMPARE(waitForFinish(reply), int(Success)); |
| 9178 |
QByteArray expectedMethod = method; |
| 9179 |
if (!keepMethod) |
| 9180 |
expectedMethod = "GET"; |
| 9181 |
QVERIFY2(target.receivedData.startsWith(expectedMethod), "Target server called with the wrong method"); |
| 9182 |
if (keepMethod) { // keepMethod also means we resend the data |
| 9183 |
QVERIFY2(target.receivedData.endsWith(data), "Target server didn't receive the data"); |
| 9184 |
} else { |
| 9185 |
// we shouldn't send Content-Length with not content (esp. for GET) |
| 9186 |
QVERIFY2(!target.receivedData.contains("Content-Length"), |
| 9187 |
"Target server should not have received a Content-Length header"); |
| 9188 |
QVERIFY2(!target.receivedData.contains("Content-Type"), |
| 9189 |
"Target server should not have received a Content-Type header"); |
| 9190 |
} |
| 9191 |
} |
| 9192 |
|
| 9193 |
#ifndef QT_NO_SSL |
| 9194 |
|
| 9195 |
class PutWithServerClosingConnectionImmediatelyHandler: public QObject |
| 9196 |
{ |
| 9197 |
Q_OBJECT |
| 9198 |
public: |
| 9199 |
bool m_parsedHeaders; |
| 9200 |
QByteArray m_receivedData; |
| 9201 |
QByteArray m_expectedData; |
| 9202 |
QSslSocket *m_socket; |
| 9203 |
PutWithServerClosingConnectionImmediatelyHandler(QSslSocket *s, QByteArray expected) :m_parsedHeaders(false), m_expectedData(expected), m_socket(s) |
| 9204 |
{ |
| 9205 |
m_socket->setParent(this); |
| 9206 |
connect(m_socket, SIGNAL(readyRead()), SLOT(readyReadSlot())); |
| 9207 |
connect(m_socket, SIGNAL(disconnected()), SLOT(disconnectedSlot())); |
| 9208 |
} |
| 9209 |
signals: |
| 9210 |
void correctFileUploadReceived(); |
| 9211 |
void corruptFileUploadReceived(); |
| 9212 |
|
| 9213 |
public slots: |
| 9214 |
void closeDelayed() { m_socket->close(); } |
| 9215 |
|
| 9216 |
void readyReadSlot() |
| 9217 |
{ |
| 9218 |
QByteArray data = m_socket->readAll(); |
| 9219 |
m_receivedData += data; |
| 9220 |
if (!m_parsedHeaders && m_receivedData.contains("\r\n\r\n")) { |
| 9221 |
m_parsedHeaders = true; |
| 9222 |
QTimer::singleShot(QRandomGenerator::global()->bounded(60), this, SLOT(closeDelayed())); // simulate random network latency |
| 9223 |
// This server simulates a web server connection closing, e.g. because of Apaches MaxKeepAliveRequests or KeepAliveTimeout |
| 9224 |
// In this case QNAM needs to re-send the upload data but it had a bug which then corrupts the upload |
| 9225 |
// This test catches that. |
| 9226 |
} |
| 9227 |
|
| 9228 |
} |
| 9229 |
void disconnectedSlot() |
| 9230 |
{ |
| 9231 |
if (m_parsedHeaders) { |
| 9232 |
//qDebug() << m_receivedData.left(m_receivedData.indexOf("\r\n\r\n")); |
| 9233 |
m_receivedData = m_receivedData.mid(m_receivedData.indexOf("\r\n\r\n")+4); // check only actual data |
| 9234 |
} |
| 9235 |
if (m_receivedData.length() > 0 && !m_expectedData.startsWith(m_receivedData)) { |
| 9236 |
// We had received some data but it is corrupt! |
| 9237 |
qDebug() << "CORRUPT" << m_receivedData.count(); |
| 9238 |
|
| 9239 |
#if 0 // Use this to track down the pattern of the corruption and conclude the source |
| 9240 |
QFile a("/tmp/corrupt"); |
| 9241 |
a.open(QIODevice::WriteOnly); |
| 9242 |
a.write(m_receivedData); |
| 9243 |
a.close(); |
| 9244 |
|
| 9245 |
QFile b("/tmp/correct"); |
| 9246 |
b.open(QIODevice::WriteOnly); |
| 9247 |
b.write(m_expectedData); |
| 9248 |
b.close(); |
| 9249 |
//exit(1); |
| 9250 |
#endif |
| 9251 |
emit corruptFileUploadReceived(); |
| 9252 |
} else { |
| 9253 |
emit correctFileUploadReceived(); |
| 9254 |
} |
| 9255 |
} |
| 9256 |
}; |
| 9257 |
|
| 9258 |
class PutWithServerClosingConnectionImmediatelyServer: public SslServer |
| 9259 |
{ |
| 9260 |
Q_OBJECT |
| 9261 |
public: |
| 9262 |
int m_correctUploads; |
| 9263 |
int m_corruptUploads; |
| 9264 |
int m_repliesFinished; |
| 9265 |
int m_expectedReplies; |
| 9266 |
QByteArray m_expectedData; |
| 9267 |
PutWithServerClosingConnectionImmediatelyServer() |
| 9268 |
: SslServer(), m_correctUploads(0), m_corruptUploads(0), |
| 9269 |
m_repliesFinished(0), m_expectedReplies(0) |
| 9270 |
{ |
| 9271 |
QObject::connect(this, SIGNAL(newEncryptedConnection(QSslSocket*)), this, SLOT(createHandlerForConnection(QSslSocket*))); |
| 9272 |
QObject::connect(this, SIGNAL(newPlainConnection(QSslSocket*)), this, SLOT(createHandlerForConnection(QSslSocket*))); |
| 9273 |
} |
| 9274 |
|
| 9275 |
public slots: |
| 9276 |
void createHandlerForConnection(QSslSocket* s) |
| 9277 |
{ |
| 9278 |
PutWithServerClosingConnectionImmediatelyHandler *handler = new PutWithServerClosingConnectionImmediatelyHandler(s, m_expectedData); |
| 9279 |
handler->setParent(this); |
| 9280 |
QObject::connect(handler, SIGNAL(correctFileUploadReceived()), this, SLOT(increaseCorrect())); |
| 9281 |
QObject::connect(handler, SIGNAL(corruptFileUploadReceived()), this, SLOT(increaseCorrupt())); |
| 9282 |
} |
| 9283 |
void increaseCorrect() { m_correctUploads++; } |
| 9284 |
void increaseCorrupt() { m_corruptUploads++; } |
| 9285 |
void replyFinished() |
| 9286 |
{ |
| 9287 |
m_repliesFinished++; |
| 9288 |
if (m_repliesFinished == m_expectedReplies) { |
| 9289 |
QTestEventLoop::instance().exitLoop(); |
| 9290 |
} |
| 9291 |
} |
| 9292 |
}; |
| 9293 |
|
| 9294 |
|
| 9295 |
|
| 9296 |
void tst_QNetworkReply::putWithServerClosingConnectionImmediately() |
| 9297 |
{ |
| 9298 |
const int numUploads = 40; |
| 9299 |
qint64 wantedSize = 512*1024; // 512 kB |
| 9300 |
QByteArray sourceFile; |
| 9301 |
for (int i = 0; i < wantedSize; ++i) { |
| 9302 |
sourceFile += (char)'a' +(i%26); |
| 9303 |
} |
| 9304 |
bool withSsl = false; |
| 9305 |
|
| 9306 |
for (int s = 0; s <= 1; s++) { |
| 9307 |
withSsl = (s == 1); |
| 9308 |
// Test also needs to run several times because of 9c2ecf89 |
| 9309 |
for (int j = 0; j < 20; j++) { |
| 9310 |
// emulate a minimal https server |
| 9311 |
PutWithServerClosingConnectionImmediatelyServer server; |
| 9312 |
server.m_ssl = withSsl; |
| 9313 |
server.m_expectedData = sourceFile; |
| 9314 |
server.m_expectedReplies = numUploads; |
| 9315 |
server.listen(QHostAddress(QHostAddress::LocalHost), 0); |
| 9316 |
|
| 9317 |
QString urlPrefix = QLatin1String("http"); |
| 9318 |
if (withSsl) |
| 9319 |
urlPrefix += QLatin1Char('s'); |
| 9320 |
urlPrefix += QLatin1String("://127.0.0.1:"); |
| 9321 |
urlPrefix += QString::number(server.serverPort()); |
| 9322 |
urlPrefix += QLatin1String("/file="); |
| 9323 |
for (int i = 0; i < numUploads; i++) { |
| 9324 |
// create the request |
| 9325 |
QNetworkRequest request(QUrl(urlPrefix + QString::number(i))); |
| 9326 |
QNetworkReply *reply = manager.put(request, sourceFile); |
| 9327 |
connect(reply, SIGNAL(sslErrors(QList<QSslError>)), reply, SLOT(ignoreSslErrors())); |
| 9328 |
connect(reply, SIGNAL(finished()), &server, SLOT(replyFinished())); |
| 9329 |
reply->setParent(&server); |
| 9330 |
} |
| 9331 |
|
| 9332 |
// get the request started and the incoming socket connected |
| 9333 |
QTestEventLoop::instance().enterLoop(10); |
| 9334 |
QVERIFY(!QTestEventLoop::instance().timeout()); |
| 9335 |
|
| 9336 |
//qDebug() << "correct=" << server.m_correctUploads << "corrupt=" << server.m_corruptUploads << "expected=" <<numUploads; |
| 9337 |
|
| 9338 |
// Sanity check because ecause of 9c2ecf89 most replies will error out but we want to make sure at least some of them worked |
| 9339 |
QVERIFY(server.m_correctUploads > 2); |
| 9340 |
// Because actually important is that we don't get any corruption: |
| 9341 |
QCOMPARE(server.m_corruptUploads, 0); |
| 9342 |
|
| 9343 |
server.close(); |
| 9344 |
} |
| 9345 |
} |
| 9346 |
|
| 9347 |
|
| 9348 |
} |
| 9349 |
|
| 9350 |
#endif |
| 9351 |
|
| 9352 |
void tst_QNetworkReply::autoDeleteRepliesAttribute_data() |
| 9353 |
{ |
| 9354 |
QTest::addColumn<QUrl>("destination"); |
| 9355 |
|
| 9356 |
QUrl webServerUrl = QtNetworkSettings::httpServerIp().toString(); |
| 9357 |
webServerUrl.setPath("/notfound"); |
| 9358 |
webServerUrl.setScheme("http"); |
| 9359 |
QTest::newRow("http") << webServerUrl; |
| 9360 |
webServerUrl.setScheme("https"); |
| 9361 |
QTest::newRow("https") << webServerUrl; |
| 9362 |
QUrl ftpServerUrl = QtNetworkSettings::ftpServerName(); |
| 9363 |
ftpServerUrl.setScheme("ftp"); |
| 9364 |
ftpServerUrl.setPath("/test/notfound"); |
| 9365 |
QTest::newRow("ftp") << ftpServerUrl; |
| 9366 |
QTest::newRow("file") << QUrl("file:///thisfolderdoesn'texist/probably.txt"); |
| 9367 |
#ifdef Q_OS_WIN |
| 9368 |
// Only supported on windows. |
| 9369 |
QTest::newRow("remote-file") << QUrl("file://QInvalidHost/thisfolderdoesn'texist/probably.txt"); |
| 9370 |
#endif |
| 9371 |
QTest::newRow("qrc") << QUrl("qrc:///path/to/nowhere"); |
| 9372 |
QTest::newRow("data") << QUrl("data:,Some%20plaintext%20data"); |
| 9373 |
} |
| 9374 |
|
| 9375 |
void tst_QNetworkReply::autoDeleteRepliesAttribute() |
| 9376 |
{ |
| 9377 |
QFETCH(QUrl, destination); |
| 9378 |
{ |
| 9379 |
// Get |
| 9380 |
QNetworkRequest request(destination); |
| 9381 |
request.setAttribute(QNetworkRequest::AutoDeleteReplyOnFinishAttribute, true); |
| 9382 |
QNetworkReply *reply = manager.get(request); |
| 9383 |
QSignalSpy finishedSpy(reply, &QNetworkReply::finished); |
| 9384 |
QSignalSpy destroyedSpy(reply, &QObject::destroyed); |
| 9385 |
QVERIFY(finishedSpy.wait()); |
| 9386 |
QCOMPARE(destroyedSpy.count(), 0); |
| 9387 |
QVERIFY(destroyedSpy.wait()); |
| 9388 |
} |
| 9389 |
{ |
| 9390 |
// Post |
| 9391 |
QNetworkRequest request(destination); |
| 9392 |
request.setAttribute(QNetworkRequest::AutoDeleteReplyOnFinishAttribute, true); |
| 9393 |
QNetworkReply *reply = manager.post(request, QByteArrayLiteral("datastring")); |
| 9394 |
QSignalSpy finishedSpy(reply, &QNetworkReply::finished); |
| 9395 |
QSignalSpy destroyedSpy(reply, &QObject::destroyed); |
| 9396 |
QVERIFY(finishedSpy.wait()); |
| 9397 |
QCOMPARE(destroyedSpy.count(), 0); |
| 9398 |
QVERIFY(destroyedSpy.wait()); |
| 9399 |
} |
| 9400 |
// Now repeated, but without the attribute to make sure it does not get deleted automatically. |
| 9401 |
// We need two calls to processEvents to test that the QNetworkReply doesn't get deleted. |
| 9402 |
// The first call executes a metacall event which adds the deleteLater meta event which |
| 9403 |
// would be executed in the second call. But that shouldn't happen without the attribute. |
| 9404 |
{ |
| 9405 |
// Get |
| 9406 |
QNetworkRequest request(destination); |
| 9407 |
QScopedPointer<QNetworkReply> reply(manager.get(request)); |
| 9408 |
QSignalSpy finishedSpy(reply.data(), &QNetworkReply::finished); |
| 9409 |
QSignalSpy destroyedSpy(reply.data(), &QObject::destroyed); |
| 9410 |
QVERIFY(finishedSpy.wait()); |
| 9411 |
QCOMPARE(destroyedSpy.count(), 0); |
| 9412 |
QCoreApplication::processEvents(); |
| 9413 |
QCoreApplication::processEvents(); |
| 9414 |
QCOMPARE(destroyedSpy.count(), 0); |
| 9415 |
} |
| 9416 |
{ |
| 9417 |
// Post |
| 9418 |
QNetworkRequest request(destination); |
| 9419 |
QScopedPointer<QNetworkReply> reply(manager.post(request, QByteArrayLiteral("datastring"))); |
| 9420 |
QSignalSpy finishedSpy(reply.data(), &QNetworkReply::finished); |
| 9421 |
QSignalSpy destroyedSpy(reply.data(), &QObject::destroyed); |
| 9422 |
QVERIFY(finishedSpy.wait()); |
| 9423 |
QCOMPARE(destroyedSpy.count(), 0); |
| 9424 |
QCoreApplication::processEvents(); |
| 9425 |
QCoreApplication::processEvents(); |
| 9426 |
QCOMPARE(destroyedSpy.count(), 0); |
| 9427 |
} |
| 9428 |
} |
| 9429 |
|
| 9430 |
void tst_QNetworkReply::autoDeleteReplies_data() |
| 9431 |
{ |
| 9432 |
autoDeleteRepliesAttribute_data(); |
| 9433 |
} |
| 9434 |
|
| 9435 |
void tst_QNetworkReply::autoDeleteReplies() |
| 9436 |
{ |
| 9437 |
QFETCH(QUrl, destination); |
| 9438 |
manager.setAutoDeleteReplies(true); |
| 9439 |
auto cleanup = qScopeGuard([this] { manager.setAutoDeleteReplies(false); }); |
| 9440 |
{ |
| 9441 |
// Get |
| 9442 |
QNetworkRequest request(destination); |
| 9443 |
QNetworkReply *reply = manager.get(request); |
| 9444 |
QSignalSpy finishedSpy(reply, &QNetworkReply::finished); |
| 9445 |
QSignalSpy destroyedSpy(reply, &QObject::destroyed); |
| 9446 |
QVERIFY(finishedSpy.wait()); |
| 9447 |
QCOMPARE(destroyedSpy.count(), 0); |
| 9448 |
QVERIFY(destroyedSpy.wait()); |
| 9449 |
} |
| 9450 |
{ |
| 9451 |
// Post |
| 9452 |
QNetworkRequest request(destination); |
| 9453 |
QNetworkReply *reply = manager.post(request, QByteArrayLiteral("datastring")); |
| 9454 |
QSignalSpy finishedSpy(reply, &QNetworkReply::finished); |
| 9455 |
QSignalSpy destroyedSpy(reply, &QObject::destroyed); |
| 9456 |
QVERIFY(finishedSpy.wait()); |
| 9457 |
QCOMPARE(destroyedSpy.count(), 0); |
| 9458 |
QVERIFY(destroyedSpy.wait()); |
| 9459 |
} |
| 9460 |
// Here we repeat the test, but override the auto-deletion in the QNetworkRequest |
| 9461 |
// We need two calls to processEvents to test that the QNetworkReply doesn't get deleted. |
| 9462 |
// The first call executes a metacall event which adds the deleteLater meta event which |
| 9463 |
// would be executed in the second call. But that shouldn't happen in this case. |
| 9464 |
{ |
| 9465 |
// Get |
| 9466 |
QNetworkRequest request(destination); |
| 9467 |
request.setAttribute(QNetworkRequest::AutoDeleteReplyOnFinishAttribute, false); |
| 9468 |
QScopedPointer<QNetworkReply> reply(manager.get(request)); |
| 9469 |
QSignalSpy finishedSpy(reply.data(), &QNetworkReply::finished); |
| 9470 |
QSignalSpy destroyedSpy(reply.data(), &QObject::destroyed); |
| 9471 |
QVERIFY(finishedSpy.wait()); |
| 9472 |
QCOMPARE(destroyedSpy.count(), 0); |
| 9473 |
QCoreApplication::processEvents(); |
| 9474 |
QCoreApplication::processEvents(); |
| 9475 |
QCOMPARE(destroyedSpy.count(), 0); |
| 9476 |
} |
| 9477 |
{ |
| 9478 |
// Post |
| 9479 |
QNetworkRequest request(destination); |
| 9480 |
request.setAttribute(QNetworkRequest::AutoDeleteReplyOnFinishAttribute, false); |
| 9481 |
QScopedPointer<QNetworkReply> reply(manager.post(request, QByteArrayLiteral("datastring"))); |
| 9482 |
QSignalSpy finishedSpy(reply.data(), &QNetworkReply::finished); |
| 9483 |
QSignalSpy destroyedSpy(reply.data(), &QObject::destroyed); |
| 9484 |
QVERIFY(finishedSpy.wait()); |
| 9485 |
QCOMPARE(destroyedSpy.count(), 0); |
| 9486 |
QCoreApplication::processEvents(); |
| 9487 |
QCoreApplication::processEvents(); |
| 9488 |
QCOMPARE(destroyedSpy.count(), 0); |
| 9489 |
} |
| 9490 |
// Now we repeat the test with autoDeleteReplies set to false |
| 9491 |
cleanup.dismiss(); |
| 9492 |
manager.setAutoDeleteReplies(false); |
| 9493 |
{ |
| 9494 |
// Get |
| 9495 |
QNetworkRequest request(destination); |
| 9496 |
QScopedPointer<QNetworkReply> reply(manager.get(request)); |
| 9497 |
QSignalSpy finishedSpy(reply.data(), &QNetworkReply::finished); |
| 9498 |
QSignalSpy destroyedSpy(reply.data(), &QObject::destroyed); |
| 9499 |
QVERIFY(finishedSpy.wait()); |
| 9500 |
QCOMPARE(destroyedSpy.count(), 0); |
| 9501 |
QCoreApplication::processEvents(); |
| 9502 |
QCoreApplication::processEvents(); |
| 9503 |
QCOMPARE(destroyedSpy.count(), 0); |
| 9504 |
} |
| 9505 |
{ |
| 9506 |
// Post |
| 9507 |
QNetworkRequest request(destination); |
| 9508 |
QScopedPointer<QNetworkReply> reply(manager.post(request, QByteArrayLiteral("datastring"))); |
| 9509 |
QSignalSpy finishedSpy(reply.data(), &QNetworkReply::finished); |
| 9510 |
QSignalSpy destroyedSpy(reply.data(), &QObject::destroyed); |
| 9511 |
QVERIFY(finishedSpy.wait()); |
| 9512 |
QCOMPARE(destroyedSpy.count(), 0); |
| 9513 |
QCoreApplication::processEvents(); |
| 9514 |
QCoreApplication::processEvents(); |
| 9515 |
QCOMPARE(destroyedSpy.count(), 0); |
| 9516 |
} |
| 9517 |
} |
| 9518 |
|
| 9519 |
void tst_QNetworkReply::getWithTimeout() |
| 9520 |
{ |
| 9521 |
MiniHttpServer server(tst_QNetworkReply::httpEmpty200Response, false); |
| 9522 |
|
| 9523 |
QNetworkRequest request(QUrl("http://localhost:" + QString::number(server.serverPort()))); |
| 9524 |
QNetworkReplyPtr reply(manager.get(request)); |
| 9525 |
QSignalSpy spy(reply.data(), SIGNAL(errorOccurred(QNetworkReply::NetworkError))); |
| 9526 |
|
| 9527 |
QCOMPARE(waitForFinish(reply), int(Success)); |
| 9528 |
|
| 9529 |
QCOMPARE(spy.count(), 0); |
| 9530 |
QVERIFY(reply->error() == QNetworkReply::NoError); |
| 9531 |
|
| 9532 |
request.setTransferTimeout(1000); |
| 9533 |
server.stopTransfer = true; |
| 9534 |
|
| 9535 |
QNetworkReplyPtr reply2(manager.get(request)); |
| 9536 |
QSignalSpy spy2(reply2.data(), SIGNAL(errorOccurred(QNetworkReply::NetworkError))); |
| 9537 |
|
| 9538 |
QCOMPARE(waitForFinish(reply2), int(Failure)); |
| 9539 |
|
| 9540 |
QCOMPARE(spy2.count(), 1); |
| 9541 |
QVERIFY(reply2->error() == QNetworkReply::OperationCanceledError); |
| 9542 |
|
| 9543 |
request.setTransferTimeout(0); |
| 9544 |
manager.setTransferTimeout(1000); |
| 9545 |
|
| 9546 |
QNetworkReplyPtr reply3(manager.get(request)); |
| 9547 |
QSignalSpy spy3(reply3.data(), SIGNAL(errorOccurred(QNetworkReply::NetworkError))); |
| 9548 |
|
| 9549 |
QCOMPARE(waitForFinish(reply3), int(Failure)); |
| 9550 |
|
| 9551 |
QCOMPARE(spy3.count(), 1); |
| 9552 |
QVERIFY(reply3->error() == QNetworkReply::OperationCanceledError); |
| 9553 |
|
| 9554 |
manager.setTransferTimeout(0); |
| 9555 |
} |
| 9556 |
|
| 9557 |
void tst_QNetworkReply::postWithTimeout() |
| 9558 |
{ |
| 9559 |
MiniHttpServer server(tst_QNetworkReply::httpEmpty200Response, false); |
| 9560 |
|
| 9561 |
QNetworkRequest request(QUrl("http://localhost:" + QString::number(server.serverPort()))); |
| 9562 |
request.setRawHeader("Content-Type", "application/octet-stream"); |
| 9563 |
QByteArray postData("Just some nonsense"); |
| 9564 |
QNetworkReplyPtr reply(manager.post(request, postData)); |
| 9565 |
QSignalSpy spy(reply.data(), SIGNAL(errorOccurred(QNetworkReply::NetworkError))); |
| 9566 |
|
| 9567 |
QCOMPARE(waitForFinish(reply), int(Success)); |
| 9568 |
|
| 9569 |
QCOMPARE(spy.count(), 0); |
| 9570 |
QVERIFY(reply->error() == QNetworkReply::NoError); |
| 9571 |
|
| 9572 |
request.setTransferTimeout(1000); |
| 9573 |
server.stopTransfer = true; |
| 9574 |
|
| 9575 |
QNetworkReplyPtr reply2(manager.post(request, postData)); |
| 9576 |
QSignalSpy spy2(reply2.data(), SIGNAL(errorOccurred(QNetworkReply::NetworkError))); |
| 9577 |
|
| 9578 |
QCOMPARE(waitForFinish(reply2), int(Failure)); |
| 9579 |
|
| 9580 |
QCOMPARE(spy2.count(), 1); |
| 9581 |
QVERIFY(reply2->error() == QNetworkReply::OperationCanceledError); |
| 9582 |
|
| 9583 |
request.setTransferTimeout(0); |
| 9584 |
manager.setTransferTimeout(1000); |
| 9585 |
|
| 9586 |
QNetworkReplyPtr reply3(manager.post(request, postData)); |
| 9587 |
QSignalSpy spy3(reply3.data(), SIGNAL(errorOccurred(QNetworkReply::NetworkError))); |
| 9588 |
|
| 9589 |
QCOMPARE(waitForFinish(reply3), int(Failure)); |
| 9590 |
|
| 9591 |
QCOMPARE(spy3.count(), 1); |
| 9592 |
QVERIFY(reply3->error() == QNetworkReply::OperationCanceledError); |
| 9593 |
|
| 9594 |
manager.setTransferTimeout(0); |
| 9595 |
} |
| 9596 |
|
| 9597 |
// NOTE: This test must be last testcase in tst_qnetworkreply! |
| 9598 |
void tst_QNetworkReply::parentingRepliesToTheApp() |
| 9599 |
{ |
| 9600 |
QNetworkRequest request(QUrl("http://" + QtNetworkSettings::httpServerName())); |
| 9601 |
manager.get(request)->setParent(this); // parent to this object |
| 9602 |
manager.get(request)->setParent(qApp); // parent to the app |
| 9603 |
} |
| 9604 |
|
| 9605 |
QTEST_MAIN(tst_QNetworkReply) |
| 9606 |
|
| 9607 |
#include "tst_qnetworkreply.moc" |