1/****************************************************************************
2**
3** Copyright (C) 2018 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com, author Sérgio Martins <sergio.martins@kdab.com>
4** Contact: https://www.qt.io/licensing/
5**
6** This file is part of the test suite of the Qt Toolkit.
7**
8** $QT_BEGIN_LICENSE:GPL-EXCEPT$
9** Commercial License Usage
10** Licensees holding valid commercial Qt licenses may use this file in
11** accordance with the commercial license agreement provided with the
12** Software or, alternatively, in accordance with the terms contained in
13** a written agreement between you and The Qt Company. For licensing terms
14** and conditions see https://www.qt.io/terms-conditions. For further
15** information use the contact form at https://www.qt.io/contact-us.
16**
17** GNU General Public License Usage
18** Alternatively, this file may be used under the terms of the GNU
19** General Public License version 3 as published by the Free Software
20** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
21** included in the packaging of this file. Please review the following
22** information to ensure the GNU General Public License requirements will
23** be met: https://www.gnu.org/licenses/gpl-3.0.html.
24**
25** $QT_END_LICENSE$
26**
27****************************************************************************/
28
29#include <QtTest/QtTest>
30#include <QtCore/QScopeGuard>
31
32/*!
33 \class tst_QScopedGuard
34 \internal
35 \since 5.11
36 \brief Tests class QScopedCleanup and function qScopeGuard
37
38 */
39class tst_QScopedGuard : public QObject
40{
41 Q_OBJECT
42
43private Q_SLOTS:
44 void leavingScope();
45 void exceptions();
46};
47
48static int s_globalState = 0;
49
50void tst_QScopedGuard::leavingScope()
51{
52 auto cleanup = qScopeGuard([] { s_globalState++; QCOMPARE(s_globalState, 3); });
53 QCOMPARE(s_globalState, 0);
54
55 {
56 auto cleanup = qScopeGuard([] { s_globalState++; });
57 QCOMPARE(s_globalState, 0);
58 }
59
60 QCOMPARE(s_globalState, 1);
61 s_globalState++;
62}
63
64void tst_QScopedGuard::exceptions()
65{
66 s_globalState = 0;
67 bool caught = false;
68 QT_TRY
69 {
70 auto cleanup = qScopeGuard([&caught] { s_globalState++; });
71 QT_THROW(std::bad_alloc()); //if Qt compiled without exceptions this is noop
72 s_globalState = 100;
73 }
74 QT_CATCH(...)
75 {
76 caught = true;
77 QCOMPARE(s_globalState, 1);
78 }
79
80 QVERIFY((caught && s_globalState == 1) || (!caught && s_globalState == 101));
81
82}
83
84QTEST_MAIN(tst_QScopedGuard)
85#include "tst_qscopeguard.moc"
86