summaryrefslogtreecommitdiffstats
path: root/tests/auto/network
diff options
context:
space:
mode:
Diffstat (limited to 'tests/auto/network')
-rw-r--r--tests/auto/network/CMakeLists.txt8
-rw-r--r--tests/auto/network/access/CMakeLists.txt8
-rw-r--r--tests/auto/network/access/hpack/CMakeLists.txt14
-rw-r--r--tests/auto/network/access/hpack/tst_hpack.cpp31
-rw-r--r--tests/auto/network/access/hsts/CMakeLists.txt12
-rw-r--r--tests/auto/network/access/hsts/tst_qhsts.cpp118
-rw-r--r--tests/auto/network/access/http2/BLACKLIST2
-rw-r--r--tests/auto/network/access/http2/CMakeLists.txt12
-rw-r--r--tests/auto/network/access/http2/http2srv.cpp111
-rw-r--r--tests/auto/network/access/http2/http2srv.h45
-rw-r--r--tests/auto/network/access/http2/tst_http2.cpp513
-rw-r--r--tests/auto/network/access/qabstractnetworkcache/CMakeLists.txt14
-rw-r--r--tests/auto/network/access/qabstractnetworkcache/tst_qabstractnetworkcache.cpp35
-rw-r--r--tests/auto/network/access/qdecompresshelper/CMakeLists.txt16
-rw-r--r--tests/auto/network/access/qdecompresshelper/tst_qdecompresshelper.cpp49
-rw-r--r--tests/auto/network/access/qhttp2connection/CMakeLists.txt16
-rw-r--r--tests/auto/network/access/qhttp2connection/tst_qhttp2connection.cpp397
-rw-r--r--tests/auto/network/access/qhttpheaderparser/CMakeLists.txt19
-rw-r--r--tests/auto/network/access/qhttpheaderparser/tst_qhttpheaderparser.cpp94
-rw-r--r--tests/auto/network/access/qhttpheaders/CMakeLists.txt16
-rw-r--r--tests/auto/network/access/qhttpheaders/tst_qhttpheaders.cpp552
-rw-r--r--tests/auto/network/access/qhttpnetworkconnection/CMakeLists.txt17
-rw-r--r--tests/auto/network/access/qhttpnetworkconnection/tst_qhttpnetworkconnection.cpp51
-rw-r--r--tests/auto/network/access/qhttpnetworkreply/CMakeLists.txt14
-rw-r--r--tests/auto/network/access/qhttpnetworkreply/tst_qhttpnetworkreply.cpp82
-rw-r--r--tests/auto/network/access/qnetworkaccessmanager/CMakeLists.txt11
-rw-r--r--tests/auto/network/access/qnetworkaccessmanager/tst_qnetworkaccessmanager.cpp29
-rw-r--r--tests/auto/network/access/qnetworkcachemetadata/CMakeLists.txt11
-rw-r--r--tests/auto/network/access/qnetworkcachemetadata/tst_qnetworkcachemetadata.cpp29
-rw-r--r--tests/auto/network/access/qnetworkcookie/CMakeLists.txt11
-rw-r--r--tests/auto/network/access/qnetworkcookie/tst_qnetworkcookie.cpp249
-rw-r--r--tests/auto/network/access/qnetworkcookiejar/CMakeLists.txt13
-rw-r--r--tests/auto/network/access/qnetworkcookiejar/testdata/publicsuffix/public_suffix_list.dafsabin0 -> 52422 bytes
-rw-r--r--tests/auto/network/access/qnetworkcookiejar/tst_qnetworkcookiejar.cpp101
-rw-r--r--tests/auto/network/access/qnetworkdiskcache/CMakeLists.txt11
-rw-r--r--tests/auto/network/access/qnetworkdiskcache/tst_qnetworkdiskcache.cpp74
-rw-r--r--tests/auto/network/access/qnetworkreply/BLACKLIST31
-rw-r--r--tests/auto/network/access/qnetworkreply/CMakeLists.txt9
-rw-r--r--tests/auto/network/access/qnetworkreply/certs/qt-test-server-cacert.pem30
-rw-r--r--tests/auto/network/access/qnetworkreply/certs/server.key38
-rw-r--r--tests/auto/network/access/qnetworkreply/certs/server.pem42
-rw-r--r--tests/auto/network/access/qnetworkreply/echo/CMakeLists.txt5
-rw-r--r--tests/auto/network/access/qnetworkreply/echo/main.cpp35
-rw-r--r--tests/auto/network/access/qnetworkreply/qnetworkreply.qrc5
-rw-r--r--tests/auto/network/access/qnetworkreply/test/CMakeLists.txt23
-rw-r--r--tests/auto/network/access/qnetworkreply/tst_qnetworkreply.cpp1498
-rw-r--r--tests/auto/network/access/qnetworkrequest/CMakeLists.txt11
-rw-r--r--tests/auto/network/access/qnetworkrequest/tst_qnetworkrequest.cpp84
-rw-r--r--tests/auto/network/access/qnetworkrequestfactory/CMakeLists.txt17
-rw-r--r--tests/auto/network/access/qnetworkrequestfactory/tst_qnetworkrequestfactory.cpp423
-rw-r--r--tests/auto/network/access/qrestaccessmanager/CMakeLists.txt17
-rw-r--r--tests/auto/network/access/qrestaccessmanager/httptestserver.cpp268
-rw-r--r--tests/auto/network/access/qrestaccessmanager/httptestserver_p.h90
-rw-r--r--tests/auto/network/access/qrestaccessmanager/tst_qrestaccessmanager.cpp870
-rw-r--r--tests/auto/network/kernel/CMakeLists.txt12
-rw-r--r--tests/auto/network/kernel/qauthenticator/CMakeLists.txt14
-rw-r--r--tests/auto/network/kernel/qauthenticator/tst_qauthenticator.cpp54
-rw-r--r--tests/auto/network/kernel/qdnslookup/BLACKLIST2
-rw-r--r--tests/auto/network/kernel/qdnslookup/CMakeLists.txt17
-rw-r--r--tests/auto/network/kernel/qdnslookup/tst_qdnslookup.cpp783
-rw-r--r--tests/auto/network/kernel/qdnslookup_appless/CMakeLists.txt11
-rw-r--r--tests/auto/network/kernel/qdnslookup_appless/tst_qdnslookup_appless.cpp29
-rw-r--r--tests/auto/network/kernel/qhostaddress/CMakeLists.txt13
-rw-r--r--tests/auto/network/kernel/qhostaddress/tst_qhostaddress.cpp41
-rw-r--r--tests/auto/network/kernel/qhostinfo/CMakeLists.txt16
-rw-r--r--tests/auto/network/kernel/qhostinfo/tst_qhostinfo.cpp396
-rw-r--r--tests/auto/network/kernel/qnetworkaddressentry/CMakeLists.txt11
-rw-r--r--tests/auto/network/kernel/qnetworkaddressentry/tst_qnetworkaddressentry.cpp29
-rw-r--r--tests/auto/network/kernel/qnetworkdatagram/CMakeLists.txt11
-rw-r--r--tests/auto/network/kernel/qnetworkdatagram/tst_qnetworkdatagram.cpp29
-rw-r--r--tests/auto/network/kernel/qnetworkinformation/CMakeLists.txt11
-rw-r--r--tests/auto/network/kernel/qnetworkinformation/tst_qnetworkinformation.cpp41
-rw-r--r--tests/auto/network/kernel/qnetworkinformation_appless/CMakeLists.txt11
-rw-r--r--tests/auto/network/kernel/qnetworkinformation_appless/tst_qnetworkinformation_appless.cpp33
-rw-r--r--tests/auto/network/kernel/qnetworkinterface/CMakeLists.txt14
-rw-r--r--tests/auto/network/kernel/qnetworkinterface/tst_qnetworkinterface.cpp77
-rw-r--r--tests/auto/network/kernel/qnetworkproxy/CMakeLists.txt11
-rw-r--r--tests/auto/network/kernel/qnetworkproxy/tst_qnetworkproxy.cpp29
-rw-r--r--tests/auto/network/kernel/qnetworkproxyfactory/BLACKLIST3
-rw-r--r--tests/auto/network/kernel/qnetworkproxyfactory/CMakeLists.txt11
-rw-r--r--tests/auto/network/kernel/qnetworkproxyfactory/tst_qnetworkproxyfactory.cpp53
-rw-r--r--tests/auto/network/selftest/tst_networkselftest.cpp29
-rw-r--r--tests/auto/network/socket/CMakeLists.txt7
-rw-r--r--tests/auto/network/socket/platformsocketengine/BLACKLIST9
-rw-r--r--tests/auto/network/socket/platformsocketengine/CMakeLists.txt18
-rw-r--r--tests/auto/network/socket/platformsocketengine/tst_platformsocketengine.cpp45
-rw-r--r--tests/auto/network/socket/qabstractsocket/CMakeLists.txt11
-rw-r--r--tests/auto/network/socket/qabstractsocket/tst_qabstractsocket.cpp29
-rw-r--r--tests/auto/network/socket/qhttpsocketengine/BLACKLIST3
-rw-r--r--tests/auto/network/socket/qhttpsocketengine/CMakeLists.txt20
-rw-r--r--tests/auto/network/socket/qhttpsocketengine/tst_qhttpsocketengine.cpp37
-rw-r--r--tests/auto/network/socket/qlocalsocket/BLACKLIST3
-rw-r--r--tests/auto/network/socket/qlocalsocket/CMakeLists.txt16
-rw-r--r--tests/auto/network/socket/qlocalsocket/socketprocess/CMakeLists.txt5
-rw-r--r--tests/auto/network/socket/qlocalsocket/socketprocess/main.cpp29
-rw-r--r--tests/auto/network/socket/qlocalsocket/tst_qlocalsocket.cpp251
-rw-r--r--tests/auto/network/socket/qsctpsocket/CMakeLists.txt11
-rw-r--r--tests/auto/network/socket/qsctpsocket/tst_qsctpsocket.cpp40
-rw-r--r--tests/auto/network/socket/qsocks5socketengine/BLACKLIST8
-rw-r--r--tests/auto/network/socket/qsocks5socketengine/CMakeLists.txt20
-rw-r--r--tests/auto/network/socket/qsocks5socketengine/tst_qsocks5socketengine.cpp41
-rw-r--r--tests/auto/network/socket/qtcpserver/BLACKLIST10
-rw-r--r--tests/auto/network/socket/qtcpserver/CMakeLists.txt11
-rw-r--r--tests/auto/network/socket/qtcpserver/crashingServer/CMakeLists.txt5
-rw-r--r--tests/auto/network/socket/qtcpserver/crashingServer/main.cpp62
-rw-r--r--tests/auto/network/socket/qtcpserver/test/CMakeLists.txt19
-rw-r--r--tests/auto/network/socket/qtcpserver/tst_qtcpserver.cpp176
-rw-r--r--tests/auto/network/socket/qtcpsocket/BLACKLIST26
-rw-r--r--tests/auto/network/socket/qtcpsocket/CMakeLists.txt9
-rw-r--r--tests/auto/network/socket/qtcpsocket/stressTest/CMakeLists.txt9
-rw-r--r--tests/auto/network/socket/qtcpsocket/stressTest/Test.cpp29
-rw-r--r--tests/auto/network/socket/qtcpsocket/stressTest/Test.h29
-rw-r--r--tests/auto/network/socket/qtcpsocket/stressTest/main.cpp29
-rw-r--r--tests/auto/network/socket/qtcpsocket/test/CMakeLists.txt23
-rw-r--r--tests/auto/network/socket/qtcpsocket/tst_qtcpsocket.cpp103
-rw-r--r--tests/auto/network/socket/qudpsocket/BLACKLIST6
-rw-r--r--tests/auto/network/socket/qudpsocket/CMakeLists.txt11
-rw-r--r--tests/auto/network/socket/qudpsocket/clientserver/CMakeLists.txt5
-rw-r--r--tests/auto/network/socket/qudpsocket/clientserver/main.cpp29
-rw-r--r--tests/auto/network/socket/qudpsocket/test/CMakeLists.txt30
-rw-r--r--tests/auto/network/socket/qudpsocket/tst_qudpsocket.cpp343
-rw-r--r--tests/auto/network/socket/qudpsocket/udpServer/CMakeLists.txt7
-rw-r--r--tests/auto/network/socket/qudpsocket/udpServer/main.cpp29
-rw-r--r--tests/auto/network/ssl/CMakeLists.txt12
-rw-r--r--tests/auto/network/ssl/qasn1element/CMakeLists.txt17
-rw-r--r--tests/auto/network/ssl/qasn1element/tst_qasn1element.cpp49
-rw-r--r--tests/auto/network/ssl/qdtls/CMakeLists.txt21
-rw-r--r--tests/auto/network/ssl/qdtls/certs/fluke.cert105
-rw-r--r--tests/auto/network/ssl/qdtls/certs/fluke.key67
-rw-r--r--tests/auto/network/ssl/qdtls/tst_qdtls.cpp97
-rw-r--r--tests/auto/network/ssl/qdtlscookie/CMakeLists.txt21
-rw-r--r--tests/auto/network/ssl/qdtlscookie/tst_qdtlscookie.cpp37
-rw-r--r--tests/auto/network/ssl/qocsp/CMakeLists.txt24
-rw-r--r--tests/auto/network/ssl/qocsp/tst_qocsp.cpp51
-rw-r--r--tests/auto/network/ssl/qpassworddigestor/CMakeLists.txt12
-rw-r--r--tests/auto/network/ssl/qpassworddigestor/tst_qpassworddigestor.cpp29
-rw-r--r--tests/auto/network/ssl/qsslcertificate/CMakeLists.txt14
-rwxr-xr-xtests/auto/network/ssl/qsslcertificate/certificates/gencertificates.sh29
-rw-r--r--tests/auto/network/ssl/qsslcertificate/more-certificates/cert-large-expiration-date.txt.0.9.842
-rw-r--r--tests/auto/network/ssl/qsslcertificate/more-certificates/cert-large-expiration-date.txt.1.0.142
-rw-r--r--tests/auto/network/ssl/qsslcertificate/more-certificates/cert-large-expiration-date.txt.1.0.1c41
-rw-r--r--tests/auto/network/ssl/qsslcertificate/more-certificates/cert-large-expiration-date.txt.3.0.5 (renamed from tests/auto/network/ssl/qsslcertificate/more-certificates/cert-large-expiration-date.txt.1.0.0)4
-rw-r--r--tests/auto/network/ssl/qsslcertificate/tst_qsslcertificate.cpp190
-rw-r--r--tests/auto/network/ssl/qsslcipher/CMakeLists.txt21
-rw-r--r--tests/auto/network/ssl/qsslcipher/tst_qsslcipher.cpp29
-rw-r--r--tests/auto/network/ssl/qssldiffiehellmanparameters/CMakeLists.txt12
-rw-r--r--tests/auto/network/ssl/qssldiffiehellmanparameters/tst_qssldiffiehellmanparameters.cpp29
-rw-r--r--tests/auto/network/ssl/qsslellipticcurve/CMakeLists.txt12
-rw-r--r--tests/auto/network/ssl/qsslellipticcurve/tst_qsslellipticcurve.cpp36
-rw-r--r--tests/auto/network/ssl/qsslerror/CMakeLists.txt21
-rw-r--r--tests/auto/network/ssl/qsslerror/tst_qsslerror.cpp29
-rw-r--r--tests/auto/network/ssl/qsslkey/BLACKLIST8
-rw-r--r--tests/auto/network/ssl/qsslkey/CMakeLists.txt21
-rwxr-xr-xtests/auto/network/ssl/qsslkey/keys/genkeys.sh29
-rw-r--r--tests/auto/network/ssl/qsslkey/tst_qsslkey.cpp123
-rw-r--r--tests/auto/network/ssl/qsslserver/CMakeLists.txt29
-rw-r--r--tests/auto/network/ssl/qsslserver/certs/selfsigned-client.crt18
-rw-r--r--tests/auto/network/ssl/qsslserver/certs/selfsigned-client.key27
-rw-r--r--tests/auto/network/ssl/qsslserver/certs/selfsigned-server.crt18
-rw-r--r--tests/auto/network/ssl/qsslserver/certs/selfsigned-server.key27
-rw-r--r--tests/auto/network/ssl/qsslserver/tst_qsslserver.cpp531
-rw-r--r--tests/auto/network/ssl/qsslsocket/BLACKLIST5
-rw-r--r--tests/auto/network/ssl/qsslsocket/CMakeLists.txt33
-rw-r--r--tests/auto/network/ssl/qsslsocket/certs/ca-generate.sh21
-rw-r--r--tests/auto/network/ssl/qsslsocket/certs/ca.conf10
-rw-r--r--tests/auto/network/ssl/qsslsocket/certs/ca.crt70
-rw-r--r--tests/auto/network/ssl/qsslsocket/certs/ca.key99
-rw-r--r--tests/auto/network/ssl/qsslsocket/certs/inter.conf14
-rw-r--r--tests/auto/network/ssl/qsslsocket/certs/inter.crt71
-rw-r--r--tests/auto/network/ssl/qsslsocket/certs/inter.key99
-rw-r--r--tests/auto/network/ssl/qsslsocket/certs/leaf.conf14
-rw-r--r--tests/auto/network/ssl/qsslsocket/certs/leaf.crt73
-rw-r--r--tests/auto/network/ssl/qsslsocket/certs/leaf.key127
-rw-r--r--tests/auto/network/ssl/qsslsocket/certs/qt-test-server-cacert.pem30
-rw-r--r--tests/auto/network/ssl/qsslsocket/tst_qsslsocket.cpp511
-rw-r--r--tests/auto/network/ssl/qsslsocket_onDemandCertificates_member/BLACKLIST7
-rw-r--r--tests/auto/network/ssl/qsslsocket_onDemandCertificates_member/CMakeLists.txt30
-rw-r--r--tests/auto/network/ssl/qsslsocket_onDemandCertificates_member/tst_qsslsocket_onDemandCertificates_member.cpp46
-rw-r--r--tests/auto/network/ssl/qsslsocket_onDemandCertificates_static/BLACKLIST2
-rw-r--r--tests/auto/network/ssl/qsslsocket_onDemandCertificates_static/CMakeLists.txt29
-rw-r--r--tests/auto/network/ssl/qsslsocket_onDemandCertificates_static/tst_qsslsocket_onDemandCertificates_static.cpp29
-rw-r--r--tests/auto/network/ssl/shared/qopenssl_symbols.h58
-rw-r--r--tests/auto/network/ssl/shared/tlshelpers.h34
183 files changed, 8670 insertions, 4341 deletions
diff --git a/tests/auto/network/CMakeLists.txt b/tests/auto/network/CMakeLists.txt
index c8bb0cf799..9b15208f71 100644
--- a/tests/auto/network/CMakeLists.txt
+++ b/tests/auto/network/CMakeLists.txt
@@ -1,5 +1,6 @@
-# Generated from network.pro.
-# special case begin
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
+
# SSL library include path is not propagated with private tests which results in
# test not being able to find the ssl header when they are not in the standard
# include paths
@@ -12,9 +13,8 @@ if (QT_FEATURE_private_tests)
include_directories($<TARGET_PROPERTY:WrapOpenSSLHeaders::WrapOpenSSLHeaders,INTERFACE_INCLUDE_DIRECTORIES>)
endif()
endif()
-# special case end
-# add_subdirectory(selftest) # special case not ported
+# add_subdirectory(selftest) # TODO: not ported
add_subdirectory(access)
add_subdirectory(kernel)
add_subdirectory(ssl)
diff --git a/tests/auto/network/access/CMakeLists.txt b/tests/auto/network/access/CMakeLists.txt
index d225eb1299..44b7d5c1bb 100644
--- a/tests/auto/network/access/CMakeLists.txt
+++ b/tests/auto/network/access/CMakeLists.txt
@@ -1,14 +1,20 @@
-# Generated from access.pro.
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
+add_subdirectory(qhttpheaders)
add_subdirectory(qnetworkdiskcache)
add_subdirectory(qnetworkcookiejar)
add_subdirectory(qnetworkaccessmanager)
add_subdirectory(qnetworkcookie)
add_subdirectory(qnetworkrequest)
+add_subdirectory(qnetworkrequestfactory)
add_subdirectory(qnetworkreply)
add_subdirectory(qnetworkcachemetadata)
add_subdirectory(qabstractnetworkcache)
+add_subdirectory(qrestaccessmanager)
if(QT_FEATURE_private_tests)
+ add_subdirectory(qhttp2connection)
+ add_subdirectory(qhttpheaderparser)
add_subdirectory(qhttpnetworkconnection)
add_subdirectory(qhttpnetworkreply)
add_subdirectory(hpack)
diff --git a/tests/auto/network/access/hpack/CMakeLists.txt b/tests/auto/network/access/hpack/CMakeLists.txt
index 421a60c17d..32cd4b2f06 100644
--- a/tests/auto/network/access/hpack/CMakeLists.txt
+++ b/tests/auto/network/access/hpack/CMakeLists.txt
@@ -1,17 +1,21 @@
-# Generated from hpack.pro.
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
#####################################################################
## tst_hpack Test:
#####################################################################
+if(NOT QT_BUILD_STANDALONE_TESTS AND NOT QT_BUILDING_QT)
+ cmake_minimum_required(VERSION 3.16)
+ project(tst_hpack LANGUAGES CXX)
+ find_package(Qt6BuildInternals REQUIRED COMPONENTS STANDALONE_TEST)
+endif()
+
qt_internal_add_test(tst_hpack
SOURCES
tst_hpack.cpp
- PUBLIC_LIBRARIES
+ LIBRARIES
Qt::CorePrivate
Qt::Network
Qt::NetworkPrivate
)
-
-#### Keys ignored in scope 1:.:.:hpack.pro:<TRUE>:
-# TEMPLATE = "app"
diff --git a/tests/auto/network/access/hpack/tst_hpack.cpp b/tests/auto/network/access/hpack/tst_hpack.cpp
index ee66ba73ca..e6b43eaed4 100644
--- a/tests/auto/network/access/hpack/tst_hpack.cpp
+++ b/tests/auto/network/access/hpack/tst_hpack.cpp
@@ -1,31 +1,6 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Copyright (C) 2014 Governikus GmbH & Co. KG.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// Copyright (C) 2014 Governikus GmbH & Co. KG.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
#include <QTest>
#include <QRandomGenerator>
diff --git a/tests/auto/network/access/hsts/CMakeLists.txt b/tests/auto/network/access/hsts/CMakeLists.txt
index ba3b110f59..821a034940 100644
--- a/tests/auto/network/access/hsts/CMakeLists.txt
+++ b/tests/auto/network/access/hsts/CMakeLists.txt
@@ -1,17 +1,23 @@
-# Generated from hsts.pro.
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
#####################################################################
## tst_qhsts Test:
#####################################################################
+if(NOT QT_BUILD_STANDALONE_TESTS AND NOT QT_BUILDING_QT)
+ cmake_minimum_required(VERSION 3.16)
+ project(tst_qhsts LANGUAGES CXX)
+ find_package(Qt6BuildInternals REQUIRED COMPONENTS STANDALONE_TEST)
+endif()
+
qt_internal_add_test(tst_qhsts
SOURCES
tst_qhsts.cpp
- PUBLIC_LIBRARIES
+ LIBRARIES
Qt::CorePrivate
Qt::Network
Qt::NetworkPrivate
)
-#### Keys ignored in scope 1:.:.:hsts.pro:<TRUE>:
# TEMPLATE = "app"
diff --git a/tests/auto/network/access/hsts/tst_qhsts.cpp b/tests/auto/network/access/hsts/tst_qhsts.cpp
index f59d04e9e2..4e9a5cc53f 100644
--- a/tests/auto/network/access/hsts/tst_qhsts.cpp
+++ b/tests/auto/network/access/hsts/tst_qhsts.cpp
@@ -1,30 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
#include <QTest>
@@ -34,6 +9,7 @@
#include <QtCore/qpair.h>
#include <QtCore/qurl.h>
+#include <QtNetwork/qhttpheaders.h>
#include <QtNetwork/private/qhstsstore_p.h>
#include <QtNetwork/private/qhsts_p.h>
@@ -214,104 +190,108 @@ void tst_QHsts::testPolicyExpiration()
void tst_QHsts::testSTSHeaderParser()
{
QHstsHeaderParser parser;
- using Header = QPair<QByteArray, QByteArray>;
- using Headers = QList<Header>;
QVERIFY(!parser.includeSubDomains());
QVERIFY(!parser.expirationDate().isValid());
- Headers list;
- QVERIFY(!parser.parse(list));
+ QHttpHeaders headers;
+ QVERIFY(!parser.parse(headers));
QVERIFY(!parser.includeSubDomains());
QVERIFY(!parser.expirationDate().isValid());
- list << Header("Strict-Transport-security", "200");
- QVERIFY(!parser.parse(list));
+ headers.append("Strict-Transport-security", "200");
+ QVERIFY(!parser.parse(headers));
QVERIFY(!parser.includeSubDomains());
QVERIFY(!parser.expirationDate().isValid());
// This header is missing REQUIRED max-age directive, so we'll ignore it:
- list << Header("Strict-Transport-Security", "includeSubDomains");
- QVERIFY(!parser.parse(list));
+ headers.append("Strict-Transport-Security", "includeSubDomains");
+ QVERIFY(!parser.parse(headers));
QVERIFY(!parser.includeSubDomains());
QVERIFY(!parser.expirationDate().isValid());
- list.pop_back();
- list << Header("Strict-Transport-Security", "includeSubDomains;max-age=1000");
- QVERIFY(parser.parse(list));
+ headers.removeAt(headers.size() - 1);
+ headers.append("Strict-Transport-Security", "includeSubDomains;max-age=1000");
+ QVERIFY(parser.parse(headers));
QVERIFY(parser.expirationDate() > QDateTime::currentDateTimeUtc());
QVERIFY(parser.includeSubDomains());
- list.pop_back();
+ headers.removeAt(headers.size() - 1);
+ headers.append("strict-transport-security", "includeSubDomains;max-age=1000");
+ QVERIFY(parser.parse(headers));
+ QVERIFY(parser.expirationDate() > QDateTime::currentDateTimeUtc());
+ QVERIFY(parser.includeSubDomains());
+
+ headers.removeAt(headers.size() - 1);
// Invalid (includeSubDomains twice):
- list << Header("Strict-Transport-Security", "max-age = 1000 ; includeSubDomains;includeSubDomains");
- QVERIFY(!parser.parse(list));
+ headers.append("Strict-Transport-Security", "max-age = 1000 ; includeSubDomains;includeSubDomains");
+ QVERIFY(!parser.parse(headers));
QVERIFY(!parser.includeSubDomains());
QVERIFY(!parser.expirationDate().isValid());
- list.pop_back();
+ headers.removeAt(headers.size() - 1);
// Invalid (weird number of seconds):
- list << Header("Strict-Transport-Security", "max-age=-1000 ; includeSubDomains");
- QVERIFY(!parser.parse(list));
+ headers.append("Strict-Transport-Security", "max-age=-1000 ; includeSubDomains");
+ QVERIFY(!parser.parse(headers));
QVERIFY(!parser.includeSubDomains());
QVERIFY(!parser.expirationDate().isValid());
- list.pop_back();
+ headers.removeAt(headers.size() - 1);
// Note, directives are case-insensitive + we should ignore unknown directive.
- list << Header("Strict-Transport-Security", ";max-age=1000 ;includesubdomains;;"
+ headers.append("Strict-Transport-Security", ";max-age=1000 ;includesubdomains;;"
"nowsomeunknownheader=\"somevaluewithescapes\\;\"");
- QVERIFY(parser.parse(list));
+ QVERIFY(parser.parse(headers));
QVERIFY(parser.includeSubDomains());
QVERIFY(parser.expirationDate().isValid());
- list.pop_back();
+ headers.removeAt(headers.size() - 1);
// Check that we know how to unescape max-age:
- list << Header("Strict-Transport-Security", "max-age=\"1000\"");
- QVERIFY(parser.parse(list));
+ headers.append("Strict-Transport-Security", "max-age=\"1000\"");
+ QVERIFY(parser.parse(headers));
QVERIFY(!parser.includeSubDomains());
QVERIFY(parser.expirationDate().isValid());
- list.pop_back();
+ headers.removeAt(headers.size() - 1);
// The only STS header, with invalid syntax though, to be ignored:
- list << Header("Strict-Transport-Security", "max-age; max-age=15768000");
- QVERIFY(!parser.parse(list));
+ headers.append("Strict-Transport-Security", "max-age; max-age=15768000");
+ QVERIFY(!parser.parse(headers));
QVERIFY(!parser.includeSubDomains());
QVERIFY(!parser.expirationDate().isValid());
// Now we check that our parse chosses the first valid STS header and ignores
// others:
- list.clear();
- list << Header("Strict-Transport-Security", "includeSubdomains; max-age=\"hehehe\";");
- list << Header("Strict-Transport-Security", "max-age=10101");
- QVERIFY(parser.parse(list));
+ headers.clear();
+ headers.append("Strict-Transport-Security", "includeSubdomains; max-age=\"hehehe\";");
+ headers.append("Strict-Transport-Security", "max-age=10101");
+ QVERIFY(parser.parse(headers));
QVERIFY(!parser.includeSubDomains());
QVERIFY(parser.expirationDate().isValid());
- list.clear();
- list << Header("Strict-Transport-Security", "max-age=0");
- QVERIFY(parser.parse(list));
+ headers.clear();
+ headers.append("Strict-Transport-Security", "max-age=0");
+ QVERIFY(parser.parse(headers));
QVERIFY(!parser.includeSubDomains());
QVERIFY(parser.expirationDate() <= QDateTime::currentDateTimeUtc());
// Parsing is case-insensitive:
- list.pop_back();
- list << Header("Strict-Transport-Security", "Max-aGE=1000; InclUdesUbdomains");
- QVERIFY(parser.parse(list));
+ headers.removeAt(headers.size() - 1);
+ headers.append("Strict-Transport-Security", "Max-aGE=1000; InclUdesUbdomains");
+ QVERIFY(parser.parse(headers));
QVERIFY(parser.includeSubDomains());
QVERIFY(parser.expirationDate().isValid());
// Grammar of STS header is quite permissive, let's check we can parse
// some weird but valid header:
- list.pop_back();
- list << Header("Strict-Transport-Security", ";;; max-age = 17; ; ; ; ;;; ;;"
+ headers.removeAt(headers.size() - 1);
+ headers.append("Strict-Transport-Security", ";;; max-age = 17; ; ; ; ;;; ;;"
";;; ; includeSubdomains ;;thisIsUnknownDirective;;;;");
- QVERIFY(parser.parse(list));
+ QVERIFY(parser.parse(headers));
QVERIFY(parser.includeSubDomains());
QVERIFY(parser.expirationDate().isValid());
- list.pop_back();
- list << Header("Strict-Transport-Security", "max-age=1000; includeSubDomains bogon");
- QVERIFY(!parser.parse(list));
+ headers.removeAt(headers.size() - 1);
+ headers.append("Strict-Transport-Security", "max-age=1000; includeSubDomains bogon");
+ QVERIFY(!parser.parse(headers));
QVERIFY(!parser.includeSubDomains());
QVERIFY(!parser.expirationDate().isValid());
}
diff --git a/tests/auto/network/access/http2/BLACKLIST b/tests/auto/network/access/http2/BLACKLIST
new file mode 100644
index 0000000000..3de8d6d448
--- /dev/null
+++ b/tests/auto/network/access/http2/BLACKLIST
@@ -0,0 +1,2 @@
+[duplicateRequestsWithAborts]
+qnx ci # QTBUG-119616
diff --git a/tests/auto/network/access/http2/CMakeLists.txt b/tests/auto/network/access/http2/CMakeLists.txt
index 5adee76cbb..7ea559940b 100644
--- a/tests/auto/network/access/http2/CMakeLists.txt
+++ b/tests/auto/network/access/http2/CMakeLists.txt
@@ -1,16 +1,24 @@
-# Generated from http2.pro.
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
#####################################################################
## tst_http2 Test:
#####################################################################
+if(NOT QT_BUILD_STANDALONE_TESTS AND NOT QT_BUILDING_QT)
+ cmake_minimum_required(VERSION 3.16)
+ project(tst_http2 LANGUAGES CXX)
+ find_package(Qt6BuildInternals REQUIRED COMPONENTS STANDALONE_TEST)
+endif()
+
qt_internal_add_test(tst_http2
SOURCES
http2srv.cpp http2srv.h
tst_http2.cpp
- PUBLIC_LIBRARIES
+ LIBRARIES
Qt::CorePrivate
Qt::Network
Qt::NetworkPrivate
Qt::TestPrivate
+ BUNDLE_ANDROID_OPENSSL_LIBS
)
diff --git a/tests/auto/network/access/http2/http2srv.cpp b/tests/auto/network/access/http2/http2srv.cpp
index 8a4917049e..b52ea5527b 100644
--- a/tests/auto/network/access/http2/http2srv.cpp
+++ b/tests/auto/network/access/http2/http2srv.cpp
@@ -1,30 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
#include <QTest>
@@ -109,6 +84,12 @@ Http2Server::~Http2Server()
{
}
+void Http2Server::setInformationalStatusCode(int code)
+{
+ if (code == 100 || (102 <= code && code <= 199))
+ informationalStatusCode = code;
+}
+
void Http2Server::enablePushPromise(bool pushEnabled, const QByteArray &path)
{
pushPromiseEnabled = pushEnabled;
@@ -130,6 +111,23 @@ void Http2Server::setAuthenticationHeader(const QByteArray &authentication)
authenticationHeader = authentication;
}
+void Http2Server::setAuthenticationRequired(bool enable)
+{
+ Q_ASSERT(!enable || authenticationHeader.isEmpty());
+ authenticationRequired = enable;
+}
+
+void Http2Server::setRedirect(const QByteArray &url, int count)
+{
+ redirectUrl = url;
+ redirectCount = count;
+}
+
+void Http2Server::setSendTrailingHEADERS(bool enable)
+{
+ sendTrailingHEADERS = enable;
+}
+
void Http2Server::emulateGOAWAY(int timeout)
{
Q_ASSERT(timeout >= 0);
@@ -267,9 +265,20 @@ void Http2Server::sendDATA(quint32 streamID, quint32 windowSize)
return;
if (last) {
- writer.start(FrameType::DATA, FrameFlag::END_STREAM, streamID);
- writer.setPayloadSize(0);
- writer.write(*socket);
+ if (sendTrailingHEADERS) {
+ writer.start(FrameType::HEADERS,
+ FrameFlag::PRIORITY | FrameFlag::END_HEADERS | FrameFlag::END_STREAM, streamID);
+ const quint32 maxFrameSize(clientSetting(Settings::MAX_FRAME_SIZE_ID,
+ Http2::maxPayloadSize));
+ // 5 bytes for PRIORITY data:
+ writer.append(quint32(0)); // streamID 0 (32-bit)
+ writer.append(quint8(0)); // + weight 0 (8-bit)
+ writer.writeHEADERS(*socket, maxFrameSize);
+ } else {
+ writer.start(FrameType::DATA, FrameFlag::END_STREAM, streamID);
+ writer.setPayloadSize(0);
+ writer.write(*socket);
+ }
suspendedStreams.erase(it);
activeRequests.erase(streamID);
@@ -319,7 +328,8 @@ void Http2Server::incomingConnection(qintptr socketDescriptor)
connect(sslSocket, SIGNAL(sslErrors(QList<QSslError>)),
this, SLOT(ignoreErrorSlot()));
QFile file(QT_TESTCASE_SOURCEDIR "/certs/fluke.key");
- file.open(QIODevice::ReadOnly);
+ if (!file.open(QIODevice::ReadOnly))
+ qFatal("Cannot open certificate file %s", qPrintable(file.fileName()));
QSslKey key(file.readAll(), QSsl::Rsa, QSsl::Pem, QSsl::PrivateKey);
sslSocket->setPrivateKey(key);
auto localCert = QSslCertificate::fromPath(QT_TESTCASE_SOURCEDIR "/certs/fluke.cert");
@@ -380,16 +390,12 @@ bool Http2Server::verifyProtocolUpgradeRequest()
bool settingsOk = false;
QHttpNetworkReplyPrivate *firstRequestReader = protocolUpgradeHandler->d_func();
+ const auto headers = firstRequestReader->headers();
// That's how we append them, that's what I expect to find:
- for (const auto &header : firstRequestReader->headers()) {
- if (header.first == "Connection")
- connectionOk = header.second.contains("Upgrade, HTTP2-Settings");
- else if (header.first == "Upgrade")
- upgradeOk = header.second.contains("h2c");
- else if (header.first == "HTTP2-Settings")
- settingsOk = true;
- }
+ connectionOk = headers.combinedValue(QHttpHeaders::WellKnownHeader::Connection).contains("Upgrade, HTTP2-Settings");
+ upgradeOk = headers.combinedValue(QHttpHeaders::WellKnownHeader::Upgrade).contains("h2c");
+ settingsOk = headers.contains("HTTP2-Settings");
return connectionOk && upgradeOk && settingsOk;
}
@@ -838,6 +844,25 @@ void Http2Server::sendResponse(quint32 streamID, bool emptyBody)
// Now we'll continue with _normal_ response.
}
+ // Create a header with an informational status code and some random header
+ // fields. The setter ensures that the value is 100 or is between 102 and 199
+ // (inclusive) if set - otherwise it is 0
+
+ if (informationalStatusCode > 0) {
+ writer.start(FrameType::HEADERS, FrameFlag::END_HEADERS, streamID);
+
+ HttpHeader informationalHeader;
+ informationalHeader.push_back({":status", QByteArray::number(informationalStatusCode)});
+ informationalHeader.push_back(HeaderField("a_random_header_field", "it_will_be_dropped"));
+ informationalHeader.push_back(HeaderField("another_random_header_field", "drop_this_too"));
+
+ HPack::BitOStream ostream(writer.outboundFrame().buffer);
+ const bool result = encoder.encodeResponse(ostream, informationalHeader);
+ Q_ASSERT(result);
+
+ writer.writeHEADERS(*socket, maxFrameSize);
+ }
+
writer.start(FrameType::HEADERS, FrameFlag::END_HEADERS, streamID);
if (emptyBody)
writer.addFlag(FrameFlag::END_STREAM);
@@ -860,11 +885,15 @@ void Http2Server::sendResponse(quint32 streamID, bool emptyBody)
const QString url("%1://localhost:%2/");
header.push_back({"location", url.arg(isClearText() ? QStringLiteral("http") : QStringLiteral("https"),
QString::number(targetPort)).toLatin1()});
-
+ } else if (redirectCount > 0) { // Not redirecting while reading, unlike above
+ --redirectCount;
+ header.push_back({":status", "308"});
+ header.push_back({"location", redirectUrl});
} else if (!authenticationHeader.isEmpty() && !hasAuth) {
header.push_back({ ":status", "401" });
header.push_back(HPack::HeaderField("www-authenticate", authenticationHeader));
- authenticationHeader.clear();
+ } else if (authenticationRequired) {
+ header.push_back({ ":status", "401" });
} else {
header.push_back({":status", "200"});
}
diff --git a/tests/auto/network/access/http2/http2srv.h b/tests/auto/network/access/http2/http2srv.h
index 671cacbd54..dc94318527 100644
--- a/tests/auto/network/access/http2/http2srv.h
+++ b/tests/auto/network/access/http2/http2srv.h
@@ -1,30 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
#ifndef HTTP2SRV_H
#define HTTP2SRV_H
@@ -83,6 +58,8 @@ public:
~Http2Server();
+ // To send responses with status code 1xx
+ void setInformationalStatusCode(int code);
// To be called before server started:
void enablePushPromise(bool enabled, const QByteArray &path = QByteArray());
void setResponseBody(const QByteArray &body);
@@ -90,6 +67,13 @@ public:
void setContentEncoding(const QByteArray &contentEncoding);
// No authentication data is generated for the method, the full header value must be set
void setAuthenticationHeader(const QByteArray &authentication);
+ // Authentication always required, no challenge provided
+ void setAuthenticationRequired(bool enable);
+ // Set the redirect URL and count. The server will return a redirect response with the url
+ // 'count' amount of times
+ void setRedirect(const QByteArray &redirectUrl, int count);
+ // Send a trailing HEADERS frame with PRIORITY and END_STREAM flag
+ void setSendTrailingHEADERS(bool enable);
void emulateGOAWAY(int timeout);
void redirectOpenStream(quint16 targetPort);
@@ -222,6 +206,13 @@ private:
QByteArray contentEncoding;
QByteArray authenticationHeader;
+ bool authenticationRequired = false;
+
+ QByteArray redirectUrl;
+ int redirectCount = 0;
+
+ bool sendTrailingHEADERS = false;
+ int informationalStatusCode = 0;
protected slots:
void ignoreErrorSlot();
};
diff --git a/tests/auto/network/access/http2/tst_http2.cpp b/tests/auto/network/access/http2/tst_http2.cpp
index 4a6e34eb7b..d9e82330b2 100644
--- a/tests/auto/network/access/http2/tst_http2.cpp
+++ b/tests/auto/network/access/http2/tst_http2.cpp
@@ -1,30 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
#include <QtNetwork/qtnetworkglobal.h>
@@ -50,6 +25,7 @@
#include <QtCore/qobject.h>
#include <QtCore/qthread.h>
#include <QtCore/qurl.h>
+#include <QtCore/qset.h>
#include <cstdlib>
#include <memory>
@@ -62,6 +38,8 @@ Q_DECLARE_METATYPE(QNetworkRequest::Attribute)
QT_BEGIN_NAMESPACE
+using namespace Qt::StringLiterals;
+
QHttp2Configuration qt_defaultH2Configuration()
{
QHttp2Configuration config;
@@ -92,8 +70,11 @@ public slots:
void init();
private slots:
// Tests:
+ void defaultQnamHttp2Configuration();
void singleRequest_data();
void singleRequest();
+ void informationalRequest_data();
+ void informationalRequest();
void multipleRequests();
void flowControlClientSide();
void flowControlServerSide();
@@ -115,6 +96,18 @@ private slots:
void authenticationRequired_data();
void authenticationRequired();
+ void unsupportedAuthenticateChallenge();
+
+ void h2cAllowedAttribute_data();
+ void h2cAllowedAttribute();
+
+ void redirect_data();
+ void redirect();
+
+ void trailingHEADERS();
+
+ void duplicateRequestsWithAborts();
+
protected slots:
// Slots to listen to our in-process server:
void serverStarted(quint16 port);
@@ -223,7 +216,12 @@ tst_Http2::~tst_Http2()
void tst_Http2::init()
{
manager.reset(new QNetworkAccessManager);
- qputenv("QT_NETWORK_H2C_ALLOWED", "1");
+}
+
+void tst_Http2::defaultQnamHttp2Configuration()
+{
+ // The configuration we also implicitly use in QNAM.
+ QCOMPARE(qt_defaultH2Configuration(), QNetworkRequest().http2Configuration());
}
void tst_Http2::singleRequest_data()
@@ -256,7 +254,7 @@ void tst_Http2::singleRequest()
// we have to use TLS sockets (== private key) and thus suppress a
// keychain UI asking for permission to use a private key.
// Our CI has this, but somebody testing locally - will have a problem.
- qputenv("QT_SSL_USE_TEMPORARY_KEYCHAIN", QByteArray("1"));
+ qputenv("QT_SSL_USE_TEMPORARY_KEYCHAIN", "1");
auto envRollback = qScopeGuard([](){
qunsetenv("QT_SSL_USE_TEMPORARY_KEYCHAIN");
});
@@ -277,6 +275,7 @@ void tst_Http2::singleRequest()
url.setPath("/index.html");
QNetworkRequest request(url);
+ request.setAttribute(QNetworkRequest::Http2CleartextAllowedAttribute, true);
QFETCH(const QNetworkRequest::Attribute, h2Attribute);
request.setAttribute(h2Attribute, QVariant(true));
@@ -293,7 +292,7 @@ void tst_Http2::singleRequest()
runEventLoop();
STOP_ON_FAILURE
- QVERIFY(nRequests == 0);
+ QCOMPARE(nRequests, 0);
QVERIFY(prefaceOK);
QVERIFY(serverGotSettingsACK);
@@ -302,10 +301,74 @@ void tst_Http2::singleRequest()
#if QT_CONFIG(ssl)
if (connectionType == H2Type::h2Alpn || connectionType == H2Type::h2Direct)
- QCOMPARE(encSpy.count(), 1);
+ QCOMPARE(encSpy.size(), 1);
#endif // QT_CONFIG(ssl)
}
+void tst_Http2::informationalRequest_data()
+{
+ QTest::addColumn<int>("statusCode");
+
+ // 'Clear text' that should always work, either via the protocol upgrade
+ // or as direct.
+ QTest::addRow("statusCode-100") << 100;
+ QTest::addRow("statusCode-125") << 125;
+ QTest::addRow("statusCode-150") << 150;
+ QTest::addRow("statusCode-175") << 175;
+}
+
+void tst_Http2::informationalRequest()
+{
+ clearHTTP2State();
+
+ serverPort = 0;
+ nRequests = 1;
+
+ ServerPtr srv(newServer(defaultServerSettings, defaultConnectionType()));
+
+ QFETCH(const int, statusCode);
+ srv->setInformationalStatusCode(statusCode);
+
+ QMetaObject::invokeMethod(srv.data(), "startServer", Qt::QueuedConnection);
+ runEventLoop();
+
+ QVERIFY(serverPort != 0);
+
+ auto url = requestUrl(defaultConnectionType());
+ url.setPath("/index.html");
+
+ QNetworkRequest request(url);
+ request.setAttribute(QNetworkRequest::Http2CleartextAllowedAttribute, true);
+
+ auto reply = manager->get(request);
+
+ connect(reply, &QNetworkReply::finished, this, &tst_Http2::replyFinished);
+ // Since we're using self-signed certificates,
+ // ignore SSL errors:
+ reply->ignoreSslErrors();
+
+ runEventLoop();
+ STOP_ON_FAILURE
+
+ QCOMPARE(nRequests, 0);
+ QVERIFY(prefaceOK);
+ QVERIFY(serverGotSettingsACK);
+
+ QCOMPARE(reply->error(), QNetworkReply::NoError);
+ QVERIFY(reply->isFinished());
+
+ const QVariant code(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute));
+
+ // We are discarding informational headers if the status code is in the range of
+ // 102-199 or if it is 100. As these header fields were part of the informational
+ // header used for this test case, we should not see them at this point and the
+ // status code should be 200.
+
+ QCOMPARE(code.value<int>(), 200);
+ QVERIFY(!reply->hasRawHeader("a_random_header_field"));
+ QVERIFY(!reply->hasRawHeader("another_random_header_field"));
+}
+
void tst_Http2::multipleRequests()
{
clearHTTP2State();
@@ -334,7 +397,7 @@ void tst_Http2::multipleRequests()
runEventLoop();
STOP_ON_FAILURE
- QVERIFY(nRequests == 0);
+ QCOMPARE(nRequests, 0);
QVERIFY(prefaceOK);
QVERIFY(serverGotSettingsACK);
}
@@ -379,7 +442,7 @@ void tst_Http2::flowControlClientSide()
runEventLoop(120000);
STOP_ON_FAILURE
- QVERIFY(nRequests == 0);
+ QCOMPARE(nRequests, 0);
QVERIFY(prefaceOK);
QVERIFY(serverGotSettingsACK);
QVERIFY(windowUpdates > 0);
@@ -420,7 +483,7 @@ void tst_Http2::flowControlServerSide()
runEventLoop(120000);
STOP_ON_FAILURE
- QVERIFY(nRequests == 0);
+ QCOMPARE(nRequests, 0);
QVERIFY(prefaceOK);
QVERIFY(serverGotSettingsACK);
}
@@ -452,6 +515,7 @@ void tst_Http2::pushPromise()
url.setPath("/index.html");
QNetworkRequest request(url);
+ request.setAttribute(QNetworkRequest::Http2CleartextAllowedAttribute, true);
request.setAttribute(QNetworkRequest::Http2AllowedAttribute, QVariant(true));
request.setHttp2Configuration(params);
@@ -463,7 +527,7 @@ void tst_Http2::pushPromise()
runEventLoop();
STOP_ON_FAILURE
- QVERIFY(nRequests == 0);
+ QCOMPARE(nRequests, 0);
QVERIFY(prefaceOK);
QVERIFY(serverGotSettingsACK);
@@ -478,6 +542,7 @@ void tst_Http2::pushPromise()
url.setPath("/script.js");
QNetworkRequest promisedRequest(url);
+ request.setAttribute(QNetworkRequest::Http2CleartextAllowedAttribute, true);
promisedRequest.setAttribute(QNetworkRequest::Http2AllowedAttribute, QVariant(true));
reply = manager->get(promisedRequest);
connect(reply, &QNetworkReply::finished, this, &tst_Http2::replyFinished);
@@ -532,6 +597,7 @@ void tst_Http2::goaway()
for (int i = 0; i < nRequests; ++i) {
url.setPath(QString("/%1").arg(i));
QNetworkRequest request(url);
+ request.setAttribute(QNetworkRequest::Http2CleartextAllowedAttribute, true);
request.setAttribute(QNetworkRequest::Http2AllowedAttribute, QVariant(true));
replies[i] = manager->get(request);
QCOMPARE(replies[i]->error(), QNetworkReply::NoError);
@@ -587,7 +653,7 @@ void tst_Http2::earlyResponse()
runEventLoop();
STOP_ON_FAILURE
- QVERIFY(nRequests == 0);
+ QCOMPARE(nRequests, 0);
QVERIFY(prefaceOK);
QVERIFY(serverGotSettingsACK);
}
@@ -644,7 +710,7 @@ void tst_Http2::connectToHost()
// we have to use TLS sockets (== private key) and thus suppress a
// keychain UI asking for permission to use a private key.
// Our CI has this, but somebody testing locally - will have a problem.
- qputenv("QT_SSL_USE_TEMPORARY_KEYCHAIN", QByteArray("1"));
+ qputenv("QT_SSL_USE_TEMPORARY_KEYCHAIN", "1");
auto envRollback = qScopeGuard([](){
qunsetenv("QT_SSL_USE_TEMPORARY_KEYCHAIN");
});
@@ -673,6 +739,7 @@ void tst_Http2::connectToHost()
auto copyUrl = url;
copyUrl.setScheme(QLatin1String("preconnect-https"));
QNetworkRequest request(copyUrl);
+ request.setAttribute(QNetworkRequest::Http2CleartextAllowedAttribute, true);
request.setAttribute(requestAttribute, true);
reply = manager->get(request);
// Since we're using self-signed certificates, ignore SSL errors:
@@ -685,6 +752,7 @@ void tst_Http2::connectToHost()
auto copyUrl = url;
copyUrl.setScheme(QLatin1String("preconnect-http"));
QNetworkRequest request(copyUrl);
+ request.setAttribute(QNetworkRequest::Http2CleartextAllowedAttribute, true);
request.setAttribute(requestAttribute, true);
reply = manager->get(request);
}
@@ -705,6 +773,7 @@ void tst_Http2::connectToHost()
QCOMPARE(nRequests, 1);
QNetworkRequest request(url);
+ request.setAttribute(QNetworkRequest::Http2CleartextAllowedAttribute, true);
request.setAttribute(requestAttribute, QVariant(true));
reply = manager->get(request);
connect(reply, &QNetworkReply::finished, this, &tst_Http2::replyFinished);
@@ -715,7 +784,7 @@ void tst_Http2::connectToHost()
runEventLoop();
STOP_ON_FAILURE
- QVERIFY(nRequests == 0);
+ QCOMPARE(nRequests, 0);
QVERIFY(prefaceOK);
QVERIFY(serverGotSettingsACK);
@@ -739,7 +808,7 @@ void tst_Http2::maxFrameSize()
// we have to use TLS sockets (== private key) and thus suppress a
// keychain UI asking for permission to use a private key.
// Our CI has this, but somebody testing locally - will have a problem.
- qputenv("QT_SSL_USE_TEMPORARY_KEYCHAIN", QByteArray("1"));
+ qputenv("QT_SSL_USE_TEMPORARY_KEYCHAIN", "1");
auto envRollback = qScopeGuard([](){
qunsetenv("QT_SSL_USE_TEMPORARY_KEYCHAIN");
});
@@ -770,6 +839,7 @@ void tst_Http2::maxFrameSize()
url.setPath(QString("/stream1.html"));
QNetworkRequest request(url);
+ request.setAttribute(QNetworkRequest::Http2CleartextAllowedAttribute, true);
request.setAttribute(attribute, QVariant(true));
request.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("text/plain"));
request.setHttp2Configuration(h2Config);
@@ -783,9 +853,9 @@ void tst_Http2::maxFrameSize()
// Normally, with a 16kb limit, our server would split such
// a response into 3 'DATA' frames (16kb + 16kb + 0|END_STREAM).
- QCOMPARE(frameCounter.count(), 1);
+ QCOMPARE(frameCounter.size(), 1);
- QVERIFY(nRequests == 0);
+ QCOMPARE(nRequests, 0);
QVERIFY(prefaceOK);
QVERIFY(serverGotSettingsACK);
}
@@ -903,7 +973,7 @@ void tst_Http2::moreActivitySignals()
// we have to use TLS sockets (== private key) and thus suppress a
// keychain UI asking for permission to use a private key.
// Our CI has this, but somebody testing locally - will have a problem.
- qputenv("QT_SSL_USE_TEMPORARY_KEYCHAIN", QByteArray("1"));
+ qputenv("QT_SSL_USE_TEMPORARY_KEYCHAIN", "1");
auto envRollback = qScopeGuard([]() { qunsetenv("QT_SSL_USE_TEMPORARY_KEYCHAIN"); });
#endif
@@ -916,13 +986,14 @@ void tst_Http2::moreActivitySignals()
auto url = requestUrl(connectionType);
url.setPath(QString("/stream1.html"));
QNetworkRequest request(url);
+ request.setAttribute(QNetworkRequest::Http2CleartextAllowedAttribute, true);
QFETCH(const QNetworkRequest::Attribute, h2Attribute);
request.setAttribute(h2Attribute, QVariant(true));
request.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("text/plain"));
QSharedPointer<QNetworkReply> reply(manager->get(request));
nRequests = 1;
connect(reply.data(), &QNetworkReply::finished, this, &tst_Http2::replyFinished);
- QSignalSpy spy1(reply.data(), SIGNAL(socketConnecting()));
+ QSignalSpy spy1(reply.data(), SIGNAL(socketStartedConnecting()));
QSignalSpy spy2(reply.data(), SIGNAL(requestSent()));
QSignalSpy spy3(reply.data(), SIGNAL(metaDataChanged()));
// Since we're using self-signed certificates,
@@ -936,7 +1007,7 @@ void tst_Http2::moreActivitySignals()
runEventLoop();
STOP_ON_FAILURE
- QVERIFY(nRequests == 0);
+ QCOMPARE(nRequests, 0);
QVERIFY(prefaceOK);
QVERIFY(serverGotSettingsACK);
@@ -1013,7 +1084,7 @@ void tst_Http2::contentEncoding()
// we have to use TLS sockets (== private key) and thus suppress a
// keychain UI asking for permission to use a private key.
// Our CI has this, but somebody testing locally - will have a problem.
- qputenv("QT_SSL_USE_TEMPORARY_KEYCHAIN", QByteArray("1"));
+ qputenv("QT_SSL_USE_TEMPORARY_KEYCHAIN", "1");
auto envRollback = qScopeGuard([]() { qunsetenv("QT_SSL_USE_TEMPORARY_KEYCHAIN"); });
#endif
@@ -1036,6 +1107,7 @@ void tst_Http2::contentEncoding()
url.setPath("/index.html");
QNetworkRequest request(url);
+ request.setAttribute(QNetworkRequest::Http2CleartextAllowedAttribute, true);
QFETCH(const QNetworkRequest::Attribute, h2Attribute);
request.setAttribute(h2Attribute, QVariant(true));
@@ -1048,7 +1120,7 @@ void tst_Http2::contentEncoding()
runEventLoop();
STOP_ON_FAILURE
- QVERIFY(nRequests == 0);
+ QCOMPARE(nRequests, 0);
QVERIFY(prefaceOK);
QVERIFY(serverGotSettingsACK);
@@ -1061,13 +1133,18 @@ void tst_Http2::authenticationRequired_data()
{
QTest::addColumn<bool>("success");
QTest::addColumn<bool>("responseHEADOnly");
+ QTest::addColumn<bool>("withChallenge");
- QTest::addRow("failed-auth") << false << true;
- QTest::addRow("successful-auth") << true << true;
+ QTest::addRow("failed-auth") << false << true << true;
+ QTest::addRow("successful-auth") << true << true << true;
// Include a DATA frame in the response from the remote server. An example would be receiving a
// JSON response on a request along with the 401 error.
- QTest::addRow("failed-auth-with-response") << false << false;
- QTest::addRow("successful-auth-with-response") << true << false;
+ QTest::addRow("failed-auth-with-response") << false << false << true;
+ QTest::addRow("successful-auth-with-response") << true << false << true;
+
+ // Don't provide a challenge header. This is valid if you are actually just
+ // denied access for whatever reason.
+ QTest::addRow("no-challenge") << false << false << false;
}
void tst_Http2::authenticationRequired()
@@ -1078,10 +1155,15 @@ void tst_Http2::authenticationRequired()
POSTResponseHEADOnly = responseHEADOnly;
QFETCH(const bool, success);
+ QFETCH(const bool, withChallenge);
ServerPtr targetServer(newServer(defaultServerSettings, defaultConnectionType()));
- targetServer->setResponseBody("Hello");
- targetServer->setAuthenticationHeader("Basic realm=\"Shadow\"");
+ QByteArray responseBody = "Hello"_ba;
+ targetServer->setResponseBody(responseBody);
+ if (withChallenge)
+ targetServer->setAuthenticationHeader("Basic realm=\"Shadow\"");
+ else
+ targetServer->setAuthenticationRequired(true);
QMetaObject::invokeMethod(targetServer.data(), "startServer", Qt::QueuedConnection);
runEventLoop();
@@ -1093,6 +1175,7 @@ void tst_Http2::authenticationRequired()
auto url = requestUrl(defaultConnectionType());
url.setPath("/index.html");
QNetworkRequest request(url);
+ request.setAttribute(QNetworkRequest::Http2CleartextAllowedAttribute, true);
QByteArray expectedBody = "Hello, World!";
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
@@ -1116,24 +1199,30 @@ void tst_Http2::authenticationRequired()
receivedBody += body;
});
- if (success)
+ if (success) {
connect(reply.get(), &QNetworkReply::finished, this, &tst_Http2::replyFinished);
- else
- connect(reply.get(), &QNetworkReply::errorOccurred, this, &tst_Http2::replyFinishedWithError);
+ } else {
+ // Use queued connection so that the finished signal can be emitted and the isFinished
+ // property can be set.
+ connect(reply.get(), &QNetworkReply::errorOccurred, this,
+ &tst_Http2::replyFinishedWithError, Qt::QueuedConnection);
+ }
// Since we're using self-signed certificates,
// ignore SSL errors:
reply->ignoreSslErrors();
runEventLoop();
STOP_ON_FAILURE
+ QVERIFY2(reply->isFinished(),
+ "The reply should error out if authentication fails, or finish if it succeeds");
if (!success)
QCOMPARE(reply->error(), QNetworkReply::AuthenticationRequiredError);
// else: no error (is checked in tst_Http2::replyFinished)
- QVERIFY(authenticationRequested);
+ QVERIFY(authenticationRequested || !withChallenge);
- const auto isAuthenticated = [](QByteArray bv) {
+ const auto isAuthenticated = [](const QByteArray &bv) {
return bv == "Basic YWRtaW46YWRtaW4="; // admin:admin
};
// Get the "authorization" header out from the server and make sure it's as expected:
@@ -1141,10 +1230,319 @@ void tst_Http2::authenticationRequired()
QCOMPARE(isAuthenticated(reqAuthHeader), success);
if (success)
QCOMPARE(receivedBody, expectedBody);
+ if (responseHEADOnly) {
+ const QVariant contentLenHeader = reply->header(QNetworkRequest::ContentLengthHeader);
+ QVERIFY2(!contentLenHeader.isValid(), "We expect no DATA frames to be received");
+ QCOMPARE(reply->readAll(), QByteArray());
+ } else {
+ const qint32 contentLen = reply->header(QNetworkRequest::ContentLengthHeader).toInt();
+ QCOMPARE(contentLen, responseBody.length());
+ QCOMPARE(reply->bytesAvailable(), responseBody.length());
+ QCOMPARE(reply->readAll(), QByteArray("Hello"));
+ }
+ // In the `!success` case we need to wait for the server to emit this or it might cause issues
+ // in the next test running after this. In the `success` case we anyway expect it to have been
+ // received.
+ QTRY_VERIFY(serverGotSettingsACK);
+}
+
+void tst_Http2::unsupportedAuthenticateChallenge()
+{
+ clearHTTP2State();
+ serverPort = 0;
+
+ if (defaultConnectionType() == H2Type::h2c)
+ QSKIP("This test requires TLS with ALPN to work");
+
+ ServerPtr targetServer(newServer(defaultServerSettings, defaultConnectionType()));
+ QByteArray responseBody = "Hello"_ba;
+ targetServer->setResponseBody(responseBody);
+ targetServer->setAuthenticationHeader("Bearer realm=\"qt.io accounts\"");
+
+ QMetaObject::invokeMethod(targetServer.data(), "startServer", Qt::QueuedConnection);
+ runEventLoop();
+
+ QVERIFY(serverPort != 0);
+
+ nRequests = 1;
+
+ QUrl url = requestUrl(defaultConnectionType());
+ url.setPath("/index.html");
+ QNetworkRequest request(url);
+
+ QByteArray expectedBody = "Hello, World!";
+ request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
+ QScopedPointer<QNetworkReply> reply;
+ reply.reset(manager->post(request, expectedBody));
+
+ bool authenticationRequested = false;
+ connect(manager.get(), &QNetworkAccessManager::authenticationRequired, reply.get(),
+ [&](QNetworkReply *, QAuthenticator *auth) {
+ authenticationRequested = true;
+ });
+
+ bool finishedReceived = false;
+ connect(reply.get(), &QNetworkReply::finished, reply.get(),
+ [&]() { finishedReceived = true; });
+ bool errorReceived = false;
+ connect(reply.get(), &QNetworkReply::errorOccurred, reply.get(),
+ [&]() { errorReceived = true; });
+
+ QSet<quint32> receivedDataOnStreams;
+ connect(targetServer.get(), &Http2Server::receivedDATAFrame, reply.get(),
+ [&receivedDataOnStreams](quint32 streamID, const QByteArray &body) {
+ Q_UNUSED(body);
+ receivedDataOnStreams.insert(streamID);
+ });
+
+ // Use queued connection so that the finished signal can be emitted and the
+ // isFinished property can be set.
+ connect(reply.get(), &QNetworkReply::errorOccurred, this,
+ &tst_Http2::replyFinishedWithError, Qt::QueuedConnection);
+
+ // Since we're using self-signed certificates, ignore SSL errors:
+ reply->ignoreSslErrors();
+
+ runEventLoop();
+ STOP_ON_FAILURE
+ QVERIFY2(reply->isFinished(),
+ "The reply should error out if authentication fails, or finish if it succeeds");
+
+ QCOMPARE(reply->error(), QNetworkReply::AuthenticationRequiredError);
+ QVERIFY(reply->isFinished());
+ QVERIFY(errorReceived);
+ QVERIFY(finishedReceived);
+ QCOMPARE(receivedDataOnStreams.size(), 1);
+ QVERIFY(receivedDataOnStreams.contains(1)); // the original, failed, request
+
+ QVERIFY(!authenticationRequested);
+
+ // We should not have sent any authentication headers to the server, since
+ // we don't support the challenge.
+ const QByteArray reqAuthHeader = targetServer->requestAuthorizationHeader();
+ QVERIFY(reqAuthHeader.isEmpty());
+
// In the `!success` case we need to wait for the server to emit this or it might cause issues
// in the next test running after this. In the `success` case we anyway expect it to have been
// received.
QTRY_VERIFY(serverGotSettingsACK);
+
+}
+
+void tst_Http2::h2cAllowedAttribute_data()
+{
+ QTest::addColumn<bool>("h2cAllowed");
+ QTest::addColumn<bool>("useAttribute"); // true: use attribute, false: use environment variable
+ QTest::addColumn<bool>("success");
+
+ QTest::addRow("h2c-not-allowed") << false << false << false;
+ // Use the attribute to enable/disable the H2C:
+ QTest::addRow("attribute") << true << true << true;
+ // Use the QT_NETWORK_H2C_ALLOWED environment variable to enable/disable the H2C:
+ QTest::addRow("environment-variable") << true << false << true;
+}
+
+void tst_Http2::h2cAllowedAttribute()
+{
+ QFETCH(const bool, h2cAllowed);
+ QFETCH(const bool, useAttribute);
+ QFETCH(const bool, success);
+
+ clearHTTP2State();
+ serverPort = 0;
+
+ ServerPtr targetServer(newServer(defaultServerSettings, H2Type::h2c));
+ targetServer->setResponseBody("Hello");
+
+ QMetaObject::invokeMethod(targetServer.data(), "startServer", Qt::QueuedConnection);
+ runEventLoop();
+
+ QVERIFY(serverPort != 0);
+
+ nRequests = 1;
+
+ auto url = requestUrl(H2Type::h2c);
+ url.setPath("/index.html");
+ QNetworkRequest request(url);
+ if (h2cAllowed) {
+ if (useAttribute)
+ request.setAttribute(QNetworkRequest::Http2CleartextAllowedAttribute, true);
+ else
+ qputenv("QT_NETWORK_H2C_ALLOWED", "1");
+ }
+ auto envCleanup = qScopeGuard([]() { qunsetenv("QT_NETWORK_H2C_ALLOWED"); });
+
+ QScopedPointer<QNetworkReply> reply;
+ reply.reset(manager->get(request));
+
+ if (success)
+ connect(reply.get(), &QNetworkReply::finished, this, &tst_Http2::replyFinished);
+ else
+ connect(reply.get(), &QNetworkReply::errorOccurred, this, &tst_Http2::replyFinishedWithError);
+
+ // Since we're using self-signed certificates,
+ // ignore SSL errors:
+ reply->ignoreSslErrors();
+
+ runEventLoop();
+ STOP_ON_FAILURE
+
+ if (!success) {
+ QCOMPARE(reply->error(), QNetworkReply::ConnectionRefusedError);
+ } else {
+ QCOMPARE(reply->readAll(), QByteArray("Hello"));
+ QTRY_VERIFY(serverGotSettingsACK);
+ }
+}
+
+void tst_Http2::redirect_data()
+{
+ QTest::addColumn<int>("maxRedirects");
+ QTest::addColumn<int>("redirectCount");
+ QTest::addColumn<bool>("success");
+
+ QTest::addRow("1-redirects-none-allowed-failure") << 0 << 1 << false;
+ QTest::addRow("1-redirects-success") << 1 << 1 << true;
+ QTest::addRow("2-redirects-1-allowed-failure") << 1 << 2 << false;
+}
+
+void tst_Http2::redirect()
+{
+ QFETCH(const int, maxRedirects);
+ QFETCH(const int, redirectCount);
+ QFETCH(const bool, success);
+ const QByteArray redirectUrl = "/b.html"_ba;
+
+ clearHTTP2State();
+ serverPort = 0;
+
+ ServerPtr targetServer(newServer(defaultServerSettings, defaultConnectionType()));
+ targetServer->setRedirect(redirectUrl, redirectCount);
+
+ QMetaObject::invokeMethod(targetServer.data(), "startServer", Qt::QueuedConnection);
+ runEventLoop();
+
+ QVERIFY(serverPort != 0);
+
+ nRequests = 1;
+
+ auto originalUrl = requestUrl(defaultConnectionType());
+ auto url = originalUrl;
+ url.setPath("/index.html");
+ QNetworkRequest request(url);
+ request.setMaximumRedirectsAllowed(maxRedirects);
+ // H2C might be used on macOS where SecureTransport doesn't support server-side ALPN
+ qputenv("QT_NETWORK_H2C_ALLOWED", "1");
+ auto envCleanup = qScopeGuard([]() { qunsetenv("QT_NETWORK_H2C_ALLOWED"); });
+
+ QScopedPointer<QNetworkReply> reply;
+ reply.reset(manager->get(request));
+
+ if (success) {
+ connect(reply.get(), &QNetworkReply::finished, this, &tst_Http2::replyFinished);
+ } else {
+ connect(reply.get(), &QNetworkReply::errorOccurred, this,
+ &tst_Http2::replyFinishedWithError);
+ }
+
+ // Since we're using self-signed certificates,
+ // ignore SSL errors:
+ reply->ignoreSslErrors();
+
+ runEventLoop();
+ STOP_ON_FAILURE
+
+ QCOMPARE(nRequests, 0);
+ if (success) {
+ QCOMPARE(reply->error(), QNetworkReply::NoError);
+ QCOMPARE(reply->url().toString(),
+ originalUrl.resolved(QString::fromLatin1(redirectUrl)).toString());
+ } else if (maxRedirects < redirectCount) {
+ QCOMPARE(reply->error(), QNetworkReply::TooManyRedirectsError);
+ }
+ QTRY_VERIFY(serverGotSettingsACK);
+}
+
+void tst_Http2::trailingHEADERS()
+{
+ clearHTTP2State();
+ serverPort = 0;
+
+ ServerPtr targetServer(newServer(defaultServerSettings, defaultConnectionType()));
+ targetServer->setSendTrailingHEADERS(true);
+
+ QMetaObject::invokeMethod(targetServer.data(), "startServer", Qt::QueuedConnection);
+ runEventLoop();
+
+ QVERIFY(serverPort != 0);
+
+ nRequests = 1;
+
+ const auto url = requestUrl(defaultConnectionType());
+ QNetworkRequest request(url);
+ // H2C might be used on macOS where SecureTransport doesn't support server-side ALPN
+ request.setAttribute(QNetworkRequest::Http2CleartextAllowedAttribute, true);
+
+ std::unique_ptr<QNetworkReply> reply{ manager->get(request) };
+ connect(reply.get(), &QNetworkReply::finished, this, &tst_Http2::replyFinished);
+
+ // Since we're using self-signed certificates, ignore SSL errors:
+ reply->ignoreSslErrors();
+
+ runEventLoop();
+ STOP_ON_FAILURE
+
+ QCOMPARE(nRequests, 0);
+
+ QCOMPARE(reply->error(), QNetworkReply::NoError);
+ QTRY_VERIFY(serverGotSettingsACK);
+}
+
+void tst_Http2::duplicateRequestsWithAborts()
+{
+ clearHTTP2State();
+ serverPort = 0;
+
+ ServerPtr targetServer(newServer(defaultServerSettings, defaultConnectionType()));
+
+ QMetaObject::invokeMethod(targetServer.data(), "startServer", Qt::QueuedConnection);
+ runEventLoop();
+
+ QVERIFY(serverPort != 0);
+
+ constexpr int ExpectedSuccessfulRequests = 1;
+ nRequests = ExpectedSuccessfulRequests;
+
+ const auto url = requestUrl(defaultConnectionType());
+ QNetworkRequest request(url);
+ // H2C might be used on macOS where SecureTransport doesn't support server-side ALPN
+ request.setAttribute(QNetworkRequest::Http2CleartextAllowedAttribute, true);
+
+ qint32 finishedCount = 0;
+ auto connectToSlots = [this, &finishedCount](QNetworkReply *reply){
+ const auto onFinished = [&finishedCount, reply, this]() {
+ ++finishedCount;
+ if (reply->error() == QNetworkReply::NoError)
+ replyFinished();
+ };
+ connect(reply, &QNetworkReply::finished, reply, onFinished);
+ };
+
+ std::vector<QNetworkReply *> replies;
+ for (qint32 i = 0; i < 3; ++i) {
+ auto &reply = replies.emplace_back(manager->get(request));
+ connectToSlots(reply);
+ if (i < 2) // Delete and abort all-but-one:
+ reply->deleteLater();
+ // Since we're using self-signed certificates, ignore SSL errors:
+ reply->ignoreSslErrors();
+ }
+
+ runEventLoop();
+ STOP_ON_FAILURE
+
+ QCOMPARE(nRequests, 0);
+ QCOMPARE(finishedCount, ExpectedSuccessfulRequests);
}
void tst_Http2::serverStarted(quint16 port)
@@ -1204,6 +1602,7 @@ void tst_Http2::sendRequest(int streamNumber,
url.setPath(QString("/stream%1.html").arg(streamNumber));
QNetworkRequest request(url);
+ request.setAttribute(QNetworkRequest::Http2CleartextAllowedAttribute, true);
request.setAttribute(QNetworkRequest::Http2AllowedAttribute, QVariant(true));
request.setAttribute(QNetworkRequest::RedirectPolicyAttribute, QNetworkRequest::NoLessSafeRedirectPolicy);
request.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("text/plain"));
diff --git a/tests/auto/network/access/qabstractnetworkcache/CMakeLists.txt b/tests/auto/network/access/qabstractnetworkcache/CMakeLists.txt
index 3958916232..37c3dbda8a 100644
--- a/tests/auto/network/access/qabstractnetworkcache/CMakeLists.txt
+++ b/tests/auto/network/access/qabstractnetworkcache/CMakeLists.txt
@@ -1,9 +1,16 @@
-# Generated from qabstractnetworkcache.pro.
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
#####################################################################
## tst_qabstractnetworkcache Test:
#####################################################################
+if(NOT QT_BUILD_STANDALONE_TESTS AND NOT QT_BUILDING_QT)
+ cmake_minimum_required(VERSION 3.16)
+ project(tst_qabstractnetworkcache LANGUAGES CXX)
+ find_package(Qt6BuildInternals REQUIRED COMPONENTS STANDALONE_TEST)
+endif()
+
# Collect test data
file(GLOB_RECURSE test_data_glob
RELATIVE ${CMAKE_CURRENT_SOURCE_DIR}
@@ -13,11 +20,10 @@ list(APPEND test_data ${test_data_glob})
qt_internal_add_test(tst_qabstractnetworkcache
SOURCES
tst_qabstractnetworkcache.cpp
- PUBLIC_LIBRARIES
+ LIBRARIES
Qt::Network
TESTDATA ${test_data}
- QT_TEST_SERVER_LIST "apache2" # special case
+ QT_TEST_SERVER_LIST "apache2"
)
-#### Keys ignored in scope 1:.:.:qabstractnetworkcache.pro:<TRUE>:
# QT_TEST_SERVER_LIST = "apache2"
diff --git a/tests/auto/network/access/qabstractnetworkcache/tst_qabstractnetworkcache.cpp b/tests/auto/network/access/qabstractnetworkcache/tst_qabstractnetworkcache.cpp
index fc21569b0b..9bdef9bbe1 100644
--- a/tests/auto/network/access/qabstractnetworkcache/tst_qabstractnetworkcache.cpp
+++ b/tests/auto/network/access/qabstractnetworkcache/tst_qabstractnetworkcache.cpp
@@ -1,30 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
#include <QTemporaryDir>
#include <QTest>
@@ -290,7 +265,7 @@ void tst_QAbstractNetworkCache::runTest()
// prime the cache
QNetworkReply *reply = manager.get(request);
QSignalSpy downloaded1(reply, SIGNAL(finished()));
- QTRY_COMPARE(downloaded1.count(), 1);
+ QTRY_COMPARE(downloaded1.size(), 1);
QCOMPARE(diskCache->gotData, false);
QByteArray goodData = reply->readAll();
@@ -299,7 +274,7 @@ void tst_QAbstractNetworkCache::runTest()
// should be in the cache now
QNetworkReply *reply2 = manager.get(request);
QSignalSpy downloaded2(reply2, SIGNAL(finished()));
- QTRY_COMPARE(downloaded2.count(), 1);
+ QTRY_COMPARE(downloaded2.size(), 1);
QByteArray secondData = reply2->readAll();
if (!fetchFromCache && cacheLoadControl == QNetworkRequest::AlwaysCache) {
@@ -388,7 +363,7 @@ void tst_QAbstractNetworkCache::deleteCache()
QNetworkReply *reply = manager.get(request);
QSignalSpy downloaded1(reply, SIGNAL(finished()));
manager.setCache(0);
- QTRY_COMPARE(downloaded1.count(), 1);
+ QTRY_COMPARE(downloaded1.size(), 1);
}
diff --git a/tests/auto/network/access/qdecompresshelper/CMakeLists.txt b/tests/auto/network/access/qdecompresshelper/CMakeLists.txt
index 49fd91db0a..09317ca3eb 100644
--- a/tests/auto/network/access/qdecompresshelper/CMakeLists.txt
+++ b/tests/auto/network/access/qdecompresshelper/CMakeLists.txt
@@ -1,9 +1,16 @@
-# Generated from qdecompresshelper.pro.
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
#####################################################################
## tst_qdecompresshelper Test:
#####################################################################
+if(NOT QT_BUILD_STANDALONE_TESTS AND NOT QT_BUILDING_QT)
+ cmake_minimum_required(VERSION 3.16)
+ project(tst_qdecompresshelper LANGUAGES CXX)
+ find_package(Qt6BuildInternals REQUIRED COMPONENTS STANDALONE_TEST)
+endif()
+
qt_internal_add_test(tst_qdecompresshelper
SOURCES
gzip.rcc.cpp
@@ -11,10 +18,7 @@ qt_internal_add_test(tst_qdecompresshelper
tst_qdecompresshelper.cpp
zstandard.rcc.cpp
DEFINES
- SRC_DIR=${CMAKE_CURRENT_SOURCE_DIR} # special case
- PUBLIC_LIBRARIES
+ SRC_DIR=${CMAKE_CURRENT_SOURCE_DIR}
+ LIBRARIES
Qt::NetworkPrivate
)
-
-#### Keys ignored in scope 1:.:.:qdecompresshelper.pro:<TRUE>:
-# TEMPLATE = "app"
diff --git a/tests/auto/network/access/qdecompresshelper/tst_qdecompresshelper.cpp b/tests/auto/network/access/qdecompresshelper/tst_qdecompresshelper.cpp
index 321d373a78..cd5a52c209 100644
--- a/tests/auto/network/access/qdecompresshelper/tst_qdecompresshelper.cpp
+++ b/tests/auto/network/access/qdecompresshelper/tst_qdecompresshelper.cpp
@@ -1,30 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2020 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2020 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
#include <QTest>
@@ -344,6 +319,9 @@ void tst_QDecompressHelper::countAheadPartialRead()
void tst_QDecompressHelper::decompressBigData_data()
{
+#if defined(QT_ASAN_ENABLED)
+ QSKIP("Tests are too slow with asan enabled");
+#endif
QTest::addColumn<QByteArray>("encoding");
QTest::addColumn<QString>("path");
QTest::addColumn<qint64>("size");
@@ -432,17 +410,25 @@ void tst_QDecompressHelper::archiveBomb()
QVERIFY(bytesRead <= output.size());
QVERIFY(helper.isValid());
- if (shouldFail)
+ if (shouldFail) {
QCOMPARE(bytesRead, -1);
- else
+ QVERIFY(!helper.errorString().isEmpty());
+ } else {
QVERIFY(bytesRead > 0);
+ QVERIFY(helper.errorString().isEmpty());
+ }
}
void tst_QDecompressHelper::bigZlib()
{
#if QT_POINTER_SIZE < 8
QSKIP("This cannot be tested on 32-bit systems");
+#elif defined(QT_ASAN_ENABLED)
+ QSKIP("Test is too slow with asan enabled");
#else
+# ifndef QT_NO_EXCEPTIONS
+ try {
+# endif
// ZLib uses unsigned integers as their size type internally which creates some special
// cases in the internal code that should be tested!
QFile file(":/5GiB.txt.inflate");
@@ -462,6 +448,11 @@ void tst_QDecompressHelper::bigZlib()
QByteArray output(expected + 42, Qt::Uninitialized);
const qsizetype size = helper.read(output.data(), output.size());
QCOMPARE(size, expected);
+# ifndef QT_NO_EXCEPTIONS
+ } catch (const std::bad_alloc &) {
+ QSKIP("Encountered most likely OOM.");
+ }
+# endif
#endif
}
diff --git a/tests/auto/network/access/qhttp2connection/CMakeLists.txt b/tests/auto/network/access/qhttp2connection/CMakeLists.txt
new file mode 100644
index 0000000000..9a6e7a064e
--- /dev/null
+++ b/tests/auto/network/access/qhttp2connection/CMakeLists.txt
@@ -0,0 +1,16 @@
+# Copyright (C) 2023 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
+
+if(NOT QT_BUILD_STANDALONE_TESTS AND NOT QT_BUILDING_QT)
+ cmake_minimum_required(VERSION 3.16)
+ project(tst_qhttp2connection LANGUAGES CXX)
+ find_package(Qt6BuildInternals REQUIRED COMPONENTS STANDALONE_TEST)
+endif()
+
+qt_internal_add_test(tst_qhttp2connection
+ SOURCES
+ tst_qhttp2connection.cpp
+ LIBRARIES
+ Qt::NetworkPrivate
+ Qt::Test
+)
diff --git a/tests/auto/network/access/qhttp2connection/tst_qhttp2connection.cpp b/tests/auto/network/access/qhttp2connection/tst_qhttp2connection.cpp
new file mode 100644
index 0000000000..b9d5219ae9
--- /dev/null
+++ b/tests/auto/network/access/qhttp2connection/tst_qhttp2connection.cpp
@@ -0,0 +1,397 @@
+// Copyright (C) 2023 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
+
+#include <QtTest/QTest>
+#include <QtTest/QSignalSpy>
+
+#include <QtNetwork/private/qhttp2connection_p.h>
+#include <QtNetwork/private/hpack_p.h>
+#include <QtNetwork/private/bitstreams_p.h>
+
+#include <limits>
+
+using namespace Qt::StringLiterals;
+
+class tst_QHttp2Connection : public QObject
+{
+ Q_OBJECT
+
+private slots:
+ void construct();
+ void constructStream();
+ void testSETTINGSFrame();
+ void testPING();
+ void connectToServer();
+ void WINDOW_UPDATE();
+
+private:
+ enum PeerType { Client, Server };
+ [[nodiscard]] auto makeFakeConnectedSockets();
+ [[nodiscard]] auto getRequiredHeaders();
+ [[nodiscard]] QHttp2Connection *makeHttp2Connection(QIODevice *socket,
+ QHttp2Configuration config, PeerType type);
+ [[nodiscard]] bool waitForSettingsExchange(QHttp2Connection *client, QHttp2Connection *server);
+};
+
+class IOBuffer : public QIODevice
+{
+ Q_OBJECT
+public:
+ IOBuffer(QObject *parent, std::shared_ptr<QBuffer> _in, std::shared_ptr<QBuffer> _out)
+ : QIODevice(parent), in(std::move(_in)), out(std::move(_out))
+ {
+ connect(in.get(), &QIODevice::readyRead, this, &IOBuffer::readyRead);
+ connect(out.get(), &QIODevice::bytesWritten, this, &IOBuffer::bytesWritten);
+ connect(out.get(), &QIODevice::aboutToClose, this, &IOBuffer::readChannelFinished);
+ connect(out.get(), &QIODevice::aboutToClose, this, &IOBuffer::aboutToClose);
+ }
+
+ bool open(OpenMode mode) override
+ {
+ QIODevice::open(mode);
+ Q_ASSERT(in->isOpen());
+ Q_ASSERT(out->isOpen());
+ return false;
+ }
+
+ bool isSequential() const override { return true; }
+
+ qint64 bytesAvailable() const override { return in->pos() - readHead; }
+ qint64 bytesToWrite() const override { return 0; }
+
+ qint64 readData(char *data, qint64 maxlen) override
+ {
+ qint64 temp = in->pos();
+ in->seek(readHead);
+ qint64 res = in->read(data, std::min(maxlen, temp - readHead));
+ readHead += res;
+ if (readHead == temp) {
+ // Reached end of buffer, reset
+ in->seek(0);
+ in->buffer().resize(0);
+ readHead = 0;
+ } else {
+ in->seek(temp);
+ }
+ return res;
+ }
+
+ qint64 writeData(const char *data, qint64 len) override
+ {
+ return out->write(data, len);
+ }
+
+ std::shared_ptr<QBuffer> in;
+ std::shared_ptr<QBuffer> out;
+
+ qint64 readHead = 0;
+};
+
+auto tst_QHttp2Connection::makeFakeConnectedSockets()
+{
+ auto clientIn = std::make_shared<QBuffer>();
+ auto serverIn = std::make_shared<QBuffer>();
+ clientIn->open(QIODevice::ReadWrite);
+ serverIn->open(QIODevice::ReadWrite);
+
+ auto client = std::make_unique<IOBuffer>(this, clientIn, serverIn);
+ auto server = std::make_unique<IOBuffer>(this, std::move(serverIn), std::move(clientIn));
+
+ client->open(QIODevice::ReadWrite);
+ server->open(QIODevice::ReadWrite);
+
+ return std::pair{ std::move(client), std::move(server) };
+}
+
+auto tst_QHttp2Connection::getRequiredHeaders()
+{
+ return HPack::HttpHeader{
+ { ":authority", "example.com" },
+ { ":method", "GET" },
+ { ":path", "/" },
+ { ":scheme", "https" },
+ };
+}
+
+QHttp2Connection *tst_QHttp2Connection::makeHttp2Connection(QIODevice *socket,
+ QHttp2Configuration config,
+ PeerType type)
+{
+ QHttp2Connection *connection = nullptr;
+ if (type == PeerType::Server)
+ connection = QHttp2Connection::createDirectServerConnection(socket, config);
+ else
+ connection = QHttp2Connection::createDirectConnection(socket, config);
+ connect(socket, &QIODevice::readyRead, connection, &QHttp2Connection::handleReadyRead);
+ return connection;
+}
+
+bool tst_QHttp2Connection::waitForSettingsExchange(QHttp2Connection *client,
+ QHttp2Connection *server)
+{
+ bool settingsFrameReceived = false;
+ bool serverSettingsFrameReceived = false;
+
+ QMetaObject::Connection c = connect(client, &QHttp2Connection::settingsFrameReceived, client,
+ [&settingsFrameReceived]() {
+ settingsFrameReceived = true;
+ });
+ QMetaObject::Connection s = connect(server, &QHttp2Connection::settingsFrameReceived, server,
+ [&serverSettingsFrameReceived]() {
+ serverSettingsFrameReceived = true;
+ });
+
+ client->handleReadyRead(); // handle incoming frames, send response
+
+ bool success = QTest::qWaitFor([&]() {
+ return settingsFrameReceived && serverSettingsFrameReceived;
+ });
+
+ disconnect(c);
+ disconnect(s);
+
+ return success;
+}
+
+void tst_QHttp2Connection::construct()
+{
+ QBuffer buffer;
+ buffer.open(QIODevice::ReadWrite);
+ auto *connection = QHttp2Connection::createDirectConnection(&buffer, {});
+ QVERIFY(!connection->isGoingAway());
+ QCOMPARE(connection->maxConcurrentStreams(), 100u);
+ QCOMPARE(connection->maxHeaderListSize(), std::numeric_limits<quint32>::max());
+ QVERIFY(!connection->isUpgradedConnection());
+ QVERIFY(!connection->getStream(1)); // No stream has been created yet
+
+ auto *upgradedConnection = QHttp2Connection::createUpgradedConnection(&buffer, {});
+ QVERIFY(upgradedConnection->isUpgradedConnection());
+ // Stream 1 is created by default for an upgraded connection
+ QVERIFY(upgradedConnection->getStream(1));
+}
+
+void tst_QHttp2Connection::constructStream()
+{
+ QBuffer buffer;
+ buffer.open(QIODevice::ReadWrite);
+ auto connection = QHttp2Connection::createDirectConnection(&buffer, {});
+ QHttp2Stream *stream = connection->createStream().unwrap();
+ QVERIFY(stream);
+ QCOMPARE(stream->isPromisedStream(), false);
+ QCOMPARE(stream->isActive(), false);
+ QCOMPARE(stream->RST_STREAM_code(), 0u);
+ QCOMPARE(stream->streamID(), 1u);
+ QCOMPARE(stream->receivedHeaders(), {});
+ QCOMPARE(stream->state(), QHttp2Stream::State::Idle);
+ QCOMPARE(stream->isUploadBlocked(), false);
+ QCOMPARE(stream->isUploadingDATA(), false);
+}
+
+void tst_QHttp2Connection::testSETTINGSFrame()
+{
+ constexpr qint32 PrefaceLength = 24;
+ QBuffer buffer;
+ buffer.open(QIODevice::ReadWrite);
+ QHttp2Configuration config;
+ constexpr quint32 MaxFrameSize = 16394;
+ constexpr bool ServerPushEnabled = false;
+ constexpr quint32 StreamReceiveWindowSize = 50000;
+ constexpr quint32 SessionReceiveWindowSize = 50001;
+ config.setMaxFrameSize(MaxFrameSize);
+ config.setServerPushEnabled(ServerPushEnabled);
+ config.setStreamReceiveWindowSize(StreamReceiveWindowSize);
+ config.setSessionReceiveWindowSize(SessionReceiveWindowSize);
+ auto connection = QHttp2Connection::createDirectConnection(&buffer, config);
+ Q_UNUSED(connection);
+ QCOMPARE_GE(buffer.size(), PrefaceLength);
+
+ // Preface
+ QByteArray preface = buffer.data().first(PrefaceLength);
+ QCOMPARE(preface, "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n");
+
+ // SETTINGS
+ buffer.seek(PrefaceLength);
+ const quint32 maxSize = buffer.size() - PrefaceLength;
+ Http2::FrameReader reader;
+ Http2::FrameStatus status = reader.read(buffer);
+ QCOMPARE(status, Http2::FrameStatus::goodFrame);
+ Http2::Frame f = reader.inboundFrame();
+ QCOMPARE(f.type(), Http2::FrameType::SETTINGS);
+ QCOMPARE_LT(f.payloadSize(), maxSize);
+
+ const qint32 settingsReceived = f.dataSize() / 6;
+ QCOMPARE_GT(settingsReceived, 0);
+ QCOMPARE_LE(settingsReceived, 6);
+
+ struct ExpectedSetting
+ {
+ Http2::Settings identifier;
+ quint32 value;
+ };
+ // Commented-out settings are not sent since they are defaults
+ ExpectedSetting expectedSettings[]{
+ // { Http2::Settings::HEADER_TABLE_SIZE_ID, HPack::FieldLookupTable::DefaultSize },
+ { Http2::Settings::ENABLE_PUSH_ID, ServerPushEnabled ? 1 : 0 },
+ // { Http2::Settings::MAX_CONCURRENT_STREAMS_ID, Http2::maxConcurrentStreams },
+ { Http2::Settings::INITIAL_WINDOW_SIZE_ID, StreamReceiveWindowSize },
+ { Http2::Settings::MAX_FRAME_SIZE_ID, MaxFrameSize },
+ // { Http2::Settings::MAX_HEADER_LIST_SIZE_ID, ??? },
+ };
+
+ QCOMPARE(quint32(settingsReceived), std::size(expectedSettings));
+ for (qint32 i = 0; i < settingsReceived; ++i) {
+ const uchar *it = f.dataBegin() + i * 6;
+ const quint16 ident = qFromBigEndian<quint16>(it);
+ const quint32 intVal = qFromBigEndian<quint32>(it + 2);
+
+ ExpectedSetting expectedSetting = expectedSettings[i];
+ QVERIFY2(ident == quint16(expectedSetting.identifier),
+ qPrintable("ident: %1, expected: %2, index: %3"_L1
+ .arg(QString::number(ident),
+ QString::number(quint16(expectedSetting.identifier)),
+ QString::number(i))));
+ QVERIFY2(intVal == expectedSetting.value,
+ qPrintable("intVal: %1, expected: %2, index: %3"_L1
+ .arg(QString::number(intVal),
+ QString::number(expectedSetting.value),
+ QString::number(i))));
+ }
+}
+
+void tst_QHttp2Connection::testPING()
+{
+ auto [client, server] = makeFakeConnectedSockets();
+ auto connection = makeHttp2Connection(client.get(), {}, Client);
+ auto serverConnection = makeHttp2Connection(server.get(), {}, Server);
+
+ QVERIFY(waitForSettingsExchange(connection, serverConnection));
+
+ QSignalSpy serverPingSpy{ serverConnection, &QHttp2Connection::pingFrameRecived };
+ QSignalSpy clientPingSpy{ connection, &QHttp2Connection::pingFrameRecived };
+
+ QByteArray data{"pingpong"};
+ connection->sendPing(data);
+
+ QVERIFY(serverPingSpy.wait());
+ QVERIFY(clientPingSpy.wait());
+
+ QCOMPARE(serverPingSpy.last().at(0).toInt(), int(QHttp2Connection::PingState::Ping));
+ QCOMPARE(clientPingSpy.last().at(0).toInt(), int(QHttp2Connection::PingState::PongSignatureIdentical));
+
+ serverConnection->sendPing();
+
+ QVERIFY(clientPingSpy.wait());
+ QVERIFY(serverPingSpy.wait());
+
+ QCOMPARE(clientPingSpy.last().at(0).toInt(), int(QHttp2Connection::PingState::Ping));
+ QCOMPARE(serverPingSpy.last().at(0).toInt(), int(QHttp2Connection::PingState::PongSignatureIdentical));
+}
+
+void tst_QHttp2Connection::connectToServer()
+{
+ auto [client, server] = makeFakeConnectedSockets();
+ auto connection = makeHttp2Connection(client.get(), {}, Client);
+ auto serverConnection = makeHttp2Connection(server.get(), {}, Server);
+
+ QVERIFY(waitForSettingsExchange(connection, serverConnection));
+
+ QSignalSpy newIncomingStreamSpy{ serverConnection, &QHttp2Connection::newIncomingStream };
+ QSignalSpy clientIncomingStreamSpy{ connection, &QHttp2Connection::newIncomingStream };
+
+ QHttp2Stream *clientStream = connection->createStream().unwrap();
+ QSignalSpy clientHeaderReceivedSpy{ clientStream, &QHttp2Stream::headersReceived };
+ QVERIFY(clientStream);
+ HPack::HttpHeader headers = getRequiredHeaders();
+ clientStream->sendHEADERS(headers, false);
+
+ QVERIFY(newIncomingStreamSpy.wait());
+ auto *serverStream = newIncomingStreamSpy.front().front().value<QHttp2Stream *>();
+ QVERIFY(serverStream);
+ const HPack::HttpHeader ExpectedResponseHeaders{ { ":status", "200" } };
+ serverStream->sendHEADERS(ExpectedResponseHeaders, true);
+
+ QVERIFY(clientHeaderReceivedSpy.wait());
+ const HPack::HttpHeader
+ headersReceived = clientHeaderReceivedSpy.front().front().value<HPack::HttpHeader>();
+ QCOMPARE(headersReceived, ExpectedResponseHeaders);
+
+ QCOMPARE(clientIncomingStreamSpy.count(), 0);
+}
+
+void tst_QHttp2Connection::WINDOW_UPDATE()
+{
+ auto [client, server] = makeFakeConnectedSockets();
+ auto connection = makeHttp2Connection(client.get(), {}, Client);
+
+ QHttp2Configuration config;
+ config.setStreamReceiveWindowSize(1024); // Small window on server to provoke WINDOW_UPDATE
+ auto serverConnection = makeHttp2Connection(server.get(), config, Server);
+
+ QVERIFY(waitForSettingsExchange(connection, serverConnection));
+
+ QSignalSpy newIncomingStreamSpy{ serverConnection, &QHttp2Connection::newIncomingStream };
+
+ QHttp2Stream *clientStream = connection->createStream().unwrap();
+ QSignalSpy clientHeaderReceivedSpy{ clientStream, &QHttp2Stream::headersReceived };
+ QSignalSpy clientDataReceivedSpy{ clientStream, &QHttp2Stream::dataReceived };
+ QVERIFY(clientStream);
+ HPack::HttpHeader expectedRequestHeaders = HPack::HttpHeader{
+ { ":authority", "example.com" },
+ { ":method", "POST" },
+ { ":path", "/" },
+ { ":scheme", "https" },
+ };
+ clientStream->sendHEADERS(expectedRequestHeaders, false);
+
+ QVERIFY(newIncomingStreamSpy.wait());
+ auto *serverStream = newIncomingStreamSpy.front().front().value<QHttp2Stream *>();
+ QVERIFY(serverStream);
+ QSignalSpy serverDataReceivedSpy{ serverStream, &QHttp2Stream::dataReceived };
+
+ // Since a stream is only opened on the remote side when the header is received,
+ // we can check the headers now immediately
+ QCOMPARE(serverStream->receivedHeaders(), expectedRequestHeaders);
+
+ QBuffer *buffer = new QBuffer(clientStream);
+ QByteArray uploadedData = "Hello World"_ba.repeated(1000);
+ buffer->setData(uploadedData);
+ buffer->open(QIODevice::ReadWrite);
+ clientStream->sendDATA(buffer, true);
+
+ bool streamEnd = false;
+ QByteArray serverReceivedData;
+ while (!streamEnd) { // The window is too small to receive all data at once, so loop
+ QVERIFY(serverDataReceivedSpy.wait());
+ auto latestEmission = serverDataReceivedSpy.back();
+ serverReceivedData += latestEmission.front().value<QByteArray>();
+ streamEnd = latestEmission.back().value<bool>();
+ }
+ QCOMPARE(serverReceivedData.size(), uploadedData.size());
+ QCOMPARE(serverReceivedData, uploadedData);
+
+ QCOMPARE(clientStream->state(), QHttp2Stream::State::HalfClosedLocal);
+ QCOMPARE(serverStream->state(), QHttp2Stream::State::HalfClosedRemote);
+
+ const HPack::HttpHeader ExpectedResponseHeaders{ { ":status", "200" } };
+ serverStream->sendHEADERS(ExpectedResponseHeaders, false);
+ QBuffer *serverBuffer = new QBuffer(serverStream);
+ serverBuffer->setData(uploadedData);
+ serverBuffer->open(QIODevice::ReadWrite);
+ serverStream->sendDATA(serverBuffer, true);
+
+ QVERIFY(clientHeaderReceivedSpy.wait());
+ const HPack::HttpHeader
+ headersReceived = clientHeaderReceivedSpy.front().front().value<HPack::HttpHeader>();
+ QCOMPARE(headersReceived, ExpectedResponseHeaders);
+
+ QTRY_COMPARE_GT(clientDataReceivedSpy.count(), 0);
+ QCOMPARE(clientDataReceivedSpy.count(), 1); // Only one DATA frame since our window is larger
+ QCOMPARE(clientDataReceivedSpy.front().front().value<QByteArray>(), uploadedData);
+
+ QCOMPARE(clientStream->state(), QHttp2Stream::State::Closed);
+ QCOMPARE(serverStream->state(), QHttp2Stream::State::Closed);
+}
+
+QTEST_MAIN(tst_QHttp2Connection)
+
+#include "tst_qhttp2connection.moc"
diff --git a/tests/auto/network/access/qhttpheaderparser/CMakeLists.txt b/tests/auto/network/access/qhttpheaderparser/CMakeLists.txt
new file mode 100644
index 0000000000..50deeb3e56
--- /dev/null
+++ b/tests/auto/network/access/qhttpheaderparser/CMakeLists.txt
@@ -0,0 +1,19 @@
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
+
+if(NOT QT_BUILD_STANDALONE_TESTS AND NOT QT_BUILDING_QT)
+ cmake_minimum_required(VERSION 3.16)
+ project(tst_qhttpheaderparser LANGUAGES CXX)
+ find_package(Qt6BuildInternals REQUIRED COMPONENTS STANDALONE_TEST)
+endif()
+
+if(NOT QT_FEATURE_private_tests)
+ return()
+endif()
+
+qt_internal_add_test(tst_qhttpheaderparser
+ SOURCES
+ tst_qhttpheaderparser.cpp
+ LIBRARIES
+ Qt::NetworkPrivate
+)
diff --git a/tests/auto/network/access/qhttpheaderparser/tst_qhttpheaderparser.cpp b/tests/auto/network/access/qhttpheaderparser/tst_qhttpheaderparser.cpp
new file mode 100644
index 0000000000..9ba889fdb3
--- /dev/null
+++ b/tests/auto/network/access/qhttpheaderparser/tst_qhttpheaderparser.cpp
@@ -0,0 +1,94 @@
+// Copyright (C) 2022 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
+
+#include <QtTest/qtest.h>
+#include <QObject>
+#include <QtNetwork/private/qhttpheaderparser_p.h>
+
+class tst_QHttpHeaderParser : public QObject
+{
+ Q_OBJECT
+private Q_SLOTS:
+ void constructor();
+ void limitsSetters();
+
+ void adjustableLimits_data();
+ void adjustableLimits();
+
+ // general parsing tests can be found in tst_QHttpNetworkReply
+};
+
+void tst_QHttpHeaderParser::constructor()
+{
+ QHttpHeaderParser parser;
+ QCOMPARE(parser.getStatusCode(), 100);
+ QCOMPARE(parser.getMajorVersion(), 0);
+ QCOMPARE(parser.getMinorVersion(), 0);
+ QCOMPARE(parser.getReasonPhrase(), QByteArray());
+ QCOMPARE(parser.combinedHeaderValue("Location"), QByteArray());
+ QCOMPARE(parser.maxHeaderFields(), HeaderConstants::MAX_HEADER_FIELDS);
+ QCOMPARE(parser.maxHeaderFieldSize(), HeaderConstants::MAX_HEADER_FIELD_SIZE);
+ QCOMPARE(parser.maxTotalHeaderSize(), HeaderConstants::MAX_TOTAL_HEADER_SIZE);
+}
+
+void tst_QHttpHeaderParser::limitsSetters()
+{
+ QHttpHeaderParser parser;
+ parser.setMaxHeaderFields(10);
+ QCOMPARE(parser.maxHeaderFields(), 10);
+ parser.setMaxHeaderFieldSize(10);
+ QCOMPARE(parser.maxHeaderFieldSize(), 10);
+ parser.setMaxTotalHeaderSize(10);
+ QCOMPARE(parser.maxTotalHeaderSize(), 10);
+}
+
+void tst_QHttpHeaderParser::adjustableLimits_data()
+{
+ QTest::addColumn<qsizetype>("maxFieldCount");
+ QTest::addColumn<qsizetype>("maxFieldSize");
+ QTest::addColumn<qsizetype>("maxTotalSize");
+ QTest::addColumn<QByteArray>("headers");
+ QTest::addColumn<bool>("success");
+
+ // We pretend -1 means to not set a new limit.
+
+ QTest::newRow("maxFieldCount-pass") << qsizetype(10) << qsizetype(-1) << qsizetype(-1)
+ << QByteArray("Location: hi\r\n\r\n") << true;
+ QTest::newRow("maxFieldCount-fail") << qsizetype(1) << qsizetype(-1) << qsizetype(-1)
+ << QByteArray("Location: hi\r\nCookie: a\r\n\r\n") << false;
+
+ QTest::newRow("maxFieldSize-pass") << qsizetype(-1) << qsizetype(50) << qsizetype(-1)
+ << QByteArray("Location: hi\r\n\r\n") << true;
+ constexpr char cookieHeader[] = "Cookie: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
+ static_assert(sizeof(cookieHeader) - 1 == 51);
+ QByteArray fullHeader = QByteArray("Location: hi\r\n") + cookieHeader;
+ QTest::newRow("maxFieldSize-fail") << qsizetype(-1) << qsizetype(50) << qsizetype(-1)
+ << (fullHeader + "\r\n\r\n") << false;
+
+ QTest::newRow("maxTotalSize-pass") << qsizetype(-1) << qsizetype(-1) << qsizetype(50)
+ << QByteArray("Location: hi\r\n\r\n") << true;
+ QTest::newRow("maxTotalSize-fail") << qsizetype(-1) << qsizetype(-1) << qsizetype(10)
+ << QByteArray("Location: hi\r\n\r\n") << false;
+}
+
+void tst_QHttpHeaderParser::adjustableLimits()
+{
+ QFETCH(qsizetype, maxFieldCount);
+ QFETCH(qsizetype, maxFieldSize);
+ QFETCH(qsizetype, maxTotalSize);
+ QFETCH(QByteArray, headers);
+ QFETCH(bool, success);
+
+ QHttpHeaderParser parser;
+ if (maxFieldCount != qsizetype(-1))
+ parser.setMaxHeaderFields(maxFieldCount);
+ if (maxFieldSize != qsizetype(-1))
+ parser.setMaxHeaderFieldSize(maxFieldSize);
+ if (maxTotalSize != qsizetype(-1))
+ parser.setMaxTotalHeaderSize(maxTotalSize);
+
+ QCOMPARE(parser.parseHeaders(headers), success);
+}
+
+QTEST_MAIN(tst_QHttpHeaderParser)
+#include "tst_qhttpheaderparser.moc"
diff --git a/tests/auto/network/access/qhttpheaders/CMakeLists.txt b/tests/auto/network/access/qhttpheaders/CMakeLists.txt
new file mode 100644
index 0000000000..0de1f96c67
--- /dev/null
+++ b/tests/auto/network/access/qhttpheaders/CMakeLists.txt
@@ -0,0 +1,16 @@
+# Copyright (C) 2023 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
+
+if(NOT QT_BUILD_STANDALONE_TESTS AND NOT QT_BUILDING_QT)
+ cmake_minimum_required(VERSION 3.16)
+ project(tst_qhttpheaders LANGUAGES CXX)
+ find_package(Qt6BuildInternals REQUIRED COMPONENTS STANDALONE_TEST)
+endif()
+
+qt_internal_add_test(tst_qhttpheaders
+ SOURCES
+ tst_qhttpheaders.cpp
+ LIBRARIES
+ Qt::Core
+ Qt::Network
+)
diff --git a/tests/auto/network/access/qhttpheaders/tst_qhttpheaders.cpp b/tests/auto/network/access/qhttpheaders/tst_qhttpheaders.cpp
new file mode 100644
index 0000000000..457d30feeb
--- /dev/null
+++ b/tests/auto/network/access/qhttpheaders/tst_qhttpheaders.cpp
@@ -0,0 +1,552 @@
+// Copyright (C) 2023 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
+
+#include <QtNetwork/qhttpheaders.h>
+
+#include <QtTest/qtest.h>
+
+#include <QtCore/qmap.h>
+#include <QtCore/qset.h>
+
+using namespace Qt::StringLiterals;
+
+class tst_QHttpHeaders : public QObject
+{
+ Q_OBJECT
+
+private slots:
+ void constructors();
+ void accessors();
+ void wellKnownHeader();
+ void headerNameField();
+ void headerValueField();
+ void valueEncoding();
+ void replaceOrAppend();
+
+private:
+ static constexpr QAnyStringView n1{"name1"};
+ static constexpr QAnyStringView n2{"name2"};
+ static constexpr QAnyStringView n3{"name3"};
+ static constexpr QAnyStringView v1{"value1"};
+ static constexpr QAnyStringView v2{"value2"};
+ static constexpr QAnyStringView v3{"value3"};
+ static constexpr QAnyStringView N1{"NAME1"};
+ static constexpr QAnyStringView N2{"NAME2"};
+ static constexpr QAnyStringView N3{"NAME3"};
+ static constexpr QAnyStringView V1{"VALUE1"};
+ static constexpr QAnyStringView V2{"VALUE2"};
+ static constexpr QAnyStringView V3{"VALUE3"};
+};
+
+void tst_QHttpHeaders::constructors()
+{
+ // Default ctor
+ QHttpHeaders h1;
+ QVERIFY(h1.isEmpty());
+
+ // Copy ctor
+ QHttpHeaders h2(h1);
+ QCOMPARE(h2.toListOfPairs(), h1.toListOfPairs());
+
+ // Copy assignment
+ QHttpHeaders h3;
+ h3 = h1;
+ QCOMPARE(h3.toListOfPairs(), h1.toListOfPairs());
+
+ // Move assignment
+ QHttpHeaders h4;
+ h4 = std::move(h2);
+ QCOMPARE(h4.toListOfPairs(), h1.toListOfPairs());
+
+ // Move ctor
+ QHttpHeaders h5(std::move(h4));
+ QCOMPARE(h5.toListOfPairs(), h1.toListOfPairs());
+
+ // Constructors that are counterparts to 'toXXX()' conversion getters
+ const QByteArray nb1{"name1"};
+ const QByteArray nb2{"name2"};
+ const QByteArray nv1{"value1"};
+ const QByteArray nv2{"value2"};
+ // Initialize three QHttpHeaders with similar content, and verify that they have
+ // similar header entries
+#define CONTAINS_HEADER(NAME, VALUE) \
+ QVERIFY(hlist.contains(NAME) && hmap.contains(NAME) && hhash.contains(NAME)); \
+ QCOMPARE(hlist.combinedValue(NAME), VALUE); \
+ QCOMPARE(hmap.combinedValue(NAME), VALUE); \
+ QCOMPARE(hhash.combinedValue(NAME), VALUE); \
+
+ QList<std::pair<QByteArray, QByteArray>> list{{nb1, nv1}, {nb2, nv2}, {nb2, nv2}};
+ QMultiMap<QByteArray, QByteArray> map{{nb1, nv1}, {nb2, nv2}, {nb2, nv2}};
+ QMultiHash<QByteArray, QByteArray> hash{{nb1, nv1}, {nb2, nv2}, {nb2, nv2}};
+ QHttpHeaders hlist = QHttpHeaders::fromListOfPairs(list);
+ QHttpHeaders hmap = QHttpHeaders::fromMultiMap(map);
+ QHttpHeaders hhash = QHttpHeaders::fromMultiHash(hash);
+ CONTAINS_HEADER(nb1, v1);
+ CONTAINS_HEADER(nb2, nv2 + ", " + nv2)
+#undef CONTAINS_HEADER
+}
+
+void tst_QHttpHeaders::accessors()
+{
+ QHttpHeaders h1;
+
+ // isEmpty(), clear(), size()
+ h1.append(n1,v1);
+ QVERIFY(!h1.isEmpty());
+ QCOMPARE(h1.size(), 1);
+ QVERIFY(h1.append(n1, v1));
+ QCOMPARE(h1.size(), 2);
+ h1.insert(0, n1, v1);
+ QCOMPARE(h1.size(), 3);
+ h1.clear();
+ QVERIFY(h1.isEmpty());
+
+ // contains()
+ h1.append(n1, v1);
+ QVERIFY(h1.contains(n1));
+ QVERIFY(h1.contains(N1));
+ QVERIFY(!h1.contains(n2));
+ QVERIFY(!h1.contains(QHttpHeaders::WellKnownHeader::Allow));
+ h1.append(QHttpHeaders::WellKnownHeader::Accept, "nothing");
+ QVERIFY(h1.contains(QHttpHeaders::WellKnownHeader::Accept));
+ QVERIFY(h1.contains("accept"));
+
+ // values()/value()
+#define EXISTS_NOT(H, N) do { \
+ QVERIFY(!H.contains(N)); \
+ QCOMPARE(H.value(N, "ENOENT"), "ENOENT"); \
+ const auto values = H.values(N); \
+ QVERIFY(values.isEmpty()); \
+ QVERIFY(H.combinedValue(N).isNull()); \
+ } while (false)
+
+#define EXISTS_N_TIMES(X, H, N, ...) do { \
+ const std::array expected = { __VA_ARGS__ }; \
+ static_assert(std::tuple_size_v<decltype(expected)> == X); \
+ QVERIFY(H.contains(N)); \
+ QCOMPARE(H.value(N, "ENOENT"), expected.front()); \
+ const auto values = H.values(N); \
+ QCOMPARE(values.size(), X); \
+ QCOMPARE(values.front(), expected.front()); \
+ /* ignore in-between */ \
+ QCOMPARE(values.back(), expected.back()); \
+ QCOMPARE(H.combinedValue(N), values.join(", ")); \
+ } while (false)
+
+#define EXISTS_ONCE(H, N, V) EXISTS_N_TIMES(1, H, N, V)
+
+ EXISTS_ONCE(h1, n1, v1);
+ EXISTS_ONCE(h1, N1, v1);
+ EXISTS_ONCE(h1, QHttpHeaders::WellKnownHeader::Accept, "nothing");
+ EXISTS_ONCE(h1, "Accept", "nothing");
+
+ EXISTS_NOT(h1, N2);
+ EXISTS_NOT(h1, QHttpHeaders::WellKnownHeader::Allow);
+
+ h1.clear();
+
+ EXISTS_NOT(h1, n1);
+
+ h1.append(n1, v1);
+ h1.append(n1, v2);
+ h1.append(n1, v3);
+ h1.append(n2, v2);
+ h1.append(n3, ""); // empty value
+
+ EXISTS_N_TIMES(3, h1, n1, v1, v2, v3);
+ EXISTS_N_TIMES(3, h1, N1, v1, v2, v3);
+ EXISTS_ONCE(h1, n3, ""); // empty value
+
+ h1.append(QHttpHeaders::WellKnownHeader::Accept, "nothing");
+ h1.append(QHttpHeaders::WellKnownHeader::Accept, "ever");
+
+ EXISTS_N_TIMES(2, h1, QHttpHeaders::WellKnownHeader::Accept, "nothing", "ever");
+ EXISTS_NOT(h1, "nonexistent");
+
+#undef EXISTS_ONCE
+#undef EXISTS_N_TIMES
+#undef EXISTS_NOT
+
+ // valueAt()
+ h1.clear();
+ h1.append(n1, v1);
+ h1.append(n2, v2);
+ h1.append(n3, v3);
+ QCOMPARE(h1.valueAt(0), v1);
+ QCOMPARE(h1.valueAt(1), v2);
+ QCOMPARE(h1.valueAt(2), v3);
+
+ // nameAt()
+ h1.clear();
+ h1.append(n1, v1);
+ h1.append(n2, v2);
+ h1.append(n3, v3);
+ QCOMPARE(h1.nameAt(0), n1);
+ QCOMPARE(h1.nameAt(1), n2);
+ QCOMPARE(h1.nameAt(2), n3);
+
+ // removeAll()
+ h1.clear();
+ QVERIFY(h1.append(n1, v1));
+ QVERIFY(h1.append(QHttpHeaders::WellKnownHeader::Accept, "nothing"));
+ QVERIFY(h1.append(n1, v1));
+ QCOMPARE(h1.size(), 3);
+ h1.removeAll(n1);
+ QVERIFY(!h1.contains(n1));
+ QCOMPARE(h1.size(), 1);
+ QVERIFY(h1.contains("accept"));
+ h1.removeAll(QHttpHeaders::WellKnownHeader::Accept);
+ QVERIFY(!h1.contains(QHttpHeaders::WellKnownHeader::Accept));
+
+ // removeAt()
+ h1.clear();
+ h1.append(n1, v1);
+ h1.append(n2, v2);
+ h1.append(n3, v3);
+
+ // Valid removals
+ QVERIFY(h1.contains(n3));
+ h1.removeAt(2);
+ QVERIFY(!h1.contains(n3));
+ QVERIFY(h1.contains(n1));
+ h1.removeAt(0);
+ QVERIFY(!h1.contains(n1));
+ QVERIFY(h1.contains(n2));
+ h1.removeAt(0);
+ QVERIFY(!h1.contains(n2));
+ QVERIFY(h1.isEmpty());
+
+ // toListOfPairs()
+ h1.clear();
+ h1.append(n1, v1);
+ h1.append(n2, v2);
+ h1.append(N3, V3); // uppercase of n3
+ auto list = h1.toListOfPairs();
+ QCOMPARE(list.size(), h1.size());
+ QCOMPARE(list.at(0).first, n1);
+ QCOMPARE(list.at(0).second, v1);
+ QCOMPARE(list.at(1).first, n2);
+ QCOMPARE(list.at(1).second, v2);
+ QCOMPARE(list.at(2).first, n3); // N3 has been lower-cased
+ QCOMPARE(list.at(2).second, V3);
+
+ // toMultiMap()
+ auto map = h1.toMultiMap();
+ QCOMPARE(map.size(), h1.size());
+ QCOMPARE(map.value(n1.toString().toLatin1()), v1);
+ QCOMPARE(map.value(n2.toString().toLatin1()), v2);
+ QCOMPARE(map.value(n3.toString().toLatin1()), V3);
+
+ // toMultiHash()
+ auto hash = h1.toMultiHash();
+ QCOMPARE(hash.size(), h1.size());
+ QCOMPARE(hash.value(n1.toString().toLatin1()), v1);
+ QCOMPARE(hash.value(n2.toString().toLatin1()), v2);
+ QCOMPARE(hash.value(n3.toString().toLatin1()), V3);
+
+ // insert()
+ h1.clear();
+ h1.append(n3, v3);
+ QVERIFY(h1.insert(0, n1, v1));
+ list = h1.toListOfPairs();
+ QCOMPARE(list.size(), 2);
+ QCOMPARE(list.at(0).first, n1);
+ QCOMPARE(list.at(0).second, v1);
+ QCOMPARE(list.at(1).first, n3);
+ QCOMPARE(list.at(1).second, v3);
+ QVERIFY(h1.insert(1, n2, v2));
+ list = h1.toListOfPairs();
+ QCOMPARE(list.size(), 3);
+ QCOMPARE(list.at(0).first, n1);
+ QCOMPARE(list.at(0).second, v1);
+ QCOMPARE(list.at(1).first, n2);
+ QCOMPARE(list.at(1).second, v2);
+ QCOMPARE(list.at(2).first, n3);
+ QCOMPARE(list.at(2).second, v3);
+ QVERIFY(h1.insert(1, QHttpHeaders::WellKnownHeader::Accept, "nothing"));
+ QCOMPARE(h1.size(), 4);
+ list = h1.toListOfPairs();
+ QCOMPARE(list.at(1).first, "accept");
+ QCOMPARE(list.at(1).second, "nothing");
+ QVERIFY(h1.insert(list.size(), "LastName", "lastValue"));
+ QCOMPARE(h1.size(), 5);
+ list = h1.toListOfPairs();
+ QCOMPARE(list.last().first, "lastname");
+ QCOMPARE(list.last().second, "lastValue");
+ // Failed insert
+ QRegularExpression re("HTTP header name contained*");
+ QTest::ignoreMessage(QtMsgType::QtWarningMsg, re);
+ QVERIFY(!h1.insert(0, "a€", "b"));
+
+ // replace
+ h1.clear();
+ h1.append(n1, v1);
+ h1.append(n2, v2);
+ QCOMPARE(h1.size(), 2);
+ QVERIFY(h1.replace(0, n3, v3));
+ QVERIFY(h1.replace(1, QHttpHeaders::WellKnownHeader::Accept, "nothing"));
+ QCOMPARE(h1.size(), 2);
+ list = h1.toListOfPairs();
+ QCOMPARE(list.at(0).first, n3);
+ QCOMPARE(list.at(0).second, v3);
+ QCOMPARE(list.at(1).first, "accept");
+ QCOMPARE(list.at(1).second, "nothing");
+ QVERIFY(h1.replace(1, "ACCEPT", "NOTHING"));
+ QCOMPARE(h1.size(), 2);
+ list = h1.toListOfPairs();
+ QCOMPARE(list.at(0).first, n3);
+ QCOMPARE(list.at(0).second, v3);
+ QCOMPARE(list.at(1).first, "accept");
+ QCOMPARE(list.at(1).second, "NOTHING");
+ // Failed replace
+ QTest::ignoreMessage(QtMsgType::QtWarningMsg, re);
+ QVERIFY(!h1.replace(0, "a€", "b"));
+
+}
+
+void tst_QHttpHeaders::wellKnownHeader()
+{
+ QByteArrayView view = QHttpHeaders::wellKnownHeaderName(QHttpHeaders::WellKnownHeader::AIM);
+ QCOMPARE(view, "a-im");
+}
+
+#define TEST_ILLEGAL_HEADER_NAME_CHARACTER(NAME) \
+ QTest::ignoreMessage(QtMsgType::QtWarningMsg, re); \
+ QVERIFY(!h1.append(NAME, v1)); \
+ QVERIFY(h1.isEmpty()); \
+
+void tst_QHttpHeaders::headerNameField()
+{
+ QHttpHeaders h1;
+
+ // All allowed characters in different encodings and types
+ // const char[]
+ h1.append("abcdefghijklmnopqrstuvwyxzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!#$%&'*+-.^_`|~", v1);
+ QCOMPARE(h1.size(), 1);
+ // UTF-8
+ h1.append(u8"abcdefghijklmnopqrstuvwyxzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!#$%&'*+-.^_`|~",
+ v1);
+ QCOMPARE(h1.size(), 2);
+ // UTF-16
+ h1.append(u"abcdefghijklmnopqrstuvwyxzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!#$%&'*+-.^_`|~", v1);
+ QCOMPARE(h1.size(), 3);
+ // QString (UTF-16)
+ h1.append(u"abcdefghijklmnopqrstuvwyxzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!#$%&'*+-.^_`|~"_s,
+ v1);
+ QCOMPARE(h1.size(), 4);
+ QCOMPARE(h1.nameAt(0), h1.nameAt(1));
+ QCOMPARE(h1.nameAt(1), h1.nameAt(2));
+ QCOMPARE(h1.nameAt(2), h1.nameAt(3));
+ h1.clear();
+
+ // Error cases
+ // Header name must contain at least 1 character
+ QTest::ignoreMessage(QtMsgType::QtWarningMsg, "HTTP header name cannot be empty");
+ h1.append("", v1);
+ QVERIFY(h1.isEmpty());
+ // Disallowed ASCII/extended ASCII characters (not exhaustive list)
+ QRegularExpression re("HTTP header name contained illegal character*");
+ TEST_ILLEGAL_HEADER_NAME_CHARACTER("foo\x08" "bar"); // BS
+ TEST_ILLEGAL_HEADER_NAME_CHARACTER("foo\x7F" "bar"); // DEL
+ TEST_ILLEGAL_HEADER_NAME_CHARACTER("foo()" "bar"); // parantheses
+ TEST_ILLEGAL_HEADER_NAME_CHARACTER("foobar" "¿"); // extended ASCII
+ TEST_ILLEGAL_HEADER_NAME_CHARACTER("©" "foobar"); // extended ASCII
+ TEST_ILLEGAL_HEADER_NAME_CHARACTER("foo,bar"); // comma
+ // Disallowed UTF-8 characters
+ TEST_ILLEGAL_HEADER_NAME_CHARACTER(u8"€");
+ TEST_ILLEGAL_HEADER_NAME_CHARACTER(u8"𝒜𝒴𝟘𝟡𐎀𐎜𐒀𐒐𝓐𝓩𝔸𝔹𝕀𝕁𝕌𝕍𓂀𓂁𓃀𓃁𓇋𓇌𓉐𓉑𓋴𓋵𓎡𓎢𓎣𓏏");
+ // Disallowed UTF-16 characters
+ TEST_ILLEGAL_HEADER_NAME_CHARACTER(u"€");
+ TEST_ILLEGAL_HEADER_NAME_CHARACTER(u"𝒜𝒴𝟘𝟡𐎀𐎜𐒀𐒐𝓐𝓩𝔸𝔹𝕀𝕁𝕌𝕍𓂀𓂁𓃀𓃁𓇋𓇌𓉐𓉑𓋴𓋵𓎡𓎢𓎣𓏏");
+
+ // Non-null-terminated name. The 'x' below is to make sure the strings don't
+ // null-terminate by happenstance
+ h1.clear();
+ constexpr char L1Array[] = {'a','b','c','x'};
+ const QLatin1StringView nonNullLatin1{L1Array, sizeof(L1Array) - 1}; // abc
+
+ constexpr char UTF8Array[] = {0x64, 0x65, 0x66, 0x78};
+ const QUtf8StringView nonNullUTF8(UTF8Array, sizeof(UTF8Array) - 1); // def
+
+ constexpr QChar UTF16Array[] = {'g', 'h', 'i', 'x'};
+ QStringView nonNullUTF16(UTF16Array, sizeof(UTF16Array) / sizeof(QChar) - 1); // ghi
+
+ h1.append(nonNullLatin1, v1);
+ QCOMPARE(h1.size(), 1);
+ QVERIFY(h1.contains(nonNullLatin1));
+ QCOMPARE(h1.combinedValue(nonNullLatin1), v1);
+
+ h1.append(nonNullUTF8, v2);
+ QCOMPARE(h1.size(), 2);
+ QVERIFY(h1.contains(nonNullUTF8));
+ QCOMPARE(h1.combinedValue(nonNullUTF8), v2);
+
+ h1.append(nonNullUTF16, v3);
+ QCOMPARE(h1.size(), 3);
+ QVERIFY(h1.contains(nonNullUTF16));
+ QCOMPARE(h1.combinedValue(nonNullUTF16), v3);
+}
+
+#define TEST_ILLEGAL_HEADER_VALUE_CHARACTER(VALUE) \
+QTest::ignoreMessage(QtMsgType::QtWarningMsg, re); \
+ QVERIFY(!h1.append(n1, VALUE)); \
+ QVERIFY(h1.isEmpty()); \
+
+void tst_QHttpHeaders::headerValueField()
+{
+ QHttpHeaders h1;
+
+ // Visible ASCII characters and space and horizontal tab
+ // const char[]
+ h1.append(n1, "!\"#$%&'()*+,-./0123456789:; \t<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_"
+ "`abcdefghijklmnopqrstuvwxyz{|}~");
+ QCOMPARE(h1.size(), 1);
+ // UTF-8
+ h1.append(n1, u8"!\"#$%&'()*+,-./0123456789:; \t<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_"
+ "`abcdefghijklmnopqrstuvwxyz{|}~");
+ QCOMPARE(h1.size(), 2);
+ // UTF-16
+ h1.append(n1, u"!\"#$%&'()*+,-./0123456789:; \t<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_"
+ "`abcdefghijklmnopqrstuvwxyz{|}~");
+ QCOMPARE(h1.size(), 3);
+ // QString / UTF-16
+ h1.append(n1, u"!\"#$%&'()*+,-./0123456789:; \t<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_"
+ "`abcdefghijklmnopqrstuvwxyz{|}~"_s);
+ QCOMPARE(h1.size(), 4);
+ const auto values = h1.values(n1);
+ QVERIFY(!values.isEmpty() && values.size() == 4);
+ QVERIFY(values[0] == values[1]
+ && values[1] == values[2]
+ && values[2] == values[3]);
+ // Extended ASCII (explicit on Latin-1 to avoid UTF-8 interpretation)
+ h1.append(n1, "\x80\x09\xB2\xFF"_L1);
+ QCOMPARE(h1.size(), 5);
+ // Empty value
+ h1.append(n1, "");
+ QCOMPARE(h1.size(), 6);
+ // Leading and trailing space
+ h1.clear();
+ h1.append(n1, " foo ");
+ QCOMPARE(h1.combinedValue(n1), "foo");
+ h1.append(n1, "\tbar\t");
+ QCOMPARE(h1.combinedValue(n1), "foo, bar");
+ QCOMPARE(h1.size(), 2);
+
+ h1.clear();
+ QRegularExpression re("HTTP header value contained illegal character*");
+ TEST_ILLEGAL_HEADER_VALUE_CHARACTER("foo\x08" "bar"); // BS
+ TEST_ILLEGAL_HEADER_VALUE_CHARACTER("foo\x1B" "bar"); // ESC
+ // Disallowed UTF-8 characters
+ TEST_ILLEGAL_HEADER_VALUE_CHARACTER(u8"€");
+ TEST_ILLEGAL_HEADER_VALUE_CHARACTER(u8"𝒜𝒴𝟘𝟡𐎀𐎜𐒀𐒐𝓐𝓩𝔸𝔹𝕀𝕁𝕌𝕍𓂀𓂁𓃀𓃁𓇋𓇌𓉐𓉑𓋴𓋵𓎡𓎢𓎣𓏏");
+ // Disallowed UTF-16 characters
+ TEST_ILLEGAL_HEADER_VALUE_CHARACTER(u"€");
+ TEST_ILLEGAL_HEADER_VALUE_CHARACTER(u"𝒜𝒴𝟘𝟡𐎀𐎜𐒀𐒐𝓐𝓩𝔸𝔹𝕀𝕁𝕌𝕍𓂀𓂁𓃀𓃁𓇋𓇌𓉐𓉑𓋴𓋵𓎡𓎢𓎣𓏏");
+
+ // Non-null-terminated value. The 'x' below is to make sure the strings don't
+ // null-terminate by happenstance
+ h1.clear();
+ constexpr char L1Array[] = {'a','b','c','x'};
+ const QLatin1StringView nonNullLatin1{L1Array, sizeof(L1Array) - 1}; // abc
+
+ constexpr char UTF8Array[] = {0x64, 0x65, 0x66, 0x78};
+ const QUtf8StringView nonNullUTF8(UTF8Array, sizeof(UTF8Array) - 1); // def
+
+ constexpr QChar UTF16Array[] = {'g', 'h', 'i', 'x'};
+ QStringView nonNullUTF16(UTF16Array, sizeof(UTF16Array) / sizeof(QChar) - 1); // ghi
+
+ h1.append(n1, nonNullLatin1);
+ QCOMPARE(h1.size(), 1);
+ QVERIFY(h1.contains(n1));
+ QCOMPARE(h1.combinedValue(n1), "abc");
+
+ h1.append(n2, nonNullUTF8);
+ QCOMPARE(h1.size(), 2);
+ QVERIFY(h1.contains(n2));
+ QCOMPARE(h1.combinedValue(n2), "def");
+
+ h1.append(n3, nonNullUTF16);
+ QCOMPARE(h1.size(), 3);
+ QVERIFY(h1.contains(n3));
+ QCOMPARE(h1.combinedValue(n3), "ghi");
+}
+
+void tst_QHttpHeaders::valueEncoding()
+{
+ // Test that common encodings are possible to set and not blocked by
+ // header value character filter (ie. don't contain disallowed characters as per RFC 9110)
+ QHttpHeaders h1;
+ // Within visible ASCII range
+ QVERIFY(h1.append(n1, "foo"_ba.toBase64()));
+ QCOMPARE(h1.values(n1).at(0), "Zm9v");
+ h1.replace(0, n1, "foo"_ba.toPercentEncoding());
+ QCOMPARE(h1.values(n1).at(0), "foo");
+
+ // Outside of ASCII/Latin-1 range (€)
+ h1.replace(0, n1, "foo€"_ba.toBase64());
+ QCOMPARE(h1.values(n1).at(0), "Zm9v4oKs");
+ h1.replace(0, n1, "foo€"_ba.toPercentEncoding());
+ QCOMPARE(h1.values(n1).at(0), "foo%E2%82%AC");
+}
+
+void tst_QHttpHeaders::replaceOrAppend()
+{
+ QHttpHeaders h1;
+
+#define REPLACE_OR_APPEND(NAME, VALUE, INDEX, TOTALSIZE) \
+ do { \
+ QVERIFY(h1.replaceOrAppend(NAME, VALUE)); \
+ QCOMPARE(h1.size(), TOTALSIZE); \
+ QCOMPARE(h1.nameAt(INDEX), NAME); \
+ QCOMPARE(h1.valueAt(INDEX), VALUE); \
+ } while (false)
+
+ // Append to empty container and replace it
+ REPLACE_OR_APPEND(n1, v1, 0, 1); // Appends
+ REPLACE_OR_APPEND(n1, v2, 0, 1); // Replaces
+
+ // Replace at beginning, middle, and end
+ h1.clear();
+ REPLACE_OR_APPEND(n1, v1, 0, 1); // Appends
+ REPLACE_OR_APPEND(n2, v2, 1, 2); // Appends
+ REPLACE_OR_APPEND(n3, v3, 2, 3); // Appends
+ REPLACE_OR_APPEND(n1, V1, 0, 3); // Replaces at beginning
+ REPLACE_OR_APPEND(n2, V2, 1, 3); // Replaces at middle
+ REPLACE_OR_APPEND(n3, V3, 2, 3); // Replaces at end
+
+ // Pre-existing multiple values (n2) are removed
+ h1.clear();
+ h1.append(n1, v1);
+ h1.append(n2, v2); // First n2 is at index 1
+ h1.append(n2, v2);
+ h1.append(n3, v3);
+ h1.append(n2, v2);
+ QCOMPARE(h1.size(), 5);
+ QCOMPARE(h1.combinedValue(n2), "value2, value2, value2");
+ REPLACE_OR_APPEND(n2, V2, 1, 3); // Replaces value at index 1, and removes the rest
+ QCOMPARE(h1.combinedValue(n2), "VALUE2");
+#undef REPLACE_OR_APPEND
+
+ // Implicit sharing / detaching
+ h1.clear();
+ h1.append(n1, v1);
+ QHttpHeaders h2 = h1;
+ QCOMPARE(h1.size(), h2.size());
+ QCOMPARE(h1.valueAt(0), h2.valueAt(0)); // Iniially values are equal
+ h1.replaceOrAppend(n1, v2); // Change value in h1 => detaches h1
+ QCOMPARE_NE(h1.valueAt(0), h2.valueAt(0)); // Values are no more equal
+ QCOMPARE(h1.valueAt(0), v2); // Value in h1 changed
+ QCOMPARE(h2.valueAt(0), v1); // Value in h2 remained
+
+ // Failed attempts
+ h1.clear();
+ h1.append(n1, v1);
+ QRegularExpression re("HTTP header*");
+ QTest::ignoreMessage(QtMsgType::QtWarningMsg, re);
+ QVERIFY(!h1.replaceOrAppend("", V1));
+ QTest::ignoreMessage(QtMsgType::QtWarningMsg, re);
+ QVERIFY(!h1.replaceOrAppend(v1, "foo\x08"));
+}
+
+QTEST_MAIN(tst_QHttpHeaders)
+#include "tst_qhttpheaders.moc"
diff --git a/tests/auto/network/access/qhttpnetworkconnection/CMakeLists.txt b/tests/auto/network/access/qhttpnetworkconnection/CMakeLists.txt
index 29b345b0db..679990062f 100644
--- a/tests/auto/network/access/qhttpnetworkconnection/CMakeLists.txt
+++ b/tests/auto/network/access/qhttpnetworkconnection/CMakeLists.txt
@@ -1,4 +1,11 @@
-# Generated from qhttpnetworkconnection.pro.
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
+
+if(NOT QT_BUILD_STANDALONE_TESTS AND NOT QT_BUILDING_QT)
+ cmake_minimum_required(VERSION 3.16)
+ project(tst_qhttpnetworkconnection LANGUAGES CXX)
+ find_package(Qt6BuildInternals REQUIRED COMPONENTS STANDALONE_TEST)
+endif()
if(NOT QT_FEATURE_private_tests)
return()
@@ -11,12 +18,8 @@ endif()
qt_internal_add_test(tst_qhttpnetworkconnection
SOURCES
tst_qhttpnetworkconnection.cpp
- PUBLIC_LIBRARIES
+ LIBRARIES
Qt::CorePrivate
Qt::NetworkPrivate
- QT_TEST_SERVER_LIST "apache2" # special case
+ QT_TEST_SERVER_LIST "apache2"
)
-
-#### Keys ignored in scope 1:.:.:qhttpnetworkconnection.pro:<TRUE>:
-# QT_TEST_SERVER_LIST = "apache2"
-# _REQUIREMENTS = "qtConfig(private_tests)"
diff --git a/tests/auto/network/access/qhttpnetworkconnection/tst_qhttpnetworkconnection.cpp b/tests/auto/network/access/qhttpnetworkconnection/tst_qhttpnetworkconnection.cpp
index 945111bfb8..decd442164 100644
--- a/tests/auto/network/access/qhttpnetworkconnection/tst_qhttpnetworkconnection.cpp
+++ b/tests/auto/network/access/qhttpnetworkconnection/tst_qhttpnetworkconnection.cpp
@@ -1,30 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
#include <QTest>
@@ -150,7 +125,7 @@ void tst_QHttpNetworkConnection::head()
QFETCH(QString, statusString);
QFETCH(int, contentLength);
- QHttpNetworkConnection connection(host, port, encrypt);
+ QHttpNetworkConnection connection(QHttpNetworkConnectionPrivate::defaultHttpChannelCount, host, port, encrypt);
QCOMPARE(connection.port(), port);
QCOMPARE(connection.hostName(), host);
QCOMPARE(connection.isSsl(), encrypt);
@@ -200,7 +175,7 @@ void tst_QHttpNetworkConnection::get()
QFETCH(int, contentLength);
QFETCH(int, downloadSize);
- QHttpNetworkConnection connection(host, port, encrypt);
+ QHttpNetworkConnection connection(QHttpNetworkConnectionPrivate::defaultHttpChannelCount, host, port, encrypt);
QCOMPARE(connection.port(), port);
QCOMPARE(connection.hostName(), host);
QCOMPARE(connection.isSsl(), encrypt);
@@ -266,7 +241,7 @@ void tst_QHttpNetworkConnection::put()
QFETCH(QString, data);
QFETCH(bool, succeed);
- QHttpNetworkConnection connection(host, port, encrypt);
+ QHttpNetworkConnection connection(QHttpNetworkConnectionPrivate::defaultHttpChannelCount, host, port, encrypt);
QCOMPARE(connection.port(), port);
QCOMPARE(connection.hostName(), host);
QCOMPARE(connection.isSsl(), encrypt);
@@ -348,7 +323,7 @@ void tst_QHttpNetworkConnection::post()
QFETCH(int, contentLength);
QFETCH(int, downloadSize);
- QHttpNetworkConnection connection(host, port, encrypt);
+ QHttpNetworkConnection connection(QHttpNetworkConnectionPrivate::defaultHttpChannelCount, host, port, encrypt);
QCOMPARE(connection.port(), port);
QCOMPARE(connection.hostName(), host);
QCOMPARE(connection.isSsl(), encrypt);
@@ -475,7 +450,7 @@ void tst_QHttpNetworkConnection::get401()
QFETCH(QString, password);
QFETCH(int, statusCode);
- QHttpNetworkConnection connection(host, port, encrypt);
+ QHttpNetworkConnection connection(QHttpNetworkConnectionPrivate::defaultHttpChannelCount, host, port, encrypt);
QCOMPARE(connection.port(), port);
QCOMPARE(connection.hostName(), host);
QCOMPARE(connection.isSsl(), encrypt);
@@ -535,7 +510,7 @@ void tst_QHttpNetworkConnection::compression()
QFETCH(bool, autoCompress);
QFETCH(QString, contentCoding);
- QHttpNetworkConnection connection(host, port, encrypt);
+ QHttpNetworkConnection connection(QHttpNetworkConnectionPrivate::defaultHttpChannelCount, host, port, encrypt);
QCOMPARE(connection.port(), port);
QCOMPARE(connection.hostName(), host);
QCOMPARE(connection.isSsl(), encrypt);
@@ -609,7 +584,7 @@ void tst_QHttpNetworkConnection::ignoresslerror()
QFETCH(bool, ignoreFromSignal);
QFETCH(int, statusCode);
- QHttpNetworkConnection connection(host, port, encrypt);
+ QHttpNetworkConnection connection(QHttpNetworkConnectionPrivate::defaultHttpChannelCount, host, port, encrypt);
QCOMPARE(connection.port(), port);
QCOMPARE(connection.hostName(), host);
if (ignoreInit)
@@ -654,7 +629,7 @@ void tst_QHttpNetworkConnection::nossl()
QFETCH(bool, encrypt);
QFETCH(QNetworkReply::NetworkError, networkError);
- QHttpNetworkConnection connection(host, port, encrypt);
+ QHttpNetworkConnection connection(QHttpNetworkConnectionPrivate::defaultHttpChannelCount, host, port, encrypt);
QCOMPARE(connection.port(), port);
QCOMPARE(connection.hostName(), host);
@@ -691,7 +666,7 @@ void tst_QHttpNetworkConnection::getMultiple_data()
static bool allRepliesFinished(const QList<QHttpNetworkReply*> *_replies)
{
const QList<QHttpNetworkReply*> &replies = *_replies;
- for (int i = 0; i < replies.length(); i++)
+ for (int i = 0; i < replies.size(); i++)
if (!replies.at(i)->isFinished())
return false;
return true;
@@ -760,7 +735,7 @@ void tst_QHttpNetworkConnection::getMultipleWithPipeliningAndMultiplePriorities(
QTRY_VERIFY_WITH_TIMEOUT(allRepliesFinished(&replies), 60000);
int pipelinedCount = 0;
- for (int i = 0; i < replies.length(); i++) {
+ for (int i = 0; i < replies.size(); i++) {
QVERIFY (!(replies.at(i)->request().isPipeliningAllowed() == false
&& replies.at(i)->isPipeliningUsed()));
@@ -944,7 +919,7 @@ void tst_QHttpNetworkConnection::getAndThenDeleteObject_data()
void tst_QHttpNetworkConnection::getAndThenDeleteObject()
{
// yes, this will leak if the testcase fails. I don't care. It must not fail then :P
- QHttpNetworkConnection *connection = new QHttpNetworkConnection(httpServerName());
+ QHttpNetworkConnection *connection = new QHttpNetworkConnection(QHttpNetworkConnectionPrivate::defaultHttpChannelCount, httpServerName());
QHttpNetworkRequest request("http://" + httpServerName() + "/qtest/bigfile");
QHttpNetworkReply *reply = connection->sendRequest(request);
reply->setDownstreamLimited(true);
diff --git a/tests/auto/network/access/qhttpnetworkreply/CMakeLists.txt b/tests/auto/network/access/qhttpnetworkreply/CMakeLists.txt
index 4d35cc8a2b..b4e4a822ee 100644
--- a/tests/auto/network/access/qhttpnetworkreply/CMakeLists.txt
+++ b/tests/auto/network/access/qhttpnetworkreply/CMakeLists.txt
@@ -1,4 +1,11 @@
-# Generated from qhttpnetworkreply.pro.
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
+
+if(NOT QT_BUILD_STANDALONE_TESTS AND NOT QT_BUILDING_QT)
+ cmake_minimum_required(VERSION 3.16)
+ project(tst_qhttpnetworkreply LANGUAGES CXX)
+ find_package(Qt6BuildInternals REQUIRED COMPONENTS STANDALONE_TEST)
+endif()
if(NOT QT_FEATURE_private_tests)
return()
@@ -11,10 +18,7 @@ endif()
qt_internal_add_test(tst_qhttpnetworkreply
SOURCES
tst_qhttpnetworkreply.cpp
- PUBLIC_LIBRARIES
+ LIBRARIES
Qt::CorePrivate
Qt::NetworkPrivate
)
-
-#### Keys ignored in scope 1:.:.:qhttpnetworkreply.pro:<TRUE>:
-# _REQUIREMENTS = "qtConfig(private_tests)"
diff --git a/tests/auto/network/access/qhttpnetworkreply/tst_qhttpnetworkreply.cpp b/tests/auto/network/access/qhttpnetworkreply/tst_qhttpnetworkreply.cpp
index eca81ba4ea..e83d15fdc3 100644
--- a/tests/auto/network/access/qhttpnetworkreply/tst_qhttpnetworkreply.cpp
+++ b/tests/auto/network/access/qhttpnetworkreply/tst_qhttpnetworkreply.cpp
@@ -1,35 +1,11 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2022 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
#include <QTest>
#include <QtCore/QBuffer>
#include <QtCore/QByteArray>
+#include <QtCore/QStringBuilder>
#include "private/qhttpnetworkconnection_p.h"
@@ -101,19 +77,13 @@ void tst_QHttpNetworkReply::parseHeader()
QHttpNetworkReply reply;
reply.parseHeader(headers);
- for (int i = 0; i < fields.count(); ++i) {
+ for (int i = 0; i < fields.size(); ++i) {
//qDebug() << "field" << fields.at(i) << "value" << reply.headerField(fields.at(i)) << "expected" << values.at(i);
QString field = reply.headerField(fields.at(i).toLatin1());
QCOMPARE(field, values.at(i));
}
}
-// both constants are taken from the default settings of Apache
-// see: http://httpd.apache.org/docs/2.2/mod/core.html#limitrequestfieldsize and
-// http://httpd.apache.org/docs/2.2/mod/core.html#limitrequestfields
-const int MAX_HEADER_FIELD_SIZE = 8 * 1024;
-const int MAX_HEADER_FIELDS = 100;
-
void tst_QHttpNetworkReply::parseHeaderVerification_data()
{
QTest::addColumn<QByteArray>("headers");
@@ -131,36 +101,62 @@ void tst_QHttpNetworkReply::parseHeaderVerification_data()
QTest::newRow("missing-colon-3")
<< QByteArray("Content-Encoding: gzip\r\nContent-Length\r\n") << false;
QTest::newRow("header-field-too-long")
- << (QByteArray("Content-Type: ") + QByteArray(MAX_HEADER_FIELD_SIZE, 'a')
- + QByteArray("\r\n"))
+ << (QByteArray("Content-Type: ")
+ + QByteArray(HeaderConstants::MAX_HEADER_FIELD_SIZE, 'a') + QByteArray("\r\n"))
<< false;
QByteArray name = "Content-Type: ";
QTest::newRow("max-header-field-size")
- << (name + QByteArray(MAX_HEADER_FIELD_SIZE - name.size(), 'a') + QByteArray("\r\n"))
+ << (name + QByteArray(HeaderConstants::MAX_HEADER_FIELD_SIZE - name.size(), 'a')
+ + QByteArray("\r\n"))
<< true;
QByteArray tooManyHeaders = QByteArray("Content-Type: text/html; charset=utf-8\r\n")
- .repeated(MAX_HEADER_FIELDS + 1);
+ .repeated(HeaderConstants::MAX_HEADER_FIELDS + 1);
QTest::newRow("too-many-headers") << tooManyHeaders << false;
- QByteArray maxHeaders =
- QByteArray("Content-Type: text/html; charset=utf-8\r\n").repeated(MAX_HEADER_FIELDS);
+ QByteArray maxHeaders = QByteArray("Content-Type: text/html; charset=utf-8\r\n")
+ .repeated(HeaderConstants::MAX_HEADER_FIELDS);
QTest::newRow("max-headers") << maxHeaders << true;
- QByteArray firstValue(MAX_HEADER_FIELD_SIZE / 2, 'a');
+ QByteArray firstValue(HeaderConstants::MAX_HEADER_FIELD_SIZE / 2, 'a');
constexpr int obsFold = 1;
QTest::newRow("max-continuation-size")
<< (name + firstValue + QByteArray("\r\n ")
- + QByteArray(MAX_HEADER_FIELD_SIZE - name.size() - firstValue.size() - obsFold, 'b')
+ + QByteArray(HeaderConstants::MAX_HEADER_FIELD_SIZE - name.size()
+ - firstValue.size() - obsFold,
+ 'b')
+ QByteArray("\r\n"))
<< true;
QTest::newRow("too-long-continuation-size")
<< (name + firstValue + QByteArray("\r\n ")
- + QByteArray(MAX_HEADER_FIELD_SIZE - name.size() - firstValue.size() - obsFold + 1,
+ + QByteArray(HeaderConstants::MAX_HEADER_FIELD_SIZE - name.size()
+ - firstValue.size() - obsFold + 1,
'b')
+ QByteArray("\r\n"))
<< false;
+
+ auto appendLongHeaderElement = [](QByteArray &result, QByteArrayView name) {
+ const qsizetype size = result.size();
+ result += name;
+ result += ": ";
+ result.resize(size + HeaderConstants::MAX_HEADER_FIELD_SIZE, 'a');
+ };
+ QByteArray longHeader;
+ constexpr qsizetype TrailerLength = sizeof("\r\n\r\n") - 1; // we ignore the trailing newlines
+ longHeader.reserve(HeaderConstants::MAX_TOTAL_HEADER_SIZE + TrailerLength + 1);
+ appendLongHeaderElement(longHeader, "Location");
+ longHeader += "\r\n";
+ appendLongHeaderElement(longHeader, "WWW-Authenticate");
+ longHeader += "\r\nProxy-Authenticate: ";
+ longHeader.resize(HeaderConstants::MAX_TOTAL_HEADER_SIZE, 'a');
+ longHeader += "\r\n\r\n";
+
+ // Test with headers which are just large enough to fit our MAX_TOTAL_HEADER_SIZE limit:
+ QTest::newRow("total-header-close-to-max-size") << longHeader << true;
+ // Now add another character to make the total header size exceed the limit:
+ longHeader.insert(HeaderConstants::MAX_TOTAL_HEADER_SIZE - TrailerLength, 'a');
+ QTest::newRow("total-header-too-large") << longHeader << false;
}
void tst_QHttpNetworkReply::parseHeaderVerification()
diff --git a/tests/auto/network/access/qnetworkaccessmanager/CMakeLists.txt b/tests/auto/network/access/qnetworkaccessmanager/CMakeLists.txt
index 1d819c3784..b0fe6eda46 100644
--- a/tests/auto/network/access/qnetworkaccessmanager/CMakeLists.txt
+++ b/tests/auto/network/access/qnetworkaccessmanager/CMakeLists.txt
@@ -1,12 +1,19 @@
-# Generated from qnetworkaccessmanager.pro.
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
#####################################################################
## tst_qnetworkaccessmanager Test:
#####################################################################
+if(NOT QT_BUILD_STANDALONE_TESTS AND NOT QT_BUILDING_QT)
+ cmake_minimum_required(VERSION 3.16)
+ project(tst_qnetworkaccessmanager LANGUAGES CXX)
+ find_package(Qt6BuildInternals REQUIRED COMPONENTS STANDALONE_TEST)
+endif()
+
qt_internal_add_test(tst_qnetworkaccessmanager
SOURCES
tst_qnetworkaccessmanager.cpp
- PUBLIC_LIBRARIES
+ LIBRARIES
Qt::Network
)
diff --git a/tests/auto/network/access/qnetworkaccessmanager/tst_qnetworkaccessmanager.cpp b/tests/auto/network/access/qnetworkaccessmanager/tst_qnetworkaccessmanager.cpp
index fcafea0125..43db6d5841 100644
--- a/tests/auto/network/access/qnetworkaccessmanager/tst_qnetworkaccessmanager.cpp
+++ b/tests/auto/network/access/qnetworkaccessmanager/tst_qnetworkaccessmanager.cpp
@@ -1,30 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
#include <QTest>
diff --git a/tests/auto/network/access/qnetworkcachemetadata/CMakeLists.txt b/tests/auto/network/access/qnetworkcachemetadata/CMakeLists.txt
index 3a8bef0aa2..2aa918c49c 100644
--- a/tests/auto/network/access/qnetworkcachemetadata/CMakeLists.txt
+++ b/tests/auto/network/access/qnetworkcachemetadata/CMakeLists.txt
@@ -1,12 +1,19 @@
-# Generated from qnetworkcachemetadata.pro.
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
#####################################################################
## tst_qnetworkcachemetadata Test:
#####################################################################
+if(NOT QT_BUILD_STANDALONE_TESTS AND NOT QT_BUILDING_QT)
+ cmake_minimum_required(VERSION 3.16)
+ project(tst_qnetworkcachemetadata LANGUAGES CXX)
+ find_package(Qt6BuildInternals REQUIRED COMPONENTS STANDALONE_TEST)
+endif()
+
qt_internal_add_test(tst_qnetworkcachemetadata
SOURCES
tst_qnetworkcachemetadata.cpp
- PUBLIC_LIBRARIES
+ LIBRARIES
Qt::Network
)
diff --git a/tests/auto/network/access/qnetworkcachemetadata/tst_qnetworkcachemetadata.cpp b/tests/auto/network/access/qnetworkcachemetadata/tst_qnetworkcachemetadata.cpp
index e35ce84898..f811943dea 100644
--- a/tests/auto/network/access/qnetworkcachemetadata/tst_qnetworkcachemetadata.cpp
+++ b/tests/auto/network/access/qnetworkcachemetadata/tst_qnetworkcachemetadata.cpp
@@ -1,30 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
#include <QTest>
diff --git a/tests/auto/network/access/qnetworkcookie/CMakeLists.txt b/tests/auto/network/access/qnetworkcookie/CMakeLists.txt
index 0460ff3235..91773a83fd 100644
--- a/tests/auto/network/access/qnetworkcookie/CMakeLists.txt
+++ b/tests/auto/network/access/qnetworkcookie/CMakeLists.txt
@@ -1,12 +1,19 @@
-# Generated from qnetworkcookie.pro.
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
#####################################################################
## tst_qnetworkcookie Test:
#####################################################################
+if(NOT QT_BUILD_STANDALONE_TESTS AND NOT QT_BUILDING_QT)
+ cmake_minimum_required(VERSION 3.16)
+ project(tst_qnetworkcookie LANGUAGES CXX)
+ find_package(Qt6BuildInternals REQUIRED COMPONENTS STANDALONE_TEST)
+endif()
+
qt_internal_add_test(tst_qnetworkcookie
SOURCES
tst_qnetworkcookie.cpp
- PUBLIC_LIBRARIES
+ LIBRARIES
Qt::Network
)
diff --git a/tests/auto/network/access/qnetworkcookie/tst_qnetworkcookie.cpp b/tests/auto/network/access/qnetworkcookie/tst_qnetworkcookie.cpp
index 7f1b8e6369..438c5e6983 100644
--- a/tests/auto/network/access/qnetworkcookie/tst_qnetworkcookie.cpp
+++ b/tests/auto/network/access/qnetworkcookie/tst_qnetworkcookie.cpp
@@ -1,36 +1,13 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
#include <QTest>
-#include <QtCore/QUrl>
#include <QtNetwork/QNetworkCookie>
+#include <QtCore/QDateTime>
+#include <QtCore/QTimeZone>
+#include <QtCore/QUrl>
class tst_QNetworkCookie: public QObject
{
@@ -110,6 +87,12 @@ void tst_QNetworkCookie::parseSingleCookie_data()
{
QTest::addColumn<QString>("cookieString");
QTest::addColumn<QNetworkCookie>("expectedCookie");
+ const auto utc = [](int year, int month, int day,
+ int hour = 0, int minute = 0, int second = 0, int millis = 0) {
+ return QDateTime(QDate(year, month, day),
+ QTime(hour, minute, second, millis),
+ QTimeZone::UTC);
+ };
QNetworkCookie cookie;
cookie.setName("a");
@@ -254,140 +237,140 @@ void tst_QNetworkCookie::parseSingleCookie_data()
cookie = QNetworkCookie();
cookie.setName("a");
cookie.setValue("b");
- cookie.setExpirationDate(QDateTime(QDate(2012, 1, 29), QTime(23, 59, 59), Qt::UTC));
+ cookie.setExpirationDate(utc(2012, 1, 29, 23, 59, 59));
QTest::newRow("broken-expiration1") << "a=b; expires=Sun, 29-Jan-2012 23:59:59;" << cookie;
- cookie.setExpirationDate(QDateTime(QDate(1999, 11, 9), QTime(23, 12, 40), Qt::UTC));
+ cookie.setExpirationDate(utc(1999, 11, 9, 23, 12, 40));
QTest::newRow("expiration1") << "a=b;expires=Wednesday, 09-Nov-1999 23:12:40 GMT" << cookie;
QTest::newRow("expiration2") << "a=b;expires=Wed, 09-Nov-1999 23:12:40 GMT" << cookie;
QTest::newRow("expiration3") << "a=b; expires=Wednesday, 09-Nov-1999 23:12:40 GMT " << cookie;
QTest::newRow("expiration-utc") << "a=b;expires=Wednesday, 09-Nov-1999 23:12:40 UTC" << cookie;
- cookie.setExpirationDate(QDateTime(QDate(1989, 4, 14), QTime(3, 20, 0, 0), Qt::UTC));
+ cookie.setExpirationDate(utc(1989, 4, 14, 3, 20));
QTest::newRow("time-0") << "a=b;expires=14 Apr 89 03:20" << cookie;
- cookie.setExpirationDate(QDateTime(QDate(1989, 4, 14), QTime(3, 20, 12, 0), Qt::UTC));
+ cookie.setExpirationDate(utc(1989, 4, 14, 3, 20, 12));
QTest::newRow("time-1") << "a=b;expires=14 Apr 89 03:20:12" << cookie;
- cookie.setExpirationDate(QDateTime(QDate(1989, 4, 14), QTime(3, 20, 12, 88), Qt::UTC));
+ cookie.setExpirationDate(utc(1989, 4, 14, 3, 20, 12, 88));
QTest::newRow("time-2") << "a=b;expires=14 Apr 89 03:20:12.88" << cookie;
- cookie.setExpirationDate(QDateTime(QDate(1989, 4, 14), QTime(3, 20, 12, 88), Qt::UTC));
+ cookie.setExpirationDate(utc(1989, 4, 14, 3, 20, 12, 88));
QTest::newRow("time-3") << "a=b;expires=14 Apr 89 03:20:12.88am" << cookie;
- cookie.setExpirationDate(QDateTime(QDate(1989, 4, 14), QTime(15, 20, 12, 88), Qt::UTC));
+ cookie.setExpirationDate(utc(1989, 4, 14, 15, 20, 12, 88));
QTest::newRow("time-4") << "a=b;expires=14 Apr 89 03:20:12.88pm" << cookie;
- cookie.setExpirationDate(QDateTime(QDate(1989, 4, 14), QTime(3, 20, 12, 88), Qt::UTC));
+ cookie.setExpirationDate(utc(1989, 4, 14, 3, 20, 12, 88));
QTest::newRow("time-5") << "a=b;expires=14 Apr 89 03:20:12.88 Am" << cookie;
- cookie.setExpirationDate(QDateTime(QDate(1989, 4, 14), QTime(15, 20, 12, 88), Qt::UTC));
+ cookie.setExpirationDate(utc(1989, 4, 14, 15, 20, 12, 88));
QTest::newRow("time-6") << "a=b;expires=14 Apr 89 03:20:12.88 PM" << cookie;
- cookie.setExpirationDate(QDateTime(QDate(1989, 4, 14), QTime(15, 20, 12, 88), Qt::UTC));
+ cookie.setExpirationDate(utc(1989, 4, 14, 15, 20, 12, 88));
QTest::newRow("time-7") << "a=b;expires=14 Apr 89 3:20:12.88 PM" << cookie;
// normal months
- cookie.setExpirationDate(QDateTime(QDate(1989, 1, 1), QTime(1, 1), Qt::UTC));
+ cookie.setExpirationDate(utc(1989, 1, 1, 1, 1));
QTest::newRow("months-1") << "a=b;expires=Jan 1 89 1:1" << cookie;
- cookie.setExpirationDate(QDateTime(QDate(1989, 2, 1), QTime(1, 1), Qt::UTC));
+ cookie.setExpirationDate(utc(1989, 2, 1, 1, 1));
QTest::newRow("months-2") << "a=b;expires=Feb 1 89 1:1" << cookie;
- cookie.setExpirationDate(QDateTime(QDate(1989, 3, 1), QTime(1, 1), Qt::UTC));
+ cookie.setExpirationDate(utc(1989, 3, 1, 1, 1));
QTest::newRow("months-3") << "a=b;expires=mar 1 89 1:1" << cookie;
- cookie.setExpirationDate(QDateTime(QDate(1989, 4, 1), QTime(1, 1), Qt::UTC));
+ cookie.setExpirationDate(utc(1989, 4, 1, 1, 1));
QTest::newRow("months-4") << "a=b;expires=Apr 1 89 1:1" << cookie;
- cookie.setExpirationDate(QDateTime(QDate(1989, 5, 1), QTime(1, 1), Qt::UTC));
+ cookie.setExpirationDate(utc(1989, 5, 1, 1, 1));
QTest::newRow("months-5") << "a=b;expires=May 1 89 1:1" << cookie;
- cookie.setExpirationDate(QDateTime(QDate(1989, 6, 1), QTime(1, 1), Qt::UTC));
+ cookie.setExpirationDate(utc(1989, 6, 1, 1, 1));
QTest::newRow("months-6") << "a=b;expires=Jun 1 89 1:1" << cookie;
- cookie.setExpirationDate(QDateTime(QDate(1989, 7, 1), QTime(1, 1), Qt::UTC));
+ cookie.setExpirationDate(utc(1989, 7, 1, 1, 1));
QTest::newRow("months-7") << "a=b;expires=Jul 1 89 1:1" << cookie;
- cookie.setExpirationDate(QDateTime(QDate(1989, 8, 1), QTime(1, 1), Qt::UTC));
+ cookie.setExpirationDate(utc(1989, 8, 1, 1, 1));
QTest::newRow("months-8") << "a=b;expires=Aug 1 89 1:1" << cookie;
- cookie.setExpirationDate(QDateTime(QDate(1989, 9, 1), QTime(1, 1), Qt::UTC));
+ cookie.setExpirationDate(utc(1989, 9, 1, 1, 1));
QTest::newRow("months-9") << "a=b;expires=Sep 1 89 1:1" << cookie;
- cookie.setExpirationDate(QDateTime(QDate(1989, 10, 1), QTime(1, 1), Qt::UTC));
+ cookie.setExpirationDate(utc(1989, 10, 1, 1, 1));
QTest::newRow("months-10") << "a=b;expires=Oct 1 89 1:1" << cookie;
- cookie.setExpirationDate(QDateTime(QDate(1989, 11, 1), QTime(1, 1), Qt::UTC));
+ cookie.setExpirationDate(utc(1989, 11, 1, 1, 1));
QTest::newRow("months-11") << "a=b;expires=Nov 1 89 1:1" << cookie;
- cookie.setExpirationDate(QDateTime(QDate(1989, 12, 1), QTime(1, 1), Qt::UTC));
+ cookie.setExpirationDate(utc(1989, 12, 1, 1, 1));
QTest::newRow("months-12") << "a=b;expires=Dec 1 89 1:1" << cookie;
// extra months
- cookie.setExpirationDate(QDateTime(QDate(1989, 12, 1), QTime(1, 1), Qt::UTC));
+ cookie.setExpirationDate(utc(1989, 12, 1, 1, 1));
QTest::newRow("months-13") << "a=b;expires=December 1 89 1:1" << cookie;
QTest::newRow("months-14") << "a=b;expires=1 89 1:1 Dec" << cookie;
//cookie.setExpirationDate(QDateTime());
//QTest::newRow("months-15") << "a=b;expires=1 89 1:1 De" << cookie;
- cookie.setExpirationDate(QDateTime(QDate(2024, 2, 29), QTime(1, 1), Qt::UTC));
+ cookie.setExpirationDate(utc(2024, 2, 29, 1, 1));
QTest::newRow("months-16") << "a=b;expires=2024 29 Feb 1:1" << cookie;
- cookie.setExpirationDate(QDateTime(QDate(2024, 2, 29), QTime(1, 1), Qt::UTC));
+ cookie.setExpirationDate(utc(2024, 2, 29, 1, 1));
QTest::newRow("months-17") << "a=b;expires=Fri, 29-Feb-2024 01:01:00 GMT" << cookie;
QTest::newRow("months-18") << "a=b;expires=2024 29 Feb 1:1 GMT" << cookie;
// normal offsets
- cookie.setExpirationDate(QDateTime(QDate(1989, 1, 1), QTime(0, 0), Qt::UTC));
+ cookie.setExpirationDate(utc(1989, 1, 1));
QTest::newRow("zoneoffset-0") << "a=b;expires=Jan 1 89 8:0 PST" << cookie;
- cookie.setExpirationDate(QDateTime(QDate(1989, 1, 1), QTime(0, 0), Qt::UTC));
+ cookie.setExpirationDate(utc(1989, 1, 1));
QTest::newRow("zoneoffset-1") << "a=b;expires=Jan 1 89 8:0 PDT" << cookie;
- cookie.setExpirationDate(QDateTime(QDate(1989, 1, 1), QTime(0, 0), Qt::UTC));
+ cookie.setExpirationDate(utc(1989, 1, 1));
QTest::newRow("zoneoffset-2") << "a=b;expires=Jan 1 89 7:0 MST" << cookie;
- cookie.setExpirationDate(QDateTime(QDate(1989, 1, 1), QTime(0, 0), Qt::UTC));
+ cookie.setExpirationDate(utc(1989, 1, 1));
QTest::newRow("zoneoffset-3") << "a=b;expires=Jan 1 89 7:0 MDT" << cookie;
- cookie.setExpirationDate(QDateTime(QDate(1989, 1, 1), QTime(0, 0), Qt::UTC));
+ cookie.setExpirationDate(utc(1989, 1, 1));
QTest::newRow("zoneoffset-4") << "a=b;expires=Jan 1 89 6:0 CST" << cookie;
- cookie.setExpirationDate(QDateTime(QDate(1989, 1, 1), QTime(0, 0), Qt::UTC));
+ cookie.setExpirationDate(utc(1989, 1, 1));
QTest::newRow("zoneoffset-5") << "a=b;expires=Jan 1 89 6:0 CDT" << cookie;
- cookie.setExpirationDate(QDateTime(QDate(1989, 1, 1), QTime(0, 0), Qt::UTC));
+ cookie.setExpirationDate(utc(1989, 1, 1));
QTest::newRow("zoneoffset-6") << "a=b;expires=Jan 1 89 5:0 EST" << cookie;
- cookie.setExpirationDate(QDateTime(QDate(1989, 1, 1), QTime(0, 0), Qt::UTC));
+ cookie.setExpirationDate(utc(1989, 1, 1));
QTest::newRow("zoneoffset-7") << "a=b;expires=Jan 1 89 5:0 EDT" << cookie;
- cookie.setExpirationDate(QDateTime(QDate(1989, 1, 1), QTime(0, 0), Qt::UTC));
+ cookie.setExpirationDate(utc(1989, 1, 1));
QTest::newRow("zoneoffset-8") << "a=b;expires=Jan 1 89 4:0 AST" << cookie;
- cookie.setExpirationDate(QDateTime(QDate(1989, 1, 1), QTime(0, 0), Qt::UTC));
+ cookie.setExpirationDate(utc(1989, 1, 1));
QTest::newRow("zoneoffset-9") << "a=b;expires=Jan 1 89 3:0 NST" << cookie;
- cookie.setExpirationDate(QDateTime(QDate(1989, 1, 1), QTime(0, 0), Qt::UTC));
+ cookie.setExpirationDate(utc(1989, 1, 1));
QTest::newRow("zoneoffset-10") << "a=b;expires=Jan 1 89 0:0 GMT" << cookie;
- cookie.setExpirationDate(QDateTime(QDate(1989, 1, 1), QTime(0, 0), Qt::UTC));
+ cookie.setExpirationDate(utc(1989, 1, 1));
QTest::newRow("zoneoffset-11") << "a=b;expires=Jan 1 89 0:0 BST" << cookie;
- cookie.setExpirationDate(QDateTime(QDate(1989, 1, 2), QTime(0, 0), Qt::UTC));
+ cookie.setExpirationDate(utc(1989, 1, 2));
QTest::newRow("zoneoffset-12") << "a=b;expires=Jan 1 89 23:0 MET" << cookie;
- cookie.setExpirationDate(QDateTime(QDate(1989, 1, 2), QTime(0, 0), Qt::UTC));
+ cookie.setExpirationDate(utc(1989, 1, 2));
QTest::newRow("zoneoffset-13") << "a=b;expires=Jan 1 89 22:0 EET" << cookie;
- cookie.setExpirationDate(QDateTime(QDate(1989, 1, 2), QTime(0, 0), Qt::UTC));
+ cookie.setExpirationDate(utc(1989, 1, 2));
QTest::newRow("zoneoffset-14") << "a=b;expires=Jan 1 89 15:0 JST" << cookie;
// extra offsets
- cookie.setExpirationDate(QDateTime(QDate(1989, 1, 2), QTime(0, 0), Qt::UTC));
+ cookie.setExpirationDate(utc(1989, 1, 2));
QTest::newRow("zoneoffset-15") << "a=b;expires=Jan 1 89 15:0 JST+1" << cookie;
- cookie.setExpirationDate(QDateTime(QDate(1989, 1, 1), QTime(1, 0), Qt::UTC));
+ cookie.setExpirationDate(utc(1989, 1, 1, 1));
QTest::newRow("zoneoffset-16") << "a=b;expires=Jan 1 89 0:0 GMT+1" << cookie;
- cookie.setExpirationDate(QDateTime(QDate(1989, 1, 1), QTime(0, 0), Qt::UTC));
+ cookie.setExpirationDate(utc(1989, 1, 1));
QTest::newRow("zoneoffset-17") << "a=b;expires=Jan 1 89 1:0 GMT-1" << cookie;
- cookie.setExpirationDate(QDateTime(QDate(1989, 1, 1), QTime(1, 0), Qt::UTC));
+ cookie.setExpirationDate(utc(1989, 1, 1, 1));
QTest::newRow("zoneoffset-18") << "a=b;expires=Jan 1 89 0:0 GMT+01" << cookie;
- cookie.setExpirationDate(QDateTime(QDate(1989, 1, 1), QTime(1, 5), Qt::UTC));
+ cookie.setExpirationDate(utc(1989, 1, 1, 1, 5));
QTest::newRow("zoneoffset-19") << "a=b;expires=Jan 1 89 0:0 GMT+0105" << cookie;
- cookie.setExpirationDate(QDateTime(QDate(1989, 1, 1), QTime(0, 0), Qt::UTC));
+ cookie.setExpirationDate(utc(1989, 1, 1));
QTest::newRow("zoneoffset-20") << "a=b;expires=Jan 1 89 0:0 GMT+015" << cookie;
- cookie.setExpirationDate(QDateTime(QDate(1989, 1, 1), QTime(0, 0), Qt::UTC));
+ cookie.setExpirationDate(utc(1989, 1, 1));
QTest::newRow("zoneoffset-21") << "a=b;expires=Jan 1 89 0:0 GM" << cookie;
- cookie.setExpirationDate(QDateTime(QDate(1989, 1, 1), QTime(0, 0), Qt::UTC));
+ cookie.setExpirationDate(utc(1989, 1, 1));
QTest::newRow("zoneoffset-22") << "a=b;expires=Jan 1 89 0:0 GMT" << cookie;
// offsets from gmt
- cookie.setExpirationDate(QDateTime(QDate(1989, 1, 1), QTime(1, 0), Qt::UTC));
+ cookie.setExpirationDate(utc(1989, 1, 1, 1));
QTest::newRow("zoneoffset-23") << "a=b;expires=Jan 1 89 0:0 +1" << cookie;
- cookie.setExpirationDate(QDateTime(QDate(1989, 1, 1), QTime(1, 0), Qt::UTC));
+ cookie.setExpirationDate(utc(1989, 1, 1, 1));
QTest::newRow("zoneoffset-24") << "a=b;expires=Jan 1 89 0:0 +01" << cookie;
- cookie.setExpirationDate(QDateTime(QDate(1989, 1, 1), QTime(1, 1), Qt::UTC));
+ cookie.setExpirationDate(utc(1989, 1, 1, 1, 1));
QTest::newRow("zoneoffset-25") << "a=b;expires=Jan 1 89 0:0 +0101" << cookie;
- cookie.setExpirationDate(QDateTime(QDate(1989, 1, 1), QTime(0, 0), Qt::UTC));
+ cookie.setExpirationDate(utc(1989, 1, 1));
QTest::newRow("zoneoffset-26") << "a=b;expires=Jan 1 89 1:0 -1" << cookie;
// Y2k
- cookie.setExpirationDate(QDateTime(QDate(2000, 1, 1), QTime(0, 0), Qt::UTC));
+ cookie.setExpirationDate(utc(2000, 1, 1));
QTest::newRow("year-0") << "a=b;expires=Jan 1 00 0:0" << cookie;
- cookie.setExpirationDate(QDateTime(QDate(1970, 1, 1), QTime(0, 0), Qt::UTC));
+ cookie.setExpirationDate(utc(1970, 1, 1));
QTest::newRow("year-1") << "a=b;expires=Jan 1 70 0:0" << cookie;
- cookie.setExpirationDate(QDateTime(QDate(1971, 1, 1), QTime(0, 0), Qt::UTC));
+ cookie.setExpirationDate(utc(1971, 1, 1));
QTest::newRow("year-2") << "a=b;expires=Jan 1 71 0:0" << cookie;
// Day, month, year
- cookie.setExpirationDate(QDateTime(QDate(2013, 1, 2), QTime(0, 0), Qt::UTC));
+ cookie.setExpirationDate(utc(2013, 1, 2));
QTest::newRow("date-0") << "a=b;expires=Jan 2 13 0:0" << cookie;
QTest::newRow("date-1") << "a=b;expires=1-2-13 0:0" << cookie;
QTest::newRow("date-2") << "a=b;expires=1/2/13 0:0" << cookie;
@@ -397,141 +380,141 @@ void tst_QNetworkCookie::parseSingleCookie_data()
QTest::newRow("date-6") << "a=b;expires=1/2/13 0:0" << cookie;
// Known Year, determine month and day
- cookie.setExpirationDate(QDateTime(QDate(1995, 1, 13), QTime(0, 0), Qt::UTC));
+ cookie.setExpirationDate(utc(1995, 1, 13));
QTest::newRow("knownyear-0") << "a=b;expires=13/1/95 0:0" << cookie;
QTest::newRow("knownyear-1") << "a=b;expires=95/13/1 0:0" << cookie;
QTest::newRow("knownyear-2") << "a=b;expires=1995/1/13 0:0" << cookie;
QTest::newRow("knownyear-3") << "a=b;expires=1995/13/1 0:0" << cookie;
- cookie.setExpirationDate(QDateTime(QDate(1995, 1, 2), QTime(0, 0), Qt::UTC));
+ cookie.setExpirationDate(utc(1995, 1, 2));
QTest::newRow("knownyear-4") << "a=b;expires=1/2/95 0:0" << cookie;
QTest::newRow("knownyear-5") << "a=b;expires=95/1/2 0:0" << cookie;
// Known Year, Known day, determining month
- cookie.setExpirationDate(QDateTime(QDate(1995, 1, 13), QTime(0, 0), Qt::UTC));
+ cookie.setExpirationDate(utc(1995, 1, 13));
QTest::newRow("knownYD-0") << "a=b;expires=13/1/95 0:0" << cookie;
QTest::newRow("knownYD-1") << "a=b;expires=1/13/95 0:0" << cookie;
QTest::newRow("knownYD-2") << "a=b;expires=95/13/1 0:0" << cookie;
QTest::newRow("knownYD-3") << "a=b;expires=95/1/13 0:0" << cookie;
// Month comes before Year
- cookie.setExpirationDate(QDateTime(QDate(2021, 03, 26), QTime(0, 0), Qt::UTC));
+ cookie.setExpirationDate(utc(2021, 03, 26));
QTest::newRow("month-0") << "a=b;expires=26/03/21 0:0" << cookie;
- cookie.setExpirationDate(QDateTime(QDate(2015, 12, 30), QTime(16, 25, 0, 0), Qt::UTC));
+ cookie.setExpirationDate(utc(2015, 12, 30, 16, 25));
QTest::newRow("month-1") << "a=b;expires=wed 16:25pm December 2015 30" << cookie;
- cookie.setExpirationDate(QDateTime(QDate(2031, 11, 11), QTime(16, 25, 0, 0), Qt::UTC));
+ cookie.setExpirationDate(utc(2031, 11, 11, 16, 25));
QTest::newRow("month-2") << "a=b;expires=16:25 11 31 11" << cookie;
// The very ambiguous cases
// Matching Firefox's behavior of guessing month, day, year in those cases
- cookie.setExpirationDate(QDateTime(QDate(2013, 10, 2), QTime(0, 0), Qt::UTC));
+ cookie.setExpirationDate(utc(2013, 10, 2));
QTest::newRow("ambiguousd-0") << "a=b;expires=10/2/13 0:0" << cookie;
- cookie.setExpirationDate(QDateTime(QDate(2013, 2, 10), QTime(0, 0), Qt::UTC));
+ cookie.setExpirationDate(utc(2013, 2, 10));
QTest::newRow("ambiguousd-1") << "a=b;expires=2/10/13 0:0" << cookie;
- cookie.setExpirationDate(QDateTime(QDate(2010, 2, 3), QTime(0, 0), Qt::UTC));
+ cookie.setExpirationDate(utc(2010, 2, 3));
QTest::newRow("ambiguousd-2") << "a=b;expires=2/3/10 0:0" << cookie;
// FYI If you try these in Firefox it won't set a cookie for the following two string
// because 03 is turned into the year at which point it is expired
- cookie.setExpirationDate(QDateTime(QDate(2003, 2, 10), QTime(0, 0), Qt::UTC));
+ cookie.setExpirationDate(utc(2003, 2, 10));
QTest::newRow("ambiguousd-3") << "a=b;expires=2/10/3 0:0" << cookie;
- cookie.setExpirationDate(QDateTime(QDate(2003, 10, 2), QTime(0, 0), Qt::UTC));
+ cookie.setExpirationDate(utc(2003, 10, 2));
QTest::newRow("ambiguousd-4") << "a=b;expires=10/2/3 0:0" << cookie;
// These are the cookies that firefox's source says it can parse
- cookie.setExpirationDate(QDateTime(QDate(1989, 4, 14), QTime(3, 20, 0, 0), Qt::UTC));
+ cookie.setExpirationDate(utc(1989, 4, 14, 3, 20));
QTest::newRow("firefox-0") << "a=b;expires=14 Apr 89 03:20" << cookie;
- cookie.setExpirationDate(QDateTime(QDate(1989, 4, 14), QTime(3, 20, 0, 0), Qt::UTC));
+ cookie.setExpirationDate(utc(1989, 4, 14, 3, 20));
QTest::newRow("firefox-1") << "a=b;expires=14 Apr 89 03:20 GMT" << cookie;
- cookie.setExpirationDate(QDateTime(QDate(1989, 3, 17), QTime(4, 1, 33, 0), Qt::UTC));
+ cookie.setExpirationDate(utc(1989, 3, 17, 4, 1, 33));
QTest::newRow("firefox-2") << "a=b;expires=Fri, 17 Mar 89 4:01:33" << cookie;
- cookie.setExpirationDate(QDateTime(QDate(1989, 3, 17), QTime(4, 1, 0, 0), Qt::UTC));
+ cookie.setExpirationDate(utc(1989, 3, 17, 4, 1));
QTest::newRow("firefox-3") << "a=b;expires=Fri, 17 Mar 89 4:01 GMT" << cookie;
- cookie.setExpirationDate(QDateTime(QDate(1989, 1, 16), QTime(16-8, 12, 0, 0), Qt::UTC));
+ cookie.setExpirationDate(utc(1989, 1, 16, 16-8, 12));
QTest::newRow("firefox-4") << "a=b;expires=Mon Jan 16 16:12 PDT 1989" << cookie;
- cookie.setExpirationDate(QDateTime(QDate(1989, 1, 16), QTime(17, 42, 0, 0), Qt::UTC));
+ cookie.setExpirationDate(utc(1989, 1, 16, 17, 42));
QTest::newRow("firefox-5") << "a=b;expires=Mon Jan 16 16:12 +0130 1989" << cookie;
- cookie.setExpirationDate(QDateTime(QDate(1992, 5, 6), QTime(16-9, 41, 0, 0), Qt::UTC));
+ cookie.setExpirationDate(utc(1992, 5, 6, 16-9, 41));
QTest::newRow("firefox-6") << "a=b;expires=6 May 1992 16:41-JST (Wednesday)" << cookie;
- cookie.setExpirationDate(QDateTime(QDate(1993, 8, 22), QTime(10, 59, 12, 82), Qt::UTC));
+ cookie.setExpirationDate(utc(1993, 8, 22, 10, 59, 12, 82));
QTest::newRow("firefox-7") << "a=b;expires=22-AUG-1993 10:59:12.82" << cookie;
- cookie.setExpirationDate(QDateTime(QDate(1993, 8, 22), QTime(22, 59, 0, 0), Qt::UTC));
+ cookie.setExpirationDate(utc(1993, 8, 22, 22, 59));
QTest::newRow("firefox-8") << "a=b;expires=22-AUG-1993 10:59pm" << cookie;
- cookie.setExpirationDate(QDateTime(QDate(1993, 8, 22), QTime(12, 59, 0, 0), Qt::UTC));
+ cookie.setExpirationDate(utc(1993, 8, 22, 12, 59));
QTest::newRow("firefox-9") << "a=b;expires=22-AUG-1993 12:59am" << cookie;
- cookie.setExpirationDate(QDateTime(QDate(1993, 8, 22), QTime(12, 59, 0, 0), Qt::UTC));
+ cookie.setExpirationDate(utc(1993, 8, 22, 12, 59));
QTest::newRow("firefox-10") << "a=b;expires=22-AUG-1993 12:59 PM" << cookie;
- cookie.setExpirationDate(QDateTime(QDate(1995, 8, 4), QTime(15, 54, 0, 0), Qt::UTC));
+ cookie.setExpirationDate(utc(1995, 8, 4, 15, 54));
QTest::newRow("firefox-11") << "a=b;expires=Friday, August 04, 1995 3:54 PM" << cookie;
- cookie.setExpirationDate(QDateTime(QDate(1995, 6, 21), QTime(16, 24, 34, 0), Qt::UTC));
+ cookie.setExpirationDate(utc(1995, 6, 21, 16, 24, 34));
QTest::newRow("firefox-12") << "a=b;expires=06/21/95 04:24:34 PM" << cookie;
- cookie.setExpirationDate(QDateTime(QDate(1995, 6, 20), QTime(21, 7, 0, 0), Qt::UTC));
+ cookie.setExpirationDate(utc(1995, 6, 20, 21, 7));
QTest::newRow("firefox-13") << "a=b;expires=20/06/95 21:07" << cookie;
- cookie.setExpirationDate(QDateTime(QDate(1995, 6, 8), QTime(19-5, 32, 48, 0), Qt::UTC));
+ cookie.setExpirationDate(utc(1995, 6, 8, 19-5, 32, 48));
QTest::newRow("firefox-14") << "a=b;expires=95-06-08 19:32:48 EDT" << cookie;
// Edge cases caught by fuzzing
// These are about the default cause creates dates that don't exits
- cookie.setExpirationDate(QDateTime(QDate(2030, 2, 25), QTime(1, 1, 0, 0), Qt::UTC));
+ cookie.setExpirationDate(utc(2030, 2, 25, 1, 1));
QTest::newRow("fuzz-0") << "a=b; expires=30 -000002 1:1 25;" << cookie;
- cookie.setExpirationDate(QDateTime(QDate(2031, 11, 20), QTime(1, 1, 0, 0), Qt::UTC));
+ cookie.setExpirationDate(utc(2031, 11, 20, 1, 1));
QTest::newRow("fuzz-1") << "a=b; expires=31 11 20 1:1;" << cookie;
// April only has 30 days
- cookie.setExpirationDate(QDateTime(QDate(2031, 4, 30), QTime(1, 1, 0, 0), Qt::UTC));
+ cookie.setExpirationDate(utc(2031, 4, 30, 1, 1));
QTest::newRow("fuzz-2") << "a=b; expires=31 30 4 1:1" << cookie;
// 9 must be the month so 31 can't be the day
- cookie.setExpirationDate(QDateTime(QDate(2031, 9, 21), QTime(1, 1, 0, 0), Qt::UTC));
+ cookie.setExpirationDate(utc(2031, 9, 21, 1, 1));
QTest::newRow("fuzz-3") << "a=b; expires=31 21 9 1:1" << cookie;
// Year is known, then fallback to defaults of filling in month and day
- cookie.setExpirationDate(QDateTime(QDate(2031, 11, 1), QTime(1, 1, 0, 0), Qt::UTC));
+ cookie.setExpirationDate(utc(2031, 11, 1, 1, 1));
QTest::newRow("fuzz-4") << "a=b; expires=31 11 01 1:1" << cookie;
// 2 must be the month so 30 can't be the day
- cookie.setExpirationDate(QDateTime(QDate(2030, 2, 20), QTime(1, 1, 0, 0), Qt::UTC));
+ cookie.setExpirationDate(utc(2030, 2, 20, 1, 1));
QTest::newRow("fuzz-5") << "a=b; expires=30 02 20 1:1" << cookie;
- cookie.setExpirationDate(QDateTime(QDate(2021, 12, 22), QTime(1, 1, 0, 0), Qt::UTC));
+ cookie.setExpirationDate(utc(2021, 12, 22, 1, 1));
QTest::newRow("fuzz-6") << "a=b; expires=2021 12 22 1:1" << cookie;
- cookie.setExpirationDate(QDateTime(QDate(2029, 2, 23), QTime(1, 1, 0, 0), Qt::UTC));
+ cookie.setExpirationDate(utc(2029, 2, 23, 1, 1));
QTest::newRow("fuzz-7") << "a=b; expires=29 23 Feb 1:1" << cookie;
// 11 and 6 don't have 31 days
- cookie.setExpirationDate(QDateTime(QDate(2031, 11, 06), QTime(1, 1, 0, 0), Qt::UTC));
+ cookie.setExpirationDate(utc(2031, 11, 06, 1, 1));
QTest::newRow("fuzz-8") << "a=b; expires=31 11 06 1:1" << cookie;
// two-digit years:
// from 70 until 99, we assume 20th century
- cookie.setExpirationDate(QDateTime(QDate(1999, 11, 9), QTime(23, 12, 40), Qt::UTC));
+ cookie.setExpirationDate(utc(1999, 11, 9, 23, 12, 40));
QTest::newRow("expiration-2digit1") << "a=b; expires=Wednesday, 09-Nov-99 23:12:40 GMT " << cookie;
- cookie.setExpirationDate(QDateTime(QDate(1970, 1, 1), QTime(23, 12, 40), Qt::UTC));
+ cookie.setExpirationDate(utc(1970, 1, 1, 23, 12, 40));
QTest::newRow("expiration-2digit2") << "a=b; expires=Thursday, 01-Jan-70 23:12:40 GMT " << cookie;
// from 00 until 69, we assume 21st century
- cookie.setExpirationDate(QDateTime(QDate(2000, 1, 1), QTime(23, 12, 40), Qt::UTC));
+ cookie.setExpirationDate(utc(2000, 1, 1, 23, 12, 40));
QTest::newRow("expiration-2digit3") << "a=b; expires=Saturday, 01-Jan-00 23:12:40 GMT " << cookie;
- cookie.setExpirationDate(QDateTime(QDate(2020, 1, 1), QTime(23, 12, 40), Qt::UTC));
+ cookie.setExpirationDate(utc(2020, 1, 1, 23, 12, 40));
QTest::newRow("expiration-2digit4") << "a=b; expires=Wednesday, 01-Jan-20 23:12:40 GMT " << cookie;
- cookie.setExpirationDate(QDateTime(QDate(2069, 1, 1), QTime(23, 12, 40), Qt::UTC));
+ cookie.setExpirationDate(utc(2069, 1, 1, 23, 12, 40));
QTest::newRow("expiration-2digit5") << "a=b; expires=Wednesday, 01-Jan-69 23:12:40 GMT " << cookie;
- cookie.setExpirationDate(QDateTime(QDate(1999, 11, 9), QTime(23, 12, 40), Qt::UTC));
+ cookie.setExpirationDate(utc(1999, 11, 9, 23, 12, 40));
cookie.setPath("/");
QTest::newRow("expires+path") << "a=b; expires=Wed, 09-Nov-1999 23:12:40 GMT; path=/" << cookie;
@@ -544,7 +527,7 @@ void tst_QNetworkCookie::parseSingleCookie_data()
// cookies obtained from the network:
cookie = QNetworkCookie("__siteid", "1");
cookie.setPath("/");
- cookie.setExpirationDate(QDateTime(QDate(9999, 12, 31), QTime(23, 59, 59), Qt::UTC));
+ cookie.setExpirationDate(utc(9999, 12, 31, 23, 59, 59));
QTest::newRow("network2") << "__siteid=1; expires=Fri, 31-Dec-9999 23:59:59 GMT; path=/" << cookie;
cookie = QNetworkCookie("YM.LC", "v=2&m=9993_262838_159_1558_1063_0_5649_4012_3776161073,9426_260205_549_1295_1336_0_5141_4738_3922731647,6733_258196_952_1364_643_0_3560_-1_0,3677_237633_1294_1294_19267_0_3244_29483_4102206176,1315_235149_1693_1541_941_0_3224_1691_1861378060,1858_214311_2100_1298_19538_0_2873_30900_716411652,6258_212007_2506_1285_1017_0_2868_3606_4288540264,3743_207884_2895_1362_2759_0_2545_7114_3388520216,2654_205253_3257_1297_1332_0_2504_4682_3048534803,1891_184881_3660_1291_19079_0_978_29178_2592538685&f=1&n=20&s=date&o=down&e=1196548712&b=Inbox&u=removed");
@@ -554,13 +537,13 @@ void tst_QNetworkCookie::parseSingleCookie_data()
cookie = QNetworkCookie("__ac", "\"c2hhdXNtYW46U2FTYW80Wm8%3D\"");
cookie.setPath("/");
- cookie.setExpirationDate(QDateTime(QDate(2008, 8, 30), QTime(20, 21, 49), Qt::UTC));
+ cookie.setExpirationDate(utc(2008, 8, 30, 20, 21, 49));
QTest::newRow("network4") << "__ac=\"c2hhdXNtYW46U2FTYW80Wm8%3D\"; Path=/; Expires=Sat, 30 Aug 2008 20:21:49 +0000" << cookie;
// linkedin.com sends cookies in quotes and expects the cookie in quotes
cookie = QNetworkCookie("leo_auth_token", "\"GST:UroVXaxYA3sVSkoVjMNH9bj4dZxVzK2yekgrAUxMfUsyLTNyPjoP60:1298974875:b675566ae32ab36d7a708c0efbf446a5c22b9fca\"");
cookie.setPath("/");
- cookie.setExpirationDate(QDateTime(QDate(2011, 3, 1), QTime(10, 51, 14), Qt::UTC));
+ cookie.setExpirationDate(utc(2011, 3, 1, 10, 51, 14));
QTest::newRow("network5") << "leo_auth_token=\"GST:UroVXaxYA3sVSkoVjMNH9bj4dZxVzK2yekgrAUxMfUsyLTNyPjoP60:1298974875:b675566ae32ab36d7a708c0efbf446a5c22b9fca\"; Version=1; Max-Age=1799; Expires=Tue, 01-Mar-2011 10:51:14 GMT; Path=/" << cookie;
// cookie containing JSON data (illegal for server, client should accept) - QTBUG-26002
@@ -578,11 +561,11 @@ void tst_QNetworkCookie::parseSingleCookie()
QList<QNetworkCookie> result = QNetworkCookie::parseCookies(cookieString.toUtf8());
//QEXPECT_FAIL("network2", "QDateTime parsing problem: the date is beyond year 8000", Abort);
- QCOMPARE(result.count(), 1);
+ QCOMPARE(result.size(), 1);
QCOMPARE(result.at(0), expectedCookie);
result = QNetworkCookie::parseCookies(result.at(0).toRawForm());
- QCOMPARE(result.count(), 1);
+ QCOMPARE(result.size(), 1);
// Drop any millisecond information, if there's any
QDateTime dt = expectedCookie.expirationDate();
@@ -636,7 +619,7 @@ void tst_QNetworkCookie::parseMultipleCookies_data()
cookie = QNetworkCookie("id", "51706646077999719");
cookie.setDomain(".bluestreak.com");
cookie.setPath("/");
- cookie.setExpirationDate(QDateTime(QDate(2017, 12, 05), QTime(9, 11, 7), Qt::UTC));
+ cookie.setExpirationDate(QDateTime(QDate(2017, 12, 05), QTime(9, 11, 7), QTimeZone::UTC));
list << cookie;
cookie.setName("bb");
cookie.setValue("\\\"K14144t\\\"_AAQ\\\"ototrK_A_ttot44AQ4KwoRQtoto|");
@@ -655,8 +638,8 @@ void tst_QNetworkCookie::parseMultipleCookies_data()
cookieB.setValue("d");
// NewLine
- cookieA.setExpirationDate(QDateTime(QDate(2009, 3, 10), QTime(7, 0, 0, 0), Qt::UTC));
- cookieB.setExpirationDate(QDateTime(QDate(2009, 3, 20), QTime(7, 0, 0, 0), Qt::UTC));
+ cookieA.setExpirationDate(QDateTime(QDate(2009, 3, 10), QTime(7, 0), QTimeZone::UTC));
+ cookieB.setExpirationDate(QDateTime(QDate(2009, 3, 20), QTime(7, 0), QTimeZone::UTC));
list = QList<QNetworkCookie>() << cookieA << cookieB;
QTest::newRow("real-0") << "a=b; expires=Tue Mar 10 07:00:00 2009 GMT\nc=d; expires=Fri Mar 20 07:00:00 2009 GMT" << list;
QTest::newRow("real-1") << "a=b; expires=Tue Mar 10 07:00:00 2009 GMT\n\nc=d; expires=Fri Mar 20 07:00:00 2009 GMT" << list;
diff --git a/tests/auto/network/access/qnetworkcookiejar/CMakeLists.txt b/tests/auto/network/access/qnetworkcookiejar/CMakeLists.txt
index 55f30633ee..0d74a1d84d 100644
--- a/tests/auto/network/access/qnetworkcookiejar/CMakeLists.txt
+++ b/tests/auto/network/access/qnetworkcookiejar/CMakeLists.txt
@@ -1,16 +1,23 @@
-# Generated from qnetworkcookiejar.pro.
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
#####################################################################
## tst_qnetworkcookiejar Test:
#####################################################################
+if(NOT QT_BUILD_STANDALONE_TESTS AND NOT QT_BUILDING_QT)
+ cmake_minimum_required(VERSION 3.16)
+ project(tst_qnetworkcookiejar LANGUAGES CXX)
+ find_package(Qt6BuildInternals REQUIRED COMPONENTS STANDALONE_TEST)
+endif()
+
# Collect test data
-list(APPEND test_data "parser.json")
+list(APPEND test_data "parser.json" "testdata/publicsuffix/public_suffix_list.dafsa")
qt_internal_add_test(tst_qnetworkcookiejar
SOURCES
tst_qnetworkcookiejar.cpp
- PUBLIC_LIBRARIES
+ LIBRARIES
Qt::CorePrivate
Qt::Network
Qt::NetworkPrivate
diff --git a/tests/auto/network/access/qnetworkcookiejar/testdata/publicsuffix/public_suffix_list.dafsa b/tests/auto/network/access/qnetworkcookiejar/testdata/publicsuffix/public_suffix_list.dafsa
new file mode 100644
index 0000000000..2bd4ca05f3
--- /dev/null
+++ b/tests/auto/network/access/qnetworkcookiejar/testdata/publicsuffix/public_suffix_list.dafsa
Binary files differ
diff --git a/tests/auto/network/access/qnetworkcookiejar/tst_qnetworkcookiejar.cpp b/tests/auto/network/access/qnetworkcookiejar/tst_qnetworkcookiejar.cpp
index d4e9698ca3..9460060dbf 100644
--- a/tests/auto/network/access/qnetworkcookiejar/tst_qnetworkcookiejar.cpp
+++ b/tests/auto/network/access/qnetworkcookiejar/tst_qnetworkcookiejar.cpp
@@ -1,31 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
#include <QTest>
#include <QtCore/QJsonArray>
@@ -37,14 +11,17 @@
#include <QtNetwork/QNetworkRequest>
#if QT_CONFIG(topleveldomain)
#include "private/qtldurl_p.h"
-#include "private/qurltlds_p.h"
#endif
+#include <memory>
+
class tst_QNetworkCookieJar: public QObject
{
Q_OBJECT
private slots:
+ void initTestCase();
+
void getterSetter();
void setCookiesFromUrl_data();
void setCookiesFromUrl();
@@ -56,6 +33,8 @@ private slots:
#endif
void rfc6265_data();
void rfc6265();
+private:
+ QSharedPointer<QTemporaryDir> m_dataDir;
};
class MyCookieJar: public QNetworkCookieJar
@@ -83,6 +62,22 @@ void tst_QNetworkCookieJar::getterSetter()
QCOMPARE(jar.allCookies(), list);
}
+void tst_QNetworkCookieJar::initTestCase()
+{
+#if QT_CONFIG(topleveldomain) && QT_CONFIG(publicsuffix_system)
+ QString testDataDir;
+#ifdef BUILTIN_TESTDATA
+ m_dataDir = QEXTRACTTESTDATA("/testdata");
+ QVERIFY(m_dataDir);
+ testDataDir = m_dataDir->path() + "/testdata";
+#else
+ testDataDir = QFINDTESTDATA("testdata");
+#endif
+ qDebug() << "Test data dir:" << testDataDir;
+ qputenv("XDG_DATA_DIRS", QFile::encodeName(testDataDir));
+#endif
+}
+
void tst_QNetworkCookieJar::setCookiesFromUrl_data()
{
QTest::addColumn<QList<QNetworkCookie> >("preset");
@@ -241,7 +236,7 @@ void tst_QNetworkCookieJar::setCookiesFromUrl()
QFETCH(QList<QNetworkCookie>, preset);
QFETCH(QNetworkCookie, newCookie);
QFETCH(QString, referenceUrl);
- QFETCH(QList<QNetworkCookie>, expectedResult);
+ QFETCH(const QList<QNetworkCookie>, expectedResult);
QFETCH(bool, setCookies);
QList<QNetworkCookie> cookieList;
@@ -251,11 +246,11 @@ void tst_QNetworkCookieJar::setCookiesFromUrl()
QCOMPARE(jar.setCookiesFromUrl(cookieList, referenceUrl), setCookies);
QList<QNetworkCookie> result = jar.allCookies();
- foreach (QNetworkCookie cookie, expectedResult) {
+ for (const QNetworkCookie &cookie : expectedResult) {
QVERIFY2(result.contains(cookie), cookie.toRawForm());
result.removeAll(cookie);
}
- QVERIFY2(result.isEmpty(), QTest::toString(result));
+ QVERIFY2(result.isEmpty(), std::unique_ptr<char[]>(QTest::toString(result)).get());
}
void tst_QNetworkCookieJar::cookiesForUrl_data()
@@ -414,13 +409,11 @@ void tst_QNetworkCookieJar::effectiveTLDs_data()
QTest::newRow("yes1") << "com" << true;
QTest::newRow("yes2") << "de" << true;
- QTest::newRow("yes3") << "ulm.museum" << true;
QTest::newRow("yes4") << "krodsherad.no" << true;
QTest::newRow("yes5") << "1.bg" << true;
QTest::newRow("yes6") << "com.cn" << true;
QTest::newRow("yes7") << "org.ws" << true;
QTest::newRow("yes8") << "co.uk" << true;
- QTest::newRow("yes9") << "wallonie.museum" << true;
QTest::newRow("yes10") << "hk.com" << true;
QTest::newRow("yes11") << "hk.org" << true;
@@ -437,33 +430,23 @@ void tst_QNetworkCookieJar::effectiveTLDs_data()
QTest::newRow("no11") << "mosreg.ru" << false;
const char16_t s1[] = {0x74, 0x72, 0x61, 0x6e, 0xf8, 0x79, 0x2e, 0x6e, 0x6f, 0x00}; // xn--trany-yua.no
- const char16_t s2[] = {0x5d9, 0x5e8, 0x5d5, 0x5e9, 0x5dc, 0x5d9, 0x5dd, 0x2e, 0x6d, 0x75, 0x73, 0x65, 0x75, 0x6d, 0x00}; // xn--9dbhblg6di.museum
const char16_t s3[] = {0x7ec4, 0x7e54, 0x2e, 0x68, 0x6b, 0x00}; // xn--mk0axi.hk
const char16_t s4[] = {0x7f51, 0x7edc, 0x2e, 0x63, 0x6e, 0x00}; // xn--io0a7i.cn
const char16_t s5[] = {0x72, 0xe1, 0x68, 0x6b, 0x6b, 0x65, 0x72, 0xe1, 0x76, 0x6a, 0x75, 0x2e, 0x6e, 0x6f, 0x00}; // xn--rhkkervju-01af.no
const char16_t s6[] = {0xb9a, 0xbbf, 0xb99, 0xbcd, 0xb95, 0xbaa, 0xbcd, 0xbaa, 0xbc2, 0xbb0, 0xbcd, 0x00}; // xn--clchc0ea0b2g2a9gcd
const char16_t s7[] = {0x627, 0x644, 0x627, 0x631, 0x62f, 0x646, 0x00}; // xn--mgbayh7gpa
- const char16_t s8[] = {0x63, 0x6f, 0x72, 0x72, 0x65, 0x69, 0x6f, 0x73, 0x2d, 0x65, 0x2d, 0x74, 0x65, 0x6c, 0x65,
- 0x63, 0x6f, 0x6d, 0x75, 0x6e, 0x69, 0x63, 0x61, 0xe7, 0xf5, 0x65, 0x73, 0x2e, 0x6d, 0x75,
- 0x73, 0x65, 0x75, 0x6d, 0x00}; // xn--correios-e-telecomunicaes-ghc29a.museum
QTest::newRow("yes-specialchars1") << QString::fromUtf16(s1) << true;
- QTest::newRow("yes-specialchars2") << QString::fromUtf16(s2) << true;
QTest::newRow("yes-specialchars3") << QString::fromUtf16(s3) << true;
QTest::newRow("yes-specialchars4") << QString::fromUtf16(s4) << true;
QTest::newRow("yes-specialchars5") << QString::fromUtf16(s5) << true;
QTest::newRow("yes-specialchars6") << QString::fromUtf16(s6) << true;
QTest::newRow("yes-specialchars7") << QString::fromUtf16(s7) << true;
- QTest::newRow("yes-specialchars8") << QString::fromUtf16(s8) << true;
QTest::newRow("no-specialchars1") << QString::fromUtf16(s1).prepend("something") << false;
- QTest::newRow("no-specialchars2") << QString::fromUtf16(s2).prepend(QString::fromUtf16(s2)) << false;
- QTest::newRow("no-specialchars2.5") << QString::fromUtf16(s2).prepend("whatever") << false;
QTest::newRow("no-specialchars3") << QString::fromUtf16(s3).prepend("foo") << false;
QTest::newRow("no-specialchars4") << QString::fromUtf16(s4).prepend("bar") << false;
- QTest::newRow("no-specialchars5") << QString::fromUtf16(s5).prepend(QString::fromUtf16(s2)) << false;
QTest::newRow("no-specialchars6") << QString::fromUtf16(s6).prepend(QLatin1Char('.') + QString::fromUtf16(s6)) << false;
QTest::newRow("no-specialchars7") << QString::fromUtf16(s7).prepend("bla") << false;
- QTest::newRow("no-specialchars8") << QString::fromUtf16(s8).append("foo") << false;
QTest::newRow("exception1") << "pref.iwate.jp" << false;
QTest::newRow("exception2") << "omanpost.om" << false;
@@ -479,28 +462,6 @@ void tst_QNetworkCookieJar::effectiveTLDs_data()
QTest::newRow("yes-wildcard5") << "foo.sch.uk" << true;
QTest::newRow("yes-platform.sh") << "eu.platform.sh" << true;
QTest::newRow("no-platform.sh") << "something.platform.sh" << false;
-
- int inFirst = 0; // First group is guaranteed to be in first chunk.
- while (tldIndices[inFirst] < tldChunks[0])
- ++inFirst;
- Q_ASSERT(inFirst < tldCount);
- const char *lastGroupFromFirstChunk = &tldData[0][tldIndices[inFirst - 1]];
- const char *cut = &tldData[0][tldChunks[0]];
- for (const char *entry = lastGroupFromFirstChunk; entry < cut; entry += strlen(entry) + 1)
- QTest::addRow("lastGroupFromFirstChunk: %s", entry) << entry << true;
-
- Q_ASSERT(tldChunkCount > 1); // There are enough TLDs to fill 64K bytes
- // The tldCount + 1 entries in tldIndices are indexed by hash value and some
- // hash cells may be empty: we need to find the last non-empty hash cell.
- int tail = tldCount;
- while (tldIndices[tail - 1] == tldIndices[tail])
- --tail;
- Q_ASSERT(tldIndices[tail] == tldChunks[tldChunkCount - 1]);
- const char *lastGroupFromLastChunk =
- &tldData[tldChunkCount-1][tldIndices[tail - 1] - tldChunks[tldChunkCount - 2]];
- const char *end = &tldData[tldChunkCount-1][tldIndices[tail] - tldChunks[tldChunkCount - 2]];
- for (const char *entry = lastGroupFromLastChunk; entry < end; entry += strlen(entry) + 1)
- QTest::addRow("lastGroupFromLastChunk: %s", entry) << entry << true;
}
void tst_QNetworkCookieJar::effectiveTLDs()
@@ -556,7 +517,7 @@ void tst_QNetworkCookieJar::rfc6265_data()
void tst_QNetworkCookieJar::rfc6265()
{
- QFETCH(QStringList, received);
+ QFETCH(const QStringList, received);
QFETCH(QList<QNetworkCookie>, sent);
QFETCH(QString, sentTo);
@@ -567,16 +528,16 @@ void tst_QNetworkCookieJar::rfc6265()
QNetworkCookieJar jar;
QList<QNetworkCookie> receivedCookies;
- foreach (const QString &cookieLine, received)
+ for (const QString &cookieLine : received)
receivedCookies.append(QNetworkCookie::parseCookies(cookieLine.toUtf8()));
jar.setCookiesFromUrl(receivedCookies, receivedUrl);
QList<QNetworkCookie> cookiesToSend = jar.cookiesForUrl(sentUrl);
//compare cookies only using name/value, as the metadata isn't sent over the network
- QCOMPARE(cookiesToSend.count(), sent.count());
+ QCOMPARE(cookiesToSend.size(), sent.size());
bool ok = true;
- for (int i = 0; i < cookiesToSend.count(); i++) {
+ for (int i = 0; i < cookiesToSend.size(); i++) {
if (cookiesToSend.at(i).name() != sent.at(i).name()) {
ok = false;
break;
diff --git a/tests/auto/network/access/qnetworkdiskcache/CMakeLists.txt b/tests/auto/network/access/qnetworkdiskcache/CMakeLists.txt
index af58132fb3..023868f57e 100644
--- a/tests/auto/network/access/qnetworkdiskcache/CMakeLists.txt
+++ b/tests/auto/network/access/qnetworkdiskcache/CMakeLists.txt
@@ -1,12 +1,19 @@
-# Generated from qnetworkdiskcache.pro.
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
#####################################################################
## tst_qnetworkdiskcache Test:
#####################################################################
+if(NOT QT_BUILD_STANDALONE_TESTS AND NOT QT_BUILDING_QT)
+ cmake_minimum_required(VERSION 3.16)
+ project(tst_qnetworkdiskcache LANGUAGES CXX)
+ find_package(Qt6BuildInternals REQUIRED COMPONENTS STANDALONE_TEST)
+endif()
+
qt_internal_add_test(tst_qnetworkdiskcache
SOURCES
tst_qnetworkdiskcache.cpp
- PUBLIC_LIBRARIES
+ LIBRARIES
Qt::Network
)
diff --git a/tests/auto/network/access/qnetworkdiskcache/tst_qnetworkdiskcache.cpp b/tests/auto/network/access/qnetworkdiskcache/tst_qnetworkdiskcache.cpp
index 5dc2936d25..ec32c780cd 100644
--- a/tests/auto/network/access/qnetworkdiskcache/tst_qnetworkdiskcache.cpp
+++ b/tests/auto/network/access/qnetworkdiskcache/tst_qnetworkdiskcache.cpp
@@ -1,30 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
#include <QtNetwork/QtNetwork>
#include <QTest>
@@ -37,7 +12,7 @@
#define EXAMPLE_URL "http://user:pass@localhost:4/#foo"
#define EXAMPLE_URL2 "http://user:pass@localhost:4/bar"
//cached objects are organized into these many subdirs
-#define NUM_SUBDIRECTORIES 16
+#define NUM_SUBDIRECTORIES 15
class tst_QNetworkDiskCache : public QObject
{
@@ -303,17 +278,17 @@ void tst_QNetworkDiskCache::clear()
QVERIFY(cache.cacheSize() > qint64(0));
QString cacheDirectory = cache.cacheDirectory();
- QCOMPARE(countFiles(cacheDirectory).count(), NUM_SUBDIRECTORIES + 3);
+ QCOMPARE(countFiles(cacheDirectory).size(), NUM_SUBDIRECTORIES + 3);
cache.clear();
- QCOMPARE(countFiles(cacheDirectory).count(), NUM_SUBDIRECTORIES + 2);
+ QCOMPARE(countFiles(cacheDirectory).size(), NUM_SUBDIRECTORIES + 2);
// don't delete files that it didn't create
QTemporaryFile file(cacheDirectory + "/XXXXXX");
if (file.open()) {
file.fileName(); // make sure it exists with a name
- QCOMPARE(countFiles(cacheDirectory).count(), NUM_SUBDIRECTORIES + 3);
+ QCOMPARE(countFiles(cacheDirectory).size(), NUM_SUBDIRECTORIES + 3);
cache.clear();
- QCOMPARE(countFiles(cacheDirectory).count(), NUM_SUBDIRECTORIES + 3);
+ QCOMPARE(countFiles(cacheDirectory).size(), NUM_SUBDIRECTORIES + 3);
}
}
@@ -380,9 +355,9 @@ void tst_QNetworkDiskCache::remove()
QUrl url(EXAMPLE_URL);
cache.setupWithOne(tempDir.path(), url);
QString cacheDirectory = cache.cacheDirectory();
- QCOMPARE(countFiles(cacheDirectory).count(), NUM_SUBDIRECTORIES + 3);
+ QCOMPARE(countFiles(cacheDirectory).size(), NUM_SUBDIRECTORIES + 3);
cache.remove(url);
- QCOMPARE(countFiles(cacheDirectory).count(), NUM_SUBDIRECTORIES + 2);
+ QCOMPARE(countFiles(cacheDirectory).size(), NUM_SUBDIRECTORIES + 2);
}
void tst_QNetworkDiskCache::accessAfterRemove() // QTBUG-17400
@@ -501,9 +476,9 @@ void tst_QNetworkDiskCache::fileMetaData()
url.setFragment(QString());
QString cacheDirectory = cache.cacheDirectory();
- QStringList list = countFiles(cacheDirectory);
- QCOMPARE(list.count(), NUM_SUBDIRECTORIES + 3);
- foreach(QString fileName, list) {
+ const QStringList list = countFiles(cacheDirectory);
+ QCOMPARE(list.size(), NUM_SUBDIRECTORIES + 3);
+ for (const QString &fileName : list) {
QFileInfo info(fileName);
if (info.isFile()) {
QNetworkCacheMetaData metaData = cache.call_fileMetaData(fileName);
@@ -546,9 +521,9 @@ void tst_QNetworkDiskCache::expire()
}
QString cacheDirectory = cache.cacheDirectory();
- QStringList list = countFiles(cacheDirectory);
+ const QStringList list = countFiles(cacheDirectory);
QStringList cacheList;
- foreach(QString fileName, list) {
+ for (const QString &fileName : list) {
QFileInfo info(fileName);
if (info.isFile()) {
QNetworkCacheMetaData metaData = cache.call_fileMetaData(fileName);
@@ -556,7 +531,7 @@ void tst_QNetworkDiskCache::expire()
}
}
std::sort(cacheList.begin(), cacheList.end());
- for (int i = 0; i < cacheList.count(); ++i) {
+ for (int i = 0; i < cacheList.size(); ++i) {
QString fileName = cacheList[i];
QCOMPARE(fileName, QLatin1String("http://localhost:4/") + QString::number(i + 6));
}
@@ -594,11 +569,11 @@ void tst_QNetworkDiskCache::oldCacheVersionFile()
QVERIFY(!metaData.isValid());
QVERIFY(!QFile::exists(name));
} else {
- QStringList files = countFiles(cache.cacheDirectory());
- QCOMPARE(files.count(), NUM_SUBDIRECTORIES + 3);
+ const QStringList files = countFiles(cache.cacheDirectory());
+ QCOMPARE(files.size(), NUM_SUBDIRECTORIES + 3);
// find the file
QString cacheFile;
- foreach (QString file, files) {
+ for (const QString &file : files) {
QFileInfo info(file);
if (info.isFile())
cacheFile = file;
@@ -635,8 +610,8 @@ void tst_QNetworkDiskCache::streamVersion()
QString cacheFile;
// find the file
- QStringList files = countFiles(cache.cacheDirectory());
- foreach (const QString &file, files) {
+ const QStringList files = countFiles(cache.cacheDirectory());
+ for (const QString &file : files) {
QFileInfo info(file);
if (info.isFile()) {
cacheFile = file;
@@ -682,6 +657,7 @@ void tst_QNetworkDiskCache::streamVersion()
QIODevice *dataDevice = cache.data(url);
QVERIFY(dataDevice != 0);
QByteArray cachedData = dataDevice->readAll();
+ delete dataDevice;
QCOMPARE(cachedData, data);
}
}
@@ -718,8 +694,6 @@ public:
QNetworkDiskCache cache;
cache.setCacheDirectory(cachePath);
- int read = 0;
-
int i = 0;
for (; i < 5000; ++i) {
if (other && other->isFinished())
@@ -761,7 +735,7 @@ public:
if (d) {
QByteArray x = d->readAll();
if (x != longString && x != longString2) {
- qDebug() << x.length() << QString(x);
+ qDebug() << x.size() << QString(x);
gotMetaData = cache.metaData(url);
qDebug() << (gotMetaData.url().toString())
<< gotMetaData.lastModified()
@@ -770,7 +744,6 @@ public:
}
if (gotMetaData.isValid())
QVERIFY(x == longString || x == longString2);
- read++;
delete d;
}
}
@@ -778,9 +751,8 @@ public:
cache.remove(url);
if (QRandomGenerator::global()->bounded(5) == 1)
cache.clear();
- sleep(0);
+ sleep(std::chrono::seconds{0});
}
- //qDebug() << "read!" << read << i;
}
QDateTime dt;
diff --git a/tests/auto/network/access/qnetworkreply/BLACKLIST b/tests/auto/network/access/qnetworkreply/BLACKLIST
index 977d8be7f5..a4c7c1ee30 100644
--- a/tests/auto/network/access/qnetworkreply/BLACKLIST
+++ b/tests/auto/network/access/qnetworkreply/BLACKLIST
@@ -1,8 +1,6 @@
# See qtbase/src/testlib/qtestblacklist.cpp for format
[getErrors:ftp-host]
linux
-[getFromHttpIntoBuffer]
-osx
[ioPostToHttpFromSocket]
osx
[ioHttpRedirectMultipartPost]
@@ -17,12 +15,8 @@ windows-10
windows-10
[backgroundRequest]
macos
-[connectToIPv6Address]
-macos
[deleteFromHttp]
macos
-[downloadProgress]
-macos
[httpCanReadLine]
macos
[httpRecursiveCreation]
@@ -31,8 +25,6 @@ osx
macos
[ioGetFromBuiltinHttp]
osx
-[ioGetFromHttp]
-macos
[ioPostToHttpFromFile]
macos
[ioPostToHttpFromSocketSynchronous]
@@ -43,35 +35,18 @@ osx
macos
[lastModifiedHeaderForHttp]
macos
-[multipartSkipIndices]
-macos
-[nestedEventLoops]
-osx
-[postToHttp]
-macos
-[postToHttpMultipart]
-macos
[postToHttpSynchronous]
macos
-[putGetDeleteGetFromHttp]
-macos
[putToHttpSynchronous]
macos
[putToHttpsSynchronous]
osx
-[putWithRateLimiting]
-macos
-[qtbug13431replyThrottling]
-macos
-[receiveCookiesFromHttp]
-osx
[receiveCookiesFromHttpSynchronous]
osx
-[sendCookies]
-osx
[sendCookiesSynchronous]
osx
-[sendCustomRequestToHttp]
-macos
[backgroundRequestConnectInBackground]
osx
+#QTBUG-103055
+[ioGetFromHttpWithProxyAuth]
+qnx
diff --git a/tests/auto/network/access/qnetworkreply/CMakeLists.txt b/tests/auto/network/access/qnetworkreply/CMakeLists.txt
index 3b138b3918..9bfd90cd56 100644
--- a/tests/auto/network/access/qnetworkreply/CMakeLists.txt
+++ b/tests/auto/network/access/qnetworkreply/CMakeLists.txt
@@ -1,4 +1,11 @@
-# Generated from qnetworkreply.pro.
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
+
+if(NOT QT_BUILD_STANDALONE_TESTS AND NOT QT_BUILDING_QT)
+ cmake_minimum_required(VERSION 3.16)
+ project(tst_qnetworkreply LANGUAGES CXX)
+ find_package(Qt6BuildInternals REQUIRED COMPONENTS STANDALONE_TEST)
+endif()
add_subdirectory(echo)
add_subdirectory(test)
diff --git a/tests/auto/network/access/qnetworkreply/certs/qt-test-server-cacert.pem b/tests/auto/network/access/qnetworkreply/certs/qt-test-server-cacert.pem
index c5aea0d7c9..29fd755de7 100644
--- a/tests/auto/network/access/qnetworkreply/certs/qt-test-server-cacert.pem
+++ b/tests/auto/network/access/qnetworkreply/certs/qt-test-server-cacert.pem
@@ -1,17 +1,17 @@
-----BEGIN CERTIFICATE-----
-MIICpzCCAhACCQCzAF1hyRVzAjANBgkqhkiG9w0BAQUFADCBlzELMAkGA1UEBhMC
-Tk8xDTALBgNVBAgTBE9zbG8xDTALBgNVBAcTBE9zbG8xDjAMBgNVBAoTBU5va2lh
-MTUwMwYDVQQLFCxRdCBTb2Z0d2FyZS9lbWFpbEFkZHJlc3M9bm9ib2R5QG5vZG9t
-YWluLm9yZzEjMCEGA1UEAxMacXQtdGVzdC1zZXJ2ZXIucXQtdGVzdC1uZXQwHhcN
-MTkwNjI0MTI0OTIxWhcNMjIwNjIzMTI0OTIxWjCBlzELMAkGA1UEBhMCTk8xDTAL
-BgNVBAgTBE9zbG8xDTALBgNVBAcTBE9zbG8xDjAMBgNVBAoTBU5va2lhMTUwMwYD
-VQQLFCxRdCBTb2Z0d2FyZS9lbWFpbEFkZHJlc3M9bm9ib2R5QG5vZG9tYWluLm9y
-ZzEjMCEGA1UEAxMacXQtdGVzdC1zZXJ2ZXIucXQtdGVzdC1uZXQwgZ8wDQYJKoZI
-hvcNAQEBBQADgY0AMIGJAoGBAM2q22/WNMmn8cC+5EEYGeICySLmp9W6Ay6eKHr0
-Xxp3X3epETuPfvAuxp7rOtkS18EMUegkUj8jw0IMEcbyHKFC/rTCaYOt93CxGBXM
-IChiMPAsFeYzGa/D6xzAkfcRaJRQ+Ek3CDLXPnXfo7xpABXezYcPXAJrgsgBfWrw
-HdxzAgMBAAEwDQYJKoZIhvcNAQEFBQADgYEASCKbqEX5ysC549mq90ydk4jyDW3m
-PUyet01fKpcRqVs+OJxdExFBTra3gho6WzzpTSPsuX2ZKOLF5k6KkCvdCGvhC1Kv
-HHPIExurfzvdlSRzj6HbKyPuSfxyOloH0bBp7/Gg5RIuBPKlbmfbnTLtwEjhhbMU
-SoYI8HZd3HfY87c=
+MIICyjCCAjMCFHPGDqJR+klHni4XbETMk6GLn/UEMA0GCSqGSIb3DQEBDQUAMIGj
+MRcwFQYDVQQKEw5UaGUgUXQgQ29tcGFueTEUMBIGA1UECxMLUXQgU29mdHdhcmUx
+IjAgBgkqhkiG9w0BCQEWE25vYm9keUBub2RvbWFpbi5vcmcxDTALBgNVBAcTBE9z
+bG8xDTALBgNVBAgTBE9zbG8xCzAJBgNVBAYTAk5PMSMwIQYDVQQDExpxdC10ZXN0
+LXNlcnZlci5xdC10ZXN0LW5ldDAeFw0yMjA2MjQxMTU4NDlaFw0zMjA2MjExMTU4
+NDlaMIGjMRcwFQYDVQQKEw5UaGUgUXQgQ29tcGFueTEUMBIGA1UECxMLUXQgU29m
+dHdhcmUxIjAgBgkqhkiG9w0BCQEWE25vYm9keUBub2RvbWFpbi5vcmcxDTALBgNV
+BAcTBE9zbG8xDTALBgNVBAgTBE9zbG8xCzAJBgNVBAYTAk5PMSMwIQYDVQQDExpx
+dC10ZXN0LXNlcnZlci5xdC10ZXN0LW5ldDCBnzANBgkqhkiG9w0BAQEFAAOBjQAw
+gYkCgYEAzarbb9Y0yafxwL7kQRgZ4gLJIuan1boDLp4oevRfGndfd6kRO49+8C7G
+nus62RLXwQxR6CRSPyPDQgwRxvIcoUL+tMJpg633cLEYFcwgKGIw8CwV5jMZr8Pr
+HMCR9xFolFD4STcIMtc+dd+jvGkAFd7Nhw9cAmuCyAF9avAd3HMCAwEAATANBgkq
+hkiG9w0BAQ0FAAOBgQCZyRe25WqOjrNS6BKPs7ep7eyCON3NKdWnfABZrSjGJQ87
+PoFKl6+9YBSlSpl8qk7c29ic+wA4qFQzPJkrbYIXjwVMAr+cC1kVrlUVqcwmvnKo
+5vj57/v8S0Uc4/GesIsxZR7QM+3diPDyk7Bsc3IkpINb31Dl0mlg25nztg8NxA==
-----END CERTIFICATE-----
diff --git a/tests/auto/network/access/qnetworkreply/certs/server.key b/tests/auto/network/access/qnetworkreply/certs/server.key
index 9d1664d609..b8d0d0449b 100644
--- a/tests/auto/network/access/qnetworkreply/certs/server.key
+++ b/tests/auto/network/access/qnetworkreply/certs/server.key
@@ -1,15 +1,27 @@
-----BEGIN RSA PRIVATE KEY-----
-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
+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
-----END RSA PRIVATE KEY-----
diff --git a/tests/auto/network/access/qnetworkreply/certs/server.pem b/tests/auto/network/access/qnetworkreply/certs/server.pem
index 67eb495319..47c22d9f29 100644
--- a/tests/auto/network/access/qnetworkreply/certs/server.pem
+++ b/tests/auto/network/access/qnetworkreply/certs/server.pem
@@ -1,24 +1,22 @@
-----BEGIN CERTIFICATE-----
-MIIEEzCCAvugAwIBAgIBADANBgkqhkiG9w0BAQUFADCBnDELMAkGA1UEBhMCTk8x
-DTALBgNVBAgTBE9zbG8xEDAOBgNVBAcTB055ZGFsZW4xFjAUBgNVBAoTDVRyb2xs
-dGVjaCBBU0ExFDASBgNVBAsTC0RldmVsb3BtZW50MRcwFQYDVQQDEw5mbHVrZS50
-cm9sbC5ubzElMCMGCSqGSIb3DQEJARYWYWhhbnNzZW5AdHJvbGx0ZWNoLmNvbTAe
-Fw0wNzEyMDQwMTEwMzJaFw0zNTA0MjEwMTEwMzJaMGMxCzAJBgNVBAYTAk5PMQ0w
-CwYDVQQIEwRPc2xvMRYwFAYDVQQKEw1Ucm9sbHRlY2ggQVNBMRQwEgYDVQQLEwtE
-ZXZlbG9wbWVudDEXMBUGA1UEAxMOZmx1a2UudHJvbGwubm8wgZ8wDQYJKoZIhvcN
-AQEBBQADgY0AMIGJAoGBAKfIoErEGQUbZroy4tLxHG8XguQ5LgFRkNsENDIRIcIN
-b1nYU5BUP4OPqdOz1e4am4CuwyXJXqWvS2AFqqDRkQEfygSD41gcmTJFhHByWAOY
-SmOLQfUISdKRAmBr5GT+3aCqdAjpNEyRXxI9N01ULK1/W5hgNgKMO/ZF8ydqm5Sd
-AgMBAAGjggEaMIIBFjAJBgNVHRMEAjAAMCwGCWCGSAGG+EIBDQQfFh1PcGVuU1NM
-IEdlbmVyYXRlZCBDZXJ0aWZpY2F0ZTAdBgNVHQ4EFgQUIYUEPSMBZuX3nxqEJIqv
-Cnn05awwgbsGA1UdIwSBszCBsKGBoqSBnzCBnDELMAkGA1UEBhMCTk8xDTALBgNV
-BAgTBE9zbG8xEDAOBgNVBAcTB055ZGFsZW4xFjAUBgNVBAoTDVRyb2xsdGVjaCBB
-U0ExFDASBgNVBAsTC0RldmVsb3BtZW50MRcwFQYDVQQDEw5mbHVrZS50cm9sbC5u
-bzElMCMGCSqGSIb3DQEJARYWYWhhbnNzZW5AdHJvbGx0ZWNoLmNvbYIJAI6otOiR
-t1QuMA0GCSqGSIb3DQEBBQUAA4IBAQBtV1/RBUPwYgXsKnGl3BkI8sSmvbsl2cqJ
-AQ7kzx/BjMgkGDVTWXvAQ7Qy5piypu8VBQtIX+GgDJepoXfYNRgwvKmP07dUx/Gp
-nl3mGb/2PFsr2OQ+YhiIi9Mk4UCbDOYpFmKr6gUkcDaqVZPvAoEbIxCiBOtWlXX8
-+JSxXULFPzZEhV06LpBGiqK5b4euDBVAGTGQ/Dslu67xZhMNhZDZSTSP8l35ettN
-XSf2dp01jAamTKOxsrZvHdejAP1y657qRKGvITR9x0LiSZEZi8CtuoKAqHFw9DUx
-kWOEIJXpYK9ki8z/PYp2dD3IVW3kjsMrHOhCGK6f5mucNAbsavLD
+MIIDrzCCApcCFGtyyXYbHuuIIseKAiLxL5nMKEnwMA0GCSqGSIb3DQEBCwUAMIGT
+MQswCQYDVQQGEwJOTzENMAsGA1UECAwET3NsbzEQMA4GA1UEBwwHTnlkYWxlbjEN
+MAsGA1UECgwEVFF0QzEUMBIGA1UECwwLRGV2ZWxvcG1lbnQxFzAVBgNVBAMMDmZs
+dWtlLnRyb2xsLm5vMSUwIwYJKoZIhvcNAQkBFhZhaGFuc3NlbkB0cm9sbHRlY2gu
+Y29tMB4XDTIyMDcwODA2Mjc1OVoXDTMyMDcwNTA2Mjc1OVowgZMxCzAJBgNVBAYT
+Ak5PMQ0wCwYDVQQIDARPc2xvMRAwDgYDVQQHDAdOeWRhbGVuMQ0wCwYDVQQKDARU
+UXRDMRQwEgYDVQQLDAtEZXZlbG9wbWVudDEXMBUGA1UEAwwOZmx1a2UudHJvbGwu
+bm8xJTAjBgkqhkiG9w0BCQEWFmFoYW5zc2VuQHRyb2xsdGVjaC5jb20wggEiMA0G
+CSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDKKdWTdAFuNL5RzNY/6Oe6AWflhm46
+cI+U8rRKZ5SJlbTHg8CReiSzstKtr5dPaGDTus8GETJBQTXepjD5FUFJ7G+HDZEO
+DvqhXXuO3uNWNvTiGEptIEqKxbhQcXSu/LOhbMnNXFqrF9wVxhPu4T63RycIeL8w
+Zf72BQjwPPjoiikIDmR8qYD5ecX/86/zCiQg3haTSWqQDJYMKD87kC/of/Nuv9Tc
+IIjl4jlxFEjBIwPFs9e/1v52C/GEwkYyS7pQwyFJ+T1pzoUJI2CFgHvDcL3MgaID
++04fKy6PAbOnNEoPNPk/+o2ouQs7G+ylSHfYEP+OCikCGg2L2kObrSItAgMBAAEw
+DQYJKoZIhvcNAQELBQADggEBALHdGWQ4YqucGJSP1n1ANrLILy+sXqEP7hMdG5HH
+GDZ/ygUhjTZ/k5Cj0+auC4Aw490l8Tj8gmzt68KJmgSH+z1erY67+fhWtAewDzU5
+zIMqKHja1hSb5JIdWaD7ZFBQzor2beBO0u+VzegWqe20kw2mkFAcdQTsV28hvr1v
+rcgpVkegQcmHpr6FBpYFmtnizpPnX5Zm+JJAlvSGvoYMI5i9Vc7/gdx790NeaXmy
+yD1ueFMfsPtAcZq8cSbGSCS5/pcuhIx+5O9+V8iwN9lKdYksTCLAn4SREHzlgi68
+SGY0OUMlXeD82K0+mDv+hzSmq4sk7CDGbSxVV5TwzFXDgNc=
-----END CERTIFICATE-----
diff --git a/tests/auto/network/access/qnetworkreply/echo/CMakeLists.txt b/tests/auto/network/access/qnetworkreply/echo/CMakeLists.txt
index 664b2f2fab..137b29110d 100644
--- a/tests/auto/network/access/qnetworkreply/echo/CMakeLists.txt
+++ b/tests/auto/network/access/qnetworkreply/echo/CMakeLists.txt
@@ -1,11 +1,12 @@
-# Generated from echo.pro.
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
#####################################################################
## echo Binary:
#####################################################################
qt_internal_add_executable(echo
- OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR} # special case
+ OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
SOURCES
main.cpp
)
diff --git a/tests/auto/network/access/qnetworkreply/echo/main.cpp b/tests/auto/network/access/qnetworkreply/echo/main.cpp
index 9085de7898..b10eaa745c 100644
--- a/tests/auto/network/access/qnetworkreply/echo/main.cpp
+++ b/tests/auto/network/access/qnetworkreply/echo/main.cpp
@@ -1,30 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
#include <QtCore/QFile>
@@ -37,11 +12,13 @@ int main(int argc, char **)
}
QFile file;
- file.open(stdin, QFile::ReadWrite);
+ if (!file.open(stdin, QFile::ReadWrite))
+ return 1;
QByteArray data = file.readAll();
file.close();
- file.open(stdout, QFile::WriteOnly);
+ if (!file.open(stdout, QFile::WriteOnly))
+ return 1;
file.write(data);
file.close();
return 0;
diff --git a/tests/auto/network/access/qnetworkreply/qnetworkreply.qrc b/tests/auto/network/access/qnetworkreply/qnetworkreply.qrc
deleted file mode 100644
index 85ca6312af..0000000000
--- a/tests/auto/network/access/qnetworkreply/qnetworkreply.qrc
+++ /dev/null
@@ -1,5 +0,0 @@
-<!DOCTYPE RCC><RCC version="1.0">
-<qresource>
- <file>resource</file>
-</qresource>
-</RCC>
diff --git a/tests/auto/network/access/qnetworkreply/test/CMakeLists.txt b/tests/auto/network/access/qnetworkreply/test/CMakeLists.txt
index d54fb40c56..fa353b2769 100644
--- a/tests/auto/network/access/qnetworkreply/test/CMakeLists.txt
+++ b/tests/auto/network/access/qnetworkreply/test/CMakeLists.txt
@@ -1,4 +1,5 @@
-# Generated from test.pro.
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
#####################################################################
## tst_qnetworkreply Test:
@@ -18,17 +19,19 @@ list(APPEND test_data "../index.html")
list(APPEND test_data "../smb-file.txt")
qt_internal_add_test(tst_qnetworkreply
- OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/../" # special case
+ OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/../"
SOURCES
../tst_qnetworkreply.cpp
../data/gzip.rcc.cpp
../data/zstandard.rcc.cpp
- PUBLIC_LIBRARIES
+ LIBRARIES
Qt::CorePrivate
Qt::NetworkPrivate
TESTDATA ${test_data}
- QT_TEST_SERVER_LIST "vsftpd" "apache2" "ftp-proxy" "danted" "squid" # special case
+ QT_TEST_SERVER_LIST "vsftpd" "apache2" "ftp-proxy" "danted" "squid"
+ BUNDLE_ANDROID_OPENSSL_LIBS
)
+add_dependencies(tst_qnetworkreply echo)
# Resources:
set(qnetworkreply_resource_files
@@ -43,15 +46,3 @@ qt_internal_add_resource(tst_qnetworkreply "qnetworkreply"
FILES
${qnetworkreply_resource_files}
)
-
-
-#### Keys ignored in scope 1:.:.:test.pro:<TRUE>:
-# QT_FOR_CONFIG = "gui-private"
-# QT_TEST_SERVER_LIST = "vsftpd" "apache2" "ftp-proxy" "danted" "squid"
-# testcase.timeout = "600"
-
-## Scopes:
-#####################################################################
-
-#### Keys ignored in scope 2:.:.:test.pro:NOT ANDROID:
-# TEST_HELPER_INSTALLS = "../echo/echo"
diff --git a/tests/auto/network/access/qnetworkreply/tst_qnetworkreply.cpp b/tests/auto/network/access/qnetworkreply/tst_qnetworkreply.cpp
index 2ebeff8689..a4a05b18f5 100644
--- a/tests/auto/network/access/qnetworkreply/tst_qnetworkreply.cpp
+++ b/tests/auto/network/access/qnetworkreply/tst_qnetworkreply.cpp
@@ -1,30 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2021 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2021 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
#include <QtNetwork/qtnetworkglobal.h>
@@ -39,19 +14,25 @@
#include <QWaitCondition>
#include <QScopeGuard>
#include <QBuffer>
+#include <QMap>
#include <QtCore/QCryptographicHash>
#include <QtCore/QDataStream>
-#include <QtCore/QUrl>
+#include <QtCore/QDateTime>
#include <QtCore/QEventLoop>
#include <QtCore/QElapsedTimer>
#include <QtCore/QFile>
+#include <QtCore/QList>
#include <QtCore/QRandomGenerator>
#include <QtCore/QRegularExpression>
#include <QtCore/QRegularExpressionMatch>
+#include <QtCore/QSet>
#include <QtCore/QSharedPointer>
#include <QtCore/QScopedPointer>
#include <QtCore/QTemporaryFile>
+#include <QtCore/QTimeZone>
+#include <QtCore/QUrl>
+
#include <QtNetwork/QTcpServer>
#include <QtNetwork/QTcpSocket>
#include <QtNetwork/QLocalSocket>
@@ -66,6 +47,7 @@
#include <QtNetwork/qnetworkdiskcache.h>
#include <QtNetwork/qnetworkrequest.h>
#include <QtNetwork/qnetworkreply.h>
+#include <QtNetwork/QHttp1Configuration>
#include <QtNetwork/qnetworkcookie.h>
#include <QtNetwork/QNetworkCookieJar>
#include <QtNetwork/QHttpPart>
@@ -86,6 +68,9 @@
Q_DECLARE_METATYPE(QSharedPointer<char>)
#endif
+#include <memory>
+#include <optional>
+
#ifdef Q_OS_UNIX
# include <sys/types.h>
# include <unistd.h> // for getuid()
@@ -105,6 +90,9 @@ Q_DECLARE_METATYPE(QNetworkProxyQuery)
typedef QSharedPointer<QNetworkReply> QNetworkReplyPtr;
+using namespace Qt::StringLiterals;
+using namespace std::chrono_literals;
+
#if QT_CONFIG(ssl)
QT_BEGIN_NAMESPACE
// Technically, a workaround, and only needed for OpenSSL:
@@ -146,6 +134,29 @@ class tst_QNetworkReply: public QObject
"\r\n";
return s;
}
+ static QString movedReplyStr() {
+ QString s = "HTTP/1.1 301 Moved Permanently\r\n"
+ "Content-Type: text/plain\r\n"
+ "location: %1\r\n"
+ "\r\n";
+ return s;
+ }
+
+ static QString foundReplyStr() {
+ QString s = "HTTP/1.1 302 Found\r\n"
+ "Content-Type: text/plain\r\n"
+ "location: %1\r\n"
+ "\r\n";
+ return s;
+ }
+
+ static QString permRedirectReplyStr() {
+ QString s = "HTTP/1.1 308 Permanent Redirect\r\n"
+ "Content-Type: text/plain\r\n"
+ "location: %1\r\n"
+ "\r\n";
+ return s;
+ }
static const QByteArray httpEmpty200Response;
static const QString filePermissionFileName;
@@ -229,6 +240,12 @@ private Q_SLOTS:
void getFromFtpAfterError(); // QTBUG-40797
void getFromHttp_data();
void getFromHttp();
+ void getWithBodyFromHttp_data();
+ void getWithBodyFromHttp();
+ void getWithAndWithoutBodyFromHttp_data();
+ void getWithAndWithoutBodyFromHttp();
+ void getWithBodyRedirected_data();
+ void getWithBodyRedirected();
void getErrors_data();
void getErrors();
#if QT_CONFIG(networkproxy)
@@ -246,6 +263,8 @@ private Q_SLOTS:
void putToHttpSynchronous();
void putToHttpMultipart_data();
void putToHttpMultipart();
+ void putWithoutBody();
+ void putWithoutBody_data();
void postToHttp_data();
void postToHttp();
void postToHttpSynchronous_data();
@@ -253,6 +272,8 @@ private Q_SLOTS:
void postToHttpMultipart_data();
void postToHttpMultipart();
void multipartSkipIndices(); // QTBUG-32534
+ void postWithoutBody_data();
+ void postWithoutBody();
#if QT_CONFIG(ssl)
void putToHttps_data();
void putToHttps();
@@ -280,6 +301,7 @@ private Q_SLOTS:
void ioGetFromFileSpecial();
void ioGetFromFile_data();
void ioGetFromFile();
+ void ioGetFromFileUrl();
void ioGetFromFtp_data();
void ioGetFromFtp();
void ioGetFromFtpWithReuse();
@@ -304,8 +326,8 @@ private Q_SLOTS:
#endif
void ioGetFromHttpBrokenServer_data();
void ioGetFromHttpBrokenServer();
- void ioGetFromHttpStatus100_data();
- void ioGetFromHttpStatus100();
+ void ioGetFromHttpStatusInformational_data();
+ void ioGetFromHttpStatusInformational();
void ioGetFromHttpNoHeaders_data();
void ioGetFromHttpNoHeaders();
void ioGetFromHttpWithCache_data();
@@ -462,6 +484,9 @@ private Q_SLOTS:
void varyingCacheExpiry_data();
void varyingCacheExpiry();
+ void amountOfHttp1ConnectionsQtbug25280_data();
+ void amountOfHttp1ConnectionsQtbug25280();
+
void dontInsertPartialContentIntoTheCache();
void httpUserAgent();
@@ -496,6 +521,7 @@ private Q_SLOTS:
void ioHttpCookiesDuringRedirect();
void ioHttpRedirect_data();
void ioHttpRedirect();
+ void ioHttpRedirectWithCache();
void ioHttpRedirectFromLocalToRemote();
void ioHttpRedirectPostPut_data();
void ioHttpRedirectPostPut();
@@ -514,8 +540,8 @@ private Q_SLOTS:
void autoDeleteReplies_data();
void autoDeleteReplies();
- void getWithTimeout();
- void postWithTimeout();
+ void requestWithTimeout_data();
+ void requestWithTimeout();
void moreActivitySignals_data();
void moreActivitySignals();
@@ -528,6 +554,16 @@ private Q_SLOTS:
void cacheWithContentEncoding();
void downloadProgressWithContentEncoding_data();
void downloadProgressWithContentEncoding();
+ void contentEncodingError_data();
+ void contentEncodingError();
+ void compressedReadyRead();
+ void notFoundWithCompression_data();
+ void notFoundWithCompression();
+
+ void qtbug68821proxyError_data();
+ void qtbug68821proxyError();
+
+ void abortAndError();
// NOTE: This test must be last!
void parentingRepliesToTheApp();
@@ -613,7 +649,8 @@ public:
int totalConnections;
bool stopTransfer = false;
- bool hasContent = false;
+ bool checkedContentLength = false;
+ bool foundContentLength = false;
int contentRead = 0;
int contentLength = 0;
@@ -645,6 +682,7 @@ public:
{
contentLength = 0;
receivedData.clear();
+ foundContentLength = false;
}
protected:
@@ -701,8 +739,13 @@ private:
void parseContentLength()
{
- int index = receivedData.indexOf("Content-Length:");
- index += sizeof("Content-Length:") - 1;
+ int index = receivedData.indexOf("content-length:");
+ if (index == -1)
+ return;
+
+ foundContentLength = true;
+
+ index += sizeof("content-length:") - 1;
const auto end = std::find(receivedData.cbegin() + index, receivedData.cend(), '\r');
auto num = receivedData.mid(index, std::distance(receivedData.cbegin() + index, end));
bool ok;
@@ -742,12 +785,14 @@ public slots:
if (doubleEndlPos != -1) {
const int endOfHeader = doubleEndlPos + 4;
- hasContent = receivedData.startsWith("POST") || receivedData.startsWith("PUT")
- || receivedData.startsWith("CUSTOM_WITH_PAYLOAD");
- if (hasContent && contentLength == 0)
+ contentRead = receivedData.size() - endOfHeader;
+
+ if (!checkedContentLength) {
parseContentLength();
- contentRead = receivedData.length() - endOfHeader;
- if (hasContent && contentRead < contentLength)
+ checkedContentLength = true;
+ }
+
+ if (contentRead < contentLength)
return;
// multiple requests incoming. remove the bytes of the current one
@@ -848,7 +893,7 @@ public:
qint64 cacheSize() const override
{
qint64 total = 0;
- foreach (const CachedContent &entry, cache)
+ for (const auto &[_, entry] : cache.asKeyValueRange())
total += entry.second.size();
return total;
}
@@ -1473,11 +1518,11 @@ QString tst_QNetworkReply::runSimpleRequest(QNetworkAccessManager::Operation op,
while (!reply->isFinished()) {
QTimer::singleShot(20000, loop, SLOT(quit()));
code = loop->exec();
- if (count == spy.count() && !reply->isFinished()) {
+ if (count == spy.size() && !reply->isFinished()) {
code = Timeout;
break;
}
- count = spy.count();
+ count = spy.size();
}
delete loop;
loop = 0;
@@ -1543,11 +1588,11 @@ int tst_QNetworkReply::waitForFinish(QNetworkReplyPtr &reply)
QSignalSpy spy(reply.data(), SIGNAL(downloadProgress(qint64,qint64)));
while (!reply->isFinished()) {
QTimer::singleShot(5000, loop, SLOT(quit()));
- if (loop->exec() == Timeout && count == spy.count() && !reply->isFinished()) {
+ if (loop->exec() == Timeout && count == spy.size() && !reply->isFinished()) {
returnCode = Timeout;
break;
}
- count = spy.count();
+ count = spy.size();
}
delete loop;
loop = 0;
@@ -1575,8 +1620,10 @@ void tst_QNetworkReply::initTestCase()
testDataDir = QCoreApplication::applicationDirPath();
#if defined(QT_TEST_SERVER)
- QVERIFY(QtNetworkSettings::verifyConnection(QtNetworkSettings::ftpServerName(), 21));
- QVERIFY(QtNetworkSettings::verifyConnection(QtNetworkSettings::ftpProxyServerName(), 2121));
+ if (ftpSupported) {
+ QVERIFY(QtNetworkSettings::verifyConnection(QtNetworkSettings::ftpServerName(), 21));
+ QVERIFY(QtNetworkSettings::verifyConnection(QtNetworkSettings::ftpProxyServerName(), 2121));
+ }
QVERIFY(QtNetworkSettings::verifyConnection(QtNetworkSettings::httpServerName(), 80));
QVERIFY(QtNetworkSettings::verifyConnection(QtNetworkSettings::httpServerName(), 443));
QVERIFY(QtNetworkSettings::verifyConnection(QtNetworkSettings::httpProxyServerName(), 3128));
@@ -1989,6 +2036,253 @@ void tst_QNetworkReply::getFromHttp()
QCOMPARE(reply->readAll(), reference.readAll());
}
+void tst_QNetworkReply::getWithBodyFromHttp_data()
+{
+ QTest::addColumn<QByteArray>("dataFromClientToServer");
+ QTest::addColumn<bool>("useDevice");
+ QTest::newRow("with-bytearray") << QByteArray("Body 1") << false;
+ QTest::newRow("with-bytearray2") << QByteArray("Body 2") << false;
+ QTest::newRow("with-bytearray3") << QByteArray("Body 3") << false;
+ QTest::newRow("with-device") << QByteArray("Body 1") << true;
+ QTest::newRow("with-device2") << QByteArray("Body 2") << true;
+ QTest::newRow("with-device3") << QByteArray("Body 3") << true;
+}
+
+void tst_QNetworkReply::getWithBodyFromHttp()
+{
+ QFETCH(QByteArray, dataFromClientToServer);
+ QFETCH(bool, useDevice);
+
+ QBuffer buff;
+ buff.setData(dataFromClientToServer);
+ buff.open(QIODevice::ReadOnly);
+
+ QByteArray dataFromServerToClient = QByteArray("Long first line\r\nLong second line");
+ QByteArray httpResponse = QByteArray("HTTP/1.0 200 OK\r\nContent-Length: ");
+ httpResponse += QByteArray::number(dataFromServerToClient.size());
+ httpResponse += "\r\n\r\n";
+ httpResponse += dataFromServerToClient;
+
+ MiniHttpServer server(httpResponse);
+ server.doClose = true;
+
+ QNetworkRequest request(QUrl("http://localhost:" + QString::number(server.serverPort())));
+ QNetworkReplyPtr reply;
+
+ if (useDevice)
+ reply.reset(manager.get(request, &buff));
+ else
+ reply.reset(manager.get(request, dataFromClientToServer));
+
+ QVERIFY2(waitForFinish(reply) == Success, msgWaitForFinished(reply));
+ QCOMPARE(server.contentLength, dataFromClientToServer.size());
+ QCOMPARE(server.receivedData.right(dataFromClientToServer.size()), dataFromClientToServer);
+ QByteArray content = reply->readAll();
+ QCOMPARE(content, dataFromServerToClient);
+}
+
+void tst_QNetworkReply::getWithAndWithoutBodyFromHttp_data()
+{
+ QTest::addColumn<QByteArray>("dataFromClientToServer");
+ QTest::addColumn<bool>("alwaysCache");
+ QTest::addColumn<tst_QNetworkReply::RunSimpleRequestReturn>("requestReturn");
+ QTest::addColumn<bool>("useDevice");
+ QTest::newRow("with-bytearray") << QByteArray("Body 1") << false << Success << false;
+ QTest::newRow("with-bytearray2") << QByteArray("Body 2") << false << Success << false;
+ QTest::newRow("with-bytearray3") << QByteArray("Body 3") << false << Success << false;
+ QTest::newRow("with-bytearray-cache") << QByteArray("Body 1") << true << Failure << false;
+ QTest::newRow("with-bytearray-cache2") << QByteArray("Body 2") << true << Failure << false;
+ QTest::newRow("with-bytearray-cache3") << QByteArray("Body 3") << true << Failure << false;
+ QTest::newRow("with-device") << QByteArray("Body 1") << false << Success << true;
+ QTest::newRow("with-device2") << QByteArray("Body 2") << false << Success << true;
+ QTest::newRow("with-device3") << QByteArray("Body 3") << false << Success << true;
+ QTest::newRow("with-device-cache") << QByteArray("Body 1") << true << Failure << true;
+ QTest::newRow("with-device-cache2") << QByteArray("Body 2") << true << Failure << true;
+ QTest::newRow("with-device-cache3") << QByteArray("Body 3") << true << Failure << true;
+}
+
+void tst_QNetworkReply::getWithAndWithoutBodyFromHttp()
+{
+ QFETCH(QByteArray, dataFromClientToServer);
+ QFETCH(bool, alwaysCache);
+ QFETCH(tst_QNetworkReply::RunSimpleRequestReturn, requestReturn);
+ QFETCH(bool, useDevice);
+
+ QBuffer buff;
+ buff.setData(dataFromClientToServer);
+ buff.open(QIODevice::ReadOnly);
+
+ QNetworkAccessManager qnam;
+ MyMemoryCache *memoryCache = new MyMemoryCache(&qnam);
+ qnam.setCache(memoryCache);
+
+ const int sizeOfDataFromServerToClient =3;
+ QByteArray dataFromServerToClient1 = QByteArray("aaa");
+ QByteArray dataFromServerToClient2 = QByteArray("bbb");
+ QByteArray dataFromServerToClient3 = QByteArray("ccc");
+
+ QByteArray baseHttpResponse = QByteArray("HTTP/1.0 200 OK\r\nContent-Length: ");
+ baseHttpResponse += QByteArray::number(sizeOfDataFromServerToClient);
+ baseHttpResponse += "\r\n\r\n";
+
+ MiniHttpServer server(baseHttpResponse + dataFromServerToClient1);
+ server.doClose = true;
+
+ QNetworkRequest request(QUrl("http://localhost:" + QString::number(server.serverPort())));
+
+ // Send request without body
+ QNetworkReplyPtr reply(manager.get(request));
+ QVERIFY2(waitForFinish(reply) == Success, msgWaitForFinished(reply));
+ QByteArray content = reply->readAll();
+ QCOMPARE(content, dataFromServerToClient1);
+
+ if (alwaysCache) {
+ request.setAttribute(QNetworkRequest::CacheLoadControlAttribute,
+ QNetworkRequest::AlwaysCache);
+ }
+
+ server.dataToTransmit = baseHttpResponse + dataFromServerToClient2;
+
+ // Send request with body
+ QNetworkReplyPtr reply2;
+ if (useDevice)
+ reply2.reset(manager.get(request, &buff));
+ else
+ reply2.reset(manager.get(request, dataFromClientToServer));
+
+ QVERIFY2(waitForFinish(reply2) == requestReturn, msgWaitForFinished(reply2));
+ content = reply2->readAll();
+
+ if (alwaysCache)
+ QVERIFY(content.isEmpty());
+ else
+ QCOMPARE(content, dataFromServerToClient2);
+
+ QCOMPARE(reply2->attribute(QNetworkRequest::SourceIsFromCacheAttribute).toBool(), false);
+
+ if (alwaysCache) {
+ request.setAttribute(QNetworkRequest::CacheLoadControlAttribute,
+ QNetworkRequest::PreferNetwork);
+ }
+
+ server.dataToTransmit = baseHttpResponse + dataFromServerToClient3;
+
+ // Send another request without a body
+ QNetworkReplyPtr reply3(manager.get(request));
+ QVERIFY2(waitForFinish(reply3) == Success, msgWaitForFinished(reply3));
+ content = reply3->readAll();
+ QCOMPARE(content, dataFromServerToClient3);
+ QCOMPARE(reply3->attribute(QNetworkRequest::SourceIsFromCacheAttribute).toBool(), false);
+}
+
+void tst_QNetworkReply::getWithBodyRedirected_data()
+{
+ QTest::addColumn<QByteArray>("dataFromClientToServer");
+ QTest::addColumn<bool>("useDevice");
+ QTest::addColumn<int>("status");
+ QTest::newRow("with-bytearray - 301") << QByteArray("Body 1") << false << 301;
+ QTest::newRow("with-bytearray2 - 301") << QByteArray("Body 2") << false << 301;
+ QTest::newRow("with-bytearray3 - 301") << QByteArray("Body 3") << false << 301;
+ QTest::newRow("with-device - 301") << QByteArray("Body 1") << true << 301;
+ QTest::newRow("with-device2 - 301") << QByteArray("Body 2") << true << 301;
+ QTest::newRow("with-device3 - 301") << QByteArray("Body 3") << true << 301;
+ QTest::newRow("with-bytearray - 302") << QByteArray("Body 1") << false << 302;
+ QTest::newRow("with-bytearray2 - 302") << QByteArray("Body 2") << false << 302;
+ QTest::newRow("with-bytearray3 - 302") << QByteArray("Body 3") << false << 302;
+ QTest::newRow("with-device - 302") << QByteArray("Body 1") << true << 302;
+ QTest::newRow("with-device2 - 302") << QByteArray("Body 2") << true << 302;
+ QTest::newRow("with-device3 - 302") << QByteArray("Body 3") << true << 302;
+ QTest::newRow("with-bytearray - 307") << QByteArray("Body 1") << false << 307;
+ QTest::newRow("with-bytearray2 - 307") << QByteArray("Body 2") << false << 307;
+ QTest::newRow("with-bytearray3 - 307") << QByteArray("Body 3") << false << 307;
+ QTest::newRow("with-device - 307") << QByteArray("Body 1") << true << 307;
+ QTest::newRow("with-device2 - 307") << QByteArray("Body 2") << true << 307;
+ QTest::newRow("with-device3 - 307") << QByteArray("Body 3") << true << 307;
+ QTest::newRow("with-bytearray - 308") << QByteArray("Body 1") << false << 308;
+ QTest::newRow("with-bytearray2 - 308") << QByteArray("Body 2") << false << 308;
+ QTest::newRow("with-bytearray3 - 308") << QByteArray("Body 3") << false << 308;
+ QTest::newRow("with-device - 308") << QByteArray("Body 1") << true << 308;
+ QTest::newRow("with-device2 - 308") << QByteArray("Body 2") << true << 308;
+ QTest::newRow("with-device3 - 308") << QByteArray("Body 3") << true << 308;
+}
+
+void tst_QNetworkReply::getWithBodyRedirected()
+{
+ QFETCH(QByteArray, dataFromClientToServer);
+ QFETCH(bool, useDevice);
+ QFETCH(int, status);
+
+ QBuffer buff;
+ buff.setData(dataFromClientToServer);
+ buff.open(QIODevice::ReadOnly);
+
+ QUrl localhost = QUrl("http://localhost");
+
+ // Setup server to which the second server will redirect to
+ MiniHttpServer server2(httpEmpty200Response);
+
+ QUrl redirectUrl = QUrl(localhost);
+ redirectUrl.setPort(server2.serverPort());
+
+ QByteArray redirectReply;
+ switch (status) {
+ case 301: redirectReply =
+ foundReplyStr().arg(QString(redirectUrl.toEncoded())).toLatin1(); break;
+ case 302: redirectReply =
+ movedReplyStr().arg(QString(redirectUrl.toEncoded())).toLatin1(); break;
+ case 307: redirectReply =
+ tempRedirectReplyStr().arg(QString(redirectUrl.toEncoded())).toLatin1(); break;
+ case 308: redirectReply =
+ permRedirectReplyStr().arg(QString(redirectUrl.toEncoded())).toLatin1(); break;
+ default: QFAIL("Unexpected status code"); break;
+ }
+
+ // Setup redirect server
+ MiniHttpServer server(redirectReply);
+
+ localhost.setPort(server.serverPort());
+ QNetworkRequest request(localhost);
+ request.setAttribute(QNetworkRequest::RedirectPolicyAttribute,
+ QNetworkRequest::NoLessSafeRedirectPolicy);
+
+ QNetworkReplyPtr reply;
+ if (useDevice)
+ reply.reset(manager.get(request, &buff));
+ else
+ reply.reset(manager.get(request, dataFromClientToServer));
+
+ QSignalSpy redSpy(reply.data(), SIGNAL(redirected(QUrl)));
+ QSignalSpy finSpy(reply.data(), SIGNAL(finished()));
+
+ QVERIFY2(waitForFinish(reply) == Success, msgWaitForFinished(reply));
+
+ // Redirected and finished should be emitted exactly once
+ QCOMPARE(redSpy.size(), 1);
+ QCOMPARE(finSpy.size(), 1);
+
+ // Original URL should not be changed after redirect
+ QCOMPARE(request.url(), localhost);
+
+ // Verify Redirect url
+ QList<QVariant> args = redSpy.takeFirst();
+ QCOMPARE(args.at(0).toUrl(), redirectUrl);
+
+ // Reply url is set to the redirect url
+ QCOMPARE(reply->url(), redirectUrl);
+ QCOMPARE(reply->error(), QNetworkReply::NoError);
+ QVERIFY(validateRedirectedResponseHeaders(reply));
+
+ // Verify that the message body has arrived to the server
+ if (status > 302) {
+ QVERIFY(server2.contentLength != 0);
+ QCOMPARE(server2.contentLength, dataFromClientToServer.size());
+ QCOMPARE(server2.receivedData.right(dataFromClientToServer.size()), dataFromClientToServer);
+ } else {
+ // In these cases the message body should not reach the server
+ QVERIFY(server2.contentLength == 0);
+ }
+}
+
#if QT_CONFIG(networkproxy)
void tst_QNetworkReply::headFromHttp_data()
{
@@ -2008,7 +2302,7 @@ void tst_QNetworkReply::headFromHttp_data()
QString httpServer = QtNetworkSettings::httpServerName();
//testing proxies, mainly for the 407 response from http proxy
- for (int i = 0; i < proxies.count(); ++i) {
+ for (int i = 0; i < proxies.size(); ++i) {
QTest::newRow("rfc" + proxies.at(i).tag)
<< rfcsize
<< QUrl("http://" + httpServer + "/qtest/rfc3252.txt")
@@ -2290,9 +2584,9 @@ void tst_QNetworkReply::putToFtp()
QSignalSpy spy(r, SIGNAL(downloadProgress(qint64,qint64)));
while (!r->isFinished()) {
QTestEventLoop::instance().enterLoop(10);
- if (count == spy.count() && !r->isFinished())
+ if (count == spy.size() && !r->isFinished())
break;
- count = spy.count();
+ count = spy.size();
}
QObject::disconnect(r, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop()));
@@ -2407,6 +2701,48 @@ void tst_QNetworkReply::putToHttpSynchronous()
QCOMPARE(uploadedData, data);
}
+void tst_QNetworkReply::putWithoutBody_data()
+{
+ QTest::addColumn<bool>("client_data");
+
+ QTest::newRow("client_has_data") << true;
+ QTest::newRow("client_does_not_have_data") << false;
+}
+
+void tst_QNetworkReply::putWithoutBody()
+{
+ QFETCH(bool, client_data);
+
+ QBuffer buff;
+
+ if (client_data) {
+ buff.setData("Dummy data from client to server");
+ buff.open(QIODevice::ReadOnly);
+ }
+
+ QByteArray dataFromServerToClient = QByteArray("Some ridiculous dummy data");
+ QByteArray httpResponse = QByteArray("HTTP/1.0 200 OK\r\nContent-Length: ");
+ httpResponse += QByteArray::number(dataFromServerToClient.size());
+ httpResponse += "\r\n\r\n";
+ httpResponse += dataFromServerToClient;
+
+ MiniHttpServer server(httpResponse);
+ server.doClose = true;
+
+ QNetworkRequest request(QUrl("http://localhost:" + QString::number(server.serverPort())));
+ request.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("text/plain"));
+
+ QNetworkReplyPtr reply;
+ if (client_data)
+ reply.reset(manager.put(request, &buff));
+ else
+ reply.reset(manager.put(request, nullptr));
+
+ QVERIFY2(waitForFinish(reply) == Success, msgWaitForFinished(reply));
+ QCOMPARE(server.foundContentLength, client_data);
+}
+
+
void tst_QNetworkReply::postToHttp_data()
{
putToFile_data();
@@ -2724,8 +3060,8 @@ void tst_QNetworkReply::postToHttpMultipart()
QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200); // 200 Ok
- QVERIFY(multiPart->boundary().count() > 20); // check that there is randomness after the "boundary_.oOo._" string
- QVERIFY(multiPart->boundary().count() < 70);
+ QVERIFY(multiPart->boundary().size() > 20); // check that there is randomness after the "boundary_.oOo._" string
+ QVERIFY(multiPart->boundary().size() < 70);
QByteArray replyData = reply->readAll();
expectedReplyData.prepend("content type: multipart/" + contentType + "; boundary=\"" + multiPart->boundary() + "\"\n");
@@ -2776,6 +3112,47 @@ void tst_QNetworkReply::multipartSkipIndices() // QTBUG-32534
multiPart->deleteLater();
}
+void tst_QNetworkReply::postWithoutBody_data()
+{
+ QTest::addColumn<bool>("client_data");
+
+ QTest::newRow("client_has_data") << true;
+ QTest::newRow("client_does_not_have_data") << false;
+}
+
+void tst_QNetworkReply::postWithoutBody()
+{
+ QFETCH(bool, client_data);
+
+ QBuffer buff;
+
+ if (client_data) {
+ buff.setData("Dummy data from client to server");
+ buff.open(QIODevice::ReadOnly);
+ }
+
+ QByteArray dataFromServerToClient = QByteArray("Some ridiculous dummy data");
+ QByteArray httpResponse = QByteArray("HTTP/1.0 200 OK\r\nContent-Length: ");
+ httpResponse += QByteArray::number(dataFromServerToClient.size());
+ httpResponse += "\r\n\r\n";
+ httpResponse += dataFromServerToClient;
+
+ MiniHttpServer server(httpResponse);
+ server.doClose = true;
+
+ QNetworkRequest request(QUrl("http://localhost:" + QString::number(server.serverPort())));
+ request.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("text/plain"));
+
+ QNetworkReplyPtr reply;
+ if (client_data)
+ reply.reset(manager.post(request, &buff));
+ else
+ reply.reset(manager.post(request, nullptr));
+
+ QVERIFY2(waitForFinish(reply) == Success, msgWaitForFinished(reply));
+ QCOMPARE(server.foundContentLength, client_data);
+}
+
void tst_QNetworkReply::putToHttpMultipart_data()
{
postToHttpMultipart_data();
@@ -2812,8 +3189,8 @@ void tst_QNetworkReply::putToHttpMultipart()
QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200); // 200 Ok
- QVERIFY(multiPart->boundary().count() > 20); // check that there is randomness after the "boundary_.oOo._" string
- QVERIFY(multiPart->boundary().count() < 70);
+ QVERIFY(multiPart->boundary().size() > 20); // check that there is randomness after the "boundary_.oOo._" string
+ QVERIFY(multiPart->boundary().size() < 70);
QByteArray replyData = reply->readAll();
expectedReplyData.prepend("content type: multipart/" + contentType + "; boundary=\"" + multiPart->boundary() + "\"\n");
@@ -3030,8 +3407,8 @@ void tst_QNetworkReply::postToHttpsMultipart()
QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200); // 200 Ok
- QVERIFY(multiPart->boundary().count() > 20); // check that there is randomness after the "boundary_.oOo._" string
- QVERIFY(multiPart->boundary().count() < 70);
+ QVERIFY(multiPart->boundary().size() > 20); // check that there is randomness after the "boundary_.oOo._" string
+ QVERIFY(multiPart->boundary().size() < 70);
QByteArray replyData = reply->readAll();
expectedReplyData.prepend("content type: multipart/" + contentType + "; boundary=\"" + multiPart->boundary() + "\"\n");
@@ -3167,7 +3544,7 @@ void tst_QNetworkReply::connectToIPv6Address()
if (!QtNetworkSettings::hasIPv6())
QSKIP("system doesn't support ipv6!");
- QByteArray httpResponse = QByteArray("HTTP/1.0 200 OK\r\nContent-Length: ");
+ QByteArray httpResponse = QByteArray("HTTP/1.0 200 OK\r\ncontent-length: ");
httpResponse += QByteArray::number(dataToSend.size());
httpResponse += "\r\n\r\n";
httpResponse += dataToSend;
@@ -3182,7 +3559,7 @@ void tst_QNetworkReply::connectToIPv6Address()
QVERIFY2(waitForFinish(reply) == Success, msgWaitForFinished(reply));
QByteArray content = reply->readAll();
//qDebug() << server.receivedData;
- QByteArray hostinfo = "\r\nHost: " + hostfield + ':' + QByteArray::number(server.serverPort()) + "\r\n";
+ QByteArray hostinfo = "\r\nhost: " + hostfield + ':' + QByteArray::number(server.serverPort()) + "\r\n";
QVERIFY(server.receivedData.contains(hostinfo));
QCOMPARE(content, dataToSend);
QCOMPARE(reply->url(), request.url());
@@ -3344,6 +3721,18 @@ void tst_QNetworkReply::ioGetFromFile()
QCOMPARE(reader.data, data);
}
+void tst_QNetworkReply::ioGetFromFileUrl()
+{
+ // This immediately fails on non-windows platforms:
+ QNetworkRequest request(QUrl("file://unc-server/some/path"));
+ QNetworkReplyPtr reply(manager.get(request));
+ QSignalSpy finishedSpy(reply.get(), &QNetworkReply::finished);
+ // QTBUG-105618: This would, on non-Windows platforms, never happen because the signal
+ // was emitted before the constructor finished, leaving no chance at all to connect to the
+ // signal
+ QVERIFY(finishedSpy.wait());
+}
+
void tst_QNetworkReply::ioGetFromFtp_data()
{
if (!ftpSupported)
@@ -3361,7 +3750,9 @@ void tst_QNetworkReply::ioGetFromFtp()
{
QFETCH(QString, fileName);
QFile reference(fileName);
- reference.open(QIODevice::ReadOnly); // will fail for bigfile
+ const bool ok = reference.open(QIODevice::ReadOnly); // will fail for bigfile
+ if (fileName != "bigfile")
+ QVERIFY(ok);
QNetworkRequest request("ftp://" + QtNetworkSettings::ftpServerName() + "/qtest/" + fileName);
QNetworkReplyPtr reply(manager.get(request));
@@ -3386,7 +3777,7 @@ void tst_QNetworkReply::ioGetFromFtpWithReuse()
QSKIP("FTP is not supported");
QString fileName = testDataDir + "/rfc3252.txt";
QFile reference(fileName);
- reference.open(QIODevice::ReadOnly);
+ QVERIFY(reference.open(QIODevice::ReadOnly));
QNetworkRequest request(QUrl("ftp://" + QtNetworkSettings::ftpServerName() + "/qtest/rfc3252.txt"));
@@ -3516,7 +3907,7 @@ void tst_QNetworkReply::ioGetFromHttpWithAuth_data()
QTest::addColumn<int>("expectedAuth");
QFile reference(testDataDir + "/rfc3252.txt");
- reference.open(QIODevice::ReadOnly);
+ QVERIFY(reference.open(QIODevice::ReadOnly));
QByteArray referenceData = reference.readAll();
QString httpServer = QtNetworkSettings::httpServerName();
QTest::newRow("basic")
@@ -3590,7 +3981,7 @@ void tst_QNetworkReply::ioGetFromHttpWithAuth()
QCOMPARE(reader1.data, expectedData);
QCOMPARE(reader2.data, expectedData);
- QCOMPARE(authspy.count(), (expectedAuth ? 1 : 0));
+ QCOMPARE(authspy.size(), (expectedAuth ? 1 : 0));
expectedAuth = qMax(0, expectedAuth - 1);
}
@@ -3611,7 +4002,7 @@ void tst_QNetworkReply::ioGetFromHttpWithAuth()
QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200);
QCOMPARE(reader.data, expectedData);
- QCOMPARE(authspy.count(), (expectedAuth ? 1 : 0));
+ QCOMPARE(authspy.size(), (expectedAuth ? 1 : 0));
expectedAuth = qMax(0, expectedAuth - 1);
}
@@ -3628,7 +4019,7 @@ void tst_QNetworkReply::ioGetFromHttpWithAuth()
// bad credentials in a synchronous request should just fail
QCOMPARE(replySync->error(), QNetworkReply::AuthenticationRequiredError);
} else {
- QCOMPARE(authspy.count(), 0);
+ QCOMPARE(authspy.size(), 0);
// we cannot use a data reader here, since that connects to the readyRead signal,
// just use readAll()
@@ -3654,7 +4045,7 @@ void tst_QNetworkReply::ioGetFromHttpWithAuth()
// bad credentials in a synchronous request should just fail
QCOMPARE(replySync->error(), QNetworkReply::AuthenticationRequiredError);
} else {
- QCOMPARE(authspy.count(), 0);
+ QCOMPARE(authspy.size(), 0);
// we cannot use a data reader here, since that connects to the readyRead signal,
// just use readAll()
@@ -3680,7 +4071,7 @@ void tst_QNetworkReply::ioGetFromHttpWithAuthSynchronous()
QNetworkReplyPtr replySync(manager.get(request));
QVERIFY(replySync->isFinished()); // synchronous
QCOMPARE(replySync->error(), QNetworkReply::AuthenticationRequiredError);
- QCOMPARE(authspy.count(), 0);
+ QCOMPARE(authspy.size(), 0);
QCOMPARE(replySync->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 401);
}
@@ -3721,7 +4112,7 @@ void tst_QNetworkReply::ioGetFromHttpWithProxyAuth()
QCOMPARE(reader1.data, referenceData);
QCOMPARE(reader2.data, referenceData);
- QCOMPARE(authspy.count(), 1);
+ QCOMPARE(authspy.size(), 1);
}
reference.seek(0);
@@ -3744,7 +4135,7 @@ void tst_QNetworkReply::ioGetFromHttpWithProxyAuth()
QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200);
QCOMPARE(reader.data, reference.readAll());
- QCOMPARE(authspy.count(), 0);
+ QCOMPARE(authspy.size(), 0);
}
// now check with synchronous calls:
@@ -3757,7 +4148,7 @@ void tst_QNetworkReply::ioGetFromHttpWithProxyAuth()
QSignalSpy authspy(&manager, SIGNAL(proxyAuthenticationRequired(QNetworkProxy,QAuthenticator*)));
QNetworkReplyPtr replySync(manager.get(request));
QVERIFY(replySync->isFinished()); // synchronous
- QCOMPARE(authspy.count(), 0);
+ QCOMPARE(authspy.size(), 0);
// we cannot use a data reader here, since that connects to the readyRead signal,
// just use readAll()
@@ -3785,7 +4176,7 @@ void tst_QNetworkReply::ioGetFromHttpWithProxyAuthSynchronous()
manager.setProxy(QNetworkProxy()); // reset
QVERIFY(replySync->isFinished()); // synchronous
QCOMPARE(replySync->error(), QNetworkReply::ProxyAuthenticationRequiredError);
- QCOMPARE(authspy.count(), 0);
+ QCOMPARE(authspy.size(), 0);
QCOMPARE(replySync->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 407);
}
@@ -3817,7 +4208,7 @@ void tst_QNetworkReply::ioGetFromHttpWithSocksProxy()
QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200);
QCOMPARE(reader.data, reference.readAll());
- QCOMPARE(authspy.count(), 0);
+ QCOMPARE(authspy.size(), 0);
}
// set an invalid proxy just to make sure that we can't load
@@ -3841,10 +4232,9 @@ void tst_QNetworkReply::ioGetFromHttpWithSocksProxy()
QVERIFY(reader.data.isEmpty());
QVERIFY(int(reply->error()) > 0);
- QEXPECT_FAIL("", "QTcpSocket doesn't return enough information yet", Continue);
QCOMPARE(int(reply->error()), int(QNetworkReply::ProxyConnectionRefusedError));
- QCOMPARE(authspy.count(), 0);
+ QCOMPARE(authspy.size(), 0);
}
}
#endif // QT_CONFIG(networkproxy)
@@ -3872,7 +4262,7 @@ void tst_QNetworkReply::ioGetFromHttpsWithSslErrors()
QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200);
QCOMPARE(reader.data, reference.readAll());
- QCOMPARE(sslspy.count(), 1);
+ QCOMPARE(sslspy.size(), 1);
QVERIFY(!storedSslConfiguration.isNull());
QVERIFY(!reply->sslConfiguration().isNull());
@@ -3900,7 +4290,7 @@ void tst_QNetworkReply::ioGetFromHttpsWithIgnoreSslErrors()
QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200);
QCOMPARE(reader.data, reference.readAll());
- QCOMPARE(sslspy.count(), 1);
+ QCOMPARE(sslspy.size(), 1);
QVERIFY(!storedSslConfiguration.isNull());
QVERIFY(!reply->sslConfiguration().isNull());
@@ -3923,7 +4313,7 @@ void tst_QNetworkReply::ioGetFromHttpsWithSslHandshakeError()
QCOMPARE(waitForFinish(reply), int(Failure));
QCOMPARE(reply->error(), QNetworkReply::SslHandshakeFailedError);
- QCOMPARE(sslspy.count(), 0);
+ QCOMPARE(sslspy.size(), 0);
}
#endif
@@ -3981,11 +4371,11 @@ void tst_QNetworkReply::ioGetFromHttpBrokenServer()
QCOMPARE(waitForFinish(reply), int(Failure));
QCOMPARE(reply->url(), request.url());
- QCOMPARE(spy.count(), 1);
+ QCOMPARE(spy.size(), 1);
QVERIFY(reply->error() != QNetworkReply::NoError);
}
-void tst_QNetworkReply::ioGetFromHttpStatus100_data()
+void tst_QNetworkReply::ioGetFromHttpStatusInformational_data()
{
QTest::addColumn<QByteArray>("dataToSend");
QTest::addColumn<int>("statusCode");
@@ -3996,9 +4386,25 @@ void tst_QNetworkReply::ioGetFromHttpStatus100_data()
QTest::newRow("minimal+404") << QByteArray("HTTP/1.1 100 Continue\n\nHTTP/1.0 204 No Content\r\n\r\n") << 204;
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;
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;
+
+ QTest::newRow("normal-custom") << QByteArray("HTTP/1.1 133 Custom\r\n\r\nHTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n") << 200;
+ QTest::newRow("minimal-custom") << QByteArray("HTTP/1.1 133 Custom\n\nHTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n") << 200;
+ QTest::newRow("minimal2-custom") << QByteArray("HTTP/1.1 133 Custom\n\nHTTP/1.0 200 OK\r\n\r\n") << 200;
+ QTest::newRow("minimal3-custom") << QByteArray("HTTP/1.1 133 Custom\n\nHTTP/1.0 200 OK\n\n") << 200;
+ QTest::newRow("minimal+404-custom") << QByteArray("HTTP/1.1 133 Custom\n\nHTTP/1.0 204 No Content\r\n\r\n") << 204;
+ QTest::newRow("with_headers-custom") << QByteArray("HTTP/1.1 133 Custom\r\nBla: x\r\n\r\nHTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n") << 200;
+ QTest::newRow("with_headers2-custom") << QByteArray("HTTP/1.1 133 Custom\nBla: x\n\nHTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n") << 200;
+
+ QTest::newRow("normal-custom2") << QByteArray("HTTP/1.1 179 Custom2\r\n\r\nHTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n") << 200;
+ QTest::newRow("minimal-custom2") << QByteArray("HTTP/1.1 179 Custom2\n\nHTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n") << 200;
+ QTest::newRow("minimal2-custom2") << QByteArray("HTTP/1.1 179 Custom2\n\nHTTP/1.0 200 OK\r\n\r\n") << 200;
+ QTest::newRow("minimal3-custom2") << QByteArray("HTTP/1.1 179 Custom2\n\nHTTP/1.0 200 OK\n\n") << 200;
+ QTest::newRow("minimal+404-custom2") << QByteArray("HTTP/1.1 179 Custom2\n\nHTTP/1.0 204 No Content\r\n\r\n") << 204;
+ QTest::newRow("with_headers-custom2") << QByteArray("HTTP/1.1 179 Custom2\r\nBla: x\r\n\r\nHTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n") << 200;
+ QTest::newRow("with_headers2-custom2") << QByteArray("HTTP/1.1 179 Custom2\nBla: x\n\nHTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n") << 200;
}
-void tst_QNetworkReply::ioGetFromHttpStatus100()
+void tst_QNetworkReply::ioGetFromHttpStatusInformational()
{
QFETCH(QByteArray, dataToSend);
QFETCH(int, statusCode);
@@ -4317,15 +4723,15 @@ void tst_QNetworkReply::ioGetWithManyProxies_data()
// Tests that fail:
- // HTTP request with FTP caching proxy
- proxyList.clear();
- proxyList << QNetworkProxy(QNetworkProxy::FtpCachingProxy, QtNetworkSettings::ftpProxyServerName(), 2121);
- QTest::newRow("http-on-ftp")
- << proxyList << QNetworkProxy()
- << "http://" + QtNetworkSettings::httpServerName() + "/qtest/rfc3252.txt"
- << QNetworkReply::ProxyNotFoundError;
-
if (ftpSupported) {
+ // HTTP request with FTP caching proxy
+ proxyList.clear();
+ proxyList << QNetworkProxy(QNetworkProxy::FtpCachingProxy, QtNetworkSettings::ftpProxyServerName(), 2121);
+ QTest::newRow("http-on-ftp")
+ << proxyList << QNetworkProxy()
+ << "http://" + QtNetworkSettings::httpServerName() + "/qtest/rfc3252.txt"
+ << QNetworkReply::ProxyNotFoundError;
+
// FTP request with HTTP caching proxy
proxyList.clear();
proxyList << QNetworkProxy(QNetworkProxy::HttpCachingProxy,
@@ -4356,13 +4762,15 @@ void tst_QNetworkReply::ioGetWithManyProxies_data()
<< "https://" + QtNetworkSettings::httpServerName() + "/qtest/rfc3252.txt"
<< QNetworkReply::ProxyNotFoundError;
- // HTTPS with FTP caching proxy
- proxyList.clear();
- proxyList << QNetworkProxy(QNetworkProxy::FtpCachingProxy, QtNetworkSettings::ftpProxyServerName(), 2121);
- QTest::newRow("https-on-ftp")
- << proxyList << QNetworkProxy()
- << "https://" + QtNetworkSettings::httpServerName() + "/qtest/rfc3252.txt"
- << QNetworkReply::ProxyNotFoundError;
+ if (ftpSupported) {
+ // HTTPS with FTP caching proxy
+ proxyList.clear();
+ proxyList << QNetworkProxy(QNetworkProxy::FtpCachingProxy, QtNetworkSettings::ftpProxyServerName(), 2121);
+ QTest::newRow("https-on-ftp")
+ << proxyList << QNetworkProxy()
+ << "https://" + QtNetworkSettings::httpServerName() + "/qtest/rfc3252.txt"
+ << QNetworkReply::ProxyNotFoundError;
+ }
#endif
// Complex requests:
@@ -4385,15 +4793,17 @@ void tst_QNetworkReply::ioGetWithManyProxies_data()
<< "http://" + QtNetworkSettings::httpServerName() + "/qtest/rfc3252.txt"
<< QNetworkReply::NoError;
- // HTTP request with FTP + HTTP + SOCKS
- proxyList.clear();
- proxyList << QNetworkProxy(QNetworkProxy::FtpCachingProxy, QtNetworkSettings::ftpProxyServerName(), 2121)
- << QNetworkProxy(QNetworkProxy::HttpCachingProxy, QtNetworkSettings::httpProxyServerName(), 3129)
- << QNetworkProxy(QNetworkProxy::Socks5Proxy, QtNetworkSettings::socksProxyServerName(), 1081);
- QTest::newRow("http-on-ftp+http+socks")
- << proxyList << proxyList.at(1) // second proxy should be used
- << "http://" + QtNetworkSettings::httpServerName() + "/qtest/rfc3252.txt"
- << QNetworkReply::NoError;
+ if (ftpSupported) {
+ // HTTP request with FTP + HTTP + SOCKS
+ proxyList.clear();
+ proxyList << QNetworkProxy(QNetworkProxy::FtpCachingProxy, QtNetworkSettings::ftpProxyServerName(), 2121)
+ << QNetworkProxy(QNetworkProxy::HttpCachingProxy, QtNetworkSettings::httpProxyServerName(), 3129)
+ << QNetworkProxy(QNetworkProxy::Socks5Proxy, QtNetworkSettings::socksProxyServerName(), 1081);
+ QTest::newRow("http-on-ftp+http+socks")
+ << proxyList << proxyList.at(1) // second proxy should be used
+ << "http://" + QtNetworkSettings::httpServerName() + "/qtest/rfc3252.txt"
+ << QNetworkReply::NoError;
+ }
// HTTP request with NoProxy + HTTP
proxyList.clear();
@@ -4405,15 +4815,15 @@ void tst_QNetworkReply::ioGetWithManyProxies_data()
<< QNetworkReply::NoError;
// HTTP request with FTP + NoProxy
- proxyList.clear();
- proxyList << QNetworkProxy(QNetworkProxy::FtpCachingProxy, QtNetworkSettings::ftpProxyServerName(), 2121)
- << QNetworkProxy(QNetworkProxy::NoProxy);
- QTest::newRow("http-on-ftp+noproxy")
- << proxyList << proxyList.at(1) // second proxy should be used
- << "http://" + QtNetworkSettings::httpServerName() + "/qtest/rfc3252.txt"
- << QNetworkReply::NoError;
-
if (ftpSupported) {
+ proxyList.clear();
+ proxyList << QNetworkProxy(QNetworkProxy::FtpCachingProxy, QtNetworkSettings::ftpProxyServerName(), 2121)
+ << QNetworkProxy(QNetworkProxy::NoProxy);
+ QTest::newRow("http-on-ftp+noproxy")
+ << proxyList << proxyList.at(1) // second proxy should be used
+ << "http://" + QtNetworkSettings::httpServerName() + "/qtest/rfc3252.txt"
+ << QNetworkReply::NoError;
+
// FTP request with HTTP Caching + FTP
proxyList.clear();
proxyList << QNetworkProxy(QNetworkProxy::HttpCachingProxy,
@@ -4436,15 +4846,17 @@ void tst_QNetworkReply::ioGetWithManyProxies_data()
<< "https://" + QtNetworkSettings::httpServerName() + "/qtest/rfc3252.txt"
<< QNetworkReply::NoError;
- // HTTPS request with FTP + HTTP C + HTTP T
- proxyList.clear();
- proxyList << QNetworkProxy(QNetworkProxy::FtpCachingProxy, QtNetworkSettings::ftpProxyServerName(), 2121)
- << QNetworkProxy(QNetworkProxy::HttpCachingProxy, QtNetworkSettings::httpProxyServerName(), 3129)
- << QNetworkProxy(QNetworkProxy::HttpProxy, QtNetworkSettings::httpProxyServerName(), 3129);
- QTest::newRow("https-on-ftp+httpcaching+http")
- << proxyList << proxyList.at(2) // skip the first two
- << "https://" + QtNetworkSettings::httpServerName() + "/qtest/rfc3252.txt"
- << QNetworkReply::NoError;
+ if (ftpSupported) {
+ // HTTPS request with FTP + HTTP C + HTTP T
+ proxyList.clear();
+ proxyList << QNetworkProxy(QNetworkProxy::FtpCachingProxy, QtNetworkSettings::ftpProxyServerName(), 2121)
+ << QNetworkProxy(QNetworkProxy::HttpCachingProxy, QtNetworkSettings::httpProxyServerName(), 3129)
+ << QNetworkProxy(QNetworkProxy::HttpProxy, QtNetworkSettings::httpProxyServerName(), 3129);
+ QTest::newRow("https-on-ftp+httpcaching+http")
+ << proxyList << proxyList.at(2) // skip the first two
+ << "https://" + QtNetworkSettings::httpServerName() + "/qtest/rfc3252.txt"
+ << QNetworkReply::NoError;
+ }
#endif
}
@@ -4499,16 +4911,16 @@ void tst_QNetworkReply::ioGetWithManyProxies()
// now verify that the proxies worked:
QFETCH(QNetworkProxy, proxyUsed);
if (proxyUsed.type() == QNetworkProxy::NoProxy) {
- QCOMPARE(authspy.count(), 0);
+ QCOMPARE(authspy.size(), 0);
} else {
if (QByteArray(QTest::currentDataTag()).startsWith("ftp-"))
return; // No authentication with current FTP or with FTP proxies
- QCOMPARE(authspy.count(), 1);
+ QCOMPARE(authspy.size(), 1);
QCOMPARE(qvariant_cast<QNetworkProxy>(authspy.at(0).at(0)), proxyUsed);
}
} else {
// request failed
- QCOMPARE(authspy.count(), 0);
+ QCOMPARE(authspy.size(), 0);
}
}
#endif // QT_CONFIG(networkproxy)
@@ -4676,6 +5088,10 @@ void tst_QNetworkReply::ioPutToFileFromProcess()
QByteArray contents = file.readAll();
QCOMPARE(contents, data);
+ if (process.state() == QProcess::Running)
+ QVERIFY(process.waitForFinished());
+ QCOMPARE(process.exitCode(), 0);
+
#endif // QT_CONFIG(process)
}
@@ -4814,7 +5230,7 @@ void tst_QNetworkReply::ioPostToHttpFromSocket_data()
QTest::addColumn<int>("authenticationRequiredCount");
QTest::addColumn<int>("proxyAuthenticationRequiredCount");
- for (int i = 0; i < proxies.count(); ++i)
+ for (int i = 0; i < proxies.size(); ++i)
for (int auth = 0; auth < 2; ++auth) {
QUrl url;
if (auth)
@@ -4892,8 +5308,8 @@ void tst_QNetworkReply::ioPostToHttpFromSocket()
QCOMPARE(reply->readAll().trimmed(), md5sum(data).toHex());
- QTEST(int(authenticationRequiredSpy.count()), "authenticationRequiredCount");
- QTEST(int(proxyAuthenticationRequiredSpy.count()), "proxyAuthenticationRequiredCount");
+ QTEST(int(authenticationRequiredSpy.size()), "authenticationRequiredCount");
+ QTEST(int(proxyAuthenticationRequiredSpy.size()), "proxyAuthenticationRequiredCount");
}
void tst_QNetworkReply::ioPostToHttpFromSocketSynchronous_data()
@@ -5365,13 +5781,9 @@ void tst_QNetworkReply::emitAllUploadProgressSignals()
QNetworkRequest catchAllSignalsRequest(normalRequest);
catchAllSignalsRequest.setAttribute(QNetworkRequest::EmitAllUploadProgressSignalsAttribute, true);
- QList<QNetworkRequest> requests;
- requests << normalRequest << catchAllSignalsRequest;
-
QList<int> signalCount;
- foreach (const QNetworkRequest &request, requests) {
-
+ for (const QNetworkRequest &request : {normalRequest, catchAllSignalsRequest}) {
sourceFile.seek(0);
QNetworkReplyPtr reply(manager.post(request, &sourceFile));
QSignalSpy spy(reply.data(), SIGNAL(uploadProgress(qint64,qint64)));
@@ -5392,7 +5804,7 @@ void tst_QNetworkReply::emitAllUploadProgressSignals()
QVERIFY(!QTestEventLoop::instance().timeout());
incomingSocket->close();
- signalCount.append(spy.count());
+ signalCount.append(spy.size());
reply->deleteLater();
}
server.close();
@@ -5438,7 +5850,7 @@ void tst_QNetworkReply::ioPostToHttpEmptyUploadProgress()
QVERIFY(!QTestEventLoop::instance().timeout());
// final check: only 1 uploadProgress has been emitted
- QCOMPARE(spy.length(), 1);
+ QCOMPARE(spy.size(), 1);
QList<QVariant> args = spy.last();
QVERIFY(!args.isEmpty());
QCOMPARE(args.at(0).toLongLong(), buffer.size());
@@ -5476,7 +5888,7 @@ void tst_QNetworkReply::lastModifiedHeaderForHttp()
QDateTime header = reply->header(QNetworkRequest::LastModifiedHeader).toDateTime();
QDateTime realDate = QDateTime::fromString("2007-05-22T12:04:57", Qt::ISODate);
- realDate.setTimeSpec(Qt::UTC);
+ realDate.setTimeZone(QTimeZone::UTC);
QCOMPARE(header, realDate);
}
@@ -5609,7 +6021,7 @@ void tst_QNetworkReply::downloadProgress()
QVERIFY(!QTestEventLoop::instance().timeout());
QVERIFY(reply->isFinished());
- QVERIFY(spy.count() > 0);
+ QVERIFY(spy.size() > 0);
//final progress should have equal current & total
QList<QVariant> args = spy.takeLast();
@@ -5655,14 +6067,14 @@ void tst_QNetworkReply::uploadProgress()
QVERIFY(server.hasPendingConnections());
QTcpSocket *receiver = server.nextPendingConnection();
- if (finished.count() == 0) {
+ if (finished.size() == 0) {
// it's not finished yet, so wait for it to be
QVERIFY2(waitForFinish(reply) == Success, msgWaitForFinished(reply));
}
delete receiver;
- QVERIFY(finished.count() > 0);
- QVERIFY(spy.count() > 0);
+ QVERIFY(finished.size() > 0);
+ QVERIFY(spy.size() > 0);
QList<QVariant> args = spy.last();
QCOMPARE(args.at(0).toInt(), data.size());
@@ -5944,8 +6356,8 @@ void tst_QNetworkReply::nestedEventLoops()
QTestEventLoop::instance().enterLoop(20);
QVERIFY2(!QTestEventLoop::instance().timeout(), "Network timeout");
- QCOMPARE(finishedspy.count(), 1);
- QCOMPARE(errorspy.count(), 0);
+ QCOMPARE(finishedspy.size(), 1);
+ QCOMPARE(errorspy.size(), 0);
}
#if QT_CONFIG(networkproxy)
@@ -5978,7 +6390,7 @@ void tst_QNetworkReply::httpProxyCommands()
manager.setProxy(proxy);
QNetworkRequest request(url);
- request.setRawHeader("User-Agent", "QNetworkReplyAutoTest/1.0");
+ request.setRawHeader("user-agent", "QNetworkReplyAutoTest/1.0");
QNetworkReplyPtr reply(manager.get(request));
// wait for the finished signal
@@ -5991,14 +6403,15 @@ void tst_QNetworkReply::httpProxyCommands()
// especially since it won't succeed in the HTTPS case
// so just check that the command was correct
- QString receivedHeader = proxyServer.receivedData.left(expectedCommand.length());
+ QString receivedHeader = proxyServer.receivedData.left(expectedCommand.size());
QCOMPARE(receivedHeader, expectedCommand);
//QTBUG-17223 - make sure the user agent from the request is sent to proxy server even for CONNECT
- int uapos = proxyServer.receivedData.indexOf("User-Agent");
+ const QByteArray cUserAgent = "user-agent: ";
+ int uapos = proxyServer.receivedData.toLower().indexOf(cUserAgent) + cUserAgent.size();
int uaend = proxyServer.receivedData.indexOf("\r\n", uapos);
QByteArray uaheader = proxyServer.receivedData.mid(uapos, uaend - uapos);
- QCOMPARE(uaheader, QByteArray("User-Agent: QNetworkReplyAutoTest/1.0"));
+ QCOMPARE(uaheader, QByteArray("QNetworkReplyAutoTest/1.0"));
}
class ProxyChangeHelper : public QObject
@@ -6035,14 +6448,6 @@ struct QThreadCleanup
}
};
-struct QDeleteLaterCleanup
-{
- static inline void cleanup(QObject *o)
- {
- o->deleteLater();
- }
-};
-
#if QT_CONFIG(networkproxy)
void tst_QNetworkReply::httpProxyCommandsSynchronous()
{
@@ -6054,7 +6459,7 @@ void tst_QNetworkReply::httpProxyCommandsSynchronous()
// the server thread, because the client is never returning to the
// event loop
QScopedPointer<QThread, QThreadCleanup> serverThread(new QThread);
- QScopedPointer<MiniHttpServer, QDeleteLaterCleanup> proxyServer(new MiniHttpServer(responseToSend, false, serverThread.data()));
+ QScopedPointer<MiniHttpServer, QScopedPointerDeleteLater> proxyServer(new MiniHttpServer(responseToSend, false, serverThread.data()));
QNetworkProxy proxy(QNetworkProxy::HttpProxy, "127.0.0.1", proxyServer->serverPort());
manager.setProxy(proxy);
@@ -6075,7 +6480,7 @@ void tst_QNetworkReply::httpProxyCommandsSynchronous()
// especially since it won't succeed in the HTTPS case
// so just check that the command was correct
- QString receivedHeader = proxyServer->receivedData.left(expectedCommand.length());
+ QString receivedHeader = proxyServer->receivedData.left(expectedCommand.size());
QCOMPARE(receivedHeader, expectedCommand);
}
@@ -6172,9 +6577,9 @@ void tst_QNetworkReply::authorizationError()
QCOMPARE(waitForFinish(reply), int(Failure));
QFETCH(int, errorSignalCount);
- QCOMPARE(errorSpy.count(), errorSignalCount);
+ QCOMPARE(errorSpy.size(), errorSignalCount);
QFETCH(int, finishedSignalCount);
- QCOMPARE(finishedSpy.count(), finishedSignalCount);
+ QCOMPARE(finishedSpy.size(), finishedSignalCount);
QFETCH(int, error);
QCOMPARE(reply->error(), QNetworkReply::NetworkError(error));
@@ -6212,7 +6617,6 @@ void tst_QNetworkReply::httpConnectionCount()
}
QVERIFY(server->listen());
- QCoreApplication::instance()->processEvents();
QUrl url("http://127.0.0.1:" + QString::number(server->serverPort()) + QLatin1Char('/'));
if (encrypted)
@@ -6223,7 +6627,7 @@ void tst_QNetworkReply::httpConnectionCount()
QUrl urlCopy = url;
urlCopy.setPath(u'/' + QString::number(i)); // Differentiate the requests a bit
QNetworkRequest request(urlCopy);
- request.setAttribute(QNetworkRequest::Http2AllowedAttribute, http2Enabled);
+ request.setAttribute(QNetworkRequest::Http2CleartextAllowedAttribute, http2Enabled);
QNetworkReply* reply = manager.get(request);
reply->setParent(server.data());
if (encrypted)
@@ -6231,26 +6635,40 @@ void tst_QNetworkReply::httpConnectionCount()
}
int pendingConnectionCount = 0;
- QElapsedTimer timer;
- timer.start();
- while(pendingConnectionCount <= 20) {
- QTestEventLoop::instance().enterLoop(1);
+ using namespace std::chrono_literals;
+ const auto newPendingConnection = [&server]() { return server->hasPendingConnections(); };
+ // If we have http2 enabled then the second connection will take a little
+ // longer to be established because we will wait for the first one to finish
+ // to see if we should upgrade:
+ const int rampDown = http2Enabled ? 2 : 1;
+ while (pendingConnectionCount <= 6) {
+ if (!QTest::qWaitFor(newPendingConnection, pendingConnectionCount >= rampDown ? 3s : 7s))
+ break;
QTcpSocket *socket = server->nextPendingConnection();
- while (socket != 0) {
- if (pendingConnectionCount == 0) {
- // respond to the first connection so we know to transition to HTTP/1.1 when using
- // HTTP/2
- socket->write(httpEmpty200Response);
+ while (socket) {
+ if (pendingConnectionCount == 0 && http2Enabled) {
+ // Respond to the first connection so we know to transition to HTTP/1.1 when using
+ // HTTP/2.
+ // Because of some internal state machinery we need to wait until the request has
+ // actually been written to the server before we can reply.
+ auto connection = std::make_shared<QMetaObject::Connection>();
+ auto replyOnRequest = [=, buffer = QByteArray()]() mutable {
+ buffer += socket->readAll();
+ if (!buffer.contains("\r\n\r\n"))
+ return;
+ socket->write(httpEmpty200Response);
+ QObject::disconnect(*connection);
+ };
+ *connection = QObject::connect(socket, &QTcpSocket::readyRead, socket,
+ std::move(replyOnRequest));
+ if (socket->bytesAvailable()) // If we already have data, check it now
+ emit socket->readyRead();
}
pendingConnectionCount++;
socket->setParent(server.data());
socket = server->nextPendingConnection();
}
-
- // at max. wait 10 sec
- if (timer.elapsed() > 10000)
- break;
}
QCOMPARE(pendingConnectionCount, 6);
@@ -6533,7 +6951,7 @@ void tst_QNetworkReply::encrypted()
QTestEventLoop::instance().enterLoop(20);
QVERIFY(!QTestEventLoop::instance().timeout());
- QCOMPARE(spy.count(), 1);
+ QCOMPARE(spy.size(), 1);
reply->deleteLater();
}
@@ -6562,7 +6980,7 @@ void tst_QNetworkReply::abortOnEncrypted()
});
QSignalSpy spyEncrypted(reply, &QNetworkReply::encrypted);
- QTRY_COMPARE(spyEncrypted.count(), 1);
+ QTRY_COMPARE(spyEncrypted.size(), 1);
// Wait for the socket to be closed again in order to be sure QTcpSocket::readyRead would have been emitted.
QTRY_VERIFY(server.socket != nullptr);
@@ -6756,7 +7174,20 @@ void tst_QNetworkReply::getAndThenDeleteObject()
// see https://bugs.webkit.org/show_bug.cgi?id=38935
void tst_QNetworkReply::symbianOpenCDataUrlCrash()
{
- 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==");
+ QString requestUrl("data:image/"
+ "png;base64,"
+ "iVBORw0KGgoAAAANSUhEUgAAABkAAAAWCAYAAAA1vze2AAAAB3RJTUUH2AUSEgolrgBvVQAAAAl"
+ "wSFlzAAALEwAACxMBAJqcGAAAAARnQU1BAACxjwv8YQUAAAHlSURBVHja5VbNShxBEK6ZaXtnHT"
+ "ebQPA1gngNmfaeq+QNPIlIXkC9iQdJxJNvEHLN3VkxhxxE8gTmEhAVddXZ6Z3f9Ndriz89/"
+ "sHmkBQUVVT1fB9d9c3uOERUKTunIdn3HzstxGpYBDS4wZk7TAJj/wlJ90J+jnuygqs8svSj+/"
+ "rGHBos3rE18XBvfU3no7NzlJfUaY/5whAwl8Lr/WDUv4ODxTMb+P5xLExe5LmO559WqTX/"
+ "MQR4WZYEAtSePS4pE0qSnuhnRUcBU5Gm2k9XljU4Z26I3NRxBrd80rj2fh+"
+ "KNE0FY4xevRgTjREvPFpasAK8Xli6MUbbuKw3afAGgSBXozo5u4hkmncAlkl5wx8iMGbdyQjnCF"
+ "EiEwGiosj1UQA/x2rVddiVoi+l4IxE0PTDnx+mrQBvvnx9cFz3krhVvuhzFn579/aq/"
+ "n5rW8fbtTqiWhIQZEo17YBvbkxOXNVndnYpTvod7AtiuN2re0+"
+ "siwcB9oH8VxxrNwQQAhzyRs30n7wTI2HIN2g2QtQwjjhJIQatOq7E8bIVCLwzpl83Lvtvl+"
+ "NohWWlE8UZTWEMAGCcR77fHKhPnZF5tYie6dfdxCphACmLPM+j8bYfmTryg64kV9Vh3mV8jP0b/"
+ "4wO/YUPiT/8i0MLf55lSQAAAABJRU5ErkJggg==");
QUrl url = QUrl::fromEncoded(requestUrl.toLatin1());
QNetworkRequest req(url);
QNetworkReplyPtr reply;
@@ -7101,7 +7532,7 @@ void tst_QNetworkReply::compressedHttpReplyBrokenGzip()
QCOMPARE(waitForFinish(reply), int(Failure));
- QCOMPARE(reply->error(), QNetworkReply::ProtocolFailure);
+ QCOMPARE(reply->error(), QNetworkReply::UnknownContentError);
}
// TODO add similar test for FTP
@@ -7145,9 +7576,9 @@ void tst_QNetworkReply::qtbug4121unknownAuthentication()
QTestEventLoop::instance().enterLoop(10);
QVERIFY(!QTestEventLoop::instance().timeout());
- QCOMPARE(authSpy.count(), 0);
- QCOMPARE(finishedSpy.count(), 1);
- QCOMPARE(errorSpy.count(), 1);
+ QCOMPARE(authSpy.size(), 0);
+ QCOMPARE(finishedSpy.size(), 1);
+ QCOMPARE(errorSpy.size(), 1);
QCOMPARE(reply->error(), QNetworkReply::AuthenticationRequiredError);
}
@@ -7158,7 +7589,7 @@ void tst_QNetworkReply::authenticationCacheAfterCancel_data()
QTest::addColumn<QNetworkProxy>("proxy");
QTest::addColumn<bool>("proxyAuth");
QTest::addColumn<QUrl>("url");
- for (int i = 0; i < proxies.count(); ++i) {
+ for (int i = 0; i < proxies.size(); ++i) {
QTest::newRow("http" + proxies.at(i).tag)
<< proxies.at(i).proxy
<< proxies.at(i).requiresAuthentication
@@ -7241,8 +7672,8 @@ void tst_QNetworkReply::authenticationCacheAfterCancel()
QVERIFY(!QTestEventLoop::instance().timeout());
QCOMPARE(reply->error(), QNetworkReply::ProxyAuthenticationRequiredError);
- QCOMPARE(authSpy.count(), 0);
- QCOMPARE(proxyAuthSpy.count(), 1);
+ QCOMPARE(authSpy.size(), 0);
+ QCOMPARE(proxyAuthSpy.size(), 1);
proxyAuthSpy.clear();
//should fail due to bad credentials
@@ -7256,8 +7687,8 @@ void tst_QNetworkReply::authenticationCacheAfterCancel()
// Work round known quirk in the old test server (danted -v < v1.1.19):
if (reply->error() != QNetworkReply::HostNotFoundError)
QCOMPARE(reply->error(), QNetworkReply::ProxyAuthenticationRequiredError);
- QCOMPARE(authSpy.count(), 0);
- QVERIFY(proxyAuthSpy.count() > 0);
+ QCOMPARE(authSpy.size(), 0);
+ QVERIFY(proxyAuthSpy.size() > 0);
proxyAuthSpy.clear();
// QTBUG-23136 workaround (needed even with danted v1.1.19):
@@ -7282,10 +7713,10 @@ void tst_QNetworkReply::authenticationCacheAfterCancel()
QVERIFY(!QTestEventLoop::instance().timeout());
QCOMPARE(reply->error(), QNetworkReply::AuthenticationRequiredError);
- QVERIFY(authSpy.count() > 0);
+ QVERIFY(authSpy.size() > 0);
authSpy.clear();
if (proxyAuth) {
- QVERIFY(proxyAuthSpy.count() > 0);
+ QVERIFY(proxyAuthSpy.size() > 0);
proxyAuthSpy.clear();
}
@@ -7298,11 +7729,11 @@ void tst_QNetworkReply::authenticationCacheAfterCancel()
QVERIFY(!QTestEventLoop::instance().timeout());
QCOMPARE(reply->error(), QNetworkReply::AuthenticationRequiredError);
- QVERIFY(authSpy.count() > 0);
+ QVERIFY(authSpy.size() > 0);
authSpy.clear();
if (proxyAuth) {
//should be supplied from cache
- QCOMPARE(proxyAuthSpy.count(), 0);
+ QCOMPARE(proxyAuthSpy.size(), 0);
proxyAuthSpy.clear();
}
@@ -7316,11 +7747,11 @@ void tst_QNetworkReply::authenticationCacheAfterCancel()
QVERIFY(!QTestEventLoop::instance().timeout());
QCOMPARE(reply->error(), QNetworkReply::NoError);
- QVERIFY(authSpy.count() > 0);
+ QVERIFY(authSpy.size() > 0);
authSpy.clear();
if (proxyAuth) {
//should be supplied from cache
- QCOMPARE(proxyAuthSpy.count(), 0);
+ QCOMPARE(proxyAuthSpy.size(), 0);
proxyAuthSpy.clear();
}
@@ -7332,11 +7763,11 @@ void tst_QNetworkReply::authenticationCacheAfterCancel()
QCOMPARE(reply->error(), QNetworkReply::NoError);
//should be supplied from cache
- QCOMPARE(authSpy.count(), 0);
+ QCOMPARE(authSpy.size(), 0);
authSpy.clear();
if (proxyAuth) {
//should be supplied from cache
- QCOMPARE(proxyAuthSpy.count(), 0);
+ QCOMPARE(proxyAuthSpy.size(), 0);
proxyAuthSpy.clear();
}
@@ -7438,8 +7869,8 @@ void tst_QNetworkReply::httpWithNoCredentialUsage()
QNetworkReplyPtr reply(manager.get(request));
QVERIFY2(waitForFinish(reply) == Success, msgWaitForFinished(reply));
// credentials in URL, so don't expect authentication signal
- QCOMPARE(authSpy.count(), 0);
- QCOMPARE(finishedSpy.count(), 1);
+ QCOMPARE(authSpy.size(), 0);
+ QCOMPARE(finishedSpy.size(), 1);
finishedSpy.clear();
}
@@ -7449,8 +7880,8 @@ void tst_QNetworkReply::httpWithNoCredentialUsage()
QNetworkReplyPtr reply(manager.get(request));
QVERIFY2(waitForFinish(reply) == Success, msgWaitForFinished(reply));
// credentials in cache, so don't expect authentication signal
- QCOMPARE(authSpy.count(), 0);
- QCOMPARE(finishedSpy.count(), 1);
+ QCOMPARE(authSpy.size(), 0);
+ QCOMPARE(finishedSpy.size(), 1);
finishedSpy.clear();
}
@@ -7467,9 +7898,9 @@ void tst_QNetworkReply::httpWithNoCredentialUsage()
QVERIFY(!QTestEventLoop::instance().timeout());
// We check if authenticationRequired was emitted, however we do not anything in it so it should be 401
- QCOMPARE(authSpy.count(), 1);
- QCOMPARE(finishedSpy.count(), 1);
- QCOMPARE(errorSpy.count(), 1);
+ QCOMPARE(authSpy.size(), 1);
+ QCOMPARE(finishedSpy.size(), 1);
+ QCOMPARE(errorSpy.size(), 1);
QCOMPARE(reply->error(), QNetworkReply::AuthenticationRequiredError);
}
@@ -7754,8 +8185,8 @@ void tst_QNetworkReply::qtbug45581WrongReplyStatusCode()
QCOMPARE(reply->readAll(), expectedContent);
- QCOMPARE(finishedSpy.count(), 0);
- QCOMPARE(sslErrorsSpy.count(), 0);
+ QCOMPARE(finishedSpy.size(), 0);
+ QCOMPARE(sslErrorsSpy.size(), 0);
QCOMPARE(reply->header(QNetworkRequest::ContentLengthHeader).toLongLong(), expectedContent.size());
@@ -7844,8 +8275,8 @@ void tst_QNetworkReply::synchronousRequest()
QSignalSpy sslErrorsSpy(&manager, SIGNAL(sslErrors(QNetworkReply*,QList<QSslError>)));
RUN_REQUEST(runSimpleRequest(QNetworkAccessManager::GetOperation, request, reply, 0));
QVERIFY(reply->isFinished());
- QCOMPARE(finishedSpy.count(), 0);
- QCOMPARE(sslErrorsSpy.count(), 0);
+ QCOMPARE(finishedSpy.size(), 0);
+ QCOMPARE(sslErrorsSpy.size(), 0);
QCOMPARE(reply->header(QNetworkRequest::ContentTypeHeader).toString(), mimeType);
@@ -7854,7 +8285,7 @@ void tst_QNetworkReply::synchronousRequest()
if (expected.startsWith("file:")) {
QString path = expected.mid(5);
QFile file(path);
- file.open(QIODevice::ReadOnly);
+ QVERIFY(file.open(QIODevice::ReadOnly));
expectedContent = file.readAll();
} else if (expected.startsWith("data:")) {
expectedContent = expected.mid(5).toUtf8();
@@ -7884,7 +8315,7 @@ void tst_QNetworkReply::synchronousRequestSslFailure()
runSimpleRequest(QNetworkAccessManager::GetOperation, request, reply, 0);
QVERIFY(reply->isFinished());
QCOMPARE(reply->error(), QNetworkReply::SslHandshakeFailedError);
- QCOMPARE(sslErrorsSpy.count(), 0);
+ QCOMPARE(sslErrorsSpy.size(), 0);
}
#endif
@@ -8048,10 +8479,10 @@ void tst_QNetworkReply::varyingCacheExpiry()
server.doClose = false;
QUrl urls[4] = {
- u"http://localhost"_qs,
- u"http://localhost"_qs,
- u"http://localhost"_qs,
- u"http://localhost"_qs,
+ u"http://localhost"_s,
+ u"http://localhost"_s,
+ u"http://localhost"_s,
+ u"http://localhost"_s,
};
for (size_t i = 0; i < std::size(urls); ++i)
urls[i].setPort(servers[i].serverPort());
@@ -8103,6 +8534,61 @@ void tst_QNetworkReply::varyingCacheExpiry()
QVERIFY(success);
}
+class Qtbug25280Server : public MiniHttpServer
+{
+public:
+ Qtbug25280Server(QByteArray qba) : MiniHttpServer(qba, false) {}
+ QSet<QTcpSocket*> receivedSockets;
+ void reply() override
+ {
+ // Save sockets in a list
+ receivedSockets.insert((QTcpSocket*)sender());
+ qobject_cast<QTcpSocket*>(sender())->write(dataToTransmit);
+ //qDebug() << "count=" << receivedSockets.count();
+ }
+};
+
+void tst_QNetworkReply::amountOfHttp1ConnectionsQtbug25280_data()
+{
+ QTest::addColumn<int>("amount");
+ QTest::addRow("default") << 6;
+ QTest::addRow("minimize") << 1;
+ QTest::addRow("increase") << 12;
+}
+
+// Also kind of QTBUG-8468
+void tst_QNetworkReply::amountOfHttp1ConnectionsQtbug25280()
+{
+ QFETCH(const int, amount);
+ QNetworkAccessManager manager; // function local instance
+ Qtbug25280Server server(tst_QNetworkReply::httpEmpty200Response);
+ server.doClose = false;
+ server.multiple = true;
+ QUrl url(QLatin1String("http://127.0.0.1")); // not "localhost" to prevent "Happy Eyeballs"
+ // from skewing the counting
+ url.setPort(server.serverPort());
+ std::optional<QHttp1Configuration> http1Configuration;
+ if (amount != 6) // don't set if it's the default
+ http1Configuration.emplace().setNumberOfConnectionsPerHost(amount);
+ constexpr int NumRequests = 200; // send a lot more than we have sockets
+ int finished = 0;
+ std::array<std::unique_ptr<QNetworkReply>, NumRequests> replies;
+ for (auto &reply : replies) {
+ QNetworkRequest request(url);
+ if (http1Configuration)
+ request.setHttp1Configuration(*http1Configuration);
+ reply.reset(manager.get(request));
+ QObject::connect(reply.get(), &QNetworkReply::finished,
+ [&finished] { ++finished; });
+ }
+ QTRY_COMPARE_WITH_TIMEOUT(finished, NumRequests, 60'000);
+ for (const auto &reply : replies) {
+ QCOMPARE(reply->error(), QNetworkReply::NoError);
+ QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200);
+ }
+ QCOMPARE(server.receivedSockets.size(), amount);
+}
+
void tst_QNetworkReply::dontInsertPartialContentIntoTheCache()
{
QByteArray reply206 =
@@ -8131,7 +8617,7 @@ void tst_QNetworkReply::dontInsertPartialContentIntoTheCache()
QVERIFY(server.totalConnections > 0);
QCOMPARE(reply->readAll().constData(), "load");
- QCOMPARE(memoryCache->m_insertedUrls.count(), 0);
+ QCOMPARE(memoryCache->m_insertedUrls.size(), 0);
}
void tst_QNetworkReply::httpUserAgent()
@@ -8148,7 +8634,7 @@ void tst_QNetworkReply::httpUserAgent()
QVERIFY(reply->isFinished());
QCOMPARE(reply->error(), QNetworkReply::NoError);
- QVERIFY(server.receivedData.contains("\r\nUser-Agent: abcDEFghi\r\n"));
+ QVERIFY(server.receivedData.contains("\r\nuser-agent: abcDEFghi\r\n"));
}
void tst_QNetworkReply::synchronousAuthenticationCache()
@@ -8168,7 +8654,7 @@ void tst_QNetworkReply::synchronousAuthenticationCache()
"Content-Type: text/plain\r\n"
"\r\n"
"auth";
- QRegularExpression rx("Authorization: Basic ([^\r\n]*)\r\n");
+ QRegularExpression rx("authorization: Basic ([^\r\n]*)\r\n");
QRegularExpressionMatch match = rx.match(receivedData);
if (match.hasMatch()) {
if (QByteArray::fromBase64(match.captured(1).toLatin1()) == "login:password") {
@@ -8189,7 +8675,7 @@ void tst_QNetworkReply::synchronousAuthenticationCache()
// the server thread, because the client is never returning to the
// event loop
QScopedPointer<QThread, QThreadCleanup> serverThread(new QThread);
- QScopedPointer<MiniHttpServer, QDeleteLaterCleanup> server(new MiniAuthServer(serverThread.data()));
+ QScopedPointer<MiniHttpServer, QScopedPointerDeleteLater> server(new MiniAuthServer(serverThread.data()));
server->doClose = true;
//1) URL without credentials, we are not authenticated
@@ -8328,31 +8814,33 @@ void tst_QNetworkReply::ftpAuthentication()
void tst_QNetworkReply::emitErrorForAllReplies() // QTBUG-36890
{
// port 100 is not well-known and should be closed
- QList<QUrl> urls = QList<QUrl>() << QUrl("http://localhost:100/request1")
- << QUrl("http://localhost:100/request2")
- << QUrl("http://localhost:100/request3");
- QList<QNetworkReply *> replies;
- QList<QSignalSpy *> errorSpies;
- QList<QSignalSpy *> finishedSpies;
- for (int a = 0; a < urls.count(); ++a) {
- QNetworkRequest request(urls.at(a));
+ const QUrl urls[] = {
+ QUrl("http://localhost:100/request1"),
+ QUrl("http://localhost:100/request2"),
+ QUrl("http://localhost:100/request3"),
+ };
+ constexpr auto NUrls = std::size(urls);
+
+ std::unique_ptr<QNetworkReply, QScopedPointerDeleteLater> replies[NUrls];
+ std::optional<QSignalSpy> errorSpies[NUrls];
+ std::optional<QSignalSpy> finishedSpies[NUrls];
+
+ for (size_t i = 0; i < NUrls; ++i) {
+ QNetworkRequest request(urls[i]);
QNetworkReply *reply = manager.get(request);
- replies.append(reply);
- QSignalSpy *errorSpy = new QSignalSpy(reply, SIGNAL(errorOccurred(QNetworkReply::NetworkError)));
- errorSpies.append(errorSpy);
- QSignalSpy *finishedSpy = new QSignalSpy(reply, SIGNAL(finished()));
- finishedSpies.append(finishedSpy);
+ replies[i].reset(reply);
+ errorSpies[i].emplace(reply, SIGNAL(errorOccurred(QNetworkReply::NetworkError)));
+ finishedSpies[i].emplace(reply, SIGNAL(finished()));
QObject::connect(reply, SIGNAL(finished()), SLOT(emitErrorForAllRepliesSlot()));
}
+
QTestEventLoop::instance().enterLoop(10);
QVERIFY(!QTestEventLoop::instance().timeout());
- for (int a = 0; a < urls.count(); ++a) {
- QVERIFY(replies.at(a)->isFinished());
- QCOMPARE(errorSpies.at(a)->count(), 1);
- errorSpies.at(a)->deleteLater();
- QCOMPARE(finishedSpies.at(a)->count(), 1);
- finishedSpies.at(a)->deleteLater();
- replies.at(a)->deleteLater();
+
+ for (size_t i = 0; i < NUrls; ++i) {
+ QVERIFY(replies[i]->isFinished());
+ QCOMPARE(errorSpies[i]->size(), 1);
+ QCOMPARE(finishedSpies[i]->size(), 1);
}
}
@@ -8400,7 +8888,7 @@ public:
return ret;
}
virtual bool atEnd() const override { return buffer.atEnd(); }
- virtual qint64 size() const override { return data.length(); }
+ virtual qint64 size() const override { return data.size(); }
qint64 bytesAvailable() const override
{
return buffer.bytesAvailable() + QIODevice::bytesAvailable();
@@ -8421,9 +8909,9 @@ protected slots:
void tst_QNetworkReply::putWithRateLimiting()
{
QFile reference(testDataDir + "/rfc3252.txt");
- reference.open(QIODevice::ReadOnly);
+ QVERIFY(reference.open(QIODevice::ReadOnly));
QByteArray data = reference.readAll();
- QVERIFY(data.length() > 0);
+ QVERIFY(data.size() > 0);
QUrl url = QUrl::fromUserInput("http://" + QtNetworkSettings::httpServerName()+ "/qtest/cgi-bin/echo.cgi?");
@@ -8438,7 +8926,7 @@ void tst_QNetworkReply::putWithRateLimiting()
QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200);
QByteArray uploadedData = reply->readAll();
- QCOMPARE(uploadedData.length(), data.length());
+ QCOMPARE(uploadedData.size(), data.size());
QCOMPARE(uploadedData, data);
}
@@ -8470,8 +8958,8 @@ void tst_QNetworkReply::ioHttpSingleRedirect()
QVERIFY2(waitForFinish(reply) == Success, msgWaitForFinished(reply));
// Redirected and finished should be emitted exactly once
- QCOMPARE(redSpy.count(), 1);
- QCOMPARE(finSpy.count(), 1);
+ QCOMPARE(redSpy.size(), 1);
+ QCOMPARE(finSpy.size(), 1);
// Original URL should not be changed after redirect
QCOMPARE(request.url(), localhost);
@@ -8517,8 +9005,8 @@ void tst_QNetworkReply::ioHttpChangeMaxRedirects()
QCOMPARE(waitForFinish(reply), int(Failure));
- QCOMPARE(redSpy.count(), request.maximumRedirectsAllowed());
- QCOMPARE(spy.count(), 1);
+ QCOMPARE(redSpy.size(), request.maximumRedirectsAllowed());
+ QCOMPARE(spy.size(), 1);
QCOMPARE(reply->error(), QNetworkReply::TooManyRedirectsError);
// Increase max redirects to allow successful completion
@@ -8529,7 +9017,7 @@ void tst_QNetworkReply::ioHttpChangeMaxRedirects()
QVERIFY2(waitForFinish(reply2) == Success, msgWaitForFinished(reply2));
- QCOMPARE(redSpy2.count(), 2);
+ QCOMPARE(redSpy2.size(), 2);
QCOMPARE(reply2->url(), server3Url);
QCOMPARE(reply2->error(), QNetworkReply::NoError);
QVERIFY(validateRedirectedResponseHeaders(reply2));
@@ -8662,8 +9150,8 @@ void tst_QNetworkReply::ioHttpRedirectPolicy()
QSignalSpy redirectSpy(reply.data(), SIGNAL(redirected(QUrl)));
QSignalSpy finishedSpy(reply.data(), SIGNAL(finished()));
QVERIFY2(waitForFinish(reply) == Success, msgWaitForFinished(reply));
- QCOMPARE(finishedSpy.count(), 1);
- QCOMPARE(redirectSpy.count(), redirectCount);
+ QCOMPARE(finishedSpy.size(), 1);
+ QCOMPARE(redirectSpy.size(), redirectCount);
QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), statusCode);
QVERIFY(validateRedirectedResponseHeaders(reply) || statusCode != 200);
}
@@ -8746,7 +9234,7 @@ void tst_QNetworkReply::ioHttpRedirectPolicyErrors()
QSignalSpy spy(reply.data(), SIGNAL(errorOccurred(QNetworkReply::NetworkError)));
QCOMPARE(waitForFinish(reply), int(Failure));
- QCOMPARE(spy.count(), 1);
+ QCOMPARE(spy.size(), 1);
QCOMPARE(reply->error(), expectedError);
}
@@ -8796,7 +9284,7 @@ void tst_QNetworkReply::ioHttpUserVerifiedRedirect()
QSignalSpy finishedSpy(reply.data(), SIGNAL(finished()));
waitForFinish(reply);
- QCOMPARE(finishedSpy.count(), 1);
+ QCOMPARE(finishedSpy.size(), 1);
QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), statusCode);
QVERIFY(validateRedirectedResponseHeaders(reply) || statusCode != 200);
}
@@ -8808,7 +9296,7 @@ void tst_QNetworkReply::ioHttpCookiesDuringRedirect()
const QString cookieHeader = QStringLiteral("Set-Cookie: hello=world; Path=/;\r\n");
QString redirect = tempRedirectReplyStr();
// Insert 'cookieHeader' before the final \r\n
- redirect.insert(redirect.length() - 2, cookieHeader);
+ redirect.insert(redirect.size() - 2, cookieHeader);
QUrl url("http://localhost/");
url.setPort(target.serverPort());
@@ -8825,7 +9313,7 @@ void tst_QNetworkReply::ioHttpCookiesDuringRedirect()
manager.setRedirectPolicy(oldRedirectPolicy);
QVERIFY(waitForFinish(reply) == Success);
- QVERIFY(target.receivedData.contains("\r\nCookie: hello=world\r\n"));
+ QVERIFY(target.receivedData.contains("\r\ncookie: hello=world\r\n"));
QVERIFY(validateRedirectedResponseHeaders(reply));
}
@@ -8868,6 +9356,64 @@ void tst_QNetworkReply::ioHttpRedirect()
QVERIFY(validateRedirectedResponseHeaders(reply));
}
+/*
+ Test that, if we load a redirect from cache, we don't treat the request to
+ the destination of the redirect as a redirect.
+
+ If it was treated as a redirect the finished() signal was never emitted!
+*/
+void tst_QNetworkReply::ioHttpRedirectWithCache()
+{
+ // Disallow caching the result so that the second request must also send the request
+ QByteArray http200ResponseNoCache = "HTTP/1.1 200 OK\r\n"
+ "Content-Type: text/plain\r\n"
+ "Cache-Control: no-cache\r\n"
+ "\r\nHello";
+
+ MiniHttpServer target(http200ResponseNoCache, false);
+ QUrl targetUrl("http://localhost/");
+ targetUrl.setPort(target.serverPort());
+
+ // A cache-able redirect reply
+ QString redirectReply = QStringLiteral("HTTP/1.1 308\r\n"
+ "Content-Type: text/plain\r\n"
+ "location: %1\r\n"
+ "Cache-Control: max-age=3600\r\n"
+ "\r\nYou're being redirected").arg(targetUrl.toString());
+ MiniHttpServer redirectServer(redirectReply.toLatin1(), false);
+ QUrl url("http://localhost/");
+ url.setPort(redirectServer.serverPort());
+
+ QTemporaryDir tempDir(QDir::tempPath() + "/tmp_cache_28035");
+ QVERIFY2(tempDir.isValid(), qPrintable(tempDir.errorString()));
+ tempDir.setAutoRemove(true);
+
+ QNetworkDiskCache *diskCache = new QNetworkDiskCache();
+ diskCache->setCacheDirectory(tempDir.path());
+ // Manager takes ownership of the cache:
+ manager.setCache(diskCache);
+ QCOMPARE(diskCache->cacheSize(), 0);
+
+ // Send the first request, we end up caching the redirect reply
+ QNetworkRequest request(url);
+ QNetworkReplyPtr reply(manager.get(request));
+
+ QCOMPARE(waitForFinish(reply), int(Success));
+ QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200);
+ QVERIFY(validateRedirectedResponseHeaders(reply));
+
+ QVERIFY(diskCache->cacheSize() != 0);
+
+ // Now for the second request, we will use the cache, and we test that the finished()
+ // signal is still emitted.
+ request.setAttribute(QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::PreferCache);
+ reply.reset(manager.get(request));
+
+ QCOMPARE(waitForFinish(reply), int(Success));
+ QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200);
+ QVERIFY(validateRedirectedResponseHeaders(reply));
+}
+
void tst_QNetworkReply::ioHttpRedirectFromLocalToRemote()
{
QUrl targetUrl("http://" + QtNetworkSettings::httpServerName() + "/qtest/rfc3252.txt");
@@ -9013,8 +9559,8 @@ void tst_QNetworkReply::ioHttpRedirectMultipartPost()
QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200); // 200 OK
- QVERIFY(multiPart->boundary().count() > 20); // check that there is randomness after the "boundary_.oOo._" string
- QVERIFY(multiPart->boundary().count() < 70);
+ QVERIFY(multiPart->boundary().size() > 20); // check that there is randomness after the "boundary_.oOo._" string
+ QVERIFY(multiPart->boundary().size() < 70);
QByteArray replyData = reply->readAll();
expectedReplyData.prepend("content type: multipart/" + contentType + "; boundary=\"" + multiPart->boundary() + "\"\n");
@@ -9177,9 +9723,9 @@ public slots:
//qDebug() << m_receivedData.left(m_receivedData.indexOf("\r\n\r\n"));
m_receivedData = m_receivedData.mid(m_receivedData.indexOf("\r\n\r\n")+4); // check only actual data
}
- if (m_receivedData.length() > 0 && !m_expectedData.startsWith(m_receivedData)) {
+ if (m_receivedData.size() > 0 && !m_expectedData.startsWith(m_receivedData)) {
// We had received some data but it is corrupt!
- qDebug() << "CORRUPT" << m_receivedData.count();
+ qDebug() << "CORRUPT" << m_receivedData.size();
#if 0 // Use this to track down the pattern of the corruption and conclude the source
QFile a("/tmp/corrupt");
@@ -9301,8 +9847,12 @@ void tst_QNetworkReply::autoDeleteRepliesAttribute_data()
{
QTest::addColumn<QUrl>("destination");
- QTest::newRow("http") << QUrl("http://QInvalidDomain.qt/test");
- QTest::newRow("https") << QUrl("https://QInvalidDomain.qt/test");
+ QUrl webServerUrl = QtNetworkSettings::httpServerIp().toString();
+ webServerUrl.setPath("/notfound");
+ webServerUrl.setScheme("http");
+ QTest::newRow("http") << webServerUrl;
+ webServerUrl.setScheme("https");
+ QTest::newRow("https") << webServerUrl;
if (ftpSupported)
QTest::newRow("ftp") << QUrl("ftp://QInvalidDomain.qt/test");
QTest::newRow("file") << QUrl("file:///thisfolderdoesn'texist/probably.txt");
@@ -9325,7 +9875,7 @@ void tst_QNetworkReply::autoDeleteRepliesAttribute()
QSignalSpy finishedSpy(reply, &QNetworkReply::finished);
QSignalSpy destroyedSpy(reply, &QObject::destroyed);
QVERIFY(finishedSpy.wait());
- QCOMPARE(destroyedSpy.count(), 0);
+ QCOMPARE(destroyedSpy.size(), 0);
QVERIFY(destroyedSpy.wait());
}
{
@@ -9336,7 +9886,7 @@ void tst_QNetworkReply::autoDeleteRepliesAttribute()
QSignalSpy finishedSpy(reply, &QNetworkReply::finished);
QSignalSpy destroyedSpy(reply, &QObject::destroyed);
QVERIFY(finishedSpy.wait());
- QCOMPARE(destroyedSpy.count(), 0);
+ QCOMPARE(destroyedSpy.size(), 0);
QVERIFY(destroyedSpy.wait());
}
// Now repeated, but without the attribute to make sure it does not get deleted automatically.
@@ -9350,10 +9900,10 @@ void tst_QNetworkReply::autoDeleteRepliesAttribute()
QSignalSpy finishedSpy(reply.data(), &QNetworkReply::finished);
QSignalSpy destroyedSpy(reply.data(), &QObject::destroyed);
QVERIFY(finishedSpy.wait());
- QCOMPARE(destroyedSpy.count(), 0);
+ QCOMPARE(destroyedSpy.size(), 0);
QCoreApplication::processEvents();
QCoreApplication::processEvents();
- QCOMPARE(destroyedSpy.count(), 0);
+ QCOMPARE(destroyedSpy.size(), 0);
}
{
// Post
@@ -9362,10 +9912,10 @@ void tst_QNetworkReply::autoDeleteRepliesAttribute()
QSignalSpy finishedSpy(reply.data(), &QNetworkReply::finished);
QSignalSpy destroyedSpy(reply.data(), &QObject::destroyed);
QVERIFY(finishedSpy.wait());
- QCOMPARE(destroyedSpy.count(), 0);
+ QCOMPARE(destroyedSpy.size(), 0);
QCoreApplication::processEvents();
QCoreApplication::processEvents();
- QCOMPARE(destroyedSpy.count(), 0);
+ QCOMPARE(destroyedSpy.size(), 0);
}
}
@@ -9386,7 +9936,7 @@ void tst_QNetworkReply::autoDeleteReplies()
QSignalSpy finishedSpy(reply, &QNetworkReply::finished);
QSignalSpy destroyedSpy(reply, &QObject::destroyed);
QVERIFY(finishedSpy.wait());
- QCOMPARE(destroyedSpy.count(), 0);
+ QCOMPARE(destroyedSpy.size(), 0);
QVERIFY(destroyedSpy.wait());
}
{
@@ -9396,7 +9946,7 @@ void tst_QNetworkReply::autoDeleteReplies()
QSignalSpy finishedSpy(reply, &QNetworkReply::finished);
QSignalSpy destroyedSpy(reply, &QObject::destroyed);
QVERIFY(finishedSpy.wait());
- QCOMPARE(destroyedSpy.count(), 0);
+ QCOMPARE(destroyedSpy.size(), 0);
QVERIFY(destroyedSpy.wait());
}
// Here we repeat the test, but override the auto-deletion in the QNetworkRequest
@@ -9411,10 +9961,10 @@ void tst_QNetworkReply::autoDeleteReplies()
QSignalSpy finishedSpy(reply.data(), &QNetworkReply::finished);
QSignalSpy destroyedSpy(reply.data(), &QObject::destroyed);
QVERIFY(finishedSpy.wait());
- QCOMPARE(destroyedSpy.count(), 0);
+ QCOMPARE(destroyedSpy.size(), 0);
QCoreApplication::processEvents();
QCoreApplication::processEvents();
- QCOMPARE(destroyedSpy.count(), 0);
+ QCOMPARE(destroyedSpy.size(), 0);
}
{
// Post
@@ -9424,10 +9974,10 @@ void tst_QNetworkReply::autoDeleteReplies()
QSignalSpy finishedSpy(reply.data(), &QNetworkReply::finished);
QSignalSpy destroyedSpy(reply.data(), &QObject::destroyed);
QVERIFY(finishedSpy.wait());
- QCOMPARE(destroyedSpy.count(), 0);
+ QCOMPARE(destroyedSpy.size(), 0);
QCoreApplication::processEvents();
QCoreApplication::processEvents();
- QCOMPARE(destroyedSpy.count(), 0);
+ QCOMPARE(destroyedSpy.size(), 0);
}
// Now we repeat the test with autoDeleteReplies set to false
cleanup.dismiss();
@@ -9439,10 +9989,10 @@ void tst_QNetworkReply::autoDeleteReplies()
QSignalSpy finishedSpy(reply.data(), &QNetworkReply::finished);
QSignalSpy destroyedSpy(reply.data(), &QObject::destroyed);
QVERIFY(finishedSpy.wait());
- QCOMPARE(destroyedSpy.count(), 0);
+ QCOMPARE(destroyedSpy.size(), 0);
QCoreApplication::processEvents();
QCoreApplication::processEvents();
- QCOMPARE(destroyedSpy.count(), 0);
+ QCOMPARE(destroyedSpy.size(), 0);
}
{
// Post
@@ -9451,140 +10001,137 @@ void tst_QNetworkReply::autoDeleteReplies()
QSignalSpy finishedSpy(reply.data(), &QNetworkReply::finished);
QSignalSpy destroyedSpy(reply.data(), &QObject::destroyed);
QVERIFY(finishedSpy.wait());
- QCOMPARE(destroyedSpy.count(), 0);
+ QCOMPARE(destroyedSpy.size(), 0);
QCoreApplication::processEvents();
QCoreApplication::processEvents();
- QCOMPARE(destroyedSpy.count(), 0);
+ QCOMPARE(destroyedSpy.size(), 0);
}
}
-void tst_QNetworkReply::getWithTimeout()
+void tst_QNetworkReply::requestWithTimeout_data()
{
- MiniHttpServer server(tst_QNetworkReply::httpEmpty200Response, false);
-
- QNetworkRequest request(QUrl("http://localhost:" + QString::number(server.serverPort())));
- QNetworkReplyPtr reply(manager.get(request));
- QSignalSpy spy(reply.data(), SIGNAL(errorOccurred(QNetworkReply::NetworkError)));
-
- QCOMPARE(waitForFinish(reply), int(Success));
-
- QCOMPARE(spy.count(), 0);
- QVERIFY(reply->error() == QNetworkReply::NoError);
-
- request.setTransferTimeout(1000);
- server.stopTransfer = true;
+ using Operation = QNetworkAccessManager::Operation;
+ QTest::addColumn<Operation>("method");
+ QTest::addColumn<int>("reqInt");
+ QTest::addColumn<std::chrono::milliseconds>("reqChrono");
+ QTest::addColumn<int>("mgrInt");
+ QTest::addColumn<std::chrono::milliseconds>("mgrChrono");
- QNetworkReplyPtr reply2(manager.get(request));
- QSignalSpy spy2(reply2.data(), SIGNAL(errorOccurred(QNetworkReply::NetworkError)));
-
- QCOMPARE(waitForFinish(reply2), int(Failure));
-
- QCOMPARE(spy2.count(), 1);
- QVERIFY(reply2->error() == QNetworkReply::OperationCanceledError);
-
- request.setTransferTimeout(0);
- manager.setTransferTimeout(1000);
+ QTest::addRow("get_req_int") << Operation::GetOperation << 500 << 0ms << 0 << 0ms;
+ QTest::addRow("get_req_chrono") << Operation::GetOperation << 0 << 500ms << 0 << 0ms;
+ QTest::addRow("get_mgr_int") << Operation::GetOperation << 0 << 0ms << 500 << 0ms;
+ QTest::addRow("get_mgr_chrono") << Operation::GetOperation << 0 << 0ms << 0 << 500ms;
- QNetworkReplyPtr reply3(manager.get(request));
- QSignalSpy spy3(reply3.data(), SIGNAL(errorOccurred(QNetworkReply::NetworkError)));
-
- QCOMPARE(waitForFinish(reply3), int(Failure));
-
- QCOMPARE(spy3.count(), 1);
- QVERIFY(reply3->error() == QNetworkReply::OperationCanceledError);
-
- manager.setTransferTimeout(0);
+ QTest::addRow("post_req_int") << Operation::PostOperation << 500 << 0ms << 0 << 0ms;
+ QTest::addRow("post_req_chrono") << Operation::PostOperation << 0 << 500ms << 0 << 0ms;
+ QTest::addRow("post_mgr_int") << Operation::PostOperation << 0 << 0ms << 500 << 0ms;
+ QTest::addRow("post_mgr_chrono") << Operation::PostOperation << 0 << 0ms << 0 << 500ms;
}
-void tst_QNetworkReply::postWithTimeout()
+void tst_QNetworkReply::requestWithTimeout()
{
+ QFETCH(QNetworkAccessManager::Operation, method);
+ QFETCH(int, reqInt);
+ QFETCH(int, mgrInt);
+ QFETCH(std::chrono::milliseconds, reqChrono);
+ QFETCH(std::chrono::milliseconds, mgrChrono);
+ const auto data = "some data"_ba;
+ // Manager instance remains between case runs => always reset it's transferTimeout to
+ // ensure setting its transferTimeout in this case has effect
+ manager.setTransferTimeout(0ms);
+ auto cleanup = qScopeGuard([this] { manager.setTransferTimeout(0ms); });
+
MiniHttpServer server(tst_QNetworkReply::httpEmpty200Response, false);
+ server.stopTransfer = true;
QNetworkRequest request(QUrl("http://localhost:" + QString::number(server.serverPort())));
request.setRawHeader("Content-Type", "application/octet-stream");
- QByteArray postData("Just some nonsense");
- QNetworkReplyPtr reply(manager.post(request, postData));
- QSignalSpy spy(reply.data(), SIGNAL(errorOccurred(QNetworkReply::NetworkError)));
-
- QCOMPARE(waitForFinish(reply), int(Success));
-
- QCOMPARE(spy.count(), 0);
- QVERIFY(reply->error() == QNetworkReply::NoError);
-
- request.setTransferTimeout(1000);
- server.stopTransfer = true;
-
- QNetworkReplyPtr reply2(manager.post(request, postData));
- QSignalSpy spy2(reply2.data(), SIGNAL(errorOccurred(QNetworkReply::NetworkError)));
-
- QCOMPARE(waitForFinish(reply2), int(Failure));
+ if (reqInt > 0)
+ request.setTransferTimeout(reqInt);
+ if (reqChrono > 0ms)
+ request.setTransferTimeout(reqChrono);
+ if (mgrInt > 0)
+ manager.setTransferTimeout(mgrInt);
+ if (mgrChrono > 0ms)
+ manager.setTransferTimeout(mgrChrono);
- QCOMPARE(spy2.count(), 1);
- QVERIFY(reply2->error() == QNetworkReply::OperationCanceledError);
-
- request.setTransferTimeout(0);
- manager.setTransferTimeout(1000);
-
- QNetworkReplyPtr reply3(manager.post(request, postData));
- QSignalSpy spy3(reply3.data(), SIGNAL(errorOccurred(QNetworkReply::NetworkError)));
-
- QCOMPARE(waitForFinish(reply3), int(Failure));
-
- QCOMPARE(spy3.count(), 1);
- QVERIFY(reply3->error() == QNetworkReply::OperationCanceledError);
+ QNetworkReplyPtr reply;
+ if (method == QNetworkAccessManager::GetOperation)
+ reply.reset(manager.get(request));
+ else if (method == QNetworkAccessManager::PostOperation)
+ reply.reset(manager.post(request, data));
+ QVERIFY(reply);
- manager.setTransferTimeout(0);
+ QSignalSpy spy(reply.data(), &QNetworkReply::errorOccurred);
+ QCOMPARE(waitForFinish(reply), int(Failure));
+ QCOMPARE(spy.size(), 1);
+ QCOMPARE(reply->error(), QNetworkReply::OperationCanceledError);
}
void tst_QNetworkReply::moreActivitySignals_data()
{
QTest::addColumn<QUrl>("url");
QTest::addColumn<bool>("useipv6");
- QTest::addRow("local4") << QUrl("http://127.0.0.1") << false;
- QTest::addRow("local6") << QUrl("http://[::1]") << true;
+ QTest::addColumn<bool>("postWithData");
+ QTest::addRow("local4") << QUrl("http://127.0.0.1") << false << false;
+ QTest::addRow("local6") << QUrl("http://[::1]") << true << false;
if (qEnvironmentVariable("QTEST_ENVIRONMENT").split(' ').contains("ci")) {
// On CI server
- QTest::addRow("localDns") << QUrl("http://localhost") << false; // will find v6
+ QTest::addRow("localDns") << QUrl("http://localhost") << false << false; // will find v6
} else {
// For manual testing
- QTest::addRow("localDns4") << QUrl("http://localhost") << true; // will find both v4 and v6
- QTest::addRow("localDns6") << QUrl("http://localhost") << false; // will find both v4 and v6
+ QTest::addRow("localDns4") << QUrl("http://localhost") << true << false; // will find both v4 and v6
+ QTest::addRow("localDns6") << QUrl("http://localhost") << false << false; // will find both v4 and v6
}
+ QTest::addRow("post-with-data") << QUrl("http://[::1]") << true << true;
}
void tst_QNetworkReply::moreActivitySignals()
{
QFETCH(QUrl, url);
QFETCH(bool, useipv6);
+ QFETCH(bool, postWithData);
MiniHttpServer server(tst_QNetworkReply::httpEmpty200Response, false, nullptr/*thread*/, useipv6);
server.doClose = false;
url.setPort(server.serverPort());
QNetworkRequest request(url);
- QNetworkReplyPtr reply(manager.get(request));
- QSignalSpy spy1(reply.data(), SIGNAL(socketConnecting()));
+ QNetworkReplyPtr reply;
+ if (postWithData) {
+ request.setRawHeader("Content-Type", "text/plain");
+ reply.reset(manager.post(request, "Hello, world!"));
+ } else {
+ reply.reset(manager.get(request));
+ }
+ QSignalSpy spy1(reply.data(), SIGNAL(socketStartedConnecting()));
QSignalSpy spy2(reply.data(), SIGNAL(requestSent()));
QSignalSpy spy3(reply.data(), SIGNAL(metaDataChanged()));
QSignalSpy spy4(reply.data(), SIGNAL(finished()));
spy1.wait();
- QCOMPARE(spy1.count(), 1);
+ QCOMPARE(spy1.size(), 1);
spy2.wait();
- QCOMPARE(spy2.count(), 1);
+ QCOMPARE(spy2.size(), 1);
spy3.wait();
- QCOMPARE(spy3.count(), 1);
+ QCOMPARE(spy3.size(), 1);
spy4.wait();
- QCOMPARE(spy4.count(), 1);
+ QCOMPARE(spy4.size(), 1);
QVERIFY(reply->error() == QNetworkReply::NoError);
- // Second request will not send socketConnecting because of keep-alive, so don't check it.
- QNetworkReplyPtr secondreply(manager.get(request));
+ // Second request will not send socketStartedConnecting because of keep-alive, so don't check it.
+ QNetworkReplyPtr secondreply;
+ if (postWithData) {
+ request.setRawHeader("Content-Type", "text/plain");
+ secondreply.reset(manager.post(request, "Hello, world!"));
+ } else {
+ secondreply.reset(manager.get(request));
+ }
QSignalSpy secondspy2(secondreply.data(), SIGNAL(requestSent()));
QSignalSpy secondspy3(secondreply.data(), SIGNAL(metaDataChanged()));
QSignalSpy secondspy4(secondreply.data(), SIGNAL(finished()));
secondspy2.wait();
- QCOMPARE(secondspy2.count(), 1);
+ QCOMPARE(secondspy2.size(), 1);
secondspy3.wait();
- QCOMPARE(secondspy3.count(), 1);
+ QCOMPARE(secondspy3.size(), 1);
secondspy4.wait();
- QCOMPARE(secondspy4.count(), 1);
+ QCOMPARE(secondspy4.size(), 1);
QVERIFY(secondreply->error() == QNetworkReply::NoError);
}
@@ -9593,25 +10140,53 @@ void tst_QNetworkReply::contentEncoding_data()
QTest::addColumn<QByteArray>("encoding");
QTest::addColumn<QByteArray>("body");
QTest::addColumn<QByteArray>("expected");
+ QTest::addColumn<bool>("decompress");
+ const QByteArray helloWorld = "hello world";
+
+ const QByteArray gzipBody = QByteArray::fromBase64("H4sIAAAAAAAAA8tIzcnJVyjPL8pJAQCFEUoNCwAAAA==");
QTest::newRow("gzip-hello-world")
<< QByteArray("gzip")
- << QByteArray::fromBase64("H4sIAAAAAAAAA8tIzcnJVyjPL8pJAQCFEUoNCwAAAA==")
- << QByteArray("hello world");
+ << gzipBody
+ << helloWorld
+ << true;
+ QTest::newRow("gzip-hello-world-no-decompress")
+ << QByteArray("gzip")
+ << gzipBody
+ << helloWorld
+ << false;
+ const QByteArray deflateBody = QByteArray::fromBase64("eJzLSM3JyVcozy/KSQEAGgsEXQ==");
QTest::newRow("deflate-hello-world")
- << QByteArray("deflate") << QByteArray::fromBase64("eJzLSM3JyVcozy/KSQEAGgsEXQ==")
- << QByteArray("hello world");
+ << QByteArray("deflate") << deflateBody
+ << helloWorld
+ << true;
+ QTest::newRow("deflate-hello-world-no-decompress")
+ << QByteArray("deflate") << deflateBody
+ << helloWorld
+ << false;
#if QT_CONFIG(brotli)
+ const QByteArray brotliBody = QByteArray::fromBase64("DwWAaGVsbG8gd29ybGQD");
QTest::newRow("brotli-hello-world")
- << QByteArray("br") << QByteArray::fromBase64("DwWAaGVsbG8gd29ybGQD")
- << QByteArray("hello world");
+ << QByteArray("br") << brotliBody
+ << helloWorld
+ << true;
+ QTest::newRow("brotli-hello-world-no-decompress")
+ << QByteArray("br") << brotliBody
+ << helloWorld
+ << false;
#endif
#if defined(QT_BUILD_INTERNAL) && QT_CONFIG(zstd)
+ const QByteArray zstdBody = QByteArray::fromBase64("KLUv/QRYWQAAaGVsbG8gd29ybGRoaR6y");
QTest::newRow("zstandard-hello-world")
- << QByteArray("zstd") << QByteArray::fromBase64("KLUv/QRYWQAAaGVsbG8gd29ybGRoaR6y")
- << QByteArray("hello world");
+ << QByteArray("zstd") << zstdBody
+ << helloWorld
+ << true;
+ QTest::newRow("zstandard-hello-world-no-decompress")
+ << QByteArray("zstd") << zstdBody
+ << helloWorld
+ << false;
#else
qDebug("Note: ZStandard testdata is only available for developer builds.");
#endif
@@ -9621,12 +10196,19 @@ void tst_QNetworkReply::contentEncoding()
{
QFETCH(QByteArray, encoding);
QFETCH(QByteArray, body);
+ QFETCH(bool, decompress);
QString header("HTTP/1.0 200 OK\r\nContent-Encoding: %1\r\nContent-Length: %2\r\n\r\n");
header = header.arg(encoding, QString::number(body.size()));
MiniHttpServer server(header.toLatin1() + body);
QNetworkRequest request(QUrl("http://localhost:" + QString::number(server.serverPort())));
+ if (!decompress) {
+ // This disables decompression of the received content:
+ request.setRawHeader("accept-encoding", QLatin1String("%1").arg(encoding).toLatin1());
+ // This disables the zerocopy optimization
+ request.setAttribute(QNetworkRequest::MaximumDownloadBufferSizeAttribute, 0);
+ }
QNetworkReplyPtr reply(manager.get(request));
QVERIFY2(waitForFinish(reply) == Success, msgWaitForFinished(reply));
@@ -9635,7 +10217,7 @@ void tst_QNetworkReply::contentEncoding()
{
// Check that we included the content encoding method in our Accept-Encoding header
const QByteArray &receivedData = server.receivedData;
- int start = receivedData.indexOf("Accept-Encoding");
+ int start = receivedData.indexOf("accept-encoding");
QVERIFY(start != -1);
int end = receivedData.indexOf("\r\n", start);
QVERIFY(end != -1);
@@ -9647,10 +10229,14 @@ void tst_QNetworkReply::contentEncoding()
QVERIFY2(list.contains(encoding), acceptedEncoding.data());
}
- QFETCH(QByteArray, expected);
-
- QCOMPARE(reply->bytesAvailable(), expected.size());
- QCOMPARE(reply->readAll(), expected);
+ if (decompress) {
+ QFETCH(QByteArray, expected);
+ QCOMPARE(reply->bytesAvailable(), expected.size());
+ QCOMPARE(reply->readAll(), expected);
+ } else {
+ QCOMPARE(reply->bytesAvailable(), body.size());
+ QCOMPARE(reply->readAll(), body);
+ }
}
void tst_QNetworkReply::contentEncodingBigPayload_data()
@@ -9664,7 +10250,7 @@ void tst_QNetworkReply::contentEncodingBigPayload_data()
QTest::addRow("gzip-4GB") << QByteArray("gzip") << (":/4G.gz") << fourGiB;
#if QT_CONFIG(brotli)
- QTest::addRow("brotli-4GB") << QByteArray("br") << (testDataDir + "./4G.br") << fourGiB;
+ QTest::addRow("brotli-4GB") << QByteArray("br") << (testDataDir + "/4G.br") << fourGiB;
#endif
#if defined(QT_BUILD_INTERNAL) && QT_CONFIG(zstd)
QTest::addRow("zstd-4GB") << QByteArray("zstd") << (":/4G.zst") << fourGiB;
@@ -9789,6 +10375,192 @@ void tst_QNetworkReply::downloadProgressWithContentEncoding()
QCOMPARE(bytesReceived, expected.size());
}
+void tst_QNetworkReply::contentEncodingError_data()
+{
+ QTest::addColumn<QByteArray>("encoding");
+ QTest::addColumn<QString>("path");
+ QTest::addColumn<QNetworkReply::NetworkError>("expectedError");
+
+ QTest::addRow("archive-bomb") << QByteArray("gzip") << (":/4G.gz")
+ << QNetworkReply::UnknownContentError;
+}
+
+void tst_QNetworkReply::contentEncodingError()
+{
+ QFETCH(QString, path);
+ QFile compressedFile(path);
+ QVERIFY(compressedFile.open(QIODevice::ReadOnly));
+ QByteArray body = compressedFile.readAll();
+
+ QFETCH(QByteArray, encoding);
+ QString header("HTTP/1.0 200 OK\r\nContent-Encoding: %1\r\nContent-Length: %2\r\n\r\n");
+ header = header.arg(encoding, QString::number(body.size()));
+
+ MiniHttpServer server(header.toLatin1() + body);
+
+ QNetworkRequest request(
+ QUrl(QLatin1String("http://localhost:%1").arg(QString::number(server.serverPort()))));
+ QNetworkReplyPtr reply(manager.get(request));
+
+ QTRY_VERIFY2_WITH_TIMEOUT(reply->isFinished(), qPrintable(reply->errorString()), 15000);
+ QTEST(reply->error(), "expectedError");
+}
+
+// When this test is failing it will appear flaky because it relies on the
+// timing of delivery from one socket to another in the OS.
+// + we have to send all the data at once, so the readyRead emissions are
+// compressed into a single emission, so we cannot artificially time it with
+// waits and sleeps.
+void tst_QNetworkReply::compressedReadyRead()
+{
+ // There were historically an issue where a mix of signal compression and
+ // data decompression made it so we accidentally didn't emit the final
+ // readyRead signal before emitting finished(). Test this here to make sure
+ // it happens:
+ const QByteArray gzipPayload =
+ QByteArray::fromBase64("H4sIAAAAAAAAA8tIzcnJVyjPL8pJAQCFEUoNCwAAAA==");
+ const QByteArray expected = "hello world";
+
+ QString header("HTTP/1.0 200 OK\r\nContent-Encoding: gzip\r\nContent-Length: %1\r\n\r\n");
+ header = header.arg(gzipPayload.size());
+ MiniHttpServer server(header.toLatin1()); // only send header automatically
+ server.doClose = false; // don't close and delete client socket right away
+
+ QNetworkRequest request(
+ QUrl(QLatin1String("http://localhost:%1").arg(QString::number(server.serverPort()))));
+ QNetworkReplyPtr reply(manager.get(request));
+
+ QObject::connect(reply.get(), &QNetworkReply::metaDataChanged, reply.get(),
+ [&server, &gzipPayload]() {
+ // Client received headers, now send data:
+ // We do this awkward write,flush,write dance to try to
+ // make sure the data does not all arrive at the same
+ // time. By design we send the final "=" byte by itself
+ qsizetype boundary = gzipPayload.size() - 1;
+ server.client->write(gzipPayload.sliced(0, boundary));
+ server.client->flush();
+ // Let the server take care of deleting the client once
+ // the rest of the data is written:
+ server.doClose = true;
+ server.client->write(gzipPayload.sliced(boundary));
+ });
+
+ QByteArray received;
+ QObject::connect(reply.get(), &QNetworkReply::readyRead, reply.get(),
+ [reply = reply.get(), &received]() {
+ received += reply->readAll();
+ });
+ QTRY_VERIFY(reply->isFinished());
+ QCOMPARE(received, expected);
+}
+
+void tst_QNetworkReply::notFoundWithCompression_data()
+{
+ contentEncoding_data();
+}
+
+void tst_QNetworkReply::notFoundWithCompression()
+{
+ QFETCH(QByteArray, encoding);
+ QFETCH(QByteArray, body);
+ QString header("HTTP/1.0 404 OK\r\nContent-Encoding: %1\r\nContent-Length: %2\r\n\r\n");
+ header = header.arg(encoding, QString::number(body.size()));
+
+ MiniHttpServer server(header.toLatin1() + body);
+
+ QNetworkRequest request(
+ QUrl(QLatin1String("http://localhost:%1").arg(QString::number(server.serverPort()))));
+ QNetworkReplyPtr reply(manager.get(request));
+
+ QTRY_VERIFY2_WITH_TIMEOUT(reply->isFinished(), qPrintable(reply->errorString()), 15000);
+ QCOMPARE(reply->error(), QNetworkReply::ContentNotFoundError);
+
+ QFETCH(QByteArray, expected);
+ QCOMPARE(reply->readAll(), expected);
+}
+
+void tst_QNetworkReply::qtbug68821proxyError_data()
+{
+ QTest::addColumn<QString>("proxyHost");
+ QTest::addColumn<QString>("scheme");
+ QTest::addColumn<QNetworkReply::NetworkError>("error");
+
+ QTest::newRow("invalidhost+http") << "this-host-will-never-exist.qt-project.org"
+ << "http" << QNetworkReply::ProxyNotFoundError;
+ QTest::newRow("localhost+http") << "localhost"
+ << "http" << QNetworkReply::ProxyConnectionRefusedError;
+#ifndef QT_NO_SSL
+ QTest::newRow("invalidhost+https") << "this-host-will-never-exist.qt-project.org"
+ << "https" << QNetworkReply::ProxyNotFoundError;
+ QTest::newRow("localhost+https") << "localhost"
+ << "https" << QNetworkReply::ProxyConnectionRefusedError;
+#endif
+}
+
+void tst_QNetworkReply::qtbug68821proxyError()
+{
+ auto getUnusedPort = []() -> std::optional<quint16> {
+ QTcpServer probeServer;
+ if (!probeServer.listen())
+ return std::nullopt;
+ // If we can listen on it, it was unused, and hopefully is also
+ // still unused after we stop listening.
+ return probeServer.serverPort();
+ };
+
+ auto proxyPort = getUnusedPort();
+ QVERIFY(proxyPort);
+
+ QFETCH(QString, proxyHost);
+ QNetworkProxy proxy(QNetworkProxy::HttpProxy, proxyHost, proxyPort.value());
+
+ manager.setProxy(proxy);
+
+ QFETCH(QString, scheme);
+ QNetworkReply *reply = manager.get(QNetworkRequest(QUrl(scheme + "://example.com")));
+ QSignalSpy spy(reply, &QNetworkReply::errorOccurred);
+ QVERIFY(spy.isValid());
+
+ QVERIFY(spy.wait(15000));
+
+ QFETCH(QNetworkReply::NetworkError, error);
+ QCOMPARE(spy.count(), 1);
+ QCOMPARE(spy.at(0).at(0), error);
+}
+
+void tst_QNetworkReply::abortAndError()
+{
+ const QByteArray response =
+ R"(HTTP/1.0 500 Internal Server Error
+Content-Length: 12
+Content-Type: text/plain
+
+Hello World!)"_ba;
+
+ MiniHttpServer server(response);
+
+ QNetworkAccessManager manager;
+ QNetworkRequest req(QUrl("http://127.0.0.1:" + QString::number(server.serverPort())));
+ std::unique_ptr<QNetworkReply> reply(manager.post(req, "my data goes here"_ba));
+ QSignalSpy errorSignal(reply.get(), &QNetworkReply::errorOccurred);
+ QSignalSpy finishedSignal(reply.get(), &QNetworkReply::finished);
+
+ reply->abort();
+
+ // We don't want to print this warning in this case because it is impossible
+ // for users to avoid it.
+ QTest::failOnWarning("QNetworkReplyImplPrivate::error: Internal problem, this method must only "
+ "be called once.");
+ // Process any signals from the http thread:
+ QTest::qWait(1s);
+ if (QTest::currentTestFailed())
+ return;
+
+ QCOMPARE(finishedSignal.count(), 1);
+ QCOMPARE(errorSignal.count(), 1);
+ QCOMPARE(reply->error(), QNetworkReply::OperationCanceledError);
+}
+
// NOTE: This test must be last testcase in tst_qnetworkreply!
void tst_QNetworkReply::parentingRepliesToTheApp()
{
diff --git a/tests/auto/network/access/qnetworkrequest/CMakeLists.txt b/tests/auto/network/access/qnetworkrequest/CMakeLists.txt
index 1a98449549..2c4a7dd7ca 100644
--- a/tests/auto/network/access/qnetworkrequest/CMakeLists.txt
+++ b/tests/auto/network/access/qnetworkrequest/CMakeLists.txt
@@ -1,12 +1,19 @@
-# Generated from qnetworkrequest.pro.
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
#####################################################################
## tst_qnetworkrequest Test:
#####################################################################
+if(NOT QT_BUILD_STANDALONE_TESTS AND NOT QT_BUILDING_QT)
+ cmake_minimum_required(VERSION 3.16)
+ project(tst_qnetworkrequest LANGUAGES CXX)
+ find_package(Qt6BuildInternals REQUIRED COMPONENTS STANDALONE_TEST)
+endif()
+
qt_internal_add_test(tst_qnetworkrequest
SOURCES
tst_qnetworkrequest.cpp
- PUBLIC_LIBRARIES
+ LIBRARIES
Qt::Network
)
diff --git a/tests/auto/network/access/qnetworkrequest/tst_qnetworkrequest.cpp b/tests/auto/network/access/qnetworkrequest/tst_qnetworkrequest.cpp
index d90289ea08..bdef1115dd 100644
--- a/tests/auto/network/access/qnetworkrequest/tst_qnetworkrequest.cpp
+++ b/tests/auto/network/access/qnetworkrequest/tst_qnetworkrequest.cpp
@@ -1,37 +1,15 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
+// Copyright (C) 2022 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
#include <QTest>
-#include <QtCore/QUrl>
+
#include <QtNetwork/QNetworkRequest>
#include <QtNetwork/QNetworkCookie>
+#include <QtCore/QDateTime>
+#include <QtCore/QTimeZone>
+#include <QtCore/QUrl>
+
Q_DECLARE_METATYPE(QNetworkRequest::KnownHeaders)
class tst_QNetworkRequest: public QObject
@@ -188,11 +166,11 @@ void tst_QNetworkRequest::rawHeaderList_data()
void tst_QNetworkRequest::rawHeaderList()
{
- QFETCH(QList<QByteArray>, set);
+ QFETCH(const QList<QByteArray>, set);
QFETCH(QList<QByteArray>, expected);
QNetworkRequest request;
- foreach (QByteArray header, set)
+ for (const QByteArray &header : set)
request.setRawHeader(header, "a value");
QList<QByteArray> got = request.rawHeaderList();
@@ -236,12 +214,30 @@ void tst_QNetworkRequest::setHeader_data()
<< QVariant(QDate(2007, 11, 01))
<< true << "Last-Modified"
<< "Thu, 01 Nov 2007 00:00:00 GMT";
- QTest::newRow("Last-Modified-DateTime") << QNetworkRequest::LastModifiedHeader
- << QVariant(QDateTime(QDate(2007, 11, 01),
- QTime(18, 8, 30),
- Qt::UTC))
- << true << "Last-Modified"
- << "Thu, 01 Nov 2007 18:08:30 GMT";
+ QTest::newRow("Last-Modified-DateTime-UTC")
+ << QNetworkRequest::LastModifiedHeader
+ << QVariant(QDateTime(QDate(2007, 11, 1), QTime(18, 8, 30), QTimeZone::UTC))
+ << true << "Last-Modified" << "Thu, 01 Nov 2007 18:08:30 GMT";
+ // QTBUG-80666: format dates correctly (as GMT) even if the date passed in isn't in UTC:
+ QTest::newRow("Last-Modified-DateTime-Local")
+ << QNetworkRequest::LastModifiedHeader
+ << QVariant(QDateTime(QDate(2007, 11, 1), QTime(18, 8, 30), QTimeZone::UTC).toLocalTime())
+ << true << "Last-Modified" << "Thu, 01 Nov 2007 18:08:30 GMT";
+ QTest::newRow("Last-Modified-DateTime-Offset")
+ << QNetworkRequest::LastModifiedHeader
+ << QVariant(QDateTime(QDate(2007, 11, 1), QTime(18, 8, 30),
+ QTimeZone::UTC).toOffsetFromUtc(3600))
+ << true << "Last-Modified" << "Thu, 01 Nov 2007 18:08:30 GMT";
+#if QT_CONFIG(timezone)
+ QTimeZone cet("Europe/Oslo");
+ if (cet.isValid()) {
+ QTest::newRow("Last-Modified-DateTime-CET")
+ << QNetworkRequest::LastModifiedHeader
+ << QVariant(QDateTime(QDate(2007, 11, 1), QTime(18, 8, 30),
+ QTimeZone::UTC).toTimeZone(cet))
+ << true << "Last-Modified" << "Thu, 01 Nov 2007 18:08:30 GMT";
+ }
+#endif
QTest::newRow("If-Modified-Since-Date") << QNetworkRequest::IfModifiedSinceHeader
<< QVariant(QDate(2017, 7, 01))
@@ -250,7 +246,7 @@ void tst_QNetworkRequest::setHeader_data()
QTest::newRow("If-Modified-Since-DateTime") << QNetworkRequest::IfModifiedSinceHeader
<< QVariant(QDateTime(QDate(2017, 7, 01),
QTime(3, 14, 15),
- Qt::UTC))
+ QTimeZone::UTC))
<< true << "If-Modified-Since"
<< "Sat, 01 Jul 2017 03:14:15 GMT";
@@ -358,38 +354,38 @@ void tst_QNetworkRequest::rawHeaderParsing_data()
QTest::newRow("Last-Modified-RFC1123") << QNetworkRequest::LastModifiedHeader
<< QVariant(QDateTime(QDate(1994, 11, 06),
QTime(8, 49, 37),
- Qt::UTC))
+ QTimeZone::UTC))
<< true << "Last-Modified"
<< "Sun, 06 Nov 1994 08:49:37 GMT";
QTest::newRow("Last-Modified-RFC850") << QNetworkRequest::LastModifiedHeader
<< QVariant(QDateTime(QDate(1994, 11, 06),
QTime(8, 49, 37),
- Qt::UTC))
+ QTimeZone::UTC))
<< true << "Last-Modified"
<< "Sunday, 06-Nov-94 08:49:37 GMT";
QTest::newRow("Last-Modified-asctime") << QNetworkRequest::LastModifiedHeader
<< QVariant(QDateTime(QDate(1994, 11, 06),
QTime(8, 49, 37),
- Qt::UTC))
+ QTimeZone::UTC))
<< true << "Last-Modified"
<< "Sun Nov 6 08:49:37 1994";
QTest::newRow("If-Modified-Since-RFC1123") << QNetworkRequest::IfModifiedSinceHeader
<< QVariant(QDateTime(QDate(1994, 8, 06),
QTime(8, 49, 37),
- Qt::UTC))
+ QTimeZone::UTC))
<< true << "If-Modified-Since"
<< "Sun, 06 Aug 1994 08:49:37 GMT";
QTest::newRow("If-Modified-Since-RFC850") << QNetworkRequest::IfModifiedSinceHeader
<< QVariant(QDateTime(QDate(1994, 8, 06),
QTime(8, 49, 37),
- Qt::UTC))
+ QTimeZone::UTC))
<< true << "If-Modified-Since"
<< "Sunday, 06-Aug-94 08:49:37 GMT";
QTest::newRow("If-Modified-Since-asctime") << QNetworkRequest::IfModifiedSinceHeader
<< QVariant(QDateTime(QDate(1994, 8, 06),
QTime(8, 49, 37),
- Qt::UTC))
+ QTimeZone::UTC))
<< true << "If-Modified-Since"
<< "Sun Aug 6 08:49:37 1994";
diff --git a/tests/auto/network/access/qnetworkrequestfactory/CMakeLists.txt b/tests/auto/network/access/qnetworkrequestfactory/CMakeLists.txt
new file mode 100644
index 0000000000..d2112de58f
--- /dev/null
+++ b/tests/auto/network/access/qnetworkrequestfactory/CMakeLists.txt
@@ -0,0 +1,17 @@
+# Copyright (C) 2023 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
+
+if(NOT QT_BUILD_STANDALONE_TESTS AND NOT QT_BUILDING_QT)
+ cmake_minimum_required(VERSION 3.16)
+ project(tst_qnetworkrequestfactory LANGUAGES CXX)
+ find_package(Qt6BuildInternals REQUIRED COMPONENTS STANDALONE_TEST)
+endif()
+
+qt_internal_add_test(tst_qnetworkrequestfactory
+ SOURCES
+ tst_qnetworkrequestfactory.cpp
+ LIBRARIES
+ Qt::Core
+ Qt::Test
+ Qt::Network
+)
diff --git a/tests/auto/network/access/qnetworkrequestfactory/tst_qnetworkrequestfactory.cpp b/tests/auto/network/access/qnetworkrequestfactory/tst_qnetworkrequestfactory.cpp
new file mode 100644
index 0000000000..d04a7ff3ec
--- /dev/null
+++ b/tests/auto/network/access/qnetworkrequestfactory/tst_qnetworkrequestfactory.cpp
@@ -0,0 +1,423 @@
+// Copyright (C) 2023 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
+
+#include <QtTest/qtest.h>
+#include <QtNetwork/qnetworkrequestfactory.h>
+#ifndef QT_NO_SSL
+#include <QtNetwork/qsslconfiguration.h>
+#endif
+#include <QtCore/qurlquery.h>
+#include <QtCore/qurl.h>
+
+using namespace Qt::StringLiterals;
+using namespace std::chrono_literals;
+
+class tst_QNetworkRequestFactory : public QObject
+{
+ Q_OBJECT
+
+private Q_SLOTS:
+ void urlAndPath_data();
+ void urlAndPath();
+ void queryParameters();
+ void sslConfiguration();
+ void headers();
+ void bearerToken();
+ void operators();
+ void timeout();
+ void userInfo();
+ void priority();
+ void attributes();
+
+private:
+ const QUrl url1{u"http://foo.io"_s};
+ const QUrl url2{u"http://bar.io"_s};
+ const QByteArray bearerToken1{"bearertoken1"};
+ const QByteArray bearerToken2{"bearertoken2"};
+};
+
+void tst_QNetworkRequestFactory::urlAndPath_data()
+{
+ QTest::addColumn<QUrl>("baseUrl");
+ QTest::addColumn<QString>("requestPath");
+ QTest::addColumn<QUrl>("expectedRequestUrl");
+
+ QUrl base{"http://xyz.io"};
+ QUrl result{"http://xyz.io/path/to"};
+ QTest::newRow("baseUrl_nopath_noslash_1") << base << u""_s << base;
+ QTest::newRow("baseUrl_nopath_noslash_2") << base << u"/path/to"_s << result;
+ QTest::newRow("baseUrl_nopath_noslash_3") << base << u"path/to"_s << result;
+
+ base.setUrl("http://xyz.io/");
+ result.setUrl("http://xyz.io/path/to");
+ QTest::newRow("baseUrl_nopath_withslash_1") << base << u""_s << base;
+ QTest::newRow("baseUrl_nopath_withslash_2") << base << u"/path/to"_s << result;
+ QTest::newRow("baseUrl_nopath_withslash_3") << base << u"path/to"_s << result;
+
+ base.setUrl("http://xyz.io/v1");
+ result.setUrl("http://xyz.io/v1/path/to");
+ QTest::newRow("baseUrl_withpath_noslash_1") << base << u""_s << base;
+ QTest::newRow("baseUrl_withpath_noslash_2") << base << u"/path/to"_s << result;
+ QTest::newRow("baseUrl_withpath_noslash_3") << base << u"path/to"_s << result;
+
+ base.setUrl("http://xyz.io/v1/");
+ QTest::newRow("baseUrl_withpath_withslash_1") << base << u""_s << base;
+ QTest::newRow("baseUrl_withpath_withslash_2") << base << u"/path/to"_s << result;
+ QTest::newRow("baseUrl_withpath_withslash_3") << base << u"path/to"_s << result;
+
+ // Currently we keep any double '//', but not sure if there is a use case for it, or could
+ // it be corrected to a single '/'
+ base.setUrl("http://xyz.io/v1//");
+ result.setUrl("http://xyz.io/v1//path/to");
+ QTest::newRow("baseUrl_withpath_doubleslash_1") << base << u""_s << base;
+ QTest::newRow("baseUrl_withpath_doubleslash_2") << base << u"/path/to"_s << result;
+ QTest::newRow("baseUrl_withpath_doubleslash_3") << base << u"path/to"_s << result;
+}
+
+void tst_QNetworkRequestFactory::urlAndPath()
+{
+ QFETCH(QUrl, baseUrl);
+ QFETCH(QString, requestPath);
+ QFETCH(QUrl, expectedRequestUrl);
+
+ // Set with constructor
+ QNetworkRequestFactory factory1{baseUrl};
+ QCOMPARE(factory1.baseUrl(), baseUrl);
+
+ // Set with setter calls
+ QNetworkRequestFactory factory2{};
+ factory2.setBaseUrl(baseUrl);
+ QCOMPARE(factory2.baseUrl(), baseUrl);
+
+ // Request path
+ QNetworkRequest request = factory1.createRequest();
+ QCOMPARE(request.url(), baseUrl); // No path was provided for createRequest(), expect baseUrl
+ request = factory1.createRequest(requestPath);
+ QCOMPARE(request.url(), expectedRequestUrl);
+
+ // Check the request path didn't change base url
+ QCOMPARE(factory1.baseUrl(), baseUrl);
+}
+
+void tst_QNetworkRequestFactory::queryParameters()
+{
+ QNetworkRequestFactory factory({"http://example.com"});
+ const QUrlQuery query1{{"q1k", "q1v"}};
+ const QUrlQuery query2{{"q2k", "q2v"}};
+
+ // Set query parameters in createRequest() call
+ QCOMPARE(factory.createRequest(query1).url(), QUrl{"http://example.com?q1k=q1v"});
+ QCOMPARE(factory.createRequest(query2).url(), QUrl{"http://example.com?q2k=q2v"});
+
+ // Set query parameters into the factory
+ factory.setQueryParameters(query1);
+ QUrlQuery resultQuery = factory.queryParameters();
+ for (const auto &item: query1.queryItems()) {
+ QVERIFY(resultQuery.hasQueryItem(item.first));
+ QCOMPARE(resultQuery.queryItemValue(item.first), item.second);
+ }
+ QCOMPARE(factory.createRequest().url(), QUrl{"http://example.com?q1k=q1v"});
+
+ // Set query parameters into both createRequest() and factory
+ QCOMPARE(factory.createRequest(query2).url(), QUrl{"http://example.com?q2k=q2v&q1k=q1v"});
+
+ // Clear query parameters
+ factory.clearQueryParameters();
+ QVERIFY(factory.queryParameters().isEmpty());
+ QCOMPARE(factory.createRequest().url(), QUrl{"http://example.com"});
+
+ const QString pathWithQuery{"content?raw=1"};
+ // Set query parameters in per-request path
+ QCOMPARE(factory.createRequest(pathWithQuery).url(),
+ QUrl{"http://example.com/content?raw=1"});
+ // Set query parameters in per-request path and the query parameter
+ QCOMPARE(factory.createRequest(pathWithQuery, query1).url(),
+ QUrl{"http://example.com/content?q1k=q1v&raw=1"});
+ // Set query parameter in per-request path and into the factory
+ factory.setQueryParameters(query2);
+ QCOMPARE(factory.createRequest(pathWithQuery).url(),
+ QUrl{"http://example.com/content?raw=1&q2k=q2v"});
+ // Set query parameters in per-request, as additional parameters, and into the factory
+ QCOMPARE(factory.createRequest(pathWithQuery, query1).url(),
+ QUrl{"http://example.com/content?q1k=q1v&raw=1&q2k=q2v"});
+
+ // Test that other than path and query items as part of path are ignored
+ factory.setQueryParameters(query1);
+ QRegularExpression re("The provided path*");
+ QTest::ignoreMessage(QtMsgType::QtWarningMsg, re);
+ QCOMPARE(factory.createRequest("https://example2.com").url(), QUrl{"http://example.com?q1k=q1v"});
+ QTest::ignoreMessage(QtMsgType::QtWarningMsg, re);
+ QCOMPARE(factory.createRequest("https://example2.com?q3k=q3v").url(),
+ QUrl{"http://example.com?q3k=q3v&q1k=q1v"});
+}
+
+void tst_QNetworkRequestFactory::sslConfiguration()
+{
+#ifdef QT_NO_SSL
+ QSKIP("Skipping SSL tests, not supported by build");
+#else
+ // Two initially equal factories
+ QNetworkRequestFactory factory1{url1};
+ QNetworkRequestFactory factory2{url1};
+
+ // Make two differing SSL configurations (for this test it's irrelevant how they differ)
+ QSslConfiguration config1;
+ config1.setProtocol(QSsl::TlsV1_2);
+ QSslConfiguration config2;
+ config2.setProtocol(QSsl::DtlsV1_2);
+
+ // Set configuration and verify that the same config is returned
+ factory1.setSslConfiguration(config1);
+ QCOMPARE(factory1.sslConfiguration(), config1);
+ factory2.setSslConfiguration(config2);
+ QCOMPARE(factory2.sslConfiguration(), config2);
+
+ // Verify requests are set with appropriate SSL configs
+ QNetworkRequest request1 = factory1.createRequest();
+ QCOMPARE(request1.sslConfiguration(), config1);
+ QNetworkRequest request2 = factory2.createRequest();
+ QCOMPARE(request2.sslConfiguration(), config2);
+#endif
+}
+
+void tst_QNetworkRequestFactory::headers()
+{
+ const QByteArray name1{"headername1"};
+ const QByteArray name2{"headername2"};
+ const QByteArray value1{"headervalue1"};
+ const QByteArray value2{"headervalue2"};
+ const QByteArray value3{"headervalue3"};
+
+ QNetworkRequestFactory factory{url1};
+ // Initial state when no headers are set
+ QVERIFY(factory.commonHeaders().isEmpty());
+ QVERIFY(factory.commonHeaders().values(name1).isEmpty());
+ QVERIFY(!factory.commonHeaders().contains(name1));
+
+ // Set headers
+ QHttpHeaders h1;
+ h1.append(name1, value1);
+ factory.setCommonHeaders(h1);
+ QVERIFY(factory.commonHeaders().contains(name1));
+ QCOMPARE(factory.commonHeaders().combinedValue(name1), value1);
+ QCOMPARE(factory.commonHeaders().size(), 1);
+ QVERIFY(factory.commonHeaders().values("nonexistent").isEmpty());
+ QNetworkRequest request = factory.createRequest();
+ QVERIFY(request.hasRawHeader(name1));
+ QCOMPARE(request.rawHeader(name1), value1);
+
+ // Check that empty header does not match
+ QVERIFY(!factory.commonHeaders().contains(""_ba));
+ QVERIFY(factory.commonHeaders().values(""_ba).isEmpty());
+
+ // Clear headers
+ factory.clearCommonHeaders();
+ QVERIFY(factory.commonHeaders().isEmpty());
+ request = factory.createRequest();
+ QVERIFY(!request.hasRawHeader(name1));
+
+ // Set headers with more entries
+ h1.clear();
+ h1.append(name1, value1);
+ h1.append(name2, value2);
+ factory.setCommonHeaders(h1);
+ QVERIFY(factory.commonHeaders().contains(name1));
+ QVERIFY(factory.commonHeaders().contains(name2));
+ QCOMPARE(factory.commonHeaders().combinedValue(name1), value1);
+ QCOMPARE(factory.commonHeaders().combinedValue(name2), value2);
+ QCOMPARE(factory.commonHeaders().size(), 2);
+ request = factory.createRequest();
+ QVERIFY(request.hasRawHeader(name1));
+ QVERIFY(request.hasRawHeader(name2));
+ QCOMPARE(request.rawHeader(name1), value1);
+ QCOMPARE(request.rawHeader(name2), value2);
+ // Append more values to pre-existing header name2
+ h1.clear();
+ h1.append(name1, value1);
+ h1.append(name1, value2);
+ h1.append(name1, value3);
+ factory.setCommonHeaders(h1);
+ QVERIFY(factory.commonHeaders().contains(name1));
+ QCOMPARE(factory.commonHeaders().combinedValue(name1), value1 + ", " + value2 + ", " + value3);
+ request = factory.createRequest();
+ QVERIFY(request.hasRawHeader(name1));
+ QCOMPARE(request.rawHeader(name1), value1 + ", " + value2 + ", " + value3);
+}
+
+void tst_QNetworkRequestFactory::bearerToken()
+{
+ const auto authHeader = "Authorization"_ba;
+ QNetworkRequestFactory factory{url1};
+ QVERIFY(factory.bearerToken().isEmpty());
+
+ factory.setBearerToken(bearerToken1);
+ QCOMPARE(factory.bearerToken(), bearerToken1);
+ QNetworkRequest request = factory.createRequest();
+ QVERIFY(request.hasRawHeader(authHeader));
+ QCOMPARE(request.rawHeader(authHeader), "Bearer "_ba + bearerToken1);
+
+ // Verify that bearerToken is not in debug output
+ QString debugOutput;
+ QDebug debug(&debugOutput);
+ debug << factory;
+ QVERIFY(debugOutput.contains("bearerToken = (is set)"));
+ QVERIFY(!debugOutput.contains(bearerToken1));
+
+ factory.setBearerToken(bearerToken2);
+ QCOMPARE(factory.bearerToken(), bearerToken2);
+ request = factory.createRequest();
+ QVERIFY(request.hasRawHeader(authHeader));
+ QCOMPARE(request.rawHeader(authHeader), "Bearer "_ba + bearerToken2);
+
+ // Set authorization header manually
+ const auto value = "headervalue"_ba;
+ QHttpHeaders h1;
+ h1.append(authHeader, value);
+ factory.setCommonHeaders(h1);
+ request = factory.createRequest();
+ QVERIFY(request.hasRawHeader(authHeader));
+ // bearerToken has precedence over manually set header
+ QCOMPARE(request.rawHeader(authHeader), "Bearer "_ba + bearerToken2);
+ // clear bearer token, the manually set header is now used
+ factory.clearBearerToken();
+ request = factory.createRequest();
+ QVERIFY(request.hasRawHeader(authHeader));
+ QCOMPARE(request.rawHeader(authHeader), value);
+}
+
+void tst_QNetworkRequestFactory::operators()
+{
+ QNetworkRequestFactory factory1(url1);
+
+ // Copy ctor
+ QNetworkRequestFactory factory2(factory1);
+ QCOMPARE(factory2.baseUrl(), factory1.baseUrl());
+
+ // Copy assignment
+ QNetworkRequestFactory factory3;
+ factory3 = factory2;
+ QCOMPARE(factory3.baseUrl(), factory2.baseUrl());
+
+ // Move assignment
+ QNetworkRequestFactory factory4;
+ factory4 = std::move(factory3);
+ QCOMPARE(factory4.baseUrl(), factory2.baseUrl());
+
+ // Verify implicit sharing
+ factory1.setBaseUrl(url2);
+ QCOMPARE(factory1.baseUrl(), url2); // changed
+ QCOMPARE(factory2.baseUrl(), url1); // remains
+
+ // Move ctor
+ QNetworkRequestFactory factory5{std::move(factory4)};
+ QCOMPARE(factory5.baseUrl(), factory2.baseUrl()); // the moved factory4 originates from factory2
+ QCOMPARE(factory5.baseUrl(), url1);
+}
+
+void tst_QNetworkRequestFactory::timeout()
+{
+ constexpr auto defaultTimeout = 0ms;
+ constexpr auto timeout = 150ms;
+
+ QNetworkRequestFactory factory;
+ QNetworkRequest request = factory.createRequest();
+ QCOMPARE(factory.transferTimeout(), defaultTimeout);
+ QCOMPARE(request.transferTimeoutAsDuration(), defaultTimeout);
+
+ factory.setTransferTimeout(timeout);
+ request = factory.createRequest();
+ QCOMPARE(factory.transferTimeout(), timeout);
+ QCOMPARE(request.transferTimeoutAsDuration(), timeout);
+}
+
+void tst_QNetworkRequestFactory::userInfo()
+{
+ QNetworkRequestFactory factory;
+ QVERIFY(factory.userName().isEmpty());
+ QVERIFY(factory.password().isEmpty());
+
+ const auto uname = u"a_username"_s;
+ const auto password = u"a_password"_s;
+ factory.setUserName(uname);
+ QCOMPARE(factory.userName(), uname);
+ factory.setPassword(password);
+ QCOMPARE(factory.password(), password);
+
+ // Verify that debug output does not contain password
+ QString debugOutput;
+ QDebug debug(&debugOutput);
+ debug << factory;
+ QVERIFY(debugOutput.contains("password = (is set)"));
+ QVERIFY(!debugOutput.contains(password));
+
+ factory.clearUserName();
+ factory.clearPassword();
+ QVERIFY(factory.userName().isEmpty());
+ QVERIFY(factory.password().isEmpty());
+}
+
+void tst_QNetworkRequestFactory::priority()
+{
+ QNetworkRequestFactory factory(u"http://example.com"_s);
+ QCOMPARE(factory.priority(), QNetworkRequest::NormalPriority);
+ auto request = factory.createRequest("/index.html");
+ QCOMPARE(request.priority(), QNetworkRequest::NormalPriority);
+
+ factory.setPriority(QNetworkRequest::HighPriority);
+ QCOMPARE(factory.priority(), QNetworkRequest::HighPriority);
+ request = factory.createRequest("/index.html");
+ QCOMPARE(request.priority(), QNetworkRequest::HighPriority);
+}
+
+void tst_QNetworkRequestFactory::attributes()
+{
+ const auto attribute1 = QNetworkRequest::Attribute::BackgroundRequestAttribute;
+ const auto attribute2 = QNetworkRequest::User;
+ QNetworkRequestFactory factory;
+ QNetworkRequest request;
+
+ // Empty factory
+ QVERIFY(!factory.attribute(attribute1).isValid());
+ request = factory.createRequest();
+ QVERIFY(!request.attribute(attribute1).isValid());
+
+ // (Re-)set and clear individual attribute
+ factory.setAttribute(attribute1, true);
+ QVERIFY(factory.attribute(attribute1).isValid());
+ QCOMPARE(factory.attribute(attribute1).toBool(), true);
+ request = factory.createRequest();
+ QVERIFY(request.attribute(attribute1).isValid());
+ QCOMPARE(request.attribute(attribute1).toBool(), true);
+ // Replace previous value
+ factory.setAttribute(attribute1, false);
+ QVERIFY(factory.attribute(attribute1).isValid());
+ QCOMPARE(factory.attribute(attribute1).toBool(), false);
+ request = factory.createRequest();
+ QVERIFY(request.attribute(attribute1).isValid());
+ QCOMPARE(request.attribute(attribute1).toBool(), false);
+ // Clear individual attribute
+ factory.clearAttribute(attribute1);
+ QVERIFY(!factory.attribute(attribute1).isValid());
+
+ // Getter default value
+ QCOMPARE(factory.attribute(attribute2, 111).toInt(), 111); // default value returned
+ factory.setAttribute(attribute2, 222);
+ QCOMPARE(factory.attribute(attribute2, 111).toInt(), 222); // actual value returned
+ factory.clearAttribute(attribute2);
+ QCOMPARE(factory.attribute(attribute2, 111).toInt(), 111); // default value returned
+
+ // Clear attributes
+ factory.setAttribute(attribute1, true);
+ factory.setAttribute(attribute2, 333);
+ QVERIFY(factory.attribute(attribute1).isValid());
+ QVERIFY(factory.attribute(attribute2).isValid());
+ factory.clearAttributes();
+ QVERIFY(!factory.attribute(attribute1).isValid());
+ QVERIFY(!factory.attribute(attribute2).isValid());
+ request = factory.createRequest();
+ QVERIFY(!request.attribute(attribute1).isValid());
+ QVERIFY(!request.attribute(attribute2).isValid());
+}
+
+QTEST_MAIN(tst_QNetworkRequestFactory)
+#include "tst_qnetworkrequestfactory.moc"
diff --git a/tests/auto/network/access/qrestaccessmanager/CMakeLists.txt b/tests/auto/network/access/qrestaccessmanager/CMakeLists.txt
new file mode 100644
index 0000000000..614248be28
--- /dev/null
+++ b/tests/auto/network/access/qrestaccessmanager/CMakeLists.txt
@@ -0,0 +1,17 @@
+# Copyright (C) 2023 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
+
+if(NOT QT_BUILD_STANDALONE_TESTS AND NOT QT_BUILDING_QT)
+ cmake_minimum_required(VERSION 3.16)
+ project(tst_qrestaccessmanager LANGUAGES CXX)
+ find_package(Qt6BuildInternals REQUIRED COMPONENTS STANDALONE_TEST)
+endif()
+
+qt_internal_add_test(tst_qrestaccessmanager
+ SOURCES
+ tst_qrestaccessmanager.cpp
+ httptestserver.cpp httptestserver_p.h
+ LIBRARIES
+ Qt::Network
+ Qt::CorePrivate
+)
diff --git a/tests/auto/network/access/qrestaccessmanager/httptestserver.cpp b/tests/auto/network/access/qrestaccessmanager/httptestserver.cpp
new file mode 100644
index 0000000000..25869eb46b
--- /dev/null
+++ b/tests/auto/network/access/qrestaccessmanager/httptestserver.cpp
@@ -0,0 +1,268 @@
+// Copyright (C) 2023 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
+
+#include "httptestserver_p.h"
+
+#include <QtNetwork/qtcpsocket.h>
+
+#include <QtCore/qcoreapplication.h>
+
+#include <private/qlocale_p.h>
+
+using namespace Qt::StringLiterals;
+
+static constexpr char CRLF[] = "\r\n";
+
+HttpTestServer::HttpTestServer(QObject *parent) : QTcpServer(parent)
+{
+ QObject::connect(this, &QTcpServer::newConnection, this, &HttpTestServer::handleConnected);
+ const auto ok = listen(QHostAddress::LocalHost);
+ Q_ASSERT(ok);
+};
+
+HttpTestServer::~HttpTestServer()
+{
+ if (isListening())
+ close();
+}
+
+QUrl HttpTestServer::url()
+{
+ return QUrl(u"http://127.0.0.1:%1"_s.arg(serverPort()));
+}
+
+void HttpTestServer::handleConnected()
+{
+ Q_ASSERT(!m_socket); // No socket must exist previously, this is a single-connection server
+ m_socket = nextPendingConnection();
+ Q_ASSERT(m_socket);
+ QObject::connect(m_socket, &QTcpSocket::readyRead,
+ this, &HttpTestServer::handleDataAvailable);
+}
+
+void HttpTestServer::handleDataAvailable()
+{
+ Q_ASSERT(m_socket);
+ bool ok = true;
+
+ // Parse the incoming request data into the HttpData object
+ while (m_socket->bytesAvailable()) {
+ if (state == State::ReadingMethod && !(ok = readMethod(m_socket)))
+ qWarning("Invalid Method");
+ if (ok && state == State::ReadingUrl && !(ok = readUrl(m_socket)))
+ qWarning("Invalid URL");
+ if (ok && state == State::ReadingStatus && !(ok = readStatus(m_socket)))
+ qWarning("Invalid Status");
+ if (ok && state == State::ReadingHeader && !(ok = readHeaders(m_socket)))
+ qWarning("Invalid Header");
+ if (ok && state == State::ReadingBody && !(ok = readBody(m_socket)))
+ qWarning("Invalid Body");
+ } // while bytes available
+
+ Q_ASSERT(ok);
+ Q_ASSERT(m_handler);
+ Q_ASSERT(state == State::AllDone);
+
+ if (auto values = m_request.headers.values(
+ QHttpHeaders::WellKnownHeader::Host); !values.empty()) {
+ const auto parts = values.first().split(':');
+ m_request.url.setHost(parts.at(0));
+ if (parts.size() == 2)
+ m_request.url.setPort(parts.at(1).toUInt());
+ }
+ HttpData response;
+ ResponseControl control;
+ // Inform the testcase about request and ask for response data
+ m_handler(m_request, response, control);
+
+ QByteArray responseMessage;
+ responseMessage += "HTTP/1.1 ";
+ responseMessage += QByteArray::number(response.status);
+ responseMessage += CRLF;
+ // Insert headers if any
+ for (const auto &[name,value] : response.headers.toListOfPairs()) {
+ responseMessage += name;
+ responseMessage += ": ";
+ responseMessage += value;
+ responseMessage += CRLF;
+ }
+ responseMessage += CRLF;
+ /*
+ qDebug() << "HTTPTestServer received request"
+ << "\nMethod:" << m_request.method
+ << "\nHeaders:" << m_request.headers
+ << "\nBody:" << m_request.body;
+ */
+ if (control.respond) {
+ if (control.responseChunkSize <= 0) {
+ responseMessage += response.body;
+ // qDebug() << "HTTPTestServer response:" << responseMessage;
+ m_socket->write(responseMessage);
+ } else {
+ // Respond in chunks, first write the headers
+ // qDebug() << "HTTPTestServer response:" << responseMessage;
+ m_socket->write(responseMessage);
+ // Then write bodydata in chunks, while allowing the testcase to process as well
+ QByteArray chunk;
+ while (!response.body.isEmpty()) {
+ chunk = response.body.left(control.responseChunkSize);
+ response.body.remove(0, control.responseChunkSize);
+ // qDebug() << "SERVER writing chunk" << chunk;
+ m_socket->write(chunk);
+ m_socket->flush();
+ m_socket->waitForBytesWritten();
+ // Process events until testcase indicates it's ready for next chunk.
+ // This way we can control the bytes the testcase gets in each chunk
+ control.readyForNextChunk = false;
+ while (!control.readyForNextChunk)
+ QCoreApplication::processEvents();
+ }
+ }
+ }
+ m_socket->disconnectFromHost();
+ m_request = {};
+ m_socket = nullptr; // deleted by QTcpServer during destruction
+ state = State::ReadingMethod;
+ fragment.clear();
+}
+
+bool HttpTestServer::readMethod(QTcpSocket *socket)
+{
+ bool finished = false;
+ while (socket->bytesAvailable() && !finished) {
+ const auto c = socket->read(1).at(0);
+ if (ascii_isspace(c))
+ finished = true;
+ else if (std::isupper(c) && fragment.size() < 8)
+ fragment += c;
+ else
+ return false;
+ }
+ if (finished) {
+ if (fragment == "HEAD")
+ method = Method::Head;
+ else if (fragment == "GET")
+ method = Method::Get;
+ else if (fragment == "PUT")
+ method = Method::Put;
+ else if (fragment == "PATCH")
+ method = Method::Patch;
+ else if (fragment == "POST")
+ method = Method::Post;
+ else if (fragment == "DELETE")
+ method = Method::Delete;
+ else if (fragment == "FOOBAR") // used by custom verb/method tests
+ method = Method::Custom;
+ else
+ qWarning("Invalid operation %s", fragment.data());
+
+ state = State::ReadingUrl;
+ m_request.method = fragment;
+ fragment.clear();
+
+ return method != Method::Unknown;
+ }
+ return true;
+}
+
+bool HttpTestServer::readUrl(QTcpSocket *socket)
+{
+ bool finished = false;
+ while (socket->bytesAvailable() && !finished) {
+ const auto c = socket->read(1).at(0);
+ if (std::isspace(c))
+ finished = true;
+ else
+ fragment += c;
+ }
+ if (finished) {
+ if (!fragment.startsWith('/')) {
+ qWarning("Invalid URL path %s", fragment.constData());
+ return false;
+ }
+ m_request.url = QStringLiteral("http://127.0.0.1:") + QString::number(m_request.port) +
+ QString::fromUtf8(fragment);
+ state = State::ReadingStatus;
+ if (!m_request.url.isValid()) {
+ qWarning("Invalid URL %s", fragment.constData());
+ return false;
+ }
+ fragment.clear();
+ }
+ return true;
+}
+
+bool HttpTestServer::readStatus(QTcpSocket *socket)
+{
+ bool finished = false;
+ while (socket->bytesAvailable() && !finished) {
+ fragment += socket->read(1);
+ if (fragment.endsWith(CRLF)) {
+ finished = true;
+ fragment.resize(fragment.size() - 2);
+ }
+ }
+ if (finished) {
+ if (!std::isdigit(fragment.at(fragment.size() - 3)) ||
+ fragment.at(fragment.size() - 2) != '.' ||
+ !std::isdigit(fragment.at(fragment.size() - 1))) {
+ qWarning("Invalid version");
+ return false;
+ }
+ m_request.version = std::pair(fragment.at(fragment.size() - 3) - '0',
+ fragment.at(fragment.size() - 1) - '0');
+ state = State::ReadingHeader;
+ fragment.clear();
+ }
+ return true;
+}
+
+bool HttpTestServer::readHeaders(QTcpSocket *socket)
+{
+ while (socket->bytesAvailable()) {
+ fragment += socket->read(1);
+ if (fragment.endsWith(CRLF)) {
+ if (fragment == CRLF) {
+ state = State::ReadingBody;
+ fragment.clear();
+ return true;
+ } else {
+ fragment.chop(2);
+ const int index = fragment.indexOf(':');
+ if (index == -1)
+ return false;
+
+ QByteArray key = fragment.sliced(0, index).trimmed();
+ QByteArray value = fragment.sliced(index + 1).trimmed();
+ m_request.headers.append(key, value);
+ fragment.clear();
+ }
+ }
+ }
+ return true;
+}
+
+bool HttpTestServer::readBody(QTcpSocket *socket)
+{
+ qint64 bytesLeft = 0;
+ if (auto values = m_request.headers.values(
+ QHttpHeaders::WellKnownHeader::ContentLength); !values.empty()) {
+ bool conversionResult;
+ bytesLeft = values.first().toInt(&conversionResult);
+ if (!conversionResult)
+ return false;
+ fragment.resize(bytesLeft);
+ }
+ while (bytesLeft) {
+ qint64 got = socket->read(&fragment.data()[fragment.size() - bytesLeft], bytesLeft);
+ if (got < 0)
+ return false; // error
+ bytesLeft -= got;
+ if (bytesLeft)
+ qApp->processEvents();
+ }
+ fragment.swap(m_request.body);
+ state = State::AllDone;
+ return true;
+}
+
diff --git a/tests/auto/network/access/qrestaccessmanager/httptestserver_p.h b/tests/auto/network/access/qrestaccessmanager/httptestserver_p.h
new file mode 100644
index 0000000000..0a94b2c8a6
--- /dev/null
+++ b/tests/auto/network/access/qrestaccessmanager/httptestserver_p.h
@@ -0,0 +1,90 @@
+// Copyright (C) 2023 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
+
+#ifndef QRESTACCESSSMANAGER_HTTPTESTSERVER_P_H
+#define QRESTACCESSSMANAGER_HTTPTESTSERVER_P_H
+
+#include <QtNetwork/qtcpserver.h>
+#include <QtNetwork/qhttpheaders.h>
+
+#include <QtCore/qmap.h>
+#include <QtCore/qurl.h>
+
+#include <functional>
+
+// This struct is used for parsing the incoming network request data into, as well
+// as getting the response data from the testcase
+struct HttpData {
+ QUrl url;
+ int status = 0;
+ QByteArray body;
+ QByteArray method;
+ quint16 port = 0;
+ QPair<quint8, quint8> version;
+ QHttpHeaders headers;
+};
+
+struct ResponseControl
+{
+ bool respond = true;
+ qsizetype responseChunkSize = -1;
+ bool readyForNextChunk = true;
+};
+
+// Simple HTTP server. Currently supports only one concurrent connection
+class HttpTestServer : public QTcpServer
+{
+ Q_OBJECT
+
+public:
+ explicit HttpTestServer(QObject *parent = nullptr);
+ ~HttpTestServer() override;
+
+ // Returns this server's URL for the testcase to send requests to
+ QUrl url();
+
+ enum class State {
+ ReadingMethod,
+ ReadingUrl,
+ ReadingStatus,
+ ReadingHeader,
+ ReadingBody,
+ AllDone
+ } state = State::ReadingMethod;
+
+ enum class Method {
+ Unknown,
+ Head,
+ Get,
+ Put,
+ Patch,
+ Post,
+ Delete,
+ Custom,
+ } method = Method::Unknown;
+
+ // Parsing helpers for incoming data => HttpData
+ bool readMethod(QTcpSocket *socket);
+ bool readUrl(QTcpSocket *socket);
+ bool readStatus(QTcpSocket *socket);
+ bool readHeaders(QTcpSocket *socket);
+ bool readBody(QTcpSocket *socket);
+ // Parsing-time buffer in case data is received a small chunk at a time (readyRead())
+ QByteArray fragment;
+
+ // Settable callback for testcase. Gives the received request data, and takes in response data
+ using Handler = std::function<void(const HttpData &request, HttpData &response,
+ ResponseControl &control)>;
+ void setHandler(Handler handler) { m_handler = std::move(handler); }
+
+private slots:
+ void handleConnected();
+ void handleDataAvailable();
+
+private:
+ QTcpSocket *m_socket = nullptr;
+ HttpData m_request;
+ Handler m_handler = nullptr;
+};
+
+#endif // QRESTACCESSSMANAGER_HTTPTESTSERVER_P_H
diff --git a/tests/auto/network/access/qrestaccessmanager/tst_qrestaccessmanager.cpp b/tests/auto/network/access/qrestaccessmanager/tst_qrestaccessmanager.cpp
new file mode 100644
index 0000000000..814a9b27f4
--- /dev/null
+++ b/tests/auto/network/access/qrestaccessmanager/tst_qrestaccessmanager.cpp
@@ -0,0 +1,870 @@
+// Copyright (C) 2023 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
+
+#include "httptestserver_p.h"
+
+#include <QtNetwork/qhttpmultipart.h>
+#include <QtNetwork/qrestaccessmanager.h>
+#include <QtNetwork/qauthenticator.h>
+#include <QtNetwork/qnetworkreply.h>
+#include <QtNetwork/qnetworkrequestfactory.h>
+#include <QtNetwork/qrestreply.h>
+
+#include <QTest>
+#include <QtTest/qsignalspy.h>
+
+#include <QtCore/private/qglobal_p.h> // for access to Qt's feature system
+#include <QtCore/qbuffer.h>
+#include <QtCore/qjsonobject.h>
+#include <QtCore/qjsondocument.h>
+#include <QtCore/qjsonarray.h>
+#include <QtCore/qstringconverter.h>
+
+using namespace Qt::StringLiterals;
+using namespace std::chrono_literals;
+
+using Header = QHttpHeaders::WellKnownHeader;
+
+class tst_QRestAccessManager : public QObject
+{
+ Q_OBJECT
+
+private slots:
+ void initialization();
+ void destruction();
+ void callbacks();
+ void requests();
+ void reply();
+ void errors();
+ void body();
+ void json();
+ void text();
+ void textStreaming();
+
+private:
+ void memberHandler(QRestReply &reply);
+
+ friend class Transient;
+ QList<QNetworkReply*> m_expectedReplies;
+ QList<QNetworkReply*> m_actualReplies;
+};
+
+void tst_QRestAccessManager::initialization()
+{
+ QTest::ignoreMessage(QtMsgType::QtWarningMsg, "QRestAccessManager: QNetworkAccesManager is nullptr");
+ QRestAccessManager manager1(nullptr);
+ QVERIFY(!manager1.networkAccessManager());
+
+ QNetworkAccessManager qnam;
+ QRestAccessManager manager2(&qnam);
+ QVERIFY(manager2.networkAccessManager());
+}
+
+void tst_QRestAccessManager::reply()
+{
+ QNetworkAccessManager qnam;
+
+ QNetworkReply *nr = qnam.get(QNetworkRequest(QUrl{"someurl"}));
+ QRestReply rr1(nr);
+ QCOMPARE(rr1.networkReply(), nr);
+
+ // Move-construct
+ QRestReply rr2(std::move(rr1));
+ QCOMPARE(rr2.networkReply(), nr);
+
+ // Move-assign
+ QTest::ignoreMessage(QtMsgType::QtWarningMsg, "QRestReply: QNetworkReply is nullptr");
+ QRestReply rr3(nullptr);
+ rr3 = std::move(rr2);
+ QCOMPARE(rr3.networkReply(), nr);
+}
+
+#define VERIFY_REPLY_OK(METHOD) \
+{ \
+ QTRY_VERIFY(networkReply); \
+ QRestReply restReply(networkReply); \
+ QCOMPARE(serverSideRequest.method, METHOD); \
+ QVERIFY(restReply.isSuccess()); \
+ QVERIFY(!restReply.hasError()); \
+ networkReply->deleteLater(); \
+ networkReply = nullptr; \
+}
+
+void tst_QRestAccessManager::requests()
+{
+ // A basic test for each HTTP method against the local testserver.
+ QNetworkAccessManager qnam;
+ QRestAccessManager manager(&qnam);
+ HttpTestServer server;
+ QTRY_VERIFY(server.isListening());
+ QNetworkRequest request(server.url());
+ request.setRawHeader("Content-Type"_ba, "text/plain"); // To silence missing content-type warn
+ QNetworkReply *networkReply = nullptr;
+ std::unique_ptr<QHttpMultiPart> multiPart;
+ QHttpPart part;
+ part.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"text\""));
+ part.setBody("multipart_text");
+ QByteArray ioDeviceData{"io_device_data"_ba};
+ QBuffer bufferIoDevice(&ioDeviceData);
+
+ HttpData serverSideRequest; // The request data the server received
+ HttpData serverSideResponse; // The response data the server responds with
+ serverSideResponse.status = 200;
+ server.setHandler([&](const HttpData &request, HttpData &response, ResponseControl&) {
+ serverSideRequest = request;
+ response = serverSideResponse;
+
+ });
+ auto callback = [&](QRestReply &reply) { networkReply = reply.networkReply(); };
+ const QByteArray byteArrayData{"some_data"_ba};
+ const QJsonObject jsonObjectData{{"key1", "value1"}, {"key2", "value2"}};
+ const QJsonArray jsonArrayData{{"arrvalue1", "arrvalue2", QJsonObject{{"key1", "value1"}}}};
+ const QVariantMap variantMapData{{"key1", "value1"}, {"key2", "value2"}};
+ const QByteArray methodDELETE{"DELETE"_ba};
+ const QByteArray methodHEAD{"HEAD"_ba};
+ const QByteArray methodPOST{"POST"_ba};
+ const QByteArray methodGET{"GET"_ba};
+ const QByteArray methodPUT{"PUT"_ba};
+ const QByteArray methodPATCH{"PATCH"_ba};
+ const QByteArray methodCUSTOM{"FOOBAR"_ba};
+
+ // DELETE
+ manager.deleteResource(request, this, callback);
+ VERIFY_REPLY_OK(methodDELETE);
+ QCOMPARE(serverSideRequest.body, ""_ba);
+
+ // HEAD
+ manager.head(request, this, callback);
+ VERIFY_REPLY_OK(methodHEAD);
+ QCOMPARE(serverSideRequest.body, ""_ba);
+
+ // GET
+ manager.get(request, this, callback);
+ VERIFY_REPLY_OK(methodGET);
+ QCOMPARE(serverSideRequest.body, ""_ba);
+
+ manager.get(request, byteArrayData, this, callback);
+ VERIFY_REPLY_OK(methodGET);
+ QCOMPARE(serverSideRequest.body, byteArrayData);
+
+ manager.get(request, QJsonDocument{jsonObjectData}, this, callback);
+ VERIFY_REPLY_OK(methodGET);
+ QCOMPARE(QJsonDocument::fromJson(serverSideRequest.body).object(), jsonObjectData);
+
+ manager.get(request, &bufferIoDevice, this, callback);
+ VERIFY_REPLY_OK(methodGET);
+ QCOMPARE(serverSideRequest.body, ioDeviceData);
+
+ // CUSTOM
+ manager.sendCustomRequest(request, methodCUSTOM, byteArrayData, this, callback);
+ VERIFY_REPLY_OK(methodCUSTOM);
+ QCOMPARE(serverSideRequest.body, byteArrayData);
+
+ manager.sendCustomRequest(request, methodCUSTOM, &bufferIoDevice, this, callback);
+ VERIFY_REPLY_OK(methodCUSTOM);
+ QCOMPARE(serverSideRequest.body, ioDeviceData);
+
+ multiPart.reset(new QHttpMultiPart(QHttpMultiPart::FormDataType));
+ multiPart->append(part);
+ manager.sendCustomRequest(request, methodCUSTOM, multiPart.get(), this, callback);
+ VERIFY_REPLY_OK(methodCUSTOM);
+ QVERIFY(serverSideRequest.body.contains("--boundary"_ba));
+ QVERIFY(serverSideRequest.body.contains("multipart_text"_ba));
+
+ // POST
+ manager.post(request, byteArrayData, this, callback);
+ VERIFY_REPLY_OK(methodPOST);
+ QCOMPARE(serverSideRequest.body, byteArrayData);
+
+ manager.post(request, QJsonDocument{jsonObjectData}, this, callback);
+ VERIFY_REPLY_OK(methodPOST);
+ QCOMPARE(QJsonDocument::fromJson(serverSideRequest.body).object(), jsonObjectData);
+
+ manager.post(request, QJsonDocument{jsonArrayData}, this, callback);
+ VERIFY_REPLY_OK(methodPOST);
+ QCOMPARE(QJsonDocument::fromJson(serverSideRequest.body).array(), jsonArrayData);
+
+ manager.post(request, variantMapData, this, callback);
+ VERIFY_REPLY_OK(methodPOST);
+ QCOMPARE(QJsonDocument::fromJson(serverSideRequest.body).object(), jsonObjectData);
+
+ multiPart = std::make_unique<QHttpMultiPart>(QHttpMultiPart::FormDataType);
+ multiPart->append(part);
+ manager.post(request, multiPart.get(), this, callback);
+ VERIFY_REPLY_OK(methodPOST);
+ QVERIFY(serverSideRequest.body.contains("--boundary"_ba));
+ QVERIFY(serverSideRequest.body.contains("multipart_text"_ba));
+
+ manager.post(request, &bufferIoDevice, this, callback);
+ VERIFY_REPLY_OK(methodPOST);
+ QCOMPARE(serverSideRequest.body, ioDeviceData);
+
+ // PUT
+ manager.put(request, byteArrayData, this, callback);
+ VERIFY_REPLY_OK(methodPUT);
+ QCOMPARE(serverSideRequest.body, byteArrayData);
+
+ manager.put(request, QJsonDocument{jsonObjectData}, this, callback);
+ VERIFY_REPLY_OK(methodPUT);
+ QCOMPARE(QJsonDocument::fromJson(serverSideRequest.body).object(), jsonObjectData);
+
+ manager.put(request, QJsonDocument{jsonArrayData}, this, callback);
+ VERIFY_REPLY_OK(methodPUT);
+ QCOMPARE(QJsonDocument::fromJson(serverSideRequest.body).array(), jsonArrayData);
+
+ manager.put(request, variantMapData, this, callback);
+ VERIFY_REPLY_OK(methodPUT);
+ QCOMPARE(QJsonDocument::fromJson(serverSideRequest.body).object(), jsonObjectData);
+
+ multiPart = std::make_unique<QHttpMultiPart>(QHttpMultiPart::FormDataType);
+ multiPart->append(part);
+ manager.put(request, multiPart.get(), this, callback);
+ VERIFY_REPLY_OK(methodPUT);
+ QVERIFY(serverSideRequest.body.contains("--boundary"_ba));
+ QVERIFY(serverSideRequest.body.contains("multipart_text"_ba));
+
+ manager.put(request, &bufferIoDevice, this, callback);
+ VERIFY_REPLY_OK(methodPUT);
+ QCOMPARE(serverSideRequest.body, ioDeviceData);
+
+ // PATCH
+ manager.patch(request, byteArrayData, this, callback);
+ VERIFY_REPLY_OK(methodPATCH);
+ QCOMPARE(serverSideRequest.body, byteArrayData);
+
+ manager.patch(request, QJsonDocument{jsonObjectData}, this, callback);
+ VERIFY_REPLY_OK(methodPATCH);
+ QCOMPARE(QJsonDocument::fromJson(serverSideRequest.body).object(), jsonObjectData);
+
+ manager.patch(request, QJsonDocument{jsonArrayData}, this, callback);
+ VERIFY_REPLY_OK(methodPATCH);
+ QCOMPARE(QJsonDocument::fromJson(serverSideRequest.body).array(), jsonArrayData);
+
+ manager.patch(request, variantMapData, this, callback);
+ VERIFY_REPLY_OK(methodPATCH);
+ QCOMPARE(QJsonDocument::fromJson(serverSideRequest.body).object(), jsonObjectData);
+
+ manager.patch(request, &bufferIoDevice, this, callback);
+ VERIFY_REPLY_OK(methodPATCH);
+ QCOMPARE(serverSideRequest.body, ioDeviceData);
+
+ //These must NOT compile
+ //manager.get(request, [](){}); // callback without context object
+ //manager.get(request, ""_ba, [](){}); // callback without context object
+ //manager.get(request, QString()); // wrong datatype
+ //manager.get(request, 123); // wrong datatype
+ //manager.post(request, QString()); // wrong datatype
+ //manager.put(request, 123); // wrong datatype
+ //manager.post(request); // data is required
+ //manager.put(request, QString()); // wrong datatype
+ //manager.put(request); // data is required
+ //manager.patch(request, 123); // wrong datatype
+ //manager.patch(request, QString()); // wrong datatype
+ //manager.patch(request); // data is required
+ //manager.deleteResource(request, "f"_ba); // data not allowed
+ //manager.head(request, "f"_ba); // data not allowed
+ //manager.post(request, ""_ba, this, [](int param){}); // Wrong callback signature
+ //manager.get(request, this, [](int param){}); // Wrong callback signature
+ //manager.sendCustomRequest(request, this, [](){}); // No verb && no data
+ //manager.sendCustomRequest(request, "FOOBAR", this, [](){}); // No verb || no data
+}
+
+void tst_QRestAccessManager::memberHandler(QRestReply &reply)
+{
+ m_actualReplies.append(reply.networkReply());
+}
+
+// Class that is destroyed during an active request.
+// Used to test that the callbacks won't be called in these cases
+class Transient : public QObject
+{
+ Q_OBJECT
+public:
+ explicit Transient(tst_QRestAccessManager *test) : QObject(test), m_test(test) {}
+
+ void memberHandler(QRestReply &reply)
+ {
+ m_test->m_actualReplies.append(reply.networkReply());
+ }
+
+private:
+ tst_QRestAccessManager *m_test = nullptr;
+};
+
+template <typename Functor, std::enable_if_t<
+ QtPrivate::AreFunctionsCompatible<void(*)(QRestReply&), Functor>::value, bool> = true>
+inline constexpr bool isCompatibleCallback(Functor &&) { return true; }
+
+template <typename Functor, std::enable_if_t<
+ !QtPrivate::AreFunctionsCompatible<void(*)(QRestReply&), Functor>::value, bool> = true,
+ typename = void>
+inline constexpr bool isCompatibleCallback(Functor &&) { return false; }
+
+void tst_QRestAccessManager::callbacks()
+{
+ QNetworkAccessManager qnam;
+ QRestAccessManager manager(&qnam);
+
+ QNetworkRequest request{u"i_dont_exist"_s}; // Will result in ProtocolUnknown error
+
+ auto lambdaHandler = [this](QRestReply &reply) { m_actualReplies.append(reply.networkReply()); };
+ Transient *transient = nullptr;
+ QByteArray data{"some_data"};
+
+ // Compile-time tests for callback signatures
+ static_assert(isCompatibleCallback([](QRestReply&){})); // Correct signature
+ static_assert(isCompatibleCallback(lambdaHandler));
+ static_assert(isCompatibleCallback(&Transient::memberHandler));
+ static_assert(isCompatibleCallback([](){})); // Less parameters are allowed
+
+ static_assert(!isCompatibleCallback([](QString){})); // Wrong parameter type
+ static_assert(!isCompatibleCallback([](QRestReply*){})); // Wrong parameter type
+ static_assert(!isCompatibleCallback([](const QString &){})); // Wrong parameter type
+ static_assert(!isCompatibleCallback([](QRestReply&, QString){})); // Too many parameters
+
+ // -- Test without data
+ // Without callback using signals and slot
+ QNetworkReply* reply = manager.get(request);
+ m_expectedReplies.append(reply);
+ QObject::connect(reply, &QNetworkReply::finished, this,
+ [this, reply](){m_actualReplies.append(reply);});
+
+ // With lambda callback, without context object
+ m_expectedReplies.append(manager.get(request, nullptr, lambdaHandler));
+ m_expectedReplies.append(manager.get(request, nullptr,
+ [this](QRestReply &reply){m_actualReplies.append(reply.networkReply());}));
+ // With lambda callback and context object
+ m_expectedReplies.append(manager.get(request, this, lambdaHandler));
+ m_expectedReplies.append(manager.get(request, this,
+ [this](QRestReply &reply){m_actualReplies.append(reply.networkReply());}));
+ // With member callback and context object
+ m_expectedReplies.append(manager.get(request, this, &tst_QRestAccessManager::memberHandler));
+ // With context object that is destroyed, there should be no callback or eg. crash.
+ transient = new Transient(this);
+ manager.get(request, transient, &Transient::memberHandler); // Reply not added to expecteds
+ delete transient;
+
+ // Let requests finish
+ QTRY_COMPARE(m_actualReplies.size(), m_expectedReplies.size());
+ for (auto reply: m_actualReplies) {
+ QRestReply restReply(reply);
+ QVERIFY(!restReply.isSuccess());
+ QVERIFY(restReply.hasError());
+ QCOMPARE(restReply.error(), QNetworkReply::ProtocolUnknownError);
+ QCOMPARE(restReply.networkReply()->isFinished(), true);
+ restReply.networkReply()->deleteLater();
+ }
+ m_actualReplies.clear();
+ m_expectedReplies.clear();
+
+ // -- Test with data
+ // With lambda callback, without context object
+ m_expectedReplies.append(manager.post(request, data, nullptr, lambdaHandler));
+ m_expectedReplies.append(manager.post(request, data, nullptr,
+ [this](QRestReply &reply){m_actualReplies.append(reply.networkReply());}));
+ // With lambda callback and context object
+ m_expectedReplies.append(manager.post(request, data, this, lambdaHandler));
+ m_expectedReplies.append(manager.post(request, data, this,
+ [this](QRestReply &reply){m_actualReplies.append(reply.networkReply());}));
+ // With member callback and context object
+ m_expectedReplies.append(manager.post(request, data,
+ this, &tst_QRestAccessManager::memberHandler));
+ // With context object that is destroyed, there should be no callback or eg. crash
+ transient = new Transient(this);
+ manager.post(request, data, transient, &Transient::memberHandler); // Note: reply not expected
+ delete transient;
+
+ // Let requests finish
+ QTRY_COMPARE(m_actualReplies.size(), m_expectedReplies.size());
+ for (auto reply: m_actualReplies) {
+ QRestReply restReply(reply);
+ QVERIFY(!restReply.isSuccess());
+ QVERIFY(restReply.hasError());
+ QCOMPARE(restReply.error(), QNetworkReply::ProtocolUnknownError);
+ QCOMPARE(restReply.networkReply()->isFinished(), true);
+ reply->deleteLater();
+ }
+ m_actualReplies.clear();
+ m_expectedReplies.clear();
+
+ // -- Test GET with data separately, as GET provides methods that are usable with and
+ // without data, and fairly easy to get the qrestaccessmanager.h template SFINAE subtly wrong.
+ // With lambda callback, without context object
+ m_expectedReplies.append(manager.get(request, data, nullptr, lambdaHandler));
+ m_expectedReplies.append(manager.get(request, data, nullptr,
+ [this](QRestReply &reply){m_actualReplies.append(reply.networkReply());}));
+ // With lambda callback and context object
+ m_expectedReplies.append(manager.get(request, data, this, lambdaHandler));
+ m_expectedReplies.append(manager.get(request, data, this,
+ [this](QRestReply &reply){m_actualReplies.append(reply.networkReply());}));
+ // With member callback and context object
+ m_expectedReplies.append(manager.get(request, data,
+ this, &tst_QRestAccessManager::memberHandler));
+ // With context object that is destroyed, there should be no callback or eg. crash
+ transient = new Transient(this);
+ manager.get(request, data, transient, &Transient::memberHandler); // Reply not added
+ delete transient;
+
+ // Let requests finish
+ QTRY_COMPARE(m_actualReplies.size(), m_expectedReplies.size());
+ for (auto reply: m_actualReplies) {
+ QRestReply restReply(reply);
+ QVERIFY(!restReply.isSuccess());
+ QVERIFY(restReply.hasError());
+ QCOMPARE(restReply.error(), QNetworkReply::ProtocolUnknownError);
+ QCOMPARE(restReply.networkReply()->isFinished(), true);
+ restReply.networkReply()->deleteLater();
+ }
+ m_actualReplies.clear();
+ m_expectedReplies.clear();
+}
+
+void tst_QRestAccessManager::destruction()
+{
+ std::unique_ptr<QNetworkAccessManager> qnam = std::make_unique<QNetworkAccessManager>();
+ std::unique_ptr<QRestAccessManager> manager = std::make_unique<QRestAccessManager>(qnam.get());
+ QNetworkRequest request{u"i_dont_exist"_s}; // Will result in ProtocolUnknown error
+ m_expectedReplies.clear();
+ m_actualReplies.clear();
+ auto handler = [this](QRestReply &reply) { m_actualReplies.append(reply.networkReply()); };
+
+ // Delete reply immediately, make sure nothing bad happens and that there is no callback
+ QNetworkReply *networkReply = manager->get(request, this, handler);
+ delete networkReply;
+ QTest::qWait(20); // allow some time for the callback to arrive (it shouldn't)
+ QCOMPARE(m_actualReplies.size(), m_expectedReplies.size()); // Both should be 0
+
+ // Delete access manager immediately after request, make sure nothing bad happens
+ manager->get(request, this, handler);
+ manager->post(request, "data"_ba, this, handler);
+ QTest::ignoreMessage(QtWarningMsg, "Access manager destroyed while 2 requests were still"
+ " in progress");
+ manager.reset();
+ QTest::qWait(20);
+ QCOMPARE(m_actualReplies.size(), m_expectedReplies.size()); // Both should be 0
+
+ // Destroy the underlying QNAM while requests in progress
+ manager = std::make_unique<QRestAccessManager>(qnam.get());
+ manager->get(request, this, handler);
+ manager->post(request, "data"_ba, this, handler);
+ qnam.reset();
+ QTest::qWait(20);
+ QCOMPARE(m_actualReplies.size(), m_expectedReplies.size()); // Both should be 0
+}
+
+#define VERIFY_HTTP_ERROR_STATUS(STATUS) \
+{ \
+ serverSideResponse.status = STATUS; \
+ QRestReply restReply(manager.get(request)); \
+ QTRY_VERIFY(restReply.networkReply()->isFinished()); \
+ QVERIFY(!restReply.hasError()); \
+ QCOMPARE(restReply.httpStatus(), serverSideResponse.status); \
+ QCOMPARE(restReply.error(), QNetworkReply::NetworkError::NoError); \
+ QVERIFY(!restReply.isSuccess()); \
+ restReply.networkReply()->deleteLater(); \
+} \
+
+void tst_QRestAccessManager::errors()
+{
+ // Tests the distinction between HTTP and other (network/protocol) errors
+ QNetworkAccessManager qnam;
+ QRestAccessManager manager(&qnam);
+ HttpTestServer server;
+ QTRY_VERIFY(server.isListening());
+ QNetworkRequest request(server.url());
+
+ HttpData serverSideResponse; // The response data the server responds with
+ server.setHandler([&](const HttpData &, HttpData &response, ResponseControl &) {
+ response = serverSideResponse;
+ });
+
+ // Test few HTTP statuses in different categories
+ VERIFY_HTTP_ERROR_STATUS(301) // QNetworkReply::ProtocolUnknownError
+ VERIFY_HTTP_ERROR_STATUS(302) // QNetworkReply::ProtocolUnknownError
+ VERIFY_HTTP_ERROR_STATUS(400) // QNetworkReply::ProtocolInvalidOperationError
+ VERIFY_HTTP_ERROR_STATUS(401) // QNetworkReply::AuthenticationRequiredEror
+ VERIFY_HTTP_ERROR_STATUS(402) // QNetworkReply::UnknownContentError
+ VERIFY_HTTP_ERROR_STATUS(403) // QNetworkReply::ContentAccessDenied
+ VERIFY_HTTP_ERROR_STATUS(404) // QNetworkReply::ContentNotFoundError
+ VERIFY_HTTP_ERROR_STATUS(405) // QNetworkReply::ContentOperationNotPermittedError
+ VERIFY_HTTP_ERROR_STATUS(406) // QNetworkReply::UnknownContentError
+ VERIFY_HTTP_ERROR_STATUS(407) // QNetworkReply::ProxyAuthenticationRequiredError
+ VERIFY_HTTP_ERROR_STATUS(408) // QNetworkReply::UnknownContentError
+ VERIFY_HTTP_ERROR_STATUS(409) // QNetworkReply::ContentConflictError
+ VERIFY_HTTP_ERROR_STATUS(410) // QNetworkReply::ContentGoneError
+ VERIFY_HTTP_ERROR_STATUS(500) // QNetworkReply::InternalServerError
+ VERIFY_HTTP_ERROR_STATUS(501) // QNetworkReply::OperationNotImplementedError
+ VERIFY_HTTP_ERROR_STATUS(502) // QNetworkReply::UnknownServerError
+ VERIFY_HTTP_ERROR_STATUS(503) // QNetworkReply::ServiceUnavailableError
+ VERIFY_HTTP_ERROR_STATUS(504) // QNetworkReply::UnknownServerError
+ VERIFY_HTTP_ERROR_STATUS(505) // QNetworkReply::UnknownServerError
+
+ {
+ // Test that actual network/protocol errors come through
+ QRestReply restReply(manager.get({})); // Empty url
+ QTRY_VERIFY(restReply.networkReply()->isFinished());
+ QVERIFY(restReply.hasError());
+ QVERIFY(!restReply.isSuccess());
+ QCOMPARE(restReply.error(), QNetworkReply::ProtocolUnknownError);
+ restReply.networkReply()->deleteLater();
+ }
+
+ {
+ QRestReply restReply(manager.get(QNetworkRequest{{"http://non-existent.foo.bar.test"}}));
+ QTRY_VERIFY(restReply.networkReply()->isFinished());
+ QVERIFY(restReply.hasError());
+ QVERIFY(!restReply.isSuccess());
+ QCOMPARE(restReply.error(), QNetworkReply::HostNotFoundError);
+ restReply.networkReply()->deleteLater();
+ }
+
+ {
+ QRestReply restReply(manager.get(request));
+ restReply.networkReply()->abort();
+ QTRY_VERIFY(restReply.networkReply()->isFinished());
+ QVERIFY(restReply.hasError());
+ QVERIFY(!restReply.isSuccess());
+ QCOMPARE(restReply.error(), QNetworkReply::OperationCanceledError);
+ restReply.networkReply()->deleteLater();
+ }
+}
+
+void tst_QRestAccessManager::body()
+{
+ // Test using QRestReply::body() data accessor
+ QNetworkAccessManager qnam;
+ QRestAccessManager manager(&qnam);
+ HttpTestServer server;
+ QTRY_VERIFY(server.isListening());
+ QNetworkRequest request(server.url());
+ QNetworkReply *networkReply = nullptr;
+
+ HttpData serverSideRequest; // The request data the server received
+ HttpData serverSideResponse; // The response data the server responds with
+ server.setHandler([&](const HttpData &request, HttpData &response, ResponseControl&) {
+ serverSideRequest = request;
+ response = serverSideResponse;
+ });
+
+ {
+ serverSideResponse.status = 200;
+ serverSideResponse.body = "some_data"_ba;
+ manager.get(request, this, [&](QRestReply &reply) { networkReply = reply.networkReply(); });
+ QTRY_VERIFY(networkReply);
+ QRestReply restReply(networkReply);
+ QCOMPARE(restReply.readBody(), serverSideResponse.body);
+ QCOMPARE(restReply.httpStatus(), serverSideResponse.status);
+ QVERIFY(!restReply.hasError());
+ QVERIFY(restReply.isSuccess());
+ networkReply->deleteLater();
+ networkReply = nullptr;
+ }
+
+ {
+ serverSideResponse.status = 200;
+ serverSideResponse.body = ""_ba; // Empty
+ manager.get(request, this, [&](QRestReply &reply) { networkReply = reply.networkReply(); });
+ QTRY_VERIFY(networkReply);
+ QRestReply restReply(networkReply);
+ QCOMPARE(restReply.readBody(), serverSideResponse.body);
+ networkReply->deleteLater();
+ networkReply = nullptr;
+ }
+
+ {
+ serverSideResponse.status = 500;
+ serverSideResponse.body = "some_other_data"_ba;
+ manager.get(request, this, [&](QRestReply &reply) { networkReply = reply.networkReply(); });
+ QTRY_VERIFY(networkReply);
+ QRestReply restReply(networkReply);
+ QCOMPARE(restReply.readBody(), serverSideResponse.body);
+ QCOMPARE(restReply.httpStatus(), serverSideResponse.status);
+ QVERIFY(!restReply.hasError());
+ QVERIFY(!restReply.isSuccess());
+ networkReply->deleteLater();
+ networkReply = nullptr;
+ }
+}
+
+void tst_QRestAccessManager::json()
+{
+ // Tests using QRestReply::readJson()
+ QNetworkAccessManager qnam;
+ QRestAccessManager manager(&qnam);
+ HttpTestServer server;
+ QTRY_VERIFY(server.isListening());
+ QNetworkRequest request(server.url());
+ QNetworkReply *networkReply = nullptr;
+ QJsonDocument responseJsonDocument;
+ std::optional<QJsonDocument> json;
+ QJsonParseError parseError;
+
+ HttpData serverSideRequest; // The request data the server received
+ HttpData serverSideResponse; // The response data the server responds with
+ serverSideResponse.status = 200;
+ server.setHandler([&](const HttpData &request, HttpData &response, ResponseControl&) {
+ serverSideRequest = request;
+ response = serverSideResponse;
+ });
+
+ {
+ // Test receiving valid json object
+ serverSideResponse.body = "{\"key1\":\"value1\",""\"key2\":\"value2\"}\n"_ba;
+ networkReply = manager.get(request);
+ // Read unfinished reply
+ QVERIFY(!networkReply->isFinished());
+ QTest::ignoreMessage(QtWarningMsg, "readJson() called on an unfinished reply, ignoring");
+ parseError.error = QJsonParseError::ParseError::DocumentTooLarge; // Reset to impossible value
+ QRestReply restReply(networkReply);
+ QVERIFY(!restReply.readJson(&parseError));
+ QCOMPARE(parseError.error, QJsonParseError::ParseError::NoError);
+ // Read finished reply
+ QTRY_VERIFY(networkReply->isFinished());
+ parseError.error = QJsonParseError::ParseError::DocumentTooLarge;
+ json = restReply.readJson(&parseError);
+ QVERIFY(json);
+ QCOMPARE(parseError.error, QJsonParseError::ParseError::NoError);
+ responseJsonDocument = *json;
+ QVERIFY(responseJsonDocument.isObject());
+ QCOMPARE(responseJsonDocument["key1"], "value1");
+ QCOMPARE(responseJsonDocument["key2"], "value2");
+ networkReply->deleteLater();
+ networkReply = nullptr;
+ }
+
+ {
+ // Test receiving an invalid json object
+ serverSideResponse.body = "foobar"_ba;
+ manager.get(request, this, [&](QRestReply &reply) { networkReply = reply.networkReply(); });
+ QTRY_VERIFY(networkReply);
+ QRestReply restReply(networkReply);
+ parseError.error = QJsonParseError::ParseError::DocumentTooLarge;
+ const auto json = restReply.readJson(&parseError);
+ networkReply->deleteLater();
+ networkReply = nullptr;
+ QCOMPARE_EQ(json, std::nullopt);
+ QCOMPARE_NE(parseError.error, QJsonParseError::ParseError::NoError);
+ QCOMPARE_NE(parseError.error, QJsonParseError::ParseError::DocumentTooLarge);
+ QCOMPARE_GT(parseError.offset, 0);
+ }
+
+ {
+ // Test receiving valid json array
+ serverSideResponse.body = "[\"foo\", \"bar\"]\n"_ba;
+ manager.get(request, this, [&](QRestReply &reply) { networkReply = reply.networkReply(); });
+ QTRY_VERIFY(networkReply);
+ QRestReply restReply(networkReply);
+ parseError.error = QJsonParseError::ParseError::DocumentTooLarge;
+ json = restReply.readJson(&parseError);
+ networkReply->deleteLater();
+ networkReply = nullptr;
+ QCOMPARE(parseError.error, QJsonParseError::ParseError::NoError);
+ QVERIFY(json);
+ responseJsonDocument = *json;
+ QVERIFY(responseJsonDocument.isArray());
+ QCOMPARE(responseJsonDocument.array().size(), 2);
+ QCOMPARE(responseJsonDocument[0].toString(), "foo"_L1);
+ QCOMPARE(responseJsonDocument[1].toString(), "bar"_L1);
+ }
+}
+
+#define VERIFY_TEXT_REPLY_OK \
+{ \
+ manager.get(request, this, [&](QRestReply &reply) { networkReply = reply.networkReply(); }); \
+ QTRY_VERIFY(networkReply); \
+ QRestReply restReply(networkReply); \
+ responseString = restReply.readText(); \
+ networkReply->deleteLater(); \
+ networkReply = nullptr; \
+ QCOMPARE(responseString, sourceString); \
+}
+
+#define VERIFY_TEXT_REPLY_ERROR(WARNING_MESSAGE) \
+{ \
+ manager.get(request, this, [&](QRestReply &reply) { networkReply = reply.networkReply(); }); \
+ QTRY_VERIFY(networkReply); \
+ QTest::ignoreMessage(QtWarningMsg, WARNING_MESSAGE); \
+ QRestReply restReply(networkReply); \
+ responseString = restReply.readText(); \
+ networkReply->deleteLater(); \
+ networkReply = nullptr; \
+ QVERIFY(responseString.isEmpty()); \
+}
+
+void tst_QRestAccessManager::text()
+{
+ // Test using QRestReply::text() data accessor with various text encodings
+ QNetworkAccessManager qnam;
+ QRestAccessManager manager(&qnam);
+ HttpTestServer server;
+ QTRY_VERIFY(server.isListening());
+ QNetworkRequest request(server.url());
+ QNetworkReply *networkReply = nullptr;
+ QJsonObject responseJsonObject;
+
+ QStringEncoder encUTF8("UTF-8");
+ QStringEncoder encUTF16("UTF-16");
+ QStringEncoder encUTF32("UTF-32");
+ QString responseString;
+
+ HttpData serverSideRequest; // The request data the server received
+ HttpData serverSideResponse; // The response data the server responds with
+ serverSideResponse.status = 200;
+ server.setHandler([&](const HttpData &request, HttpData &response, ResponseControl&) {
+ serverSideRequest = request;
+ response = serverSideResponse;
+ });
+
+ const QString sourceString("this is a string"_L1);
+
+ // Charset parameter of Content-Type header may specify non-UTF-8 character encoding.
+ //
+ // QString is UTF-16, and in the tests below we encode the response data to various
+ // charset encodings (into byte arrays). When we get the response data, the text()
+ // should consider the indicated charset and convert it to an UTF-16 QString => the returned
+ // QString from text() should match with the original (UTF-16) QString.
+
+ // Successful UTF-8 (explicit)
+ serverSideResponse.headers.append(Header::ContentType, "text/plain; charset=UTF-8"_ba);
+ serverSideResponse.body = encUTF8(sourceString);
+ VERIFY_TEXT_REPLY_OK;
+
+ // Successful UTF-8 (obfuscated)
+ serverSideResponse.headers.removeAll(Header::ContentType);
+ serverSideResponse.headers.append(Header::ContentType, "text/plain; charset=\"UT\\F-8\""_ba);
+ serverSideResponse.body = encUTF8(sourceString);
+ VERIFY_TEXT_REPLY_OK;
+
+ // Successful UTF-8 (empty charset)
+ serverSideResponse.headers.removeAll(Header::ContentType);
+ serverSideResponse.headers.append(Header::ContentType, "text/plain; charset=\"\""_ba);
+ serverSideResponse.body = encUTF8(sourceString);
+ VERIFY_TEXT_REPLY_OK;
+
+ // Successful UTF-8 (implicit)
+ serverSideResponse.headers.removeAll(Header::ContentType);
+ serverSideResponse.headers.append(Header::ContentType, "text/plain"_ba);
+ serverSideResponse.body = encUTF8(sourceString);
+ VERIFY_TEXT_REPLY_OK;
+
+ // Successful UTF-16
+ serverSideResponse.headers.removeAll(Header::ContentType);
+ serverSideResponse.headers.append(Header::ContentType, "text/plain; charset=UTF-16"_ba);
+ serverSideResponse.body = encUTF16(sourceString);
+ VERIFY_TEXT_REPLY_OK;
+
+ // Successful UTF-16, parameter case insensitivity
+ serverSideResponse.headers.removeAll(Header::ContentType);
+ serverSideResponse.headers.append(Header::ContentType, "text/plain; chARset=uTf-16"_ba);
+ serverSideResponse.body = encUTF16(sourceString);
+ VERIFY_TEXT_REPLY_OK;
+
+ // Successful UTF-32
+ serverSideResponse.headers.removeAll(Header::ContentType);
+ serverSideResponse.headers.append(Header::ContentType, "text/plain; charset=UTF-32"_ba);
+ serverSideResponse.body = encUTF32(sourceString);
+ VERIFY_TEXT_REPLY_OK;
+
+ // Successful UTF-32 with spec-wise allowed extra trailing content in the Content-Type header value
+ serverSideResponse.headers.removeAll(Header::ContentType);
+ serverSideResponse.headers.append(Header::ContentType,
+ "text/plain; charset = \"UTF-32\";extraparameter=bar"_ba);
+ serverSideResponse.body = encUTF32(sourceString);
+ VERIFY_TEXT_REPLY_OK;
+
+ // Successful UTF-32 with spec-wise allowed extra leading content in the Content-Type header value
+ serverSideResponse.headers.removeAll(Header::ContentType);
+ serverSideResponse.headers.append(Header::ContentType,
+ "text/plain; extraparameter=bar;charset = \"UT\\F-32\""_ba);
+ serverSideResponse.body = encUTF32(sourceString);
+ VERIFY_TEXT_REPLY_OK;
+
+ {
+ // Unsuccessful UTF-32, wrong encoding indicated (indicated UTF-32 but data is UTF-8)
+ serverSideResponse.headers.removeAll(Header::ContentType);
+ serverSideResponse.headers.append(Header::ContentType, "text/plain; charset=UTF-32"_ba);
+ serverSideResponse.body = encUTF8(sourceString);
+ manager.get(request, this, [&](QRestReply &reply) { networkReply = reply.networkReply(); });
+ QTRY_VERIFY(networkReply);
+ QRestReply restReply(networkReply);
+ responseString = restReply.readText();
+ QCOMPARE_NE(responseString, sourceString);
+ networkReply->deleteLater();
+ networkReply = nullptr;
+ }
+
+ // Unsupported encoding
+ serverSideResponse.headers.removeAll(Header::ContentType);
+ serverSideResponse.headers.append(Header::ContentType, "text/plain; charset=foo"_ba);
+ serverSideResponse.body = encUTF8(sourceString);
+ VERIFY_TEXT_REPLY_ERROR("readText(): Charset \"foo\" is not supported")
+
+ // Broken UTF-8
+ serverSideResponse.headers.removeAll(Header::ContentType);
+ serverSideResponse.headers.append(Header::ContentType, "text/plain; charset=UTF-8"_ba);
+ serverSideResponse.body = "\xF0\x28\x8C\x28\xA0\xB0\xC0\xD0"; // invalid characters
+ VERIFY_TEXT_REPLY_ERROR("readText(): Decoding error occurred");
+}
+
+void tst_QRestAccessManager::textStreaming()
+{
+ // Tests textual data received in chunks
+ QNetworkAccessManager qnam;
+ QRestAccessManager manager(&qnam);
+ HttpTestServer server;
+ QTRY_VERIFY(server.isListening());
+ QNetworkRequest request(server.url());
+
+ // Create long text data
+ const QString expectedData = u"사랑abcd€fghiklmnΩpqrstuvwx愛사랑A사랑BCD€FGHIJKLMNΩPQRsTUVWXYZ愛"_s;
+ QString cumulativeReceivedText;
+ QStringEncoder encUTF8("UTF-8");
+ ResponseControl *responseControl = nullptr;
+
+ HttpData serverSideResponse; // The response data the server responds with
+ serverSideResponse.headers.removeAll(Header::ContentType);
+ serverSideResponse.headers.append(Header::ContentType, "text/plain; charset=UTF-8"_ba);
+ serverSideResponse.body = encUTF8(expectedData);
+ serverSideResponse.status = 200;
+
+ server.setHandler([&](const HttpData &, HttpData &response, ResponseControl &control) {
+ response = serverSideResponse;
+ responseControl = &control; // store for later
+ control.responseChunkSize = 5; // tell testserver to send data in chunks of this size
+ });
+
+ {
+ QRestReply restReply(manager.get(request));
+ QObject::connect(restReply.networkReply(), &QNetworkReply::readyRead, this, [&]() {
+ cumulativeReceivedText += restReply.readText();
+ // Tell testserver that test is ready for next chunk
+ responseControl->readyForNextChunk = true;
+ });
+ QTRY_VERIFY(restReply.networkReply()->isFinished());
+ QCOMPARE(cumulativeReceivedText, expectedData);
+ restReply.networkReply()->deleteLater();
+ }
+
+ {
+ cumulativeReceivedText.clear();
+ // Broken UTF-8 characters after first five ok characters
+ serverSideResponse.body =
+ "12345"_ba + "\xF0\x28\x8C\x28\xA0\xB0\xC0\xD0" + "abcde"_ba;
+ QRestReply restReply(manager.get(request));
+ QObject::connect(restReply.networkReply(), &QNetworkReply::readyRead, this, [&]() {
+ static bool firstTime = true;
+ if (!firstTime) // First text part is without warnings
+ QTest::ignoreMessage(QtWarningMsg, "readText(): Decoding error occurred");
+ firstTime = false;
+ cumulativeReceivedText += restReply.readText();
+ // Tell testserver that test is ready for next chunk
+ responseControl->readyForNextChunk = true;
+ });
+ QTRY_VERIFY(restReply.networkReply()->isFinished());
+ QCOMPARE(cumulativeReceivedText, "12345"_ba);
+ restReply.networkReply()->deleteLater();
+ }
+}
+
+QTEST_MAIN(tst_QRestAccessManager)
+#include "tst_qrestaccessmanager.moc"
diff --git a/tests/auto/network/kernel/CMakeLists.txt b/tests/auto/network/kernel/CMakeLists.txt
index c7b0d0dfeb..b42a9724b3 100644
--- a/tests/auto/network/kernel/CMakeLists.txt
+++ b/tests/auto/network/kernel/CMakeLists.txt
@@ -1,11 +1,15 @@
-# Generated from kernel.pro.
-if(NOT INTEGRITY)
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
+
+if(QT_FEATURE_dnslookup AND (QT_FEATURE_libresolv OR WIN32))
add_subdirectory(qdnslookup)
add_subdirectory(qdnslookup_appless)
endif()
-add_subdirectory(qnetworkproxyfactory)
+if(QT_FEATURE_networkinterface)
+ add_subdirectory(qnetworkproxyfactory)
+ add_subdirectory(qnetworkinterface)
+endif()
add_subdirectory(qnetworkproxy)
-add_subdirectory(qnetworkinterface)
add_subdirectory(qnetworkdatagram)
add_subdirectory(qnetworkaddressentry)
add_subdirectory(qhostaddress)
diff --git a/tests/auto/network/kernel/qauthenticator/CMakeLists.txt b/tests/auto/network/kernel/qauthenticator/CMakeLists.txt
index d772fe0e28..552e9065ed 100644
--- a/tests/auto/network/kernel/qauthenticator/CMakeLists.txt
+++ b/tests/auto/network/kernel/qauthenticator/CMakeLists.txt
@@ -1,4 +1,11 @@
-# Generated from qauthenticator.pro.
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
+
+if(NOT QT_BUILD_STANDALONE_TESTS AND NOT QT_BUILDING_QT)
+ cmake_minimum_required(VERSION 3.16)
+ project(tst_qauthenticator LANGUAGES CXX)
+ find_package(Qt6BuildInternals REQUIRED COMPONENTS STANDALONE_TEST)
+endif()
if(NOT QT_FEATURE_private_tests)
return()
@@ -11,9 +18,6 @@ endif()
qt_internal_add_test(tst_qauthenticator
SOURCES
tst_qauthenticator.cpp
- PUBLIC_LIBRARIES
+ LIBRARIES
Qt::NetworkPrivate
)
-
-#### Keys ignored in scope 1:.:.:qauthenticator.pro:<TRUE>:
-# _REQUIREMENTS = "qtConfig(private_tests)"
diff --git a/tests/auto/network/kernel/qauthenticator/tst_qauthenticator.cpp b/tests/auto/network/kernel/qauthenticator/tst_qauthenticator.cpp
index 8e573d7ded..1cd1b6a63b 100644
--- a/tests/auto/network/kernel/qauthenticator/tst_qauthenticator.cpp
+++ b/tests/auto/network/kernel/qauthenticator/tst_qauthenticator.cpp
@@ -1,36 +1,12 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the FOO module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
#include <QtCore/QString>
#include <QTest>
#include <QtCore/QCoreApplication>
#include <QtNetwork/QAuthenticator>
+#include <QtNetwork/QHttpHeaders>
#include <private/qauthenticator_p.h>
@@ -85,8 +61,8 @@ void tst_QAuthenticator::basicAuth()
QAuthenticatorPrivate *priv = QAuthenticatorPrivate::getPrivate(auth);
QCOMPARE(priv->phase, QAuthenticatorPrivate::Start);
- QList<QPair<QByteArray, QByteArray> > headers;
- headers << qMakePair(QByteArray("WWW-Authenticate"), "Basic " + data.toUtf8());
+ QHttpHeaders headers;
+ headers.append(QByteArray("WWW-Authenticate"), "Basic " + data.toUtf8());
priv->parseHttpResponse(headers, /*isProxy = */ false, {});
QCOMPARE(auth.realm(), realm);
@@ -97,7 +73,7 @@ void tst_QAuthenticator::basicAuth()
QCOMPARE(priv->phase, QAuthenticatorPrivate::Start);
- QCOMPARE(priv->calculateResponse("GET", "/", "").constData(), QByteArray("Basic " + expectedReply).constData());
+ QCOMPARE(priv->calculateResponse("GET", "/", u"").constData(), QByteArray("Basic " + expectedReply).constData());
}
void tst_QAuthenticator::ntlmAuth_data()
@@ -128,29 +104,29 @@ void tst_QAuthenticator::ntlmAuth()
QAuthenticatorPrivate *priv = QAuthenticatorPrivate::getPrivate(auth);
QCOMPARE(priv->phase, QAuthenticatorPrivate::Start);
- QList<QPair<QByteArray, QByteArray> > headers;
+ QHttpHeaders headers;
// NTLM phase 1: negotiate
// This phase of NTLM contains no information, other than what we're willing to negotiate
// Current implementation uses flags:
// NTLMSSP_NEGOTIATE_UNICODE | NTLMSSP_NEGOTIATE_NTLM | NTLMSSP_REQUEST_TARGET
- headers << qMakePair(QByteArrayLiteral("WWW-Authenticate"), QByteArrayLiteral("NTLM"));
+ headers.append(QByteArrayLiteral("WWW-Authenticate"), QByteArrayLiteral("NTLM"));
priv->parseHttpResponse(headers, /*isProxy = */ false, {});
if (sso)
- QVERIFY(priv->calculateResponse("GET", "/", "").startsWith("NTLM "));
+ QVERIFY(priv->calculateResponse("GET", "/", u"").startsWith("NTLM "));
else
- QCOMPARE(priv->calculateResponse("GET", "/", "").constData(), "NTLM TlRMTVNTUAABAAAABYIIAAAAAAAAAAAAAAAAAAAAAAA=");
+ QCOMPARE(priv->calculateResponse("GET", "/", u"").constData(), "NTLM TlRMTVNTUAABAAAABYIIAAAAAAAAAAAAAAAAAAAAAAA=");
// NTLM phase 2: challenge
headers.clear();
- headers << qMakePair(QByteArray("WWW-Authenticate"), "NTLM " + data.toUtf8());
+ headers.append(QByteArray("WWW-Authenticate"), "NTLM " + data.toUtf8());
priv->parseHttpResponse(headers, /*isProxy = */ false, {});
QEXPECT_FAIL("with-realm", "NTLM authentication code doesn't extract the realm", Continue);
QEXPECT_FAIL("with-realm-sso", "NTLM authentication code doesn't extract the realm", Continue);
QCOMPARE(auth.realm(), realm);
- QVERIFY(priv->calculateResponse("GET", "/", "").startsWith("NTLM "));
+ QVERIFY(priv->calculateResponse("GET", "/", u"").startsWith("NTLM "));
}
// We don't (currently) support SHA256. So, when presented with the option of MD5 or SHA256,
@@ -168,10 +144,10 @@ void tst_QAuthenticator::sha256AndMd5Digest()
QVERIFY(priv->isMethodSupported("digest")); // sanity check
QCOMPARE(priv->phase, QAuthenticatorPrivate::Start);
- QList<QPair<QByteArray, QByteArray>> headers;
+ QHttpHeaders headers;
// Put sha256 first, so that its parsed first...
- headers.emplace_back("WWW-Authenticate", sha256);
- headers.emplace_back("WWW-Authenticate", md5);
+ headers.append("WWW-Authenticate", sha256);
+ headers.append("WWW-Authenticate", md5);
priv->parseHttpResponse(headers, false, QString());
QByteArray response = priv->calculateResponse("GET", "/index", {});
diff --git a/tests/auto/network/kernel/qdnslookup/BLACKLIST b/tests/auto/network/kernel/qdnslookup/BLACKLIST
deleted file mode 100644
index f07a8ce9a3..0000000000
--- a/tests/auto/network/kernel/qdnslookup/BLACKLIST
+++ /dev/null
@@ -1,2 +0,0 @@
-[lookup]
-*
diff --git a/tests/auto/network/kernel/qdnslookup/CMakeLists.txt b/tests/auto/network/kernel/qdnslookup/CMakeLists.txt
index b039b4e91b..ea539ecbe0 100644
--- a/tests/auto/network/kernel/qdnslookup/CMakeLists.txt
+++ b/tests/auto/network/kernel/qdnslookup/CMakeLists.txt
@@ -1,12 +1,25 @@
-# Generated from qdnslookup.pro.
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
#####################################################################
## tst_qdnslookup Test:
#####################################################################
+if(NOT QT_BUILD_STANDALONE_TESTS AND NOT QT_BUILDING_QT)
+ cmake_minimum_required(VERSION 3.16)
+ project(tst_qdnslookup LANGUAGES CXX)
+ find_package(Qt6BuildInternals REQUIRED COMPONENTS STANDALONE_TEST)
+endif()
+
qt_internal_add_test(tst_qdnslookup
SOURCES
tst_qdnslookup.cpp
- PUBLIC_LIBRARIES
+ LIBRARIES
Qt::Network
+ Qt::TestPrivate
+)
+
+qt_internal_extend_target(tst_qdnslookup CONDITION WIN32
+ LIBRARIES
+ iphlpapi
)
diff --git a/tests/auto/network/kernel/qdnslookup/tst_qdnslookup.cpp b/tests/auto/network/kernel/qdnslookup/tst_qdnslookup.cpp
index f462330fdf..f71e94862c 100644
--- a/tests/auto/network/kernel/qdnslookup/tst_qdnslookup.cpp
+++ b/tests/auto/network/kernel/qdnslookup/tst_qdnslookup.cpp
@@ -1,64 +1,186 @@
-/****************************************************************************
-**
-** Copyright (C) 2012 Jeremy Lainé <jeremy.laine@m4x.org>
-** Copyright (C) 2016 Intel Corporation.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
+// Copyright (C) 2012 Jeremy Lainé <jeremy.laine@m4x.org>
+// Copyright (C) 2016 Intel Corporation.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
#include <QTest>
#include <QSignalSpy>
+#include <QtTest/private/qpropertytesthelper_p.h>
#include <QtNetwork/QDnsLookup>
+
+#include <QtCore/QRandomGenerator>
#include <QtNetwork/QHostAddress>
+#include <QtNetwork/QNetworkDatagram>
+#include <QtNetwork/QUdpSocket>
+
+#ifdef Q_OS_UNIX
+# include <QtCore/QFile>
+#else
+# include <winsock2.h>
+# include <iphlpapi.h>
+#endif
+using namespace Qt::StringLiterals;
static const int Timeout = 15000; // 15s
class tst_QDnsLookup: public QObject
{
Q_OBJECT
+ const QString normalDomain = u".test.qt-project.org"_s;
+ const QString idnDomain = u".alqualondë.test.qt-project.org"_s;
+ bool usingIdnDomain = false;
+ bool dnsServersMustWork = false;
+
QString domainName(const QString &input);
QString domainNameList(const QString &input);
QStringList domainNameListAlternatives(const QString &input);
+
+ std::unique_ptr<QDnsLookup> lookupCommon(QDnsLookup::Type type, const QString &domain,
+ const QHostAddress &server = {}, quint16 port = 53);
+ QStringList formatReply(const QDnsLookup *lookup) const;
public slots:
void initTestCase();
private slots:
+ void lookupLocalhost();
+ void lookupRoot();
+ void lookupNxDomain_data();
+ void lookupNxDomain();
void lookup_data();
void lookup();
+ void lookupIdn_data() { lookup_data(); }
+ void lookupIdn();
+
void lookupReuse();
void lookupAbortRetry();
+ void setNameserverLoopback();
+ void setNameserver_data();
+ void setNameserver();
void bindingsAndProperties();
+ void automatedBindings();
};
+static constexpr qsizetype HeaderSize = 6 * sizeof(quint16);
+static const char preparedDnsQuery[] =
+ // header
+ "\x00\x00" // transaction ID, we'll replace
+ "\x01\x20" // flags
+ "\x00\x01" // qdcount
+ "\x00\x00" // ancount
+ "\x00\x00" // nscount
+ "\x00\x00" // arcount
+ // query:
+ "\x00\x00\x06\x00\x01" // <root domain> IN SOA
+ ;
+
+static QList<QHostAddress> systemNameservers()
+{
+ QList<QHostAddress> result;
+
+#ifdef Q_OS_WIN
+ ULONG infosize = 0;
+ DWORD r = GetNetworkParams(nullptr, &infosize);
+ auto buffer = std::make_unique<uchar[]>(infosize);
+ auto info = new (buffer.get()) FIXED_INFO;
+ r = GetNetworkParams(info, &infosize);
+ if (r == NO_ERROR) {
+ for (PIP_ADDR_STRING ptr = &info->DnsServerList; ptr; ptr = ptr->Next) {
+ QLatin1StringView addr(ptr->IpAddress.String);
+ result.emplaceBack(addr);
+ }
+ }
+#else
+ auto parseFile = [&](QLatin1StringView path) {
+ QFile f(path);
+ if (!f.open(QIODevice::ReadOnly))
+ return;
+
+ while (!f.atEnd()) {
+ static const char command[] = "nameserver";
+ QByteArray line = f.readLine().simplified();
+ if (!line.startsWith(command))
+ continue;
+
+ QString addr = QLatin1StringView(line).mid(sizeof(command));
+ result.emplaceBack(addr);
+ }
+ };
+ parseFile("/etc/resolv.conf"_L1);
+ parseFile("/run/systemd/resolve/resolv.conf"_L1);
+#endif
+
+ return result;
+}
+
+static QList<QHostAddress> globalPublicNameservers()
+{
+ const char *const candidates[] = {
+ // Google's dns.google
+ "8.8.8.8", "2001:4860:4860::8888",
+ //"8.8.4.4", "2001:4860:4860::8844",
+
+ // CloudFare's one.one.one.one
+ "1.1.1.1", "2606:4700:4700::1111",
+ //"1.0.0.1", "2606:4700:4700::1001",
+
+ // Quad9's dns9
+ //"9.9.9.9", "2620:fe::9",
+ };
+
+ QList<QHostAddress> result;
+ QRandomGenerator &rng = *QRandomGenerator::system();
+ for (auto name : candidates) {
+ // check the candidates for reachability
+ QHostAddress addr{QLatin1StringView(name)};
+ quint16 id = quint16(rng());
+ QByteArray data(preparedDnsQuery, sizeof(preparedDnsQuery));
+ char *ptr = data.data();
+ qToBigEndian(id, ptr);
+
+ QUdpSocket socket;
+ socket.connectToHost(addr, 53);
+ if (socket.waitForConnected(1))
+ socket.write(data);
+
+ if (!socket.waitForReadyRead(1000)) {
+ qDebug() << addr << "discarded:" << socket.errorString();
+ continue;
+ }
+
+ QNetworkDatagram dgram = socket.receiveDatagram();
+ if (!dgram.isValid()) {
+ qDebug() << addr << "discarded:" << socket.errorString();
+ continue;
+ }
+
+ data = dgram.data();
+ ptr = data.data();
+ if (data.size() < HeaderSize) {
+ qDebug() << addr << "discarded: reply too small";
+ continue;
+ }
+
+ bool ok = qFromBigEndian<quint16>(ptr) == id
+ && (ptr[2] & 0x80) // is a reply
+ && (ptr[3] & 0xf) == 0 // rcode NOERROR
+ && qFromBigEndian<quint16>(ptr + 4) == 1 // qdcount
+ && qFromBigEndian<quint16>(ptr + 6) >= 1; // ancount
+ if (!ok) {
+ qDebug() << addr << "discarded: invalid reply";
+ continue;
+ }
+
+ result.emplaceBack(std::move(addr));
+ }
+
+ return result;
+}
+
void tst_QDnsLookup::initTestCase()
{
- QTest::addColumn<QString>("tld");
- QTest::newRow("normal") << ".test.qt-project.org";
- QTest::newRow("idn") << ".alqualond\xc3\xab.test.qt-project.org";
+ if (qgetenv("QTEST_ENVIRONMENT") == "ci")
+ dnsServersMustWork = true;
}
QString tst_QDnsLookup::domainName(const QString &input)
@@ -72,15 +194,16 @@ QString tst_QDnsLookup::domainName(const QString &input)
return nodot;
}
- QFETCH_GLOBAL(QString, tld);
- return input + tld;
+ if (usingIdnDomain)
+ return input + idnDomain;
+ return input + normalDomain;
}
QString tst_QDnsLookup::domainNameList(const QString &input)
{
- QStringList list = input.split(QLatin1Char(';'));
+ const QStringList list = input.split(QLatin1Char(';'));
QString result;
- foreach (const QString &s, list) {
+ for (const QString &s : list) {
if (!result.isEmpty())
result += ';';
result += domainName(s);
@@ -91,229 +214,272 @@ QString tst_QDnsLookup::domainNameList(const QString &input)
QStringList tst_QDnsLookup::domainNameListAlternatives(const QString &input)
{
QStringList alternatives = input.split('|');
- for (int i = 0; i < alternatives.length(); ++i)
+ for (int i = 0; i < alternatives.size(); ++i)
alternatives[i] = domainNameList(alternatives[i]);
return alternatives;
}
+std::unique_ptr<QDnsLookup>
+tst_QDnsLookup::lookupCommon(QDnsLookup::Type type, const QString &domain,
+ const QHostAddress &server, quint16 port)
+{
+ auto lookup = std::make_unique<QDnsLookup>(type, domainName(domain), server, port);
+ QObject::connect(lookup.get(), &QDnsLookup::finished,
+ &QTestEventLoop::instance(), &QTestEventLoop::exitLoop);
+ lookup->lookup();
+ QTestEventLoop::instance().enterLoopMSecs(Timeout);
+
+ QDnsLookup::Error error = lookup->error();
+ if (QTestEventLoop::instance().timeout())
+ error = QDnsLookup::TimeoutError;
+
+ if (!dnsServersMustWork && (error == QDnsLookup::ServerFailureError
+ || error == QDnsLookup::ServerRefusedError
+ || error == QDnsLookup::TimeoutError)) {
+ // It's not a QDnsLookup problem if the server refuses to answer the query.
+ // This happens for queries of type ANY through Dnsmasq, for example.
+ [&] {
+ auto me = QMetaEnum::fromType<QDnsLookup::Type>();
+ QString msg = u"Server refused or was unable to answer query; %1 type %3: %2"_s
+ .arg(domain, lookup->errorString(), QString(me.valueToKey(int(type))));
+ QSKIP(msg.toLocal8Bit());
+ }();
+ return {};
+ }
+
+ return lookup;
+}
+
+QStringList tst_QDnsLookup::formatReply(const QDnsLookup *lookup) const
+{
+ QStringList result;
+ QString domain = lookup->name();
+
+ auto shorter = [this](QString value) {
+ const QString &ending = usingIdnDomain ? idnDomain : normalDomain;
+ if (value.endsWith(ending))
+ value.chop(ending.size());
+ else
+ value += u'.';
+ return value;
+ };
+
+ for (const QDnsMailExchangeRecord &rr : lookup->mailExchangeRecords()) {
+ QString entry = u"MX %1 %2"_s.arg(rr.preference(), 5).arg(shorter(rr.exchange()));
+ if (rr.name() != domain)
+ entry = "MX unexpected label to "_L1 + rr.name();
+ result.append(std::move(entry));
+ }
+
+ for (const QDnsServiceRecord &rr : lookup->serviceRecords()) {
+ QString entry = u"SRV %1 %2 %3 %4"_s.arg(rr.priority(), 5).arg(rr.weight())
+ .arg(rr.port()).arg(shorter(rr.target()));
+ if (rr.name() != domain)
+ entry = "SRV unexpected label to "_L1 + rr.name();
+ result.append(std::move(entry));
+ }
+
+ auto addNameRecords = [&](QLatin1StringView rrtype, const QList<QDnsDomainNameRecord> &rrset) {
+ for (const QDnsDomainNameRecord &rr : rrset) {
+ QString entry = u"%1 %2"_s.arg(rrtype, shorter(rr.value()));
+ if (rr.name() != domain)
+ entry = rrtype + " unexpected label to "_L1 + rr.name();
+ result.append(std::move(entry));
+ }
+ };
+ addNameRecords("NS"_L1, lookup->nameServerRecords());
+ addNameRecords("PTR"_L1, lookup->pointerRecords());
+ addNameRecords("CNAME"_L1, lookup->canonicalNameRecords());
+
+ for (const QDnsHostAddressRecord &rr : lookup->hostAddressRecords()) {
+ if (rr.name() != domain)
+ continue; // A and AAAA may appear as extra records in the answer section
+ QHostAddress addr = rr.value();
+ result.append(u"%1 %2"_s
+ .arg(addr.protocol() == QHostAddress::IPv6Protocol ? "AAAA" : "A",
+ addr.toString()));
+ }
+
+ for (const QDnsTextRecord &rr : lookup->textRecords()) {
+ QString entry = "TXT"_L1;
+ for (const QByteArray &data : rr.values()) {
+ entry += u' ';
+ entry += QDebug::toString(data);
+ }
+ result.append(std::move(entry));
+ }
+
+ result.sort();
+ return result;
+}
+
+void tst_QDnsLookup::lookupLocalhost()
+{
+ auto lookup = lookupCommon(QDnsLookup::Type::A, u"localhost."_s);
+ QVERIFY(lookup);
+ QCOMPARE(lookup->error(), QDnsLookup::NoError);
+
+ QList<QDnsHostAddressRecord> hosts = lookup->hostAddressRecords();
+ QCOMPARE(hosts.size(), 1);
+ QCOMPARE(hosts.at(0).value(), QHostAddress::LocalHost);
+ QVERIFY2(hosts.at(0).name().startsWith(lookup->name()),
+ qPrintable(hosts.at(0).name()));
+}
+
+void tst_QDnsLookup::lookupRoot()
+{
+#ifdef Q_OS_WIN
+ QSKIP("This test fails on Windows as it seems to treat the lookup as a local one.");
+#else
+ auto lookup = lookupCommon(QDnsLookup::Type::NS, u""_s);
+ if (!lookup)
+ return;
+ QCOMPARE(lookup->error(), QDnsLookup::NoError);
+
+ const QList<QDnsDomainNameRecord> servers = lookup->nameServerRecords();
+ QVERIFY(!servers.isEmpty());
+ for (const QDnsDomainNameRecord &ns : servers) {
+ QCOMPARE(ns.name(), QString());
+ QVERIFY(ns.value().endsWith(".root-servers.net"));
+ }
+#endif
+}
+
+void tst_QDnsLookup::lookupNxDomain_data()
+{
+ QTest::addColumn<QDnsLookup::Type>("type");
+ QTest::addColumn<QString>("domain");
+
+ QTest::newRow("a") << QDnsLookup::A << "invalid.invalid";
+ QTest::newRow("aaaa") << QDnsLookup::AAAA << "invalid.invalid";
+ QTest::newRow("any") << QDnsLookup::ANY << "invalid.invalid";
+ QTest::newRow("mx") << QDnsLookup::MX << "invalid.invalid";
+ QTest::newRow("ns") << QDnsLookup::NS << "invalid.invalid";
+ QTest::newRow("ptr") << QDnsLookup::PTR << "invalid.invalid";
+ QTest::newRow("srv") << QDnsLookup::SRV << "invalid.invalid";
+ QTest::newRow("txt") << QDnsLookup::TXT << "invalid.invalid";
+}
+
+void tst_QDnsLookup::lookupNxDomain()
+{
+ QFETCH(QDnsLookup::Type, type);
+ QFETCH(QString, domain);
+
+ auto lookup = lookupCommon(type, domain);
+ if (!lookup)
+ return;
+ QCOMPARE(lookup->name(), domainName(domain));
+ QCOMPARE(lookup->type(), type);
+ QCOMPARE(lookup->error(), QDnsLookup::NotFoundError);
+}
+
void tst_QDnsLookup::lookup_data()
{
- QTest::addColumn<int>("type");
+ QTest::addColumn<QDnsLookup::Type>("type");
QTest::addColumn<QString>("domain");
- QTest::addColumn<int>("error");
- QTest::addColumn<QString>("cname");
- QTest::addColumn<QString>("host");
- QTest::addColumn<QString>("mx");
- QTest::addColumn<QString>("ns");
- QTest::addColumn<QString>("ptr");
- QTest::addColumn<QString>("srv");
- QTest::addColumn<QString>("txt");
-
- QTest::newRow("a-empty") << int(QDnsLookup::A) << "" << int(QDnsLookup::InvalidRequestError) << "" << "" << "" << "" << ""<< "" << "";
- QTest::newRow("a-notfound") << int(QDnsLookup::A) << "invalid.invalid" << int(QDnsLookup::NotFoundError) << "" << "" << "" << "" << "" << "" << "";
- QTest::newRow("a-single") << int(QDnsLookup::A) << "a-single" << int(QDnsLookup::NoError) << "" << "192.0.2.1" << "" << "" << "" << "" << "";
- QTest::newRow("a-multi") << int(QDnsLookup::A) << "a-multi" << int(QDnsLookup::NoError) << "" << "192.0.2.1;192.0.2.2;192.0.2.3" << "" << "" << "" << "" << "";
- QTest::newRow("aaaa-empty") << int(QDnsLookup::AAAA) << "" << int(QDnsLookup::InvalidRequestError) << "" << "" << "" << "" << "" << "" << "";
- QTest::newRow("aaaa-notfound") << int(QDnsLookup::AAAA) << "invalid.invalid" << int(QDnsLookup::NotFoundError) << "" << "" << "" << "" << "" << "" << "";
- QTest::newRow("aaaa-single") << int(QDnsLookup::AAAA) << "aaaa-single" << int(QDnsLookup::NoError) << "" << "2001:db8::1" << "" << "" << "" << "" << "";
- QTest::newRow("aaaa-multi") << int(QDnsLookup::AAAA) << "aaaa-multi" << int(QDnsLookup::NoError) << "" << "2001:db8::1;2001:db8::2;2001:db8::3" << "" << "" << "" << "" << "";
-
- QTest::newRow("any-empty") << int(QDnsLookup::ANY) << "" << int(QDnsLookup::InvalidRequestError) << "" << "" << "" << "" << "" << "" << "";
- QTest::newRow("any-notfound") << int(QDnsLookup::ANY) << "invalid.invalid" << int(QDnsLookup::NotFoundError) << "" << "" << "" << "" << "" << "" << "";
- QTest::newRow("any-a-single") << int(QDnsLookup::ANY) << "a-single" << int(QDnsLookup::NoError) << "" << "192.0.2.1" << "" << "" << "" << "" << "";
- QTest::newRow("any-a-plus-aaaa") << int(QDnsLookup::ANY) << "a-plus-aaaa" << int(QDnsLookup::NoError) << "" << "198.51.100.1;2001:db8::1:1" << "" << "" << "" << "" << "";
- QTest::newRow("any-multi") << int(QDnsLookup::ANY) << "multi" << int(QDnsLookup::NoError) << "" << "198.51.100.1;198.51.100.2;198.51.100.3;2001:db8::1:1;2001:db8::1:2" << "" << "" << "" << "" << "";
-
- QTest::newRow("mx-empty") << int(QDnsLookup::MX) << "" << int(QDnsLookup::InvalidRequestError) << "" << "" << "" << "" << "" << "" << "";
- QTest::newRow("mx-notfound") << int(QDnsLookup::MX) << "invalid.invalid" << int(QDnsLookup::NotFoundError) << "" << "" << "" << "" << "" << "" << "";
- QTest::newRow("mx-single") << int(QDnsLookup::MX) << "mx-single" << int(QDnsLookup::NoError) << "" << "" << "10 multi" << "" << "" << "" << "";
- QTest::newRow("mx-single-cname") << int(QDnsLookup::MX) << "mx-single-cname" << int(QDnsLookup::NoError) << "" << "" << "10 cname" << "" << "" << "" << "";
- QTest::newRow("mx-multi") << int(QDnsLookup::MX) << "mx-multi" << int(QDnsLookup::NoError) << "" << "" << "10 multi;20 a-single" << "" << "" << "" << "";
- QTest::newRow("mx-multi-sameprio") << int(QDnsLookup::MX) << "mx-multi-sameprio" << int(QDnsLookup::NoError) << "" << ""
- << "10 multi;10 a-single|"
- "10 a-single;10 multi" << "" << "" << "" << "";
-
- QTest::newRow("ns-empty") << int(QDnsLookup::NS) << "" << int(QDnsLookup::InvalidRequestError) << "" << "" << "" << "" << "" << "" << "";
- QTest::newRow("ns-notfound") << int(QDnsLookup::NS) << "invalid.invalid" << int(QDnsLookup::NotFoundError) << "" << "" << "" << "" << "" << "" << "";
- QTest::newRow("ns-single") << int(QDnsLookup::NS) << "ns-single" << int(QDnsLookup::NoError) << "" << "" << "" << "ns11.cloudns.net." << "" << "" << "";
- QTest::newRow("ns-multi") << int(QDnsLookup::NS) << "ns-multi" << int(QDnsLookup::NoError) << "" << "" << "" << "ns11.cloudns.net.;ns12.cloudns.net." << "" << "" << "";
-
- QTest::newRow("ptr-empty") << int(QDnsLookup::PTR) << "" << int(QDnsLookup::InvalidRequestError) << "" << "" << "" << "" << "" << "" << "";
- QTest::newRow("ptr-notfound") << int(QDnsLookup::PTR) << "invalid.invalid" << int(QDnsLookup::NotFoundError) << "" << "" << "" << "" << "" << "" << "";
+ QTest::addColumn<QString>("expected");
+
+ QTest::newRow("a-single") << QDnsLookup::A << "a-single"
+ << "A 192.0.2.1";
+ QTest::newRow("a-multi") << QDnsLookup::A << "a-multi"
+ << "A 192.0.2.1;A 192.0.2.2;A 192.0.2.3";
+ QTest::newRow("aaaa-single") << QDnsLookup::AAAA << "aaaa-single"
+ << "AAAA 2001:db8::1";
+ QTest::newRow("aaaa-multi") << QDnsLookup::AAAA << "aaaa-multi"
+ << "AAAA 2001:db8::1;AAAA 2001:db8::2;AAAA 2001:db8::3";
+
+ QTest::newRow("any-a-single") << QDnsLookup::ANY << "a-single"
+ << "A 192.0.2.1";
+ QTest::newRow("any-a-plus-aaaa") << QDnsLookup::ANY << "a-plus-aaaa"
+ << "A 198.51.100.1;AAAA 2001:db8::1:1";
+ QTest::newRow("any-multi") << QDnsLookup::ANY << "multi"
+ << "A 198.51.100.1;A 198.51.100.2;A 198.51.100.3;"
+ "AAAA 2001:db8::1:1;AAAA 2001:db8::1:2" ;
+
+ QTest::newRow("mx-single") << QDnsLookup::MX << "mx-single"
+ << "MX 10 multi";
+ QTest::newRow("mx-single-cname") << QDnsLookup::MX << "mx-single-cname"
+ << "MX 10 cname";
+ QTest::newRow("mx-multi") << QDnsLookup::MX << "mx-multi"
+ << "MX 10 multi;MX 20 a-single";
+ QTest::newRow("mx-multi-sameprio") << QDnsLookup::MX << "mx-multi-sameprio"
+ << "MX 10 a-single;MX 10 multi";
+
+ QTest::newRow("ns-single") << QDnsLookup::NS << "ns-single"
+ << "NS ns11.cloudns.net.";
+ QTest::newRow("ns-multi") << QDnsLookup::NS << "ns-multi"
+ << "NS ns11.cloudns.net.;NS ns12.cloudns.net.";
+
#if 0
// temporarily disabled since the new hosting provider can't insert
// PTR records outside of the in-addr.arpa zone
- QTest::newRow("ptr-single") << int(QDnsLookup::PTR) << "ptr-single" << int(QDnsLookup::NoError) << "" << "" << "" << "" << "a-single" << "" << "";
+ QTest::newRow("ptr-single") << QDnsLookup::PTR << "ptr-single"
+ << "PTR a-single";
#endif
-
- QTest::newRow("srv-empty") << int(QDnsLookup::SRV) << "" << int(QDnsLookup::InvalidRequestError) << "" << "" << "" << "" << "" << "" << "";
- QTest::newRow("srv-notfound") << int(QDnsLookup::SRV) << "invalid.invalid" << int(QDnsLookup::NotFoundError) << "" << "" << "" << "" << "" << "" << "";
- QTest::newRow("srv-single") << int(QDnsLookup::SRV) << "_echo._tcp.srv-single" << int(QDnsLookup::NoError) << "" << "" << "" << "" << "" << "5 0 7 multi" << "";
- QTest::newRow("srv-prio") << int(QDnsLookup::SRV) << "_echo._tcp.srv-prio" << int(QDnsLookup::NoError) << "" << "" << "" << "" << "" << "1 0 7 multi;2 0 7 a-plus-aaaa" << "";
- QTest::newRow("srv-weighted") << int(QDnsLookup::SRV) << "_echo._tcp.srv-weighted" << int(QDnsLookup::NoError) << "" << "" << "" << "" << ""
- << "5 75 7 multi;5 25 7 a-plus-aaaa|"
- "5 25 7 a-plus-aaaa;5 75 7 multi" << "";
- QTest::newRow("srv-multi") << int(QDnsLookup::SRV) << "_echo._tcp.srv-multi" << int(QDnsLookup::NoError) << "" << "" << "" << "" << ""
- << "1 50 7 multi;2 50 7 a-single;2 50 7 aaaa-single;3 50 7 a-multi|"
- "1 50 7 multi;2 50 7 aaaa-single;2 50 7 a-single;3 50 7 a-multi" << "";
-
- QTest::newRow("txt-empty") << int(QDnsLookup::TXT) << "" << int(QDnsLookup::InvalidRequestError) << "" << "" << "" << "" << "" << "" << "";
- QTest::newRow("txt-notfound") << int(QDnsLookup::TXT) << "invalid.invalid" << int(QDnsLookup::NotFoundError) << "" << "" << "" << "" << "" << "" << "";
- QTest::newRow("txt-single") << int(QDnsLookup::TXT) << "txt-single" << int(QDnsLookup::NoError) << "" << "" << "" << "" << "" << "" << "Hello";
- QTest::newRow("txt-multi-onerr") << int(QDnsLookup::TXT) << "txt-multi-onerr" << int(QDnsLookup::NoError) << "" << "" << "" << "" << "" << ""
- << QString::fromLatin1("Hello\0World", sizeof("Hello\0World") - 1);
- QTest::newRow("txt-multi-multirr") << int(QDnsLookup::TXT) << "txt-multi-multirr" << int(QDnsLookup::NoError) << "" << "" << "" << "" << "" << "" << "Hello;World";
-}
-
-static QByteArray msgDnsLookup(QDnsLookup::Error actualError,
- int expectedError,
- const QString &domain,
- const QString &cname,
- const QString &host,
- const QString &srv,
- const QString &mx,
- const QString &ns,
- const QString &ptr,
- const QString &errorString)
-{
- QString result;
- QTextStream str(&result);
- str << "Actual error: " << actualError;
- if (!errorString.isEmpty())
- str << " (" << errorString << ')';
- str << ", expected: " << expectedError;
- str << ", domain: " << domain;
- if (!cname.isEmpty())
- str << ", cname: " << cname;
- str << ", host: " << host;
- if (!srv.isEmpty())
- str << " server: " << srv;
- if (!mx.isEmpty())
- str << " mx: " << mx;
- if (!ns.isEmpty())
- str << " ns: " << ns;
- if (!ptr.isEmpty())
- str << " ptr: " << ptr;
- return result.toLocal8Bit();
+ QTest::newRow("ptr-1.1.1.1") << QDnsLookup::PTR << "1.1.1.1.in-addr.arpa."
+ << "PTR one.one.one.one.";
+ QTest::newRow("ptr-8.8.8.8") << QDnsLookup::PTR << "8.8.8.8.in-addr.arpa."
+ << "PTR dns.google.";
+ QTest::newRow("ptr-2001:4860:4860::8888")
+ << QDnsLookup::PTR << "8.8.8.8.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.6.8.4.0.6.8.4.1.0.0.2.ip6.arpa."
+ << "PTR dns.google.";
+ QTest::newRow("ptr-2606:4700:4700::1111")
+ << QDnsLookup::PTR << "1.1.1.1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.7.4.0.0.7.4.6.0.6.2.ip6.arpa."
+ << "PTR one.one.one.one.";
+
+ QTest::newRow("srv-single") << QDnsLookup::SRV << "_echo._tcp.srv-single"
+ << "SRV 5 0 7 multi";
+ QTest::newRow("srv-prio") << QDnsLookup::SRV << "_echo._tcp.srv-prio"
+ << "SRV 1 0 7 multi;SRV 2 0 7 a-plus-aaaa";
+ QTest::newRow("srv-weighted") << QDnsLookup::SRV << "_echo._tcp.srv-weighted"
+ << "SRV 5 25 7 a-plus-aaaa;SRV 5 75 7 multi";
+ QTest::newRow("srv-multi") << QDnsLookup::SRV << "_echo._tcp.srv-multi"
+ << "SRV 1 50 7 multi;"
+ "SRV 2 50 7 a-single;"
+ "SRV 2 50 7 aaaa-single;"
+ "SRV 3 50 7 a-multi";
+
+ QTest::newRow("txt-single") << QDnsLookup::TXT << "txt-single"
+ << "TXT \"Hello\"";
+ QTest::newRow("txt-multi-onerr") << QDnsLookup::TXT << "txt-multi-onerr"
+ << "TXT \"Hello\" \"World\"";
+ QTest::newRow("txt-multi-multirr") << QDnsLookup::TXT << "txt-multi-multirr"
+ << "TXT \"Hello\";TXT \"World\"";
}
void tst_QDnsLookup::lookup()
{
- QFETCH(int, type);
+ QFETCH(QDnsLookup::Type, type);
QFETCH(QString, domain);
- QFETCH(int, error);
- QFETCH(QString, cname);
- QFETCH(QString, host);
- QFETCH(QString, mx);
- QFETCH(QString, ns);
- QFETCH(QString, ptr);
- QFETCH(QString, srv);
- QFETCH(QString, txt);
-
- // transform the inputs
- domain = domainName(domain);
- cname = domainName(cname);
- ns = domainNameList(ns);
- ptr = domainNameList(ptr);
-
- // SRV and MX have reply entries that can change order
- // and we can't sort
- QStringList mx_alternatives = domainNameListAlternatives(mx);
- QStringList srv_alternatives = domainNameListAlternatives(srv);
+ QFETCH(QString, expected);
- QDnsLookup lookup;
- lookup.setType(static_cast<QDnsLookup::Type>(type));
- lookup.setName(domain);
- lookup.lookup();
- QTRY_VERIFY_WITH_TIMEOUT(lookup.isFinished(), Timeout);
+ std::unique_ptr<QDnsLookup> lookup = lookupCommon(type, domain);
+ if (!lookup)
+ return;
-#if defined(Q_OS_ANDROID)
- if (lookup.errorString() == QStringLiteral("Not yet supported on Android"))
- QEXPECT_FAIL("", "Not yet supported on Android", Abort);
-#endif
+ QCOMPARE(lookup->error(), QDnsLookup::NoError);
+ QCOMPARE(lookup->errorString(), QString());
+ QCOMPARE(lookup->type(), type);
+ QCOMPARE(lookup->name(), domainName(domain));
- QVERIFY2(int(lookup.error()) == error,
- msgDnsLookup(lookup.error(), error, domain, cname, host, srv, mx, ns, ptr, lookup.errorString()));
- if (error == QDnsLookup::NoError)
- QVERIFY(lookup.errorString().isEmpty());
- QCOMPARE(int(lookup.type()), type);
- QCOMPARE(lookup.name(), domain);
-
- // canonical names
- if (!cname.isEmpty()) {
- QVERIFY(!lookup.canonicalNameRecords().isEmpty());
- const QDnsDomainNameRecord cnameRecord = lookup.canonicalNameRecords().first();
- QCOMPARE(cnameRecord.name(), domain);
- QCOMPARE(cnameRecord.value(), cname);
- } else {
- QVERIFY(lookup.canonicalNameRecords().isEmpty());
- }
+ QString result = formatReply(lookup.get()).join(u';');
+ QCOMPARE(result, expected);
- // host addresses
- const QString hostName = cname.isEmpty() ? domain : cname;
- QStringList addresses;
- foreach (const QDnsHostAddressRecord &record, lookup.hostAddressRecords()) {
- //reply may include A & AAAA records for nameservers, ignore them and only look at records matching the query
- if (record.name() == hostName)
- addresses << record.value().toString().toLower();
- }
- addresses.sort();
- QCOMPARE(addresses.join(';'), host);
-
- // mail exchanges
- QStringList mailExchanges;
- foreach (const QDnsMailExchangeRecord &record, lookup.mailExchangeRecords()) {
- QCOMPARE(record.name(), domain);
- mailExchanges << QString::number(record.preference()) + QLatin1Char(' ') + record.exchange();
- }
- QVERIFY2(mx_alternatives.contains(mailExchanges.join(';')),
- qPrintable("Actual: " + mailExchanges.join(';') + "\nExpected one of:\n" + mx_alternatives.join('\n')));
-
- // name servers
- QStringList nameServers;
- foreach (const QDnsDomainNameRecord &record, lookup.nameServerRecords()) {
- //reply may include NS records for authoritative nameservers, ignore them and only look at records matching the query
- if (record.name() == domain)
- nameServers << record.value();
- }
- nameServers.sort();
- QCOMPARE(nameServers.join(';'), ns);
-
- // pointers
- if (!ptr.isEmpty()) {
- QVERIFY(!lookup.pointerRecords().isEmpty());
- const QDnsDomainNameRecord ptrRecord = lookup.pointerRecords().first();
- QCOMPARE(ptrRecord.name(), domain);
- QCOMPARE(ptrRecord.value(), ptr);
- } else {
- QVERIFY(lookup.pointerRecords().isEmpty());
- }
+ // confirm that MX and SRV records are properly sorted
+ const QList<QDnsMailExchangeRecord> mx = lookup->mailExchangeRecords();
+ for (qsizetype i = 1; i < mx.size(); ++i)
+ QCOMPARE_GE(mx[i].preference(), mx[i - 1].preference());
- // services
- QStringList services;
- foreach (const QDnsServiceRecord &record, lookup.serviceRecords()) {
- QCOMPARE(record.name(), domain);
- services << (QString::number(record.priority()) + QLatin1Char(' ')
- + QString::number(record.weight()) + QLatin1Char(' ')
- + QString::number(record.port()) + QLatin1Char(' ') + record.target());
- }
- QVERIFY2(srv_alternatives.contains(services.join(';')),
- qPrintable("Actual: " + services.join(';') + "\nExpected one of:\n" + srv_alternatives.join('\n')));
-
- // text
- QStringList texts;
- foreach (const QDnsTextRecord &record, lookup.textRecords()) {
- QCOMPARE(record.name(), domain);
- QString text;
- foreach (const QByteArray &ba, record.values()) {
- if (!text.isEmpty())
- text += '\0';
- text += QString::fromLatin1(ba);
- }
- texts << text;
- }
- texts.sort();
- QCOMPARE(texts.join(';'), txt);
+ const QList<QDnsServiceRecord> srv = lookup->serviceRecords();
+ for (qsizetype i = 1; i < srv.size(); ++i)
+ QCOMPARE_GE(srv[i].priority(), srv[i - 1].priority());
+}
+
+void tst_QDnsLookup::lookupIdn()
+{
+ usingIdnDomain = true;
+ lookup();
+ usingIdnDomain = false;
}
void tst_QDnsLookup::lookupReuse()
@@ -326,11 +492,6 @@ void tst_QDnsLookup::lookupReuse()
lookup.lookup();
QTRY_VERIFY_WITH_TIMEOUT(lookup.isFinished(), Timeout);
-#if defined(Q_OS_ANDROID)
- if (lookup.errorString() == QStringLiteral("Not yet supported on Android"))
- QEXPECT_FAIL("", "Not yet supported on Android", Abort);
-#endif
-
QCOMPARE(int(lookup.error()), int(QDnsLookup::NoError));
QVERIFY(!lookup.hostAddressRecords().isEmpty());
QCOMPARE(lookup.hostAddressRecords().first().name(), domainName("a-single"));
@@ -367,23 +528,96 @@ void tst_QDnsLookup::lookupAbortRetry()
lookup.lookup();
QTRY_VERIFY_WITH_TIMEOUT(lookup.isFinished(), Timeout);
-#if defined(Q_OS_ANDROID)
- if (lookup.errorString() == QStringLiteral("Not yet supported on Android"))
- QEXPECT_FAIL("", "Not yet supported on Android", Abort);
-#endif
-
QCOMPARE(int(lookup.error()), int(QDnsLookup::NoError));
QVERIFY(!lookup.hostAddressRecords().isEmpty());
QCOMPARE(lookup.hostAddressRecords().first().name(), domainName("aaaa-single"));
QCOMPARE(lookup.hostAddressRecords().first().value(), QHostAddress("2001:db8::1"));
}
-void tst_QDnsLookup::bindingsAndProperties()
+void tst_QDnsLookup::setNameserverLoopback()
+{
+#ifdef Q_OS_WIN
+ // Windows doesn't like sending DNS requests to ports other than 53, so
+ // let's try it first.
+ constexpr quint16 DesiredPort = 53;
+#else
+ // Trying to bind to port 53 will fail on Unix systems unless this test is
+ // run as root, so we try mDNS's port (to help decoding in a packet capture).
+ constexpr quint16 DesiredPort = 5353; // mDNS
+#endif
+ // random loopback address so multiple copies of this test can run
+ QHostAddress desiredAddress(0x7f000000 | QRandomGenerator::system()->bounded(0xffffff));
+
+ QUdpSocket server;
+ if (!server.bind(desiredAddress, DesiredPort)) {
+ // port in use, try a random one
+ server.bind(QHostAddress::LocalHost, 0);
+ }
+ QCOMPARE(server.state(), QUdpSocket::BoundState);
+
+ QDnsLookup lookup(QDnsLookup::Type::A, u"somelabel.somedomain"_s);
+ QSignalSpy spy(&lookup, SIGNAL(finished()));
+ lookup.setNameserver(server.localAddress(), server.localPort());
+
+ // QDnsLookup is threaded, so we can answer on the main thread
+ QObject::connect(&server, &QUdpSocket::readyRead,
+ &QTestEventLoop::instance(), &QTestEventLoop::exitLoop);
+ QObject::connect(&lookup, &QDnsLookup::finished,
+ &QTestEventLoop::instance(), &QTestEventLoop::exitLoop);
+ lookup.lookup();
+ QTestEventLoop::instance().enterLoop(5);
+ QVERIFY(!QTestEventLoop::instance().timeout());
+ QVERIFY2(spy.isEmpty(), qPrintable(lookup.errorString()));
+
+ QNetworkDatagram dgram = server.receiveDatagram();
+ QByteArray data = dgram.data();
+ QCOMPARE_GT(data.size(), HeaderSize);
+
+ quint8 opcode = (quint8(data.at(2)) >> 3) & 0xF;
+ QCOMPARE(opcode, 0); // standard query
+
+ // send an NXDOMAIN reply to release the lookup thread
+ QByteArray reply = data;
+ reply[2] = 0x80U; // header->qr = true;
+ reply[3] = 3; // header->rcode = NXDOMAIN;
+ server.writeDatagram(reply.constData(), reply.size(), dgram.senderAddress(),
+ dgram.senderPort());
+ server.close();
+
+ // now check that the QDnsLookup finished
+ QTestEventLoop::instance().enterLoop(5);
+ QVERIFY(!QTestEventLoop::instance().timeout());
+ QCOMPARE(spy.size(), 1);
+ QCOMPARE(lookup.error(), QDnsLookup::NotFoundError);
+}
+
+void tst_QDnsLookup::setNameserver_data()
{
- QFETCH_GLOBAL(const QString, tld);
- if (tld == QStringLiteral("idn"))
+ static QList<QHostAddress> servers = systemNameservers() + globalPublicNameservers();
+ QTest::addColumn<QHostAddress>("server");
+
+ if (servers.isEmpty()) {
+ QSKIP("No reachable DNS servers were found");
+ } else {
+ for (const QHostAddress &h : std::as_const(servers))
+ QTest::addRow("%s", qUtf8Printable(h.toString())) << h;
+ }
+}
+
+void tst_QDnsLookup::setNameserver()
+{
+ QFETCH(QHostAddress, server);
+ std::unique_ptr<QDnsLookup> lookup =
+ lookupCommon(QDnsLookup::Type::A, "a-single", server);
+ if (!lookup)
return;
+ QCOMPARE(lookup->error(), QDnsLookup::NoError);
+ QString result = formatReply(lookup.get()).join(';');
+ QCOMPARE(result, "A 192.0.2.1");
+}
+void tst_QDnsLookup::bindingsAndProperties()
+{
QDnsLookup lookup;
lookup.setType(QDnsLookup::A);
@@ -392,7 +626,7 @@ void tst_QDnsLookup::bindingsAndProperties()
const QSignalSpy typeChangeSpy(&lookup, &QDnsLookup::typeChanged);
dnsTypeProp = QDnsLookup::AAAA;
- QCOMPARE(typeChangeSpy.count(), 1);
+ QCOMPARE(typeChangeSpy.size(), 1);
QCOMPARE(lookup.type(), QDnsLookup::AAAA);
dnsTypeProp.setBinding(lookup.bindableType().makeBinding());
@@ -404,7 +638,7 @@ void tst_QDnsLookup::bindingsAndProperties()
const QSignalSpy nameChangeSpy(&lookup, &QDnsLookup::nameChanged);
nameProp = QStringLiteral("a-plus-aaaa");
- QCOMPARE(nameChangeSpy.count(), 1);
+ QCOMPARE(nameChangeSpy.size(), 1);
QCOMPARE(lookup.name(), QStringLiteral("a-plus-aaaa"));
nameProp.setBinding(lookup.bindableName().makeBinding());
@@ -414,14 +648,55 @@ void tst_QDnsLookup::bindingsAndProperties()
QProperty<QHostAddress> nameserverProp;
lookup.bindableNameserver().setBinding(Qt::makePropertyBinding(nameserverProp));
const QSignalSpy nameserverChangeSpy(&lookup, &QDnsLookup::nameserverChanged);
+ const QSignalSpy nameserverPortChangeSpy(&lookup, &QDnsLookup::nameserverPortChanged);
nameserverProp = QHostAddress::LocalHost;
- QCOMPARE(nameserverChangeSpy.count(), 1);
+ QCOMPARE(nameserverChangeSpy.size(), 1);
+ QCOMPARE(nameserverPortChangeSpy.size(), 0);
QCOMPARE(lookup.nameserver(), QHostAddress::LocalHost);
nameserverProp.setBinding(lookup.bindableNameserver().makeBinding());
lookup.setNameserver(QHostAddress::Any);
QCOMPARE(nameserverProp.value(), QHostAddress::Any);
+ QCOMPARE(nameserverChangeSpy.size(), 2);
+ QCOMPARE(nameserverPortChangeSpy.size(), 0);
+
+ lookup.setNameserver(QHostAddress::LocalHostIPv6, 10053);
+ QCOMPARE(nameserverProp.value(), QHostAddress::LocalHostIPv6);
+ QCOMPARE(nameserverChangeSpy.size(), 3);
+ QCOMPARE(nameserverPortChangeSpy.size(), 1);
+}
+
+void tst_QDnsLookup::automatedBindings()
+{
+ QDnsLookup lookup;
+
+ QTestPrivate::testReadWritePropertyBasics(lookup, u"aaaa"_s, u"txt"_s, "name");
+ if (QTest::currentTestFailed()) {
+ qDebug("Failed property test for QDnsLookup::name");
+ return;
+ }
+
+ QTestPrivate::testReadWritePropertyBasics(lookup, QDnsLookup::AAAA, QDnsLookup::TXT, "type");
+ if (QTest::currentTestFailed()) {
+ qDebug("Failed property test for QDnsLookup::type");
+ return;
+ }
+
+ QTestPrivate::testReadWritePropertyBasics(lookup, QHostAddress{QHostAddress::Any},
+ QHostAddress{QHostAddress::LocalHost},
+ "nameserver");
+ if (QTest::currentTestFailed()) {
+ qDebug("Failed property test for QDnsLookup::nameserver");
+ return;
+ }
+
+ QTestPrivate::testReadWritePropertyBasics(lookup, quint16(123), quint16(456),
+ "nameserverPort");
+ if (QTest::currentTestFailed()) {
+ qDebug("Failed property test for QDnsLookup::nameserverPort");
+ return;
+ }
}
QTEST_MAIN(tst_QDnsLookup)
diff --git a/tests/auto/network/kernel/qdnslookup_appless/CMakeLists.txt b/tests/auto/network/kernel/qdnslookup_appless/CMakeLists.txt
index 1505228176..41cf19753f 100644
--- a/tests/auto/network/kernel/qdnslookup_appless/CMakeLists.txt
+++ b/tests/auto/network/kernel/qdnslookup_appless/CMakeLists.txt
@@ -1,12 +1,19 @@
-# Generated from qdnslookup_appless.pro.
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
#####################################################################
## tst_qdnslookup_appless Test:
#####################################################################
+if(NOT QT_BUILD_STANDALONE_TESTS AND NOT QT_BUILDING_QT)
+ cmake_minimum_required(VERSION 3.16)
+ project(tst_qdnslookup_appless LANGUAGES CXX)
+ find_package(Qt6BuildInternals REQUIRED COMPONENTS STANDALONE_TEST)
+endif()
+
qt_internal_add_test(tst_qdnslookup_appless
SOURCES
tst_qdnslookup_appless.cpp
- PUBLIC_LIBRARIES
+ LIBRARIES
Qt::Network
)
diff --git a/tests/auto/network/kernel/qdnslookup_appless/tst_qdnslookup_appless.cpp b/tests/auto/network/kernel/qdnslookup_appless/tst_qdnslookup_appless.cpp
index 9346a82dbb..21393ee628 100644
--- a/tests/auto/network/kernel/qdnslookup_appless/tst_qdnslookup_appless.cpp
+++ b/tests/auto/network/kernel/qdnslookup_appless/tst_qdnslookup_appless.cpp
@@ -1,30 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2012 Jeremy Lainé <jeremy.laine@m4x.org>
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2012 Jeremy Lainé <jeremy.laine@m4x.org>
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
#include <QtCore/QCoreApplication>
#include <QtNetwork/QDnsLookup>
diff --git a/tests/auto/network/kernel/qhostaddress/CMakeLists.txt b/tests/auto/network/kernel/qhostaddress/CMakeLists.txt
index a33ae6d709..e11a600b60 100644
--- a/tests/auto/network/kernel/qhostaddress/CMakeLists.txt
+++ b/tests/auto/network/kernel/qhostaddress/CMakeLists.txt
@@ -1,13 +1,20 @@
-# Generated from qhostaddress.pro.
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
#####################################################################
## tst_qhostaddress Test:
#####################################################################
+if(NOT QT_BUILD_STANDALONE_TESTS AND NOT QT_BUILDING_QT)
+ cmake_minimum_required(VERSION 3.16)
+ project(tst_qhostaddress LANGUAGES CXX)
+ find_package(Qt6BuildInternals REQUIRED COMPONENTS STANDALONE_TEST)
+endif()
+
qt_internal_add_test(tst_qhostaddress
SOURCES
tst_qhostaddress.cpp
- PUBLIC_LIBRARIES
+ LIBRARIES
Qt::NetworkPrivate
)
@@ -15,6 +22,6 @@ qt_internal_add_test(tst_qhostaddress
#####################################################################
qt_internal_extend_target(tst_qhostaddress CONDITION WIN32
- PUBLIC_LIBRARIES
+ LIBRARIES
ws2_32
)
diff --git a/tests/auto/network/kernel/qhostaddress/tst_qhostaddress.cpp b/tests/auto/network/kernel/qhostaddress/tst_qhostaddress.cpp
index 78f072fb54..18d1c04a85 100644
--- a/tests/auto/network/kernel/qhostaddress/tst_qhostaddress.cpp
+++ b/tests/auto/network/kernel/qhostaddress/tst_qhostaddress.cpp
@@ -1,31 +1,6 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Copyright (C) 2016 Intel Corporation.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// Copyright (C) 2016 Intel Corporation.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
#include <qhostaddress.h>
#include <private/qhostaddress_p.h>
@@ -40,7 +15,7 @@
# include <qt_windows.h>
#endif
-#ifdef Q_OS_ANDROID
+#if defined(Q_OS_ANDROID) || defined(Q_OS_WASM) || defined(Q_OS_VXWORKS)
# include <netinet/in.h>
#endif
@@ -351,6 +326,12 @@ void tst_QHostAddress::isEqual_data()
QTest::newRow("anyv6-anyv4-local") << QHostAddress(QHostAddress::AnyIPv6) << QHostAddress(QHostAddress::AnyIPv4) << (int)QHostAddress::ConvertLocalHost << false;
QTest::newRow("any-anyv4-local") << QHostAddress(QHostAddress::Any) << QHostAddress(QHostAddress::AnyIPv4) << (int)QHostAddress::ConvertLocalHost << false;
QTest::newRow("any-anyv6-local") << QHostAddress(QHostAddress::Any) << QHostAddress(QHostAddress::AnyIPv6) << (int)QHostAddress::ConvertLocalHost << false;
+ QTest::newRow("localhostv6-any-tolerant") << QHostAddress(QHostAddress::LocalHostIPv6) << QHostAddress(QHostAddress::Any) << (int)QHostAddress::TolerantConversion << false;
+ QTest::newRow("localhostv4-any-tolerant") << QHostAddress(QHostAddress::LocalHost) << QHostAddress(QHostAddress::Any) << (int)QHostAddress::TolerantConversion << false;
+ QTest::newRow("localhostv6-anyv6-tolerant") << QHostAddress(QHostAddress::LocalHostIPv6) << QHostAddress(QHostAddress::AnyIPv6) << (int)QHostAddress::TolerantConversion << false;
+ QTest::newRow("localhostv4-anyv6-tolerant") << QHostAddress(QHostAddress::LocalHost) << QHostAddress(QHostAddress::AnyIPv6) << (int)QHostAddress::TolerantConversion << false;
+ QTest::newRow("localhostv6-anyv4-tolerant") << QHostAddress(QHostAddress::LocalHostIPv6) << QHostAddress(QHostAddress::AnyIPv4) << (int)QHostAddress::TolerantConversion << false;
+ QTest::newRow("localhostv4-anyv4-tolerant") << QHostAddress(QHostAddress::LocalHost) << QHostAddress(QHostAddress::AnyIPv4) << (int)QHostAddress::TolerantConversion << false;
}
void tst_QHostAddress::isEqual()
@@ -722,6 +703,7 @@ void tst_QHostAddress::classification()
bool isUniqueLocalAddress = (result == UniqueLocalAddress);
bool isMulticast = (result == MulticastAddress);
bool isBroadcast = (result == BroadcastAddress);
+ bool isPrivateUse = (result == PrivateNetworkAddress || result == UniqueLocalAddress);
QCOMPARE(address.isLoopback(), isLoopback);
QCOMPARE(address.isGlobal(), isGlobal);
@@ -730,6 +712,7 @@ void tst_QHostAddress::classification()
QCOMPARE(address.isUniqueLocalUnicast(), isUniqueLocalAddress);
QCOMPARE(address.isMulticast(), isMulticast);
QCOMPARE(address.isBroadcast(), isBroadcast);
+ QCOMPARE(address.isPrivateUse(), isPrivateUse);
}
void tst_QHostAddress::convertv4v6_data()
diff --git a/tests/auto/network/kernel/qhostinfo/CMakeLists.txt b/tests/auto/network/kernel/qhostinfo/CMakeLists.txt
index 40e0456d5f..dc7ab3b221 100644
--- a/tests/auto/network/kernel/qhostinfo/CMakeLists.txt
+++ b/tests/auto/network/kernel/qhostinfo/CMakeLists.txt
@@ -1,4 +1,11 @@
-# Generated from qhostinfo.pro.
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
+
+if(NOT QT_BUILD_STANDALONE_TESTS AND NOT QT_BUILDING_QT)
+ cmake_minimum_required(VERSION 3.16)
+ project(tst_qhostinfo LANGUAGES CXX)
+ find_package(Qt6BuildInternals REQUIRED COMPONENTS STANDALONE_TEST)
+endif()
if(NOT QT_FEATURE_private_tests)
return()
@@ -11,18 +18,15 @@ endif()
qt_internal_add_test(tst_qhostinfo
SOURCES
tst_qhostinfo.cpp
- PUBLIC_LIBRARIES
+ LIBRARIES
Qt::CorePrivate
Qt::NetworkPrivate
)
-#### Keys ignored in scope 1:.:.:qhostinfo.pro:<TRUE>:
-# _REQUIREMENTS = "qtConfig(private_tests)"
-
## Scopes:
#####################################################################
qt_internal_extend_target(tst_qhostinfo CONDITION WIN32
- PUBLIC_LIBRARIES
+ LIBRARIES
ws2_32
)
diff --git a/tests/auto/network/kernel/qhostinfo/tst_qhostinfo.cpp b/tests/auto/network/kernel/qhostinfo/tst_qhostinfo.cpp
index 98644933fd..bd4bb7ef81 100644
--- a/tests/auto/network/kernel/qhostinfo/tst_qhostinfo.cpp
+++ b/tests/auto/network/kernel/qhostinfo/tst_qhostinfo.cpp
@@ -1,76 +1,52 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Copyright (C) 2016 Intel Corporation.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// Copyright (C) 2016 Intel Corporation.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
// When using WinSock2 on Windows, it's the first thing that can be included
// (except qglobal.h), or else you'll get tons of compile errors
#include <qglobal.h>
-// To prevent windows system header files from re-defining min/max
-#define NOMINMAX 1
-
#if defined(Q_OS_WIN)
# include <winsock2.h>
# include <ws2tcpip.h>
#endif
-#include <QTest>
-#include <QTestEventLoop>
-#include <QProcess>
+#include <qhostinfo.h>
+#include "private/qhostinfo_p.h"
+#include "private/qnativesocketengine_p.h"
+
#include <QCoreApplication>
#include <QDebug>
-#include <QTcpSocket>
#include <QTcpServer>
+#include <QTcpSocket>
+#include <QTest>
+#include <QTestEventLoop>
#include <private/qthread_p.h>
-#include <time.h>
+#include <sys/types.h>
+
#if defined(Q_OS_WIN)
-#include <qt_windows.h>
+# include <qt_windows.h>
+# ifdef gai_strerror
+# undef gai_strerror
+# define gai_strerror gai_strerrorA
+# endif
#else
-#include <unistd.h>
-#include <signal.h>
-#endif
-
-#include <qhostinfo.h>
-#include "private/qhostinfo_p.h"
-
-#include <sys/types.h>
-#if defined(Q_OS_UNIX)
-# include <sys/socket.h>
# include <netdb.h>
+# include <sys/socket.h>
+# include <unistd.h>
+#endif
+#ifndef NI_MAXHOST
+# define NI_MAXHOST 1025
#endif
#include "../../../network-settings.h"
#define TEST_DOMAIN ".test.qt-project.org"
+using namespace std::chrono_literals;
class tst_QHostInfo : public QObject
{
@@ -109,15 +85,55 @@ private slots:
void cache();
void abortHostLookup();
-protected slots:
- void resultsReady(const QHostInfo &);
private:
bool ipv6LookupsAvailable;
bool ipv6Available;
- bool lookupDone;
- int lookupsDoneCounter;
+};
+
+class tst_QHostInfo_Helper : public QObject
+{
+ Q_OBJECT
+protected slots:
+ void resultsReady(const QHostInfo &);
+public:
+ tst_QHostInfo_Helper(const QString &hostname)
+ : hostname(hostname)
+ {}
+
+ QString hostname;
+ bool lookupDone = false;
+ int lookupsDoneCounter = 0;
QHostInfo lookupResults;
+
+ void blockingLookup()
+ {
+ lookupResults = QHostInfo::fromName(hostname);
+ lookupDone = true;
+ ++lookupsDoneCounter;
+ }
+ void lookupHostOldStyle()
+ {
+ QHostInfo::lookupHost(hostname, this, SLOT(resultsReady(QHostInfo)));
+ }
+ void lookupHostNewStyle()
+ {
+ QHostInfo::lookupHost(hostname, this, &tst_QHostInfo_Helper::resultsReady);
+ }
+ void lookupHostLambda()
+ {
+ QHostInfo::lookupHost(hostname, this, [this](const QHostInfo &hostInfo) {
+ resultsReady(hostInfo);
+ });
+ }
+
+ bool waitForResults(std::chrono::milliseconds timeout = 15s)
+ {
+ QTestEventLoop::instance().enterLoop(timeout);
+ return !QTestEventLoop::instance().timeout() && lookupDone;
+ }
+
+ void checkResults(QHostInfo::HostInfoError err, const QString &addresses);
};
void tst_QHostInfo::swapFunction()
@@ -233,26 +249,15 @@ void tst_QHostInfo::lookupIPv4_data()
QTest::newRow("idn-unicode") << QString::fromLatin1("a-single.alqualond\353" TEST_DOMAIN) << "192.0.2.1" << int(QHostInfo::NoError);
}
-void tst_QHostInfo::lookupIPv4()
+void tst_QHostInfo_Helper::checkResults(QHostInfo::HostInfoError err, const QString &addresses)
{
- QFETCH(QString, hostname);
- QFETCH(int, err);
- QFETCH(QString, addresses);
-
- lookupDone = false;
- QHostInfo::lookupHost(hostname, this, SLOT(resultsReady(QHostInfo)));
-
- QTestEventLoop::instance().enterLoop(10);
- QVERIFY(!QTestEventLoop::instance().timeout());
- QVERIFY(lookupDone);
-
if ((int)lookupResults.error() != (int)err) {
qWarning() << hostname << "=>" << lookupResults.errorString();
}
- QCOMPARE((int)lookupResults.error(), (int)err);
+ QCOMPARE(lookupResults.error(), err);
QStringList tmp;
- for (int i = 0; i < lookupResults.addresses().count(); ++i)
+ for (int i = 0; i < lookupResults.addresses().size(); ++i)
tmp.append(lookupResults.addresses().at(i).toString());
tmp.sort();
@@ -262,6 +267,18 @@ void tst_QHostInfo::lookupIPv4()
QCOMPARE(tmp.join(' '), expected.join(' '));
}
+void tst_QHostInfo::lookupIPv4()
+{
+ QFETCH(QString, hostname);
+ QFETCH(int, err);
+ QFETCH(QString, addresses);
+
+ tst_QHostInfo_Helper helper(hostname);
+ helper.lookupHostOldStyle();
+ QVERIFY(helper.waitForResults());
+ helper.checkResults(QHostInfo::HostInfoError(err), addresses);
+}
+
void tst_QHostInfo::lookupIPv6_data()
{
QTest::addColumn<QString>("hostname");
@@ -287,24 +304,10 @@ void tst_QHostInfo::lookupIPv6()
if (!ipv6LookupsAvailable)
QSKIP("This platform does not support IPv6 lookups");
- lookupDone = false;
- QHostInfo::lookupHost(hostname, this, SLOT(resultsReady(QHostInfo)));
-
- QTestEventLoop::instance().enterLoop(10);
- QVERIFY(!QTestEventLoop::instance().timeout());
- QVERIFY(lookupDone);
-
- QCOMPARE((int)lookupResults.error(), (int)err);
-
- QStringList tmp;
- for (int i = 0; i < lookupResults.addresses().count(); ++i)
- tmp.append(lookupResults.addresses().at(i).toString());
- tmp.sort();
-
- QStringList expected = addresses.split(' ');
- expected.sort();
-
- QCOMPARE(tmp.join(' ').toLower(), expected.join(' ').toLower());
+ tst_QHostInfo_Helper helper(hostname);
+ helper.lookupHostOldStyle();
+ QVERIFY(helper.waitForResults());
+ helper.checkResults(QHostInfo::HostInfoError(err), addresses);
}
void tst_QHostInfo::lookupConnectToFunctionPointer_data()
@@ -318,26 +321,10 @@ void tst_QHostInfo::lookupConnectToFunctionPointer()
QFETCH(int, err);
QFETCH(QString, addresses);
- lookupDone = false;
- QHostInfo::lookupHost(hostname, this, &tst_QHostInfo::resultsReady);
-
- QTestEventLoop::instance().enterLoop(10);
- QVERIFY(!QTestEventLoop::instance().timeout());
- QVERIFY(lookupDone);
-
- if (int(lookupResults.error()) != int(err))
- qWarning() << hostname << "=>" << lookupResults.errorString();
- QCOMPARE(int(lookupResults.error()), int(err));
-
- QStringList tmp;
- for (const auto &result : lookupResults.addresses())
- tmp.append(result.toString());
- tmp.sort();
-
- QStringList expected = addresses.split(' ');
- expected.sort();
-
- QCOMPARE(tmp.join(' '), expected.join(' '));
+ tst_QHostInfo_Helper helper(hostname);
+ helper.lookupHostNewStyle();
+ QVERIFY(helper.waitForResults());
+ helper.checkResults(QHostInfo::HostInfoError(err), addresses);
}
void tst_QHostInfo::lookupConnectToFunctionPointerDeleted()
@@ -362,89 +349,38 @@ void tst_QHostInfo::lookupConnectToLambda()
QFETCH(int, err);
QFETCH(QString, addresses);
- lookupDone = false;
- QHostInfo::lookupHost(hostname, [this](const QHostInfo &hostInfo) {
- resultsReady(hostInfo);
- });
-
- QTestEventLoop::instance().enterLoop(10);
- QVERIFY(!QTestEventLoop::instance().timeout());
- QVERIFY(lookupDone);
-
- if (int(lookupResults.error()) != int(err))
- qWarning() << hostname << "=>" << lookupResults.errorString();
- QCOMPARE(int(lookupResults.error()), int(err));
-
- QStringList tmp;
- for (int i = 0; i < lookupResults.addresses().count(); ++i)
- tmp.append(lookupResults.addresses().at(i).toString());
- tmp.sort();
-
- QStringList expected = addresses.split(' ');
- expected.sort();
-
- QCOMPARE(tmp.join(' '), expected.join(' '));
+ tst_QHostInfo_Helper helper(hostname);
+ helper.lookupHostLambda();
+ QVERIFY(helper.waitForResults());
+ helper.checkResults(QHostInfo::HostInfoError(err), addresses);
}
static QStringList reverseLookupHelper(const QString &ip)
{
QStringList results;
-
- const QString pythonCode =
- "import socket;"
- "import sys;"
- "print (socket.getnameinfo((sys.argv[1], 0), 0)[0]);";
-
- QList<QByteArray> lines;
- QProcess python;
- python.setProcessChannelMode(QProcess::ForwardedErrorChannel);
- python.start("python", QStringList() << QString("-c") << pythonCode << ip);
- if (python.waitForFinished()) {
- if (python.exitStatus() == QProcess::NormalExit && python.exitCode() == 0)
- lines = python.readAllStandardOutput().split('\n');
- for (QByteArray line : lines) {
- if (!line.isEmpty())
- results << line.trimmed();
- }
- if (!results.isEmpty())
- return results;
- }
-
- qDebug() << "Python failed, falling back to nslookup";
- QProcess lookup;
- lookup.setProcessChannelMode(QProcess::ForwardedErrorChannel);
- lookup.start("nslookup", QStringList(ip));
- if (!lookup.waitForFinished()) {
- results << "nslookup failure";
- qDebug() << "nslookup failure";
+ union qt_sockaddr {
+ sockaddr a;
+ sockaddr_in a4;
+ sockaddr_in6 a6;
+ } sa = {};
+
+ QHostAddress addr(ip);
+ if (addr.isNull()) {
+ qWarning("Could not parse IP address: %ls", qUtf16Printable(ip));
return results;
}
- lines = lookup.readAllStandardOutput().split('\n');
-
- QByteArray name;
-
- const QByteArray nameMarkerNix("name =");
- const QByteArray nameMarkerWin("Name:");
- const QByteArray addressMarkerWin("Address:");
-
- for (QByteArray line : lines) {
- int index = -1;
- if ((index = line.indexOf(nameMarkerNix)) != -1) { // Linux and macOS
- name = line.mid(index + nameMarkerNix.length()).chopped(1).trimmed();
- results << name;
- } else if (line.startsWith(nameMarkerWin)) { // Windows formatting
- name = line.mid(line.lastIndexOf(" ")).trimmed();
- } else if (line.startsWith(addressMarkerWin)) {
- QByteArray address = line.mid(addressMarkerWin.length()).trimmed();
- if (address == ip.toUtf8()) {
- results << name;
- }
- }
- }
- if (results.isEmpty()) {
- qDebug() << "Failure to parse nslookup output: " << lines;
+ // from qnativesocketengine_p.h:
+ QT_SOCKLEN_T len = setSockaddr(&sa.a, addr, /*port = */ 0);
+
+ QByteArray name(NI_MAXHOST, Qt::Uninitialized);
+ int ni_flags = NI_NAMEREQD | NI_NUMERICSERV;
+ if (int r = getnameinfo(&sa.a, len, name.data(), name.size(), nullptr, 0, ni_flags)) {
+ qWarning("Failed to reverse look up '%ls': %s", qUtf16Printable(ip), gai_strerror(r));
+ } else {
+ results << QString::fromLatin1(name, qstrnlen(name, name.size()));
}
+
return results;
}
@@ -457,8 +393,10 @@ void tst_QHostInfo::reverseLookup_data()
QTest::newRow("dns.google") << QString("8.8.8.8") << reverseLookupHelper("8.8.8.8") << 0 << false;
QTest::newRow("one.one.one.one") << QString("1.1.1.1") << reverseLookupHelper("1.1.1.1") << 0 << false;
- QTest::newRow("dns.google IPv6") << QString("2001:4860:4860::8888") << reverseLookupHelper("2001:4860:4860::8888") << 0 << true;
- QTest::newRow("cloudflare IPv6") << QString("2606:4700:4700::1111") << reverseLookupHelper("2606:4700:4700::1111") << 0 << true;
+ if (QStringList hostNames = reverseLookupHelper("2001:4860:4860::8888"); !hostNames.isEmpty())
+ QTest::newRow("dns.google IPv6") << QString("2001:4860:4860::8888") << std::move(hostNames) << 0 << true;
+ if (QStringList hostNames = reverseLookupHelper("2606:4700:4700::1111"); !hostNames.isEmpty())
+ QTest::newRow("cloudflare IPv6") << QString("2606:4700:4700::1111") << std::move(hostNames) << 0 << true;
QTest::newRow("bogus-name IPv6") << QString("1::2::3::4") << QStringList() << 1 << true;
}
@@ -467,11 +405,6 @@ void tst_QHostInfo::reverseLookup()
QFETCH(QString, address);
QFETCH(QStringList, hostNames);
QFETCH(int, err);
- QFETCH(bool, ipv6);
-
- if (ipv6 && !ipv6LookupsAvailable) {
- QSKIP("IPv6 reverse lookups are not supported on this platform");
- }
QHostInfo info = QHostInfo::fromName(address);
@@ -479,7 +412,7 @@ void tst_QHostInfo::reverseLookup()
if (!hostNames.contains(info.hostName()))
qDebug() << "Failure: expecting" << hostNames << ",got " << info.hostName();
QVERIFY(hostNames.contains(info.hostName()));
- QCOMPARE(info.addresses().first(), QHostAddress(address));
+ QCOMPARE(info.addresses().constFirst(), QHostAddress(address));
} else {
QCOMPARE(info.hostName(), address);
QCOMPARE(info.error(), QHostInfo::HostNotFound);
@@ -500,21 +433,9 @@ void tst_QHostInfo::blockingLookup()
QFETCH(int, err);
QFETCH(QString, addresses);
- QHostInfo hostInfo = QHostInfo::fromName(hostname);
- QStringList tmp;
- for (int i = 0; i < hostInfo.addresses().count(); ++i)
- tmp.append(hostInfo.addresses().at(i).toString());
- tmp.sort();
-
- if ((int)hostInfo.error() != (int)err) {
- qWarning() << hostname << "=>" << lookupResults.errorString();
- }
- QCOMPARE((int)hostInfo.error(), (int)err);
-
- QStringList expected = addresses.split(' ');
- expected.sort();
-
- QCOMPARE(tmp.join(' ').toUpper(), expected.join(' ').toUpper());
+ tst_QHostInfo_Helper helper(hostname);
+ helper.blockingLookup();
+ helper.checkResults(QHostInfo::HostInfoError(err), addresses);
}
void tst_QHostInfo::raceCondition()
@@ -531,8 +452,9 @@ protected:
inline void run() override
{
QHostInfo info = QHostInfo::fromName("a-single" TEST_DOMAIN);
+ QCOMPARE(info.errorString(), "Unknown error"); // no error
QCOMPARE(info.error(), QHostInfo::NoError);
- QVERIFY(info.addresses().count() > 0);
+ QVERIFY(info.addresses().size() > 0);
QCOMPARE(info.addresses().at(0).toString(), QString("192.0.2.1"));
}
};
@@ -579,24 +501,22 @@ void tst_QHostInfo::threadSafetyAsynchronousAPI()
{
const int nattempts = 10;
const int lookupsperthread = 10;
- QList<QThread*> threads;
- QList<LookupReceiver*> receivers;
+ QThread threads[nattempts];
+ LookupReceiver receivers[nattempts];
for (int i = 0; i < nattempts; ++i) {
- QThread* thread = new QThread;
- LookupReceiver* receiver = new LookupReceiver;
+ QThread *thread = &threads[i];
+ LookupReceiver *receiver = &receivers[i];
receiver->numrequests = lookupsperthread;
- receivers.append(receiver);
receiver->moveToThread(thread);
connect(thread, SIGNAL(started()), receiver, SLOT(start()));
thread->start();
- threads.append(thread);
}
- for (int k = threads.count() - 1; k >= 0; --k)
- QVERIFY(threads.at(k)->wait(60000));
- foreach (LookupReceiver* receiver, receivers) {
- QCOMPARE(receiver->result.error(), QHostInfo::NoError);
- QCOMPARE(receiver->result.addresses().at(0).toString(), QString("192.0.2.1"));
- QCOMPARE(receiver->numrequests, 0);
+ for (int k = nattempts - 1; k >= 0; --k)
+ QVERIFY(threads[k].wait(60000));
+ for (LookupReceiver &receiver : receivers) {
+ QCOMPARE(receiver.result.error(), QHostInfo::NoError);
+ QCOMPARE(receiver.result.addresses().at(0).toString(), QString("192.0.2.1"));
+ QCOMPARE(receiver.numrequests, 0);
}
}
@@ -605,17 +525,11 @@ void tst_QHostInfo::threadSafetyAsynchronousAPI()
void tst_QHostInfo::multipleSameLookups()
{
const int COUNT = 10;
- lookupsDoneCounter = 0;
-
+ tst_QHostInfo_Helper helper("localhost");
for (int i = 0; i < COUNT; i++)
- QHostInfo::lookupHost("localhost", this, SLOT(resultsReady(QHostInfo)));
+ helper.lookupHostOldStyle();
- QElapsedTimer timer;
- timer.start();
- while (timer.elapsed() < 10000 && lookupsDoneCounter < COUNT) {
- QTestEventLoop::instance().enterLoop(2);
- }
- QCOMPARE(lookupsDoneCounter, COUNT);
+ QTRY_COMPARE_WITH_TIMEOUT(helper.lookupsDoneCounter, COUNT, 10s);
}
// this test is for the multi-threaded QHostInfo rewrite. It is about getting results at all,
@@ -644,19 +558,15 @@ void tst_QHostInfo::multipleDifferentLookups()
QFETCH(int, repeats);
const int COUNT = hostnameList.size();
- lookupsDoneCounter = 0;
+ tst_QHostInfo_Helper helper(QString{});
for (int i = 0; i < hostnameList.size(); i++)
- for (int j = 0; j < repeats; ++j)
- QHostInfo::lookupHost(hostnameList.at(i), this, SLOT(resultsReady(QHostInfo)));
-
- QElapsedTimer timer;
- timer.start();
- while (timer.elapsed() < 60000 && lookupsDoneCounter < repeats*COUNT) {
- QTestEventLoop::instance().enterLoop(2);
- //qDebug() << "t:" << timer.elapsed();
- }
- QCOMPARE(lookupsDoneCounter, repeats*COUNT);
+ for (int j = 0; j < repeats; ++j) {
+ helper.hostname = hostnameList.at(i);
+ helper.lookupHostOldStyle();
+ }
+
+ QTRY_COMPARE_WITH_TIMEOUT(helper.lookupsDoneCounter, repeats*COUNT, 60s);
}
void tst_QHostInfo::cache()
@@ -665,13 +575,12 @@ void tst_QHostInfo::cache()
if (!cache)
return; // test makes only sense when cache enabled
- // reset slot counter
- lookupsDoneCounter = 0;
+ tst_QHostInfo_Helper helper("localhost");
// lookup once, wait in event loop, result should not come directly.
bool valid = true;
int id = -1;
- QHostInfo result = qt_qhostinfo_lookup("localhost", this, SLOT(resultsReady(QHostInfo)), &valid, &id);
+ QHostInfo result = qt_qhostinfo_lookup(helper.hostname, &helper, SLOT(resultsReady(QHostInfo)), &valid, &id);
QTestEventLoop::instance().enterLoop(5);
QVERIFY(!QTestEventLoop::instance().timeout());
QVERIFY(!valid);
@@ -679,7 +588,7 @@ void tst_QHostInfo::cache()
// loopkup second time, result should come directly
valid = false;
- result = qt_qhostinfo_lookup("localhost", this, SLOT(resultsReady(QHostInfo)), &valid, &id);
+ result = qt_qhostinfo_lookup(helper.hostname, &helper, SLOT(resultsReady(QHostInfo)), &valid, &id);
QVERIFY(valid);
QVERIFY(!result.addresses().isEmpty());
@@ -688,17 +597,17 @@ void tst_QHostInfo::cache()
// lookup third time, result should not come directly.
valid = true;
- result = qt_qhostinfo_lookup("localhost", this, SLOT(resultsReady(QHostInfo)), &valid, &id);
+ result = qt_qhostinfo_lookup(helper.hostname, &helper, SLOT(resultsReady(QHostInfo)), &valid, &id);
QTestEventLoop::instance().enterLoop(5);
QVERIFY(!QTestEventLoop::instance().timeout());
QVERIFY(!valid);
QVERIFY(result.addresses().isEmpty());
// the slot should have been called 2 times.
- QCOMPARE(lookupsDoneCounter, 2);
+ QCOMPARE(helper.lookupsDoneCounter, 2);
}
-void tst_QHostInfo::resultsReady(const QHostInfo &hi)
+void tst_QHostInfo_Helper::resultsReady(const QHostInfo &hi)
{
QVERIFY(QThread::currentThread() == thread());
lookupDone = true;
@@ -709,16 +618,15 @@ void tst_QHostInfo::resultsReady(const QHostInfo &hi)
void tst_QHostInfo::abortHostLookup()
{
- //reset counter
- lookupsDoneCounter = 0;
+ tst_QHostInfo_Helper helper("a-single" TEST_DOMAIN);
bool valid = false;
int id = -1;
- QHostInfo result = qt_qhostinfo_lookup("a-single" TEST_DOMAIN, this, SLOT(resultsReady(QHostInfo)), &valid, &id);
+ QHostInfo result = qt_qhostinfo_lookup(helper.hostname, &helper, SLOT(resultsReady(QHostInfo)), &valid, &id);
QVERIFY(!valid);
//it is assumed that the DNS request/response in the backend is slower than it takes to call abort
QHostInfo::abortHostLookup(id);
QTestEventLoop::instance().enterLoop(5);
- QCOMPARE(lookupsDoneCounter, 0);
+ QCOMPARE(helper.lookupsDoneCounter, 0);
}
class LookupAborter : public QObject
diff --git a/tests/auto/network/kernel/qnetworkaddressentry/CMakeLists.txt b/tests/auto/network/kernel/qnetworkaddressentry/CMakeLists.txt
index bc9463aa13..02bf37880a 100644
--- a/tests/auto/network/kernel/qnetworkaddressentry/CMakeLists.txt
+++ b/tests/auto/network/kernel/qnetworkaddressentry/CMakeLists.txt
@@ -1,12 +1,19 @@
-# Generated from qnetworkaddressentry.pro.
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
#####################################################################
## tst_qnetworkaddressentry Test:
#####################################################################
+if(NOT QT_BUILD_STANDALONE_TESTS AND NOT QT_BUILDING_QT)
+ cmake_minimum_required(VERSION 3.16)
+ project(tst_qnetworkaddressentry LANGUAGES CXX)
+ find_package(Qt6BuildInternals REQUIRED COMPONENTS STANDALONE_TEST)
+endif()
+
qt_internal_add_test(tst_qnetworkaddressentry
SOURCES
tst_qnetworkaddressentry.cpp
- PUBLIC_LIBRARIES
+ LIBRARIES
Qt::Network
)
diff --git a/tests/auto/network/kernel/qnetworkaddressentry/tst_qnetworkaddressentry.cpp b/tests/auto/network/kernel/qnetworkaddressentry/tst_qnetworkaddressentry.cpp
index 097d53caf5..801eb58931 100644
--- a/tests/auto/network/kernel/qnetworkaddressentry/tst_qnetworkaddressentry.cpp
+++ b/tests/auto/network/kernel/qnetworkaddressentry/tst_qnetworkaddressentry.cpp
@@ -1,30 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
#include <QTest>
diff --git a/tests/auto/network/kernel/qnetworkdatagram/CMakeLists.txt b/tests/auto/network/kernel/qnetworkdatagram/CMakeLists.txt
index 13dcbcb2e3..5bfc2edc6a 100644
--- a/tests/auto/network/kernel/qnetworkdatagram/CMakeLists.txt
+++ b/tests/auto/network/kernel/qnetworkdatagram/CMakeLists.txt
@@ -1,12 +1,19 @@
-# Generated from qnetworkdatagram.pro.
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
#####################################################################
## tst_qnetworkdatagram Test:
#####################################################################
+if(NOT QT_BUILD_STANDALONE_TESTS AND NOT QT_BUILDING_QT)
+ cmake_minimum_required(VERSION 3.16)
+ project(tst_qnetworkdatagram LANGUAGES CXX)
+ find_package(Qt6BuildInternals REQUIRED COMPONENTS STANDALONE_TEST)
+endif()
+
qt_internal_add_test(tst_qnetworkdatagram
SOURCES
tst_qnetworkdatagram.cpp
- PUBLIC_LIBRARIES
+ LIBRARIES
Qt::Network
)
diff --git a/tests/auto/network/kernel/qnetworkdatagram/tst_qnetworkdatagram.cpp b/tests/auto/network/kernel/qnetworkdatagram/tst_qnetworkdatagram.cpp
index a15272caa6..df473133a6 100644
--- a/tests/auto/network/kernel/qnetworkdatagram/tst_qnetworkdatagram.cpp
+++ b/tests/auto/network/kernel/qnetworkdatagram/tst_qnetworkdatagram.cpp
@@ -1,30 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 Intel Corporation.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 Intel Corporation.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
#include <QNetworkDatagram>
#include <QTest>
diff --git a/tests/auto/network/kernel/qnetworkinformation/CMakeLists.txt b/tests/auto/network/kernel/qnetworkinformation/CMakeLists.txt
index f0c37913a8..354cefc993 100644
--- a/tests/auto/network/kernel/qnetworkinformation/CMakeLists.txt
+++ b/tests/auto/network/kernel/qnetworkinformation/CMakeLists.txt
@@ -1,6 +1,15 @@
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
+
+if(NOT QT_BUILD_STANDALONE_TESTS AND NOT QT_BUILDING_QT)
+ cmake_minimum_required(VERSION 3.16)
+ project(tst_qnetworkinformation LANGUAGES CXX)
+ find_package(Qt6BuildInternals REQUIRED COMPONENTS STANDALONE_TEST)
+endif()
+
qt_internal_add_test(tst_qnetworkinformation
SOURCES
tst_qnetworkinformation.cpp
- PUBLIC_LIBRARIES
+ LIBRARIES
Qt::NetworkPrivate
)
diff --git a/tests/auto/network/kernel/qnetworkinformation/tst_qnetworkinformation.cpp b/tests/auto/network/kernel/qnetworkinformation/tst_qnetworkinformation.cpp
index e37db514e3..daf81823e8 100644
--- a/tests/auto/network/kernel/qnetworkinformation/tst_qnetworkinformation.cpp
+++ b/tests/auto/network/kernel/qnetworkinformation/tst_qnetworkinformation.cpp
@@ -1,30 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2021 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2021 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
#include <QtNetwork/private/qnetworkinformation_p.h>
#include <QtNetwork/qnetworkinformation.h>
@@ -135,10 +110,10 @@ void tst_QNetworkInformation::initTestCase()
auto backends = QNetworkInformation::availableBackends();
QVERIFY(backends.size() > prevBackends.size());
QVERIFY(backends.contains(u"mock"));
- QVERIFY(QNetworkInformation::load(u"mock"));
- QVERIFY(QNetworkInformation::load(u"mock"));
- QVERIFY(QNetworkInformation::load(u"mOcK"));
- QVERIFY(!QNetworkInformation::load(u"mocks"));
+ QVERIFY(QNetworkInformation::loadBackendByName(u"mock"));
+ QVERIFY(QNetworkInformation::loadBackendByName(u"mock"));
+ QVERIFY(QNetworkInformation::loadBackendByName(u"mOcK"));
+ QVERIFY(!QNetworkInformation::loadBackendByName(u"mocks"));
}
void tst_QNetworkInformation::cleanupTestCase()
@@ -266,14 +241,14 @@ void tst_QNetworkInformation::isMetered()
QSignalSpy spy(info, &QNetworkInformation::isMeteredChanged);
QVERIFY(!info->isMetered());
MockBackend::setNewMetered(true);
- QCOMPARE(spy.count(), 1);
+ QCOMPARE(spy.size(), 1);
QVERIFY(info->isMetered());
QVERIFY(spy[0][0].toBool());
spy.clear();
// Set the same value again, signal should not be emitted again
MockBackend::setNewMetered(true);
- QCOMPARE(spy.count(), 0);
+ QCOMPARE(spy.size(), 0);
}
QTEST_MAIN(tst_QNetworkInformation);
diff --git a/tests/auto/network/kernel/qnetworkinformation_appless/CMakeLists.txt b/tests/auto/network/kernel/qnetworkinformation_appless/CMakeLists.txt
index 76cbf594c3..d4a2e486bd 100644
--- a/tests/auto/network/kernel/qnetworkinformation_appless/CMakeLists.txt
+++ b/tests/auto/network/kernel/qnetworkinformation_appless/CMakeLists.txt
@@ -1,6 +1,15 @@
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
+
+if(NOT QT_BUILD_STANDALONE_TESTS AND NOT QT_BUILDING_QT)
+ cmake_minimum_required(VERSION 3.16)
+ project(tst_qnetworkinformation_appless LANGUAGES CXX)
+ find_package(Qt6BuildInternals REQUIRED COMPONENTS STANDALONE_TEST)
+endif()
+
qt_internal_add_test(tst_qnetworkinformation_appless
SOURCES
tst_qnetworkinformation_appless.cpp
- PUBLIC_LIBRARIES
+ LIBRARIES
Qt::Network
)
diff --git a/tests/auto/network/kernel/qnetworkinformation_appless/tst_qnetworkinformation_appless.cpp b/tests/auto/network/kernel/qnetworkinformation_appless/tst_qnetworkinformation_appless.cpp
index ff058e8a9b..b08843314a 100644
--- a/tests/auto/network/kernel/qnetworkinformation_appless/tst_qnetworkinformation_appless.cpp
+++ b/tests/auto/network/kernel/qnetworkinformation_appless/tst_qnetworkinformation_appless.cpp
@@ -1,30 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2021 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2021 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
#include <QtCore/qcoreapplication.h>
#include <QtNetwork/qnetworkinformation.h>
@@ -48,7 +23,7 @@ void tst_QNetworkInformation_appless::reinit()
if (QNetworkInformation::availableBackends().isEmpty())
QSKIP("No backends available!");
- QVERIFY(QNetworkInformation::load(QNetworkInformation::Feature::Reachability));
+ QVERIFY(QNetworkInformation::loadDefaultBackend());
auto info = QNetworkInformation::instance();
QVERIFY(info);
}
@@ -57,7 +32,7 @@ void tst_QNetworkInformation_appless::reinit()
{
QCoreApplication app(argc, argv);
- QVERIFY(QNetworkInformation::load(QNetworkInformation::Feature::Reachability));
+ QVERIFY(QNetworkInformation::loadDefaultBackend());
auto info = QNetworkInformation::instance();
QVERIFY(info);
}
diff --git a/tests/auto/network/kernel/qnetworkinterface/CMakeLists.txt b/tests/auto/network/kernel/qnetworkinterface/CMakeLists.txt
index 0c667781e9..3e5dab63e0 100644
--- a/tests/auto/network/kernel/qnetworkinterface/CMakeLists.txt
+++ b/tests/auto/network/kernel/qnetworkinterface/CMakeLists.txt
@@ -1,12 +1,20 @@
-# Generated from qnetworkinterface.pro.
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
#####################################################################
## tst_qnetworkinterface Test:
#####################################################################
+if(NOT QT_BUILD_STANDALONE_TESTS AND NOT QT_BUILDING_QT)
+ cmake_minimum_required(VERSION 3.16)
+ project(tst_qnetworkinterface LANGUAGES CXX)
+ find_package(Qt6BuildInternals REQUIRED COMPONENTS STANDALONE_TEST)
+endif()
+
qt_internal_add_test(tst_qnetworkinterface
SOURCES
tst_qnetworkinterface.cpp
- PUBLIC_LIBRARIES
- Qt::Network
+ LIBRARIES
+ Qt::NetworkPrivate
+ QT_TEST_SERVER_LIST "apache2"
)
diff --git a/tests/auto/network/kernel/qnetworkinterface/tst_qnetworkinterface.cpp b/tests/auto/network/kernel/qnetworkinterface/tst_qnetworkinterface.cpp
index e18c50afbd..141ca25021 100644
--- a/tests/auto/network/kernel/qnetworkinterface/tst_qnetworkinterface.cpp
+++ b/tests/auto/network/kernel/qnetworkinterface/tst_qnetworkinterface.cpp
@@ -1,41 +1,18 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Copyright (C) 2016 Intel Corporation.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
+// Copyright (C) 2016 The Qt Company Ltd.
+// Copyright (C) 2016 Intel Corporation.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
#include <QTest>
#include <QtEndian>
+#include <QSet>
#include <qcoreapplication.h>
#include <qnetworkinterface.h>
#include <qudpsocket.h>
#include "../../../network-settings.h"
+#include <private/qtnetwork-config_p.h>
+
Q_DECLARE_METATYPE(QHostAddress)
class tst_QNetworkInterface : public QObject
@@ -59,6 +36,8 @@ private slots:
void interfaceFromXXX_data();
void interfaceFromXXX();
void copyInvalidInterface();
+private:
+ bool hasNetworkServer = false;
};
tst_QNetworkInterface::tst_QNetworkInterface()
@@ -71,22 +50,29 @@ tst_QNetworkInterface::~tst_QNetworkInterface()
bool tst_QNetworkInterface::isIPv6Working()
{
- QUdpSocket socket;
- socket.connectToHost(QHostAddress::LocalHostIPv6, 1234);
- return socket.state() == QAbstractSocket::ConnectedState || socket.waitForConnected(100);
+ // QNetworkInterface may be unable to detect IPv6 addresses even if they
+ // are there, due to limitations of the implementation.
+ if (QOperatingSystemVersion::currentType() == QOperatingSystemVersion::Windows ||
+ QT_CONFIG(linux_netlink) || (QT_CONFIG(getifaddrs) && QT_CONFIG(ipv6ifname))) {
+ return QtNetworkSettings::hasIPv6();
+ }
+ return false;
}
void tst_QNetworkInterface::initTestCase()
{
- if (!QtNetworkSettings::verifyTestNetworkSettings())
- QSKIP("No network test server available");
+#ifdef QT_TEST_SERVER
+ hasNetworkServer = QtNetworkSettings::verifyConnection(QtNetworkSettings::httpServerName(), 80);
+#else
+ hasNetworkServer = QtNetworkSettings::verifyTestNetworkSettings();
+#endif
}
void tst_QNetworkInterface::dump()
{
// This is for manual testing:
- QList<QNetworkInterface> allInterfaces = QNetworkInterface::allInterfaces();
- foreach (const QNetworkInterface &i, allInterfaces) {
+ const QList<QNetworkInterface> allInterfaces = QNetworkInterface::allInterfaces();
+ for (const QNetworkInterface &i : allInterfaces) {
QString flags;
if (i.flags() & QNetworkInterface::IsUp) flags += "Up,";
if (i.flags() & QNetworkInterface::IsRunning) flags += "Running,";
@@ -113,7 +99,8 @@ void tst_QNetworkInterface::dump()
qDebug() << " MTU: " << i.maximumTransmissionUnit();
int count = 0;
- foreach (const QNetworkAddressEntry &e, i.addressEntries()) {
+ const auto entries = i.addressEntries();
+ for (const QNetworkAddressEntry &e : entries) {
QDebug s = qDebug();
s.nospace() << " address "
<< qSetFieldWidth(2) << count++ << qSetFieldWidth(0);
@@ -139,11 +126,11 @@ void tst_QNetworkInterface::dump()
void tst_QNetworkInterface::consistencyCheck()
{
- QList<QNetworkInterface> ifaces = QNetworkInterface::allInterfaces();
+ const QList<QNetworkInterface> ifaces = QNetworkInterface::allInterfaces();
QSet<QString> interfaceNames;
QList<int> interfaceIndexes;
- foreach (const QNetworkInterface &iface, ifaces) {
+ for (const QNetworkInterface &iface : ifaces) {
QVERIFY(iface.isValid());
QVERIFY2(!interfaceNames.contains(iface.name()),
"duplicate name = " + iface.name().toLocal8Bit());
@@ -189,7 +176,8 @@ void tst_QNetworkInterface::localAddress_data()
if (ipv6)
QTest::newRow("localhost-ipv6") << QHostAddress(QHostAddress::LocalHostIPv6);
- QTest::newRow("test-server") << QtNetworkSettings::serverIP();
+ if (hasNetworkServer)
+ QTest::newRow("test-server") << QtNetworkSettings::httpServerIp();
QSet<QHostAddress> added;
const QList<QNetworkInterface> ifaces = QNetworkInterface::allInterfaces();
@@ -263,10 +251,10 @@ void tst_QNetworkInterface::interfaceFromXXX_data()
{
QTest::addColumn<QNetworkInterface>("iface");
- QList<QNetworkInterface> allInterfaces = QNetworkInterface::allInterfaces();
- if (allInterfaces.count() == 0)
+ const QList<QNetworkInterface> allInterfaces = QNetworkInterface::allInterfaces();
+ if (allInterfaces.size() == 0)
QSKIP("No interfaces to test!");
- foreach (QNetworkInterface iface, allInterfaces)
+ for (const QNetworkInterface &iface : allInterfaces)
QTest::newRow(iface.name().toLocal8Bit()) << iface;
}
@@ -280,7 +268,8 @@ void tst_QNetworkInterface::interfaceFromXXX()
QCOMPARE(QNetworkInterface::interfaceNameFromIndex(idx), iface.name());
QCOMPARE(QNetworkInterface::interfaceIndexFromName(iface.name()), idx);
}
- foreach (QNetworkAddressEntry entry, iface.addressEntries()) {
+ const auto entries = iface.addressEntries();
+ for (const QNetworkAddressEntry &entry : entries) {
QVERIFY(!entry.ip().isNull());
if (!entry.netmask().isNull()) {
diff --git a/tests/auto/network/kernel/qnetworkproxy/CMakeLists.txt b/tests/auto/network/kernel/qnetworkproxy/CMakeLists.txt
index 40650726a7..629bfb0a8a 100644
--- a/tests/auto/network/kernel/qnetworkproxy/CMakeLists.txt
+++ b/tests/auto/network/kernel/qnetworkproxy/CMakeLists.txt
@@ -1,12 +1,19 @@
-# Generated from qnetworkproxy.pro.
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
#####################################################################
## tst_qnetworkproxy Test:
#####################################################################
+if(NOT QT_BUILD_STANDALONE_TESTS AND NOT QT_BUILDING_QT)
+ cmake_minimum_required(VERSION 3.16)
+ project(tst_qnetworkproxy LANGUAGES CXX)
+ find_package(Qt6BuildInternals REQUIRED COMPONENTS STANDALONE_TEST)
+endif()
+
qt_internal_add_test(tst_qnetworkproxy
SOURCES
tst_qnetworkproxy.cpp
- PUBLIC_LIBRARIES
+ LIBRARIES
Qt::Network
)
diff --git a/tests/auto/network/kernel/qnetworkproxy/tst_qnetworkproxy.cpp b/tests/auto/network/kernel/qnetworkproxy/tst_qnetworkproxy.cpp
index 5ec60fb5b2..1f00f8d054 100644
--- a/tests/auto/network/kernel/qnetworkproxy/tst_qnetworkproxy.cpp
+++ b/tests/auto/network/kernel/qnetworkproxy/tst_qnetworkproxy.cpp
@@ -1,30 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
#include <QTest>
diff --git a/tests/auto/network/kernel/qnetworkproxyfactory/BLACKLIST b/tests/auto/network/kernel/qnetworkproxyfactory/BLACKLIST
deleted file mode 100644
index 6e9d9ffdec..0000000000
--- a/tests/auto/network/kernel/qnetworkproxyfactory/BLACKLIST
+++ /dev/null
@@ -1,3 +0,0 @@
-# QTBUG-87385
-[genericSystemProxy]
-android
diff --git a/tests/auto/network/kernel/qnetworkproxyfactory/CMakeLists.txt b/tests/auto/network/kernel/qnetworkproxyfactory/CMakeLists.txt
index e9e2d8ae0b..41dae6a02a 100644
--- a/tests/auto/network/kernel/qnetworkproxyfactory/CMakeLists.txt
+++ b/tests/auto/network/kernel/qnetworkproxyfactory/CMakeLists.txt
@@ -1,12 +1,19 @@
-# Generated from qnetworkproxyfactory.pro.
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
#####################################################################
## tst_qnetworkproxyfactory Test:
#####################################################################
+if(NOT QT_BUILD_STANDALONE_TESTS AND NOT QT_BUILDING_QT)
+ cmake_minimum_required(VERSION 3.16)
+ project(tst_qnetworkproxyfactory LANGUAGES CXX)
+ find_package(Qt6BuildInternals REQUIRED COMPONENTS STANDALONE_TEST)
+endif()
+
qt_internal_add_test(tst_qnetworkproxyfactory
SOURCES
tst_qnetworkproxyfactory.cpp
- PUBLIC_LIBRARIES
+ LIBRARIES
Qt::NetworkPrivate
)
diff --git a/tests/auto/network/kernel/qnetworkproxyfactory/tst_qnetworkproxyfactory.cpp b/tests/auto/network/kernel/qnetworkproxyfactory/tst_qnetworkproxyfactory.cpp
index 8b64788a73..c38a480766 100644
--- a/tests/auto/network/kernel/qnetworkproxyfactory/tst_qnetworkproxyfactory.cpp
+++ b/tests/auto/network/kernel/qnetworkproxyfactory/tst_qnetworkproxyfactory.cpp
@@ -1,31 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
#include <QtTest/QTest>
#include <QtTest/QTestEventLoop>
@@ -119,7 +93,8 @@ void tst_QNetworkProxyFactory::systemProxyForQuery_data()
QTest::newRow("autobind-server") << (int)QNetworkProxyQuery::TcpServer << QUrl() << QString() << QString() << 0 << (int)QNetworkProxy::ListeningCapability;
QTest::newRow("web-server") << (int)QNetworkProxyQuery::TcpServer << QUrl() << QString() << QString() << 80 << (int)QNetworkProxy::ListeningCapability;
//windows: these should be bypassed if "bypass proxy server for local addresses" is ticked
- foreach (QHostAddress address, QNetworkInterface::allAddresses()) {
+ const auto addresses = QNetworkInterface::allAddresses();
+ for (const QHostAddress &address : addresses) {
QTest::newRow(qPrintable(address.toString())) << (int)QNetworkProxyQuery::TcpSocket << QUrl() << QString() << address.toString() << 0 << 0;
}
@@ -172,16 +147,15 @@ void tst_QNetworkProxyFactory::systemProxyForQuery() const
QElapsedTimer sw;
sw.start();
- QList<QNetworkProxy> systemProxyList = QNetworkProxyFactory::systemProxyForQuery(query);
+ const QList<QNetworkProxy> systemProxyList = QNetworkProxyFactory::systemProxyForQuery(query);
qDebug() << sw.elapsed() << "ms";
QVERIFY(!systemProxyList.isEmpty());
// for manual comparison with system
qDebug() << systemProxyList;
- foreach (const QNetworkProxy &proxy, systemProxyList) {
+ for (const QNetworkProxy &proxy : systemProxyList)
QVERIFY((requiredCapabilities == 0) || (proxy.capabilities() & requiredCapabilities));
- }
}
void tst_QNetworkProxyFactory::systemProxyForQuery_local()
@@ -256,8 +230,6 @@ void tst_QNetworkProxyFactory::genericSystemProxy()
QFETCH(QString, hostName);
QFETCH(int, port);
-// We can only use the generic system proxy where available:
-#if !defined(Q_OS_WIN) && !defined(Q_OS_MACOS) && !QT_CONFIG(libproxy)
qputenv(envVar, url);
const QList<QNetworkProxy> systemProxy = QNetworkProxyFactory::systemProxyForQuery();
QCOMPARE(systemProxy.size(), 1);
@@ -265,18 +237,14 @@ void tst_QNetworkProxyFactory::genericSystemProxy()
QCOMPARE(systemProxy.first().hostName(), hostName);
QCOMPARE(systemProxy.first().port(), static_cast<quint16>(port));
qunsetenv(envVar);
-#else
- Q_UNUSED(envVar);
- Q_UNUSED(url);
- Q_UNUSED(proxyType);
- Q_UNUSED(hostName);
- Q_UNUSED(port);
- QSKIP("Generic system proxy not available on this platform.");
-#endif
}
void tst_QNetworkProxyFactory::genericSystemProxy_data()
{
+ // We can only use the generic system proxy where available:
+#if defined(Q_OS_WIN) || defined(Q_OS_MACOS) || defined(Q_OS_ANDROID) || QT_CONFIG(libproxy)
+ QSKIP("Generic system proxy not available on this platform.");
+#else
QTest::addColumn<QByteArray>("envVar");
QTest::addColumn<QByteArray>("url");
QTest::addColumn<QNetworkProxy::ProxyType>("proxyType");
@@ -289,6 +257,7 @@ void tst_QNetworkProxyFactory::genericSystemProxy_data()
<< QNetworkProxy::Socks5Proxy << QString("127.0.0.1") << 4242;
QTest::newRow("http") << QByteArray("http_proxy") << QByteArray("http://example.com:666")
<< QNetworkProxy::HttpProxy << QString("example.com") << 666;
+#endif
}
class QSPFQThread : public QThread
diff --git a/tests/auto/network/selftest/tst_networkselftest.cpp b/tests/auto/network/selftest/tst_networkselftest.cpp
index 501a86c78d..4288a65a37 100644
--- a/tests/auto/network/selftest/tst_networkselftest.cpp
+++ b/tests/auto/network/selftest/tst_networkselftest.cpp
@@ -1,30 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2020 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2020 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
#include <QTest>
diff --git a/tests/auto/network/socket/CMakeLists.txt b/tests/auto/network/socket/CMakeLists.txt
index 6e4421aad8..c3f8e8f87f 100644
--- a/tests/auto/network/socket/CMakeLists.txt
+++ b/tests/auto/network/socket/CMakeLists.txt
@@ -1,4 +1,5 @@
-# Generated from socket.pro.
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
if(QT_FEATURE_private_tests)
add_subdirectory(qhttpsocketengine)
@@ -9,9 +10,9 @@ endif()
add_subdirectory(qudpsocket)
add_subdirectory(qabstractsocket)
if(NOT ANDROID)
- # QTBUG-87387 # special case
+ # QTBUG-87387
add_subdirectory(qlocalsocket)
- # QTBUG-87388 # special case
+ # QTBUG-87388
add_subdirectory(qtcpserver)
endif()
if(QT_FEATURE_sctp)
diff --git a/tests/auto/network/socket/platformsocketengine/BLACKLIST b/tests/auto/network/socket/platformsocketengine/BLACKLIST
index f1f88d26d1..796f81a02a 100644
--- a/tests/auto/network/socket/platformsocketengine/BLACKLIST
+++ b/tests/auto/network/socket/platformsocketengine/BLACKLIST
@@ -1,11 +1,2 @@
[tcpLoopbackPerformance]
-windows-10 msvc-2015
-windows-7sp1
-[receiveUrgentData]
-windows-10 msvc-2015
-windows-7sp1
-[serverTest]
-windows-10 msvc-2015
-windows-7sp1
-[tcpLoopbackPerformance]
windows
diff --git a/tests/auto/network/socket/platformsocketengine/CMakeLists.txt b/tests/auto/network/socket/platformsocketengine/CMakeLists.txt
index cfd8a118ca..891041df04 100644
--- a/tests/auto/network/socket/platformsocketengine/CMakeLists.txt
+++ b/tests/auto/network/socket/platformsocketengine/CMakeLists.txt
@@ -1,4 +1,11 @@
-# Generated from platformsocketengine.pro.
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
+
+if(NOT QT_BUILD_STANDALONE_TESTS AND NOT QT_BUILDING_QT)
+ cmake_minimum_required(VERSION 3.16)
+ project(tst_platformsocketengine LANGUAGES CXX)
+ find_package(Qt6BuildInternals REQUIRED COMPONENTS STANDALONE_TEST)
+endif()
if(NOT QT_FEATURE_private_tests)
return()
@@ -11,19 +18,16 @@ endif()
qt_internal_add_test(tst_platformsocketengine
SOURCES
tst_platformsocketengine.cpp
- PUBLIC_LIBRARIES
+ LIBRARIES
Qt::CorePrivate
Qt::NetworkPrivate
+ QT_TEST_SERVER_LIST "cyrus"
)
-#### Keys ignored in scope 1:.:.:platformsocketengine.pro:<TRUE>:
-# MOC_DIR = "tmp"
-# _REQUIREMENTS = "qtConfig(private_tests)"
-
## Scopes:
#####################################################################
qt_internal_extend_target(tst_platformsocketengine CONDITION WIN32
- PUBLIC_LIBRARIES
+ LIBRARIES
ws2_32
)
diff --git a/tests/auto/network/socket/platformsocketengine/tst_platformsocketengine.cpp b/tests/auto/network/socket/platformsocketengine/tst_platformsocketengine.cpp
index 23566a3d70..1f6ecf9200 100644
--- a/tests/auto/network/socket/platformsocketengine/tst_platformsocketengine.cpp
+++ b/tests/auto/network/socket/platformsocketengine/tst_platformsocketengine.cpp
@@ -1,31 +1,6 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Copyright (C) 2016 Intel Corporation.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// Copyright (C) 2016 Intel Corporation.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
#include <QtTest/QTest>
@@ -48,7 +23,7 @@
#define PLATFORMSOCKETENGINE QNativeSocketEngine
#define PLATFORMSOCKETENGINESTRING "QNativeSocketEngine"
-#include <private/qnativesocketengine_p.h>
+#include <private/qnativesocketengine_p_p.h>
#include <qstringlist.h>
@@ -81,8 +56,12 @@ private slots:
void tst_PlatformSocketEngine::initTestCase()
{
+#ifdef QT_TEST_SERVER
+ QVERIFY(QtNetworkSettings::verifyConnection(QtNetworkSettings::imapServerName(), 143));
+#else
if (!QtNetworkSettings::verifyTestNetworkSettings())
QSKIP("No network test server available");
+#endif
}
//---------------------------------------------------------------------------
@@ -122,14 +101,14 @@ void tst_PlatformSocketEngine::simpleConnectToIMAP()
QVERIFY(socketDevice.initialize(QAbstractSocket::TcpSocket, QAbstractSocket::IPv4Protocol));
QCOMPARE(socketDevice.state(), QAbstractSocket::UnconnectedState);
- const bool isConnected = socketDevice.connectToHost(QtNetworkSettings::serverIP(), 143);
+ const bool isConnected = socketDevice.connectToHost(QtNetworkSettings::imapServerIp(), 143);
if (!isConnected) {
QCOMPARE(socketDevice.state(), QAbstractSocket::ConnectingState);
QVERIFY(socketDevice.waitForWrite());
QCOMPARE(socketDevice.state(), QAbstractSocket::ConnectedState);
}
QCOMPARE(socketDevice.state(), QAbstractSocket::ConnectedState);
- QCOMPARE(socketDevice.peerAddress(), QtNetworkSettings::serverIP());
+ QCOMPARE(socketDevice.peerAddress(), QtNetworkSettings::imapServerIp());
// Wait for the greeting
QVERIFY(socketDevice.waitForRead());
@@ -276,7 +255,7 @@ void tst_PlatformSocketEngine::broadcastTest()
PLATFORMSOCKETENGINE broadcastSocket;
// Initialize a regular Udp socket
- QVERIFY(broadcastSocket.initialize(QAbstractSocket::UdpSocket, QAbstractSocket::AnyIPProtocol));
+ QVERIFY(broadcastSocket.initialize(QAbstractSocket::UdpSocket, QAbstractSocket::IPv4Protocol));
// Bind to any port on all interfaces
QVERIFY(broadcastSocket.bind(QHostAddress::Any, 0));
@@ -567,7 +546,7 @@ void tst_PlatformSocketEngine::networkError()
QVERIFY(client.initialize(QAbstractSocket::TcpSocket, QAbstractSocket::IPv4Protocol));
- const bool isConnected = client.connectToHost(QtNetworkSettings::serverIP(), 143);
+ const bool isConnected = client.connectToHost(QtNetworkSettings::imapServerIp(), 143);
if (!isConnected) {
QCOMPARE(client.state(), QAbstractSocket::ConnectingState);
QVERIFY(client.waitForWrite());
diff --git a/tests/auto/network/socket/qabstractsocket/CMakeLists.txt b/tests/auto/network/socket/qabstractsocket/CMakeLists.txt
index ee83261ab0..3ca18aceef 100644
--- a/tests/auto/network/socket/qabstractsocket/CMakeLists.txt
+++ b/tests/auto/network/socket/qabstractsocket/CMakeLists.txt
@@ -1,12 +1,19 @@
-# Generated from qabstractsocket.pro.
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
#####################################################################
## tst_qabstractsocket Test:
#####################################################################
+if(NOT QT_BUILD_STANDALONE_TESTS AND NOT QT_BUILDING_QT)
+ cmake_minimum_required(VERSION 3.16)
+ project(tst_qabstractsocket LANGUAGES CXX)
+ find_package(Qt6BuildInternals REQUIRED COMPONENTS STANDALONE_TEST)
+endif()
+
qt_internal_add_test(tst_qabstractsocket
SOURCES
tst_qabstractsocket.cpp
- PUBLIC_LIBRARIES
+ LIBRARIES
Qt::Network
)
diff --git a/tests/auto/network/socket/qabstractsocket/tst_qabstractsocket.cpp b/tests/auto/network/socket/qabstractsocket/tst_qabstractsocket.cpp
index bb5e8090f8..6b038acdfa 100644
--- a/tests/auto/network/socket/qabstractsocket/tst_qabstractsocket.cpp
+++ b/tests/auto/network/socket/qabstractsocket/tst_qabstractsocket.cpp
@@ -1,30 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
#include <QTest>
diff --git a/tests/auto/network/socket/qhttpsocketengine/BLACKLIST b/tests/auto/network/socket/qhttpsocketengine/BLACKLIST
index ceb3b7862e..e0cd701636 100644
--- a/tests/auto/network/socket/qhttpsocketengine/BLACKLIST
+++ b/tests/auto/network/socket/qhttpsocketengine/BLACKLIST
@@ -1,5 +1,2 @@
-[downloadBigFile]
-windows-10 msvc-2015
-windows-7sp1
[ensureEofTriggersNotification]
windows
diff --git a/tests/auto/network/socket/qhttpsocketengine/CMakeLists.txt b/tests/auto/network/socket/qhttpsocketengine/CMakeLists.txt
index fcad653783..6b4f904725 100644
--- a/tests/auto/network/socket/qhttpsocketengine/CMakeLists.txt
+++ b/tests/auto/network/socket/qhttpsocketengine/CMakeLists.txt
@@ -1,4 +1,11 @@
-# Generated from qhttpsocketengine.pro.
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
+
+if(NOT QT_BUILD_STANDALONE_TESTS AND NOT QT_BUILDING_QT)
+ cmake_minimum_required(VERSION 3.16)
+ project(tst_qhttpsocketengine LANGUAGES CXX)
+ find_package(Qt6BuildInternals REQUIRED COMPONENTS STANDALONE_TEST)
+endif()
if(NOT QT_FEATURE_private_tests)
return()
@@ -11,23 +18,18 @@ endif()
qt_internal_add_test(tst_qhttpsocketengine
SOURCES
tst_qhttpsocketengine.cpp
- PUBLIC_LIBRARIES
+ LIBRARIES
Qt::CorePrivate
Qt::NetworkPrivate
- QT_TEST_SERVER_LIST "squid" "danted" "cyrus" "apache2" # special case
+ QT_TEST_SERVER_LIST "squid" "danted" "cyrus" "apache2"
)
-#### Keys ignored in scope 1:.:.:qhttpsocketengine.pro:<TRUE>:
-# MOC_DIR = "tmp"
-# _REQUIREMENTS = "qtConfig(private_tests)"
-
## Scopes:
#####################################################################
-#### Keys ignored in scope 2:.:.:qhttpsocketengine.pro:LINUX:
# QT_TEST_SERVER_LIST = "squid" "danted" "cyrus" "apache2"
qt_internal_extend_target(tst_qhttpsocketengine CONDITION WIN32
- PUBLIC_LIBRARIES
+ LIBRARIES
ws2_32
)
diff --git a/tests/auto/network/socket/qhttpsocketengine/tst_qhttpsocketengine.cpp b/tests/auto/network/socket/qhttpsocketengine/tst_qhttpsocketengine.cpp
index 2d0d9f5ffc..a52099b5b4 100644
--- a/tests/auto/network/socket/qhttpsocketengine/tst_qhttpsocketengine.cpp
+++ b/tests/auto/network/socket/qhttpsocketengine/tst_qhttpsocketengine.cpp
@@ -1,30 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
#include <QtTest/QTest>
@@ -43,6 +18,8 @@
#include "../../../network-settings.h"
+using namespace std::chrono_literals;
+
class tst_QHttpSocketEngine : public QObject
{
Q_OBJECT
@@ -108,9 +85,9 @@ public slots:
int idx = client->property("dataTransmitionIdx").toInt();
if (receivedData.contains("\r\n\r\n") ||
receivedData.contains("\n\n")) {
- if (idx < dataToTransmit.length())
+ if (idx < dataToTransmit.size())
client->write(dataToTransmit.at(idx++));
- if (idx == dataToTransmit.length()) {
+ if (idx == dataToTransmit.size()) {
client->disconnectFromHost();
disconnect(client, 0, this, 0);
client = 0;
@@ -348,7 +325,7 @@ void tst_QHttpSocketEngine::simpleErrorsAndStates()
QCOMPARE(socketDevice.state(), QAbstractSocket::UnconnectedState);
QVERIFY(!socketDevice.connectToHost(QHostAddress(QtNetworkSettings::socksProxyServerName()), 8088));
QCOMPARE(socketDevice.state(), QAbstractSocket::ConnectingState);
- if (socketDevice.waitForWrite(30000)) {
+ if (socketDevice.waitForWrite(30s)) {
QVERIFY(socketDevice.state() == QAbstractSocket::ConnectedState ||
socketDevice.state() == QAbstractSocket::UnconnectedState);
} else {
diff --git a/tests/auto/network/socket/qlocalsocket/BLACKLIST b/tests/auto/network/socket/qlocalsocket/BLACKLIST
index cec50425c5..730b7e6d2f 100644
--- a/tests/auto/network/socket/qlocalsocket/BLACKLIST
+++ b/tests/auto/network/socket/qlocalsocket/BLACKLIST
@@ -3,5 +3,8 @@
android
[processConnection]
android
+windows
[verifySocketOptions]
android
+[threadedConnection]
+windows
diff --git a/tests/auto/network/socket/qlocalsocket/CMakeLists.txt b/tests/auto/network/socket/qlocalsocket/CMakeLists.txt
index b0eca25191..4b886a02ee 100644
--- a/tests/auto/network/socket/qlocalsocket/CMakeLists.txt
+++ b/tests/auto/network/socket/qlocalsocket/CMakeLists.txt
@@ -1,14 +1,22 @@
-# Generated from qlocalsocket.pro.
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
+
+if(NOT QT_BUILD_STANDALONE_TESTS AND NOT QT_BUILDING_QT)
+ cmake_minimum_required(VERSION 3.16)
+ project(tst_qlocalsocket LANGUAGES CXX)
+ find_package(Qt6BuildInternals REQUIRED COMPONENTS STANDALONE_TEST)
+endif()
-# add_subdirectory(test) # special case remove
add_subdirectory(socketprocess)
+
qt_internal_add_test(tst_qlocalsocket
SOURCES
tst_qlocalsocket.cpp
DEFINES
QLOCALSERVER_DEBUG
QLOCALSOCKET_DEBUG
- PUBLIC_LIBRARIES
+ LIBRARIES
Qt::Network
+ Qt::TestPrivate
)
-# special case end
+add_dependencies(tst_qlocalsocket socketprocess)
diff --git a/tests/auto/network/socket/qlocalsocket/socketprocess/CMakeLists.txt b/tests/auto/network/socket/qlocalsocket/socketprocess/CMakeLists.txt
index adf1752ac0..3e0476d2b6 100644
--- a/tests/auto/network/socket/qlocalsocket/socketprocess/CMakeLists.txt
+++ b/tests/auto/network/socket/qlocalsocket/socketprocess/CMakeLists.txt
@@ -1,4 +1,5 @@
-# Generated from socketprocess.pro.
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
#####################################################################
## socketprocess Binary:
@@ -8,7 +9,7 @@ qt_internal_add_executable(socketprocess
OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/"
SOURCES
main.cpp
- PUBLIC_LIBRARIES
+ LIBRARIES
Qt::Network
Qt::Test
)
diff --git a/tests/auto/network/socket/qlocalsocket/socketprocess/main.cpp b/tests/auto/network/socket/qlocalsocket/socketprocess/main.cpp
index 272e837ac5..d254253aca 100644
--- a/tests/auto/network/socket/qlocalsocket/socketprocess/main.cpp
+++ b/tests/auto/network/socket/qlocalsocket/socketprocess/main.cpp
@@ -1,30 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
#include <qcoreapplication.h>
diff --git a/tests/auto/network/socket/qlocalsocket/tst_qlocalsocket.cpp b/tests/auto/network/socket/qlocalsocket/tst_qlocalsocket.cpp
index ed665253da..1ecd871ceb 100644
--- a/tests/auto/network/socket/qlocalsocket/tst_qlocalsocket.cpp
+++ b/tests/auto/network/socket/qlocalsocket/tst_qlocalsocket.cpp
@@ -1,35 +1,11 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Copyright (C) 2016 Intel Corporation.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// Copyright (C) 2016 Intel Corporation.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
#include <QTest>
#include <QSignalSpy>
+#include <QtTest/private/qpropertytesthelper_p.h>
#if QT_CONFIG(process)
#include <QProcess>
#endif
@@ -148,6 +124,7 @@ private slots:
void verifyListenWithDescriptor_data();
void serverBindingsAndProperties();
+ void socketBindings();
protected slots:
void socketClosedSlot();
@@ -162,14 +139,13 @@ tst_QLocalSocket::tst_QLocalSocket()
qRegisterMetaType<QFile::Permissions>("QFile::Permissions");
}
-class LocalServer : public QLocalServer
+class CrashSafeLocalServer : public QLocalServer
{
Q_OBJECT
public:
- LocalServer() : QLocalServer()
+ CrashSafeLocalServer() : QLocalServer()
{
- connect(this, SIGNAL(newConnection()), this, SLOT(slotNewConnection()));
}
bool listen(const QString &name)
@@ -178,6 +154,19 @@ public:
return QLocalServer::listen(name);
}
+ bool listen(qintptr socketDescriptor) { return QLocalServer::listen(socketDescriptor); }
+};
+
+class LocalServer : public CrashSafeLocalServer
+{
+ Q_OBJECT
+
+public:
+ LocalServer() : CrashSafeLocalServer()
+ {
+ connect(this, SIGNAL(newConnection()), this, SLOT(slotNewConnection()));
+ }
+
QList<int> hits;
protected:
@@ -258,8 +247,8 @@ void tst_QLocalSocket::server_basic()
QVERIFY(!timedOut);
QCOMPARE(server.listen(QString()), false);
- QCOMPARE(server.hits.count(), 0);
- QCOMPARE(spyNewConnection.count(), 0);
+ QCOMPARE(server.hits.size(), 0);
+ QCOMPARE(spyNewConnection.size(), 0);
}
void tst_QLocalSocket::server_connectionsCount()
@@ -300,11 +289,11 @@ void tst_QLocalSocket::socket_basic()
QCOMPARE(socket.waitForDisconnected(0), false);
QCOMPARE(socket.waitForReadyRead(0), false);
- QCOMPARE(spyConnected.count(), 0);
- QCOMPARE(spyDisconnected.count(), 0);
- QCOMPARE(spyError.count(), 0);
- QCOMPARE(spyStateChanged.count(), 0);
- QCOMPARE(spyReadyRead.count(), 0);
+ QCOMPARE(spyConnected.size(), 0);
+ QCOMPARE(spyDisconnected.size(), 0);
+ QCOMPARE(spyError.size(), 0);
+ QCOMPARE(spyStateChanged.size(), 0);
+ QCOMPARE(spyReadyRead.size(), 0);
}
void tst_QLocalSocket::listen_data()
@@ -313,8 +302,8 @@ void tst_QLocalSocket::listen_data()
QTest::addColumn<bool>("canListen");
QTest::addColumn<bool>("close");
QTest::newRow("null") << QString() << false << false;
- QTest::newRow("tst_localsocket") << "tst_localsocket" << true << true;
- QTest::newRow("tst_localsocket") << "tst_localsocket" << true << false;
+ QTest::newRow("tst_localsocket,close") << "tst_localsocket" << true << true;
+ QTest::newRow("tst_localsocket,no-close") << "tst_localsocket" << true << false;
}
// start a server that listens, but don't connect a socket, make sure everything is in order
@@ -326,7 +315,7 @@ void tst_QLocalSocket::listen()
QFETCH(QString, name);
QFETCH(bool, canListen);
QFETCH(bool, close);
- QVERIFY2((server.listen(name) == canListen), server.errorString().toLatin1().constData());
+ QVERIFY2((server.listen(name) == canListen), qUtf8Printable(server.errorString()));
// test listening
QCOMPARE(server.serverName(), name);
@@ -334,8 +323,8 @@ void tst_QLocalSocket::listen()
QCOMPARE(server.isListening(), canListen);
QCOMPARE(server.hasPendingConnections(), false);
QCOMPARE(server.nextPendingConnection(), (QLocalSocket*)0);
- QCOMPARE(server.hits.count(), 0);
- QCOMPARE(spyNewConnection.count(), 0);
+ QCOMPARE(server.hits.size(), 0);
+ QCOMPARE(spyNewConnection.size(), 0);
if (canListen) {
QVERIFY(server.errorString().isEmpty());
QCOMPARE(server.serverError(), QAbstractSocket::UnknownSocketError);
@@ -409,7 +398,7 @@ void tst_QLocalSocket::listenAndConnect()
QCOMPARE(socket->error(), QLocalSocket::UnknownSocketError);
QCOMPARE(socket->state(), QLocalSocket::ConnectedState);
//QVERIFY(socket->socketDescriptor() != -1);
- QCOMPARE(spyError.count(), 0);
+ QCOMPARE(spyError.size(), 0);
} else {
QVERIFY(!socket->errorString().isEmpty());
QVERIFY(socket->error() != QLocalSocket::UnknownSocketError);
@@ -428,13 +417,13 @@ void tst_QLocalSocket::listenAndConnect()
QCOMPARE(socket->waitForConnected(0), canListen);
QCOMPARE(socket->waitForReadyRead(0), false);
- QTRY_COMPARE(spyConnected.count(), canListen ? 1 : 0);
- QCOMPARE(spyDisconnected.count(), 0);
+ QTRY_COMPARE(spyConnected.size(), canListen ? 1 : 0);
+ QCOMPARE(spyDisconnected.size(), 0);
// error signals
- QVERIFY(spyError.count() >= 0);
+ QVERIFY(spyError.size() >= 0);
if (canListen) {
- if (spyError.count() > 0)
+ if (spyError.size() > 0)
QCOMPARE(qvariant_cast<QLocalSocket::LocalSocketError>(spyError.first()[0]),
QLocalSocket::SocketTimeoutError);
} else {
@@ -449,8 +438,8 @@ void tst_QLocalSocket::listenAndConnect()
if (canListen)
QCOMPARE(qvariant_cast<QLocalSocket::LocalSocketState>(spyStateChanged.last()[0]),
QLocalSocket::ConnectedState);
- QCOMPARE(spyStateChanged.count(), 2);
- QCOMPARE(spyReadyRead.count(), 0);
+ QCOMPARE(spyStateChanged.size(), 2);
+ QCOMPARE(spyReadyRead.size(), 0);
bool timedOut = true;
QCOMPARE(server.waitForNewConnection(3000, &timedOut), canListen);
@@ -464,16 +453,16 @@ void tst_QLocalSocket::listenAndConnect()
QCOMPARE(server.serverName(), name);
QVERIFY(server.fullServerName().contains(name));
QVERIFY(server.nextPendingConnection() != (QLocalSocket*)0);
- QTRY_COMPARE(server.hits.count(), i + 1);
- QCOMPARE(spyNewConnection.count(), i + 1);
+ QTRY_COMPARE(server.hits.size(), i + 1);
+ QCOMPARE(spyNewConnection.size(), i + 1);
QVERIFY(server.errorString().isEmpty());
QCOMPARE(server.serverError(), QAbstractSocket::UnknownSocketError);
} else {
QVERIFY(server.serverName().isEmpty());
QVERIFY(server.fullServerName().isEmpty());
QCOMPARE(server.nextPendingConnection(), (QLocalSocket*)0);
- QCOMPARE(spyNewConnection.count(), 0);
- QCOMPARE(server.hits.count(), 0);
+ QCOMPARE(spyNewConnection.size(), 0);
+ QCOMPARE(server.hits.size(), 0);
QVERIFY(!server.errorString().isEmpty());
QCOMPARE(server.serverError(), QAbstractSocket::HostNotFoundError);
}
@@ -482,14 +471,14 @@ void tst_QLocalSocket::listenAndConnect()
server.close();
- QCOMPARE(server.hits.count(), (canListen ? connections : 0));
- QCOMPARE(spyNewConnection.count(), (canListen ? connections : 0));
+ QCOMPARE(server.hits.size(), (canListen ? connections : 0));
+ QCOMPARE(spyNewConnection.size(), (canListen ? connections : 0));
}
void tst_QLocalSocket::connectWithOpen()
{
LocalServer server;
- QVERIFY(server.listen("tst_qlocalsocket"));
+ QVERIFY2(server.listen("tst_qlocalsocket"), qUtf8Printable(server.errorString()));
LocalSocket socket;
QSignalSpy spyAboutToClose(&socket, SIGNAL(aboutToClose()));
@@ -507,7 +496,7 @@ void tst_QLocalSocket::connectWithOpen()
socket.close();
server.close();
- QCOMPARE(spyAboutToClose.count(), 1);
+ QCOMPARE(spyAboutToClose.size(), 1);
}
void tst_QLocalSocket::listenAndConnectAbstractNamespaceTrailingZeros_data()
@@ -541,7 +530,7 @@ void tst_QLocalSocket::listenAndConnectAbstractNamespaceTrailingZeros()
client_path.append(QChar('\0'));
LocalServer server;
server.setSocketOptions(QLocalServer::AbstractNamespaceOption);
- QVERIFY(server.listen(server_path));
+ QVERIFY2(server.listen(server_path), qUtf8Printable(server.errorString()));
QCOMPARE(server.fullServerName(), server_path);
LocalSocket socket;
@@ -590,7 +579,7 @@ void tst_QLocalSocket::listenAndConnectAbstractNamespace()
LocalServer server;
server.setSocketOptions(serverOption);
- QVERIFY(server.listen("tst_qlocalsocket"));
+ QVERIFY2(server.listen("tst_qlocalsocket"), qUtf8Printable(server.errorString()));
LocalSocket socket;
socket.setSocketOptions(socketOption);
@@ -673,7 +662,7 @@ void tst_QLocalSocket::sendData()
QTest::qWait(250);
#endif
QVERIFY(!timedOut);
- QCOMPARE(spyConnected.count(), canListen ? 1 : 0);
+ QCOMPARE(spyConnected.size(), canListen ? 1 : 0);
QCOMPARE(socket.state(), canListen ? QLocalSocket::ConnectedState : QLocalSocket::UnconnectedState);
// test sending/receiving data
@@ -699,7 +688,7 @@ void tst_QLocalSocket::sendData()
QCOMPARE(socket.flush(), false);
QCOMPARE(socket.isValid(), canListen);
QCOMPARE(socket.readBufferSize(), (qint64)0);
- QCOMPARE(spyReadyRead.count(), expectedReadyReadSignals);
+ QCOMPARE(spyReadyRead.size(), expectedReadyReadSignals);
QVERIFY(testLine.startsWith(in.readLine()));
@@ -710,16 +699,16 @@ void tst_QLocalSocket::sendData()
}
socket.disconnectFromServer();
- QCOMPARE(spyConnected.count(), canListen ? 1 : 0);
- QCOMPARE(spyDisconnected.count(), canListen ? 1 : 0);
- QCOMPARE(spyError.count(), canListen ? 0 : 1);
- QCOMPARE(spyStateChanged.count(), canListen ? 4 : 2);
- QCOMPARE(spyReadyRead.count(), canListen ? expectedReadyReadSignals : 0);
+ QCOMPARE(spyConnected.size(), canListen ? 1 : 0);
+ QCOMPARE(spyDisconnected.size(), canListen ? 1 : 0);
+ QCOMPARE(spyError.size(), canListen ? 0 : 1);
+ QCOMPARE(spyStateChanged.size(), canListen ? 4 : 2);
+ QCOMPARE(spyReadyRead.size(), canListen ? expectedReadyReadSignals : 0);
server.close();
- QCOMPARE(server.hits.count(), (canListen ? 1 : 0));
- QCOMPARE(spy.count(), (canListen ? 1 : 0));
+ QCOMPARE(server.hits.size(), (canListen ? 1 : 0));
+ QCOMPARE(spy.size(), (canListen ? 1 : 0));
}
void tst_QLocalSocket::readLine_data()
@@ -771,7 +760,7 @@ void tst_QLocalSocket::readLine()
const QString serverName = QLatin1String("tst_localsocket");
LocalServer server;
- QVERIFY(server.listen(serverName));
+ QVERIFY2(server.listen(serverName), qUtf8Printable(server.errorString()));
LocalSocket client;
client.connectToServer(serverName);
@@ -847,7 +836,7 @@ void tst_QLocalSocket::skip()
const QString serverName = QLatin1String("tst_localsocket");
LocalServer server;
- QVERIFY(server.listen(serverName));
+ QVERIFY2(server.listen(serverName), qUtf8Printable(server.errorString()));
LocalSocket client;
client.connectToServer(serverName);
@@ -946,7 +935,7 @@ static QVariant readCommand(QIODevice *ioDevice, int *readCommandCounter, bool r
void tst_QLocalSocket::simpleCommandProtocol1()
{
- QLocalServer server;
+ CrashSafeLocalServer server;
server.listen(QStringLiteral("simpleProtocol"));
QLocalSocket localSocketWrite;
@@ -972,7 +961,7 @@ void tst_QLocalSocket::simpleCommandProtocol1()
void tst_QLocalSocket::simpleCommandProtocol2()
{
- QLocalServer server;
+ CrashSafeLocalServer server;
server.listen(QStringLiteral("simpleProtocol"));
QLocalSocket localSocketWrite;
@@ -1019,7 +1008,7 @@ void tst_QLocalSocket::simpleCommandProtocol2()
localSocketWrite.abort();
QCOMPARE(localSocketWrite.state(), QLocalSocket::UnconnectedState);
- QCOMPARE(spyDisconnected.count(), 1);
+ QCOMPARE(spyDisconnected.size(), 1);
QCOMPARE(localSocketWrite.bytesToWrite(), 0);
QVERIFY(!localSocketWrite.isOpen());
@@ -1029,7 +1018,7 @@ void tst_QLocalSocket::simpleCommandProtocol2()
// QLocalSocket/Server can take a name or path, check that it works as expected
void tst_QLocalSocket::fullPath()
{
- QLocalServer server;
+ CrashSafeLocalServer server;
QString name = "qlocalsocket_pathtest";
#if defined(QT_LOCALSOCKET_TCP)
QString path = "QLocalServer";
@@ -1039,7 +1028,7 @@ void tst_QLocalSocket::fullPath()
QString path = "/tmp";
#endif
QString serverName = path + '/' + name;
- QVERIFY2(server.listen(serverName), server.errorString().toLatin1().constData());
+ QVERIFY2(server.listen(serverName), qUtf8Printable(server.errorString()));
QCOMPARE(server.serverName(), serverName);
QCOMPARE(server.fullServerName(), serverName);
@@ -1070,7 +1059,7 @@ void tst_QLocalSocket::hitMaximumConnections()
LocalServer server;
QString name = "tst_localsocket";
server.setMaxPendingConnections(max);
- QVERIFY2(server.listen(name), server.errorString().toLatin1().constData());
+ QVERIFY2(server.listen(name), qUtf8Printable(server.errorString()));
int connections = server.maxPendingConnections() + 1;
QList<QLocalSocket*> sockets;
for (int i = 0; i < connections; ++i) {
@@ -1081,7 +1070,7 @@ void tst_QLocalSocket::hitMaximumConnections()
bool timedOut = true;
QVERIFY(server.waitForNewConnection(3000, &timedOut));
QVERIFY(!timedOut);
- QVERIFY(server.hits.count() > 0);
+ QVERIFY(server.hits.size() > 0);
qDeleteAll(sockets.begin(), sockets.end());
}
@@ -1109,9 +1098,9 @@ public:
QVERIFY(socket.waitForConnected(1000));
// We should *not* have this signal yet!
- QCOMPARE(spyReadyRead.count(), 0);
+ QCOMPARE(spyReadyRead.size(), 0);
socket.waitForReadyRead();
- QCOMPARE(spyReadyRead.count(), 1);
+ QCOMPARE(spyReadyRead.size(), 1);
QTextStream in(&socket);
QCOMPARE(in.readLine(), testLine);
socket.close();
@@ -1131,7 +1120,7 @@ public:
LocalServer server;
server.setMaxPendingConnections(10);
QVERIFY2(server.listen("qlocalsocket_threadtest"),
- server.errorString().toLatin1().constData());
+ qUtf8Printable(server.errorString()));
mutex.lock();
wc.wakeAll();
mutex.unlock();
@@ -1153,7 +1142,7 @@ public:
--done;
delete serverSocket;
}
- QCOMPARE(server.hits.count(), clients);
+ QCOMPARE(server.hits.size(), clients);
}
};
@@ -1292,7 +1281,7 @@ void tst_QLocalSocket::waitForDisconnect()
{
QString name = "tst_localsocket";
LocalServer server;
- QVERIFY(server.listen(name));
+ QVERIFY2(server.listen(name), qUtf8Printable(server.errorString()));
LocalSocket socket;
socket.connectToServer(name);
QVERIFY(socket.waitForConnected(3000));
@@ -1310,7 +1299,7 @@ void tst_QLocalSocket::waitForDisconnectByServer()
{
QString name = "tst_localsocket";
LocalServer server;
- QVERIFY(server.listen(name));
+ QVERIFY2(server.listen(name), qUtf8Printable(server.errorString()));
LocalSocket socket;
QSignalSpy spy(&socket, SIGNAL(disconnected()));
QVERIFY(spy.isValid());
@@ -1322,14 +1311,14 @@ void tst_QLocalSocket::waitForDisconnectByServer()
serverSocket->close();
QCOMPARE(serverSocket->state(), QLocalSocket::UnconnectedState);
QVERIFY(socket.waitForDisconnected(3000));
- QCOMPARE(spy.count(), 1);
+ QCOMPARE(spy.size(), 1);
}
void tst_QLocalSocket::waitForReadyReadOnDisconnected()
{
QString name = "tst_localsocket";
LocalServer server;
- QVERIFY(server.listen(name));
+ QVERIFY2(server.listen(name), qUtf8Printable(server.errorString()));
LocalSocket socket;
connect(&socket, &QLocalSocket::readyRead, [&socket]() {
QVERIFY(socket.getChar(nullptr));
@@ -1363,7 +1352,7 @@ void tst_QLocalSocket::delayedDisconnect()
{
QString name = "tst_localsocket";
LocalServer server;
- QVERIFY(server.listen(name));
+ QVERIFY2(server.listen(name), qUtf8Printable(server.errorString()));
LocalSocket socket;
socket.connectToServer(name);
QVERIFY(socket.waitForConnected(3000));
@@ -1392,9 +1381,11 @@ void tst_QLocalSocket::delayedDisconnect()
void tst_QLocalSocket::removeServer()
{
// this is a hostile takeover, but recovering from a crash results in the same
+ // Note: Explicitly not a CrashSafeLocalServer
QLocalServer server, server2;
+
QVERIFY(QLocalServer::removeServer("cleanuptest"));
- QVERIFY(server.listen("cleanuptest"));
+ QVERIFY2(server.listen("cleanuptest"), qUtf8Printable(server.errorString()));
#ifndef Q_OS_WIN
// on Windows, there can be several sockets listening on the same pipe
// on Unix, there can only be one socket instance
@@ -1406,10 +1397,10 @@ void tst_QLocalSocket::removeServer()
void tst_QLocalSocket::recycleServer()
{
- QLocalServer server;
+ CrashSafeLocalServer server;
QLocalSocket client;
- QVERIFY(server.listen("recycletest1"));
+ QVERIFY2(server.listen("recycletest1"), qUtf8Printable(server.errorString()));
client.connectToServer("recycletest1");
QVERIFY(client.waitForConnected(201));
QVERIFY(server.waitForNewConnection(201));
@@ -1419,7 +1410,7 @@ void tst_QLocalSocket::recycleServer()
client.disconnectFromServer();
qApp->processEvents();
- QVERIFY(server.listen("recycletest2"));
+ QVERIFY2(server.listen("recycletest2"), qUtf8Printable(server.errorString()));
client.connectToServer("recycletest2");
QVERIFY(client.waitForConnected(202));
QVERIFY(server.waitForNewConnection(202));
@@ -1431,13 +1422,13 @@ void tst_QLocalSocket::recycleClientSocket()
const QByteArrayList lines = QByteArrayList() << "Have you heard of that new band"
<< "\"1023 Megabytes\"?"
<< "They haven't made it to a gig yet.";
- QLocalServer server;
+ CrashSafeLocalServer server;
const QString serverName = QStringLiteral("recycleClientSocket");
- QVERIFY(server.listen(serverName));
+ QVERIFY2(server.listen(serverName), qUtf8Printable(server.errorString()));
QLocalSocket client;
QSignalSpy clientReadyReadSpy(&client, SIGNAL(readyRead()));
QSignalSpy clientErrorSpy(&client, SIGNAL(errorOccurred(QLocalSocket::LocalSocketError)));
- for (int i = 0; i < lines.count(); ++i) {
+ for (int i = 0; i < lines.size(); ++i) {
client.abort();
clientReadyReadSpy.clear();
client.connectToServer(serverName);
@@ -1456,12 +1447,12 @@ void tst_QLocalSocket::recycleClientSocket()
void tst_QLocalSocket::multiConnect()
{
- QLocalServer server;
+ CrashSafeLocalServer server;
QLocalSocket client1;
QLocalSocket client2;
QLocalSocket client3;
- QVERIFY(server.listen("multiconnect"));
+ QVERIFY2(server.listen("multiconnect"), qUtf8Printable(server.errorString()));
client1.connectToServer("multiconnect");
client2.connectToServer("multiconnect");
@@ -1481,8 +1472,8 @@ void tst_QLocalSocket::multiConnect()
void tst_QLocalSocket::writeOnlySocket()
{
- QLocalServer server;
- QVERIFY(server.listen("writeOnlySocket"));
+ CrashSafeLocalServer server;
+ QVERIFY2(server.listen("writeOnlySocket"), qUtf8Printable(server.errorString()));
QLocalSocket client;
client.connectToServer("writeOnlySocket", QIODevice::WriteOnly);
@@ -1512,11 +1503,11 @@ void tst_QLocalSocket::writeToClientAndDisconnect_data()
void tst_QLocalSocket::writeToClientAndDisconnect()
{
QFETCH(int, chunks);
- QLocalServer server;
+ CrashSafeLocalServer server;
QLocalSocket client;
QSignalSpy readChannelFinishedSpy(&client, SIGNAL(readChannelFinished()));
- QVERIFY(server.listen("writeAndDisconnectServer"));
+ QVERIFY2(server.listen("writeAndDisconnectServer"), qUtf8Printable(server.errorString()));
client.connectToServer("writeAndDisconnectServer");
QVERIFY(client.waitForConnected(200));
QVERIFY(server.waitForNewConnection(200));
@@ -1532,7 +1523,7 @@ void tst_QLocalSocket::writeToClientAndDisconnect()
QVERIFY(clientSocket->waitForDisconnected());
QVERIFY(client.waitForDisconnected());
- QCOMPARE(readChannelFinishedSpy.count(), 1);
+ QCOMPARE(readChannelFinishedSpy.size(), 1);
const QByteArray received = client.readAll();
QCOMPARE(received.size(), qint64(sizeof(buffer) * chunks));
QCOMPARE(client.state(), QLocalSocket::UnconnectedState);
@@ -1540,8 +1531,8 @@ void tst_QLocalSocket::writeToClientAndDisconnect()
void tst_QLocalSocket::writeToDisconnected()
{
- QLocalServer server;
- QVERIFY(server.listen("writeToDisconnected"));
+ CrashSafeLocalServer server;
+ QVERIFY2(server.listen("writeToDisconnected"), qUtf8Printable(server.errorString()));
QLocalSocket client;
QSignalSpy spyError(&client, SIGNAL(errorOccurred(QLocalSocket::LocalSocketError)));
@@ -1562,7 +1553,7 @@ void tst_QLocalSocket::writeToDisconnected()
QCOMPARE(client.bytesToWrite(), qint64(1));
QVERIFY(!client.waitForBytesWritten());
- QCOMPARE(spyError.count(), 1);
+ QCOMPARE(spyError.size(), 1);
QCOMPARE(client.state(), QLocalSocket::UnconnectedState);
}
@@ -1611,8 +1602,8 @@ public slots:
*/
void tst_QLocalSocket::bytesWrittenSignal()
{
- QLocalServer server;
- QVERIFY(server.listen("qlocalsocket_readyread"));
+ CrashSafeLocalServer server;
+ QVERIFY2(server.listen("qlocalsocket_readyread"), qUtf8Printable(server.errorString()));
WriteThread writeThread;
QSignalSpy receivedSpy(&writeThread, &WriteThread::bytesWrittenReceived);
writeThread.start();
@@ -1632,8 +1623,8 @@ void tst_QLocalSocket::socketClosedSlot()
void tst_QLocalSocket::syncDisconnectNotify()
{
- QLocalServer server;
- QVERIFY(server.listen("syncDisconnectNotify"));
+ CrashSafeLocalServer server;
+ QVERIFY2(server.listen("syncDisconnectNotify"), qUtf8Printable(server.errorString()));
QLocalSocket client;
connect(&client, &QLocalSocket::disconnected,
this, &tst_QLocalSocket::socketClosedSlot);
@@ -1651,8 +1642,8 @@ void tst_QLocalSocket::syncDisconnectNotify()
void tst_QLocalSocket::asyncDisconnectNotify()
{
- QLocalServer server;
- QVERIFY(server.listen("asyncDisconnectNotify"));
+ CrashSafeLocalServer server;
+ QVERIFY2(server.listen("asyncDisconnectNotify"), qUtf8Printable(server.errorString()));
QLocalSocket client;
QSignalSpy disconnectedSpy(&client, SIGNAL(disconnected()));
QSignalSpy readChannelFinishedSpy(&client, SIGNAL(readChannelFinished()));
@@ -1667,7 +1658,7 @@ void tst_QLocalSocket::asyncDisconnectNotify()
QVERIFY(serverSocket);
delete serverSocket;
QTRY_VERIFY(!disconnectedSpy.isEmpty());
- QCOMPARE(readChannelFinishedSpy.count(), 1);
+ QCOMPARE(readChannelFinishedSpy.size(), 1);
}
void tst_QLocalSocket::verifySocketOptions_data()
@@ -1698,16 +1689,14 @@ void tst_QLocalSocket::verifySocketOptions_data()
void tst_QLocalSocket::verifySocketOptions()
{
// These are only guaranteed to be useful on linux at this time
-#ifdef Q_OS_LINUX
+#if defined(Q_OS_LINUX) && !defined(Q_OS_WEBOS)
QFETCH(QString, service);
QFETCH(QLocalServer::SocketOption, opts);
QFETCH(QFile::Permissions, perms);
-
- QLocalServer::removeServer(service);
- QLocalServer server;
+ CrashSafeLocalServer server;
server.setSocketOptions(opts);
- QVERIFY2(server.listen(service), "service failed to start listening");
+ QVERIFY2(server.listen(service), qUtf8Printable(server.errorString()));
// find the socket
QString fullServerPath = QDir::cleanPath(QDir::tempPath());
@@ -1720,7 +1709,7 @@ void tst_QLocalSocket::verifySocketOptions()
void tst_QLocalSocket::verifyListenWithDescriptor()
{
-#ifdef Q_OS_UNIX
+#if defined(Q_OS_UNIX) && !defined(Q_OS_VXWORKS)
QFETCH(QString, path);
QFETCH(bool, abstract);
QFETCH(bool, bound);
@@ -1762,10 +1751,10 @@ void tst_QLocalSocket::verifyListenWithDescriptor()
close(fds[1]);
}
- QLocalServer server;
- QVERIFY2(server.listen(listenSocket), "failed to start create QLocalServer with local socket");
+ CrashSafeLocalServer server;
+ QVERIFY2(server.listen(listenSocket), qUtf8Printable(server.errorString()));
-#ifdef Q_OS_LINUX
+#if defined(Q_OS_LINUX) || defined(Q_OS_QNX)
if (!bound) {
QCOMPARE(server.serverName().isEmpty(), true);
QCOMPARE(server.fullServerName().isEmpty(), true);
@@ -1806,7 +1795,7 @@ void tst_QLocalSocket::verifyListenWithDescriptor_data()
QTest::addColumn<bool>("bound");
QTest::newRow("normal") << QDir::tempPath() + QLatin1String("/testsocket") << false << true;
-#ifdef Q_OS_LINUX
+#if defined(Q_OS_LINUX) || defined(Q_OS_QNX)
QTest::newRow("abstract") << QString::fromLatin1("abstractsocketname") << true << true;
QTest::newRow("abstractwithslash") << QString::fromLatin1("abstractsocketwitha/inthename") << true << true;
#endif
@@ -1818,16 +1807,20 @@ void tst_QLocalSocket::verifyListenWithDescriptor_data()
void tst_QLocalSocket::serverBindingsAndProperties()
{
- QLocalServer server;
+ CrashSafeLocalServer server;
- QProperty<QLocalServer::SocketOptions> sockOpts;
- server.bindableSocketOptions().setBinding(Qt::makePropertyBinding(sockOpts));
- sockOpts = QLocalServer::GroupAccessOption | QLocalServer::UserAccessOption;
- QCOMPARE(server.socketOptions(), sockOpts.value());
+ QTestPrivate::testReadWritePropertyBasics(
+ server, QLocalServer::SocketOptions{QLocalServer::GroupAccessOption},
+ QLocalServer::SocketOptions{QLocalServer::OtherAccessOption}, "socketOptions");
+}
+
+void tst_QLocalSocket::socketBindings()
+{
+ QLocalSocket socket;
- sockOpts.setBinding(server.bindableSocketOptions().makeBinding());
- server.setSocketOptions(QLocalServer::OtherAccessOption);
- QCOMPARE(sockOpts.value(), QLocalServer::OtherAccessOption);
+ QTestPrivate::testReadWritePropertyBasics(
+ socket, QLocalSocket::SocketOptions{QLocalSocket::AbstractNamespaceOption},
+ QLocalSocket::SocketOptions{QLocalSocket::NoOptions}, "socketOptions");
}
QTEST_MAIN(tst_QLocalSocket)
diff --git a/tests/auto/network/socket/qsctpsocket/CMakeLists.txt b/tests/auto/network/socket/qsctpsocket/CMakeLists.txt
index af3f809113..4bf5438841 100644
--- a/tests/auto/network/socket/qsctpsocket/CMakeLists.txt
+++ b/tests/auto/network/socket/qsctpsocket/CMakeLists.txt
@@ -1,12 +1,19 @@
-# Generated from qsctpsocket.pro.
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
#####################################################################
## tst_qsctpsocket Test:
#####################################################################
+if(NOT QT_BUILD_STANDALONE_TESTS AND NOT QT_BUILDING_QT)
+ cmake_minimum_required(VERSION 3.16)
+ project(tst_qsctpsocket LANGUAGES CXX)
+ find_package(Qt6BuildInternals REQUIRED COMPONENTS STANDALONE_TEST)
+endif()
+
qt_internal_add_test(tst_qsctpsocket
SOURCES
tst_qsctpsocket.cpp
- PUBLIC_LIBRARIES
+ LIBRARIES
Qt::Network
)
diff --git a/tests/auto/network/socket/qsctpsocket/tst_qsctpsocket.cpp b/tests/auto/network/socket/qsctpsocket/tst_qsctpsocket.cpp
index c2e29c0ce2..2893053158 100644
--- a/tests/auto/network/socket/qsctpsocket/tst_qsctpsocket.cpp
+++ b/tests/auto/network/socket/qsctpsocket/tst_qsctpsocket.cpp
@@ -1,30 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 Alex Trotsenko <alex1973tr@gmail.com>
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 Alex Trotsenko <alex1973tr@gmail.com>
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
#include <QTest>
#include <QDebug>
@@ -152,12 +127,13 @@ void tst_QSctpSocket::bind_data()
// these ranges are guaranteed to be reserved for 'documentation purposes',
// and thus, should be unused in the real world. Not that I'm assuming the
// world is full of competent administrators, or anything.
- QStringList knownBad;
- knownBad << "198.51.100.1";
- knownBad << "2001:0DB8::1";
- foreach (const QString &badAddress, knownBad) {
+ const QString knownBad[] = {
+ "198.51.100.1",
+ "2001:0DB8::1",
+ };
+
+ for (const QString &badAddress : knownBad)
QTest::newRow(badAddress.toLatin1().constData()) << badAddress << false << QString();
- }
}
// Testing bind function
diff --git a/tests/auto/network/socket/qsocks5socketengine/BLACKLIST b/tests/auto/network/socket/qsocks5socketengine/BLACKLIST
index 405d03f990..6b3a39ab5e 100644
--- a/tests/auto/network/socket/qsocks5socketengine/BLACKLIST
+++ b/tests/auto/network/socket/qsocks5socketengine/BLACKLIST
@@ -1,12 +1,10 @@
[udpTest]
*
[passwordAuth]
-ubuntu-18.04
-ubuntu-20.04
+ubuntu
+# QTBUG-101274
+qnx ci
# QTBUG-74162
[passwordAuth2]
ubuntu
-[downloadBigFile]
-windows-10 msvc-2015
-windows-7sp1
diff --git a/tests/auto/network/socket/qsocks5socketengine/CMakeLists.txt b/tests/auto/network/socket/qsocks5socketengine/CMakeLists.txt
index 64f3aa7a9e..dc0b87cd94 100644
--- a/tests/auto/network/socket/qsocks5socketengine/CMakeLists.txt
+++ b/tests/auto/network/socket/qsocks5socketengine/CMakeLists.txt
@@ -1,4 +1,11 @@
-# Generated from qsocks5socketengine.pro.
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
+
+if(NOT QT_BUILD_STANDALONE_TESTS AND NOT QT_BUILDING_QT)
+ cmake_minimum_required(VERSION 3.16)
+ project(tst_qsocks5socketengine LANGUAGES CXX)
+ find_package(Qt6BuildInternals REQUIRED COMPONENTS STANDALONE_TEST)
+endif()
if(NOT QT_FEATURE_private_tests)
return()
@@ -11,23 +18,18 @@ endif()
qt_internal_add_test(tst_qsocks5socketengine
SOURCES
tst_qsocks5socketengine.cpp
- PUBLIC_LIBRARIES
+ LIBRARIES
Qt::CorePrivate
Qt::NetworkPrivate
- QT_TEST_SERVER_LIST "danted" "apache2" "cyrus" # special case
+ QT_TEST_SERVER_LIST "danted" "apache2" "cyrus"
)
-#### Keys ignored in scope 1:.:.:qsocks5socketengine.pro:<TRUE>:
-# MOC_DIR = "tmp"
-# _REQUIREMENTS = "qtConfig(private_tests)"
-
## Scopes:
#####################################################################
-#### Keys ignored in scope 2:.:.:qsocks5socketengine.pro:LINUX:
# QT_TEST_SERVER_LIST = "danted" "apache2" "cyrus"
qt_internal_extend_target(tst_qsocks5socketengine CONDITION WIN32
- PUBLIC_LIBRARIES
+ LIBRARIES
ws2_32
)
diff --git a/tests/auto/network/socket/qsocks5socketengine/tst_qsocks5socketengine.cpp b/tests/auto/network/socket/qsocks5socketengine/tst_qsocks5socketengine.cpp
index 11e17cb319..cc77ba2da3 100644
--- a/tests/auto/network/socket/qsocks5socketengine/tst_qsocks5socketengine.cpp
+++ b/tests/auto/network/socket/qsocks5socketengine/tst_qsocks5socketengine.cpp
@@ -1,30 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
#include <QtTest/QTest>
@@ -48,6 +23,8 @@
#include "../../../network-settings.h"
+using namespace std::chrono_literals;
+
class tst_QSocks5SocketEngine : public QObject, public QAbstractSocketEngineReceiver
{
Q_OBJECT
@@ -366,7 +343,7 @@ void tst_QSocks5SocketEngine::simpleErrorsAndStates()
QCOMPARE(socketDevice.state(), QAbstractSocket::UnconnectedState);
QVERIFY(!socketDevice.connectToHost(QHostInfo::fromName(QtNetworkSettings::socksProxyServerName()).addresses().first(), 8088));
QCOMPARE(socketDevice.state(), QAbstractSocket::ConnectingState);
- if (socketDevice.waitForWrite(15000)) {
+ if (socketDevice.waitForWrite(15s)) {
QVERIFY(socketDevice.state() == QAbstractSocket::UnconnectedState ||
socketDevice.state() == QAbstractSocket::ConnectedState);
} else {
@@ -940,13 +917,13 @@ void tst_QSocks5SocketEngine::fragmentation_data()
responses << authMethodBasic << authSuccess.left(1) << authSuccess.mid(1) << connectResponseIPv4;
QTest::newRow("auth-response") << responses;
- for (int i = 1; i < connectResponseIPv4.length() - 1; i++) {
+ for (int i = 1; i < connectResponseIPv4.size() - 1; i++) {
responses.clear();
responses << authMethodNone << connectResponseIPv4.left(i) << connectResponseIPv4.mid(i);
QTest::newRow(qPrintable(QString("connect-response-ipv4-") + QString::number(i))) << responses;
}
- for (int i = 1; i < connectResponseIPv6.length() - 1; i++) {
+ for (int i = 1; i < connectResponseIPv6.size() - 1; i++) {
responses.clear();
responses << authMethodNone << connectResponseIPv6.left(i) << connectResponseIPv6.mid(i);
QTest::newRow(qPrintable(QString("connect-response-ipv6-") + QString::number(i))) << responses;
@@ -989,13 +966,13 @@ void tst_QSocks5SocketEngine::incomplete_data()
responses << authMethodBasic << authSuccess.left(1);
QTest::newRow("auth-response") << responses;
- for (int i = 1; i < connectResponseIPv4.length() - 1; i++) {
+ for (int i = 1; i < connectResponseIPv4.size() - 1; i++) {
responses.clear();
responses << authMethodNone << connectResponseIPv4.left(i);
QTest::newRow(qPrintable(QString("connect-response-ipv4-") + QString::number(i))) << responses;
}
- for (int i = 1; i < connectResponseIPv6.length() - 1; i++) {
+ for (int i = 1; i < connectResponseIPv6.size() - 1; i++) {
responses.clear();
responses << authMethodNone << connectResponseIPv6.left(i);
QTest::newRow(qPrintable(QString("connect-response-ipv6-") + QString::number(i))) << responses;
diff --git a/tests/auto/network/socket/qtcpserver/BLACKLIST b/tests/auto/network/socket/qtcpserver/BLACKLIST
index c6d4d49908..a8b5f5d137 100644
--- a/tests/auto/network/socket/qtcpserver/BLACKLIST
+++ b/tests/auto/network/socket/qtcpserver/BLACKLIST
@@ -1,19 +1,13 @@
[listenWhileListening:WithSocks5Proxy]
linux
windows
-[ipv6Server]
-windows-7sp1
-windows-10 msvc-2017
[ipv6Server:WithoutProxy]
windows
osx
-[eagainBlockingAccept]
-windows-7sp1
-windows-10
[serverAddress]
-windows-7sp1
+# QTBUG-103056
+qnx
windows-10
[linkLocal]
macos arm
-
diff --git a/tests/auto/network/socket/qtcpserver/CMakeLists.txt b/tests/auto/network/socket/qtcpserver/CMakeLists.txt
index 01f6c8b672..b01a164302 100644
--- a/tests/auto/network/socket/qtcpserver/CMakeLists.txt
+++ b/tests/auto/network/socket/qtcpserver/CMakeLists.txt
@@ -1,4 +1,11 @@
-# Generated from qtcpserver.pro.
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
+
+if(NOT QT_BUILD_STANDALONE_TESTS AND NOT QT_BUILDING_QT)
+ cmake_minimum_required(VERSION 3.16)
+ project(tst_qtcpserver LANGUAGES CXX)
+ find_package(Qt6BuildInternals REQUIRED COMPONENTS STANDALONE_TEST)
+endif()
-add_subdirectory(test)
add_subdirectory(crashingServer)
+add_subdirectory(test)
diff --git a/tests/auto/network/socket/qtcpserver/crashingServer/CMakeLists.txt b/tests/auto/network/socket/qtcpserver/crashingServer/CMakeLists.txt
index dd309ba605..bb1feb0237 100644
--- a/tests/auto/network/socket/qtcpserver/crashingServer/CMakeLists.txt
+++ b/tests/auto/network/socket/qtcpserver/crashingServer/CMakeLists.txt
@@ -1,4 +1,5 @@
-# Generated from crashingServer.pro.
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
#####################################################################
## crashingServer Binary:
@@ -8,7 +9,7 @@ qt_internal_add_executable(crashingServer
OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/"
SOURCES
main.cpp
- PUBLIC_LIBRARIES
+ LIBRARIES
Qt::Network
)
diff --git a/tests/auto/network/socket/qtcpserver/crashingServer/main.cpp b/tests/auto/network/socket/qtcpserver/crashingServer/main.cpp
index 7cb65cd1a3..1c41552eb5 100644
--- a/tests/auto/network/socket/qtcpserver/crashingServer/main.cpp
+++ b/tests/auto/network/socket/qtcpserver/crashingServer/main.cpp
@@ -1,30 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
#include <QtCore>
@@ -32,18 +7,45 @@
#if defined(Q_OS_WIN) && defined(Q_CC_MSVC)
# include <crtdbg.h>
#endif
+#ifdef Q_OS_UNIX
+# include <sys/resource.h>
+# include <unistd.h>
+#endif
int main(int argc, char *argv[])
{
- // Windows: Suppress crash notification dialog.
#if defined(Q_OS_WIN) && defined(Q_CC_MSVC)
+ // Windows: Suppress crash notification dialog.
_CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_DEBUG);
+#elif defined(RLIMIT_CORE)
+ // Unix: set our core dump limit to zero to request no dialogs.
+ if (struct rlimit rlim; getrlimit(RLIMIT_CORE, &rlim) == 0) {
+ rlim.rlim_cur = 0;
+ setrlimit(RLIMIT_CORE, &rlim);
+ }
#endif
+
QCoreApplication app(argc, argv);
+ if (argc < 1) {
+ fprintf(stderr, "Need a port number\n");
+ return 1;
+ }
+ int port = QByteArrayView(argv[1]).toInt();
QTcpServer server;
- if (!server.listen(QHostAddress::LocalHost, 49199)) {
- qDebug("Failed to listen: %s", server.errorString().toLatin1().constData());
+ if (!server.listen(QHostAddress::LocalHost, port)) {
+ fprintf(stderr, "Failed to listen: %s\n", server.errorString().toLatin1().constData());
+ if (server.serverError() == QTcpSocket::AddressInUseError) {
+ // let's see if we can find the process that would be holding this
+ // still open
+#ifdef Q_OS_LINUX
+ static const char *ss_args[] = {
+ "ss", "-nap", "sport", "=", argv[1], nullptr
+ };
+ dup2(STDERR_FILENO, STDOUT_FILENO);
+ execvp(ss_args[0], const_cast<char **>(ss_args));
+#endif
+ }
return 1;
}
diff --git a/tests/auto/network/socket/qtcpserver/test/CMakeLists.txt b/tests/auto/network/socket/qtcpserver/test/CMakeLists.txt
index 74aed77c95..55615bbae1 100644
--- a/tests/auto/network/socket/qtcpserver/test/CMakeLists.txt
+++ b/tests/auto/network/socket/qtcpserver/test/CMakeLists.txt
@@ -1,28 +1,27 @@
-# Generated from test.pro.
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
#####################################################################
## tst_qtcpserver Test:
#####################################################################
qt_internal_add_test(tst_qtcpserver
- OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/../" # special case
+ OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/../"
SOURCES
../tst_qtcpserver.cpp
- PUBLIC_LIBRARIES
+ LIBRARIES
Qt::Network
- QT_TEST_SERVER_LIST "danted" "cyrus" "squid" "ftp-proxy" # special case
+ QT_TEST_SERVER_LIST "danted" "cyrus" "squid" "ftp-proxy"
)
-#### Keys ignored in scope 1:.:.:test.pro:<TRUE>:
-# MOC_DIR = "tmp"
+add_dependencies(tst_qtcpserver
+ crashingServer
+)
## Scopes:
#####################################################################
qt_internal_extend_target(tst_qtcpserver CONDITION WIN32
- PUBLIC_LIBRARIES
+ LIBRARIES
ws2_32
)
-
-#### Keys ignored in scope 6:.:.:test.pro:LINUX:
-# QT_TEST_SERVER_LIST = "danted" "cyrus" "squid" "ftp-proxy"
diff --git a/tests/auto/network/socket/qtcpserver/tst_qtcpserver.cpp b/tests/auto/network/socket/qtcpserver/tst_qtcpserver.cpp
index 4759ac292a..c03076d98e 100644
--- a/tests/auto/network/socket/qtcpserver/tst_qtcpserver.cpp
+++ b/tests/auto/network/socket/qtcpserver/tst_qtcpserver.cpp
@@ -1,34 +1,7 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
#include <qglobal.h>
-// To prevent windows system header files from re-defining min/max
-#define NOMINMAX 1
#if defined(_WIN32)
#include <winsock2.h>
#else
@@ -60,6 +33,8 @@
#include <qnetworkinterface.h>
#include <QNetworkProxy>
+#include <QSet>
+#include <QList>
#include "../../../network-settings.h"
@@ -117,6 +92,9 @@ private slots:
void pauseAccepting();
+ void pendingConnectionAvailable_data();
+ void pendingConnectionAvailable();
+
private:
bool shouldSkipIpv6TestsForBrokenGetsockopt();
#ifdef SHOULD_CHECK_SYSCALL_SUPPORT
@@ -160,7 +138,8 @@ void tst_QTcpServer::initTestCase()
#ifdef QT_TEST_SERVER
QVERIFY(QtNetworkSettings::verifyConnection(QtNetworkSettings::socksProxyServerName(), 1080));
QVERIFY(QtNetworkSettings::verifyConnection(QtNetworkSettings::httpProxyServerName(), 3128));
- QVERIFY(QtNetworkSettings::verifyConnection(QtNetworkSettings::ftpProxyServerName(), 2121));
+ // FTP currently not supported:
+ // QVERIFY(QtNetworkSettings::verifyConnection(QtNetworkSettings::ftpProxyServerName(), 2121));
QVERIFY(QtNetworkSettings::verifyConnection(QtNetworkSettings::imapServerName(), 143));
#else
if (!QtNetworkSettings::verifyTestNetworkSettings())
@@ -268,7 +247,7 @@ void tst_QTcpServer::clientServerLoop()
QVERIFY(server.waitForNewConnection(5000));
QVERIFY(server.hasPendingConnections());
- QCOMPARE(spy.count(), 1);
+ QCOMPARE(spy.size(), 1);
QTcpSocket *serverSocket = server.nextPendingConnection();
QVERIFY(serverSocket != 0);
@@ -429,9 +408,9 @@ void tst_QTcpServer::maxPendingConnections()
// two connections have been made. The second compare makes sure no
// more are accepted. Creating connections happens multithreaded so
// qWait must be used for that.
- QTRY_COMPARE(spy.count(), 2);
+ QTRY_COMPARE(spy.size(), 2);
QTest::qWait(100);
- QCOMPARE(spy.count(), 2);
+ QCOMPARE(spy.size(), 2);
QVERIFY(server.hasPendingConnections());
QVERIFY(server.nextPendingConnection());
@@ -480,7 +459,7 @@ public:
protected:
void run() override
{
- sleep(2);
+ sleep(std::chrono::seconds{2});
QTcpSocket socket;
socket.connectToHost(host, port);
@@ -598,9 +577,6 @@ void tst_QTcpServer::addressReusable()
#if !QT_CONFIG(process)
QSKIP("No qprocess support", SkipAll);
#else
-#ifdef Q_OS_LINUX
- QSKIP("The addressReusable test is unstable on Linux. See QTBUG-39985.");
-#endif
QFETCH_GLOBAL(bool, setProxy);
if (setProxy) {
#ifndef QT_NO_NETWORKPROXY
@@ -611,16 +587,25 @@ void tst_QTcpServer::addressReusable()
QSKIP("No proxy support");
#endif // QT_NO_NETWORKPROXY
}
+
+ QTcpServer server;
+ QVERIFY(server.listen(QHostAddress::LocalHost, 0));
+ quint16 serverPort = server.serverPort();
+ qDebug() << "Got port" << serverPort;
+ server.close(); // cleanly close
+
+ QTest::qSleep(10);
+
// The crashingServer process will crash once it gets a connection.
QProcess process;
QString processExe = crashingServerDir + "/crashingServer";
- process.start(processExe);
+ process.start(processExe, { QString::number(serverPort) });
QVERIFY2(process.waitForStarted(), qPrintable(
QString::fromLatin1("Could not start %1: %2").arg(processExe, process.errorString())));
- QVERIFY(process.waitForReadyRead(5000));
+ QVERIFY2(process.waitForReadyRead(5000), qPrintable(process.readAllStandardError()));
QTcpSocket socket;
- socket.connectToHost(QHostAddress::LocalHost, 49199);
+ socket.connectToHost(QHostAddress::LocalHost, serverPort);
QVERIFY(socket.waitForConnected(5000));
QVERIFY(process.waitForFinished(30000));
@@ -628,8 +613,9 @@ void tst_QTcpServer::addressReusable()
// Give the system some time.
QTest::qSleep(10);
- QTcpServer server;
- QVERIFY(server.listen(QHostAddress::LocalHost, 49199));
+ // listen again
+ QVERIFY2(server.listen(QHostAddress::LocalHost, serverPort),
+ qPrintable(server.errorString()));
#endif
}
@@ -748,6 +734,7 @@ void tst_QTcpServer::proxyFactory_data()
<< proxyList << proxyList.at(1)
<< false << int(QAbstractSocket::UnknownSocketError);
+#if 0 // ftp not currently supported
proxyList.clear();
proxyList << QNetworkProxy(QNetworkProxy::FtpCachingProxy, QtNetworkSettings::ftpProxyServerName(), 2121)
<< QNetworkProxy(QNetworkProxy::HttpCachingProxy, QtNetworkSettings::httpProxyServerName(), 3128)
@@ -755,6 +742,7 @@ void tst_QTcpServer::proxyFactory_data()
QTest::newRow("ftp+cachinghttp+socks5")
<< proxyList << proxyList.at(2)
<< false << int(QAbstractSocket::UnknownSocketError);
+#endif
// tests that fail to listen
proxyList.clear();
@@ -769,6 +757,7 @@ void tst_QTcpServer::proxyFactory_data()
<< proxyList << QNetworkProxy()
<< true << int(QAbstractSocket::UnsupportedSocketOperationError);
+#if 0 // ftp not currently supported
proxyList.clear();
proxyList << QNetworkProxy(QNetworkProxy::FtpCachingProxy, QtNetworkSettings::ftpProxyServerName(), 2121);
QTest::newRow("ftp")
@@ -781,6 +770,7 @@ void tst_QTcpServer::proxyFactory_data()
QTest::newRow("ftp+cachinghttp")
<< proxyList << QNetworkProxy()
<< true << int(QAbstractSocket::UnsupportedSocketOperationError);
+#endif
}
void tst_QTcpServer::proxyFactory()
@@ -875,10 +865,12 @@ void tst_QTcpServer::serverAddress_data()
QTest::newRow("AnyIPv4") << QHostAddress(QHostAddress::AnyIPv4) << QHostAddress(QHostAddress::AnyIPv4);
if (QtNetworkSettings::hasIPv6())
QTest::newRow("AnyIPv6") << QHostAddress(QHostAddress::AnyIPv6) << QHostAddress(QHostAddress::AnyIPv6);
- foreach (const QNetworkInterface &iface, QNetworkInterface::allInterfaces()) {
+ const auto ifaces = QNetworkInterface::allInterfaces();
+ for (const QNetworkInterface &iface : ifaces) {
if ((iface.flags() & QNetworkInterface::IsUp) == 0)
continue;
- foreach (const QNetworkAddressEntry &entry, iface.addressEntries()) {
+ const auto entries = iface.addressEntries();
+ for (const QNetworkAddressEntry &entry : entries) {
QTest::newRow(qPrintable(entry.ip().toString())) << entry.ip() << entry.ip();
}
}
@@ -932,7 +924,8 @@ void tst_QTcpServer::linkLocal()
QSet <QString> scopes;
QHostAddress localMaskv4("169.254.0.0");
QHostAddress localMaskv6("fe80::");
- foreach (const QNetworkInterface& iface, QNetworkInterface::allInterfaces()) {
+ const auto ifaces = QNetworkInterface::allInterfaces();
+ for (const QNetworkInterface &iface : ifaces) {
//Windows preallocates link local addresses to interfaces that are down.
//These may or may not work depending on network driver (they do not work for the Bluetooth PAN driver)
if (iface.flags() & QNetworkInterface::IsUp) {
@@ -945,8 +938,15 @@ void tst_QTcpServer::linkLocal()
// (we don't know why)
if (iface.name().startsWith("utun"))
continue;
+ // Do not use the iBridge interfae
+ if (iface.hardwareAddress() == "AC:DE:48:00:11:22")
+ continue;
+ // Do no use the Apple Wireless Direct Link interfaces
+ if (iface.name().startsWith("awdl"))
+ continue;
#endif
- foreach (QNetworkAddressEntry addressEntry, iface.addressEntries()) {
+ const auto entries = iface.addressEntries();
+ for (const QNetworkAddressEntry &addressEntry : entries) {
QHostAddress addr = addressEntry.ip();
if (addr.isInSubnet(localMaskv4, 16)) {
addresses << addr;
@@ -965,7 +965,7 @@ void tst_QTcpServer::linkLocal()
QList<QTcpServer*> servers;
quint16 port = 0;
- foreach (const QHostAddress& addr, addresses) {
+ for (const QHostAddress &addr : std::as_const(addresses)) {
QTcpServer *server = new QTcpServer;
QVERIFY(server->listen(addr, port));
port = server->serverPort(); //listen to same port on different interfaces
@@ -973,7 +973,7 @@ void tst_QTcpServer::linkLocal()
}
QList<QTcpSocket*> clients;
- foreach (const QHostAddress& addr, addresses) {
+ for (const QHostAddress &addr : std::as_const(addresses)) {
//unbound socket
QTcpSocket *socket = new QTcpSocket;
socket->connectToHost(addr, port);
@@ -988,7 +988,7 @@ void tst_QTcpServer::linkLocal()
}
//each server should have two connections
- foreach (QTcpServer* server, servers) {
+ for (QTcpServer *server : std::as_const(servers)) {
//qDebug() << "checking for connections" << server->serverAddress() << ":" << server->serverPort();
QVERIFY(server->waitForNewConnection(5000));
QTcpSocket* remote = server->nextPendingConnection();
@@ -1023,12 +1023,12 @@ void tst_QTcpServer::eagainBlockingAccept()
QTcpSocket s;
s.connectToHost(QHostAddress::LocalHost, 7896);
QSignalSpy spy(&server, SIGNAL(newConnection()));
- QTRY_COMPARE_WITH_TIMEOUT(spy.count(), 1, 500);
+ QTRY_COMPARE_WITH_TIMEOUT(spy.size(), 1, 500);
s.close();
// To test try again, should connect just fine.
s.connectToHost(QHostAddress::LocalHost, 7896);
- QTRY_COMPARE_WITH_TIMEOUT(spy.count(), 2, 500);
+ QTRY_COMPARE_WITH_TIMEOUT(spy.size(), 2, 500);
s.close();
server.close();
}
@@ -1064,13 +1064,13 @@ void tst_QTcpServer::pauseAccepting()
QTcpSocket sockets[NumSockets];
sockets[0].connectToHost(address, server.serverPort());
QVERIFY(spy.wait());
- QCOMPARE(spy.count(), 1);
+ QCOMPARE(spy.size(), 1);
server.pauseAccepting();
for (int i = 1; i < NumSockets; ++i)
sockets[i].connectToHost(address, server.serverPort());
QVERIFY(!spy.wait(400));
- QCOMPARE(spy.count(), 1);
+ QCOMPARE(spy.size(), 1);
server.resumeAccepting();
if (setProxy) {
@@ -1078,7 +1078,75 @@ void tst_QTcpServer::pauseAccepting()
Abort);
}
QVERIFY(spy.wait());
- QCOMPARE(spy.count(), 6);
+ QCOMPARE(spy.size(), 6);
+}
+
+
+// Only adds the socket to the pending connections list after emitNextSocket is
+// called. It's very artificial, but it allows us to test the behavior of
+// the pendingConnectionAvailable signal when a server doesn't add the socket
+// during the incomingConnection virtual function.
+class DerivedServer : public QTcpServer
+{
+public:
+ explicit DerivedServer(QObject *parent = nullptr)
+ : QTcpServer(parent)
+ {
+ }
+
+ void emitNextSocket()
+ {
+ if (m_socketDescriptors.isEmpty())
+ return;
+ auto *socket = new QTcpSocket(this);
+ socket->setSocketDescriptor(m_socketDescriptors.back());
+ m_socketDescriptors.pop_back();
+ addPendingConnection(socket);
+ }
+protected:
+ void incomingConnection(qintptr socketDescriptor) override
+ {
+ m_socketDescriptors.push_back(socketDescriptor);
+ }
+private:
+ QList<qintptr> m_socketDescriptors;
+};
+
+void tst_QTcpServer::pendingConnectionAvailable_data()
+{
+ QTest::addColumn<bool>("useDerivedServer");
+ QTest::newRow("QTcpServer") << false;
+ QTest::newRow("DerivedServer") << true;
+}
+
+void tst_QTcpServer::pendingConnectionAvailable()
+{
+ QFETCH_GLOBAL(bool, setProxy);
+ if (setProxy)
+ QSKIP("This feature does not differentiate with or without proxy");
+ QFETCH(bool, useDerivedServer);
+
+ QTcpServer *server = useDerivedServer ? new DerivedServer : new QTcpServer;
+ if (!server->listen(QHostAddress::LocalHost, 0)) {
+ qWarning() << "Server failed to listen:" << server->errorString();
+ QSKIP("Server failed to listen");
+ }
+ QSignalSpy newConnectionSpy(server, &QTcpServer::newConnection);
+ QSignalSpy pendingConnectionSpy(server, &QTcpServer::pendingConnectionAvailable);
+
+ QTcpSocket socket;
+ socket.connectToHost(QHostAddress::LocalHost, server->serverPort());
+
+ QVERIFY(newConnectionSpy.wait());
+ QVERIFY(socket.waitForConnected());
+ QCOMPARE(socket.state(), QTcpSocket::ConnectedState);
+
+ int expectedPendingConnections = useDerivedServer ? 0 : 1;
+ QCOMPARE(pendingConnectionSpy.size(), expectedPendingConnections);
+
+ if (useDerivedServer)
+ static_cast<DerivedServer *>(server)->emitNextSocket();
+ QCOMPARE(pendingConnectionSpy.size(), 1);
}
QTEST_MAIN(tst_QTcpServer)
diff --git a/tests/auto/network/socket/qtcpsocket/BLACKLIST b/tests/auto/network/socket/qtcpsocket/BLACKLIST
index d42457d743..6261c85a09 100644
--- a/tests/auto/network/socket/qtcpsocket/BLACKLIST
+++ b/tests/auto/network/socket/qtcpsocket/BLACKLIST
@@ -1,7 +1,24 @@
[timeoutConnect:ip]
windows
-[connectToHostError]
-windows-10 gcc developer-build
+# QTBUG-101274
+[timeoutConnect:WithSocks5Proxy:ip]
+qnx ci
+[timeoutConnect:WithSocks5ProxyAuth:ip]
+qnx ci
+[timeoutConnect:WithHttpProxy:ip]
+qnx ci
+[timeoutConnect:WithHttpProxyBasicAuth:ip]
+qnx ci
+[timeoutConnect:WithSocks5Proxy SSL:ip]
+qnx ci
+[timeoutConnect:WithSocks5AuthProxy SSL:ip]
+qnx ci
+[timeoutConnect:WithHttpProxy SSL:ip]
+qnx ci
+[timeoutConnect:WithHttpProxyBasicAuth SSL:ip]
+qnx ci
+[suddenRemoteDisconnect:WithoutProxy:Qt4 Client <-> Qt4 Server]
+qnx ci
# QTBUG-66247
[delayedClose:WithSocks5Proxy]
windows-10 gcc developer-build
@@ -53,3 +70,8 @@ windows-10 gcc developer-build
windows-10 gcc developer-build
[bind]
macos arm
+# QTBUG-101274
+[bindThenResolveHost:WithoutProxy:first-fail]
+qnx ci
+[bindThenResolveHost:WithoutProxy SSL:first-fail]
+qnx ci
diff --git a/tests/auto/network/socket/qtcpsocket/CMakeLists.txt b/tests/auto/network/socket/qtcpsocket/CMakeLists.txt
index 645c65671a..7b6bb4d881 100644
--- a/tests/auto/network/socket/qtcpsocket/CMakeLists.txt
+++ b/tests/auto/network/socket/qtcpsocket/CMakeLists.txt
@@ -1,4 +1,11 @@
-# Generated from qtcpsocket.pro.
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
+
+if(NOT QT_BUILD_STANDALONE_TESTS AND NOT QT_BUILDING_QT)
+ cmake_minimum_required(VERSION 3.16)
+ project(tst_qtcpsocket LANGUAGES CXX)
+ find_package(Qt6BuildInternals REQUIRED COMPONENTS STANDALONE_TEST)
+endif()
if(NOT QT_FEATURE_private_tests)
return()
diff --git a/tests/auto/network/socket/qtcpsocket/stressTest/CMakeLists.txt b/tests/auto/network/socket/qtcpsocket/stressTest/CMakeLists.txt
index 950c4356e2..3ea6c55895 100644
--- a/tests/auto/network/socket/qtcpsocket/stressTest/CMakeLists.txt
+++ b/tests/auto/network/socket/qtcpsocket/stressTest/CMakeLists.txt
@@ -1,4 +1,5 @@
-# Generated from stressTest.pro.
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
#####################################################################
## stressTest Binary:
@@ -9,11 +10,7 @@ qt_internal_add_executable(stressTest
SOURCES
Test.cpp Test.h
main.cpp
- PUBLIC_LIBRARIES
+ LIBRARIES
Qt::Network
Qt::Test
)
-
-#### Keys ignored in scope 1:.:.:stressTest.pro:<TRUE>:
-# MOC_DIR = ".moc/"
-# TMP_DIR = ".tmp/"
diff --git a/tests/auto/network/socket/qtcpsocket/stressTest/Test.cpp b/tests/auto/network/socket/qtcpsocket/stressTest/Test.cpp
index ed61db1a13..8d6e470220 100644
--- a/tests/auto/network/socket/qtcpsocket/stressTest/Test.cpp
+++ b/tests/auto/network/socket/qtcpsocket/stressTest/Test.cpp
@@ -1,30 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
// Qt
#include <QByteArray>
#include <QCoreApplication>
diff --git a/tests/auto/network/socket/qtcpsocket/stressTest/Test.h b/tests/auto/network/socket/qtcpsocket/stressTest/Test.h
index 5e6b2b9467..495b90d733 100644
--- a/tests/auto/network/socket/qtcpsocket/stressTest/Test.h
+++ b/tests/auto/network/socket/qtcpsocket/stressTest/Test.h
@@ -1,30 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
#ifndef TEST_H
#define TEST_H
diff --git a/tests/auto/network/socket/qtcpsocket/stressTest/main.cpp b/tests/auto/network/socket/qtcpsocket/stressTest/main.cpp
index 1948389e37..f989a4de34 100644
--- a/tests/auto/network/socket/qtcpsocket/stressTest/main.cpp
+++ b/tests/auto/network/socket/qtcpsocket/stressTest/main.cpp
@@ -1,30 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
#include "Test.h"
#include <QCoreApplication>
diff --git a/tests/auto/network/socket/qtcpsocket/test/CMakeLists.txt b/tests/auto/network/socket/qtcpsocket/test/CMakeLists.txt
index 759f655417..c3258f8a95 100644
--- a/tests/auto/network/socket/qtcpsocket/test/CMakeLists.txt
+++ b/tests/auto/network/socket/qtcpsocket/test/CMakeLists.txt
@@ -1,35 +1,24 @@
-# Generated from test.pro.
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
#####################################################################
## tst_qtcpsocket Test:
#####################################################################
qt_internal_add_test(tst_qtcpsocket
- OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/../" # special case
+ OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/../"
SOURCES
../tst_qtcpsocket.cpp
- PUBLIC_LIBRARIES
+ LIBRARIES
Qt::CorePrivate
Qt::NetworkPrivate
- QT_TEST_SERVER_LIST "danted" "squid" "apache2" "ftp-proxy" "vsftpd" "iptables" "cyrus" # special case
+ QT_TEST_SERVER_LIST "danted" "squid" "apache2" "ftp-proxy" "vsftpd" "iptables" "cyrus"
)
## Scopes:
#####################################################################
qt_internal_extend_target(tst_qtcpsocket CONDITION WIN32
- PUBLIC_LIBRARIES
+ LIBRARIES
ws2_32
)
-
-#### Keys ignored in scope 4:.:.:test.pro:(CMAKE_BUILD_TYPE STREQUAL Debug):
-# DESTDIR = "../debug"
-
-#### Keys ignored in scope 5:.:.:test.pro:else:
-# DESTDIR = "../release"
-
-#### Keys ignored in scope 6:.:.:test.pro:else:
-# DESTDIR = "../"
-
-#### Keys ignored in scope 7:.:.:test.pro:LINUX:
-# QT_TEST_SERVER_LIST = "danted" "squid" "apache2" "ftp-proxy" "vsftpd" "iptables" "cyrus"
diff --git a/tests/auto/network/socket/qtcpsocket/tst_qtcpsocket.cpp b/tests/auto/network/socket/qtcpsocket/tst_qtcpsocket.cpp
index 4d903a710a..4ec01a9d94 100644
--- a/tests/auto/network/socket/qtcpsocket/tst_qtcpsocket.cpp
+++ b/tests/auto/network/socket/qtcpsocket/tst_qtcpsocket.cpp
@@ -1,36 +1,9 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Copyright (C) 2017 Intel Corporation.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// Copyright (C) 2017 Intel Corporation.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
#include <qglobal.h>
-// To prevent windows system header files from re-defining min/max
-#define NOMINMAX 1
#if defined(_WIN32)
#include <winsock2.h>
#else
@@ -83,14 +56,12 @@
#include <memory>
-#ifdef Q_OS_LINUX
-#include "private/qnativesocketengine_p.h"
-#endif // Q_OS_LINUX
-
#include "private/qhostinfo_p.h"
#include "../../../network-settings.h"
+using namespace Qt::StringLiterals;
+
QT_FORWARD_DECLARE_CLASS(QTcpSocket)
class SocketPair;
@@ -312,7 +283,7 @@ tst_QTcpSocket::tst_QTcpSocket()
tmpSocket = 0;
//This code relates to the socketsConstructedBeforeEventLoop test case
- earlyConstructedSockets = new SocketPair;
+ earlyConstructedSockets = new SocketPair(this);
QVERIFY(earlyConstructedSockets->create());
earlyBytesWrittenCount = 0;
earlyReadyReadCount = 0;
@@ -361,7 +332,8 @@ void tst_QTcpSocket::initTestCase()
//QVERIFY(QtNetworkSettings::verifyConnection(QtNetworkSettings::firewallServerName(), 1357));
QVERIFY(QtNetworkSettings::verifyConnection(QtNetworkSettings::socksProxyServerName(), 1080));
QVERIFY(QtNetworkSettings::verifyConnection(QtNetworkSettings::ftpServerName(), 21));
- QVERIFY(QtNetworkSettings::verifyConnection(QtNetworkSettings::ftpProxyServerName(), 2121));
+ // FTP currently not supported:
+ // QVERIFY(QtNetworkSettings::verifyConnection(QtNetworkSettings::ftpProxyServerName(), 2121));
#else
if (!QtNetworkSettings::verifyTestNetworkSettings())
QSKIP("No network test server available");
@@ -376,8 +348,8 @@ void tst_QTcpSocket::init()
QFETCH_GLOBAL(int, proxyType);
QList<QHostAddress> socks5Addresses = QHostInfo::fromName(QtNetworkSettings::socksProxyServerName()).addresses();
QList<QHostAddress> httpProxyAddresses = QHostInfo::fromName(QtNetworkSettings::httpProxyServerName()).addresses();
- QVERIFY2(socks5Addresses.count() > 0, "failed to get ip address for SOCKS5 proxy server");
- QVERIFY2(httpProxyAddresses.count() > 0, "failed to get ip address for HTTP proxy server");
+ QVERIFY2(socks5Addresses.size() > 0, "failed to get ip address for SOCKS5 proxy server");
+ QVERIFY2(httpProxyAddresses.size() > 0, "failed to get ip address for HTTP proxy server");
QString socks5Address = socks5Addresses.first().toString();
QString httpProxyAddress = httpProxyAddresses.first().toString();
QNetworkProxy proxy;
@@ -517,12 +489,13 @@ void tst_QTcpSocket::bind_data()
bool testIpv6 = false;
// iterate all interfaces, add all addresses on them as test data
- QList<QNetworkInterface> interfaces = QNetworkInterface::allInterfaces();
- foreach (const QNetworkInterface &netinterface, interfaces) {
+ const QList<QNetworkInterface> interfaces = QNetworkInterface::allInterfaces();
+ for (const QNetworkInterface &netinterface : interfaces) {
if (!netinterface.isValid())
continue;
- foreach (const QNetworkAddressEntry &entry, netinterface.addressEntries()) {
+ const auto entries = netinterface.addressEntries();
+ for (const QNetworkAddressEntry &entry : entries) {
if (entry.ip().isInSubnet(QHostAddress::parseSubnet("fe80::/10"))
|| entry.ip().isInSubnet(QHostAddress::parseSubnet("169.254/16")))
continue; // link-local bind will fail, at least on Linux, so skip it.
@@ -552,12 +525,12 @@ void tst_QTcpSocket::bind_data()
// these ranges are guaranteed to be reserved for 'documentation purposes',
// and thus, should be unused in the real world. Not that I'm assuming the
// world is full of competent administrators, or anything.
- QStringList knownBad;
- knownBad << "198.51.100.1";
- knownBad << "2001:0DB8::1";
- foreach (const QString &badAddress, knownBad) {
+ const QString knownBad[] = {
+ u"198.51.100.1"_s,
+ u"2001:0DB8::1"_s
+ };
+ for (const QString &badAddress : knownBad)
QTest::addRow("%s:0", badAddress.toLatin1().constData()) << badAddress << 0 << false << QString();
- }
// try to bind to a privileged ports
// we should fail if we're not root (unless the ports are in use!)
@@ -592,7 +565,7 @@ void tst_QTcpSocket::bind()
std::unique_ptr<QTcpSocket> socket(newSocket());
quint16 boundPort;
- qintptr fd;
+ qintptr fd = 0;
if (successExpected) {
bool randomPort = port == -1;
@@ -1810,7 +1783,7 @@ void tst_QTcpSocket::recursiveReadyRead()
QVERIFY2(!timeout(),
"Timed out when waiting for the readyRead() signal.");
- QCOMPARE(spy.count(), 1);
+ QCOMPARE(spy.size(), 1);
delete testSocket;
}
@@ -1852,7 +1825,7 @@ void tst_QTcpSocket::atEnd()
QVERIFY2(greeting.startsWith("220 (vsFTPd 3."), qPrintable(greeting));
#else
// Test server must use some vsFTPd 2.x.x version
- QVERIFY2(greeting.length() == sizeof("220 (vsFTPd 2.x.x)")-1, qPrintable(greeting));
+ QVERIFY2(greeting.size() == sizeof("220 (vsFTPd 2.x.x)")-1, qPrintable(greeting));
QVERIFY2(greeting.startsWith("220 (vsFTPd 2."), qPrintable(greeting));
#endif
QVERIFY2(greeting.endsWith(QLatin1Char(')')), qPrintable(greeting));
@@ -2035,8 +2008,8 @@ void tst_QTcpSocket::remoteCloseError()
enterLoop(30);
QVERIFY(!timeout());
- QCOMPARE(disconnectedSpy.count(), 1);
- QCOMPARE(errorSpy.count(), 1);
+ QCOMPARE(disconnectedSpy.size(), 1);
+ QCOMPARE(errorSpy.size(), 1);
QCOMPARE(clientSocket->error(), QAbstractSocket::RemoteHostClosedError);
delete serverSocket;
@@ -2167,7 +2140,7 @@ void tst_QTcpSocket::waitForConnectedInHostLookupSlot()
if (tmpSocket->state() != QAbstractSocket::ConnectedState)
loop.exec();
- QCOMPARE(timerSpy.count(), 0);
+ QCOMPARE(timerSpy.size(), 0);
delete tmpSocket;
}
@@ -2221,7 +2194,7 @@ public slots:
#if defined(Q_OS_MAC)
pthread_yield_np();
#elif defined Q_OS_LINUX && !defined Q_OS_ANDROID
- pthread_yield();
+ sched_yield();
#endif
if (!sock->waitForConnected()) {
networkTimeout = true;
@@ -2272,7 +2245,7 @@ void tst_QTcpSocket::readyReadSignalsAfterWaitForReadyRead()
// Wait for the read
QVERIFY(socket->waitForReadyRead(10000));
- QCOMPARE(readyReadSpy.count(), 1);
+ QCOMPARE(readyReadSpy.size(), 1);
QString s = socket->readLine();
QVERIFY2(QtNetworkSettings::compareReplyIMAP(s.toLatin1()), s.toLatin1().constData());
@@ -2280,7 +2253,7 @@ void tst_QTcpSocket::readyReadSignalsAfterWaitForReadyRead()
QCoreApplication::instance()->processEvents();
QCOMPARE(socket->bytesAvailable(), qint64(0));
- QCOMPARE(readyReadSpy.count(), 1);
+ QCOMPARE(readyReadSpy.size(), 1);
delete socket;
}
@@ -2354,8 +2327,8 @@ void tst_QTcpSocket::abortiveClose()
enterLoop(5);
- QCOMPARE(readyReadSpy.count(), 0);
- QCOMPARE(errorSpy.count(), 1);
+ QCOMPARE(readyReadSpy.size(), 0);
+ QCOMPARE(errorSpy.size(), 1);
QCOMPARE(*static_cast<const int *>(errorSpy.at(0).at(0).constData()),
int(QAbstractSocket::RemoteHostClosedError));
@@ -2474,11 +2447,11 @@ void tst_QTcpSocket::connectionRefused()
QCOMPARE(socket->state(), QAbstractSocket::UnconnectedState);
QCOMPARE(socket->error(), QAbstractSocket::ConnectionRefusedError);
- QCOMPARE(stateSpy.count(), 3);
+ QCOMPARE(stateSpy.size(), 3);
QCOMPARE(qvariant_cast<QAbstractSocket::SocketState>(stateSpy.at(0).at(0)), QAbstractSocket::HostLookupState);
QCOMPARE(qvariant_cast<QAbstractSocket::SocketState>(stateSpy.at(1).at(0)), QAbstractSocket::ConnectingState);
QCOMPARE(qvariant_cast<QAbstractSocket::SocketState>(stateSpy.at(2).at(0)), QAbstractSocket::UnconnectedState);
- QCOMPARE(errorSpy.count(), 1);
+ QCOMPARE(errorSpy.size(), 1);
delete socket;
}
@@ -2610,7 +2583,7 @@ void tst_QTcpSocket::moveToThread0()
{
// Case 1: Moved after connecting, before waiting for connection.
- QTcpSocket *socket = newSocket();;
+ QTcpSocket *socket = newSocket();
socket->connectToHost(QtNetworkSettings::imapServerName(), 143);
socket->moveToThread(0);
QVERIFY(socket->waitForConnected(5000));
@@ -2941,6 +2914,7 @@ void tst_QTcpSocket::proxyFactory_data()
<< proxyList << proxyList.at(1)
<< false << int(QAbstractSocket::UnknownSocketError);
+#if 0 // FTP not currently supported
proxyList.clear();
proxyList << QNetworkProxy(QNetworkProxy::FtpCachingProxy, QtNetworkSettings::ftpProxyServerName(), 2121)
<< QNetworkProxy(QNetworkProxy::HttpCachingProxy, QtNetworkSettings::httpProxyServerName(), 3129)
@@ -2948,6 +2922,7 @@ void tst_QTcpSocket::proxyFactory_data()
QTest::newRow("ftp+cachinghttp+socks5")
<< proxyList << proxyList.at(2)
<< false << int(QAbstractSocket::UnknownSocketError);
+#endif
// tests that fail to connect
proxyList.clear();
@@ -2956,6 +2931,7 @@ void tst_QTcpSocket::proxyFactory_data()
<< proxyList << QNetworkProxy()
<< true << int(QAbstractSocket::UnsupportedSocketOperationError);
+#if 0 // FTP not currently supported
proxyList.clear();
proxyList << QNetworkProxy(QNetworkProxy::FtpCachingProxy, QtNetworkSettings::ftpProxyServerName(), 2121);
QTest::newRow("ftp")
@@ -2968,6 +2944,7 @@ void tst_QTcpSocket::proxyFactory_data()
QTest::newRow("ftp+cachinghttp")
<< proxyList << QNetworkProxy()
<< true << int(QAbstractSocket::UnsupportedSocketOperationError);
+#endif
}
void tst_QTcpSocket::proxyFactory()
@@ -3147,8 +3124,8 @@ void tst_QTcpSocket::serverDisconnectWithBuffered()
QCOMPARE(socket->state(), QAbstractSocket::UnconnectedState);
}
// Test signal emitting
- QCOMPARE(spyDisconnected.count(), 1);
- QVERIFY(spyStateChanged.count() > 0);
+ QCOMPARE(spyDisconnected.size(), 1);
+ QVERIFY(spyStateChanged.size() > 0);
QVERIFY(qvariant_cast<QAbstractSocket::SocketState>(spyStateChanged.last().first())
== QAbstractSocket::UnconnectedState);
@@ -3237,7 +3214,7 @@ void tst_QTcpSocket::readNotificationsAfterBind()
QTestEventLoop::instance().enterLoop(10);
QVERIFY2(!QTestEventLoop::instance().timeout(), "Connection to closed port timed out instead of refusing, something is wrong");
QVERIFY2(socket.state() == QAbstractSocket::UnconnectedState, "Socket connected unexpectedly!");
- QCOMPARE(spyReadyRead.count(), 0);
+ QCOMPARE(spyReadyRead.size(), 0);
}
QTEST_MAIN(tst_QTcpSocket)
diff --git a/tests/auto/network/socket/qudpsocket/BLACKLIST b/tests/auto/network/socket/qudpsocket/BLACKLIST
index 9d4396deb6..f5f6a8e156 100644
--- a/tests/auto/network/socket/qudpsocket/BLACKLIST
+++ b/tests/auto/network/socket/qudpsocket/BLACKLIST
@@ -1,13 +1,7 @@
[writeDatagramToNonExistingPeer]
windows
-# QTBUG-85364
-windows-10 gcc cmake
[readyReadForEmptyDatagram]
opensuse-leap
-[echo]
-opensuse-42.3
-[readyReadForEmptyDatagram]
-linux
[multicast]
centos
macos arm
diff --git a/tests/auto/network/socket/qudpsocket/CMakeLists.txt b/tests/auto/network/socket/qudpsocket/CMakeLists.txt
index b9d0646e58..a7a2659340 100644
--- a/tests/auto/network/socket/qudpsocket/CMakeLists.txt
+++ b/tests/auto/network/socket/qudpsocket/CMakeLists.txt
@@ -1,4 +1,11 @@
-# Generated from qudpsocket.pro.
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
+
+if(NOT QT_BUILD_STANDALONE_TESTS AND NOT QT_BUILDING_QT)
+ cmake_minimum_required(VERSION 3.16)
+ project(tst_qudpsocket LANGUAGES CXX)
+ find_package(Qt6BuildInternals REQUIRED COMPONENTS STANDALONE_TEST)
+endif()
-add_subdirectory(test)
add_subdirectory(clientserver)
+add_subdirectory(test)
diff --git a/tests/auto/network/socket/qudpsocket/clientserver/CMakeLists.txt b/tests/auto/network/socket/qudpsocket/clientserver/CMakeLists.txt
index 7c8b924ca9..4644d0d96f 100644
--- a/tests/auto/network/socket/qudpsocket/clientserver/CMakeLists.txt
+++ b/tests/auto/network/socket/qudpsocket/clientserver/CMakeLists.txt
@@ -1,4 +1,5 @@
-# Generated from clientserver.pro.
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
#####################################################################
## clientserver Binary:
@@ -8,6 +9,6 @@ qt_internal_add_executable(clientserver
OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/"
SOURCES
main.cpp
- PUBLIC_LIBRARIES
+ LIBRARIES
Qt::Network
)
diff --git a/tests/auto/network/socket/qudpsocket/clientserver/main.cpp b/tests/auto/network/socket/qudpsocket/clientserver/main.cpp
index 705abf87e3..76bdf3aada 100644
--- a/tests/auto/network/socket/qudpsocket/clientserver/main.cpp
+++ b/tests/auto/network/socket/qudpsocket/clientserver/main.cpp
@@ -1,30 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
#include <QtNetwork>
class ClientServer : public QUdpSocket
diff --git a/tests/auto/network/socket/qudpsocket/test/CMakeLists.txt b/tests/auto/network/socket/qudpsocket/test/CMakeLists.txt
index 6a781aadc4..69b62c2f9f 100644
--- a/tests/auto/network/socket/qudpsocket/test/CMakeLists.txt
+++ b/tests/auto/network/socket/qudpsocket/test/CMakeLists.txt
@@ -1,34 +1,20 @@
-# Generated from test.pro.
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
#####################################################################
## tst_qudpsocket Test:
#####################################################################
qt_internal_add_test(tst_qudpsocket
- OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/../" # special case
+ OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/../"
SOURCES
../tst_qudpsocket.cpp
- PUBLIC_LIBRARIES
+ LIBRARIES
Qt::Network
Qt::TestPrivate
- QT_TEST_SERVER_LIST "danted" "echo" # special case
+ QT_TEST_SERVER_LIST "danted" "echo"
)
-#### Keys ignored in scope 1:.:.:test.pro:<TRUE>:
-# MOC_DIR = "tmp"
-# testcase.timeout = "800"
-
-## Scopes:
-#####################################################################
-
-#### Keys ignored in scope 3:.:.:test.pro:(CMAKE_BUILD_TYPE STREQUAL Debug):
-# DESTDIR = "../debug"
-
-#### Keys ignored in scope 4:.:.:test.pro:else:
-# DESTDIR = "../release"
-
-#### Keys ignored in scope 5:.:.:test.pro:else:
-# DESTDIR = "../"
-
-#### Keys ignored in scope 6:.:.:test.pro:LINUX:
-# QT_TEST_SERVER_LIST = "danted" "echo"
+if(QT_FEATURE_process)
+ add_dependencies(tst_qudpsocket clientserver)
+endif()
diff --git a/tests/auto/network/socket/qudpsocket/tst_qudpsocket.cpp b/tests/auto/network/socket/qudpsocket/tst_qudpsocket.cpp
index 31fd1a3b30..689ff452f9 100644
--- a/tests/auto/network/socket/qudpsocket/tst_qudpsocket.cpp
+++ b/tests/auto/network/socket/qudpsocket/tst_qudpsocket.cpp
@@ -1,32 +1,6 @@
-/****************************************************************************
-**
-** Copyright (C) 2021 The Qt Company Ltd.
-** Copyright (C) 2017 Intel Corporation.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
+// Copyright (C) 2021 The Qt Company Ltd.
+// Copyright (C) 2017 Intel Corporation.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
#include <QTest>
#include <QSignalSpy>
@@ -36,6 +10,7 @@
#endif
#include <QScopeGuard>
#include <QVersionNumber>
+#include <QSemaphore>
#include <qcoreapplication.h>
#include <qfileinfo.h>
@@ -53,6 +28,7 @@
#include <QNetworkInterface>
#include <qstringlist.h>
+#include <QSet>
#include "../../../network-settings.h"
#include <QtTest/private/qemulationdetector_p.h>
@@ -70,6 +46,8 @@
# define RELIABLE_BYTES_AVAILABLE
#endif
+using namespace Qt::StringLiterals;
+
Q_DECLARE_METATYPE(QHostAddress)
QT_FORWARD_DECLARE_CLASS(QUdpSocket)
@@ -127,6 +105,8 @@ private slots:
void asyncReadDatagram();
void writeInHostLookupState();
+ void readyReadConnectionThrottling();
+
protected slots:
void empty_readyReadSlot();
void empty_connectedSlot();
@@ -145,6 +125,7 @@ private:
QList<QHostAddress> allAddresses;
QHostAddress multicastGroup4, multicastGroup6;
QList<QHostAddress> linklocalMulticastGroups;
+ QNetworkInterface ifaceWithIPv6;
QUdpSocket *m_asyncSender;
QUdpSocket *m_asyncReceiver;
};
@@ -195,26 +176,7 @@ QNetworkInterface tst_QUdpSocket::interfaceForGroup(const QHostAddress &multicas
if (!scope.isEmpty())
return QNetworkInterface::interfaceFromName(scope);
- static QNetworkInterface ipv6if = [&]() {
- // find any link local address in the allAddress list
- for (const QHostAddress &addr: qAsConst(allAddresses)) {
- if (addr.isLoopback())
- continue;
-
- QString scope = addr.scopeId();
- if (!scope.isEmpty()) {
- QNetworkInterface iface = QNetworkInterface::interfaceFromName(scope);
- qDebug() << "Will bind IPv6 sockets to" << iface;
- return iface;
- }
- }
-
- qWarning("interfaceForGroup(%s) could not find any link-local IPv6 address! "
- "Make sure this test is behind a check of QtNetworkSettings::hasIPv6().",
- qUtf8Printable(multicastGroup.toString()));
- return QNetworkInterface();
- }();
- return ipv6if;
+ return ifaceWithIPv6;
}
bool tst_QUdpSocket::shouldWorkaroundLinuxKernelBug()
@@ -293,15 +255,22 @@ void tst_QUdpSocket::initTestCase()
// ff12:: is temporary, not prefix-based, link-local
r[0] = qToBigEndian(Q_UINT64_C(0xff12) << 48);
QHostAddress llbase(*reinterpret_cast<Q_IPV6ADDR *>(&r));
- for (const QHostAddress &a : qAsConst(allAddresses)) {
+ for (const QHostAddress &a : std::as_const(allAddresses)) {
QString scope = a.scopeId();
if (scope.isEmpty())
continue;
llbase.setScopeId(scope);
linklocalMulticastGroups << llbase;
+ if (!ifaceWithIPv6.isValid()) {
+ // Remember the first interface we've found that has IPv6 so we can
+ // bind non-link-local sockets to it (the first is least likely to
+ // be some weird virtual interface).
+ ifaceWithIPv6 = QNetworkInterface::interfaceFromName(scope);
+ }
}
qDebug() << "Will use multicast groups" << multicastGroup4 << multicastGroup6 << linklocalMulticastGroups;
+ qDebug() << "Will bind IPv6 sockets to" << ifaceWithIPv6;
m_workaroundLinuxKernelBug = shouldWorkaroundLinuxKernelBug();
if (QTestPrivate::isRunningArmOnX86())
@@ -358,7 +327,7 @@ void tst_QUdpSocket::unconnectedServerAndClientTest()
QSignalSpy stateChangedSpy(&serverSocket, SIGNAL(stateChanged(QAbstractSocket::SocketState)));
QVERIFY2(serverSocket.bind(), serverSocket.errorString().toLatin1().constData());
- QCOMPARE(stateChangedSpy.count(), 1);
+ QCOMPARE(stateChangedSpy.size(), 1);
const char *message[] = {"Yo mista", "Yo", "Wassap"};
@@ -407,10 +376,11 @@ void tst_QUdpSocket::broadcasting()
const char *message[] = {"Yo mista", "", "Yo", "Wassap"};
QList<QHostAddress> broadcastAddresses;
- foreach (QNetworkInterface iface, QNetworkInterface::allInterfaces()) {
+ const auto ifaces = QNetworkInterface::allInterfaces();
+ for (const QNetworkInterface &iface : ifaces) {
if ((iface.flags() & QNetworkInterface::CanBroadcast)
&& iface.flags() & QNetworkInterface::IsUp) {
- for (int i=0;i<iface.addressEntries().count();i++) {
+ for (int i=0;i<iface.addressEntries().size();i++) {
QHostAddress broadcast = iface.addressEntries().at(i).broadcast();
if (broadcast.protocol() == QAbstractSocket::IPv4Protocol)
broadcastAddresses.append(broadcast);
@@ -435,7 +405,7 @@ void tst_QUdpSocket::broadcasting()
for (int k = 0; k < 4; k++) {
broadcastSocket.writeDatagram(message[i], strlen(message[i]),
QHostAddress::Broadcast, serverPort);
- foreach (QHostAddress addr, broadcastAddresses)
+ for (const QHostAddress &addr : std::as_const(broadcastAddresses))
broadcastSocket.writeDatagram(message[i], strlen(message[i]), addr, serverPort);
}
QTestEventLoop::instance().enterLoop(15);
@@ -455,7 +425,7 @@ void tst_QUdpSocket::broadcasting()
QVERIFY(dgram.isValid());
QByteArray arr = dgram.data();
- QCOMPARE(arr.length(), messageLength);
+ QCOMPARE(arr.size(), messageLength);
arr.resize(messageLength);
QCOMPARE(arr, QByteArray(message[i]));
@@ -515,27 +485,27 @@ void tst_QUdpSocket::loop()
QHostAddress peterAddress = makeNonAny(peter.localAddress());
QHostAddress paulAddress = makeNonAny(paul.localAddress());
- QCOMPARE(peter.writeDatagram(peterMessage.data(), peterMessage.length(),
- paulAddress, paul.localPort()), qint64(peterMessage.length()));
- QCOMPARE(paul.writeDatagram(paulMessage.data(), paulMessage.length(),
- peterAddress, peter.localPort()), qint64(paulMessage.length()));
+ QCOMPARE(peter.writeDatagram(peterMessage.data(), peterMessage.size(),
+ paulAddress, paul.localPort()), qint64(peterMessage.size()));
+ QCOMPARE(paul.writeDatagram(paulMessage.data(), paulMessage.size(),
+ peterAddress, peter.localPort()), qint64(paulMessage.size()));
QVERIFY2(peter.waitForReadyRead(9000), QtNetworkSettings::msgSocketError(peter).constData());
QVERIFY2(paul.waitForReadyRead(9000), QtNetworkSettings::msgSocketError(paul).constData());
- QNetworkDatagram peterDatagram = peter.receiveDatagram(paulMessage.length() * 2);
- QNetworkDatagram paulDatagram = paul.receiveDatagram(peterMessage.length() * 2);
+ QNetworkDatagram peterDatagram = peter.receiveDatagram(paulMessage.size() * 2);
+ QNetworkDatagram paulDatagram = paul.receiveDatagram(peterMessage.size() * 2);
if (success) {
- QCOMPARE(peterDatagram.data().length(), qint64(paulMessage.length()));
- QCOMPARE(paulDatagram.data().length(), qint64(peterMessage.length()));
+ QCOMPARE(peterDatagram.data().size(), qint64(paulMessage.size()));
+ QCOMPARE(paulDatagram.data().size(), qint64(peterMessage.size()));
} else {
// this code path seems to never be executed
- QVERIFY(peterDatagram.data().length() != paulMessage.length());
- QVERIFY(paulDatagram.data().length() != peterMessage.length());
+ QVERIFY(peterDatagram.data().size() != paulMessage.size());
+ QVERIFY(paulDatagram.data().size() != peterMessage.size());
}
- QCOMPARE(peterDatagram.data().left(paulMessage.length()), paulMessage);
- QCOMPARE(paulDatagram.data().left(peterMessage.length()), peterMessage);
+ QCOMPARE(peterDatagram.data().left(paulMessage.size()), paulMessage);
+ QCOMPARE(paulDatagram.data().left(peterMessage.size()), peterMessage);
QCOMPARE(peterDatagram.senderAddress(), paulAddress);
QCOMPARE(paulDatagram.senderAddress(), peterAddress);
@@ -592,27 +562,27 @@ void tst_QUdpSocket::ipv6Loop()
peterPort = peter.localPort();
paulPort = paul.localPort();
- QCOMPARE(peter.writeDatagram(peterMessage.data(), peterMessage.length(), QHostAddress("::1"),
- paulPort), qint64(peterMessage.length()));
- QCOMPARE(paul.writeDatagram(paulMessage.data(), paulMessage.length(),
- QHostAddress("::1"), peterPort), qint64(paulMessage.length()));
+ QCOMPARE(peter.writeDatagram(peterMessage.data(), peterMessage.size(), QHostAddress("::1"),
+ paulPort), qint64(peterMessage.size()));
+ QCOMPARE(paul.writeDatagram(paulMessage.data(), paulMessage.size(),
+ QHostAddress("::1"), peterPort), qint64(paulMessage.size()));
QVERIFY(peter.waitForReadyRead(5000));
QVERIFY(paul.waitForReadyRead(5000));
- QNetworkDatagram peterDatagram = peter.receiveDatagram(paulMessage.length() * 2);
- QNetworkDatagram paulDatagram = paul.receiveDatagram(peterMessage.length() * 2);
+ QNetworkDatagram peterDatagram = peter.receiveDatagram(paulMessage.size() * 2);
+ QNetworkDatagram paulDatagram = paul.receiveDatagram(peterMessage.size() * 2);
if (success) {
- QCOMPARE(peterDatagram.data().length(), qint64(paulMessage.length()));
- QCOMPARE(paulDatagram.data().length(), qint64(peterMessage.length()));
+ QCOMPARE(peterDatagram.data().size(), qint64(paulMessage.size()));
+ QCOMPARE(paulDatagram.data().size(), qint64(peterMessage.size()));
} else {
// this code path seems to never be executed
- QVERIFY(peterDatagram.data().length() != paulMessage.length());
- QVERIFY(paulDatagram.data().length() != peterMessage.length());
+ QVERIFY(peterDatagram.data().size() != paulMessage.size());
+ QVERIFY(paulDatagram.data().size() != peterMessage.size());
}
- QCOMPARE(peterDatagram.data().left(paulMessage.length()), paulMessage);
- QCOMPARE(paulDatagram.data().left(peterMessage.length()), peterMessage);
+ QCOMPARE(peterDatagram.data().left(paulMessage.size()), paulMessage);
+ QCOMPARE(paulDatagram.data().left(peterMessage.size()), peterMessage);
QCOMPARE(peterDatagram.senderAddress(), paulAddress);
QCOMPARE(paulDatagram.senderAddress(), peterAddress);
@@ -640,7 +610,7 @@ void tst_QUdpSocket::dualStack()
QVERIFY(v4Sock.bind(QHostAddress(QHostAddress::AnyIPv4), 0));
//test v4 -> dual
- QCOMPARE((int)v4Sock.writeDatagram(v4Data.constData(), v4Data.length(), QHostAddress(QHostAddress::LocalHost), dualSock.localPort()), v4Data.length());
+ QCOMPARE((int)v4Sock.writeDatagram(v4Data.constData(), v4Data.size(), QHostAddress(QHostAddress::LocalHost), dualSock.localPort()), v4Data.size());
QVERIFY2(dualSock.waitForReadyRead(5000), QtNetworkSettings::msgSocketError(dualSock).constData());
QNetworkDatagram dgram = dualSock.receiveDatagram(100);
QVERIFY(dgram.isValid());
@@ -652,7 +622,7 @@ void tst_QUdpSocket::dualStack()
QCOMPARE(dgram.senderAddress(), makeNonAny(v4Sock.localAddress(), QHostAddress::Null));
if (dgram.destinationPort() != -1) {
QCOMPARE(dgram.destinationPort(), int(dualSock.localPort()));
- QVERIFY(dgram.destinationAddress().isEqual(dualSock.localAddress()));
+ QVERIFY(dgram.destinationAddress().isEqual(makeNonAny(dualSock.localAddress(), QHostAddress::LocalHost)));
} else {
qInfo("Getting IPv4 destination address failed.");
}
@@ -663,7 +633,7 @@ void tst_QUdpSocket::dualStack()
QVERIFY(v6Sock.bind(QHostAddress(QHostAddress::AnyIPv6), 0));
//test v6 -> dual
- QCOMPARE((int)v6Sock.writeDatagram(v6Data.constData(), v6Data.length(), QHostAddress(QHostAddress::LocalHostIPv6), dualSock.localPort()), v6Data.length());
+ QCOMPARE((int)v6Sock.writeDatagram(v6Data.constData(), v6Data.size(), QHostAddress(QHostAddress::LocalHostIPv6), dualSock.localPort()), v6Data.size());
QVERIFY2(dualSock.waitForReadyRead(5000), QtNetworkSettings::msgSocketError(dualSock).constData());
dgram = dualSock.receiveDatagram(100);
QVERIFY(dgram.isValid());
@@ -674,7 +644,7 @@ void tst_QUdpSocket::dualStack()
QCOMPARE(dgram.destinationAddress(), makeNonAny(dualSock.localAddress(), QHostAddress::LocalHostIPv6));
//test dual -> v6
- QCOMPARE((int)dualSock.writeDatagram(dualData.constData(), dualData.length(), QHostAddress(QHostAddress::LocalHostIPv6), v6Sock.localPort()), dualData.length());
+ QCOMPARE((int)dualSock.writeDatagram(dualData.constData(), dualData.size(), QHostAddress(QHostAddress::LocalHostIPv6), v6Sock.localPort()), dualData.size());
QVERIFY2(v6Sock.waitForReadyRead(5000), QtNetworkSettings::msgSocketError(v6Sock).constData());
dgram = v6Sock.receiveDatagram(100);
QVERIFY(dgram.isValid());
@@ -686,7 +656,7 @@ void tst_QUdpSocket::dualStack()
}
//test dual -> v4
- QCOMPARE((int)dualSock.writeDatagram(dualData.constData(), dualData.length(), QHostAddress(QHostAddress::LocalHost), v4Sock.localPort()), dualData.length());
+ QCOMPARE((int)dualSock.writeDatagram(dualData.constData(), dualData.size(), QHostAddress(QHostAddress::LocalHost), v4Sock.localPort()), dualData.size());
QVERIFY2(v4Sock.waitForReadyRead(5000), QtNetworkSettings::msgSocketError(v4Sock).constData());
dgram = v4Sock.receiveDatagram(100);
QVERIFY(dgram.isValid());
@@ -725,19 +695,19 @@ void tst_QUdpSocket::dualStackAutoBinding()
//test an autobound socket can send to both v4 and v6 addresses (v4 first)
QUdpSocket dualSock;
- QCOMPARE((int)dualSock.writeDatagram(dualData.constData(), dualData.length(), QHostAddress(QHostAddress::LocalHost), v4Sock.localPort()), dualData.length());
+ QCOMPARE((int)dualSock.writeDatagram(dualData.constData(), dualData.size(), QHostAddress(QHostAddress::LocalHost), v4Sock.localPort()), dualData.size());
QVERIFY2(v4Sock.waitForReadyRead(5000), QtNetworkSettings::msgSocketError(v4Sock).constData());
buffer.reserve(100);
size = v4Sock.readDatagram(buffer.data(), 100, &from, &port);
- QCOMPARE((int)size, dualData.length());
+ QCOMPARE((int)size, dualData.size());
buffer.resize(size);
QCOMPARE(buffer, dualData);
- QCOMPARE((int)dualSock.writeDatagram(dualData.constData(), dualData.length(), QHostAddress(QHostAddress::LocalHostIPv6), v6Sock.localPort()), dualData.length());
+ QCOMPARE((int)dualSock.writeDatagram(dualData.constData(), dualData.size(), QHostAddress(QHostAddress::LocalHostIPv6), v6Sock.localPort()), dualData.size());
QVERIFY2(v6Sock.waitForReadyRead(5000), QtNetworkSettings::msgSocketError(v6Sock).constData());
buffer.reserve(100);
size = v6Sock.readDatagram(buffer.data(), 100, &from, &port);
- QCOMPARE((int)size, dualData.length());
+ QCOMPARE((int)size, dualData.size());
buffer.resize(size);
QCOMPARE(buffer, dualData);
}
@@ -746,19 +716,19 @@ void tst_QUdpSocket::dualStackAutoBinding()
//test an autobound socket can send to both v4 and v6 addresses (v6 first)
QUdpSocket dualSock;
- QCOMPARE((int)dualSock.writeDatagram(dualData.constData(), dualData.length(), QHostAddress(QHostAddress::LocalHostIPv6), v6Sock.localPort()), dualData.length());
+ QCOMPARE((int)dualSock.writeDatagram(dualData.constData(), dualData.size(), QHostAddress(QHostAddress::LocalHostIPv6), v6Sock.localPort()), dualData.size());
QVERIFY2(v6Sock.waitForReadyRead(5000), QtNetworkSettings::msgSocketError(v6Sock).constData());
buffer.reserve(100);
size = v6Sock.readDatagram(buffer.data(), 100, &from, &port);
- QCOMPARE((int)size, dualData.length());
+ QCOMPARE((int)size, dualData.size());
buffer.resize(size);
QCOMPARE(buffer, dualData);
- QCOMPARE((int)dualSock.writeDatagram(dualData.constData(), dualData.length(), QHostAddress(QHostAddress::LocalHost), v4Sock.localPort()), dualData.length());
+ QCOMPARE((int)dualSock.writeDatagram(dualData.constData(), dualData.size(), QHostAddress(QHostAddress::LocalHost), v4Sock.localPort()), dualData.size());
QVERIFY2(v4Sock.waitForReadyRead(5000), QtNetworkSettings::msgSocketError(v4Sock).constData());
buffer.reserve(100);
size = v4Sock.readDatagram(buffer.data(), 100, &from, &port);
- QCOMPARE((int)size, dualData.length());
+ QCOMPARE((int)size, dualData.size());
buffer.resize(size);
QCOMPARE(buffer, dualData);
}
@@ -779,7 +749,7 @@ void tst_QUdpSocket::dualStackNoIPv4onV6only()
QVERIFY(v6Sock.bind(QHostAddress(QHostAddress::AnyIPv6), 0));
//test v4 -> v6 (should not be received as this is a v6 only socket)
- QCOMPARE((int)v4Sock.writeDatagram(v4Data.constData(), v4Data.length(), QHostAddress(QHostAddress::LocalHost), v6Sock.localPort()), v4Data.length());
+ QCOMPARE((int)v4Sock.writeDatagram(v4Data.constData(), v4Data.size(), QHostAddress(QHostAddress::LocalHost), v6Sock.localPort()), v4Data.size());
QVERIFY(!v6Sock.waitForReadyRead(1000));
}
@@ -899,17 +869,17 @@ void tst_QUdpSocket::writeDatagram()
#if defined (Q_OS_HPUX)
QSKIP("HP-UX 11.11 on hai (PA-RISC 64) truncates too long datagrams.");
#endif
- QCOMPARE(bytesspy.count(), 0);
- QCOMPARE(errorspy.count(), 1);
+ QCOMPARE(bytesspy.size(), 0);
+ QCOMPARE(errorspy.size(), 1);
QCOMPARE(*static_cast<const int *>(errorspy.at(0).at(0).constData()),
int(QUdpSocket::DatagramTooLargeError));
QCOMPARE(client.error(), QUdpSocket::DatagramTooLargeError);
break;
}
- QCOMPARE(bytesspy.count(), 1);
+ QCOMPARE(bytesspy.size(), 1);
QCOMPARE(*static_cast<const qint64 *>(bytesspy.at(0).at(0).constData()),
qint64(i * 1024));
- QCOMPARE(errorspy.count(), 0);
+ QCOMPARE(errorspy.size(), 0);
if (!server.waitForReadyRead(5000))
QSKIP(QString("UDP packet lost at size %1, unable to complete the test.").arg(i * 1024).toLatin1().data());
QCOMPARE(server.pendingDatagramSize(), qint64(i * 1024));
@@ -1022,7 +992,7 @@ void tst_QUdpSocket::writeDatagramToNonExistingPeer()
QVERIFY(sUdp.bind());
QCOMPARE(sUdp.writeDatagram("", 1, peerAddress, peerPort), qint64(1));
QTestEventLoop::instance().enterLoop(1);
- QCOMPARE(sReadyReadSpy.count(), 0);
+ QCOMPARE(sReadyReadSpy.size(), 0);
}
void tst_QUdpSocket::writeToNonExistingPeer_data()
@@ -1065,8 +1035,8 @@ void tst_QUdpSocket::writeToNonExistingPeer()
// the third one will succeed...
QCOMPARE(sConnected.write("", 1), qint64(1));
QTestEventLoop::instance().enterLoop(1);
- QCOMPARE(sConnectedReadyReadSpy.count(), 0);
- QCOMPARE(sConnectedErrorSpy.count(), 1);
+ QCOMPARE(sConnectedReadyReadSpy.size(), 0);
+ QCOMPARE(sConnectedErrorSpy.size(), 1);
QCOMPARE(int(sConnected.error()), int(QUdpSocket::ConnectionRefusedError));
// we should now get a read error
@@ -1265,11 +1235,12 @@ void tst_QUdpSocket::multicastTtlOption_data()
QTest::addColumn<int>("ttl");
QTest::addColumn<int>("expected");
- QList<QHostAddress> addresses;
- addresses += QHostAddress(QHostAddress::AnyIPv4);
- addresses += QHostAddress(QHostAddress::AnyIPv6);
+ const QHostAddress addresses[] = {
+ QHostAddress(QHostAddress::AnyIPv4),
+ QHostAddress(QHostAddress::AnyIPv6),
+ };
- foreach (const QHostAddress &address, addresses) {
+ for (const QHostAddress &address : addresses) {
const QByteArray addressB = address.toString().toLatin1();
QTest::newRow((addressB + " 0").constData()) << address << 0 << 0;
QTest::newRow((addressB + " 1").constData()) << address << 1 << 1;
@@ -1311,11 +1282,12 @@ void tst_QUdpSocket::multicastLoopbackOption_data()
QTest::addColumn<int>("loopback");
QTest::addColumn<int>("expected");
- QList<QHostAddress> addresses;
- addresses += QHostAddress(QHostAddress::AnyIPv4);
- addresses += QHostAddress(QHostAddress::AnyIPv6);
+ const QHostAddress addresses[] = {
+ QHostAddress(QHostAddress::AnyIPv4),
+ QHostAddress(QHostAddress::AnyIPv6),
+ };
- foreach (const QHostAddress &address, addresses) {
+ for (const QHostAddress &address : addresses) {
const QByteArray addressB = address.toString().toLatin1();
QTest::newRow((addressB + " 0").constData()) << address << 0 << 0;
QTest::newRow((addressB + " 1").constData()) << address << 1 << 1;
@@ -1358,7 +1330,7 @@ void tst_QUdpSocket::multicastJoinBeforeBind_data()
QTest::newRow("valid ipv4 group address") << multicastGroup4;
QTest::newRow("invalid ipv4 group address") << QHostAddress(QHostAddress::Broadcast);
QTest::newRow("valid ipv6 group address") << multicastGroup6;
- for (const QHostAddress &a : qAsConst(linklocalMulticastGroups))
+ for (const QHostAddress &a : std::as_const(linklocalMulticastGroups))
QTest::addRow("valid ipv6 %s-link group address", a.scopeId().toLatin1().constData()) << a;
QTest::newRow("invalid ipv6 group address") << QHostAddress(QHostAddress::AnyIPv6);
}
@@ -1378,7 +1350,7 @@ void tst_QUdpSocket::multicastLeaveAfterClose_data()
QTest::addColumn<QHostAddress>("groupAddress");
QTest::newRow("ipv4") << multicastGroup4;
QTest::newRow("ipv6") << multicastGroup6;
- for (const QHostAddress &a : qAsConst(linklocalMulticastGroups))
+ for (const QHostAddress &a : std::as_const(linklocalMulticastGroups))
QTest::addRow("ipv6-link-%s", a.scopeId().toLatin1().constData()) << a;
}
@@ -1415,11 +1387,12 @@ void tst_QUdpSocket::setMulticastInterface_data()
{
QTest::addColumn<QNetworkInterface>("iface");
QTest::addColumn<QHostAddress>("address");
- QList<QNetworkInterface> interfaces = QNetworkInterface::allInterfaces();
- foreach (const QNetworkInterface &iface, interfaces) {
+ const QList<QNetworkInterface> interfaces = QNetworkInterface::allInterfaces();
+ for (const QNetworkInterface &iface : interfaces) {
if ((iface.flags() & QNetworkInterface::IsUp) == 0)
continue;
- foreach (const QNetworkAddressEntry &entry, iface.addressEntries()) {
+ const auto entries = iface.addressEntries();
+ for (const QNetworkAddressEntry &entry : entries) {
const QByteArray testName = iface.name().toLatin1() + ':' + entry.ip().toString().toLatin1();
QTest::newRow(testName.constData()) << iface << entry.ip();
}
@@ -1472,13 +1445,13 @@ void tst_QUdpSocket::multicast_data()
QTest::newRow("valid bind, group ipv4 address") << anyAddress << true << groupAddress << true;
QTest::newRow("valid bind, invalid group ipv4 address") << anyAddress << true << anyAddress << false;
QTest::newRow("valid bind, group ipv6 address") << any6Address << true << group6Address << true;
- for (const QHostAddress &a : qAsConst(linklocalMulticastGroups))
+ for (const QHostAddress &a : std::as_const(linklocalMulticastGroups))
QTest::addRow("valid bind, %s-link group ipv6 address", a.scopeId().toLatin1().constData())
<< any6Address << true << a << true;
QTest::newRow("valid bind, invalid group ipv6 address") << any6Address << true << any6Address << false;
QTest::newRow("dual bind, group ipv4 address") << dualAddress << true << groupAddress << false;
QTest::newRow("dual bind, group ipv6 address") << dualAddress << true << group6Address << true;
- for (const QHostAddress &a : qAsConst(linklocalMulticastGroups))
+ for (const QHostAddress &a : std::as_const(linklocalMulticastGroups))
QTest::addRow("dual bind, %s-link group ipv6 address", a.scopeId().toLatin1().constData())
<< dualAddress << true << a << true;
}
@@ -1523,15 +1496,16 @@ void tst_QUdpSocket::multicast()
if (!joinResult)
return;
- QList<QByteArray> datagrams = QList<QByteArray>()
- << QByteArray("0123")
- << QByteArray("4567")
- << QByteArray("89ab")
- << QByteArray("cdef");
+ const QByteArray datagrams[] = {
+ "0123"_ba,
+ "4567"_ba,
+ "89ab"_ba,
+ "cdef"_ba,
+ };
QUdpSocket sender;
sender.bind();
- foreach (const QByteArray &datagram, datagrams) {
+ for (const QByteArray &datagram : datagrams) {
QNetworkDatagram dgram(datagram, groupAddress, receiver.localPort());
dgram.setInterfaceIndex(interfaceForGroup(groupAddress).index());
QCOMPARE(int(sender.writeDatagram(dgram)),
@@ -1574,7 +1548,7 @@ void tst_QUdpSocket::echo()
{
QFETCH(bool, connect);
QHostInfo info = QHostInfo::fromName(QtNetworkSettings::echoServerName());
- QVERIFY(info.addresses().count());
+ QVERIFY(info.addresses().size());
QHostAddress remote = info.addresses().first();
QUdpSocket sock;
@@ -1601,7 +1575,7 @@ void tst_QUdpSocket::echo()
in = sock.read(sock.pendingDatagramSize());
} else {
in.resize(sock.pendingDatagramSize());
- sock.readDatagram(in.data(), in.length(), &from, &port);
+ sock.readDatagram(in.data(), in.size(), &from, &port);
}
if (in==out)
successes++;
@@ -1624,7 +1598,8 @@ void tst_QUdpSocket::linkLocalIPv6()
QList <QHostAddress> addresses;
QSet <QString> scopes;
QHostAddress localMask("fe80::");
- foreach (const QNetworkInterface& iface, QNetworkInterface::allInterfaces()) {
+ const auto ifaces = QNetworkInterface::allInterfaces();
+ for (const QNetworkInterface &iface : ifaces) {
//Windows preallocates link local addresses to interfaces that are down.
//These may or may not work depending on network driver
if (iface.flags() & QNetworkInterface::IsUp) {
@@ -1639,7 +1614,8 @@ void tst_QUdpSocket::linkLocalIPv6()
continue;
#endif
- foreach (QNetworkAddressEntry addressEntry, iface.addressEntries()) {
+ const auto entries = iface.addressEntries();
+ for (const QNetworkAddressEntry &addressEntry : entries) {
QHostAddress addr(addressEntry.ip());
if (!addr.scopeId().isEmpty() && addr.isInSubnet(localMask, 64)) {
scopes << addr.scopeId();
@@ -1654,7 +1630,7 @@ void tst_QUdpSocket::linkLocalIPv6()
QList <QUdpSocket*> sockets;
quint16 port = 0;
- foreach (const QHostAddress& addr, addresses) {
+ for (const QHostAddress &addr : std::as_const(addresses)) {
QUdpSocket *s = new QUdpSocket;
QVERIFY2(s->bind(addr, port), addr.toString().toLatin1()
+ '/' + QByteArray::number(port) + ": " + qPrintable(s->errorString()));
@@ -1663,7 +1639,7 @@ void tst_QUdpSocket::linkLocalIPv6()
}
QByteArray testData("hello");
- foreach (QUdpSocket *s, sockets) {
+ for (QUdpSocket *s : std::as_const(sockets)) {
QUdpSocket neutral;
QVERIFY(neutral.bind(QHostAddress(QHostAddress::AnyIPv6)));
QSignalSpy neutralReadSpy(&neutral, SIGNAL(readyRead()));
@@ -1671,27 +1647,26 @@ void tst_QUdpSocket::linkLocalIPv6()
QSignalSpy spy(s, SIGNAL(readyRead()));
QVERIFY(s->writeDatagram(testData, s->localAddress(), neutral.localPort()));
- QTRY_VERIFY(neutralReadSpy.count() > 0); //note may need to accept a firewall prompt
+ QTRY_VERIFY(neutralReadSpy.size() > 0); //note may need to accept a firewall prompt
- QNetworkDatagram dgram = neutral.receiveDatagram(testData.length() * 2);
+ QNetworkDatagram dgram = neutral.receiveDatagram(testData.size() * 2);
QVERIFY(dgram.isValid());
QCOMPARE(dgram.senderAddress(), s->localAddress());
QCOMPARE(dgram.senderPort(), int(s->localPort()));
QCOMPARE(dgram.destinationAddress(), s->localAddress());
QCOMPARE(dgram.destinationPort(), int(neutral.localPort()));
- QCOMPARE(dgram.data().length(), testData.length());
+ QCOMPARE(dgram.data().size(), testData.size());
QCOMPARE(dgram.data(), testData);
QVERIFY(neutral.writeDatagram(dgram.makeReply(testData)));
- QTRY_VERIFY(spy.count() > 0); //note may need to accept a firewall prompt
+ QTRY_VERIFY(spy.size() > 0); //note may need to accept a firewall prompt
- dgram = s->receiveDatagram(testData.length() * 2);
+ dgram = s->receiveDatagram(testData.size() * 2);
QCOMPARE(dgram.data(), testData);
//sockets bound to other interfaces shouldn't have received anything
- foreach (QUdpSocket *s2, sockets) {
+ for (QUdpSocket *s2 : std::as_const(sockets))
QCOMPARE((int)s2->bytesAvailable(), 0);
- }
//Sending to the same address with different scope should normally fail
//However it will pass if there is a route between two interfaces,
@@ -1710,7 +1685,8 @@ void tst_QUdpSocket::linkLocalIPv4()
QList <QHostAddress> addresses;
QHostAddress localMask("169.254.0.0");
- foreach (const QNetworkInterface& iface, QNetworkInterface::allInterfaces()) {
+ const auto ifaces = QNetworkInterface::allInterfaces();
+ for (const QNetworkInterface &iface : ifaces) {
//Windows preallocates link local addresses to interfaces that are down.
//These may or may not work depending on network driver (they do not work for the Bluetooth PAN driver)
if (iface.flags() & QNetworkInterface::IsUp) {
@@ -1724,7 +1700,8 @@ void tst_QUdpSocket::linkLocalIPv4()
if (iface.name().startsWith("utun"))
continue;
#endif
- foreach (QNetworkAddressEntry addr, iface.addressEntries()) {
+ const auto entries = iface.addressEntries();
+ for (const QNetworkAddressEntry &addr : entries) {
if (addr.ip().isInSubnet(localMask, 16)) {
addresses << addr.ip();
qDebug() << "Found IPv4 link local address" << addr.ip();
@@ -1737,7 +1714,7 @@ void tst_QUdpSocket::linkLocalIPv4()
QList <QUdpSocket*> sockets;
quint16 port = 0;
- foreach (const QHostAddress& addr, addresses) {
+ for (const QHostAddress &addr : std::as_const(addresses)) {
QUdpSocket *s = new QUdpSocket;
QVERIFY2(s->bind(addr, port), qPrintable(s->errorString()));
port = s->localPort(); //bind same port, different networks
@@ -1748,15 +1725,15 @@ void tst_QUdpSocket::linkLocalIPv4()
QVERIFY(neutral.bind(QHostAddress(QHostAddress::AnyIPv4)));
QByteArray testData("hello");
- foreach (QUdpSocket *s, sockets) {
+ for (QUdpSocket *s : std::as_const(sockets)) {
QVERIFY(s->writeDatagram(testData, s->localAddress(), neutral.localPort()));
QVERIFY2(neutral.waitForReadyRead(10000), QtNetworkSettings::msgSocketError(neutral).constData());
- QNetworkDatagram dgram = neutral.receiveDatagram(testData.length() * 2);
+ QNetworkDatagram dgram = neutral.receiveDatagram(testData.size() * 2);
QVERIFY(dgram.isValid());
QCOMPARE(dgram.senderAddress(), s->localAddress());
QCOMPARE(dgram.senderPort(), int(s->localPort()));
- QCOMPARE(dgram.data().length(), testData.length());
+ QCOMPARE(dgram.data().size(), testData.size());
QCOMPARE(dgram.data(), testData);
// Unlike for IPv6 with IPV6_PKTINFO, IPv4 has no standardized way of
@@ -1775,14 +1752,13 @@ void tst_QUdpSocket::linkLocalIPv4()
QVERIFY(neutral.writeDatagram(dgram.makeReply(testData)));
QVERIFY2(s->waitForReadyRead(10000), QtNetworkSettings::msgSocketError(*s).constData());
- dgram = s->receiveDatagram(testData.length() * 2);
+ dgram = s->receiveDatagram(testData.size() * 2);
QVERIFY(dgram.isValid());
QCOMPARE(dgram.data(), testData);
//sockets bound to other interfaces shouldn't have received anything
- foreach (QUdpSocket *s2, sockets) {
+ for (QUdpSocket *s2 : std::as_const(sockets))
QCOMPARE((int)s2->bytesAvailable(), 0);
- }
}
qDeleteAll(sockets);
}
@@ -1810,7 +1786,7 @@ void tst_QUdpSocket::readyRead()
QTest::qWait(100);
// make sure only one signal was emitted
- QCOMPARE(spy.count(), 1);
+ QCOMPARE(spy.size(), 1);
QVERIFY(receiver.hasPendingDatagrams());
#ifdef RELIABLE_BYTES_AVAILABLE
QCOMPARE(receiver.bytesAvailable(), qint64(2));
@@ -1822,7 +1798,7 @@ void tst_QUdpSocket::readyRead()
// no new signal should be emitted because we haven't read the first datagram yet
QTest::qWait(100);
- QCOMPARE(spy.count(), 1);
+ QCOMPARE(spy.size(), 1);
QVERIFY(receiver.hasPendingDatagrams());
QVERIFY(receiver.bytesAvailable() >= 1); // most likely is 1, but it could be 1 + 2 in the future
QCOMPARE(receiver.pendingDatagramSize(), qint64(2));
@@ -1834,7 +1810,7 @@ void tst_QUdpSocket::readyRead()
// write a new datagram and ensure the signal is emitted now
sender.writeDatagram("abc", makeNonAny(receiver.localAddress()), port);
QTest::qWait(100);
- QCOMPARE(spy.count(), 2);
+ QCOMPARE(spy.size(), 2);
QVERIFY(receiver.hasPendingDatagrams());
#ifdef RELIABLE_BYTES_AVAILABLE
QCOMPARE(receiver.bytesAvailable(), qint64(3));
@@ -1914,7 +1890,7 @@ void tst_QUdpSocket::asyncReadDatagram()
QTestEventLoop::instance().enterLoop(1);
QVERIFY(!QTestEventLoop::instance().timeout());
- QCOMPARE(spy.count(), 2);
+ QCOMPARE(spy.size(), 2);
delete m_asyncSender;
delete m_asyncReceiver;
@@ -1932,5 +1908,78 @@ void tst_QUdpSocket::writeInHostLookupState()
QVERIFY(!socket.putChar('0'));
}
+void tst_QUdpSocket::readyReadConnectionThrottling()
+{
+ QFETCH_GLOBAL(bool, setProxy);
+ if (setProxy)
+ return;
+ using namespace std::chrono_literals;
+
+ // QTBUG-105871:
+ // We have some signal/slot connection throttling in QAbstractSocket, but it
+ // was caring about the bytes, not about the datagrams.
+ // Test that we don't disable read notifications until we have at least one
+ // datagram available. Otherwise our good users who use the datagram APIs
+ // can get into scenarios where they no longer get the readyRead signal
+ // unless they call a read function once in a while.
+
+ QUdpSocket receiver;
+ QVERIFY(receiver.bind(QHostAddress(QHostAddress::LocalHost), 0));
+
+ QSemaphore semaphore;
+
+ // Repro-ing deterministically eludes me, so we are bruteforcing it:
+ // The thread acts as a remote sender, flooding the receiver with datagrams,
+ // and at some point the receiver would get into the broken state mentioned
+ // earlier.
+ std::unique_ptr<QThread> thread(QThread::create([&semaphore, port = receiver.localPort()]() {
+ QUdpSocket sender;
+ sender.connectToHost(QHostAddress(QHostAddress::LocalHost), port);
+ QCOMPARE(sender.state(), QUdpSocket::ConnectedState);
+
+ constexpr qsizetype PayloadSize = 242;
+ const QByteArray payload(PayloadSize, 'a');
+
+ semaphore.acquire(); // Wait for main thread to be ready
+ while (true) {
+ // We send 100 datagrams at a time, then sleep.
+ // This is mostly to let the main thread catch up between bursts so
+ // it doesn't get stuck in the loop.
+ for (int i = 0; i < 100; ++i) {
+ [[maybe_unused]]
+ qsizetype sent = sender.write(payload);
+ Q_ASSERT(sent > 0);
+ }
+ if (QThread::currentThread()->isInterruptionRequested())
+ break;
+ QThread::sleep(20ms);
+ }
+ }));
+ thread->start();
+ auto threadStopAndWaitGuard = qScopeGuard([&thread] {
+ thread->requestInterruption();
+ thread->quit();
+ thread->wait();
+ });
+
+ qsizetype count = 0;
+ QObject::connect(&receiver, &QUdpSocket::readyRead, &receiver,
+ [&] {
+ while (receiver.hasPendingDatagrams()) {
+ receiver.readDatagram(nullptr, 0);
+ ++count;
+ }
+ // If this prints `false, xxxx` we were pretty much guaranteed
+ // that we would not get called again:
+ // qDebug() << receiver.hasPendingDatagrams() << receiver.bytesAvailable();
+ },
+ Qt::QueuedConnection);
+
+ semaphore.release();
+ constexpr qsizetype MaxCount = 500;
+ QVERIFY2(QTest::qWaitFor([&] { return count >= MaxCount; }, 10s),
+ QByteArray::number(count).constData());
+}
+
QTEST_MAIN(tst_QUdpSocket)
#include "tst_qudpsocket.moc"
diff --git a/tests/auto/network/socket/qudpsocket/udpServer/CMakeLists.txt b/tests/auto/network/socket/qudpsocket/udpServer/CMakeLists.txt
index 4afeb529a7..7dd7f2ba5d 100644
--- a/tests/auto/network/socket/qudpsocket/udpServer/CMakeLists.txt
+++ b/tests/auto/network/socket/qudpsocket/udpServer/CMakeLists.txt
@@ -1,13 +1,14 @@
-# Generated from udpServer.pro.
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
#####################################################################
## udpServer Binary:
#####################################################################
qt_internal_add_executable(udpServer
- OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/./" # special case
+ OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/./"
SOURCES
main.cpp
- PUBLIC_LIBRARIES
+ LIBRARIES
Qt::Network
)
diff --git a/tests/auto/network/socket/qudpsocket/udpServer/main.cpp b/tests/auto/network/socket/qudpsocket/udpServer/main.cpp
index a5986c29c7..ba5bb3c0d0 100644
--- a/tests/auto/network/socket/qudpsocket/udpServer/main.cpp
+++ b/tests/auto/network/socket/qudpsocket/udpServer/main.cpp
@@ -1,30 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
#include <QtNetwork>
class Server : public QObject
diff --git a/tests/auto/network/ssl/CMakeLists.txt b/tests/auto/network/ssl/CMakeLists.txt
index 9c44e5c375..b11b15b6ba 100644
--- a/tests/auto/network/ssl/CMakeLists.txt
+++ b/tests/auto/network/ssl/CMakeLists.txt
@@ -1,10 +1,11 @@
-# Generated from ssl.pro.
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
add_subdirectory(qpassworddigestor)
-add_subdirectory(qsslcertificate)
-add_subdirectory(qsslcipher)
-add_subdirectory(qsslellipticcurve)
if(QT_FEATURE_ssl)
+ add_subdirectory(qsslcertificate)
+ add_subdirectory(qsslcipher)
+ add_subdirectory(qsslellipticcurve)
add_subdirectory(qsslkey)
add_subdirectory(qsslerror)
endif()
@@ -12,8 +13,9 @@ if(QT_FEATURE_private_tests AND QT_FEATURE_ssl)
add_subdirectory(qsslsocket)
add_subdirectory(qsslsocket_onDemandCertificates_member)
add_subdirectory(qsslsocket_onDemandCertificates_static)
-# add_subdirectory(qasn1element)
+ add_subdirectory(qasn1element)
add_subdirectory(qssldiffiehellmanparameters)
+ add_subdirectory(qsslserver)
endif()
if(QT_FEATURE_dtls AND QT_FEATURE_private_tests AND QT_FEATURE_ssl)
add_subdirectory(qdtlscookie)
diff --git a/tests/auto/network/ssl/qasn1element/CMakeLists.txt b/tests/auto/network/ssl/qasn1element/CMakeLists.txt
index 4fab2f3e3e..7b01a0b22d 100644
--- a/tests/auto/network/ssl/qasn1element/CMakeLists.txt
+++ b/tests/auto/network/ssl/qasn1element/CMakeLists.txt
@@ -1,13 +1,26 @@
-# Generated from qasn1element.pro.
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
#####################################################################
## tst_qasn1element Test:
#####################################################################
+if(NOT QT_BUILD_STANDALONE_TESTS AND NOT QT_BUILDING_QT)
+ cmake_minimum_required(VERSION 3.16)
+ project(tst_qasn1element LANGUAGES CXX)
+ find_package(Qt6BuildInternals REQUIRED COMPONENTS STANDALONE_TEST)
+endif()
+
qt_internal_add_test(tst_qasn1element
SOURCES
tst_qasn1element.cpp
- PUBLIC_LIBRARIES
+ ../../../../../src/plugins/tls/shared/qasn1element_p.h
+ ../../../../../src/plugins/tls/shared/qasn1element.cpp
+ INCLUDE_DIRECTORIES
+ ../../../../../src/plugins/tls/shared
+ LIBRARIES
+ Qt::Core
Qt::Network
Qt::NetworkPrivate
+ BUNDLE_ANDROID_OPENSSL_LIBS
)
diff --git a/tests/auto/network/ssl/qasn1element/tst_qasn1element.cpp b/tests/auto/network/ssl/qasn1element/tst_qasn1element.cpp
index 9a4d23f650..a54f0bd9d8 100644
--- a/tests/auto/network/ssl/qasn1element/tst_qasn1element.cpp
+++ b/tests/auto/network/ssl/qasn1element/tst_qasn1element.cpp
@@ -1,34 +1,12 @@
-/****************************************************************************
-**
-** Copyright (C) 2014 Jeremy Lainé <jeremy.laine@m4x.org>
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2014 Jeremy Lainé <jeremy.laine@m4x.org>
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
+#include "qasn1element_p.h"
#include <QTest>
-#include "private/qasn1element_p.h"
+
+#include <QtCore/QDateTime>
+#include <QtCore/QTimeZone>
class tst_QAsn1Element : public QObject
{
@@ -127,7 +105,7 @@ void tst_QAsn1Element::dateTime_data()
<< QDateTime();
QTest::newRow("UTCTime - 070417074026Z")
<< QByteArray::fromHex("170d3037303431373037343032365a")
- << QDateTime(QDate(2007, 4, 17), QTime(7, 40, 26), Qt::UTC);
+ << QDateTime(QDate(2007, 4, 17), QTime(7, 40, 26), QTimeZone::UTC);
QTest::newRow("UTCTime - bad length")
<< QByteArray::fromHex("170c30373034313730373430325a")
<< QDateTime();
@@ -136,16 +114,19 @@ void tst_QAsn1Element::dateTime_data()
<< QDateTime();
QTest::newRow("UTCTime - year 1950")
<< QByteArray::fromHex("170d3530313232343035353530305a")
- << QDateTime(QDate(1950, 12, 24), QTime(5, 55), Qt::UTC);
+ << QDateTime(QDate(1950, 12, 24), QTime(5, 55), QTimeZone::UTC);
QTest::newRow("UTCTime - year 1999")
<< QByteArray::fromHex("170d3939313232343035353530305a")
- << QDateTime(QDate(1999, 12, 24), QTime(5, 55), Qt::UTC);
+ << QDateTime(QDate(1999, 12, 24), QTime(5, 55), QTimeZone::UTC);
QTest::newRow("UTCTime - year 2000")
<< QByteArray::fromHex("170d3030313232343035353530305a")
- << QDateTime(QDate(2000, 12, 24), QTime(5, 55), Qt::UTC);
+ << QDateTime(QDate(2000, 12, 24), QTime(5, 55), QTimeZone::UTC);
+ QTest::newRow("UTCTime - leap day year 2000")
+ << QByteArray::fromHex("170d3030303232393035353530305a")
+ << QDateTime(QDate(2000, 2, 29), QTime(5, 55), QTimeZone::UTC);
QTest::newRow("UTCTime - year 2049")
<< QByteArray::fromHex("170d3439313232343035353530305a")
- << QDateTime(QDate(2049, 12, 24), QTime(5, 55), Qt::UTC);
+ << QDateTime(QDate(2049, 12, 24), QTime(5, 55), QTimeZone::UTC);
QTest::newRow("UTCTime - invalid year ('-9')")
<< QByteArray::fromHex("170d2d39313232343035353530305a")
<< QDateTime();
@@ -163,7 +144,7 @@ void tst_QAsn1Element::dateTime_data()
<< QDateTime();
QTest::newRow("GeneralizedTime - 20510829095341Z")
<< QByteArray::fromHex("180f32303531303832393039353334315a")
- << QDateTime(QDate(2051, 8, 29), QTime(9, 53, 41), Qt::UTC);
+ << QDateTime(QDate(2051, 8, 29), QTime(9, 53, 41), QTimeZone::UTC);
QTest::newRow("GeneralizedTime - bad length")
<< QByteArray::fromHex("180e323035313038323930393533345a")
<< QDateTime();
diff --git a/tests/auto/network/ssl/qdtls/CMakeLists.txt b/tests/auto/network/ssl/qdtls/CMakeLists.txt
index 310629370c..1d5eef094c 100644
--- a/tests/auto/network/ssl/qdtls/CMakeLists.txt
+++ b/tests/auto/network/ssl/qdtls/CMakeLists.txt
@@ -1,25 +1,24 @@
-# Generated from qdtls.pro.
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
#####################################################################
## tst_qdtls Test:
#####################################################################
+if(NOT QT_BUILD_STANDALONE_TESTS AND NOT QT_BUILDING_QT)
+ cmake_minimum_required(VERSION 3.16)
+ project(tst_qdtls LANGUAGES CXX)
+ find_package(Qt6BuildInternals REQUIRED COMPONENTS STANDALONE_TEST)
+endif()
+
# Collect test data
list(APPEND test_data "certs")
qt_internal_add_test(tst_qdtls
SOURCES
tst_qdtls.cpp
- PUBLIC_LIBRARIES
+ LIBRARIES
Qt::NetworkPrivate
TESTDATA ${test_data}
+ BUNDLE_ANDROID_OPENSSL_LIBS
)
-
-## Scopes:
-#####################################################################
-
-#### Keys ignored in scope 3:.:.:qdtls.pro:(CMAKE_BUILD_TYPE STREQUAL Debug):
-# DESTDIR = "debug"
-
-#### Keys ignored in scope 4:.:.:qdtls.pro:else:
-# DESTDIR = "release"
diff --git a/tests/auto/network/ssl/qdtls/certs/fluke.cert b/tests/auto/network/ssl/qdtls/certs/fluke.cert
index ace4e4f0eb..4cc4d9a5ea 100644
--- a/tests/auto/network/ssl/qdtls/certs/fluke.cert
+++ b/tests/auto/network/ssl/qdtls/certs/fluke.cert
@@ -1,75 +1,34 @@
-Certificate:
- Data:
- Version: 3 (0x2)
- Serial Number: 0 (0x0)
- Signature Algorithm: sha1WithRSAEncryption
- Issuer: C=NO, ST=Oslo, L=Nydalen, O=Nokia Corporation and/or its subsidiary(-ies), OU=Development, CN=fluke.troll.no/emailAddress=ahanssen@trolltech.com
- Validity
- Not Before: Dec 4 01:10:32 2007 GMT
- Not After : Apr 21 01:10:32 2035 GMT
- Subject: C=NO, ST=Oslo, O=Nokia Corporation and/or its subsidiary(-ies), OU=Development, CN=fluke.troll.no
- Subject Public Key Info:
- Public Key Algorithm: rsaEncryption
- RSA Public Key: (1024 bit)
- Modulus (1024 bit):
- 00:a7:c8:a0:4a:c4:19:05:1b:66:ba:32:e2:d2:f1:
- 1c:6f:17:82:e4:39:2e:01:51:90:db:04:34:32:11:
- 21:c2:0d:6f:59:d8:53:90:54:3f:83:8f:a9:d3:b3:
- d5:ee:1a:9b:80:ae:c3:25:c9:5e:a5:af:4b:60:05:
- aa:a0:d1:91:01:1f:ca:04:83:e3:58:1c:99:32:45:
- 84:70:72:58:03:98:4a:63:8b:41:f5:08:49:d2:91:
- 02:60:6b:e4:64:fe:dd:a0:aa:74:08:e9:34:4c:91:
- 5f:12:3d:37:4d:54:2c:ad:7f:5b:98:60:36:02:8c:
- 3b:f6:45:f3:27:6a:9b:94:9d
- Exponent: 65537 (0x10001)
- X509v3 extensions:
- X509v3 Basic Constraints:
- CA:FALSE
- Netscape Comment:
- OpenSSL Generated Certificate
- X509v3 Subject Key Identifier:
- 21:85:04:3D:23:01:66:E5:F7:9F:1A:84:24:8A:AF:0A:79:F4:E5:AC
- X509v3 Authority Key Identifier:
- DirName:/C=NO/ST=Oslo/L=Nydalen/O=Nokia Corporation and/or its subsidiary(-ies)/OU=Development/CN=fluke.troll.no/emailAddress=ahanssen@trolltech.com
- serial:8E:A8:B4:E8:91:B7:54:2E
-
- Signature Algorithm: sha1WithRSAEncryption
- 6d:57:5f:d1:05:43:f0:62:05:ec:2a:71:a5:dc:19:08:f2:c4:
- a6:bd:bb:25:d9:ca:89:01:0e:e4:cf:1f:c1:8c:c8:24:18:35:
- 53:59:7b:c0:43:b4:32:e6:98:b2:a6:ef:15:05:0b:48:5f:e1:
- a0:0c:97:a9:a1:77:d8:35:18:30:bc:a9:8f:d3:b7:54:c7:f1:
- a9:9e:5d:e6:19:bf:f6:3c:5b:2b:d8:e4:3e:62:18:88:8b:d3:
- 24:e1:40:9b:0c:e6:29:16:62:ab:ea:05:24:70:36:aa:55:93:
- ef:02:81:1b:23:10:a2:04:eb:56:95:75:fc:f8:94:b1:5d:42:
- c5:3f:36:44:85:5d:3a:2e:90:46:8a:a2:b9:6f:87:ae:0c:15:
- 40:19:31:90:fc:3b:25:bb:ae:f1:66:13:0d:85:90:d9:49:34:
- 8f:f2:5d:f9:7a:db:4d:5d:27:f6:76:9d:35:8c:06:a6:4c:a3:
- b1:b2:b6:6f:1d:d7:a3:00:fd:72:eb:9e:ea:44:a1:af:21:34:
- 7d:c7:42:e2:49:91:19:8b:c0:ad:ba:82:80:a8:71:70:f4:35:
- 31:91:63:84:20:95:e9:60:af:64:8b:cc:ff:3d:8a:76:74:3d:
- c8:55:6d:e4:8e:c3:2b:1c:e8:42:18:ae:9f:e6:6b:9c:34:06:
- ec:6a:f2:c3
-----BEGIN CERTIFICATE-----
-MIIEEzCCAvugAwIBAgIBADANBgkqhkiG9w0BAQUFADCBnDELMAkGA1UEBhMCTk8x
-DTALBgNVBAgTBE9zbG8xEDAOBgNVBAcTB055ZGFsZW4xFjAUBgNVBAoTDVRyb2xs
-dGVjaCBBU0ExFDASBgNVBAsTC0RldmVsb3BtZW50MRcwFQYDVQQDEw5mbHVrZS50
-cm9sbC5ubzElMCMGCSqGSIb3DQEJARYWYWhhbnNzZW5AdHJvbGx0ZWNoLmNvbTAe
-Fw0wNzEyMDQwMTEwMzJaFw0zNTA0MjEwMTEwMzJaMGMxCzAJBgNVBAYTAk5PMQ0w
-CwYDVQQIEwRPc2xvMRYwFAYDVQQKEw1Ucm9sbHRlY2ggQVNBMRQwEgYDVQQLEwtE
-ZXZlbG9wbWVudDEXMBUGA1UEAxMOZmx1a2UudHJvbGwubm8wgZ8wDQYJKoZIhvcN
-AQEBBQADgY0AMIGJAoGBAKfIoErEGQUbZroy4tLxHG8XguQ5LgFRkNsENDIRIcIN
-b1nYU5BUP4OPqdOz1e4am4CuwyXJXqWvS2AFqqDRkQEfygSD41gcmTJFhHByWAOY
-SmOLQfUISdKRAmBr5GT+3aCqdAjpNEyRXxI9N01ULK1/W5hgNgKMO/ZF8ydqm5Sd
-AgMBAAGjggEaMIIBFjAJBgNVHRMEAjAAMCwGCWCGSAGG+EIBDQQfFh1PcGVuU1NM
-IEdlbmVyYXRlZCBDZXJ0aWZpY2F0ZTAdBgNVHQ4EFgQUIYUEPSMBZuX3nxqEJIqv
-Cnn05awwgbsGA1UdIwSBszCBsKGBoqSBnzCBnDELMAkGA1UEBhMCTk8xDTALBgNV
-BAgTBE9zbG8xEDAOBgNVBAcTB055ZGFsZW4xFjAUBgNVBAoTDVRyb2xsdGVjaCBB
-U0ExFDASBgNVBAsTC0RldmVsb3BtZW50MRcwFQYDVQQDEw5mbHVrZS50cm9sbC5u
-bzElMCMGCSqGSIb3DQEJARYWYWhhbnNzZW5AdHJvbGx0ZWNoLmNvbYIJAI6otOiR
-t1QuMA0GCSqGSIb3DQEBBQUAA4IBAQBtV1/RBUPwYgXsKnGl3BkI8sSmvbsl2cqJ
-AQ7kzx/BjMgkGDVTWXvAQ7Qy5piypu8VBQtIX+GgDJepoXfYNRgwvKmP07dUx/Gp
-nl3mGb/2PFsr2OQ+YhiIi9Mk4UCbDOYpFmKr6gUkcDaqVZPvAoEbIxCiBOtWlXX8
-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
+MIIF6zCCA9OgAwIBAgIUfo9amJtJGWqWE6f+SkAO85zkGr4wDQYJKoZIhvcNAQEL
+BQAwgYMxCzAJBgNVBAYTAk5PMQ0wCwYDVQQIDARPc2xvMQ0wCwYDVQQHDARPc2xv
+MRcwFQYDVQQKDA5UaGUgUXQgQ29tcGFueTEMMAoGA1UECwwDUiZEMRIwEAYDVQQD
+DAlIMiBUZXN0ZXIxGzAZBgkqhkiG9w0BCQEWDG1pbmltaUBxdC5pbzAgFw0yMDEw
+MjYxMjAxMzFaGA8yMTIwMTAwMjEyMDEzMVowgYMxCzAJBgNVBAYTAk5PMQ0wCwYD
+VQQIDARPc2xvMQ0wCwYDVQQHDARPc2xvMRcwFQYDVQQKDA5UaGUgUXQgQ29tcGFu
+eTEMMAoGA1UECwwDUiZEMRIwEAYDVQQDDAlIMiBUZXN0ZXIxGzAZBgkqhkiG9w0B
+CQEWDG1pbmltaUBxdC5pbzCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIB
+AOiUp5+E4blouKH7q+rVNR8NoYX2XkBW+q+rpy1zu5ssRSzbqxAjDx9dkht7Qlnf
+VlDT00JvpOWdeuPon5915edQRsY4Unl6mKH29ra3OtUa1/yCJXsGVJTKCj7k4Bxb
+5mZzb/fTlZntMLdTIBMfUbw62FKir1WjKIcJ9fCoG8JaGeKVO4Rh5p0ezd4UUUId
+r1BXl5Nqdqy2vTMsEDnjOsD3egkv8I2SKN4O6n/C3wWYpMOWYZkGoZiKz7rJs/i/
+ez7bsV7JlwdzTlhpJzkcOSVFBP6JlEOxTNNxZ1wtKy7PtZGmsSSATq2e6+bw38Ae
+Op0XnzzqcGjtDDofBmT7OFzZWjS9VZS6+DOOe2QHWle1nCHcHyH4ku6IRlsr9xkR
+NAIlOfnvHHxqJUenoeaZ4oQDjCBKS1KXygJO/tL7BLTQVn/xK1EmPvKNnjzWk4tR
+PnibUhhs5635qpOU/YPqFBh1JjVruZbsWcDAhRcew0uxONXOa9E+4lttQ9ySYa1A
+LvWqJuAX7gu2BsBMLyqfm811YnA7CIFMyO+HlqmkLFfv5L/xIRAXR7l26YGO0VwX
+CGjMfz4NVPMMke4nB7qa9NkpXQBQKMms3Qzd5JW0Hy9Ruj5O8GPcFZmV0twjd1uJ
+PD/cAjkWLaXjdNsJ16QWc2nghQRS6HYqKRX6j+CXOxupAgMBAAGjUzBRMB0GA1Ud
+DgQWBBRSCOU58j9NJZkMamt623qyCrhN3TAfBgNVHSMEGDAWgBRSCOU58j9NJZkM
+amt623qyCrhN3TAPBgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3DQEBCwUAA4ICAQCq
+q4jxsWeNDv5Nq14hJtF9HB+ZL64zcZtRjJP1YgNs0QppKICmjPOL2nIMGmI/jKrs
+0eGAL/9XXNVHPxm1OPOncvimMMmU6emZfpMdEtTfKP43+Pg9HgKRjLoQp406vGeQ
+8ki/mbBhrItVPgEm3tu2AFA02XTYi+YxCI9kRZLGkM3FbgtOuTLPl0Z9y+kiPc9F
+uCSC03anBEqv+vDSI8+wODymQ/IJ3Jyz1lxIRDfp4qAekmy0jU2c91VOHHEmOmqq
+kqygGFRdwbe99m9yP63r6q0b5K3X2UnJ6bns0hmTwThYwpVPXLU8jdaTddbMukN2
+/Ef96Tsw8nWOEOPMySHOTIPgwyZRp26b0kA9EmhLwOP401SxXVQCmSRmtwNagmtg
+jJKmZoYBN+//D45ibK8z6Q0oOm9P+Whf/uUXehcRxBxyV3xz7k0wKGQbHj/ddwcy
+IUoIN4lrAlib+lK170kTKN352PDmrpo2gmIzPEsfurKAIMSelDl6H+kih16BtZ8y
+Nz6fh9Soqrg3OSAware8pxV7k51crBMoPLN78KoRV8MFCK4K7Fddq4rRISq6hiXq
+r1nsjoEPuKM9huprmZVZe9t5YcDa2I+wb3IiE3uwpZbAdaLDyQ5n6F/qpsiIkZXn
+gtcF7oqpG5oYrwCcZ53y/ezUgUg7PlSz2XwAGvQtgg==
-----END CERTIFICATE-----
diff --git a/tests/auto/network/ssl/qdtls/certs/fluke.key b/tests/auto/network/ssl/qdtls/certs/fluke.key
index 9d1664d609..337ce541a6 100644
--- a/tests/auto/network/ssl/qdtls/certs/fluke.key
+++ b/tests/auto/network/ssl/qdtls/certs/fluke.key
@@ -1,15 +1,52 @@
------BEGIN RSA PRIVATE KEY-----
-MIICXAIBAAKBgQCnyKBKxBkFG2a6MuLS8RxvF4LkOS4BUZDbBDQyESHCDW9Z2FOQ
-VD+Dj6nTs9XuGpuArsMlyV6lr0tgBaqg0ZEBH8oEg+NYHJkyRYRwclgDmEpji0H1
-CEnSkQJga+Rk/t2gqnQI6TRMkV8SPTdNVCytf1uYYDYCjDv2RfMnapuUnQIDAQAB
-AoGANFzLkanTeSGNFM0uttBipFT9F4a00dqHz6JnO7zXAT26I5r8sU1pqQBb6uLz
-/+Qz5Zwk8RUAQcsMRgJetuPQUb0JZjF6Duv24hNazqXBCu7AZzUenjafwmKC/8ri
-KpX3fTwqzfzi//FKGgbXQ80yykSSliDL3kn/drATxsLCgQECQQDXhEFWLJ0vVZ1s
-1Ekf+3NITE+DR16X+LQ4W6vyEHAjTbaNWtcTKdAWLA2l6N4WAAPYSi6awm+zMxx4
-VomVTsjdAkEAx0z+e7natLeFcrrq8pbU+wa6SAP1VfhQWKitxL1e7u/QO90NCpxE
-oQYKzMkmmpOOFjQwEMAy1dvFMbm4LHlewQJAC/ksDBaUcQHHqjktCtrUb8rVjAyW
-A8lscckeB2fEYyG5J6dJVaY4ClNOOs5yMDS2Afk1F6H/xKvtQ/5CzInA/QJATDub
-K+BPU8jO9q+gpuIi3VIZdupssVGmCgObVCHLakG4uO04y9IyPhV9lA9tALtoIf4c
-VIvv5fWGXBrZ48kZAQJBAJmVCdzQxd9LZI5vxijUCj5EI4e+x5DRqVUvyP8KCZrC
-AiNyoDP85T+hBZaSXK3aYGpVwelyj3bvo1GrTNwNWLw=
------END RSA PRIVATE KEY-----
+-----BEGIN PRIVATE KEY-----
+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
+g0veFbyfzlJ0q8qzD/iffqqIa2ZSmQ==
+-----END PRIVATE KEY-----
diff --git a/tests/auto/network/ssl/qdtls/tst_qdtls.cpp b/tests/auto/network/ssl/qdtls/tst_qdtls.cpp
index 75d949d957..372ee3a181 100644
--- a/tests/auto/network/ssl/qdtls/tst_qdtls.cpp
+++ b/tests/auto/network/ssl/qdtls/tst_qdtls.cpp
@@ -1,30 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2021 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2021 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
#include <QTest>
#include <QTestEventLoop>
@@ -51,6 +26,8 @@
#include <algorithm>
+using namespace std::chrono_literals;
+
QT_BEGIN_NAMESPACE
namespace
@@ -152,8 +129,8 @@ private:
DtlsPtr clientCrypto;
QTestEventLoop testLoop;
- const int handshakeTimeoutMS = 5000;
- const int dataExchangeTimeoutMS = 1000;
+ static constexpr auto HandshakeTimeout = 5s;
+ static constexpr auto DataExchangeTimeout = 1s;
const QByteArray presharedKey = "DEADBEEFDEADBEEF";
QString certDirPath;
@@ -295,7 +272,7 @@ void tst_QDtls::configuration()
QFETCH(const QSslSocket::SslMode, mode);
QDtls dtls(mode);
QCOMPARE(dtls.dtlsConfiguration(), config);
- config.setProtocol(QSsl::DtlsV1_0OrLater);
+ config.setProtocol(QSsl::DtlsV1_2);
config.setDtlsCookieVerificationEnabled(false);
QCOMPARE(config.dtlsCookieVerificationEnabled(), false);
@@ -438,7 +415,7 @@ void tst_QDtls::handshake()
QDTLS_VERIFY_NO_ERROR(clientCrypto);
QCOMPARE(clientCrypto->handshakeState(), QDtls::HandshakeInProgress);
- testLoop.enterLoopMSecs(handshakeTimeoutMS);
+ testLoop.enterLoop(HandshakeTimeout);
QVERIFY(!testLoop.timeout());
@@ -498,7 +475,7 @@ void tst_QDtls::handshakeWithRetransmission()
// client will re-transmit in 1s., the first part of 'ServerHello' to be
// dropped, the client then will re-transmit after another 2 s. Thus it's ~3.
// We err on safe side and double our (already quite generous) 5s.
- testLoop.enterLoopMSecs(handshakeTimeoutMS * 2);
+ testLoop.enterLoop(HandshakeTimeout * 2);
QVERIFY(!testLoop.timeout());
QDTLS_VERIFY_HANDSHAKE_SUCCESS(serverCrypto);
@@ -521,7 +498,7 @@ void tst_QDtls::sessionCipher()
QVERIFY(clientCrypto->setPeer(serverAddress, serverPort, hostName));
QVERIFY(clientCrypto->doHandshake(&clientSocket));
- testLoop.enterLoopMSecs(handshakeTimeoutMS);
+ testLoop.enterLoop(HandshakeTimeout);
QVERIFY(!testLoop.timeout());
QDTLS_VERIFY_HANDSHAKE_SUCCESS(clientCrypto);
@@ -584,7 +561,7 @@ void tst_QDtls::cipherPreferences()
QVERIFY(clientCrypto->doHandshake(&clientSocket));
QDTLS_VERIFY_NO_ERROR(clientCrypto);
- testLoop.enterLoopMSecs(handshakeTimeoutMS);
+ testLoop.enterLoop(HandshakeTimeout);
QVERIFY(!testLoop.timeout());
QDTLS_VERIFY_HANDSHAKE_SUCCESS(clientCrypto);
QDTLS_VERIFY_HANDSHAKE_SUCCESS(serverCrypto);
@@ -604,20 +581,36 @@ void tst_QDtls::protocolVersionMatching_data()
QTest::addColumn<QSsl::SslProtocol>("clientProtocol");
QTest::addColumn<bool>("works");
- QTest::addRow("DtlsV1_0 <-> DtlsV1_0") << QSsl::DtlsV1_0 << QSsl::DtlsV1_0 << true;
- QTest::addRow("DtlsV1_0OrLater <-> DtlsV1_0") << QSsl::DtlsV1_0OrLater << QSsl::DtlsV1_0 << true;
- QTest::addRow("DtlsV1_0 <-> DtlsV1_0OrLater") << QSsl::DtlsV1_0 << QSsl::DtlsV1_0OrLater << true;
- QTest::addRow("DtlsV1_0OrLater <-> DtlsV1_0OrLater") << QSsl::DtlsV1_0OrLater << QSsl::DtlsV1_0OrLater << true;
+ //OPENSSL_VERSION_NUMBER :
+ //(OPENSSL_VERSION_MAJOR<<28) | (OPENSSL_VERSION_MINOR<<20) | (OPENSSL_VERSION_PATCH<<4)
+ const long ossl311 = 0x30100010;
+
+ if (QSslSocket::sslLibraryVersionNumber() < ossl311) {
+#if QT_DEPRECATED_SINCE(6, 3)
+QT_WARNING_PUSH QT_WARNING_DISABLE_DEPRECATED
+ QTest::addRow("DtlsV1_0 <-> DtlsV1_0") << QSsl::DtlsV1_0 << QSsl::DtlsV1_0 << true;
+ QTest::addRow("DtlsV1_0OrLater <-> DtlsV1_0") << QSsl::DtlsV1_0OrLater << QSsl::DtlsV1_0 << true;
+ QTest::addRow("DtlsV1_0 <-> DtlsV1_0OrLater") << QSsl::DtlsV1_0 << QSsl::DtlsV1_0OrLater << true;
+ QTest::addRow("DtlsV1_0OrLater <-> DtlsV1_0OrLater") << QSsl::DtlsV1_0OrLater << QSsl::DtlsV1_0OrLater << true;
+QT_WARNING_POP
+#endif // QT_DEPRECATED_SINCE(6, 3)
+ }
QTest::addRow("DtlsV1_2 <-> DtlsV1_2") << QSsl::DtlsV1_2 << QSsl::DtlsV1_2 << true;
QTest::addRow("DtlsV1_2OrLater <-> DtlsV1_2") << QSsl::DtlsV1_2OrLater << QSsl::DtlsV1_2 << true;
QTest::addRow("DtlsV1_2 <-> DtlsV1_2OrLater") << QSsl::DtlsV1_2 << QSsl::DtlsV1_2OrLater << true;
QTest::addRow("DtlsV1_2OrLater <-> DtlsV1_2OrLater") << QSsl::DtlsV1_2OrLater << QSsl::DtlsV1_2OrLater << true;
- QTest::addRow("DtlsV1_0 <-> DtlsV1_2") << QSsl::DtlsV1_0 << QSsl::DtlsV1_2 << false;
- QTest::addRow("DtlsV1_0 <-> DtlsV1_2OrLater") << QSsl::DtlsV1_0 << QSsl::DtlsV1_2OrLater << false;
- QTest::addRow("DtlsV1_2 <-> DtlsV1_0") << QSsl::DtlsV1_2 << QSsl::DtlsV1_0 << false;
- QTest::addRow("DtlsV1_2OrLater <-> DtlsV1_0") << QSsl::DtlsV1_2OrLater << QSsl::DtlsV1_0 << false;
+ if (QSslSocket::sslLibraryVersionNumber() < ossl311) {
+#if QT_DEPRECATED_SINCE(6, 3)
+QT_WARNING_PUSH QT_WARNING_DISABLE_DEPRECATED
+ QTest::addRow("DtlsV1_0 <-> DtlsV1_2") << QSsl::DtlsV1_0 << QSsl::DtlsV1_2 << false;
+ QTest::addRow("DtlsV1_0 <-> DtlsV1_2OrLater") << QSsl::DtlsV1_0 << QSsl::DtlsV1_2OrLater << false;
+ QTest::addRow("DtlsV1_2 <-> DtlsV1_0") << QSsl::DtlsV1_2 << QSsl::DtlsV1_0 << false;
+ QTest::addRow("DtlsV1_2OrLater <-> DtlsV1_0") << QSsl::DtlsV1_2OrLater << QSsl::DtlsV1_0 << false;
+QT_WARNING_POP
+#endif // QT_DEPRECATED_SINCE(6, 3
+ }
}
void tst_QDtls::protocolVersionMatching()
@@ -643,7 +636,7 @@ void tst_QDtls::protocolVersionMatching()
QVERIFY(clientCrypto->setPeer(serverAddress, serverPort));
QVERIFY(clientCrypto->doHandshake(&clientSocket));
- testLoop.enterLoopMSecs(handshakeTimeoutMS);
+ testLoop.enterLoop(HandshakeTimeout);
if (works) {
QDTLS_VERIFY_HANDSHAKE_SUCCESS(serverCrypto);
@@ -678,7 +671,7 @@ void tst_QDtls::verificationErrors()
// Now we are ready for handshake:
QVERIFY(clientCrypto->doHandshake(&clientSocket));
- testLoop.enterLoopMSecs(handshakeTimeoutMS);
+ testLoop.enterLoop(HandshakeTimeout);
QVERIFY(!testLoop.timeout());
QDTLS_VERIFY_NO_ERROR(serverCrypto);
@@ -748,7 +741,7 @@ void tst_QDtls::presetExpectedErrors()
QVERIFY(clientCrypto->setPeer(serverAddress, serverPort));
QVERIFY(clientCrypto->doHandshake(&clientSocket));
- testLoop.enterLoopMSecs(handshakeTimeoutMS);
+ testLoop.enterLoop(HandshakeTimeout);
QVERIFY(!testLoop.timeout());
@@ -835,7 +828,7 @@ void tst_QDtls::verifyServerCertificate()
QVERIFY(clientCrypto->doHandshake(&clientSocket));
- testLoop.enterLoopMSecs(handshakeTimeoutMS);
+ testLoop.enterLoop(HandshakeTimeout);
QVERIFY(!testLoop.timeout());
if (serverKey.isNull() && !serverCerts.isEmpty()) {
@@ -965,7 +958,7 @@ void tst_QDtls::verifyClientCertificate()
QVERIFY(clientCrypto->doHandshake(&clientSocket));
QDTLS_VERIFY_NO_ERROR(clientCrypto);
- testLoop.enterLoopMSecs(handshakeTimeoutMS);
+ testLoop.enterLoop(HandshakeTimeout);
serverConfig = serverCrypto->dtlsConfiguration();
@@ -1012,7 +1005,7 @@ void tst_QDtls::blacklistedCerificate()
QVERIFY(clientCrypto->setPeer(serverAddress, serverPort, name));
QVERIFY(clientCrypto->doHandshake(&clientSocket));
- testLoop.enterLoopMSecs(handshakeTimeoutMS);
+ testLoop.enterLoop(HandshakeTimeout);
QVERIFY(!testLoop.timeout());
QCOMPARE(clientCrypto->handshakeState(), QDtls::PeerVerificationFailed);
QCOMPARE(clientCrypto->dtlsError(), QDtlsError::PeerVerificationError);
@@ -1064,7 +1057,7 @@ void tst_QDtls::readWriteEncrypted()
QCOMPARE(clientCrypto->dtlsError(), QDtlsError::InvalidOperation);
// 1.2 Finish the handshake:
- testLoop.enterLoopMSecs(handshakeTimeoutMS);
+ testLoop.enterLoop(HandshakeTimeout);
QVERIFY(!testLoop.timeout());
QDTLS_VERIFY_HANDSHAKE_SUCCESS(clientCrypto);
@@ -1082,7 +1075,7 @@ void tst_QDtls::readWriteEncrypted()
QVERIFY(clientBytesWritten > 0);
// 5. Exchange client/server messages:
- testLoop.enterLoopMSecs(dataExchangeTimeoutMS);
+ testLoop.enterLoop(DataExchangeTimeout);
QVERIFY(!testLoop.timeout());
QCOMPARE(serverExpectedPlainText, serverReceivedPlainText);
@@ -1100,7 +1093,7 @@ void tst_QDtls::readWriteEncrypted()
QCOMPARE(crypto->handshakeState(), QDtls::HandshakeNotStarted);
QVERIFY(!crypto->isConnectionEncrypted());
// 8. Receive this read notification and handle it:
- testLoop.enterLoopMSecs(dataExchangeTimeoutMS);
+ testLoop.enterLoop(DataExchangeTimeout);
QVERIFY(!testLoop.timeout());
DtlsPtr &peerCrypto = serverSideShutdown ? clientCrypto : serverCrypto;
@@ -1125,7 +1118,7 @@ void tst_QDtls::datagramFragmentation()
QVERIFY(clientCrypto->doHandshake(&clientSocket));
- testLoop.enterLoopMSecs(handshakeTimeoutMS);
+ testLoop.enterLoop(HandshakeTimeout);
QVERIFY(!testLoop.timeout());
QDTLS_VERIFY_HANDSHAKE_SUCCESS(clientCrypto);
diff --git a/tests/auto/network/ssl/qdtlscookie/CMakeLists.txt b/tests/auto/network/ssl/qdtlscookie/CMakeLists.txt
index 28b1418173..d965c7efb6 100644
--- a/tests/auto/network/ssl/qdtlscookie/CMakeLists.txt
+++ b/tests/auto/network/ssl/qdtlscookie/CMakeLists.txt
@@ -1,21 +1,20 @@
-# Generated from qdtlscookie.pro.
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
#####################################################################
## tst_qdtlscookie Test:
#####################################################################
+if(NOT QT_BUILD_STANDALONE_TESTS AND NOT QT_BUILDING_QT)
+ cmake_minimum_required(VERSION 3.16)
+ project(tst_qdtlscookie LANGUAGES CXX)
+ find_package(Qt6BuildInternals REQUIRED COMPONENTS STANDALONE_TEST)
+endif()
+
qt_internal_add_test(tst_qdtlscookie
SOURCES
tst_qdtlscookie.cpp
- PUBLIC_LIBRARIES
+ LIBRARIES
Qt::NetworkPrivate
+ BUNDLE_ANDROID_OPENSSL_LIBS
)
-
-## Scopes:
-#####################################################################
-
-#### Keys ignored in scope 3:.:.:qdtlscookie.pro:(CMAKE_BUILD_TYPE STREQUAL Debug):
-# DESTDIR = "debug"
-
-#### Keys ignored in scope 4:.:.:qdtlscookie.pro:else:
-# DESTDIR = "release"
diff --git a/tests/auto/network/ssl/qdtlscookie/tst_qdtlscookie.cpp b/tests/auto/network/ssl/qdtlscookie/tst_qdtlscookie.cpp
index 42b51ad413..167a196104 100644
--- a/tests/auto/network/ssl/qdtlscookie/tst_qdtlscookie.cpp
+++ b/tests/auto/network/ssl/qdtlscookie/tst_qdtlscookie.cpp
@@ -1,30 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2021 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2021 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
#include <QTest>
#include <QTestEventLoop>
@@ -47,6 +22,8 @@
#include <utility>
#include <vector>
+using namespace std::chrono_literals;
+
QT_BEGIN_NAMESPACE
#define STOP_ON_FAILURE \
@@ -101,7 +78,7 @@ private:
quint16 serverPort = 0;
QTestEventLoop testLoop;
- int handshakeTimeoutMS = 500;
+ static constexpr auto HandshakeTimeout = 500ms;
QDtlsClientVerifier listener;
using HandshakePtr = QSharedPointer<QDtls>;
@@ -352,7 +329,7 @@ void tst_QDtlsCookie::verifyMultipleClients()
clientsToAdd = clientsToWait = 100;
- testLoop.enterLoopMSecs(handshakeTimeoutMS * clientsToWait);
+ testLoop.enterLoop(HandshakeTimeout * clientsToWait);
QVERIFY(!testLoop.timeout());
QVERIFY(clientsToWait == 0);
}
@@ -376,7 +353,7 @@ void tst_QDtlsCookie::receiveMessage(QUdpSocket *socket, QByteArray *message,
Q_ASSERT(socket && message);
if (socket->pendingDatagramSize() <= 0)
- testLoop.enterLoopMSecs(handshakeTimeoutMS);
+ testLoop.enterLoop(HandshakeTimeout);
QVERIFY(!testLoop.timeout());
QVERIFY(socket->pendingDatagramSize());
diff --git a/tests/auto/network/ssl/qocsp/CMakeLists.txt b/tests/auto/network/ssl/qocsp/CMakeLists.txt
index 827c81e9d8..98d38ec1c0 100644
--- a/tests/auto/network/ssl/qocsp/CMakeLists.txt
+++ b/tests/auto/network/ssl/qocsp/CMakeLists.txt
@@ -1,22 +1,26 @@
-# Generated from qocsp.pro.
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
#####################################################################
## tst_qocsp Test:
#####################################################################
+if(NOT QT_BUILD_STANDALONE_TESTS AND NOT QT_BUILDING_QT)
+ cmake_minimum_required(VERSION 3.16)
+ project(tst_qocsp LANGUAGES CXX)
+ find_package(Qt6BuildInternals REQUIRED COMPONENTS STANDALONE_TEST)
+endif()
+
qt_internal_add_test(tst_qocsp
SOURCES
tst_qocsp.cpp
- PUBLIC_LIBRARIES
+ LIBRARIES
Qt::Network
Qt::NetworkPrivate
+ BUNDLE_ANDROID_OPENSSL_LIBS
)
-## Scopes:
-#####################################################################
-
-#### Keys ignored in scope 3:.:.:qocsp.pro:(CMAKE_BUILD_TYPE STREQUAL Debug):
-# DESTDIR = "debug"
-
-#### Keys ignored in scope 4:.:.:qocsp.pro:else:
-# DESTDIR = "release"
+qt_internal_extend_target(tst_qocsp CONDITION QT_FEATURE_openssl_linked
+ LIBRARIES
+ WrapOpenSSL::WrapOpenSSL
+)
diff --git a/tests/auto/network/ssl/qocsp/tst_qocsp.cpp b/tests/auto/network/ssl/qocsp/tst_qocsp.cpp
index 1b48b59534..81ce030be0 100644
--- a/tests/auto/network/ssl/qocsp/tst_qocsp.cpp
+++ b/tests/auto/network/ssl/qocsp/tst_qocsp.cpp
@@ -1,30 +1,5 @@
-/****************************************************************************
- **
- ** Copyright (C) 2018 The Qt Company Ltd.
- ** Contact: https://www.qt.io/licensing/
- **
- ** This file is part of the test suite of the Qt Toolkit.
- **
- ** $QT_BEGIN_LICENSE:GPL-EXCEPT$
- ** Commercial License Usage
- ** Licensees holding valid commercial Qt licenses may use this file in
- ** accordance with the commercial license agreement provided with the
- ** Software or, alternatively, in accordance with the terms contained in
- ** a written agreement between you and The Qt Company. For licensing terms
- ** and conditions see https://www.qt.io/terms-conditions. For further
- ** information use the contact form at https://www.qt.io/contact-us.
- **
- ** GNU General Public License Usage
- ** Alternatively, this file may be used under the terms of the GNU
- ** General Public License version 3 as published by the Free Software
- ** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
- ** included in the packaging of this file. Please review the following
- ** information to ensure the GNU General Public License requirements will
- ** be met: https://www.gnu.org/licenses/gpl-3.0.html.
- **
- ** $QT_END_LICENSE$
- **
- ****************************************************************************/
+// Copyright (C) 2018 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
#include <QTest>
#include <QTestEventLoop>
@@ -53,6 +28,8 @@
#include <algorithm>
#include <utility>
+using namespace std::chrono_literals;
+
// NOTE: the word 'subject' in the code below means the subject of a status request,
// so in general it's our peer's certificate we are asking about.
@@ -411,7 +388,7 @@ private:
void (QSslSocket::*tlsErrorsSignal)(const QList<QSslError> &) = &QSslSocket::sslErrors;
void (QTestEventLoop::*exitLoopSlot)() = &QTestEventLoop::exitLoop;
- const int handshakeTimeoutMS = 500;
+ static constexpr auto HandshakeTimeout = 500ms;
QTestEventLoop loop;
std::vector<QSslError::SslError> ocspErrorCodes = {QSslError::OcspNoResponseFound,
@@ -487,7 +464,7 @@ void tst_QOcsp::connectSelfSigned()
auto roots = clientConfig.caCertificates();
setupOcspClient(clientSocket, issuerToChain(subjectChain), server.peerVerifyName());
clientSocket.connectToHostEncrypted(server.hostName(), server.serverPort());
- loop.enterLoopMSecs(handshakeTimeoutMS);
+ loop.enterLoop(HandshakeTimeout);
QVERIFY(!clientSocket.isEncrypted());
QCOMPARE_SINGLE_ERROR(clientSocket, expectedError);
@@ -503,7 +480,7 @@ void tst_QOcsp::connectSelfSigned()
QSslSocket clientSocket;
setupOcspClient(clientSocket, issuerToChain(subjectChain), server.peerVerifyName());
clientSocket.connectToHostEncrypted(server.hostName(), server.serverPort());
- loop.enterLoopMSecs(handshakeTimeoutMS);
+ loop.enterLoop(HandshakeTimeout);
QVERIFY_HANDSHAKE_WITHOUT_ERRORS(clientSocket);
@@ -568,7 +545,7 @@ void tst_QOcsp::badStatus()
QSslSocket clientSocket;
setupOcspClient(clientSocket, issuerToChain(subjectChain), server.peerVerifyName());
clientSocket.connectToHostEncrypted(server.hostName(), server.serverPort());
- loop.enterLoopMSecs(handshakeTimeoutMS);
+ loop.enterLoop(HandshakeTimeout);
QVERIFY(!clientSocket.isEncrypted());
QCOMPARE_SINGLE_ERROR(clientSocket, expectedError.error());
@@ -599,7 +576,7 @@ void tst_QOcsp::multipleSingleResponses()
QSslSocket clientSocket;
setupOcspClient(clientSocket, issuerToChain(responderChain), server.peerVerifyName());
clientSocket.connectToHostEncrypted(server.hostName(), server.serverPort());
- loop.enterLoopMSecs(handshakeTimeoutMS);
+ loop.enterLoop(HandshakeTimeout);
QVERIFY(!clientSocket.isEncrypted());
QCOMPARE_SINGLE_ERROR(clientSocket, expectedError);
@@ -619,7 +596,7 @@ void tst_QOcsp::malformedResponse()
QSslSocket clientSocket;
setupOcspClient(clientSocket, issuerToChain(serverChain), server.peerVerifyName());
clientSocket.connectToHostEncrypted(server.hostName(), server.serverPort());
- loop.enterLoopMSecs(handshakeTimeoutMS);
+ loop.enterLoop(HandshakeTimeout);
QVERIFY(!clientSocket.isEncrypted());
QCOMPARE(clientSocket.error(), QAbstractSocket::SslHandshakeFailedError);
@@ -658,7 +635,7 @@ void tst_QOcsp::expiredResponse()
QSslSocket clientSocket;
setupOcspClient(clientSocket, issuerToChain(subjectChain), server.peerVerifyName());
clientSocket.connectToHostEncrypted(server.hostName(), server.serverPort());
- loop.enterLoopMSecs(handshakeTimeoutMS);
+ loop.enterLoop(HandshakeTimeout);
QVERIFY(!clientSocket.isEncrypted());
QCOMPARE_SINGLE_ERROR(clientSocket, expectedError);
@@ -689,7 +666,7 @@ void tst_QOcsp::noNextUpdate()
QSslSocket clientSocket;
setupOcspClient(clientSocket, issuerToChain(subjectChain), server.peerVerifyName());
clientSocket.connectToHostEncrypted(server.hostName(), server.serverPort());
- loop.enterLoopMSecs(handshakeTimeoutMS);
+ loop.enterLoop(HandshakeTimeout);
QVERIFY_HANDSHAKE_WITHOUT_ERRORS(clientSocket);
}
@@ -735,7 +712,7 @@ void tst_QOcsp::wrongCertificateInResponse()
QSslSocket clientSocket;
setupOcspClient(clientSocket, issuerToChain(subjectChain), server.peerVerifyName());
clientSocket.connectToHostEncrypted(server.hostName(), server.serverPort());
- loop.enterLoopMSecs(handshakeTimeoutMS);
+ loop.enterLoop(HandshakeTimeout);
QVERIFY(!clientSocket.isEncrypted());
QVERIFY(containsError(clientSocket.sslHandshakeErrors(), expectedError));
@@ -760,7 +737,7 @@ void tst_QOcsp::untrustedResponder()
QSslSocket clientSocket;
setupOcspClient(clientSocket, {}, server.peerVerifyName());
clientSocket.connectToHostEncrypted(server.hostName(), server.serverPort());
- loop.enterLoopMSecs(handshakeTimeoutMS);
+ loop.enterLoop(HandshakeTimeout);
QVERIFY(!clientSocket.isEncrypted());
QVERIFY(containsError(clientSocket.sslHandshakeErrors(), expectedError));
diff --git a/tests/auto/network/ssl/qpassworddigestor/CMakeLists.txt b/tests/auto/network/ssl/qpassworddigestor/CMakeLists.txt
index 29eb26e377..96491eada9 100644
--- a/tests/auto/network/ssl/qpassworddigestor/CMakeLists.txt
+++ b/tests/auto/network/ssl/qpassworddigestor/CMakeLists.txt
@@ -1,12 +1,20 @@
-# Generated from qpassworddigestor.pro.
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
#####################################################################
## tst_qpassworddigestor Test:
#####################################################################
+if(NOT QT_BUILD_STANDALONE_TESTS AND NOT QT_BUILDING_QT)
+ cmake_minimum_required(VERSION 3.16)
+ project(tst_qpassworddigestor LANGUAGES CXX)
+ find_package(Qt6BuildInternals REQUIRED COMPONENTS STANDALONE_TEST)
+endif()
+
qt_internal_add_test(tst_qpassworddigestor
SOURCES
tst_qpassworddigestor.cpp
- PUBLIC_LIBRARIES
+ LIBRARIES
Qt::Network
+ BUNDLE_ANDROID_OPENSSL_LIBS
)
diff --git a/tests/auto/network/ssl/qpassworddigestor/tst_qpassworddigestor.cpp b/tests/auto/network/ssl/qpassworddigestor/tst_qpassworddigestor.cpp
index 27201d23d0..1876c955af 100644
--- a/tests/auto/network/ssl/qpassworddigestor/tst_qpassworddigestor.cpp
+++ b/tests/auto/network/ssl/qpassworddigestor/tst_qpassworddigestor.cpp
@@ -1,30 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2018 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2018 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
#include <QTest>
#include <QtNetwork/qpassworddigestor.h>
diff --git a/tests/auto/network/ssl/qsslcertificate/CMakeLists.txt b/tests/auto/network/ssl/qsslcertificate/CMakeLists.txt
index caeac8d68a..6f81a5e030 100644
--- a/tests/auto/network/ssl/qsslcertificate/CMakeLists.txt
+++ b/tests/auto/network/ssl/qsslcertificate/CMakeLists.txt
@@ -1,15 +1,20 @@
-# Generated from qsslcertificate.pro.
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
#####################################################################
## tst_qsslcertificate Test:
#####################################################################
-# special case begin
+if(NOT QT_BUILD_STANDALONE_TESTS AND NOT QT_BUILDING_QT)
+ cmake_minimum_required(VERSION 3.16)
+ project(tst_qsslcertificate LANGUAGES CXX)
+ find_package(Qt6BuildInternals REQUIRED COMPONENTS STANDALONE_TEST)
+endif()
+
# This test requires private tests to properly build
if (NOT QT_FEATURE_private_tests)
return()
endif()
-# special case end
# Collect test data
file(GLOB_RECURSE test_data_glob
@@ -32,7 +37,8 @@ list(APPEND test_data ${test_data_glob})
qt_internal_add_test(tst_qsslcertificate
SOURCES
tst_qsslcertificate.cpp
- PUBLIC_LIBRARIES
+ LIBRARIES
Qt::Network
TESTDATA ${test_data}
+ BUNDLE_ANDROID_OPENSSL_LIBS
)
diff --git a/tests/auto/network/ssl/qsslcertificate/certificates/gencertificates.sh b/tests/auto/network/ssl/qsslcertificate/certificates/gencertificates.sh
index 4d68549396..cdc1019dcb 100755
--- a/tests/auto/network/ssl/qsslcertificate/certificates/gencertificates.sh
+++ b/tests/auto/network/ssl/qsslcertificate/certificates/gencertificates.sh
@@ -1,31 +1,6 @@
#!/bin/sh
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is the build configuration utility of the Qt Toolkit.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
+# Copyright (C) 2016 The Qt Company Ltd.
+# SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0
# This script generates digital certificates of different types.
diff --git a/tests/auto/network/ssl/qsslcertificate/more-certificates/cert-large-expiration-date.txt.0.9.8 b/tests/auto/network/ssl/qsslcertificate/more-certificates/cert-large-expiration-date.txt.0.9.8
deleted file mode 100644
index 20500b221f..0000000000
--- a/tests/auto/network/ssl/qsslcertificate/more-certificates/cert-large-expiration-date.txt.0.9.8
+++ /dev/null
@@ -1,42 +0,0 @@
-Certificate:
- Data:
- Version: 3 (0x2)
- Serial Number:
- ce:db:31:28:45:c4:05:40
- Signature Algorithm: sha1WithRSAEncryption
- Issuer: C=AU, ST=Some-State, O=Internet Widgits Pty Ltd
- Validity
- Not Before: Aug 4 09:53:41 2010 GMT
- Not After : Aug 29 09:53:41 2051 GMT
- Subject: C=AU, ST=Some-State, O=Internet Widgits Pty Ltd
- Subject Public Key Info:
- Public Key Algorithm: rsaEncryption
- RSA Public Key: (1024 bit)
- Modulus (1024 bit):
- 00:cd:aa:db:6f:d6:34:c9:a7:f1:c0:be:e4:41:18:
- 19:e2:02:c9:22:e6:a7:d5:ba:03:2e:9e:28:7a:f4:
- 5f:1a:77:5f:77:a9:11:3b:8f:7e:f0:2e:c6:9e:eb:
- 3a:d9:12:d7:c1:0c:51:e8:24:52:3f:23:c3:42:0c:
- 11:c6:f2:1c:a1:42:fe:b4:c2:69:83:ad:f7:70:b1:
- 18:15:cc:20:28:62:30:f0:2c:15:e6:33:19:af:c3:
- eb:1c:c0:91:f7:11:68:94:50:f8:49:37:08:32:d7:
- 3e:75:df:a3:bc:69:00:15:de:cd:87:0f:5c:02:6b:
- 82:c8:01:7d:6a:f0:1d:dc:73
- Exponent: 65537 (0x10001)
- X509v3 extensions:
- X509v3 Subject Key Identifier:
- 8A:6E:19:E7:97:9B:8F:D9:7F:B3:BB:01:4F:E8:6A:2F:52:95:0D:D9
- X509v3 Authority Key Identifier:
- keyid:8A:6E:19:E7:97:9B:8F:D9:7F:B3:BB:01:4F:E8:6A:2F:52:95:0D:D9
-
- X509v3 Basic Constraints:
- CA:TRUE
- Signature Algorithm: sha1WithRSAEncryption
- a1:74:8e:5d:36:96:2c:05:7e:ea:66:cc:2e:68:c7:3d:93:dc:
- 8c:a3:11:ad:b5:7e:6e:d0:04:c4:09:bd:0a:f9:39:3b:97:d7:
- f0:bb:0c:09:7b:83:fe:bf:87:b0:47:e8:94:b7:aa:9c:79:ad:
- 71:9e:b7:c4:99:98:6f:1d:38:32:f8:a3:75:38:c4:e5:e7:37:
- 37:21:ec:7b:50:8b:15:b0:97:1e:17:9c:50:17:3c:c1:df:94:
- 55:fb:60:2e:50:40:d1:ea:23:c6:3c:21:6f:97:8c:06:16:a5:
- 82:72:c1:63:14:64:86:eb:d7:ff:72:f6:09:f5:6d:e6:04:13:
- 7a:6a
diff --git a/tests/auto/network/ssl/qsslcertificate/more-certificates/cert-large-expiration-date.txt.1.0.1 b/tests/auto/network/ssl/qsslcertificate/more-certificates/cert-large-expiration-date.txt.1.0.1
deleted file mode 100644
index 1a7d945b76..0000000000
--- a/tests/auto/network/ssl/qsslcertificate/more-certificates/cert-large-expiration-date.txt.1.0.1
+++ /dev/null
@@ -1,42 +0,0 @@
-Certificate:
- Data:
- Version: 3 (0x2)
- Serial Number:
- ce:db:31:28:45:c4:05:40
- Signature Algorithm: sha1WithRSAEncryption
- Issuer: C=AU, ST=Some-State, O=Internet Widgits Pty Ltd
- Validity
- Not Before: Aug 4 09:53:41 2010 GMT
- Not After : Aug 29 09:53:41 2051 GMT
- Subject: C=AU, ST=Some-State, O=Internet Widgits Pty Ltd
- Subject Public Key Info:
- Public Key Algorithm: rsaEncryption
- Public-Key: (1024 bit)
- Modulus:
- 00:cd:aa:db:6f:d6:34:c9:a7:f1:c0:be:e4:41:18:
- 19:e2:02:c9:22:e6:a7:d5:ba:03:2e:9e:28:7a:f4:
- 5f:1a:77:5f:77:a9:11:3b:8f:7e:f0:2e:c6:9e:eb:
- 3a:d9:12:d7:c1:0c:51:e8:24:52:3f:23:c3:42:0c:
- 11:c6:f2:1c:a1:42:fe:b4:c2:69:83:ad:f7:70:b1:
- 18:15:cc:20:28:62:30:f0:2c:15:e6:33:19:af:c3:
- eb:1c:c0:91:f7:11:68:94:50:f8:49:37:08:32:d7:
- 3e:75:df:a3:bc:69:00:15:de:cd:87:0f:5c:02:6b:
- 82:c8:01:7d:6a:f0:1d:dc:73
- Exponent: 65537 (0x10001)
- X509v3 extensions:
- X509v3 Subject Key Identifier:
- 8A:6E:19:E7:97:9B:8F:D9:7F:B3:BB:01:4F:E8:6A:2F:52:95:0D:D9
- X509v3 Authority Key Identifier:
- keyid:8A:6E:19:E7:97:9B:8F:D9:7F:B3:BB:01:4F:E8:6A:2F:52:95:0D:D9
-
- X509v3 Basic Constraints:
- CA:TRUE
- Signature Algorithm: sha1WithRSAEncryption
- a1:74:8e:5d:36:96:2c:05:7e:ea:66:cc:2e:68:c7:3d:93:dc:
- 8c:a3:11:ad:b5:7e:6e:d0:04:c4:09:bd:0a:f9:39:3b:97:d7:
- f0:bb:0c:09:7b:83:fe:bf:87:b0:47:e8:94:b7:aa:9c:79:ad:
- 71:9e:b7:c4:99:98:6f:1d:38:32:f8:a3:75:38:c4:e5:e7:37:
- 37:21:ec:7b:50:8b:15:b0:97:1e:17:9c:50:17:3c:c1:df:94:
- 55:fb:60:2e:50:40:d1:ea:23:c6:3c:21:6f:97:8c:06:16:a5:
- 82:72:c1:63:14:64:86:eb:d7:ff:72:f6:09:f5:6d:e6:04:13:
- 7a:6a
diff --git a/tests/auto/network/ssl/qsslcertificate/more-certificates/cert-large-expiration-date.txt.1.0.1c b/tests/auto/network/ssl/qsslcertificate/more-certificates/cert-large-expiration-date.txt.1.0.1c
deleted file mode 100644
index a45ed864f4..0000000000
--- a/tests/auto/network/ssl/qsslcertificate/more-certificates/cert-large-expiration-date.txt.1.0.1c
+++ /dev/null
@@ -1,41 +0,0 @@
-Certificate:
- Data:
- Version: 3 (0x2)
- Serial Number: 14905561440751715648 (0xcedb312845c40540)
- Signature Algorithm: sha1WithRSAEncryption
- Issuer: C=AU, ST=Some-State, O=Internet Widgits Pty Ltd
- Validity
- Not Before: Aug 4 09:53:41 2010 GMT
- Not After : Aug 29 09:53:41 2051 GMT
- Subject: C=AU, ST=Some-State, O=Internet Widgits Pty Ltd
- Subject Public Key Info:
- Public Key Algorithm: rsaEncryption
- Public-Key: (1024 bit)
- Modulus:
- 00:cd:aa:db:6f:d6:34:c9:a7:f1:c0:be:e4:41:18:
- 19:e2:02:c9:22:e6:a7:d5:ba:03:2e:9e:28:7a:f4:
- 5f:1a:77:5f:77:a9:11:3b:8f:7e:f0:2e:c6:9e:eb:
- 3a:d9:12:d7:c1:0c:51:e8:24:52:3f:23:c3:42:0c:
- 11:c6:f2:1c:a1:42:fe:b4:c2:69:83:ad:f7:70:b1:
- 18:15:cc:20:28:62:30:f0:2c:15:e6:33:19:af:c3:
- eb:1c:c0:91:f7:11:68:94:50:f8:49:37:08:32:d7:
- 3e:75:df:a3:bc:69:00:15:de:cd:87:0f:5c:02:6b:
- 82:c8:01:7d:6a:f0:1d:dc:73
- Exponent: 65537 (0x10001)
- X509v3 extensions:
- X509v3 Subject Key Identifier:
- 8A:6E:19:E7:97:9B:8F:D9:7F:B3:BB:01:4F:E8:6A:2F:52:95:0D:D9
- X509v3 Authority Key Identifier:
- keyid:8A:6E:19:E7:97:9B:8F:D9:7F:B3:BB:01:4F:E8:6A:2F:52:95:0D:D9
-
- X509v3 Basic Constraints:
- CA:TRUE
- Signature Algorithm: sha1WithRSAEncryption
- a1:74:8e:5d:36:96:2c:05:7e:ea:66:cc:2e:68:c7:3d:93:dc:
- 8c:a3:11:ad:b5:7e:6e:d0:04:c4:09:bd:0a:f9:39:3b:97:d7:
- f0:bb:0c:09:7b:83:fe:bf:87:b0:47:e8:94:b7:aa:9c:79:ad:
- 71:9e:b7:c4:99:98:6f:1d:38:32:f8:a3:75:38:c4:e5:e7:37:
- 37:21:ec:7b:50:8b:15:b0:97:1e:17:9c:50:17:3c:c1:df:94:
- 55:fb:60:2e:50:40:d1:ea:23:c6:3c:21:6f:97:8c:06:16:a5:
- 82:72:c1:63:14:64:86:eb:d7:ff:72:f6:09:f5:6d:e6:04:13:
- 7a:6a
diff --git a/tests/auto/network/ssl/qsslcertificate/more-certificates/cert-large-expiration-date.txt.1.0.0 b/tests/auto/network/ssl/qsslcertificate/more-certificates/cert-large-expiration-date.txt.3.0.5
index b2ccb2751e..a2cf759c10 100644
--- a/tests/auto/network/ssl/qsslcertificate/more-certificates/cert-large-expiration-date.txt.1.0.0
+++ b/tests/auto/network/ssl/qsslcertificate/more-certificates/cert-large-expiration-date.txt.3.0.5
@@ -27,11 +27,11 @@ Certificate:
X509v3 Subject Key Identifier:
8A:6E:19:E7:97:9B:8F:D9:7F:B3:BB:01:4F:E8:6A:2F:52:95:0D:D9
X509v3 Authority Key Identifier:
- keyid:8A:6E:19:E7:97:9B:8F:D9:7F:B3:BB:01:4F:E8:6A:2F:52:95:0D:D9
-
+ 8A:6E:19:E7:97:9B:8F:D9:7F:B3:BB:01:4F:E8:6A:2F:52:95:0D:D9
X509v3 Basic Constraints:
CA:TRUE
Signature Algorithm: sha1WithRSAEncryption
+ Signature Value:
a1:74:8e:5d:36:96:2c:05:7e:ea:66:cc:2e:68:c7:3d:93:dc:
8c:a3:11:ad:b5:7e:6e:d0:04:c4:09:bd:0a:f9:39:3b:97:d7:
f0:bb:0c:09:7b:83:fe:bf:87:b0:47:e8:94:b7:aa:9c:79:ad:
diff --git a/tests/auto/network/ssl/qsslcertificate/tst_qsslcertificate.cpp b/tests/auto/network/ssl/qsslcertificate/tst_qsslcertificate.cpp
index d9e58c39c1..b51053effd 100644
--- a/tests/auto/network/ssl/qsslcertificate/tst_qsslcertificate.cpp
+++ b/tests/auto/network/ssl/qsslcertificate/tst_qsslcertificate.cpp
@@ -1,43 +1,22 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
#include <QTest>
#include <QtNetwork/qtnetworkglobal.h>
+#include <QtCore/qdatetime.h>
+#include <QtCore/qtimezone.h>
+#include <QtCore/qscopeguard.h>
+#include <QtCore/qset.h>
+
#include <qsslcertificate.h>
#include <qsslkey.h>
#include <qsslsocket.h>
#include <qsslcertificateextension.h>
-#include <qscopeguard.h>
#ifndef QT_NO_OPENSSL
+#include <openssl/opensslv.h>
#include <openssl/obj_mac.h>
#endif
@@ -123,7 +102,31 @@ private slots:
#endif // QT_CONFIG(ssl)
private:
QString testDataDir;
- bool isNonOpenSslTls = false;
+
+ enum class TLSBackend {
+ OpenSSL,
+ Schannel,
+ SecureTransport,
+ CertOnly,
+ Unknown,
+ };
+ static TLSBackend currentBackend()
+ {
+ static TLSBackend activeBackend = []() {
+ using namespace Qt::StringLiterals;
+ const QString active = QSslSocket::activeBackend();
+ if (active == "openssl"_L1)
+ return TLSBackend::OpenSSL;
+ if (active == "schannel")
+ return TLSBackend::Schannel;
+ if (active == "securetransport")
+ return TLSBackend::SecureTransport;
+ if (active == "cert-only")
+ return TLSBackend::CertOnly;
+ return TLSBackend::Unknown;
+ }();
+ return activeBackend;
+ }
};
void tst_QSslCertificate::initTestCase()
@@ -133,22 +136,15 @@ void tst_QSslCertificate::initTestCase()
testDataDir = QCoreApplication::applicationDirPath();
if (!testDataDir.endsWith(QLatin1String("/")))
testDataDir += QLatin1String("/");
-#if QT_CONFIG(opensslv11)
- // In the presence of 'openssl' backend, QSslSocket will
- // select 'openssl' as the default one.
- isNonOpenSslTls = QSslSocket::activeBackend() != QStringLiteral("openssl");
-#else
- isNonOpenSslTls = true;
-#endif // QT_CONFIG(ssl)
QDir dir(testDataDir + "certificates");
- QFileInfoList fileInfoList = dir.entryInfoList(QDir::Files | QDir::Readable);
+ const QFileInfoList fileInfoList = dir.entryInfoList(QDir::Files | QDir::Readable);
QRegularExpression rxCert(QLatin1String("^.+\\.(pem|der)$"));
QRegularExpression rxSan(QLatin1String("^(.+\\.(?:pem|der))\\.san$"));
QRegularExpression rxPubKey(QLatin1String("^(.+\\.(?:pem|der))\\.pubkey$"));
QRegularExpression rxDigest(QLatin1String("^(.+\\.(?:pem|der))\\.digest-(md5|sha1)$"));
QRegularExpressionMatch match;
- foreach (QFileInfo fileInfo, fileInfoList) {
+ for (const QFileInfo &fileInfo : fileInfoList) {
if ((match = rxCert.match(fileInfo.fileName())).hasMatch())
certInfoList <<
CertInfo(fileInfo,
@@ -211,7 +207,7 @@ void tst_QSslCertificate::createTestRows()
{
QTest::addColumn<QString>("absFilePath");
QTest::addColumn<QSsl::EncodingFormat>("format");
- foreach (CertInfo certInfo, certInfoList) {
+ for (const CertInfo &certInfo : std::as_const(certInfoList)) {
QTest::newRow(certInfo.fileInfo.fileName().toLatin1())
<< certInfo.fileInfo.absoluteFilePath() << certInfo.format;
}
@@ -342,7 +338,7 @@ void tst_QSslCertificate::digest_data()
QTest::addColumn<QSsl::EncodingFormat>("format");
QTest::addColumn<QString>("absFilePath_digest_md5");
QTest::addColumn<QString>("absFilePath_digest_sha1");
- foreach (CertInfo certInfo, certInfoList) {
+ for (const CertInfo &certInfo : std::as_const(certInfoList)) {
QString certName = certInfo.fileInfo.fileName();
QTest::newRow(certName.toLatin1())
<< certInfo.fileInfo.absoluteFilePath()
@@ -395,7 +391,7 @@ void tst_QSslCertificate::subjectAlternativeNames_data()
QTest::addColumn<QSsl::EncodingFormat>("format");
QTest::addColumn<QString>("subjAltNameFilePath");
- foreach (CertInfo certInfo, certInfoList) {
+ for (const CertInfo &certInfo : std::as_const(certInfoList)) {
QString certName = certInfo.fileInfo.fileName();
if (subjAltNameMap.contains(certName))
QTest::newRow(certName.toLatin1())
@@ -477,7 +473,7 @@ void tst_QSslCertificate::subjectInfoToString()
QVERIFY(testInfo(QSslCertificate::DistinguishedNameQualifier, QString()));
QVERIFY(testInfo(QSslCertificate::SerialNumber, QString()));
// TODO: check why generic code does not handle this!
- if (!isNonOpenSslTls)
+ if (currentBackend() == TLSBackend::OpenSSL)
QVERIFY(testInfo(QSslCertificate::EmailAddress, QStringLiteral("ababic@trolltech.com")));
}
@@ -489,9 +485,8 @@ void tst_QSslCertificate::subjectIssuerDisplayName_data()
QTest::addRow("CommonName") << QStringLiteral("more-certificates/cert-cn.pem") << QStringLiteral("YOUR name");
QTest::addRow("OrganizationName") << QStringLiteral("more-certificates/cert-on.pem") << QStringLiteral("R&D");
QTest::addRow("OrganizationUnitName") << QStringLiteral("more-certificates/cert-oun.pem") << QStringLiteral("Foundations");
-#ifndef QT_NO_OPENSSL
- QTest::addRow("NoSubjectName") << QStringLiteral("more-certificates/cert-noname.pem") << QString();
-#endif
+ if (currentBackend() == TLSBackend::OpenSSL)
+ QTest::addRow("NoSubjectName") << QStringLiteral("more-certificates/cert-noname.pem") << QString();
}
void tst_QSslCertificate::subjectIssuerDisplayName()
@@ -521,7 +516,7 @@ void tst_QSslCertificate::utf8SubjectNames()
static const char *ou = "\xe3\x88\xa7" "A" "\xe3\x89\x81\xef\xbd\xab" "BC";
// the following two tests should help find "\x"-literal encoding bugs in the test itself
- QCOMPARE(cert.subjectInfo("O")[0].length(), QString::fromUtf8(o).length());
+ QCOMPARE(cert.subjectInfo("O")[0].size(), QString::fromUtf8(o).size());
QCOMPARE (cert.subjectInfo("O")[0].toUtf8().toHex(), QByteArray(o).toHex());
QCOMPARE(cert.subjectInfo("O")[0], QString::fromUtf8(o));
@@ -534,7 +529,7 @@ void tst_QSslCertificate::publicKey_data()
QTest::addColumn<QSsl::EncodingFormat>("format");
QTest::addColumn<QString>("pubkeyFilePath");
- foreach (CertInfo certInfo, certInfoList) {
+ for (const CertInfo &certInfo : std::as_const(certInfoList)) {
QString certName = certInfo.fileInfo.fileName();
if (pubkeyMap.contains(certName))
QTest::newRow(certName.toLatin1())
@@ -836,8 +831,10 @@ void tst_QSslCertificate::certInfo()
QCOMPARE(cert.digest(QCryptographicHash::Sha1),
QByteArray::fromHex("B6:D1:51:82:E0:29:CA:59:96:38:BD:B6:F9:40:05:91:6D:49:09:60"));
- QCOMPARE(cert.effectiveDate().toUTC(), QDateTime(QDate(2007, 4, 17), QTime(7,40,26), Qt::UTC));
- QCOMPARE(cert.expiryDate().toUTC(), QDateTime(QDate(2007, 5, 17), QTime(7,40,26), Qt::UTC));
+ QCOMPARE(cert.effectiveDate().toUTC(),
+ QDateTime(QDate(2007, 4, 17), QTime(7,40,26), QTimeZone::UTC));
+ QCOMPARE(cert.expiryDate().toUTC(),
+ QDateTime(QDate(2007, 5, 17), QTime(7,40,26), QTimeZone::UTC));
QVERIFY(cert.expiryDate() < QDateTime::currentDateTime()); // cert has expired
QSslCertificate copy = cert;
@@ -899,7 +896,7 @@ void tst_QSslCertificate::task256066toPem()
void tst_QSslCertificate::nulInCN()
{
- if (isNonOpenSslTls)
+ if (currentBackend() != TLSBackend::OpenSSL)
QSKIP("Generic QSslCertificatePrivate fails this test");
QList<QSslCertificate> certList =
@@ -919,7 +916,7 @@ void tst_QSslCertificate::nulInCN()
void tst_QSslCertificate::nulInSan()
{
- if (isNonOpenSslTls)
+ if (currentBackend() != TLSBackend::OpenSSL)
QSKIP("Generic QSslCertificatePrivate fails this test");
QList<QSslCertificate> certList =
@@ -961,16 +958,18 @@ void tst_QSslCertificate::largeExpirationDate() // QTBUG-12489
const QSslCertificate &cert = certList.at(0);
QVERIFY(!cert.isNull());
- QCOMPARE(cert.effectiveDate().toUTC(), QDateTime(QDate(2010, 8, 4), QTime(9, 53, 41), Qt::UTC));
+ QCOMPARE(cert.effectiveDate().toUTC(),
+ QDateTime(QDate(2010, 8, 4), QTime(9, 53, 41), QTimeZone::UTC));
// if the date is larger than 2049, then the generalized time format is used
- QCOMPARE(cert.expiryDate().toUTC(), QDateTime(QDate(2051, 8, 29), QTime(9, 53, 41), Qt::UTC));
+ QCOMPARE(cert.expiryDate().toUTC(),
+ QDateTime(QDate(2051, 8, 29), QTime(9, 53, 41), QTimeZone::UTC));
}
void tst_QSslCertificate::blacklistedCertificates()
{
QList<QSslCertificate> blacklistedCerts = QSslCertificate::fromPath(testDataDir + "more-certificates/blacklisted*.pem", QSsl::Pem, QSslCertificate::PatternSyntax::Wildcard);
- QVERIFY(blacklistedCerts.count() > 0);
- for (int a = 0; a < blacklistedCerts.count(); a++) {
+ QVERIFY(blacklistedCerts.size() > 0);
+ for (int a = 0; a < blacklistedCerts.size(); a++) {
QVERIFY(blacklistedCerts.at(a).isBlacklisted());
}
}
@@ -984,7 +983,7 @@ void tst_QSslCertificate::selfsignedCertificates()
void tst_QSslCertificate::toText()
{
- if (isNonOpenSslTls)
+ if (currentBackend() != TLSBackend::OpenSSL)
QSKIP("QSslCertificate::toText is not implemented on platforms which do not use openssl");
QList<QSslCertificate> certList =
@@ -993,42 +992,26 @@ void tst_QSslCertificate::toText()
QCOMPARE(certList.size(), 1);
const QSslCertificate &cert = certList.at(0);
- // Openssl's cert dump method changed slightly between 0.9.8, 1.0.0 and 1.01 versions, so we want it to match any output
-
- QFile f098(testDataDir + "more-certificates/cert-large-expiration-date.txt.0.9.8");
- QVERIFY(f098.open(QIODevice::ReadOnly | QFile::Text));
- QByteArray txt098 = f098.readAll();
-
- QFile f100(testDataDir + "more-certificates/cert-large-expiration-date.txt.1.0.0");
- QVERIFY(f100.open(QIODevice::ReadOnly | QFile::Text));
- QByteArray txt100 = f100.readAll();
-
- QFile f101(testDataDir + "more-certificates/cert-large-expiration-date.txt.1.0.1");
- QVERIFY(f101.open(QIODevice::ReadOnly | QFile::Text));
- QByteArray txt101 = f101.readAll();
-
- QFile f101c(testDataDir + "more-certificates/cert-large-expiration-date.txt.1.0.1c");
- QVERIFY(f101c.open(QIODevice::ReadOnly | QFile::Text));
- QByteArray txt101c = f101c.readAll();
-
+ // Openssl's cert dump method changed slightly between 1.1.1 and 3.0.5 versions, so we want it to match any output
QFile f111(testDataDir + "more-certificates/cert-large-expiration-date.txt.1.1.1");
QVERIFY(f111.open(QIODevice::ReadOnly | QFile::Text));
QByteArray txt111 = f111.readAll();
+ QFile f305(testDataDir + "more-certificates/cert-large-expiration-date.txt.3.0.5");
+ QVERIFY(f305.open(QIODevice::ReadOnly | QFile::Text));
+ QByteArray txt305 = f305.readAll();
+
QString txtcert = cert.toText();
- QVERIFY(QString::fromLatin1(txt098) == txtcert ||
- QString::fromLatin1(txt100) == txtcert ||
- QString::fromLatin1(txt101) == txtcert ||
- QString::fromLatin1(txt101c) == txtcert ||
- QString::fromLatin1(txt111) == txtcert );
+ QVERIFY(QString::fromLatin1(txt111) == txtcert ||
+ QString::fromLatin1(txt305) == txtcert);
}
void tst_QSslCertificate::multipleCommonNames()
{
QList<QSslCertificate> certList =
QSslCertificate::fromPath(testDataDir + "more-certificates/test-cn-two-cns-cert.pem", QSsl::Pem, QSslCertificate::PatternSyntax::FixedString);
- QVERIFY(certList.count() > 0);
+ QVERIFY(certList.size() > 0);
QStringList commonNames = certList[0].subjectInfo(QSslCertificate::CommonName);
QVERIFY(commonNames.contains(QString("www.example.com")));
@@ -1039,18 +1022,18 @@ void tst_QSslCertificate::subjectAndIssuerAttributes()
{
QList<QSslCertificate> certList =
QSslCertificate::fromPath(testDataDir + "more-certificates/test-cn-with-drink-cert.pem", QSsl::Pem, QSslCertificate::PatternSyntax::FixedString);
- QVERIFY(certList.count() > 0);
+ QVERIFY(certList.size() > 0);
QList<QByteArray> attributes = certList[0].subjectInfoAttributes();
QVERIFY(attributes.contains(QByteArray("favouriteDrink")));
attributes.clear();
certList = QSslCertificate::fromPath(testDataDir + "more-certificates/natwest-banking.pem", QSsl::Pem, QSslCertificate::PatternSyntax::FixedString);
- QVERIFY(certList.count() > 0);
+ QVERIFY(certList.size() > 0);
QByteArray shortName("1.3.6.1.4.1.311.60.2.1.3");
#if !defined(QT_NO_OPENSSL) && defined(SN_jurisdictionCountryName)
- if (!isNonOpenSslTls)
+ if (currentBackend() == TLSBackend::OpenSSL)
shortName = SN_jurisdictionCountryName;
#endif
attributes = certList[0].subjectInfoAttributes();
@@ -1059,8 +1042,8 @@ void tst_QSslCertificate::subjectAndIssuerAttributes()
void tst_QSslCertificate::verify()
{
- if (isNonOpenSslTls)
- QSKIP("Not implemented in SecureTransport or Schannel");
+ if (currentBackend() != TLSBackend::OpenSSL)
+ QSKIP("Only implemented for OpenSSL");
QList<QSslError> errors;
QList<QSslCertificate> toVerify;
@@ -1073,7 +1056,7 @@ void tst_QSslCertificate::verify()
// Empty chain is unspecified error
errors = QSslCertificate::verify(toVerify);
- VERIFY_VERBOSE(errors.count() == 1);
+ VERIFY_VERBOSE(errors.size() == 1);
VERIFY_VERBOSE(errors[0] == QSslError(QSslError::UnspecifiedError));
errors.clear();
@@ -1092,14 +1075,14 @@ void tst_QSslCertificate::verify()
toVerify = QSslCertificate::fromPath(testDataDir + "verify-certs/test-ocsp-good-cert.pem", QSsl::Pem, QSslCertificate::PatternSyntax::FixedString);
errors = QSslCertificate::verify(toVerify);
- VERIFY_VERBOSE(errors.count() == 0);
+ VERIFY_VERBOSE(errors.size() == 0);
errors.clear();
// Test a blacklisted certificate
toVerify = QSslCertificate::fromPath(testDataDir + "verify-certs/test-addons-mozilla-org-cert.pem", QSsl::Pem, QSslCertificate::PatternSyntax::FixedString);
errors = QSslCertificate::verify(toVerify);
bool foundBlack = false;
- foreach (const QSslError &error, errors) {
+ for (const QSslError &error : std::as_const(errors)) {
if (error.error() == QSslError::CertificateBlacklisted) {
foundBlack = true;
break;
@@ -1127,11 +1110,11 @@ void tst_QSslCertificate::verify()
toVerify << QSslCertificate::fromPath(testDataDir + "verify-certs/test-intermediate-is-ca-cert.pem", QSsl::Pem, QSslCertificate::PatternSyntax::FixedString).first();
toVerify << QSslCertificate::fromPath(testDataDir + "verify-certs/test-intermediate-ca-cert.pem", QSsl::Pem, QSslCertificate::PatternSyntax::FixedString).first();
errors = QSslCertificate::verify(toVerify);
- VERIFY_VERBOSE(errors.count() == 0);
+ VERIFY_VERBOSE(errors.size() == 0);
// Recheck the above with hostname validation
errors = QSslCertificate::verify(toVerify, QLatin1String("example.com"));
- VERIFY_VERBOSE(errors.count() == 0);
+ VERIFY_VERBOSE(errors.size() == 0);
// Recheck the above with a bad hostname
errors = QSslCertificate::verify(toVerify, QLatin1String("fail.example.com"));
@@ -1145,9 +1128,8 @@ QString tst_QSslCertificate::toString(const QList<QSslError>& errors)
{
QStringList errorStrings;
- foreach (const QSslError& error, errors) {
+ for (const QSslError &error : errors)
errorStrings.append(QLatin1Char('"') + error.errorString() + QLatin1Char('"'));
- }
return QLatin1String("[ ") + errorStrings.join(QLatin1String(", ")) + QLatin1String(" ]");
}
@@ -1156,11 +1138,11 @@ void tst_QSslCertificate::extensions()
{
QList<QSslCertificate> certList =
QSslCertificate::fromPath(testDataDir + "more-certificates/natwest-banking.pem", QSsl::Pem, QSslCertificate::PatternSyntax::FixedString);
- QVERIFY(certList.count() > 0);
+ QVERIFY(certList.size() > 0);
QSslCertificate cert = certList[0];
QList<QSslCertificateExtension> extensions = cert.extensions();
- QCOMPARE(extensions.count(), 9);
+ QCOMPARE(extensions.size(), 9);
int unknown_idx = -1;
int authority_info_idx = -1;
@@ -1168,7 +1150,7 @@ void tst_QSslCertificate::extensions()
int subject_key_idx = -1;
int auth_key_idx = -1;
- for (int i=0; i < extensions.length(); ++i) {
+ for (int i=0; i < extensions.size(); ++i) {
QSslCertificateExtension ext = extensions[i];
//qDebug() << i << ":" << ext.name() << ext.oid();
@@ -1254,16 +1236,16 @@ void tst_QSslCertificate::extensionsCritical()
{
QList<QSslCertificate> certList =
QSslCertificate::fromPath(testDataDir + "verify-certs/test-addons-mozilla-org-cert.pem", QSsl::Pem, QSslCertificate::PatternSyntax::FixedString);
- QVERIFY(certList.count() > 0);
+ QVERIFY(certList.size() > 0);
QSslCertificate cert = certList[0];
QList<QSslCertificateExtension> extensions = cert.extensions();
- QCOMPARE(extensions.count(), 9);
+ QCOMPARE(extensions.size(), 9);
int basic_constraints_idx = -1;
int key_usage_idx = -1;
- for (int i=0; i < extensions.length(); ++i) {
+ for (int i=0; i < extensions.size(); ++i) {
QSslCertificateExtension ext = extensions[i];
if (ext.name() == QStringLiteral("basicConstraints"))
@@ -1401,6 +1383,9 @@ void tst_QSslCertificate::pkcs12()
return;
}
+ if (currentBackend() == TLSBackend::OpenSSL && QSslSocket::sslLibraryVersionNumber() >= 0x30000000L)
+ QSKIP("leaf.p12 is using RC2, which is disabled by default in OpenSSL v >= 3");
+
QFile f(testDataDir + QLatin1String("pkcs12/leaf.p12"));
bool ok = f.open(QIODevice::ReadOnly);
QVERIFY(ok);
@@ -1409,8 +1394,8 @@ void tst_QSslCertificate::pkcs12()
QSslCertificate cert;
QList<QSslCertificate> caCerts;
- if (isNonOpenSslTls)
- QEXPECT_FAIL("", "pkcs12 imports are only supported when openssl is used", Abort); // TODO?
+ if (currentBackend() != TLSBackend::OpenSSL)
+ QEXPECT_FAIL("", "pkcs12 imports are not available with the current TLS backend", Abort); // TODO?
ok = QSslCertificate::importPkcs12(&f, &key, &cert, &caCerts);
QVERIFY(ok);
@@ -1442,7 +1427,8 @@ void tst_QSslCertificate::pkcs12()
QFile nocert(testDataDir + QLatin1String("pkcs12/leaf-nokey.p12"));
ok = nocert.open(QIODevice::ReadOnly);
QVERIFY(ok);
- QTest::ignoreMessage(QtWarningMsg, "Unable to convert private key");
+ if (currentBackend() == TLSBackend::OpenSSL)
+ QTest::ignoreMessage(QtWarningMsg, "Unable to convert private key");
ok = QSslCertificate::importPkcs12(&nocert, &key, &cert, &caCerts);
QVERIFY(!ok);
nocert.close();
diff --git a/tests/auto/network/ssl/qsslcipher/CMakeLists.txt b/tests/auto/network/ssl/qsslcipher/CMakeLists.txt
index b8e8ba47d6..8538f56acd 100644
--- a/tests/auto/network/ssl/qsslcipher/CMakeLists.txt
+++ b/tests/auto/network/ssl/qsslcipher/CMakeLists.txt
@@ -1,21 +1,20 @@
-# Generated from qsslcipher.pro.
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
#####################################################################
## tst_qsslcipher Test:
#####################################################################
+if(NOT QT_BUILD_STANDALONE_TESTS AND NOT QT_BUILDING_QT)
+ cmake_minimum_required(VERSION 3.16)
+ project(tst_qsslcipher LANGUAGES CXX)
+ find_package(Qt6BuildInternals REQUIRED COMPONENTS STANDALONE_TEST)
+endif()
+
qt_internal_add_test(tst_qsslcipher
SOURCES
tst_qsslcipher.cpp
- PUBLIC_LIBRARIES
+ LIBRARIES
Qt::Network
+ BUNDLE_ANDROID_OPENSSL_LIBS
)
-
-## Scopes:
-#####################################################################
-
-#### Keys ignored in scope 3:.:.:qsslcipher.pro:(CMAKE_BUILD_TYPE STREQUAL Debug):
-# DESTDIR = "debug"
-
-#### Keys ignored in scope 4:.:.:qsslcipher.pro:else:
-# DESTDIR = "release"
diff --git a/tests/auto/network/ssl/qsslcipher/tst_qsslcipher.cpp b/tests/auto/network/ssl/qsslcipher/tst_qsslcipher.cpp
index 3d415bcd19..6810149c11 100644
--- a/tests/auto/network/ssl/qsslcipher/tst_qsslcipher.cpp
+++ b/tests/auto/network/ssl/qsslcipher/tst_qsslcipher.cpp
@@ -1,30 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
#include <QTest>
diff --git a/tests/auto/network/ssl/qssldiffiehellmanparameters/CMakeLists.txt b/tests/auto/network/ssl/qssldiffiehellmanparameters/CMakeLists.txt
index 0ef55a7b55..3ac34b2f6c 100644
--- a/tests/auto/network/ssl/qssldiffiehellmanparameters/CMakeLists.txt
+++ b/tests/auto/network/ssl/qssldiffiehellmanparameters/CMakeLists.txt
@@ -1,12 +1,20 @@
-# Generated from qssldiffiehellmanparameters.pro.
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
#####################################################################
## tst_qssldiffiehellmanparameters Test:
#####################################################################
+if(NOT QT_BUILD_STANDALONE_TESTS AND NOT QT_BUILDING_QT)
+ cmake_minimum_required(VERSION 3.16)
+ project(tst_qssldiffiehellmanparameters LANGUAGES CXX)
+ find_package(Qt6BuildInternals REQUIRED COMPONENTS STANDALONE_TEST)
+endif()
+
qt_internal_add_test(tst_qssldiffiehellmanparameters
SOURCES
tst_qssldiffiehellmanparameters.cpp
- PUBLIC_LIBRARIES
+ LIBRARIES
Qt::Network
+ BUNDLE_ANDROID_OPENSSL_LIBS
)
diff --git a/tests/auto/network/ssl/qssldiffiehellmanparameters/tst_qssldiffiehellmanparameters.cpp b/tests/auto/network/ssl/qssldiffiehellmanparameters/tst_qssldiffiehellmanparameters.cpp
index 3bf3c75dce..d8c6d9158a 100644
--- a/tests/auto/network/ssl/qssldiffiehellmanparameters/tst_qssldiffiehellmanparameters.cpp
+++ b/tests/auto/network/ssl/qssldiffiehellmanparameters/tst_qssldiffiehellmanparameters.cpp
@@ -1,30 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 Mikkel Krautz <mikkel@krautz.dk>
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2015 Mikkel Krautz <mikkel@krautz.dk>
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
#include <QTest>
diff --git a/tests/auto/network/ssl/qsslellipticcurve/CMakeLists.txt b/tests/auto/network/ssl/qsslellipticcurve/CMakeLists.txt
index bf4d255d19..dd031a991b 100644
--- a/tests/auto/network/ssl/qsslellipticcurve/CMakeLists.txt
+++ b/tests/auto/network/ssl/qsslellipticcurve/CMakeLists.txt
@@ -1,12 +1,20 @@
-# Generated from qsslellipticcurve.pro.
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
#####################################################################
## tst_qsslellipticcurve Test:
#####################################################################
+if(NOT QT_BUILD_STANDALONE_TESTS AND NOT QT_BUILDING_QT)
+ cmake_minimum_required(VERSION 3.16)
+ project(tst_qsslellipticcurve LANGUAGES CXX)
+ find_package(Qt6BuildInternals REQUIRED COMPONENTS STANDALONE_TEST)
+endif()
+
qt_internal_add_test(tst_qsslellipticcurve
SOURCES
tst_qsslellipticcurve.cpp
- PUBLIC_LIBRARIES
+ LIBRARIES
Qt::Network
+ BUNDLE_ANDROID_OPENSSL_LIBS
)
diff --git a/tests/auto/network/ssl/qsslellipticcurve/tst_qsslellipticcurve.cpp b/tests/auto/network/ssl/qsslellipticcurve/tst_qsslellipticcurve.cpp
index 35b7082fad..96ef7e9828 100644
--- a/tests/auto/network/ssl/qsslellipticcurve/tst_qsslellipticcurve.cpp
+++ b/tests/auto/network/ssl/qsslellipticcurve/tst_qsslellipticcurve.cpp
@@ -1,31 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2014 Governikus GmbH & Co. KG.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
-
+// Copyright (C) 2014 Governikus GmbH & Co. KG.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
#include <QTest>
@@ -91,7 +65,8 @@ void tst_QSslEllipticCurve::fromShortName_data()
QTest::newRow("QString()") << QString() << QSslEllipticCurve() << false;
QTest::newRow("\"\"") << QString("") << QSslEllipticCurve() << false;
QTest::newRow("does-not-exist") << QStringLiteral("does-not-exist") << QSslEllipticCurve() << false;
- Q_FOREACH (QSslEllipticCurve ec, QSslConfiguration::supportedEllipticCurves()) {
+ const auto supported = QSslConfiguration::supportedEllipticCurves();
+ for (QSslEllipticCurve ec : supported) {
const QString sN = ec.shortName();
QTest::newRow(qPrintable("supported EC \"" + sN + '"')) << sN << ec << true;
// At least in the OpenSSL impl, the short name is case-sensitive. That feels odd.
@@ -124,7 +99,8 @@ void tst_QSslEllipticCurve::fromLongName_data()
QTest::newRow("QString()") << QString() << QSslEllipticCurve() << false;
QTest::newRow("\"\"") << QString("") << QSslEllipticCurve() << false;
QTest::newRow("does-not-exist") << QStringLiteral("does-not-exist") << QSslEllipticCurve() << false;
- Q_FOREACH (QSslEllipticCurve ec, QSslConfiguration::supportedEllipticCurves()) {
+ const auto supported = QSslConfiguration::supportedEllipticCurves();
+ for (QSslEllipticCurve ec : supported) {
const QString lN = ec.longName();
QTest::newRow(qPrintable("supported EC \"" + lN + '"')) << lN << ec << true;
}
diff --git a/tests/auto/network/ssl/qsslerror/CMakeLists.txt b/tests/auto/network/ssl/qsslerror/CMakeLists.txt
index e9dd0953ba..006bec3ef2 100644
--- a/tests/auto/network/ssl/qsslerror/CMakeLists.txt
+++ b/tests/auto/network/ssl/qsslerror/CMakeLists.txt
@@ -1,21 +1,20 @@
-# Generated from qsslerror.pro.
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
#####################################################################
## tst_qsslerror Test:
#####################################################################
+if(NOT QT_BUILD_STANDALONE_TESTS AND NOT QT_BUILDING_QT)
+ cmake_minimum_required(VERSION 3.16)
+ project(tst_qsslerror LANGUAGES CXX)
+ find_package(Qt6BuildInternals REQUIRED COMPONENTS STANDALONE_TEST)
+endif()
+
qt_internal_add_test(tst_qsslerror
SOURCES
tst_qsslerror.cpp
- PUBLIC_LIBRARIES
+ LIBRARIES
Qt::Network
+ BUNDLE_ANDROID_OPENSSL_LIBS
)
-
-## Scopes:
-#####################################################################
-
-#### Keys ignored in scope 3:.:.:qsslerror.pro:(CMAKE_BUILD_TYPE STREQUAL Debug):
-# DESTDIR = "debug"
-
-#### Keys ignored in scope 4:.:.:qsslerror.pro:else:
-# DESTDIR = "release"
diff --git a/tests/auto/network/ssl/qsslerror/tst_qsslerror.cpp b/tests/auto/network/ssl/qsslerror/tst_qsslerror.cpp
index cb82edd556..981fe3a0d5 100644
--- a/tests/auto/network/ssl/qsslerror/tst_qsslerror.cpp
+++ b/tests/auto/network/ssl/qsslerror/tst_qsslerror.cpp
@@ -1,30 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
#include <QtNetwork/qtnetworkglobal.h>
diff --git a/tests/auto/network/ssl/qsslkey/BLACKLIST b/tests/auto/network/ssl/qsslkey/BLACKLIST
deleted file mode 100644
index 5705a1982d..0000000000
--- a/tests/auto/network/ssl/qsslkey/BLACKLIST
+++ /dev/null
@@ -1,8 +0,0 @@
-[constructor]
-rhel
-[length]
-rhel
-[toEncryptedPemOrDer]
-rhel
-[toPemOrDer]
-rhel
diff --git a/tests/auto/network/ssl/qsslkey/CMakeLists.txt b/tests/auto/network/ssl/qsslkey/CMakeLists.txt
index 8bf450f8fd..aae017562a 100644
--- a/tests/auto/network/ssl/qsslkey/CMakeLists.txt
+++ b/tests/auto/network/ssl/qsslkey/CMakeLists.txt
@@ -1,9 +1,16 @@
-# Generated from qsslkey.pro.
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
#####################################################################
## tst_qsslkey Test:
#####################################################################
+if(NOT QT_BUILD_STANDALONE_TESTS AND NOT QT_BUILDING_QT)
+ cmake_minimum_required(VERSION 3.16)
+ project(tst_qsslkey LANGUAGES CXX)
+ find_package(Qt6BuildInternals REQUIRED COMPONENTS STANDALONE_TEST)
+endif()
+
# Collect test data
file(GLOB_RECURSE test_data_glob
RELATIVE ${CMAKE_CURRENT_SOURCE_DIR}
@@ -17,16 +24,22 @@ list(APPEND test_data ${test_data_glob})
qt_internal_add_test(tst_qsslkey
SOURCES
tst_qsslkey.cpp
- PUBLIC_LIBRARIES
+ LIBRARIES
Qt::Network
TESTDATA ${test_data}
+ BUNDLE_ANDROID_OPENSSL_LIBS
+)
+
+qt_internal_extend_target(tst_qsslkey CONDITION QT_FEATURE_developer_build AND QT_FEATURE_openssl_linked
+ LIBRARIES
+ WrapOpenSSL::WrapOpenSSL
)
## Scopes:
#####################################################################
-qt_internal_extend_target(tst_qsslkey CONDITION QT_FEATURE_private_tests
- PUBLIC_LIBRARIES
+qt_internal_extend_target(tst_qsslkey CONDITION QT_FEATURE_developer_build
+ LIBRARIES
Qt::CorePrivate
Qt::NetworkPrivate
)
diff --git a/tests/auto/network/ssl/qsslkey/keys/genkeys.sh b/tests/auto/network/ssl/qsslkey/keys/genkeys.sh
index 0106953bff..afa4b7fe84 100755
--- a/tests/auto/network/ssl/qsslkey/keys/genkeys.sh
+++ b/tests/auto/network/ssl/qsslkey/keys/genkeys.sh
@@ -1,31 +1,6 @@
#!/bin/sh
-#############################################################################
-##
-## Copyright (C) 2016 The Qt Company Ltd.
-## Contact: https://www.qt.io/licensing/
-##
-## This file is the build configuration utility of the Qt Toolkit.
-##
-## $QT_BEGIN_LICENSE:GPL-EXCEPT$
-## Commercial License Usage
-## Licensees holding valid commercial Qt licenses may use this file in
-## accordance with the commercial license agreement provided with the
-## Software or, alternatively, in accordance with the terms contained in
-## a written agreement between you and The Qt Company. For licensing terms
-## and conditions see https://www.qt.io/terms-conditions. For further
-## information use the contact form at https://www.qt.io/contact-us.
-##
-## GNU General Public License Usage
-## Alternatively, this file may be used under the terms of the GNU
-## General Public License version 3 as published by the Free Software
-## Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-## included in the packaging of this file. Please review the following
-## information to ensure the GNU General Public License requirements will
-## be met: https://www.gnu.org/licenses/gpl-3.0.html.
-##
-## $QT_END_LICENSE$
-##
-#############################################################################
+# Copyright (C) 2016 The Qt Company Ltd.
+# SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0
# This script generates cryptographic keys of different types.
diff --git a/tests/auto/network/ssl/qsslkey/tst_qsslkey.cpp b/tests/auto/network/ssl/qsslkey/tst_qsslkey.cpp
index e57409c665..79bae3c270 100644
--- a/tests/auto/network/ssl/qsslkey/tst_qsslkey.cpp
+++ b/tests/auto/network/ssl/qsslkey/tst_qsslkey.cpp
@@ -1,30 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
#include <QTest>
#include <qsslkey.h>
@@ -40,6 +15,8 @@
#include <QtCore/qdebug.h>
#include <QtCore/qlist.h>
+using namespace Qt::StringLiterals;
+
#ifdef QT_BUILD_INTERNAL
#if QT_CONFIG(ssl)
#include "private/qsslkey_p.h"
@@ -115,6 +92,7 @@ private:
QString testDataDir;
bool fileContainsUnsupportedEllipticCurve(const QString &fileName) const;
+ bool algorithmsSupported(const QString &fileName) const;
QVector<QString> unsupportedCurves;
bool isOpenSsl = false;
@@ -178,6 +156,37 @@ bool tst_QSslKey::fileContainsUnsupportedEllipticCurve(const QString &fileName)
return false;
}
+bool tst_QSslKey::algorithmsSupported(const QString &fileName) const
+{
+#if QT_CONFIG(ssl)
+ if (isSchannel && fileName.contains("RC2-64")) // Schannel treats RC2 as 128 bit
+ return false;
+
+ if (isSchannel || isSecureTransport) {
+ // No AES support in the generic back-end, PKCS#12 algorithms not supported either.
+ return !(fileName.contains(QRegularExpression("-aes\\d\\d\\d-")) || fileName.contains("pkcs8-pkcs12"));
+ }
+
+ if (!isOpenSsl || QSslSocket::sslLibraryVersionNumber() >> 28 < 3)
+ return true;
+
+ // OpenSSL v3 first introduced the notion of 'providers'. Many algorithms
+ // were moved into the 'legacy' provider. While they are still supported in theory,
+ // the 'legacy' provider is NOT loaded by default and we are not loading it either.
+ // Thus, some of the keys we are using in tst_QSslKey would fail the test. We
+ // have to filter them out.
+ const auto name = fileName.toLower();
+ if (name.contains("-des."))
+ return false;
+
+ return !name.contains("-rc2-") && !name.contains("-rc4-");
+#else
+ Q_UNUSED(fileName);
+ return false;
+#endif // QT_CONFIG(ssl)
+}
+
+
void tst_QSslKey::initTestCase()
{
testDataDir = QFileInfo(QFINDTESTDATA("rsa-without-passphrase.pem")).absolutePath();
@@ -242,21 +251,12 @@ void tst_QSslKey::createPlainTestRows(bool pemOnly)
QTest::addColumn<QSsl::KeyType>("type");
QTest::addColumn<int>("length");
QTest::addColumn<QSsl::EncodingFormat>("format");
- foreach (KeyInfo keyInfo, keyInfoList) {
+ for (const KeyInfo &keyInfo : std::as_const(keyInfoList)) {
if (pemOnly && keyInfo.format != QSsl::EncodingFormat::Pem)
continue;
- if (isSchannel) {
- if (keyInfo.fileInfo.fileName().contains("RC2-64"))
- continue; // Schannel treats RC2 as 128 bit
- }
-
- if (isSchannel || isSecureTransport) {
- if (keyInfo.fileInfo.fileName().contains(QRegularExpression("-aes\\d\\d\\d-")))
- continue; // No AES support in the generic back-end
- if (keyInfo.fileInfo.fileName().contains("pkcs8-pkcs12"))
- continue; // The generic back-end doesn't support PKCS#12 algorithms
- }
+ if (!algorithmsSupported(keyInfo.fileInfo.fileName()))
+ continue;
QTest::newRow(keyInfo.fileInfo.fileName().toLatin1())
<< keyInfo.fileInfo.absoluteFilePath() << keyInfo.algorithm << keyInfo.type
@@ -317,7 +317,7 @@ void tst_QSslKey::constructorHandle()
passphrase = "1234";
BIO* bio = q_BIO_new(q_BIO_s_mem());
- q_BIO_write(bio, pem.constData(), pem.length());
+ q_BIO_write(bio, pem.constData(), pem.size());
EVP_PKEY *origin = func(bio, nullptr, nullptr, static_cast<void *>(passphrase.data()));
Q_ASSERT(origin);
q_EVP_PKEY_up_ref(origin);
@@ -469,13 +469,18 @@ void tst_QSslKey::toEncryptedPemOrDer_data()
QTest::addColumn<QSsl::EncodingFormat>("format");
QTest::addColumn<QString>("password");
- QStringList passwords;
- passwords << " " << "foobar" << "foo bar"
- << "aAzZ`1234567890-=~!@#$%^&*()_+[]{}\\|;:'\",.<>/?"; // ### add more (?)
- foreach (KeyInfo keyInfo, keyInfoList) {
+ const QString passwords[] = {
+ u" "_s,
+ u"foobar"_s,
+ u"foo bar"_s,
+ u"aAzZ`1234567890-=~!@#$%^&*()_+[]{}\\|;:'\",.<>/?"_s,
+ // ### add more (?)
+ };
+
+ for (const KeyInfo &keyInfo : std::as_const(keyInfoList)) {
if (keyInfo.fileInfo.fileName().contains("pkcs8"))
continue; // pkcs8 keys are encrypted in a different way than the other keys
- foreach (QString password, passwords) {
+ for (const QString &password : passwords) {
const QByteArray testName = keyInfo.fileInfo.fileName().toLatin1()
+ '-' + (keyInfo.algorithm == QSsl::Rsa ? "RSA" :
(keyInfo.algorithm == QSsl::Dsa ? "DSA" : "EC"))
@@ -550,9 +555,15 @@ void tst_QSslKey::passphraseChecks_data()
const QByteArray pass("123");
const QByteArray aesPass("1234");
- QTest::newRow("DES") << QString(testDataDir + "rsa-with-passphrase-des.pem") << pass;
+ if (!isOpenSsl || QSslSocket::sslLibraryVersionNumber() >> 28 < 3) {
+ // DES and RC2 are not provided by default in OpenSSL v3.
+ // This part is for either non-OpenSSL build, or OpenSSL v < 3.x.
+ QTest::newRow("DES") << QString(testDataDir + "rsa-with-passphrase-des.pem") << pass;
+ QTest::newRow("RC2") << QString(testDataDir + "rsa-with-passphrase-rc2.pem") << pass;
+ }
+
QTest::newRow("3DES") << QString(testDataDir + "rsa-with-passphrase-3des.pem") << pass;
- QTest::newRow("RC2") << QString(testDataDir + "rsa-with-passphrase-rc2.pem") << pass;
+
#if defined(QT_NO_OPENSSL) || !defined(OPENSSL_NO_AES)
QTest::newRow("AES128") << QString(testDataDir + "rsa-with-passphrase-aes128.pem") << aesPass;
QTest::newRow("AES192") << QString(testDataDir + "rsa-with-passphrase-aes192.pem") << aesPass;
@@ -569,7 +580,7 @@ void tst_QSslKey::passphraseChecks()
QVERIFY(keyFile.exists());
{
if (!keyFile.isOpen())
- keyFile.open(QIODevice::ReadOnly);
+ QVERIFY(keyFile.open(QIODevice::ReadOnly));
else
keyFile.reset();
QSslKey key(&keyFile,QSsl::Rsa,QSsl::Pem, QSsl::PrivateKey);
@@ -577,7 +588,7 @@ void tst_QSslKey::passphraseChecks()
}
{
if (!keyFile.isOpen())
- keyFile.open(QIODevice::ReadOnly);
+ QVERIFY(keyFile.open(QIODevice::ReadOnly));
else
keyFile.reset();
QSslKey key(&keyFile,QSsl::Rsa,QSsl::Pem, QSsl::PrivateKey, "");
@@ -585,7 +596,7 @@ void tst_QSslKey::passphraseChecks()
}
{
if (!keyFile.isOpen())
- keyFile.open(QIODevice::ReadOnly);
+ QVERIFY(keyFile.open(QIODevice::ReadOnly));
else
keyFile.reset();
QSslKey key(&keyFile,QSsl::Rsa,QSsl::Pem, QSsl::PrivateKey, "WRONG!");
@@ -593,7 +604,7 @@ void tst_QSslKey::passphraseChecks()
}
{
if (!keyFile.isOpen())
- keyFile.open(QIODevice::ReadOnly);
+ QVERIFY(keyFile.open(QIODevice::ReadOnly));
else
keyFile.reset();
QSslKey key(&keyFile,QSsl::Rsa,QSsl::Pem, QSsl::PrivateKey, passphrase);
@@ -611,7 +622,7 @@ void tst_QSslKey::noPassphraseChecks()
QFile keyFile(fileName);
{
if (!keyFile.isOpen())
- keyFile.open(QIODevice::ReadOnly);
+ QVERIFY(keyFile.open(QIODevice::ReadOnly));
else
keyFile.reset();
QSslKey key(&keyFile,QSsl::Rsa,QSsl::Pem, QSsl::PrivateKey);
@@ -619,7 +630,7 @@ void tst_QSslKey::noPassphraseChecks()
}
{
if (!keyFile.isOpen())
- keyFile.open(QIODevice::ReadOnly);
+ QVERIFY(keyFile.open(QIODevice::ReadOnly));
else
keyFile.reset();
QSslKey key(&keyFile,QSsl::Rsa,QSsl::Pem, QSsl::PrivateKey, "");
@@ -627,7 +638,7 @@ void tst_QSslKey::noPassphraseChecks()
}
{
if (!keyFile.isOpen())
- keyFile.open(QIODevice::ReadOnly);
+ QVERIFY(keyFile.open(QIODevice::ReadOnly));
else
keyFile.reset();
QSslKey key(&keyFile,QSsl::Rsa,QSsl::Pem, QSsl::PrivateKey, "xxx");
@@ -649,6 +660,9 @@ void tst_QSslKey::encrypt_data()
QTest::addColumn<QByteArray>("iv");
QByteArray iv("abcdefgh");
+#if OPENSSL_VERSION_MAJOR < 3
+ // Either non-OpenSSL build, or OpenSSL v < 3
+ // (with DES and other legacy algorithms available by default)
QTest::newRow("DES-CBC, length 0")
<< Cipher::DesCbc << QByteArray("01234567")
<< QByteArray()
@@ -738,6 +752,7 @@ void tst_QSslKey::encrypt_data()
<< QByteArray(8, 'a')
<< QByteArray::fromHex("5AEC1A5B295660B02613454232F7DECE")
<< iv;
+#endif // OPENSSL_VERSION_MAJOR
#if defined(QT_NO_OPENSSL) || !defined(OPENSSL_NO_AES)
// AES needs a longer IV
diff --git a/tests/auto/network/ssl/qsslserver/CMakeLists.txt b/tests/auto/network/ssl/qsslserver/CMakeLists.txt
new file mode 100644
index 0000000000..5957b2720e
--- /dev/null
+++ b/tests/auto/network/ssl/qsslserver/CMakeLists.txt
@@ -0,0 +1,29 @@
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
+
+if(NOT QT_BUILD_STANDALONE_TESTS AND NOT QT_BUILDING_QT)
+ cmake_minimum_required(VERSION 3.16)
+ project(tst_qsslserver LANGUAGES CXX)
+ find_package(Qt6BuildInternals REQUIRED COMPONENTS STANDALONE_TEST)
+endif()
+
+if(NOT QT_FEATURE_private_tests)
+ return()
+endif()
+
+#####################################################################
+## tst_qsslserver Test:
+#####################################################################
+
+# Collect test data
+list(APPEND test_data "certs")
+
+qt_internal_add_test(tst_qsslserver
+ SOURCES
+ tst_qsslserver.cpp
+ LIBRARIES
+ Qt::CorePrivate
+ Qt::NetworkPrivate
+ TESTDATA ${test_data}
+ BUNDLE_ANDROID_OPENSSL_LIBS
+)
diff --git a/tests/auto/network/ssl/qsslserver/certs/selfsigned-client.crt b/tests/auto/network/ssl/qsslserver/certs/selfsigned-client.crt
new file mode 100644
index 0000000000..88da2db920
--- /dev/null
+++ b/tests/auto/network/ssl/qsslserver/certs/selfsigned-client.crt
@@ -0,0 +1,18 @@
+-----BEGIN CERTIFICATE-----
+MIIC6TCCAdECCC/r9KvmbWTKMA0GCSqGSIb3DQEBCwUAMDUxFDASBgNVBAMMC0F1
+c3dlaXNBcHAyMR0wGwYDVQQFExQxODIzNTE0MTY0NzI5NDg5NDM3MTAiGA8xOTcw
+MDEwMTAwMDAwMFoYDzk5OTkxMjMxMjM1OTU5WjA1MRQwEgYDVQQDDAtBdXN3ZWlz
+QXBwMjEdMBsGA1UEBRMUMTgyMzUxNDE2NDcyOTQ4OTQzNzEwggEiMA0GCSqGSIb3
+DQEBAQUAA4IBDwAwggEKAoIBAQCahBpcZyr+PJBCpolzQeFVvDKABwlpdRKGZ8qq
+jD4sq2L7VlBJslgJGv5vsB5oJbnX1FFEu4Uw2kYb/LhnFCEXEFtGKRpWOEZOOqWb
+4l4q2MCa82ZCoIDt8yoAt0sSShbtR6pjW+l0lwAOEpfGvMaMVo5JUyspRxhl1dSu
+sS2Wf65zliqF5VSM2r4xMfJ6LVytxDZsGfTe/HFT2OYYrF+UQZg0mNL39rYWOK4R
+xoOz8eLl3K5hKuHNfn5zPt5QtMhaIvebijBg23xJpl+BeoS37WzaK1f+NyWZKPFb
+rttvSnFxpkyRHqJJ5piNGH6pkQ1+zhd7uh7eOIwxktjYBOFzAgMBAAEwDQYJKoZI
+hvcNAQELBQADggEBADw3MYPft+X78OK/2HAltzsKjfxv/D5qVizm9hcyG1GYe5pS
+qgFn0trCyJopYdbRr+hP7CuHwMmv62CZiHSog3CBPoUh19JENUDGbHXxTEFleB0i
+Fd8I2+WvRjbQ+ehaeTJPx88v5kkJnB2tZUNZuhEws8emCwr1G0TQv1tRYCR1Lp9i
+8/I3FSFpL1zyk47WfM/THa279MPw9WtrFGA6oi36gH9mYxek7n/zQTVi54xDx9GT
+KigBYqavjFdNXryjLTCCtJpMTDePgP66NAUnxn0D/amI2vSbIN++PSTsBm+n4Ti5
+QW/ShFQDNb4bDiwjtTKCeKwvAp2/6GSHVkYy28M=
+-----END CERTIFICATE-----
diff --git a/tests/auto/network/ssl/qsslserver/certs/selfsigned-client.key b/tests/auto/network/ssl/qsslserver/certs/selfsigned-client.key
new file mode 100644
index 0000000000..9e59342963
--- /dev/null
+++ b/tests/auto/network/ssl/qsslserver/certs/selfsigned-client.key
@@ -0,0 +1,27 @@
+-----BEGIN RSA PRIVATE KEY-----
+MIIEogIBAAKCAQEAmoQaXGcq/jyQQqaJc0HhVbwygAcJaXUShmfKqow+LKti+1ZQ
+SbJYCRr+b7AeaCW519RRRLuFMNpGG/y4ZxQhFxBbRikaVjhGTjqlm+JeKtjAmvNm
+QqCA7fMqALdLEkoW7UeqY1vpdJcADhKXxrzGjFaOSVMrKUcYZdXUrrEtln+uc5Yq
+heVUjNq+MTHyei1crcQ2bBn03vxxU9jmGKxflEGYNJjS9/a2FjiuEcaDs/Hi5dyu
+YSrhzX5+cz7eULTIWiL3m4owYNt8SaZfgXqEt+1s2itX/jclmSjxW67bb0pxcaZM
+kR6iSeaYjRh+qZENfs4Xe7oe3jiMMZLY2AThcwIDAQABAoIBAFjgvc0C5t8AdTZx
+VsS+U2Aedang4lAPsE0xbIj3TFgjaTcLKfmKJUtvhIU39/WOJbz4+pofhvhXxVYZ
+4vQfxvzeQrIzuFt52S7sWxA0gFgC/57hfKO8cQzt/u4UgJEPnupze5XVa47NwJFX
+rof5U/erXgLdXQlMRMNm4QRvE7rp58E2MkSYNur0Xgy9L7cRcUQJ8iuMaxBpOzhS
+fbNFi5zT7RCGcQSIDcb1JFlgs5tMUs6jzLoDSVD2+vvsN4i4LAAPkJSGTGed5vY1
+xn4G8KPR4HHrnBYEb0SGu4ZTznOnQ+JSKhQrbnvEzXM4RTfjqn0YvF8x70+pWSMi
+Fb4mlBECgYEAzW82O79HAlMm8LD7J4byPfVc/1M5/JOnE9H+RR5Vt4jZQGyjCmJu
+cj4UeZyVim0xg30sSYrJ2Urd27CtHp+sMgHkvJt3/ZgcfMZJbMKNGq/OUtV8s/cA
+nkU++/LgeW8r7wpaDjT7bfnOdcf16mYoXrmk0rTJvRqGXCBvCxtt5bsCgYEAwIxu
+vZjPV4Vu/VX6sH2d31D9EFZuZKjGhqukFVtRqLbeosqT9mA+LhQ/wP5qoR2gLQbe
+EwxJLJwGFjUhyhbHNlo6oHv3fWkzmHIMPwDRRI3Ktwi/50SwNSnyERUQcLaiwqKx
+BqaxPYNnspUt0nKE0LFZsSlrfEyxajqAlUEgm6kCgYAV+uQumFScpxDvh8AXhpS8
+lFgS6XC22YVy1XEDLC+3p2i3P+hh4A45IvNF378QRIabrvTiGXtnSF9cdhbPw/3E
+i/dRRsEb3P6PSxfoDxjR1iWZL0Zcav0h8f6/LkleNMralJz2EC0moye36mEhZzTC
+jdJYyQccuI3PpZi7839aqQKBgGezOnEiO4kHdB88jyc+gCglliWWZx4PR9x/1H8s
+D26uDnneYJHwg4yNm0h1vTfInNujNzdLBp3f6edL9kbAvcmoDqsgGMqSPhd8VNwZ
+tJsXQnYRYElN1RjM3nIUxiXuNvpcZLsQS6S1gMPNVEBjLOS4n3WquRjYtTRhDZ9U
+1BsBAoGAUFrIatOLFhcgaqENHyUbMx5uSx0lIfF6Xd5KIAgi+btdmugHe+NK8Cd2
+Rc2bQLQ9K1SvKFX6nFuEsGxnXkKuyhL/j0Kgm8nZin4uAcrtFnNdFumvCL6YgYSc
+IvvM+uVfGEdbqm4pTuiLBfzOXIIy3kVlLGo402QG1pBzOtmsRMs=
+-----END RSA PRIVATE KEY-----
diff --git a/tests/auto/network/ssl/qsslserver/certs/selfsigned-server.crt b/tests/auto/network/ssl/qsslserver/certs/selfsigned-server.crt
new file mode 100644
index 0000000000..c97d27721c
--- /dev/null
+++ b/tests/auto/network/ssl/qsslserver/certs/selfsigned-server.crt
@@ -0,0 +1,18 @@
+-----BEGIN CERTIFICATE-----
+MIIC5TCCAc0CCAO22gNi0v20MA0GCSqGSIb3DQEBCwUAMDMxFDASBgNVBAMMC0F1
+c3dlaXNBcHAyMRswGQYDVQQFExIyNTIxMTE1NjY3NjM2MjExODgwIhgPMTk3MDAx
+MDEwMDAwMDBaGA85OTk5MTIzMTIzNTk1OVowMzEUMBIGA1UEAwwLQXVzd2Vpc0Fw
+cDIxGzAZBgNVBAUTEjI1MjExMTU2Njc2MzYyMTE4ODCCASIwDQYJKoZIhvcNAQEB
+BQADggEPADCCAQoCggEBAL+Fl6v5dcU7qk7vbINclWOhvCe/uklKnXV2QU382x7g
+qpbYxJiJvz24C6tgDMmE0pwEz6PiCbh1dkc8+9cdp37eBcFLCOXYQb27gqVVyVtu
+xO0LLVXPCv48bGSwljOz0FRC3FolzWxzrZogM/i2b/lmehHJ3D4ejmINmIgtFJ9P
+JNNCH4Oh5YEbaFFlNf2m7lCoSuQkOlLZcGeLoipK2XvhZJff6c1uxValh/Mx5dNB
+5Mgd5cOZSSEhwf7mcE8C3SHVfjeNfZGIqlkwdY8lvAOjirAtj6Yl88sJOUID/Q/N
+hU9D8IZy6+Bk2cJQwI/Gzr590VYvlSTI+6lXr//oBBECAwEAATANBgkqhkiG9w0B
+AQsFAAOCAQEArSMO88AYT+9tPCl5lXtSRa0OycqKNlW58GujxIDuR8WX1eFmGSHQ
+uijo5KPYUnqydZzAewGC8NvC9WcLwFltNZ9igXikUHiAHc1JLfW7+7SgKpwOUb02
+rJkUkpPA/SmwkLSKYiR1prt5wgSulU1HPBESep05DfR8MCU5+KHkLyXDqtrbudJ4
+lQd9dSKJFn+cSjUC5JNxCPHoIISe7hfGFMLkd0/tVfSIXLVOAZG4K6zExUdjyPi8
+qEuPq6QCRyIJbYQc5HfnARgwK6GXHqkyLWlqK946Yz8VOba7Nan5uQ6xCjUMHw8Z
+z/673o/3DCaQ9N6dWahNQ09a9ZH8U1X4iA==
+-----END CERTIFICATE-----
diff --git a/tests/auto/network/ssl/qsslserver/certs/selfsigned-server.key b/tests/auto/network/ssl/qsslserver/certs/selfsigned-server.key
new file mode 100644
index 0000000000..b7be118cb9
--- /dev/null
+++ b/tests/auto/network/ssl/qsslserver/certs/selfsigned-server.key
@@ -0,0 +1,27 @@
+-----BEGIN RSA PRIVATE KEY-----
+MIIEpAIBAAKCAQEAv4WXq/l1xTuqTu9sg1yVY6G8J7+6SUqddXZBTfzbHuCqltjE
+mIm/PbgLq2AMyYTSnATPo+IJuHV2Rzz71x2nft4FwUsI5dhBvbuCpVXJW27E7Qst
+Vc8K/jxsZLCWM7PQVELcWiXNbHOtmiAz+LZv+WZ6EcncPh6OYg2YiC0Un08k00If
+g6HlgRtoUWU1/abuUKhK5CQ6UtlwZ4uiKkrZe+Fkl9/pzW7FVqWH8zHl00HkyB3l
+w5lJISHB/uZwTwLdIdV+N419kYiqWTB1jyW8A6OKsC2PpiXzywk5QgP9D82FT0Pw
+hnLr4GTZwlDAj8bOvn3RVi+VJMj7qVev/+gEEQIDAQABAoIBADdoXsjSEtBMwqiz
+e6FFV7LLR7P4M9ygSY2B+MKnNH1qYe/iJn4626jvZfDeiNSEKKoaejffXRCQaveR
+HQrO+XYqpV+WZayZM+vAI7vRZb+d/DrX0PXSQEvtDy7SJ6Itk0fNUBKEfTmy/bZp
+Op/pp9tvWkFrNNyD2o1jgY1j/WNY8g605m0oURJ9WQsMUu/Kzu+NMoaKTIoQGb3d
+dP71F4KaTXHYxj3B0c+y0NedKbrvnBsP6XbEpgJBaXjtD9z+z/aMF6dmuvpkx7uY
+qzwPMRw05QPyJ9x+1V/v4TytY5f596NgW2niVj77BunkZasTYIEX7bjByrlTeLdx
+xvPRpAECgYEA5KkM/ORbhN1oaw9+tQxA48oG2DFqChBr+vc4NU4j5SNFn9ks5nHI
+xdJNZ9k+bjVUkBP4m88Wd07SW9zXCL8Q5lczb+p5SWl/Pp7ltqaxpH17uzamsaIv
+KIBkeJTOU5TuWdXiV5FY+ofK9ojyEaqX1tmylWnoVe4bIMRWXE5bMSkCgYEA1mvJ
+snkNzPFG0RK7ikjsNxrhzE07+7RSnoM9WeW8y2lvQ9MjdR6eOgqnnlcdk2A7OVbf
+culNgLc0qx/PxZ4BV+8yLLb1EBBGvuVG+x4a6H2mLHdFCJekByZHaQNs9ogVLvdv
+3z8D59KknBUjtj9dCw90Z41yMM4kpWMG9yfSEKkCgYEAvuCvytwF2d/JrrV8nD3i
+XUTkecymLEiRGysMbNMR+9F56XotlSEe7KQloa8kAnPaZ3uEaOxyYJ4X1D+B8fct
+cFsSwTYGkVXTtr6GG/cDC8EEbL+uX1J382Nae54croEAh1WYYGkg0eJRd4PSLxUt
+M1j/TuLd4/2j/7JmNR/j2CECgYBdB3MBHghgzKXe+/OmMbFazyz8SN4nfLsDzwkF
+QenBj0MY+DhADkK0B/9lcYKBeJT5cbmMz7AykkolnK22nbETh9ILGG4GxCkNlchQ
+F2WxTSKV1EF9Ut11xKPi6fuSksQuFmjRQTPelsOYfIt7/M3PiKsGapYKmsXHg8l3
+3i0D0QKBgQCi+HNOaYqduxwjrj8h4eUbiwjID8DCNJ+jXsuGVa6jcsfFpdpivx2c
+ytYSXuTXLRq0I3c1ChUOGQQeztJ5GtCPnXjLHHMf3f6yr7Pk56AUmUsaIlR1Q2Zo
+gqpFD8zYD5UFc2KM7Y38YTh4j82uDzDvHBBFpli7dEmSn2WpcmzFag==
+-----END RSA PRIVATE KEY-----
diff --git a/tests/auto/network/ssl/qsslserver/tst_qsslserver.cpp b/tests/auto/network/ssl/qsslserver/tst_qsslserver.cpp
new file mode 100644
index 0000000000..26d3a50a5b
--- /dev/null
+++ b/tests/auto/network/ssl/qsslserver/tst_qsslserver.cpp
@@ -0,0 +1,531 @@
+// Copyright (C) 2022 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
+
+#include <QTest>
+#include <QDebug>
+#include <QSignalSpy>
+#include <QTimer>
+
+#include <QtNetwork/QSslServer>
+#include <QtNetwork/QSslKey>
+#include "private/qtlsbackend_p.h"
+
+class tst_QSslServer : public QObject
+{
+ Q_OBJECT
+
+private slots:
+ void initTestCase();
+ void testOneSuccessfulConnection();
+ void testSelfSignedCertificateRejectedByServer();
+ void testSelfSignedCertificateRejectedByClient();
+#if QT_CONFIG(openssl)
+ void testHandshakeInterruptedOnError();
+ void testPreSharedKeyAuthenticationRequired();
+#endif
+ void plaintextClient();
+ void quietClient();
+ void twoGoodAndManyBadClients();
+
+private:
+ QString testDataDir;
+ bool isTestingOpenSsl = false;
+ QSslConfiguration selfSignedClientQSslConfiguration();
+ QSslConfiguration selfSignedServerQSslConfiguration();
+ QSslConfiguration createQSslConfiguration(QString keyFileName, QString certificateFileName);
+};
+
+class SslServerSpy : public QObject
+{
+ Q_OBJECT
+
+public:
+ SslServerSpy(QSslConfiguration &configuration);
+
+ QSslServer server;
+ QSignalSpy sslErrorsSpy;
+ QSignalSpy peerVerifyErrorSpy;
+ QSignalSpy errorOccurredSpy;
+ QSignalSpy pendingConnectionAvailableSpy;
+ QSignalSpy preSharedKeyAuthenticationRequiredSpy;
+ QSignalSpy alertSentSpy;
+ QSignalSpy alertReceivedSpy;
+ QSignalSpy handshakeInterruptedOnErrorSpy;
+ QSignalSpy startedEncryptionHandshakeSpy;
+};
+
+SslServerSpy::SslServerSpy(QSslConfiguration &configuration)
+ : server(),
+ sslErrorsSpy(&server, &QSslServer::sslErrors),
+ peerVerifyErrorSpy(&server, &QSslServer::peerVerifyError),
+ errorOccurredSpy(&server, &QSslServer::errorOccurred),
+ pendingConnectionAvailableSpy(&server, &QSslServer::pendingConnectionAvailable),
+ preSharedKeyAuthenticationRequiredSpy(&server,
+ &QSslServer::preSharedKeyAuthenticationRequired),
+ alertSentSpy(&server, &QSslServer::alertSent),
+ alertReceivedSpy(&server, &QSslServer::alertReceived),
+ handshakeInterruptedOnErrorSpy(&server, &QSslServer::handshakeInterruptedOnError),
+ startedEncryptionHandshakeSpy(&server, &QSslServer::startedEncryptionHandshake)
+{
+ server.setSslConfiguration(configuration);
+}
+
+void tst_QSslServer::initTestCase()
+{
+ testDataDir = QFileInfo(QFINDTESTDATA("certs")).absolutePath();
+ if (testDataDir.isEmpty())
+ testDataDir = QCoreApplication::applicationDirPath();
+ if (!testDataDir.endsWith(QLatin1String("/")))
+ testDataDir += QLatin1String("/");
+
+ const QString openSslBackend = QTlsBackend::builtinBackendNames[QTlsBackend::nameIndexOpenSSL];
+ const auto &tlsBackends = QSslSocket::availableBackends();
+ if (tlsBackends.contains(openSslBackend)) {
+ isTestingOpenSsl = true;
+ }
+}
+
+QSslConfiguration tst_QSslServer::selfSignedClientQSslConfiguration()
+{
+ return createQSslConfiguration(testDataDir + "certs/selfsigned-client.key",
+ testDataDir + "certs/selfsigned-client.crt");
+}
+
+QSslConfiguration tst_QSslServer::selfSignedServerQSslConfiguration()
+{
+ return createQSslConfiguration(testDataDir + "certs/selfsigned-server.key",
+ testDataDir + "certs/selfsigned-server.crt");
+}
+
+QSslConfiguration tst_QSslServer::createQSslConfiguration(QString keyFileName,
+ QString certificateFileName)
+{
+ QSslConfiguration configuration(QSslConfiguration::defaultConfiguration());
+
+ QFile keyFile(keyFileName);
+ if (keyFile.open(QIODevice::ReadOnly)) {
+ QSslKey key(keyFile.readAll(), QSsl::Rsa, QSsl::Pem, QSsl::PrivateKey);
+ if (!key.isNull()) {
+ configuration.setPrivateKey(key);
+ } else {
+ qCritical() << "Could not parse key: " << keyFileName;
+ }
+ } else {
+ qCritical() << "Could not find key: " << keyFileName;
+ }
+
+ QList<QSslCertificate> localCert = QSslCertificate::fromPath(certificateFileName);
+ if (!localCert.isEmpty() && !localCert.first().isNull()) {
+ configuration.setLocalCertificate(localCert.first());
+ } else {
+ qCritical() << "Could not find certificate: " << certificateFileName;
+ }
+ return configuration;
+}
+
+void tst_QSslServer::testOneSuccessfulConnection()
+{
+ // Setup server
+ QSslConfiguration serverConfiguration = selfSignedServerQSslConfiguration();
+ SslServerSpy server(serverConfiguration);
+ QVERIFY(server.server.listen());
+
+ // Check that all signal spys are valid
+ QVERIFY(server.sslErrorsSpy.isValid());
+ QVERIFY(server.peerVerifyErrorSpy.isValid());
+ QVERIFY(server.errorOccurredSpy.isValid());
+ QVERIFY(server.pendingConnectionAvailableSpy.isValid());
+ QVERIFY(server.preSharedKeyAuthenticationRequiredSpy.isValid());
+ QVERIFY(server.alertSentSpy.isValid());
+ QVERIFY(server.alertReceivedSpy.isValid());
+ QVERIFY(server.handshakeInterruptedOnErrorSpy.isValid());
+ QVERIFY(server.startedEncryptionHandshakeSpy.isValid());
+
+ // Check that no connections has occurred
+ QCOMPARE(server.sslErrorsSpy.size(), 0);
+ QCOMPARE(server.peerVerifyErrorSpy.size(), 0);
+ QCOMPARE(server.errorOccurredSpy.size(), 0);
+ QCOMPARE(server.pendingConnectionAvailableSpy.size(), 0);
+ QCOMPARE(server.preSharedKeyAuthenticationRequiredSpy.size(), 0);
+ QCOMPARE(server.alertSentSpy.size(), 0);
+ QCOMPARE(server.alertReceivedSpy.size(), 0);
+ QCOMPARE(server.handshakeInterruptedOnErrorSpy.size(), 0);
+ QCOMPARE(server.startedEncryptionHandshakeSpy.size(), 0);
+
+ // Connect client
+ QSslSocket client;
+ QSslConfiguration clientConfiguration = QSslConfiguration::defaultConfiguration();
+ client.setSslConfiguration(clientConfiguration);
+ client.connectToHostEncrypted(QHostAddress(QHostAddress::LocalHost).toString(),
+ server.server.serverPort());
+
+ // Type of certificate error to expect
+ const auto certificateError =
+ isTestingOpenSsl ? QSslError::SelfSignedCertificate : QSslError::CertificateUntrusted;
+ // Expected errors
+ connect(&client, &QSslSocket::sslErrors,
+ [&certificateError, &client](const QList<QSslError> &errors) {
+ QCOMPARE(errors.size(), 2);
+ for (auto error : errors) {
+ QVERIFY(error.error() == certificateError
+ || error.error() == QSslError::HostNameMismatch);
+ }
+ client.ignoreSslErrors();
+ });
+
+ QEventLoop loop;
+ int waitFor = 2;
+ connect(&client, &QSslSocket::encrypted, [&loop, &waitFor]() {
+ if (!--waitFor)
+ loop.quit();
+ });
+ connect(&server.server, &QTcpServer::pendingConnectionAvailable, [&loop, &waitFor]() {
+ if (!--waitFor)
+ loop.quit();
+ });
+ QTimer::singleShot(5000, &loop, SLOT(quit()));
+ loop.exec();
+
+ // Check that one encrypted connection has occurred without error
+ QCOMPARE(server.sslErrorsSpy.size(), 0);
+ QCOMPARE(server.peerVerifyErrorSpy.size(), 0);
+ QCOMPARE(server.errorOccurredSpy.size(), 0);
+ QCOMPARE(server.pendingConnectionAvailableSpy.size(), 1);
+ QCOMPARE(server.preSharedKeyAuthenticationRequiredSpy.size(), 0);
+ QCOMPARE(server.alertSentSpy.size(), 0);
+ QCOMPARE(server.alertReceivedSpy.size(), 0);
+ QCOMPARE(server.handshakeInterruptedOnErrorSpy.size(), 0);
+ QCOMPARE(server.startedEncryptionHandshakeSpy.size(), 1);
+
+ // Check client socket
+ QVERIFY(client.isEncrypted());
+ QCOMPARE(client.state(), QAbstractSocket::ConnectedState);
+}
+
+void tst_QSslServer::testSelfSignedCertificateRejectedByServer()
+{
+ // Set up server that verifies client
+ QSslConfiguration serverConfiguration = selfSignedServerQSslConfiguration();
+ serverConfiguration.setPeerVerifyMode(QSslSocket::VerifyPeer);
+ SslServerSpy server(serverConfiguration);
+ QVERIFY(server.server.listen());
+
+ // Connect client
+ QSslSocket client;
+ QSslConfiguration clientConfiguration = selfSignedClientQSslConfiguration();
+ clientConfiguration.setPeerVerifyMode(QSslSocket::VerifyNone);
+ client.setSslConfiguration(clientConfiguration);
+ client.connectToHostEncrypted(QHostAddress(QHostAddress::LocalHost).toString(),
+ server.server.serverPort());
+
+ QEventLoop loop;
+ QObject::connect(&client, SIGNAL(disconnected()), &loop, SLOT(quit()));
+ QTimer::singleShot(5000, &loop, SLOT(quit()));
+ loop.exec();
+
+ // Check that one encrypted connection has failed
+ QCOMPARE(server.sslErrorsSpy.size(), 1);
+ QCOMPARE(server.peerVerifyErrorSpy.size(), 1);
+ QCOMPARE(server.errorOccurredSpy.size(), 1);
+ QCOMPARE(server.pendingConnectionAvailableSpy.size(), 0);
+ QCOMPARE(server.preSharedKeyAuthenticationRequiredSpy.size(), 0);
+ QCOMPARE(server.alertSentSpy.size(),
+ isTestingOpenSsl ? 1 : 0); // OpenSSL only signal
+ QCOMPARE(server.alertReceivedSpy.size(), 0);
+ QCOMPARE(server.handshakeInterruptedOnErrorSpy.size(), 0);
+ QCOMPARE(server.startedEncryptionHandshakeSpy.size(), 1);
+
+ // Type of certificate error to expect
+ const auto certificateError =
+ isTestingOpenSsl ? QSslError::SelfSignedCertificate : QSslError::CertificateUntrusted;
+
+ // Check the sslErrorsSpy
+ const auto sslErrorsSpyErrors =
+ qvariant_cast<QList<QSslError>>(std::as_const(server.sslErrorsSpy).first()[1]);
+ QCOMPARE(sslErrorsSpyErrors.size(), 1);
+ QCOMPARE(sslErrorsSpyErrors.first().error(), certificateError);
+
+ // Check the peerVerifyErrorSpy
+ const auto peerVerifyErrorSpyError =
+ qvariant_cast<QSslError>(std::as_const(server.peerVerifyErrorSpy).first()[1]);
+ QCOMPARE(peerVerifyErrorSpyError.error(), certificateError);
+
+ // Check client socket
+ QVERIFY(!client.isEncrypted());
+ QCOMPARE(client.state(), QAbstractSocket::UnconnectedState);
+}
+
+void tst_QSslServer::testSelfSignedCertificateRejectedByClient()
+{
+ // Set up server without verification of client
+ QSslConfiguration serverConfiguration = selfSignedServerQSslConfiguration();
+ SslServerSpy server(serverConfiguration);
+ QVERIFY(server.server.listen());
+
+ // Connect client that authenticates server
+ QSslSocket client;
+ QSslConfiguration clientConfiguration = selfSignedClientQSslConfiguration();
+ if (isTestingOpenSsl) {
+ clientConfiguration.setHandshakeMustInterruptOnError(true);
+ QVERIFY(clientConfiguration.handshakeMustInterruptOnError());
+ }
+ client.setSslConfiguration(clientConfiguration);
+ QSignalSpy clientConnectedSpy(&client, SIGNAL(connected()));
+ QSignalSpy clientHostFoundSpy(&client, SIGNAL(hostFound()));
+ QSignalSpy clientDisconnectedSpy(&client, SIGNAL(disconnected()));
+ QSignalSpy clientConnectionEncryptedSpy(&client, SIGNAL(encrypted()));
+ QSignalSpy clientSslErrorsSpy(&client, SIGNAL(sslErrors(QList<QSslError>)));
+ QSignalSpy clientErrorOccurredSpy(&client, SIGNAL(errorOccurred(QAbstractSocket::SocketError)));
+ client.connectToHostEncrypted(QHostAddress(QHostAddress::LocalHost).toString(),
+ server.server.serverPort());
+ QEventLoop loop;
+ QTimer::singleShot(1000, &loop, SLOT(quit()));
+ loop.exec();
+
+ // Type of socket error to expect
+ const auto socketError = isTestingOpenSsl
+ ? QAbstractSocket::SocketError::SslHandshakeFailedError
+ : QAbstractSocket::SocketError::RemoteHostClosedError;
+
+ QTcpSocket *connection = server.server.nextPendingConnection();
+ if (connection == nullptr) {
+ // Client disconnected before connection accepted by server
+ QCOMPARE(server.sslErrorsSpy.size(), 0);
+ QCOMPARE(server.peerVerifyErrorSpy.size(), 0);
+ QCOMPARE(server.errorOccurredSpy.size(), 1); // Client rejected first
+ QCOMPARE(server.pendingConnectionAvailableSpy.size(), 0);
+ QCOMPARE(server.preSharedKeyAuthenticationRequiredSpy.size(), 0);
+ QCOMPARE(server.alertSentSpy.size(), 0);
+ QCOMPARE(server.alertReceivedSpy.size(),
+ isTestingOpenSsl ? 1 : 0); // OpenSSL only signal
+ QCOMPARE(server.handshakeInterruptedOnErrorSpy.size(), 0);
+ QCOMPARE(server.startedEncryptionHandshakeSpy.size(), 1);
+
+ const auto errrOccuredSpyError = qvariant_cast<QAbstractSocket::SocketError>(
+ std::as_const(server.errorOccurredSpy).first()[1]);
+ QCOMPARE(errrOccuredSpyError, socketError);
+ } else {
+ // Client disconnected after connection accepted by server
+ QCOMPARE(server.sslErrorsSpy.size(), 0);
+ QCOMPARE(server.peerVerifyErrorSpy.size(), 0);
+ QCOMPARE(server.errorOccurredSpy.size(), 0); // Server accepted first
+ QCOMPARE(server.pendingConnectionAvailableSpy.size(), 1);
+ QCOMPARE(server.preSharedKeyAuthenticationRequiredSpy.size(), 0);
+ QCOMPARE(server.alertSentSpy.size(), 0);
+ QCOMPARE(server.alertReceivedSpy.size(),
+ isTestingOpenSsl ? 1 : 0); // OpenSSL only signal
+ QCOMPARE(server.handshakeInterruptedOnErrorSpy.size(), 0);
+ QCOMPARE(server.startedEncryptionHandshakeSpy.size(), 1);
+
+ QCOMPARE(connection->state(), QAbstractSocket::UnconnectedState);
+ QCOMPARE(connection->error(), socketError);
+ auto sslConnection = qobject_cast<QSslSocket *>(connection);
+ QVERIFY(sslConnection);
+ QVERIFY(!sslConnection->isEncrypted());
+ }
+
+ // Check that client has rejected server
+ QCOMPARE(clientConnectedSpy.size(), 1);
+ QCOMPARE(clientHostFoundSpy.size(), 1);
+ QCOMPARE(clientDisconnectedSpy.size(), 1);
+ QCOMPARE(clientConnectionEncryptedSpy.size(), 0);
+ QCOMPARE(clientSslErrorsSpy.size(), isTestingOpenSsl ? 0 : 1);
+ QCOMPARE(clientErrorOccurredSpy.size(), 1);
+
+ // Check client socket
+ QVERIFY(!client.isEncrypted());
+ QCOMPARE(client.state(), QAbstractSocket::UnconnectedState);
+}
+
+#if QT_CONFIG(openssl)
+
+void tst_QSslServer::testHandshakeInterruptedOnError()
+{
+ if (!isTestingOpenSsl)
+ QSKIP("This test requires OpenSSL as the active TLS backend");
+
+ auto serverConfiguration = selfSignedServerQSslConfiguration();
+ serverConfiguration.setHandshakeMustInterruptOnError(true);
+ QVERIFY(serverConfiguration.handshakeMustInterruptOnError());
+ serverConfiguration.setPeerVerifyMode(QSslSocket::VerifyPeer);
+ SslServerSpy server(serverConfiguration);
+ server.server.listen();
+
+ QSslSocket client;
+ auto clientConfiguration = selfSignedClientQSslConfiguration();
+ clientConfiguration.setPeerVerifyMode(QSslSocket::VerifyNone);
+ client.setSslConfiguration(clientConfiguration);
+ client.connectToHostEncrypted(QHostAddress(QHostAddress::LocalHost).toString(),
+ server.server.serverPort());
+
+ QEventLoop loop;
+ QObject::connect(&client, SIGNAL(disconnected()), &loop, SLOT(quit()));
+ QTimer::singleShot(5000, &loop, SLOT(quit()));
+ loop.exec();
+
+ // Check that client certificate causes handshake interrupted signal to be emitted
+ QCOMPARE(server.sslErrorsSpy.size(), 0);
+ QCOMPARE(server.peerVerifyErrorSpy.size(), 0);
+ QCOMPARE(server.errorOccurredSpy.size(), 1);
+ QCOMPARE(server.pendingConnectionAvailableSpy.size(), 0);
+ QCOMPARE(server.preSharedKeyAuthenticationRequiredSpy.size(), 0);
+ QCOMPARE(server.alertSentSpy.size(), 1);
+ QCOMPARE(server.alertReceivedSpy.size(), 0);
+ QCOMPARE(server.handshakeInterruptedOnErrorSpy.size(), 1);
+ QCOMPARE(server.startedEncryptionHandshakeSpy.size(), 1);
+}
+
+void tst_QSslServer::testPreSharedKeyAuthenticationRequired()
+{
+ if (!isTestingOpenSsl)
+ QSKIP("This test requires OpenSSL as the active TLS backend");
+
+ auto serverConfiguration = QSslConfiguration::defaultConfiguration();
+ serverConfiguration.setPeerVerifyMode(QSslSocket::VerifyPeer);
+ serverConfiguration.setProtocol(QSsl::TlsV1_2);
+ serverConfiguration.setCiphers({ QSslCipher("PSK-AES256-CBC-SHA") });
+ serverConfiguration.setPreSharedKeyIdentityHint("Server Y");
+ SslServerSpy server(serverConfiguration);
+ connect(&server.server, &QSslServer::preSharedKeyAuthenticationRequired,
+ [](QSslSocket *, QSslPreSharedKeyAuthenticator *authenticator) {
+ QCOMPARE(authenticator->identity(), QByteArray("Client X"));
+ authenticator->setPreSharedKey("123456");
+ });
+ server.server.listen();
+
+ QSslSocket client;
+ auto clientConfiguration = QSslConfiguration::defaultConfiguration();
+ clientConfiguration.setPeerVerifyMode(QSslSocket::VerifyNone);
+ clientConfiguration.setProtocol(QSsl::TlsV1_2);
+ clientConfiguration.setCiphers({ QSslCipher("PSK-AES256-CBC-SHA") });
+ client.setSslConfiguration(clientConfiguration);
+ connect(&client, &QSslSocket::preSharedKeyAuthenticationRequired,
+ [](QSslPreSharedKeyAuthenticator *authenticator) {
+ QCOMPARE(authenticator->identityHint(), QByteArray("Server Y"));
+ authenticator->setPreSharedKey("123456");
+ authenticator->setIdentity("Client X");
+ });
+ client.connectToHostEncrypted(QHostAddress(QHostAddress::LocalHost).toString(),
+ server.server.serverPort());
+
+ connect(&server.server, &QSslServer::sslErrors,
+ [](QSslSocket *socket, const QList<QSslError> &errors) {
+ for (auto error : errors) {
+ QCOMPARE(error.error(), QSslError::NoPeerCertificate);
+ }
+ socket->ignoreSslErrors();
+ });
+
+ QEventLoop loop;
+ QObject::connect(&client, SIGNAL(encrypted()), &loop, SLOT(quit()));
+ QTimer::singleShot(5000, &loop, SLOT(quit()));
+ loop.exec();
+
+ // Check that server is connected
+ QCOMPARE(server.sslErrorsSpy.size(), 1);
+ QCOMPARE(server.peerVerifyErrorSpy.size(), 1);
+ QCOMPARE(server.errorOccurredSpy.size(), 0);
+ QCOMPARE(server.pendingConnectionAvailableSpy.size(), 1);
+ QCOMPARE(server.preSharedKeyAuthenticationRequiredSpy.size(), 1);
+ QCOMPARE(server.alertSentSpy.size(), 0);
+ QCOMPARE(server.alertReceivedSpy.size(), 0);
+ QCOMPARE(server.handshakeInterruptedOnErrorSpy.size(), 0);
+ QCOMPARE(server.startedEncryptionHandshakeSpy.size(), 1);
+
+ // Check client socket
+ QVERIFY(client.isEncrypted());
+ QCOMPARE(client.state(), QAbstractSocket::ConnectedState);
+}
+
+#endif
+
+void tst_QSslServer::plaintextClient()
+{
+ QSslConfiguration serverConfiguration = selfSignedServerQSslConfiguration();
+ SslServerSpy server(serverConfiguration);
+ QVERIFY(server.server.listen());
+
+ QTcpSocket socket;
+ QSignalSpy socketDisconnectedSpy(&socket, &QTcpSocket::disconnected);
+ socket.connectToHost(QHostAddress::LocalHost, server.server.serverPort());
+ QVERIFY(socket.waitForConnected());
+ QTest::qWait(100);
+ // No disconnect from short break...:
+ QCOMPARE(socket.state(), QAbstractSocket::SocketState::ConnectedState);
+
+ // ... but we write some plaintext data...:
+ socket.write("Hello World!");
+ socket.waitForBytesWritten();
+ // ... and quickly get disconnected:
+ QTRY_COMPARE_GT(socketDisconnectedSpy.size(), 0);
+ QCOMPARE(socket.state(), QAbstractSocket::SocketState::UnconnectedState);
+}
+
+void tst_QSslServer::quietClient()
+{
+ QSslConfiguration serverConfiguration = selfSignedServerQSslConfiguration();
+ SslServerSpy server(serverConfiguration);
+ server.server.setHandshakeTimeout(1'000);
+ QVERIFY(server.server.listen());
+
+ quint16 serverPeerPort = 0;
+ auto grabServerPeerPort = [&serverPeerPort](QSslSocket *socket) {
+ serverPeerPort = socket->peerPort();
+ };
+ QObject::connect(&server.server, &QSslServer::errorOccurred, &server.server,
+ grabServerPeerPort);
+
+ QTcpSocket socket;
+ QSignalSpy socketDisconnectedSpy(&socket, &QTcpSocket::disconnected);
+ socket.connectToHost(QHostAddress::LocalHost, server.server.serverPort());
+ quint16 clientLocalPort = socket.localPort();
+ QVERIFY(socket.waitForConnected());
+ // Disconnects after overlong break:
+ QVERIFY(socketDisconnectedSpy.wait(5'000));
+ QCOMPARE(socket.state(), QAbstractSocket::SocketState::UnconnectedState);
+
+ QCOMPARE_GT(server.errorOccurredSpy.size(), 0);
+ QCOMPARE(serverPeerPort, clientLocalPort);
+}
+
+void tst_QSslServer::twoGoodAndManyBadClients()
+{
+ QSslConfiguration serverConfiguration = selfSignedServerQSslConfiguration();
+ SslServerSpy server(serverConfiguration);
+ server.server.setHandshakeTimeout(750);
+ constexpr qsizetype ExpectedConnections = 5;
+ server.server.setMaxPendingConnections(ExpectedConnections);
+ QVERIFY(server.server.listen());
+
+ auto connectGoodClient = [&server](QSslSocket *socket) {
+ QObject::connect(socket, &QSslSocket::sslErrors, socket,
+ qOverload<const QList<QSslError> &>(&QSslSocket::ignoreSslErrors));
+ socket->connectToHostEncrypted("127.0.0.1", server.server.serverPort());
+ };
+ // Connect one socket encrypted so we have a socket in the regular queue
+ QSslSocket tlsSocket;
+ connectGoodClient(&tlsSocket);
+
+ // Then we connect a bunch of TCP sockets who will not send any data at all
+ std::array<QTcpSocket, size_t(ExpectedConnections) * 2> sockets;
+ for (QTcpSocket &socket : sockets)
+ socket.connectToHost(QHostAddress::LocalHost, server.server.serverPort());
+ QTest::qWait(500); // some leeway to let connections try to connect...
+
+ // I happen to know the sockets are all children of the server, so let's see
+ // how many are created:
+ qsizetype connectedCount = server.server.findChildren<QSslSocket *>().size();
+ QCOMPARE(connectedCount, ExpectedConnections);
+ // 1 socket is ready and pending
+ QCOMPARE(server.pendingConnectionAvailableSpy.size(), 1);
+
+ // Connect another client to make sure that the server is accepting connections again even after
+ // all the bad actors tried to connect:
+ QSslSocket goodClient;
+ connectGoodClient(&goodClient);
+ QTRY_COMPARE(server.pendingConnectionAvailableSpy.size(), 2);
+}
+
+QTEST_MAIN(tst_QSslServer)
+
+#include "tst_qsslserver.moc"
diff --git a/tests/auto/network/ssl/qsslsocket/BLACKLIST b/tests/auto/network/ssl/qsslsocket/BLACKLIST
index 749c59d968..b990516676 100644
--- a/tests/auto/network/ssl/qsslsocket/BLACKLIST
+++ b/tests/auto/network/ssl/qsslsocket/BLACKLIST
@@ -1,11 +1,6 @@
[deprecatedProtocols]
windows
-[spontaneousWrite]
-windows-7sp1
[connectToHostEncrypted]
macos
-[setSslConfiguration]
-windows-10 msvc-2015
-windows-7sp1
[connectToHostEncryptedWithVerificationPeerName]
macos
diff --git a/tests/auto/network/ssl/qsslsocket/CMakeLists.txt b/tests/auto/network/ssl/qsslsocket/CMakeLists.txt
index 0e6bf353ee..456deacb60 100644
--- a/tests/auto/network/ssl/qsslsocket/CMakeLists.txt
+++ b/tests/auto/network/ssl/qsslsocket/CMakeLists.txt
@@ -1,4 +1,11 @@
-# Generated from qsslsocket.pro.
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
+
+if(NOT QT_BUILD_STANDALONE_TESTS AND NOT QT_BUILDING_QT)
+ cmake_minimum_required(VERSION 3.16)
+ project(tst_qsslsocket LANGUAGES CXX)
+ find_package(Qt6BuildInternals REQUIRED COMPONENTS STANDALONE_TEST)
+endif()
if(NOT QT_FEATURE_private_tests)
return()
@@ -14,24 +21,16 @@ list(APPEND test_data "certs")
qt_internal_add_test(tst_qsslsocket
SOURCES
tst_qsslsocket.cpp
- PUBLIC_LIBRARIES
+ LIBRARIES
Qt::CorePrivate
Qt::NetworkPrivate
+ Qt::TestPrivate
TESTDATA ${test_data}
- QT_TEST_SERVER_LIST "squid" "danted" "cyrus" "apache2" "echo" # special case
+ QT_TEST_SERVER_LIST "squid" "danted" "cyrus" "apache2" "echo"
+ BUNDLE_ANDROID_OPENSSL_LIBS
)
-#### Keys ignored in scope 1:.:.:qsslsocket.pro:<TRUE>:
-# _REQUIREMENTS = "qtConfig(private_tests)"
-
-## Scopes:
-#####################################################################
-
-#### Keys ignored in scope 3:.:.:qsslsocket.pro:(CMAKE_BUILD_TYPE STREQUAL Debug):
-# DESTDIR = "debug"
-
-#### Keys ignored in scope 4:.:.:qsslsocket.pro:else:
-# DESTDIR = "release"
-
-#### Keys ignored in scope 5:.:.:qsslsocket.pro:LINUX:
-# QT_TEST_SERVER_LIST = "squid" "danted" "cyrus" "apache2" "echo"
+qt_internal_extend_target(tst_qsslsocket CONDITION QT_FEATURE_private_tests AND QT_FEATURE_openssl_linked
+ LIBRARIES
+ WrapOpenSSL::WrapOpenSSL
+)
diff --git a/tests/auto/network/ssl/qsslsocket/certs/ca-generate.sh b/tests/auto/network/ssl/qsslsocket/certs/ca-generate.sh
new file mode 100644
index 0000000000..10aea0905e
--- /dev/null
+++ b/tests/auto/network/ssl/qsslsocket/certs/ca-generate.sh
@@ -0,0 +1,21 @@
+#!/bin/sh
+# Copyright (C) 2016 The Qt Company Ltd.
+# SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0
+
+# generate ca.crt
+openssl genrsa -out ca.key 8192
+openssl req -x509 -new -sha512 -nodes -key ca.key -days 10000 -out ca.crt -config ca.conf
+
+# generate inter.crt
+openssl genrsa -out inter.key 8192
+openssl req -new -sha512 -nodes -key inter.key -out inter.csr -config inter.conf
+openssl x509 -req -sha512 -days 45 -in inter.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out inter.crt
+rm inter.csr
+rm ca.srl
+
+# generate leaf.crt
+openssl genrsa -out leaf.key 8192
+openssl req -new -sha512 -nodes -key leaf.key -out leaf.csr -config leaf.conf
+openssl x509 -req -sha512 -days 45 -in leaf.csr -CA inter.crt -CAkey inter.key -CAcreateserial -out leaf.crt
+rm leaf.csr
+rm inter.srl
diff --git a/tests/auto/network/ssl/qsslsocket/certs/ca.conf b/tests/auto/network/ssl/qsslsocket/certs/ca.conf
new file mode 100644
index 0000000000..1f94247a2f
--- /dev/null
+++ b/tests/auto/network/ssl/qsslsocket/certs/ca.conf
@@ -0,0 +1,10 @@
+basicConstraints = CA:TRUE
+keyUsage = cRLSign, keyCertSign
+[req]
+distinguished_name = network-tests.qt-project.org
+prompt = no
+[network-tests.qt-project.org]
+C = NO
+ST = Oslo
+L = Oslo
+CN = Fake Qt Project Certificate Authority
diff --git a/tests/auto/network/ssl/qsslsocket/certs/ca.crt b/tests/auto/network/ssl/qsslsocket/certs/ca.crt
index 5cbe8ef726..8e6c6e255c 100644
--- a/tests/auto/network/ssl/qsslsocket/certs/ca.crt
+++ b/tests/auto/network/ssl/qsslsocket/certs/ca.crt
@@ -1,22 +1,52 @@
-----BEGIN CERTIFICATE-----
-MIIDpTCCAl2gAwIBAgIQAKraD9BoqaSa75qOqcP7ZTANBgkqhkiG9w0BAQUFADA8
-MQswCQYDVQQGEwJHQjEZMBcGA1UEChMQV2VzdHBvaW50IENBIEtleTESMBAGA1UE
-ChMJV2VzdHBvaW50MB4XDTEzMDIxNjE2NTMwOFoXDTIzMDIxNjE2NTMwOFowPDEL
-MAkGA1UEBhMCR0IxGTAXBgNVBAoTEFdlc3Rwb2ludCBDQSBLZXkxEjAQBgNVBAoT
-CVdlc3Rwb2ludDCCAVIwDQYJKoZIhvcNAQEBBQADggE/ADCCAToCggExAJv0H92j
-WjDB9h1DmSQzt772IPSirpE82sN9ls5J19TJcPnw49LdUUqkELJkpS1ty2hYPdUw
-7q3n00D+nzS+rt1QIDSKwDVoqeIyFZw4h0ULbASErfy51xBjVIr6NNoiqazp59wQ
-RDvqps7of+b/NcbOh73MsiYi8T5OoI4Quv9rMBefQTAI3d2NRQ4GUzS6Hzh2INOc
-4twApTDYY+yrU8IalXttIOVdKJZTHeTCdIXD3HMfHCkzyELz8rCI1/wDEp8zyoqF
-/tpBStZ5LUSrlRRM7PegqcnM+aojXyrEiXBvPuqO7tabU3nsfix9+8+7GDweDXsP
-OUHv+ahGNTUya7hBDaQmVk3/5hbig9kQlNiOcvcdnYYyJqiXhvjPPzOBbRaFNvBT
-uG/ehHNHYsdhEBkCAwEAAaNDMEEwDwYDVR0TAQH/BAUwAwEB/zAPBgNVHQ8BAf8E
-BQMDBwYAMB0GA1UdDgQWBBSUJzi1uYQUxqb3Nr33LOLCaUUTyTANBgkqhkiG9w0B
-AQUFAAOCATEAPeGh2GiIhT3cii3DU8ihd5TmnEstuHKz2FwHDChmen0zxE8lf08/
-onL1yIeaxbDA8KwZnv71/zZHJv02sPtIMUfuXQc0wOIFjDf0ngc6xIBuU7FUpLxF
-2dK7g9OsiNeC7L/ZemRXgpJURdNF2Ujge9/H9yfpHFBXZztmaWir+TXc5g3PKIu6
-97t75Og+stPhTcSlph8ZHYep08b2uthCfcnuIRGeDW9LkfR8VugnuUf7GoIlqSTs
-SR6bNuyTnnCHQMJzbsQ472+ag3aZS5HzoR8wyGiPmpc43lQM5ZEDrWGu8bub2gKa
-/+KeqHd0wnl7Y5cxnmAptQjxvzBXX/pl4sWczesiGcYm5z5mabp4CY09Y8JtrJZT
-IJodXy9ykRmEurgtRoRVc1aSp+xfV725bQ==
+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
+i+VYGJPNrI6E/LMy1lq/iCVQJQ==
-----END CERTIFICATE-----
diff --git a/tests/auto/network/ssl/qsslsocket/certs/ca.key b/tests/auto/network/ssl/qsslsocket/certs/ca.key
new file mode 100644
index 0000000000..eb2c48dbac
--- /dev/null
+++ b/tests/auto/network/ssl/qsslsocket/certs/ca.key
@@ -0,0 +1,99 @@
+-----BEGIN RSA PRIVATE KEY-----
+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
+-----END RSA PRIVATE KEY-----
diff --git a/tests/auto/network/ssl/qsslsocket/certs/inter.conf b/tests/auto/network/ssl/qsslsocket/certs/inter.conf
new file mode 100644
index 0000000000..ed350da8ea
--- /dev/null
+++ b/tests/auto/network/ssl/qsslsocket/certs/inter.conf
@@ -0,0 +1,14 @@
+[req]
+default_md = sha512
+basicConstraints = CA:TRUE
+keyUsage = cRLSign, keyCertSign
+[req]
+distinguished_name = intermediate_authority
+prompt = no
+[intermediate_authority]
+C = NO
+ST = Oslo
+L = Oslo
+O = The Qt Project
+OU = The Qt Project
+CN = Fake Qt Project Intermediate Certificate
diff --git a/tests/auto/network/ssl/qsslsocket/certs/inter.crt b/tests/auto/network/ssl/qsslsocket/certs/inter.crt
index 4e1d67c3e0..2d924f3a96 100644
--- a/tests/auto/network/ssl/qsslsocket/certs/inter.crt
+++ b/tests/auto/network/ssl/qsslsocket/certs/inter.crt
@@ -1,22 +1,53 @@
-----BEGIN CERTIFICATE-----
-MIIDvDCCAnSgAwIBAgIQO+uZxerYC10Ll11PBnVL4TANBgkqhkiG9w0BAQUFADA8
-MQswCQYDVQQGEwJHQjEZMBcGA1UEChMQV2VzdHBvaW50IENBIEtleTESMBAGA1UE
-ChMJV2VzdHBvaW50MB4XDTEzMDIxNjE2NTMwOFoXDTIzMDIxNjE2NTMwOFowMjEL
-MAkGA1UEBhMCR0IxIzAhBgNVBAoTGldlc3Rwb2ludCBJbnRlcm1lZGlhdGUgS2V5
-MIIBUjANBgkqhkiG9w0BAQEFAAOCAT8AMIIBOgKCATEAsR4tRskg2IFfQFMfGBJ1
-eqlrNejANw0oM6k5HlEB8uFA9qeyAzmflwQUPoJ55KRQ/gVHTOBdWrtgGgPMiekF
-1Q36Ry1elwbAl4a+LZ6qsc9ASipvk8HirKpt1v5L9hG+aI4yDxyvjNztFtg5R4P5
-zqsh/WwhCgsYmEVfcSDbhUjqoqxGRLaZxPKO+IMCNFrjZqi0yxc8f6Un4G5SQzHA
-4szi/ezcITnAFYWxHG2yaed4hawpxNS1WXabk2rzCi0pWeIcHuIczaCfZ7ElRcqV
-VNNXbGTtUDlfIsh6FAVI5kTUDcPV27uf6BmHuFOu/R9Tjni25+vBFvohwQh7ZwCX
-5COXnfkJLPkJQQEFVQv8nS27ht/vmyoKjERUeiuMd+hFcN5zl7bS5A2JCgi7erlP
-ZQIDAQABo2QwYjAPBgNVHRMBAf8EBTADAQH/MA8GA1UdDwEB/wQFAwMHBgAwHQYD
-VR0OBBYEFGn5shQ0SeTcc3x/cNu6TkoV0bPmMB8GA1UdIwQYMBaAFJQnOLW5hBTG
-pvc2vfcs4sJpRRPJMA0GCSqGSIb3DQEBBQUAA4IBMQAVDS0enQQ1FL0d92xOFfwx
-mjcNPz9oO7jMyEVxAs2eR2QD+xZ3Xj4gAiUEp40aGieDcLv+dg+cmuBFWF61IYSR
-UyuoakVm08VDcLAwUzU+xtSvJiSSROb0GsAnVsYZj4TYlvKDplqfapOYaiIkwF+c
-iE4n7G0hQW9fzqO+n3FGtBD8YUjghRqLggeRVJ2+8S3Bm8cfx8xPpRIO3ksA6opn
-CORRGuzetDHihbks59mkoY3GqKFgBOyrC3kG07nv5wtKjdKDtmD/kS/SAc4fIXKy
-Uruq2uXNf/1BUgF5gFGRyj22yB2D0763fJJpl5nqcLrL5RmnVObQKZGhE2VsRTV0
-untj+AmiJivhiAjjkHfw3XDf8tuL7D4pTmEkGgl5xl23fyeTIuygDCLT8fRD3ZqQ
+MIIJczCCBVsCFBFyNLwh5soEJBP4NUiEpuneliIVMA0GCSqGSIb3DQEBDQUAMFsx
+CzAJBgNVBAYTAk5PMQ0wCwYDVQQIDARPc2xvMQ0wCwYDVQQHDARPc2xvMS4wLAYD
+VQQDDCVGYWtlIFF0IFByb2plY3QgQ2VydGlmaWNhdGUgQXV0aG9yaXR5MB4XDTIy
+MDkwMjE1MDIyMVoXDTIyMTAxNzE1MDIyMVowgZAxCzAJBgNVBAYTAk5PMQ0wCwYD
+VQQIDARPc2xvMQ0wCwYDVQQHDARPc2xvMRcwFQYDVQQKDA5UaGUgUXQgUHJvamVj
+dDEXMBUGA1UECwwOVGhlIFF0IFByb2plY3QxMTAvBgNVBAMMKEZha2UgUXQgUHJv
+amVjdCBJbnRlcm1lZGlhdGUgQ2VydGlmaWNhdGUwggQiMA0GCSqGSIb3DQEBAQUA
+A4IEDwAwggQKAoIEAQDf31Hd+5tMLrBf966j4BiTBP7yIS7BJ7jBSUWVStd8F1Pc
+hxB/h8hKj8T8M8Fq2prmxkkjg4epxmgqYeGqYnBqPY0Gke0RXC506WGW8B4IQ+qk
+szVHJyNC2dnZ7byaqj1/vleQESmaQhXRxSvaw3Qu54/SbXuEOot8tiBZ90oVvHHt
+yn1nQYpGGDszTATKMaaqaE+D/lsNzxJGGzndbg9yjrvLRKBRbFIhT7L7ME4d2NLm
+AcXvFHHjV2bEBCvQrShXE0t11qAUrT48rDcBA0OsMW6YwxCBoFXvnpg5iuCfbQGf
+zRVgGIhb8Bo1dV2nTBTMpz9ssupTOmlS1/WJ99w4nPHUHBtYe8QBaWigHbIqyxlP
+hm6NBe4i1EoqY7fsfI6uH9eo0l8ZvB/tLCgFRE5OqHQZXPUHutnlhSoouj7gA7Lp
+VPYundGY8mauVV9YFVDECh8oiJI9/dqq4i6QhLHFXFUG6P95yqgzv9fsy2HKKr06
+2deBjOGMoQv7CRgRr9/JOAYOdk8SeQ1eWRA2O2Vx9N2davIczvuODqP2Y2IqJ9/x
+xvYVZNlnLIrtJvTCh4ROe3+ecdLeg/hFT/J2BmG6oHeNm0TJPnI1bK6TDJYb/Nqi
+EIuDDpbNs4IZn70DCU+Fg1FiV+evAziQ67utijyOg/xooUKVvXH4c5s7jUcFmYJd
+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
+wvnYOPu8PDnRWerAdoRZUNlKigb6oUA=
-----END CERTIFICATE-----
diff --git a/tests/auto/network/ssl/qsslsocket/certs/inter.key b/tests/auto/network/ssl/qsslsocket/certs/inter.key
new file mode 100644
index 0000000000..8d282647e5
--- /dev/null
+++ b/tests/auto/network/ssl/qsslsocket/certs/inter.key
@@ -0,0 +1,99 @@
+-----BEGIN RSA PRIVATE KEY-----
+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
+-----END RSA PRIVATE KEY-----
diff --git a/tests/auto/network/ssl/qsslsocket/certs/leaf.conf b/tests/auto/network/ssl/qsslsocket/certs/leaf.conf
new file mode 100644
index 0000000000..5ecbd31b55
--- /dev/null
+++ b/tests/auto/network/ssl/qsslsocket/certs/leaf.conf
@@ -0,0 +1,14 @@
+[req]
+default_md = sha512
+basicConstraints = CA:FALSE
+keyUsage = nonRepudiation, digitalSignature, keyEncipherment
+[req]
+distinguished_name = leaf_cert
+prompt = no
+[leaf_cert]
+C = NO
+ST = Oslo
+L = Oslo
+O = The Qt Project
+OU = The Qt Project
+CN = networking-tests.qt-project.org
diff --git a/tests/auto/network/ssl/qsslsocket/certs/leaf.crt b/tests/auto/network/ssl/qsslsocket/certs/leaf.crt
index 4a7dc40540..b9af13b896 100644
--- a/tests/auto/network/ssl/qsslsocket/certs/leaf.crt
+++ b/tests/auto/network/ssl/qsslsocket/certs/leaf.crt
@@ -1,23 +1,54 @@
-----BEGIN CERTIFICATE-----
-MIID3zCCApegAwIBAgIQEKCtd1j2bq5Gk6ND+VmKnjANBgkqhkiG9w0BAQUFADAy
-MQswCQYDVQQGEwJHQjEjMCEGA1UEChMaV2VzdHBvaW50IEludGVybWVkaWF0ZSBL
-ZXkwHhcNMTMwMjE2MTY1MzA4WhcNMjMwMjE2MTY1MzA4WjA1MQswCQYDVQQGEwJH
-QjESMBAGA1UEChMJV2VzdHBvaW50MRIwEAYDVQQDEwkxMjcuMC4wLjEwggFSMA0G
-CSqGSIb3DQEBAQUAA4IBPwAwggE6AoIBMQC7EIWIzb7XCfmQQ1KFdZ5E9f49eNK/
-KvsXYfq/iV29K1cz2hUyvfdKgyU5F/+BOPQKQ5zdWn1CraZosFv/ibuO3mhRpMfB
-SfNn3rfdrE7WtA0wgT2YNIN0L4aCe+C15j2ESdmyMaFLUaUIS47JS66UtaYxp5ia
-mJFO1hSNaoI0pGHyPFTTtfOza9z/01qkBbHB4htzauqs/fX5ZrnyCDSrfpVipXke
-zkPKg4MkkytEkjRKw6tSXLpWIgF3ee2N/jBdefqlw8YPW08K0wmwF5qGuX6PZ8vB
-sOZeWeCfVr136BopkbfP3TkGWw2BrD8xSzOUez9HVc0v4SZ/7pe5w3L4V/mzYQLt
-O+1AHevCjX8+M58HYGBaWCAjxYUPGcGKcj0LLtgZgL6wY88N7RtfeOY3AgMBAAGj
-gY0wgYowFAYDVR0RBA0wC4IJMTI3LjAuMC4xMAwGA1UdEwEB/wQCMAAwEwYDVR0l
-BAwwCgYIKwYBBQUHAwEwDwYDVR0PAQH/BAUDAwcoADAdBgNVHQ4EFgQUKKuyJSrT
-Y+dnm1do7l0sVMX96SYwHwYDVR0jBBgwFoAUafmyFDRJ5NxzfH9w27pOShXRs+Yw
-DQYJKoZIhvcNAQEFBQADggExAHELijlIFdcncP3B+vxEp0SGKl0arIaCXahivb2F
-VxeM3WajN6O+oDRLFltzMeDKA9RVkao7fgITzXQgCGzeNhKv0vc9iDyvR9/67vuS
-W8xEEJrYowtw3VK5H1y0ewqZaxJhvKUjm4TBRWe8FGKD3s64lEsfbjOaI5VPidVc
-DXmdAlXsj0Hk+v4Ej8mshPQAnVSyJ3D0ZMgTjk8Di28N0qROFIYJaTObK1rCb1nQ
-GaCcmbZU6JnkYvVZ+iUe5U0GXFbb+LRNTUT8/fw1zADeHnv/G+WWVrfND+sov5Oc
-33fkNE6z+n6ayABVnGLuCYhbzD38sv0dnxeh8vbykNBPzYdzPg6nw3Czv2vlhKpJ
-8Yj/maoXuAyTXVf30K1/fAWyU45noq57MjQpU6UxIX1D7qw=
+MIIJoDCCBYgCFFjfM8GbvMVRegCGZEOUQeIm7z+JMA0GCSqGSIb3DQEBDQUAMIGQ
+MQswCQYDVQQGEwJOTzENMAsGA1UECAwET3NsbzENMAsGA1UEBwwET3NsbzEXMBUG
+A1UECgwOVGhlIFF0IFByb2plY3QxFzAVBgNVBAsMDlRoZSBRdCBQcm9qZWN0MTEw
+LwYDVQQDDChGYWtlIFF0IFByb2plY3QgSW50ZXJtZWRpYXRlIENlcnRpZmljYXRl
+MB4XDTIyMDkwMjE1MDIzMFoXDTIyMTAxNzE1MDIzMFowgYcxCzAJBgNVBAYTAk5P
+MQ0wCwYDVQQIDARPc2xvMQ0wCwYDVQQHDARPc2xvMRcwFQYDVQQKDA5UaGUgUXQg
+UHJvamVjdDEXMBUGA1UECwwOVGhlIFF0IFByb2plY3QxKDAmBgNVBAMMH25ldHdv
+cmtpbmctdGVzdHMucXQtcHJvamVjdC5vcmcwggQiMA0GCSqGSIb3DQEBAQUAA4IE
+DwAwggQKAoIEAQCjQsmsZpATuLv54ERkqSdjWZYuulm5gZwzz9fS7R/K1CoSFQza
+T+rY7Kauv1zpalfZGNs4zmEiHDsJ/hhVxCC0L6L2PqmkZjFT9psAkPHENRMIvBYl
+QsrJbSNj09UeBfAR+ux2vktreyZc3UFyq74iQbHeXFuzDnH17BZMR8nMs72wDD5J
+QMaRmvtEvOlNuiT6X7YluO7L3f4EAGbLh3s4OxDHOIqtSXkFjMlgmqU3fKBsZ89F
+YlYH/v0X6ItK7tMbwJjXea1gPomO7pIH2H7CzTQ2DNL6fGRvqCFjZeseZudgRhwN
+LYz67yDKtZ0TvjqD3ShEboh5CxjL+8kskmofBf4WcF0z8xg2GtopAwFQU6ZI+FKY
+rNbUvTWcew4Q/Q0Ya01obeTXsOKZ7IVAo5SxOFSdBa+wS4Igekl7A0C9d9QTduxA
+4fnD+Rhw0dvZqL3lBnSisIsCIo/WK6g2L/gYvgRG/3ChRibfeW81rU8q6+MJIx4P
+Ad3f1wvEWGAWiYYnHfF0qpxhd3UYUN/31w3idaA4LAuQCOSfQHKnGEhp0hVng68H
+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
+y7Sk5pZgg67qgXybVQfxbPwEK6A=
-----END CERTIFICATE-----
diff --git a/tests/auto/network/ssl/qsslsocket/certs/leaf.key b/tests/auto/network/ssl/qsslsocket/certs/leaf.key
index 54327925d8..738d5ea8b9 100644
--- a/tests/auto/network/ssl/qsslsocket/certs/leaf.key
+++ b/tests/auto/network/ssl/qsslsocket/certs/leaf.key
@@ -1,32 +1,99 @@
-----BEGIN RSA PRIVATE KEY-----
-MIIFfAIBAAKCATEAuxCFiM2+1wn5kENShXWeRPX+PXjSvyr7F2H6v4ldvStXM9oV
-Mr33SoMlORf/gTj0CkOc3Vp9Qq2maLBb/4m7jt5oUaTHwUnzZ9633axO1rQNMIE9
-mDSDdC+GgnvgteY9hEnZsjGhS1GlCEuOyUuulLWmMaeYmpiRTtYUjWqCNKRh8jxU
-07Xzs2vc/9NapAWxweIbc2rqrP31+Wa58gg0q36VYqV5Hs5DyoODJJMrRJI0SsOr
-Uly6ViIBd3ntjf4wXXn6pcPGD1tPCtMJsBeahrl+j2fLwbDmXlngn1a9d+gaKZG3
-z905BlsNgaw/MUszlHs/R1XNL+Emf+6XucNy+Ff5s2EC7TvtQB3rwo1/PjOfB2Bg
-WlggI8WFDxnBinI9Cy7YGYC+sGPPDe0bX3jmNwIDAQABAoIBMQCczBNyAStGqjjC
-oHuKHHWmTh9mPWFBFfDTv6/jXmvxRWPZtaHxH2Qp09Wejqv/D9MWy2ev7spx2oZS
-2Ai1ICjTbz83uAwryyW4Wen6aBTJSLCJiLstWk8ZU0DHHLjVH4FO4mwUPh95t5zC
-YDr2JXbXdY8xrc5vPxUFZNJjWvR61ZK37bQYpTn5mZ7r3KfsNk2yOylRTDwa9XFo
-ZZ+B82NKdrrz0UvGOnXZa5qd1ap7V+67FIAS2Mt8AMzSCG8TW0JXRUk89ISgAd8r
-NQTPtX9XCnMZSbBzDKdznXfHS9ZlJcSrpsbQCPcvMVNrdBfCF0eNnsRJffJGdaXI
-MsN6PvbcXWD08lXNGyeLjon03RdJnTAamNM3YQEIcjFmu5Y0o0CCJkZSCJPKJGMG
-0d/1tN/5AoGZANOcOgQZ9Wiu0ej3YoQ3aSHu3y8ZBJH4B3ViX8i+2x/6UnG7KNaa
-4Ygid1upnX6hk4CW5WZcoxGFacrFRpInKh5Ng8lEIHGp0VSzOBVDR0L5sAxutFuX
-6N9C0CuH80vD101mOloNnfT5KHZMI5RXqP6sDGUFlwak2XybDL1qOAza3gZAy25H
-vS/ll1BneBavikR5j+zxoTztAoGZAOJOJ5RyOrqpNuhiWZylah5LIFT9N1lCF4Hl
-ZbFIjUZ4jcApJ7JxkMXNQ4RU/3AiKCC1xr5ib7dd/qyjKXhdMo4SnLoKhapx5R9G
-3XOsQMahiCD/Zcymv9tmk8MxxzbLxhZYhEPzIP/NFkua3CHiX+d1e6fkzFLF/EiX
-ZGQOgRcFKrlzUeBputRQRXAkKJH+kMClgAWvy28zAoGYKyaMXhG9DV+4xjzMBhIW
-iijfsgbz+6AMRU+OIK1qmZa+ARsdNMXYf54noLVxvETOg0ZB+SGizwvZitO3lE4Q
-NKWx3fTaeNMcMJ1rLkrN2UZ5M8/PT24muoAxWu8aGbURzmKuO3bTYwT7z0OvbayC
-dYw36tG8/knXX6Vub6GdVGG9LKFB2nceiQnUVT0EK/wXwebYBoUvT/ECgZgF9qdG
-Wyg/CPyAbS8NWLKOL86fTrjpqjsyWhgu7smCROT/XlZEdoepHrqbvx2oF85U5lVh
-aPimrVxrsjUCjfoqEkV9BY/2KOAvzc9CIBTo5xLOQ8yr8uz1XCOiriogwIfsyNJb
-dAm3k/D1dxQ79FowoEDs8LONrtfyFcM4e8VdFO7GSkqrDj41IBRkWx+SkVHBMdtI
-yxQiTwKBmQCWym2iDCJg1ZZq4/lVwRudMhVmHoD0yoCAwADYHjjAi8QBplM0vfdd
-CESKsnBhlcrPGB279BKVJyZHehKZG+/dfnFs+to14l6A3IqU2d6+pu3EyFNX34HS
-xo+64QxMeF0akWnSaIPfUJfk36phjCvLBr4eLXN1i4jW3RdGFwF1THXt29VSSGmU
-q/hM51H0bsQ13AIVUSdNHA==
+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
-----END RSA PRIVATE KEY-----
diff --git a/tests/auto/network/ssl/qsslsocket/certs/qt-test-server-cacert.pem b/tests/auto/network/ssl/qsslsocket/certs/qt-test-server-cacert.pem
index c5aea0d7c9..29fd755de7 100644
--- a/tests/auto/network/ssl/qsslsocket/certs/qt-test-server-cacert.pem
+++ b/tests/auto/network/ssl/qsslsocket/certs/qt-test-server-cacert.pem
@@ -1,17 +1,17 @@
-----BEGIN CERTIFICATE-----
-MIICpzCCAhACCQCzAF1hyRVzAjANBgkqhkiG9w0BAQUFADCBlzELMAkGA1UEBhMC
-Tk8xDTALBgNVBAgTBE9zbG8xDTALBgNVBAcTBE9zbG8xDjAMBgNVBAoTBU5va2lh
-MTUwMwYDVQQLFCxRdCBTb2Z0d2FyZS9lbWFpbEFkZHJlc3M9bm9ib2R5QG5vZG9t
-YWluLm9yZzEjMCEGA1UEAxMacXQtdGVzdC1zZXJ2ZXIucXQtdGVzdC1uZXQwHhcN
-MTkwNjI0MTI0OTIxWhcNMjIwNjIzMTI0OTIxWjCBlzELMAkGA1UEBhMCTk8xDTAL
-BgNVBAgTBE9zbG8xDTALBgNVBAcTBE9zbG8xDjAMBgNVBAoTBU5va2lhMTUwMwYD
-VQQLFCxRdCBTb2Z0d2FyZS9lbWFpbEFkZHJlc3M9bm9ib2R5QG5vZG9tYWluLm9y
-ZzEjMCEGA1UEAxMacXQtdGVzdC1zZXJ2ZXIucXQtdGVzdC1uZXQwgZ8wDQYJKoZI
-hvcNAQEBBQADgY0AMIGJAoGBAM2q22/WNMmn8cC+5EEYGeICySLmp9W6Ay6eKHr0
-Xxp3X3epETuPfvAuxp7rOtkS18EMUegkUj8jw0IMEcbyHKFC/rTCaYOt93CxGBXM
-IChiMPAsFeYzGa/D6xzAkfcRaJRQ+Ek3CDLXPnXfo7xpABXezYcPXAJrgsgBfWrw
-HdxzAgMBAAEwDQYJKoZIhvcNAQEFBQADgYEASCKbqEX5ysC549mq90ydk4jyDW3m
-PUyet01fKpcRqVs+OJxdExFBTra3gho6WzzpTSPsuX2ZKOLF5k6KkCvdCGvhC1Kv
-HHPIExurfzvdlSRzj6HbKyPuSfxyOloH0bBp7/Gg5RIuBPKlbmfbnTLtwEjhhbMU
-SoYI8HZd3HfY87c=
+MIICyjCCAjMCFHPGDqJR+klHni4XbETMk6GLn/UEMA0GCSqGSIb3DQEBDQUAMIGj
+MRcwFQYDVQQKEw5UaGUgUXQgQ29tcGFueTEUMBIGA1UECxMLUXQgU29mdHdhcmUx
+IjAgBgkqhkiG9w0BCQEWE25vYm9keUBub2RvbWFpbi5vcmcxDTALBgNVBAcTBE9z
+bG8xDTALBgNVBAgTBE9zbG8xCzAJBgNVBAYTAk5PMSMwIQYDVQQDExpxdC10ZXN0
+LXNlcnZlci5xdC10ZXN0LW5ldDAeFw0yMjA2MjQxMTU4NDlaFw0zMjA2MjExMTU4
+NDlaMIGjMRcwFQYDVQQKEw5UaGUgUXQgQ29tcGFueTEUMBIGA1UECxMLUXQgU29m
+dHdhcmUxIjAgBgkqhkiG9w0BCQEWE25vYm9keUBub2RvbWFpbi5vcmcxDTALBgNV
+BAcTBE9zbG8xDTALBgNVBAgTBE9zbG8xCzAJBgNVBAYTAk5PMSMwIQYDVQQDExpx
+dC10ZXN0LXNlcnZlci5xdC10ZXN0LW5ldDCBnzANBgkqhkiG9w0BAQEFAAOBjQAw
+gYkCgYEAzarbb9Y0yafxwL7kQRgZ4gLJIuan1boDLp4oevRfGndfd6kRO49+8C7G
+nus62RLXwQxR6CRSPyPDQgwRxvIcoUL+tMJpg633cLEYFcwgKGIw8CwV5jMZr8Pr
+HMCR9xFolFD4STcIMtc+dd+jvGkAFd7Nhw9cAmuCyAF9avAd3HMCAwEAATANBgkq
+hkiG9w0BAQ0FAAOBgQCZyRe25WqOjrNS6BKPs7ep7eyCON3NKdWnfABZrSjGJQ87
+PoFKl6+9YBSlSpl8qk7c29ic+wA4qFQzPJkrbYIXjwVMAr+cC1kVrlUVqcwmvnKo
+5vj57/v8S0Uc4/GesIsxZR7QM+3diPDyk7Bsc3IkpINb31Dl0mlg25nztg8NxA==
-----END CERTIFICATE-----
diff --git a/tests/auto/network/ssl/qsslsocket/tst_qsslsocket.cpp b/tests/auto/network/ssl/qsslsocket/tst_qsslsocket.cpp
index a03809fc09..b45d6b5d8f 100644
--- a/tests/auto/network/ssl/qsslsocket/tst_qsslsocket.cpp
+++ b/tests/auto/network/ssl/qsslsocket/tst_qsslsocket.cpp
@@ -1,31 +1,6 @@
-/****************************************************************************
-**
-** Copyright (C) 2021 The Qt Company Ltd.
-** Copyright (C) 2014 Governikus GmbH & Co. KG.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2021 The Qt Company Ltd.
+// Copyright (C) 2014 Governikus GmbH & Co. KG.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
#include <QtNetwork/private/qtnetworkglobal_p.h>
@@ -44,6 +19,8 @@
#include <QtNetwork/qtcpserver.h>
#include <QtNetwork/qsslpresharedkeyauthenticator.h>
+#include <QtTest/private/qemulationdetector_p.h>
+
#include <QTest>
#include <QNetworkProxy>
#include <QAuthenticator>
@@ -66,6 +43,23 @@
#include "private/qsslsocket_p.h"
#include "private/qsslconfiguration_p.h"
+using namespace std::chrono_literals;
+
+QT_WARNING_PUSH
+QT_WARNING_DISABLE_DEPRECATED
+// make these enum values available without causing deprecation warnings:
+namespace Test {
+#define COPY(tag, v) \
+ constexpr auto tag ## V ## v = QSsl:: tag ## V ## v ; \
+ constexpr auto tag ## V ## v ## OrLater = QSsl:: tag ## V ## v ## OrLater ; \
+ /* end */
+COPY(Tls, 1_0)
+COPY(Dtls, 1_0)
+COPY(Tls, 1_1)
+#undef COPY
+} // namespace Test
+QT_WARNING_POP
+
Q_DECLARE_METATYPE(QSslSocket::SslMode)
typedef QList<QSslError::SslError> SslErrorList;
Q_DECLARE_METATYPE(SslErrorList)
@@ -155,6 +149,9 @@ private slots:
void sslErrors_data();
void sslErrors();
void ciphers();
+#if QT_CONFIG(securetransport)
+ void tls13Ciphers();
+#endif // QT_CONFIG(securetransport)
void connectToHostEncrypted();
void connectToHostEncryptedWithVerificationPeerName();
void sessionCipher();
@@ -169,9 +166,7 @@ private slots:
void protocol();
void protocolServerSide_data();
void protocolServerSide();
-#if QT_CONFIG(openssl)
void serverCipherPreferences();
-#endif
void setCaCertificates();
void setLocalCertificate();
void localCertificateChain();
@@ -296,6 +291,7 @@ private:
QSslSocket *socket;
QList<QSslError> storedExpectedSslErrors;
bool isTestingOpenSsl = false;
+ bool isSecurityLevel0Required = false;
bool opensslResolved = false;
bool isTestingSecureTransport = false;
bool isTestingSchannel = false;
@@ -415,6 +411,9 @@ void tst_QSslSocket::initTestCase()
flukeCertificateError = QSslError::SelfSignedCertificate;
#if QT_CONFIG(openssl)
opensslResolved = qt_auto_test_resolve_OpenSSL_symbols();
+ // This is where OpenSSL moved several protocols under
+ // non-default (0) security level (the default is 1).
+ isSecurityLevel0Required = OPENSSL_VERSION_NUMBER >= 0x30100010;
#else
opensslResolved = false; // Not 'unused variable' anymore.
#endif
@@ -799,22 +798,31 @@ void tst_QSslSocket::configNoOnDemandLoad()
QCOMPARE(customConfig, socket.sslConfiguration());
}
+static void downgrade_TLS_QTQAINFRA_4499(QSslSocket &socket)
+{
+ // Set TLS 1.0 or above because the server doesn't support TLS 1.2 or above
+ // QTQAINFRA-4499
+ QSslConfiguration config = socket.sslConfiguration();
+ config.setProtocol(Test::TlsV1_0OrLater);
+ socket.setSslConfiguration(config);
+}
+
void tst_QSslSocket::simpleConnect()
{
if (!QSslSocket::supportsSsl())
return;
+ // Starting from OpenSSL v 3.1.1 deprecated protocol versions (we want to use when connecting) are not available by default.
+ if (isSecurityLevel0Required)
+ QSKIP("Testing with OpenSSL backend, but security level 0 is required for TLS v1.1 or earlier");
+
QFETCH_GLOBAL(bool, setProxy);
if (setProxy)
return;
QSslSocket socket;
- // Set TLS 1.0 or above because the server doesn't support TLS 1.2 or above
- // QTQAINFRA-4499
- QSslConfiguration config = socket.sslConfiguration();
- config.setProtocol(QSsl::TlsV1_0OrLater);
- socket.setSslConfiguration(config);
+ downgrade_TLS_QTQAINFRA_4499(socket);
QSignalSpy connectedSpy(&socket, SIGNAL(connected()));
QSignalSpy hostFoundSpy(&socket, SIGNAL(hostFound()));
@@ -836,30 +844,30 @@ void tst_QSslSocket::simpleConnect()
// Entered connecting state
QCOMPARE(socket.state(), QAbstractSocket::ConnectingState);
- QCOMPARE(connectedSpy.count(), 0);
- QCOMPARE(hostFoundSpy.count(), 1);
- QCOMPARE(disconnectedSpy.count(), 0);
+ QCOMPARE(connectedSpy.size(), 0);
+ QCOMPARE(hostFoundSpy.size(), 1);
+ QCOMPARE(disconnectedSpy.size(), 0);
enterLoop(10);
// Entered connected state
QCOMPARE(socket.state(), QAbstractSocket::ConnectedState);
QCOMPARE(socket.mode(), QSslSocket::UnencryptedMode);
QVERIFY(!socket.isEncrypted());
- QCOMPARE(connectedSpy.count(), 1);
- QCOMPARE(hostFoundSpy.count(), 1);
- QCOMPARE(disconnectedSpy.count(), 0);
+ QCOMPARE(connectedSpy.size(), 1);
+ QCOMPARE(hostFoundSpy.size(), 1);
+ QCOMPARE(disconnectedSpy.size(), 0);
// Enter encrypted mode
socket.startClientEncryption();
QCOMPARE(socket.mode(), QSslSocket::SslClientMode);
QVERIFY(!socket.isEncrypted());
- QCOMPARE(connectionEncryptedSpy.count(), 0);
- QCOMPARE(sslErrorsSpy.count(), 0);
+ QCOMPARE(connectionEncryptedSpy.size(), 0);
+ QCOMPARE(sslErrorsSpy.size(), 0);
// Starting handshake
enterLoop(10);
- QCOMPARE(sslErrorsSpy.count(), 1);
- QCOMPARE(connectionEncryptedSpy.count(), 0);
+ QCOMPARE(sslErrorsSpy.size(), 1);
+ QCOMPARE(connectionEncryptedSpy.size(), 0);
QVERIFY(!socket.isEncrypted());
QCOMPARE(socket.state(), QAbstractSocket::UnconnectedState);
}
@@ -869,6 +877,10 @@ void tst_QSslSocket::simpleConnectWithIgnore()
if (!QSslSocket::supportsSsl())
return;
+ // Starting from OpenSSL v 3.1.1 deprecated protocol versions (we want to use when connecting) are not available by default.
+ if (isSecurityLevel0Required)
+ QSKIP("Testing with OpenSSL backend, but security level 0 is required for TLS v1.1 or earlier");
+
QFETCH_GLOBAL(bool, setProxy);
if (setProxy)
return;
@@ -878,11 +890,7 @@ void tst_QSslSocket::simpleConnectWithIgnore()
QSignalSpy encryptedSpy(&socket, SIGNAL(encrypted()));
QSignalSpy sslErrorsSpy(&socket, SIGNAL(sslErrors(QList<QSslError>)));
- // Set TLS 1.0 or above because the server doesn't support TLS 1.2 or above
- // QTQAINFRA-4499
- QSslConfiguration config = socket.sslConfiguration();
- config.setProtocol(QSsl::TlsV1_0OrLater);
- socket.setSslConfiguration(config);
+ downgrade_TLS_QTQAINFRA_4499(socket);
connect(&socket, SIGNAL(readyRead()), this, SLOT(exitLoop()));
connect(&socket, SIGNAL(encrypted()), this, SLOT(exitLoop()));
@@ -901,10 +909,10 @@ void tst_QSslSocket::simpleConnectWithIgnore()
enterLoop(10);
// Done; encryption should be enabled.
- QCOMPARE(sslErrorsSpy.count(), 1);
+ QCOMPARE(sslErrorsSpy.size(), 1);
QVERIFY(socket.isEncrypted());
QCOMPARE(socket.state(), QAbstractSocket::ConnectedState);
- QCOMPARE(encryptedSpy.count(), 1);
+ QCOMPARE(encryptedSpy.size(), 1);
// Wait for incoming data
if (!socket.canReadLine())
@@ -917,6 +925,10 @@ void tst_QSslSocket::simpleConnectWithIgnore()
void tst_QSslSocket::sslErrors_data()
{
+ // Starting from OpenSSL v 3.1.1 deprecated protocol versions (we want to use in 'sslErrors' test) are not available by default.
+ if (isSecurityLevel0Required)
+ QSKIP("Testing with OpenSSL backend, but security level 0 is required for TLS v1.1 or earlier");
+
QTest::addColumn<QString>("host");
QTest::addColumn<int>("port");
@@ -934,11 +946,8 @@ void tst_QSslSocket::sslErrors()
QSslSocketPtr socket = newSocket();
- // Set TLS 1.0 or above because the server doesn't support TLS 1.2 or above
- // QTQAINFRA-4499
- QSslConfiguration config = socket->sslConfiguration();
- config.setProtocol(QSsl::TlsV1_0OrLater);
- socket->setSslConfiguration(config);
+ QVERIFY(socket);
+ downgrade_TLS_QTQAINFRA_4499(*socket);
QSignalSpy sslErrorsSpy(socket.data(), SIGNAL(sslErrors(QList<QSslError>)));
QSignalSpy peerVerifyErrorSpy(socket.data(), SIGNAL(peerVerifyError(QSslError)));
@@ -977,7 +986,7 @@ void tst_QSslSocket::sslErrors()
// check the same errors were emitted by sslErrors
QVERIFY(!sslErrorsSpy.isEmpty());
SslErrorList emittedErrors;
- const auto sslErrorsSpyErrors = qvariant_cast<QList<QSslError> >(qAsConst(sslErrorsSpy).first().first());
+ const auto sslErrorsSpyErrors = qvariant_cast<QList<QSslError> >(std::as_const(sslErrorsSpy).first().first());
for (const QSslError &err : sslErrorsSpyErrors)
emittedErrors << err.error();
std::sort(emittedErrors.begin(), emittedErrors.end());
@@ -1026,7 +1035,7 @@ void tst_QSslSocket::ciphers()
QString ciphersAsString;
const auto &supported = sslConfig.supportedCiphers();
for (const auto &cipher : supported) {
- if (cipher.isNull() || !cipher.name().length())
+ if (cipher.isNull() || !cipher.name().size())
continue;
if (ciphers.size() > 0)
ciphersAsString += QStringLiteral(":");
@@ -1063,14 +1072,48 @@ void tst_QSslSocket::ciphers()
}
}
+#if QT_CONFIG(securetransport)
+void tst_QSslSocket::tls13Ciphers()
+{
+ // SecureTransport introduced several new ciphers under
+ // "TLS 1.3 ciphersuites" section. Since Qt 6 we respect
+ // the ciphers from QSslConfiguration. In case of default
+ // configuration, these are the same we report and we
+ // were failing (for historical reasons) to report those
+ // TLS 1.3 suites when creating default QSslConfiguration.
+ // Check we now have them.
+ if (!isTestingSecureTransport)
+ QSKIP("The feature 'securetransport' was enabled, but active backend is not \"securetransport\"");
+
+ QFETCH_GLOBAL(const bool, setProxy);
+ if (setProxy)
+ return;
+
+ const auto suites = QSslConfiguration::defaultConfiguration().ciphers();
+ QSslCipher ciph;
+ // Check the one of reported and previously missed:
+ for (const auto &suite : suites) {
+ if (suite.encryptionMethod() == QStringLiteral("CHACHA20")) {
+ // There are several ciphesuites using CHACHA20, the first one
+ // is sufficient for the purpose of this test:
+ ciph = suite;
+ break;
+ }
+ }
+
+ QVERIFY(!ciph.isNull());
+ QCOMPARE(ciph.encryptionMethod(), QStringLiteral("CHACHA20"));
+ QCOMPARE(ciph.supportedBits(), 256);
+ QCOMPARE(ciph.usedBits(), 256);
+}
+#endif // QT_CONFIG(securetransport)
+
void tst_QSslSocket::connectToHostEncrypted()
{
if (!QSslSocket::supportsSsl())
return;
QSslSocketPtr socket = newSocket();
- if (isTestingSchannel) // old certificate not supported with TLS 1.2
- socket->setProtocol(QSsl::SslProtocol::TlsV1_1);
this->socket = socket.data();
auto config = socket->sslConfiguration();
@@ -1108,8 +1151,6 @@ void tst_QSslSocket::connectToHostEncryptedWithVerificationPeerName()
return;
QSslSocketPtr socket = newSocket();
- if (isTestingSchannel) // old certificate not supported with TLS 1.2
- socket->setProtocol(QSsl::SslProtocol::TlsV1_1);
this->socket = socket.data();
@@ -1208,7 +1249,7 @@ void tst_QSslSocket::peerCertificateChain()
QSslSocketPtr socket = newSocket();
this->socket = socket.data();
QList<QSslCertificate> caCertificates = QSslCertificate::fromPath(httpServerCertChainPath());
- QCOMPARE(caCertificates.count(), 1);
+ QCOMPARE(caCertificates.size(), 1);
auto config = socket->sslConfiguration();
config.addCaCertificates(caCertificates);
socket->setSslConfiguration(config);
@@ -1225,7 +1266,7 @@ void tst_QSslSocket::peerCertificateChain()
QSKIP("Skipping flaky test - See QTBUG-29941");
QList<QSslCertificate> certChain = socket->peerCertificateChain();
- QVERIFY(certChain.count() > 0);
+ QVERIFY(certChain.size() > 0);
QCOMPARE(certChain.first(), socket->peerCertificate());
socket->disconnectFromHost();
@@ -1269,6 +1310,7 @@ void tst_QSslSocket::privateKey()
#if QT_CONFIG(openssl)
void tst_QSslSocket::privateKeyOpaque()
{
+#ifndef OPENSSL_NO_DEPRECATED_3_0
if (!isTestingOpenSsl)
QSKIP("The active TLS backend does not support private opaque keys");
@@ -1302,6 +1344,7 @@ void tst_QSslSocket::privateKeyOpaque()
QFETCH_GLOBAL(bool, setProxy);
if (setProxy && !socket->waitForEncrypted(10000))
QSKIP("Skipping flaky test - See QTBUG-29941");
+#endif // OPENSSL_NO_DEPRECATED_3_0
}
#endif // Feature 'openssl'.
@@ -1327,38 +1370,38 @@ void tst_QSslSocket::protocol()
QFETCH_GLOBAL(bool, setProxy);
{
// qt-test-server allows TLSV1.
- socket->setProtocol(QSsl::TlsV1_0);
- QCOMPARE(socket->protocol(), QSsl::TlsV1_0);
+ socket->setProtocol(Test::TlsV1_0);
+ QCOMPARE(socket->protocol(), Test::TlsV1_0);
socket->connectToHostEncrypted(QtNetworkSettings::httpServerName(), 443);
if (setProxy && !socket->waitForEncrypted())
QSKIP("Skipping flaky test - See QTBUG-29941");
- QCOMPARE(socket->protocol(), QSsl::TlsV1_0);
+ QCOMPARE(socket->protocol(), Test::TlsV1_0);
socket->abort();
- QCOMPARE(socket->protocol(), QSsl::TlsV1_0);
+ QCOMPARE(socket->protocol(), Test::TlsV1_0);
socket->connectToHost(QtNetworkSettings::httpServerName(), 443);
QVERIFY2(socket->waitForConnected(), qPrintable(socket->errorString()));
socket->startClientEncryption();
if (setProxy && !socket->waitForEncrypted())
QSKIP("Skipping flaky test - See QTBUG-29941");
- QCOMPARE(socket->protocol(), QSsl::TlsV1_0);
+ QCOMPARE(socket->protocol(), Test::TlsV1_0);
socket->abort();
}
{
// qt-test-server probably doesn't allow TLSV1.1
- socket->setProtocol(QSsl::TlsV1_1);
- QCOMPARE(socket->protocol(), QSsl::TlsV1_1);
+ socket->setProtocol(Test::TlsV1_1);
+ QCOMPARE(socket->protocol(), Test::TlsV1_1);
socket->connectToHostEncrypted(QtNetworkSettings::httpServerName(), 443);
if (setProxy && !socket->waitForEncrypted())
QSKIP("Skipping flaky test - See QTBUG-29941");
- QCOMPARE(socket->protocol(), QSsl::TlsV1_1);
+ QCOMPARE(socket->protocol(), Test::TlsV1_1);
socket->abort();
- QCOMPARE(socket->protocol(), QSsl::TlsV1_1);
+ QCOMPARE(socket->protocol(), Test::TlsV1_1);
socket->connectToHost(QtNetworkSettings::httpServerName(), 443);
QVERIFY2(socket->waitForConnected(), qPrintable(socket->errorString()));
socket->startClientEncryption();
if (setProxy && !socket->waitForEncrypted())
QSKIP("Skipping flaky test - See QTBUG-29941");
- QCOMPARE(socket->protocol(), QSsl::TlsV1_1);
+ QCOMPARE(socket->protocol(), Test::TlsV1_1);
socket->abort();
}
{
@@ -1534,41 +1577,34 @@ void tst_QSslSocket::protocolServerSide_data()
QTest::addColumn<QSsl::SslProtocol>("clientProtocol");
QTest::addColumn<bool>("works");
- QTest::newRow("tls1.0-tls1.0") << QSsl::TlsV1_0 << QSsl::TlsV1_0 << true;
QTest::newRow("any-any") << QSsl::AnyProtocol << QSsl::AnyProtocol << true;
QTest::newRow("secure-secure") << QSsl::SecureProtocols << QSsl::SecureProtocols << true;
- QTest::newRow("tls1.0-secure") << QSsl::TlsV1_0 << QSsl::SecureProtocols << false;
- QTest::newRow("tls1.0-any") << QSsl::TlsV1_0 << QSsl::AnyProtocol << true;
-
- QTest::newRow("secure-tls1.0") << QSsl::SecureProtocols << QSsl::TlsV1_0 << false;
+ QTest::newRow("tls1.0-secure") << Test::TlsV1_0 << QSsl::SecureProtocols << false;
+ QTest::newRow("secure-tls1.0") << QSsl::SecureProtocols << Test::TlsV1_0 << false;
QTest::newRow("secure-any") << QSsl::SecureProtocols << QSsl::AnyProtocol << true;
- QTest::newRow("tls1.0orlater-tls1.0") << QSsl::TlsV1_0OrLater << QSsl::TlsV1_0 << true;
- QTest::newRow("tls1.0orlater-tls1.1") << QSsl::TlsV1_0OrLater << QSsl::TlsV1_1 << true;
- QTest::newRow("tls1.0orlater-tls1.2") << QSsl::TlsV1_0OrLater << QSsl::TlsV1_2 << true;
+ QTest::newRow("tls1.0orlater-tls1.2") << Test::TlsV1_0OrLater << QSsl::TlsV1_2 << true;
if (supportsTls13())
- QTest::newRow("tls1.0orlater-tls1.3") << QSsl::TlsV1_0OrLater << QSsl::TlsV1_3 << true;
+ QTest::newRow("tls1.0orlater-tls1.3") << Test::TlsV1_0OrLater << QSsl::TlsV1_3 << true;
- QTest::newRow("tls1.1orlater-tls1.0") << QSsl::TlsV1_1OrLater << QSsl::TlsV1_0 << false;
- QTest::newRow("tls1.1orlater-tls1.1") << QSsl::TlsV1_1OrLater << QSsl::TlsV1_1 << true;
- QTest::newRow("tls1.1orlater-tls1.2") << QSsl::TlsV1_1OrLater << QSsl::TlsV1_2 << true;
+ QTest::newRow("tls1.1orlater-tls1.0") << Test::TlsV1_1OrLater << Test::TlsV1_0 << false;
+ QTest::newRow("tls1.1orlater-tls1.2") << Test::TlsV1_1OrLater << QSsl::TlsV1_2 << true;
if (supportsTls13())
- QTest::newRow("tls1.1orlater-tls1.3") << QSsl::TlsV1_1OrLater << QSsl::TlsV1_3 << true;
+ QTest::newRow("tls1.1orlater-tls1.3") << Test::TlsV1_1OrLater << QSsl::TlsV1_3 << true;
- QTest::newRow("tls1.2orlater-tls1.0") << QSsl::TlsV1_2OrLater << QSsl::TlsV1_0 << false;
- QTest::newRow("tls1.2orlater-tls1.1") << QSsl::TlsV1_2OrLater << QSsl::TlsV1_1 << false;
+ QTest::newRow("tls1.2orlater-tls1.0") << QSsl::TlsV1_2OrLater << Test::TlsV1_0 << false;
+ QTest::newRow("tls1.2orlater-tls1.1") << QSsl::TlsV1_2OrLater << Test::TlsV1_1 << false;
QTest::newRow("tls1.2orlater-tls1.2") << QSsl::TlsV1_2OrLater << QSsl::TlsV1_2 << true;
if (supportsTls13()) {
QTest::newRow("tls1.2orlater-tls1.3") << QSsl::TlsV1_2OrLater << QSsl::TlsV1_3 << true;
- QTest::newRow("tls1.3orlater-tls1.0") << QSsl::TlsV1_3OrLater << QSsl::TlsV1_0 << false;
- QTest::newRow("tls1.3orlater-tls1.1") << QSsl::TlsV1_3OrLater << QSsl::TlsV1_1 << false;
+ QTest::newRow("tls1.3orlater-tls1.0") << QSsl::TlsV1_3OrLater << Test::TlsV1_0 << false;
+ QTest::newRow("tls1.3orlater-tls1.1") << QSsl::TlsV1_3OrLater << Test::TlsV1_1 << false;
QTest::newRow("tls1.3orlater-tls1.2") << QSsl::TlsV1_3OrLater << QSsl::TlsV1_2 << false;
QTest::newRow("tls1.3orlater-tls1.3") << QSsl::TlsV1_3OrLater << QSsl::TlsV1_3 << true;
}
- QTest::newRow("any-tls1.0") << QSsl::AnyProtocol << QSsl::TlsV1_0 << true;
QTest::newRow("any-secure") << QSsl::AnyProtocol << QSsl::SecureProtocols << true;
}
@@ -1625,8 +1661,6 @@ void tst_QSslSocket::protocolServerSide()
QCOMPARE(client.isEncrypted(), works);
}
-#if QT_CONFIG(openssl)
-
void tst_QSslSocket::serverCipherPreferences()
{
if (!isTestingOpenSsl)
@@ -1636,11 +1670,28 @@ void tst_QSslSocket::serverCipherPreferences()
if (setProxy)
return;
- // First using the default (server preference)
+ QSslCipher testedCiphers[2];
{
+ // First using the default (server preference)
+ const auto supportedCiphers = QSslConfiguration::supportedCiphers();
+ int nSet = 0;
+ for (const auto &cipher : supportedCiphers) {
+ // Ciphersuites from TLS 1.2 and 1.3 are set separately,
+ // let's select 1.3 or above explicitly.
+ if (cipher.protocol() < QSsl::TlsV1_3)
+ continue;
+
+ testedCiphers[nSet++] = cipher;
+ if (nSet == 2)
+ break;
+ }
+
+ if (nSet != 2)
+ QSKIP("Failed to find two proper ciphersuites to test, bailing out.");
+
SslServer server;
- server.protocol = QSsl::TlsV1_0;
- server.ciphers = {QSslCipher("AES128-SHA"), QSslCipher("AES256-SHA")};
+ server.protocol = QSsl::TlsV1_2OrLater;
+ server.ciphers = {testedCiphers[0], testedCiphers[1]};
QVERIFY(server.listen());
QEventLoop loop;
@@ -1650,8 +1701,8 @@ void tst_QSslSocket::serverCipherPreferences()
socket = &client;
auto sslConfig = socket->sslConfiguration();
- sslConfig.setProtocol(QSsl::TlsV1_0OrLater);
- sslConfig.setCiphers({QSslCipher("AES256-SHA"), QSslCipher("AES128-SHA")});
+ sslConfig.setProtocol(QSsl::TlsV1_2OrLater);
+ sslConfig.setCiphers({testedCiphers[1], testedCiphers[0]});
socket->setSslConfiguration(sslConfig);
// upon SSL wrong version error, errorOccurred will be triggered, not sslErrors
@@ -1664,17 +1715,19 @@ void tst_QSslSocket::serverCipherPreferences()
loop.exec();
QVERIFY(client.isEncrypted());
- QCOMPARE(client.sessionCipher().name(), QString("AES128-SHA"));
+ QCOMPARE(client.sessionCipher().name(), testedCiphers[0].name());
}
{
+ if (QTestPrivate::isRunningArmOnX86())
+ QSKIP("This test is known to crash on QEMU emulation for no good reason.");
// Now using the client preferences
SslServer server;
QSslConfiguration config = QSslConfiguration::defaultConfiguration();
config.setSslOption(QSsl::SslOptionDisableServerCipherPreference, true);
server.config = config;
- server.protocol = QSsl::TlsV1_0OrLater;
- server.ciphers = {QSslCipher("AES128-SHA"), QSslCipher("AES256-SHA")};
+ server.protocol = QSsl::TlsV1_2OrLater;
+ server.ciphers = {testedCiphers[0], testedCiphers[1]};
QVERIFY(server.listen());
QEventLoop loop;
@@ -1684,8 +1737,8 @@ void tst_QSslSocket::serverCipherPreferences()
socket = &client;
auto sslConfig = socket->sslConfiguration();
- sslConfig.setProtocol(QSsl::TlsV1_0);
- sslConfig.setCiphers({QSslCipher("AES256-SHA"), QSslCipher("AES128-SHA")});
+ sslConfig.setProtocol(QSsl::TlsV1_2OrLater);
+ sslConfig.setCiphers({testedCiphers[1], testedCiphers[0]});
socket->setSslConfiguration(sslConfig);
// upon SSL wrong version error, errorOccurred will be triggered, not sslErrors
@@ -1698,12 +1751,10 @@ void tst_QSslSocket::serverCipherPreferences()
loop.exec();
QVERIFY(client.isEncrypted());
- QCOMPARE(client.sessionCipher().name(), QString("AES256-SHA"));
+ QCOMPARE(client.sessionCipher().name(), testedCiphers[1].name());
}
}
-#endif // Feature 'openssl'.
-
void tst_QSslSocket::setCaCertificates()
{
@@ -1780,8 +1831,10 @@ void tst_QSslSocket::setLocalCertificateChain()
}
QCOMPARE(chain.size(), 2);
- QCOMPARE(chain[0].serialNumber(), QByteArray("10:a0:ad:77:58:f6:6e:ae:46:93:a3:43:f9:59:8a:9e"));
- QCOMPARE(chain[1].serialNumber(), QByteArray("3b:eb:99:c5:ea:d8:0b:5d:0b:97:5d:4f:06:75:4b:e1"));
+ QCOMPARE(chain[0].serialNumber(),
+ QByteArray("58:df:33:c1:9b:bc:c5:51:7a:00:86:64:43:94:41:e2:26:ef:3f:89"));
+ QCOMPARE(chain[1].serialNumber(),
+ QByteArray("11:72:34:bc:21:e6:ca:04:24:13:f8:35:48:84:a6:e9:de:96:22:15"));
}
void tst_QSslSocket::tlsConfiguration()
@@ -1873,8 +1926,6 @@ void tst_QSslSocket::setSslConfiguration()
QSslSocketPtr socket = newSocket();
QFETCH(QSslConfiguration, configuration);
socket->setSslConfiguration(configuration);
- if (isTestingSchannel) // old certificate not supported with TLS 1.2
- socket->setProtocol(QSsl::SslProtocol::TlsV1_1);
this->socket = socket.data();
socket->connectToHostEncrypted(QtNetworkSettings::httpServerName(), 443);
@@ -1928,13 +1979,17 @@ void tst_QSslSocket::waitForConnectedEncryptedReadyRead()
if (!QSslSocket::supportsSsl())
return;
+ // Starting from OpenSSL v 3.1.1 deprecated protocol versions (we want to use here) are not available by default.
+ if (isSecurityLevel0Required)
+ QSKIP("Testing with OpenSSL backend, but security level 0 is required for TLS v1.1 or earlier");
+
QSslSocketPtr socket = newSocket();
this->socket = socket.data();
// Set TLS 1.0 or above because the server doesn't support TLS 1.2 or above
// QTQAINFRA-4499
QSslConfiguration config = socket->sslConfiguration();
- config.setProtocol(QSsl::TlsV1_0OrLater);
+ config.setProtocol(Test::TlsV1_0OrLater);
socket->setSslConfiguration(config);
connect(this->socket, SIGNAL(sslErrors(QList<QSslError>)), this, SLOT(ignoreErrorSlot()));
@@ -2602,8 +2657,6 @@ void tst_QSslSocket::verifyMode()
return;
QSslSocket socket;
- if (isTestingSchannel) // old certificate not supported with TLS 1.2
- socket.setProtocol(QSsl::SslProtocol::TlsV1_1);
QCOMPARE(socket.peerVerifyMode(), QSslSocket::AutoVerifyPeer);
socket.setPeerVerifyMode(QSslSocket::VerifyNone);
@@ -2783,10 +2836,10 @@ void tst_QSslSocket::closeWhileEmittingSocketError()
// Make sure we have some data buffered so that close will try to flush:
clientSocket.write(QByteArray(1000000, Qt::Uninitialized));
- QTestEventLoop::instance().enterLoopMSecs(1000);
+ QTestEventLoop::instance().enterLoop(1s);
QVERIFY(!QTestEventLoop::instance().timeout());
- QCOMPARE(socketErrorSpy.count(), 1);
+ QCOMPARE(socketErrorSpy.size(), 1);
}
#endif // Feature 'openssl'.
@@ -2883,7 +2936,7 @@ void tst_QSslSocket::ignoreSslErrorsList()
bool expectEncryptionSuccess = (expectedSslErrorSignalCount == 0);
if (socket.waitForEncrypted(10000) != expectEncryptionSuccess)
QSKIP("Skipping flaky test - See QTBUG-29941");
- QCOMPARE(sslErrorsSpy.count(), expectedSslErrorSignalCount);
+ QCOMPARE(sslErrorsSpy.size(), expectedSslErrorSignalCount);
}
void tst_QSslSocket::ignoreSslErrorsListWithSlot_data()
@@ -2944,8 +2997,6 @@ void tst_QSslSocket::abortOnSslErrors()
void tst_QSslSocket::readFromClosedSocket()
{
QSslSocketPtr socket = newSocket();
- if (isTestingSchannel) // old certificate not supported with TLS 1.2
- socket->setProtocol(QSsl::SslProtocol::TlsV1_1);
socket->ignoreSslErrors();
socket->connectToHostEncrypted(QtNetworkSettings::httpServerName(), 443);
@@ -3043,9 +3094,16 @@ void tst_QSslSocket::blacklistedCertificates()
connect(receiver, SIGNAL(encrypted()), SLOT(exitLoop()));
enterLoop(1);
QList<QSslError> sslErrors = receiver->sslHandshakeErrors();
- QVERIFY(sslErrors.count() > 0);
+ QVERIFY(sslErrors.size() > 0);
// there are more errors (self signed cert and hostname mismatch), but we only care about the blacklist error
- QCOMPARE(sslErrors.at(0).error(), QSslError::CertificateBlacklisted);
+ std::optional<QSslError> blacklistedError;
+ for (const QSslError &error : sslErrors) {
+ if (error.error() == QSslError::CertificateBlacklisted) {
+ blacklistedError = error;
+ break;
+ }
+ }
+ QVERIFY2(blacklistedError, "CertificateBlacklisted error not found!");
}
void tst_QSslSocket::versionAccessors()
@@ -3071,6 +3129,10 @@ void tst_QSslSocket::encryptWithoutConnecting()
void tst_QSslSocket::resume_data()
{
+ // Starting from OpenSSL v 3.1.1 deprecated protocol versions (we want to use in 'resume' test) are not available by default.
+ if (isSecurityLevel0Required)
+ QSKIP("Testing with OpenSSL backend, but security level 0 is required for TLS v1.1 or earlier");
+
QTest::addColumn<bool>("ignoreErrorsAfterPause");
QTest::addColumn<QList<QSslError> >("errorsToIgnore");
QTest::addColumn<bool>("expectSuccess");
@@ -3109,7 +3171,7 @@ void tst_QSslSocket::resume()
// Set TLS 1.0 or above because the server doesn't support TLS 1.2 or above
// QTQAINFRA-4499
QSslConfiguration config = socket.sslConfiguration();
- config.setProtocol(QSsl::TlsV1_0OrLater);
+ config.setProtocol(Test::TlsV1_0OrLater);
socket.setSslConfiguration(config);
QSignalSpy sslErrorSpy(&socket, SIGNAL(sslErrors(QList<QSslError>)));
@@ -3127,9 +3189,9 @@ void tst_QSslSocket::resume()
QFETCH_GLOBAL(bool, setProxy);
if (setProxy && QTestEventLoop::instance().timeout())
QSKIP("Skipping flaky test - See QTBUG-29941");
- QCOMPARE(sslErrorSpy.count(), 1);
- QCOMPARE(errorSpy.count(), 0);
- QCOMPARE(encryptedSpy.count(), 0);
+ QCOMPARE(sslErrorSpy.size(), 1);
+ QCOMPARE(errorSpy.size(), 0);
+ QCOMPARE(encryptedSpy.size(), 0);
QVERIFY(!socket.isEncrypted());
if (ignoreErrorsAfterPause) {
if (errorsToIgnore.empty())
@@ -3141,15 +3203,15 @@ void tst_QSslSocket::resume()
QTestEventLoop::instance().enterLoop(10);
QVERIFY(!QTestEventLoop::instance().timeout()); // quit by encrypted() or error() signal
if (expectSuccess) {
- QCOMPARE(encryptedSpy.count(), 1);
+ QCOMPARE(encryptedSpy.size(), 1);
QVERIFY(socket.isEncrypted());
- QCOMPARE(errorSpy.count(), 0);
+ QCOMPARE(errorSpy.size(), 0);
socket.disconnectFromHost();
QVERIFY(socket.waitForDisconnected(10000));
} else {
- QCOMPARE(encryptedSpy.count(), 0);
+ QCOMPARE(encryptedSpy.size(), 0);
QVERIFY(!socket.isEncrypted());
- QCOMPARE(errorSpy.count(), 1);
+ QCOMPARE(errorSpy.size(), 1);
QCOMPARE(socket.error(), QAbstractSocket::SslHandshakeFailedError);
}
}
@@ -3336,17 +3398,17 @@ void tst_QSslSocket::qtbug18498_peek2()
bigblock.fill('#', QIODEVICE_BUFFERSIZE + 1024);
QVERIFY(client->write(QByteArray("head")));
QVERIFY(client->write(bigblock));
- QTRY_COMPARE(server->bytesAvailable(), bigblock.length() + 4);
+ QTRY_COMPARE(server->bytesAvailable(), bigblock.size() + 4);
QCOMPARE(server->read(4), QByteArray("head"));
- QCOMPARE(server->peek(bigblock.length()), bigblock);
- b.reserve(bigblock.length());
- b.resize(server->peek(b.data(), bigblock.length()));
+ QCOMPARE(server->peek(bigblock.size()), bigblock);
+ b.reserve(bigblock.size());
+ b.resize(server->peek(b.data(), bigblock.size()));
QCOMPARE(b, bigblock);
//check oversized peek
- QCOMPARE(server->peek(bigblock.length() * 3), bigblock);
- b.reserve(bigblock.length() * 3);
- b.resize(server->peek(b.data(), bigblock.length() * 3));
+ QCOMPARE(server->peek(bigblock.size() * 3), bigblock);
+ b.reserve(bigblock.size() * 3);
+ b.resize(server->peek(b.data(), bigblock.size() * 3));
QCOMPARE(b, bigblock);
QCOMPARE(server->readAll(), bigblock);
@@ -3414,7 +3476,13 @@ void tst_QSslSocket::dhServer()
return;
SslServer server;
- server.ciphers = {QSslCipher("DHE-RSA-AES256-SHA"), QSslCipher("DHE-DSS-AES256-SHA")};
+ QSslCipher rsaCipher("DHE-RSA-AES256-SHA");
+ QSslCipher dssCipher("DHE-DSS-AES256-SHA");
+ if (rsaCipher.isNull())
+ QSKIP("The current backend doesn't support DHE-RSA-AES256-SHA");
+ if (dssCipher.isNull())
+ QSKIP("The current backend doesn't support DHE-DSS-AES256-SHA");
+ server.ciphers = { rsaCipher, dssCipher };
QVERIFY(server.listen());
QEventLoop loop;
@@ -3442,9 +3510,10 @@ void tst_QSslSocket::dhServerCustomParamsNull()
if (setProxy)
return;
+ const QSslCipher cipherWithDH("DHE-RSA-AES256-SHA256");
SslServer server;
- server.ciphers = {QSslCipher("DHE-RSA-AES256-SHA"), QSslCipher("DHE-DSS-AES256-SHA")};
- server.protocol = QSsl::TlsV1_0;
+ server.ciphers = {cipherWithDH};
+ server.protocol = QSsl::TlsV1_2;
QSslConfiguration cfg = server.config;
cfg.setDiffieHellmanParameters(QSslDiffieHellmanParameters());
@@ -3457,7 +3526,6 @@ void tst_QSslSocket::dhServerCustomParamsNull()
QSslSocket client;
QSslConfiguration config = client.sslConfiguration();
- config.setProtocol(QSsl::TlsV1_0);
client.setSslConfiguration(config);
socket = &client;
connect(socket, SIGNAL(errorOccurred(QAbstractSocket::SocketError)), &loop, SLOT(quit()));
@@ -3468,20 +3536,25 @@ void tst_QSslSocket::dhServerCustomParamsNull()
loop.exec();
- QVERIFY(client.state() != QAbstractSocket::ConnectedState);
+ QCOMPARE(client.state(), QAbstractSocket::ConnectedState);
+ QCOMPARE(client.sessionCipher(), cipherWithDH);
}
void tst_QSslSocket::dhServerCustomParams()
{
if (!QSslSocket::supportsSsl())
QSKIP("No SSL support");
+ if (!QSslSocket::isClassImplemented(QSsl::ImplementedClass::DiffieHellman))
+ QSKIP("The current backend doesn't support diffie hellman parameters");
QFETCH_GLOBAL(bool, setProxy);
if (setProxy)
return;
SslServer server;
- server.ciphers = {QSslCipher("DHE-RSA-AES256-SHA"), QSslCipher("DHE-DSS-AES256-SHA")};
+ const QSslCipher cipherWithDH("DHE-RSA-AES256-SHA256");
+ server.ciphers = {cipherWithDH};
+ server.protocol = QSsl::TlsV1_2;
QSslConfiguration cfg = server.config;
@@ -3511,7 +3584,8 @@ void tst_QSslSocket::dhServerCustomParams()
loop.exec();
- QVERIFY(client.state() == QAbstractSocket::ConnectedState);
+ QCOMPARE(client.state(), QAbstractSocket::ConnectedState);
+ QCOMPARE(client.sessionCipher(), cipherWithDH);
}
#endif // QT_CONFIG(openssl)
@@ -3527,7 +3601,10 @@ void tst_QSslSocket::ecdhServer()
return;
SslServer server;
- server.ciphers = {QSslCipher("ECDHE-RSA-AES128-SHA")};
+ QSslCipher cipher("ECDHE-RSA-AES128-SHA");
+ if (cipher.isNull())
+ QSKIP("The current backend doesn't support ECDHE-RSA-AES128-SHA");
+ server.ciphers = {cipher};
QVERIFY(server.listen());
QEventLoop loop;
@@ -3640,7 +3717,7 @@ void tst_QSslSocket::verifyClientCertificate()
}
SslServer server;
- server.protocol = QSsl::TlsV1_0;
+ server.protocol = QSsl::TlsV1_2;
server.addCaCertificates = testDataDir + "certs/bogus-ca.crt";
server.ignoreSslErrors = false;
server.peerVerifyMode = peerVerifyMode;
@@ -3655,7 +3732,7 @@ void tst_QSslSocket::verifyClientCertificate()
client.setLocalCertificateChain(clientCerts);
client.setPrivateKey(clientKey);
QSslConfiguration config = client.sslConfiguration();
- config.setProtocol(QSsl::TlsV1_0OrLater);
+ config.setProtocol(Test::TlsV1_0OrLater);
client.setSslConfiguration(config);
socket = &client;
@@ -3682,7 +3759,7 @@ void tst_QSslSocket::verifyClientCertificate()
} else {
QCOMPARE(server.socket->peerCertificate(), clientCerts.first());
if (isTestingSchannel) {
- if (clientCerts.count() == 1 && server.socket->peerCertificateChain().count() == 2) {
+ if (clientCerts.size() == 1 && server.socket->peerCertificateChain().size() == 2) {
QEXPECT_FAIL("",
"Schannel includes the entire chain, not just the leaf and intermediates",
Continue);
@@ -4042,14 +4119,14 @@ void tst_QSslSocket::simplePskConnect()
case PskConnectWrongCredentials:
// provide totally wrong credentials
- provider.setIdentity(PSK_CLIENT_IDENTITY.left(PSK_CLIENT_IDENTITY.length() - 1));
- provider.setPreSharedKey(PSK_CLIENT_PRESHAREDKEY.left(PSK_CLIENT_PRESHAREDKEY.length() - 1));
+ provider.setIdentity(PSK_CLIENT_IDENTITY.left(PSK_CLIENT_IDENTITY.size() - 1));
+ provider.setPreSharedKey(PSK_CLIENT_PRESHAREDKEY.left(PSK_CLIENT_PRESHAREDKEY.size() - 1));
connect(&socket, SIGNAL(preSharedKeyAuthenticationRequired(QSslPreSharedKeyAuthenticator*)), &provider, SLOT(providePsk(QSslPreSharedKeyAuthenticator*)));
break;
case PskConnectWrongIdentity:
// right PSK, wrong identity
- provider.setIdentity(PSK_CLIENT_IDENTITY.left(PSK_CLIENT_IDENTITY.length() - 1));
+ provider.setIdentity(PSK_CLIENT_IDENTITY.left(PSK_CLIENT_IDENTITY.size() - 1));
provider.setPreSharedKey(PSK_CLIENT_PRESHAREDKEY);
connect(&socket, SIGNAL(preSharedKeyAuthenticationRequired(QSslPreSharedKeyAuthenticator*)), &provider, SLOT(providePsk(QSslPreSharedKeyAuthenticator*)));
break;
@@ -4057,7 +4134,7 @@ void tst_QSslSocket::simplePskConnect()
case PskConnectWrongPreSharedKey:
// right identity, wrong PSK
provider.setIdentity(PSK_CLIENT_IDENTITY);
- provider.setPreSharedKey(PSK_CLIENT_PRESHAREDKEY.left(PSK_CLIENT_PRESHAREDKEY.length() - 1));
+ provider.setPreSharedKey(PSK_CLIENT_PRESHAREDKEY.left(PSK_CLIENT_PRESHAREDKEY.size() - 1));
connect(&socket, SIGNAL(preSharedKeyAuthenticationRequired(QSslPreSharedKeyAuthenticator*)), &provider, SLOT(providePsk(QSslPreSharedKeyAuthenticator*)));
break;
@@ -4109,32 +4186,32 @@ void tst_QSslSocket::simplePskConnect()
// Entered connecting state
QCOMPARE(socket.state(), QAbstractSocket::ConnectingState);
- QCOMPARE(connectedSpy.count(), 0);
- QCOMPARE(hostFoundSpy.count(), 1);
- QCOMPARE(disconnectedSpy.count(), 0);
+ QCOMPARE(connectedSpy.size(), 0);
+ QCOMPARE(hostFoundSpy.size(), 1);
+ QCOMPARE(disconnectedSpy.size(), 0);
enterLoop(10);
// Entered connected state
QCOMPARE(socket.state(), QAbstractSocket::ConnectedState);
QCOMPARE(socket.mode(), QSslSocket::UnencryptedMode);
QVERIFY(!socket.isEncrypted());
- QCOMPARE(connectedSpy.count(), 1);
- QCOMPARE(hostFoundSpy.count(), 1);
- QCOMPARE(disconnectedSpy.count(), 0);
+ QCOMPARE(connectedSpy.size(), 1);
+ QCOMPARE(hostFoundSpy.size(), 1);
+ QCOMPARE(disconnectedSpy.size(), 0);
// Enter encrypted mode
socket.startClientEncryption();
QCOMPARE(socket.mode(), QSslSocket::SslClientMode);
QVERIFY(!socket.isEncrypted());
- QCOMPARE(connectionEncryptedSpy.count(), 0);
- QCOMPARE(sslErrorsSpy.count(), 0);
- QCOMPARE(peerVerifyErrorSpy.count(), 0);
+ QCOMPARE(connectionEncryptedSpy.size(), 0);
+ QCOMPARE(sslErrorsSpy.size(), 0);
+ QCOMPARE(peerVerifyErrorSpy.size(), 0);
// Start handshake.
enterLoop(10);
// We must get the PSK signal in all cases
- QCOMPARE(pskAuthenticationRequiredSpy.count(), 1);
+ QCOMPARE(pskAuthenticationRequiredSpy.size(), 1);
switch (pskTestType) {
case PskConnectDoNotHandlePsk:
@@ -4143,40 +4220,40 @@ void tst_QSslSocket::simplePskConnect()
case PskConnectWrongIdentity:
case PskConnectWrongPreSharedKey:
// Handshake failure
- QCOMPARE(socketErrorsSpy.count(), 1);
+ QCOMPARE(socketErrorsSpy.size(), 1);
QCOMPARE(qvariant_cast<QAbstractSocket::SocketError>(socketErrorsSpy.at(0).at(0)), QAbstractSocket::SslHandshakeFailedError);
- QCOMPARE(sslErrorsSpy.count(), 0);
- QCOMPARE(peerVerifyErrorSpy.count(), 0);
- QCOMPARE(connectionEncryptedSpy.count(), 0);
+ QCOMPARE(sslErrorsSpy.size(), 0);
+ QCOMPARE(peerVerifyErrorSpy.size(), 0);
+ QCOMPARE(connectionEncryptedSpy.size(), 0);
QVERIFY(!socket.isEncrypted());
break;
case PskConnectRightCredentialsPeerVerifyFailure:
// Peer verification failure
- QCOMPARE(socketErrorsSpy.count(), 1);
+ QCOMPARE(socketErrorsSpy.size(), 1);
QCOMPARE(qvariant_cast<QAbstractSocket::SocketError>(socketErrorsSpy.at(0).at(0)), QAbstractSocket::SslHandshakeFailedError);
- QCOMPARE(sslErrorsSpy.count(), 1);
- QCOMPARE(peerVerifyErrorSpy.count(), 1);
- QCOMPARE(connectionEncryptedSpy.count(), 0);
+ QCOMPARE(sslErrorsSpy.size(), 1);
+ QCOMPARE(peerVerifyErrorSpy.size(), 1);
+ QCOMPARE(connectionEncryptedSpy.size(), 0);
QVERIFY(!socket.isEncrypted());
break;
case PskConnectRightCredentialsVerifyPeer:
// Peer verification failure, but ignore it and keep connecting
- QCOMPARE(socketErrorsSpy.count(), 0);
- QCOMPARE(sslErrorsSpy.count(), 1);
- QCOMPARE(peerVerifyErrorSpy.count(), 1);
- QCOMPARE(connectionEncryptedSpy.count(), 1);
+ QCOMPARE(socketErrorsSpy.size(), 0);
+ QCOMPARE(sslErrorsSpy.size(), 1);
+ QCOMPARE(peerVerifyErrorSpy.size(), 1);
+ QCOMPARE(connectionEncryptedSpy.size(), 1);
QVERIFY(socket.isEncrypted());
QCOMPARE(socket.state(), QAbstractSocket::ConnectedState);
break;
case PskConnectRightCredentialsDoNotVerifyPeer:
// No peer verification => no failure
- QCOMPARE(socketErrorsSpy.count(), 0);
- QCOMPARE(sslErrorsSpy.count(), 0);
- QCOMPARE(peerVerifyErrorSpy.count(), 0);
- QCOMPARE(connectionEncryptedSpy.count(), 1);
+ QCOMPARE(socketErrorsSpy.size(), 0);
+ QCOMPARE(sslErrorsSpy.size(), 0);
+ QCOMPARE(peerVerifyErrorSpy.size(), 0);
+ QCOMPARE(connectionEncryptedSpy.size(), 1);
QVERIFY(socket.isEncrypted());
QCOMPARE(socket.state(), QAbstractSocket::ConnectedState);
break;
@@ -4217,7 +4294,7 @@ void tst_QSslSocket::simplePskConnect()
}
QCOMPARE(socket.state(), QAbstractSocket::UnconnectedState);
- QCOMPARE(disconnectedSpy.count(), 1);
+ QCOMPARE(disconnectedSpy.size(), 1);
}
void tst_QSslSocket::ephemeralServerKey_data()
@@ -4250,7 +4327,7 @@ void tst_QSslSocket::ephemeralServerKey()
client->connectToHostEncrypted(QHostAddress(QHostAddress::LocalHost).toString(), server.serverPort());
spy.wait();
- QCOMPARE(spy.count(), 1);
+ QCOMPARE(spy.size(), 1);
QVERIFY(server.config.ephemeralServerKey().isNull());
QCOMPARE(client->sslConfiguration().ephemeralServerKey().isNull(), emptyKey);
}
@@ -4313,22 +4390,22 @@ void tst_QSslSocket::pskServer()
QCOMPARE(socket.state(), QAbstractSocket::ConnectedState);
QCOMPARE(socket.mode(), QSslSocket::UnencryptedMode);
QVERIFY(!socket.isEncrypted());
- QCOMPARE(connectedSpy.count(), 1);
- QCOMPARE(disconnectedSpy.count(), 0);
+ QCOMPARE(connectedSpy.size(), 1);
+ QCOMPARE(disconnectedSpy.size(), 0);
// Enter encrypted mode
socket.startClientEncryption();
QCOMPARE(socket.mode(), QSslSocket::SslClientMode);
QVERIFY(!socket.isEncrypted());
- QCOMPARE(connectionEncryptedSpy.count(), 0);
+ QCOMPARE(connectionEncryptedSpy.size(), 0);
// Start handshake.
enterLoop(10);
// We must get the PSK signal in all cases
- QCOMPARE(pskAuthenticationRequiredSpy.count(), 1);
+ QCOMPARE(pskAuthenticationRequiredSpy.size(), 1);
- QCOMPARE(connectionEncryptedSpy.count(), 1);
+ QCOMPARE(connectionEncryptedSpy.size(), 1);
QVERIFY(socket.isEncrypted());
QCOMPARE(socket.state(), QAbstractSocket::ConnectedState);
@@ -4341,7 +4418,7 @@ void tst_QSslSocket::pskServer()
enterLoop(10);
QCOMPARE(socket.state(), QAbstractSocket::UnconnectedState);
- QCOMPARE(disconnectedSpy.count(), 1);
+ QCOMPARE(disconnectedSpy.size(), 1);
}
void tst_QSslSocket::signatureAlgorithm_data()
@@ -4413,7 +4490,7 @@ void tst_QSslSocket::signatureAlgorithm_data()
// signature algorithms do not match, but are ignored because the tls version is not v1.2
QTest::newRow("client_ignore_TlsV1_1")
<< QByteArrayList({rsaSha256})
- << QSsl::TlsV1_1
+ << Test::TlsV1_1
<< QByteArrayList({rsaSha512})
<< QSsl::AnyProtocol
<< QAbstractSocket::ConnectedState;
@@ -4421,11 +4498,11 @@ void tst_QSslSocket::signatureAlgorithm_data()
<< QByteArrayList({rsaSha256})
<< QSsl::AnyProtocol
<< QByteArrayList({rsaSha512})
- << QSsl::TlsV1_1
+ << Test::TlsV1_1
<< QAbstractSocket::ConnectedState;
QTest::newRow("client_ignore_TlsV1_0")
<< QByteArrayList({rsaSha256})
- << QSsl::TlsV1_0
+ << Test::TlsV1_0
<< QByteArrayList({rsaSha512})
<< QSsl::AnyProtocol
<< QAbstractSocket::ConnectedState;
@@ -4433,7 +4510,7 @@ void tst_QSslSocket::signatureAlgorithm_data()
<< QByteArrayList({rsaSha256})
<< QSsl::AnyProtocol
<< QByteArrayList({rsaSha512})
- << QSsl::TlsV1_0
+ << Test::TlsV1_0
<< QAbstractSocket::ConnectedState;
}
@@ -4494,7 +4571,7 @@ void tst_QSslSocket::forwardReadChannelFinished()
&QTestEventLoop::instance(), &QTestEventLoop::exitLoop);
socket.connectToHostEncrypted(QtNetworkSettings::httpServerName(), 443);
enterLoop(10);
- QVERIFY(readChannelFinishedSpy.count());
+ QVERIFY(readChannelFinishedSpy.size());
}
#endif // QT_CONFIG(openssl)
@@ -4502,9 +4579,9 @@ void tst_QSslSocket::forwardReadChannelFinished()
void tst_QSslSocket::unsupportedProtocols_data()
{
QTest::addColumn<QSsl::SslProtocol>("unsupportedProtocol");
- QTest::newRow("DtlsV1_0") << QSsl::DtlsV1_0;
+ QTest::newRow("DtlsV1_0") << Test::DtlsV1_0;
QTest::newRow("DtlsV1_2") << QSsl::DtlsV1_2;
- QTest::newRow("DtlsV1_0OrLater") << QSsl::DtlsV1_0OrLater;
+ QTest::newRow("DtlsV1_0OrLater") << Test::DtlsV1_0OrLater;
QTest::newRow("DtlsV1_2OrLater") << QSsl::DtlsV1_2OrLater;
QTest::newRow("UnknownProtocol") << QSsl::UnknownProtocol;
}
@@ -4516,7 +4593,7 @@ void tst_QSslSocket::unsupportedProtocols()
return;
QFETCH(const QSsl::SslProtocol, unsupportedProtocol);
- const int timeoutMS = 500;
+ constexpr auto timeout = 500ms;
// Test a client socket.
{
// 0. connectToHostEncrypted: client-side, non-blocking API, error is discovered
@@ -4538,7 +4615,7 @@ void tst_QSslSocket::unsupportedProtocols()
QCOMPARE(socket.error(), QAbstractSocket::UnknownSocketError);
socket.connectToHost(QHostAddress::LocalHost, server.serverPort());
- QVERIFY(socket.waitForConnected(timeoutMS));
+ QVERIFY(socket.waitForConnected(int(timeout.count())));
socket.setProtocol(unsupportedProtocol);
socket.startClientEncryption();
@@ -4563,7 +4640,7 @@ void tst_QSslSocket::unsupportedProtocols()
QTcpSocket client;
client.connectToHost(QHostAddress::LocalHost, server.serverPort());
- loop.enterLoopMSecs(timeoutMS);
+ loop.enterLoop(timeout);
QVERIFY(!loop.timeout());
QVERIFY(server.socket);
QCOMPARE(server.socket->error(), QAbstractSocket::SslInvalidUserDataError);
@@ -4576,13 +4653,15 @@ void tst_QSslSocket::oldErrorsOnSocketReuse()
if (setProxy)
return; // not relevant
SslServer server;
- server.protocol = QSsl::TlsV1_1;
+ if (!isTestingOpenSsl)
+ server.protocol = Test::TlsV1_1;
server.m_certFile = testDataDir + "certs/fluke.cert";
server.m_keyFile = testDataDir + "certs/fluke.key";
QVERIFY(server.listen(QHostAddress::SpecialAddress::LocalHost));
QSslSocket socket;
- socket.setProtocol(QSsl::TlsV1_1);
+ if (!isTestingOpenSsl)
+ socket.setProtocol(Test::TlsV1_1);
QList<QSslError> errorList;
auto connection = connect(&socket, QOverload<const QList<QSslError> &>::of(&QSslSocket::sslErrors),
[&socket, &errorList](const QList<QSslError> &errors) {
@@ -4668,7 +4747,7 @@ void tst_QSslSocket::alertMissingCertificate()
connect(&clientSocket, &QAbstractSocket::errorOccurred, earlyQuitter);
connect(&server, &SslServer::socketError, earlyQuitter);
- runner.enterLoopMSecs(1000);
+ runner.enterLoop(1s);
if (clientSocket.isEncrypted()) {
// When using TLS 1.3 the client side thinks it is connected very
@@ -4676,11 +4755,11 @@ void tst_QSslSocket::alertMissingCertificate()
// inevitable disconnect.
QCOMPARE(clientSocket.sessionProtocol(), QSsl::TlsV1_3);
connect(&clientSocket, &QSslSocket::disconnected, &runner, &QTestEventLoop::exitLoop);
- runner.enterLoopMSecs(10000);
+ runner.enterLoop(10s);
}
- QVERIFY(serverSpy.count() > 0);
- QVERIFY(clientSpy.count() > 0);
+ QVERIFY(serverSpy.size() > 0);
+ QVERIFY(clientSpy.size() > 0);
QVERIFY(server.socket && !server.socket->isEncrypted());
QVERIFY(!clientSocket.isEncrypted());
}
@@ -4731,11 +4810,11 @@ void tst_QSslSocket::alertInvalidCertificate()
connect(&clientSocket, &QAbstractSocket::errorOccurred, earlyQuitter);
connect(&server, &SslServer::socketError, earlyQuitter);
- runner.enterLoopMSecs(1000);
+ runner.enterLoop(1s);
- QVERIFY(serverSpy.count() > 0);
- QVERIFY(clientSpy.count() > 0);
- QVERIFY(interruptedSpy.count() > 0);
+ QVERIFY(serverSpy.size() > 0);
+ QVERIFY(clientSpy.size() > 0);
+ QVERIFY(interruptedSpy.size() > 0);
QVERIFY(server.socket && !server.socket->isEncrypted());
QVERIFY(!clientSocket.isEncrypted());
}
@@ -4859,17 +4938,17 @@ void tst_QSslSocket::selfSignedCertificates()
connect(&clientSocket, &QAbstractSocket::errorOccurred, earlyQuitter);
connect(&server, &SslServer::socketError, earlyQuitter);
- runner.enterLoopMSecs(1000);
+ runner.enterLoop(1s);
if (clientKnown) {
- QCOMPARE(serverSpy.count(), 0);
- QCOMPARE(clientSpy.count(), 0);
+ QCOMPARE(serverSpy.size(), 0);
+ QCOMPARE(clientSpy.size(), 0);
QVERIFY(server.socket && server.socket->isEncrypted());
QVERIFY(clientSocket.isEncrypted());
} else {
- QVERIFY(serverSpy.count() > 0);
+ QVERIFY(serverSpy.size() > 0);
QEXPECT_FAIL("", "Failing to trigger signal, QTBUG-81661", Continue);
- QVERIFY(clientSpy.count() > 0);
+ QVERIFY(clientSpy.size() > 0);
QVERIFY(server.socket && !server.socket->isEncrypted());
QVERIFY(!clientSocket.isEncrypted());
}
@@ -4997,18 +5076,18 @@ void tst_QSslSocket::pskHandshake()
connect(&clientSocket, &QAbstractSocket::errorOccurred, earlyQuitter);
connect(&server, &SslServer::socketError, earlyQuitter);
- runner.enterLoopMSecs(1000);
+ runner.enterLoop(1s);
if (pskRight) {
- QCOMPARE(serverSpy.count(), 0);
- QCOMPARE(clientSpy.count(), 0);
+ QCOMPARE(serverSpy.size(), 0);
+ QCOMPARE(clientSpy.size(), 0);
QVERIFY(server.socket && server.socket->isEncrypted());
QVERIFY(clientSocket.isEncrypted());
} else {
- QVERIFY(serverSpy.count() > 0);
+ QVERIFY(serverSpy.size() > 0);
QCOMPARE(serverSpy.first().at(0).toInt(), static_cast<int>(QSsl::AlertLevel::Fatal));
QCOMPARE(serverSpy.first().at(1).toInt(), static_cast<int>(QSsl::AlertType::BadRecordMac));
- QVERIFY(clientSpy.count() > 0);
+ QVERIFY(clientSpy.size() > 0);
QCOMPARE(clientSpy.first().at(0).toInt(), static_cast<int>(QSsl::AlertLevel::Fatal));
QCOMPARE(clientSpy.first().at(1).toInt(), static_cast<int>(QSsl::AlertType::BadRecordMac));
QVERIFY(server.socket && !server.socket->isEncrypted());
diff --git a/tests/auto/network/ssl/qsslsocket_onDemandCertificates_member/BLACKLIST b/tests/auto/network/ssl/qsslsocket_onDemandCertificates_member/BLACKLIST
new file mode 100644
index 0000000000..96d94bd935
--- /dev/null
+++ b/tests/auto/network/ssl/qsslsocket_onDemandCertificates_member/BLACKLIST
@@ -0,0 +1,7 @@
+# QTBUG-101274
+# [onDemandRootCertLoadingMemberMethods:WithoutProxy]
+# qnx ci
+
+# QTBUG-63481
+[onDemandRootCertLoadingMemberMethods]
+*
diff --git a/tests/auto/network/ssl/qsslsocket_onDemandCertificates_member/CMakeLists.txt b/tests/auto/network/ssl/qsslsocket_onDemandCertificates_member/CMakeLists.txt
index 8c897caa70..34e026cb8b 100644
--- a/tests/auto/network/ssl/qsslsocket_onDemandCertificates_member/CMakeLists.txt
+++ b/tests/auto/network/ssl/qsslsocket_onDemandCertificates_member/CMakeLists.txt
@@ -1,4 +1,11 @@
-# Generated from qsslsocket_onDemandCertificates_member.pro.
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
+
+if(NOT QT_BUILD_STANDALONE_TESTS AND NOT QT_BUILDING_QT)
+ cmake_minimum_required(VERSION 3.16)
+ project(tst_qsslsocket_onDemandCertificates_member LANGUAGES CXX)
+ find_package(Qt6BuildInternals REQUIRED COMPONENTS STANDALONE_TEST)
+endif()
if(NOT QT_FEATURE_private_tests)
return()
@@ -11,24 +18,9 @@ endif()
qt_internal_add_test(tst_qsslsocket_onDemandCertificates_member
SOURCES
tst_qsslsocket_onDemandCertificates_member.cpp
- PUBLIC_LIBRARIES
+ LIBRARIES
Qt::CorePrivate
Qt::NetworkPrivate
- QT_TEST_SERVER_LIST "squid" "danted" # special case
+ QT_TEST_SERVER_LIST "squid" "danted"
+ BUNDLE_ANDROID_OPENSSL_LIBS
)
-
-#### Keys ignored in scope 1:.:.:qsslsocket_onDemandCertificates_member.pro:<TRUE>:
-# _REQUIREMENTS = "qtConfig(private_tests)"
-# testcase.timeout = "300"
-
-## Scopes:
-#####################################################################
-
-#### Keys ignored in scope 3:.:.:qsslsocket_onDemandCertificates_member.pro:(CMAKE_BUILD_TYPE STREQUAL Debug):
-# DESTDIR = "debug"
-
-#### Keys ignored in scope 4:.:.:qsslsocket_onDemandCertificates_member.pro:else:
-# DESTDIR = "release"
-
-#### Keys ignored in scope 5:.:.:qsslsocket_onDemandCertificates_member.pro:LINUX:
-# QT_TEST_SERVER_LIST = "squid" "danted"
diff --git a/tests/auto/network/ssl/qsslsocket_onDemandCertificates_member/tst_qsslsocket_onDemandCertificates_member.cpp b/tests/auto/network/ssl/qsslsocket_onDemandCertificates_member/tst_qsslsocket_onDemandCertificates_member.cpp
index 759fad6a02..119891c916 100644
--- a/tests/auto/network/ssl/qsslsocket_onDemandCertificates_member/tst_qsslsocket_onDemandCertificates_member.cpp
+++ b/tests/auto/network/ssl/qsslsocket_onDemandCertificates_member/tst_qsslsocket_onDemandCertificates_member.cpp
@@ -1,30 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
#include <QtNetwork>
@@ -219,6 +194,7 @@ static bool waitForEncrypted(QSslSocket *socket)
void tst_QSslSocket_onDemandCertificates_member::onDemandRootCertLoadingMemberMethods()
{
+#define ERR(socket) socket->errorString().toLatin1()
const QString host("www.qt.io");
// not using any root certs -> should not work
@@ -228,13 +204,13 @@ void tst_QSslSocket_onDemandCertificates_member::onDemandRootCertLoadingMemberMe
sslConfig.setCaCertificates(QList<QSslCertificate>());
socket2->setSslConfiguration(sslConfig);
socket2->connectToHostEncrypted(host, 443);
- QVERIFY(!waitForEncrypted(socket2.data()));
+ QVERIFY2(!waitForEncrypted(socket2.data()), ERR(socket2));
// default: using on demand loading -> should work
QSslSocketPtr socket = newSocket();
this->socket = socket.data();
socket->connectToHostEncrypted(host, 443);
- QVERIFY2(waitForEncrypted(socket.data()), qPrintable(socket->errorString()));
+ QVERIFY2(waitForEncrypted(socket.data()), ERR(socket));
// not using any root certs again -> should not work
QSslSocketPtr socket3 = newSocket();
@@ -243,7 +219,7 @@ void tst_QSslSocket_onDemandCertificates_member::onDemandRootCertLoadingMemberMe
sslConfig.setCaCertificates(QList<QSslCertificate>());
socket3->setSslConfiguration(sslConfig);
socket3->connectToHostEncrypted(host, 443);
- QVERIFY(!waitForEncrypted(socket3.data()));
+ QVERIFY2(!waitForEncrypted(socket3.data()), ERR(socket3));
// setting empty SSL configuration explicitly -> depends on on-demand loading
QSslSocketPtr socket4 = newSocket();
@@ -254,16 +230,20 @@ void tst_QSslSocket_onDemandCertificates_member::onDemandRootCertLoadingMemberMe
#ifdef QT_BUILD_INTERNAL
const bool works = QSslSocketPrivate::rootCertOnDemandLoadingSupported();
#if defined(Q_OS_LINUX) || defined(Q_OS_WIN)
- QCOMPARE(works, true);
+ QVERIFY2(works, ERR(socket4));
#elif defined(Q_OS_MAC)
- QCOMPARE(works, false);
+ QVERIFY2(!works, ERR(socket4));
#endif // other platforms: undecided.
// When we *allow* on-demand loading, we enable it by default; so, on Unix,
// it will work without setting any certificates. Otherwise, the configuration
// contains an empty set of certificates, so on-demand loading shall fail.
- QCOMPARE(waitForEncrypted(socket4.data()), works);
+ const bool result = waitForEncrypted(socket4.data());
+ if (result != works)
+ qDebug() << socket4->errorString();
+ QCOMPARE(waitForEncrypted(socket4.data()), works);
#endif // QT_BUILD_INTERNAL
}
+#undef ERR
#endif // QT_NO_OPENSSL
diff --git a/tests/auto/network/ssl/qsslsocket_onDemandCertificates_static/BLACKLIST b/tests/auto/network/ssl/qsslsocket_onDemandCertificates_static/BLACKLIST
deleted file mode 100644
index 52bd2bc86d..0000000000
--- a/tests/auto/network/ssl/qsslsocket_onDemandCertificates_static/BLACKLIST
+++ /dev/null
@@ -1,2 +0,0 @@
-[onDemandRootCertLoadingStaticMethods:WithSocks5ProxyAuth]
-windows
diff --git a/tests/auto/network/ssl/qsslsocket_onDemandCertificates_static/CMakeLists.txt b/tests/auto/network/ssl/qsslsocket_onDemandCertificates_static/CMakeLists.txt
index b9340c338e..696eec98ee 100644
--- a/tests/auto/network/ssl/qsslsocket_onDemandCertificates_static/CMakeLists.txt
+++ b/tests/auto/network/ssl/qsslsocket_onDemandCertificates_static/CMakeLists.txt
@@ -1,4 +1,11 @@
-# Generated from qsslsocket_onDemandCertificates_static.pro.
+# Copyright (C) 2022 The Qt Company Ltd.
+# SPDX-License-Identifier: BSD-3-Clause
+
+if(NOT QT_BUILD_STANDALONE_TESTS AND NOT QT_BUILDING_QT)
+ cmake_minimum_required(VERSION 3.16)
+ project(tst_qsslsocket_onDemandCertificates_static LANGUAGES CXX)
+ find_package(Qt6BuildInternals REQUIRED COMPONENTS STANDALONE_TEST)
+endif()
if(NOT QT_FEATURE_private_tests)
return()
@@ -11,23 +18,9 @@ endif()
qt_internal_add_test(tst_qsslsocket_onDemandCertificates_static
SOURCES
tst_qsslsocket_onDemandCertificates_static.cpp
- PUBLIC_LIBRARIES
+ LIBRARIES
Qt::CorePrivate
Qt::NetworkPrivate
- QT_TEST_SERVER_LIST "squid" "danted" # special case
+ QT_TEST_SERVER_LIST "squid" "danted"
+ BUNDLE_ANDROID_OPENSSL_LIBS
)
-
-#### Keys ignored in scope 1:.:.:qsslsocket_onDemandCertificates_static.pro:<TRUE>:
-# _REQUIREMENTS = "qtConfig(private_tests)"
-
-## Scopes:
-#####################################################################
-
-#### Keys ignored in scope 3:.:.:qsslsocket_onDemandCertificates_static.pro:(CMAKE_BUILD_TYPE STREQUAL Debug):
-# DESTDIR = "debug"
-
-#### Keys ignored in scope 4:.:.:qsslsocket_onDemandCertificates_static.pro:else:
-# DESTDIR = "release"
-
-#### Keys ignored in scope 5:.:.:qsslsocket_onDemandCertificates_static.pro:LINUX:
-# QT_TEST_SERVER_LIST = "squid" "danted"
diff --git a/tests/auto/network/ssl/qsslsocket_onDemandCertificates_static/tst_qsslsocket_onDemandCertificates_static.cpp b/tests/auto/network/ssl/qsslsocket_onDemandCertificates_static/tst_qsslsocket_onDemandCertificates_static.cpp
index bbcdb5b13f..c5475da581 100644
--- a/tests/auto/network/ssl/qsslsocket_onDemandCertificates_static/tst_qsslsocket_onDemandCertificates_static.cpp
+++ b/tests/auto/network/ssl/qsslsocket_onDemandCertificates_static/tst_qsslsocket_onDemandCertificates_static.cpp
@@ -1,30 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2016 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
#include <QtNetwork>
diff --git a/tests/auto/network/ssl/shared/qopenssl_symbols.h b/tests/auto/network/ssl/shared/qopenssl_symbols.h
index 4b6d1e6407..c98e90d424 100644
--- a/tests/auto/network/ssl/shared/qopenssl_symbols.h
+++ b/tests/auto/network/ssl/shared/qopenssl_symbols.h
@@ -1,42 +1,6 @@
-/****************************************************************************
-**
-** Copyright (C) 2021 The Qt Company Ltd.
-** Copyright (C) 2014 BlackBerry Limited. All rights reserved.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the QtNetwork module of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:LGPL$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU Lesser General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU Lesser
-** General Public License version 3 as published by the Free Software
-** Foundation and appearing in the file LICENSE.LGPL3 included in the
-** packaging of this file. Please review the following information to
-** ensure the GNU Lesser General Public License version 3 requirements
-** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 2.0 or (at your option) the GNU General
-** Public license version 3 or any later version approved by the KDE Free
-** Qt Foundation. The licenses are as published by the Free Software
-** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-2.0.html and
-** https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2021 The Qt Company Ltd.
+// Copyright (C) 2014 BlackBerry Limited. All rights reserved.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
/****************************************************************************
**
@@ -71,6 +35,7 @@
// reduced to the needs of our auto-tests, that have to mess with
// OpenSSL calls directly.
+#include <QtCore/qset.h>
#include <QtNetwork/private/qtnetworkglobal_p.h>
QT_REQUIRE_CONFIG(openssl);
@@ -440,7 +405,7 @@ struct LibGreaterThan
{
const auto lhsparts = lhs.split(QLatin1Char('.'));
const auto rhsparts = rhs.split(QLatin1Char('.'));
- Q_ASSERT(lhsparts.count() > 1 && rhsparts.count() > 1);
+ Q_ASSERT(lhsparts.size() > 1 && rhsparts.size() > 1);
// note: checking rhs < lhs, the same as lhs > rhs
return std::lexicographical_compare(rhsparts.begin() + 1, rhsparts.end(),
@@ -516,7 +481,7 @@ QStringList findAllLibs(QLatin1String filter)
QStringList entryList = dir.entryList(filters, QDir::Files);
std::sort(entryList.begin(), entryList.end(), LibGreaterThan());
- for (const QString &entry : qAsConst(entryList))
+ for (const QString &entry : std::as_const(entryList))
found << path + QLatin1Char('/') + entry;
}
@@ -537,6 +502,12 @@ QStringList findAllLibCrypto()
#ifdef Q_OS_WIN
+#if (OPENSSL_VERSION_NUMBER >> 28) < 3
+#define QT_OPENSSL_VERSION "1_1"
+#elif OPENSSL_VERSION_MAJOR == 3 // Starting with 3.0 this define is available
+#define QT_OPENSSL_VERSION "3"
+#endif // > 3 intentionally left undefined
+
struct LoadedOpenSsl {
std::unique_ptr<QSystemLibrary> ssl, crypto;
};
@@ -575,8 +546,9 @@ static LoadedOpenSsl loadOpenSsl()
#define QT_SSL_SUFFIX
#endif
- tryToLoadOpenSslWin32Library(QLatin1String("libssl-1_1" QT_SSL_SUFFIX),
- QLatin1String("libcrypto-1_1" QT_SSL_SUFFIX), result);
+ tryToLoadOpenSslWin32Library(QLatin1String("libssl-" QT_OPENSSL_VERSION QT_SSL_SUFFIX),
+ QLatin1String("libcrypto-" QT_OPENSSL_VERSION QT_SSL_SUFFIX),
+ result);
#undef QT_SSL_SUFFIX
return result;
diff --git a/tests/auto/network/ssl/shared/tlshelpers.h b/tests/auto/network/ssl/shared/tlshelpers.h
index cd0f785aee..de3c2ea51a 100644
--- a/tests/auto/network/ssl/shared/tlshelpers.h
+++ b/tests/auto/network/ssl/shared/tlshelpers.h
@@ -1,30 +1,5 @@
-/****************************************************************************
-**
-** Copyright (C) 2021 The Qt Company Ltd.
-** Contact: https://www.qt.io/licensing/
-**
-** This file is part of the test suite of the Qt Toolkit.
-**
-** $QT_BEGIN_LICENSE:GPL-EXCEPT$
-** Commercial License Usage
-** Licensees holding valid commercial Qt licenses may use this file in
-** accordance with the commercial license agreement provided with the
-** Software or, alternatively, in accordance with the terms contained in
-** a written agreement between you and The Qt Company. For licensing terms
-** and conditions see https://www.qt.io/terms-conditions. For further
-** information use the contact form at https://www.qt.io/contact-us.
-**
-** GNU General Public License Usage
-** Alternatively, this file may be used under the terms of the GNU
-** General Public License version 3 as published by the Free Software
-** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
-** included in the packaging of this file. Please review the following
-** information to ensure the GNU General Public License requirements will
-** be met: https://www.gnu.org/licenses/gpl-3.0.html.
-**
-** $QT_END_LICENSE$
-**
-****************************************************************************/
+// Copyright (C) 2021 The Qt Company Ltd.
+// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
#include <QtNetwork/qtnetworkglobal.h>
@@ -37,13 +12,8 @@
#include <QtCore/qstring.h>
#include <QtCore/qglobal.h>
-// TODO: these 'helpers' later to include OpenSSL resolver/sumbols
-// required by some auto-tests.
-
QT_BEGIN_NAMESPACE
-
-
namespace TlsAux {
inline bool classImplemented(QSsl::ImplementedClass cl)