Debian Codegraph @

tests/ut_singleton.cpp

raw
1 // SPDX-FileCopyrightText: 2016 - 2022 UnionTech Software Technology Co., Ltd.
2 //
3 // SPDX-License-Identifier: LGPL-3.0-or-later
4
5 #include "ut_singleton.h"
6 #include <gtest/gtest.h>
7 #include <QTest>
8 #include <QThread>
9
10 Singleton::Singleton(QObject *parent)
11 : QObject(parent),
12 count(0)
13 {
14 }
15
16 MultiSingletonTester::MultiSingletonTester(QObject *parent)
17 : QObject(parent)
18 {
19 }
20
21 void MultiSingletonTester::run()
22 {
23 Singleton::ref().count.ref();
24 }
25
26 int MultiSingletonTester::count() const
27 {
28 #if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0)
29 return Singleton::ref().count.loadRelaxed();
30 #else
31 return Singleton::ref().count.load();
32 #endif
33 }
34
35 TEST(ut_DSingleton, testDSingleton)
36 {
37 const int exampleCount = 5;
38 QVector<QThread*> threads;
39 QVector<MultiSingletonTester*> testers;
40 threads.reserve(exampleCount);
41 testers.reserve(exampleCount);
42 for (int i = 0; i < exampleCount; i++) {
43 auto thread = new QThread();
44 auto tester = new MultiSingletonTester;
45 tester->moveToThread(thread);
46 QObject::connect(thread, &QThread::started, tester, &MultiSingletonTester::run);
47
48 threads.push_back(thread);
49 testers.push_back(tester);
50 thread->start();
51 }
52
53 for (auto thread : threads) {
54 thread->quit();
55 }
56
57 ASSERT_TRUE(QTest::qWaitFor([threads] {
58 for (auto thread : threads) {
59 if (!thread->isFinished()) {
60 return false;
61 }
62 }
63 return true;
64 }));
65
66 for (auto tester : testers) {
67 ASSERT_EQ(tester->count(), exampleCount);
68 }
69
70 qDeleteAll(threads);
71 qDeleteAll(testers);
72 }