Page MenuHomePhorge

qt-promise-handler-test.cpp
No OneTemporary

Size
3 KB
Referenced Files
None
Subscribers
None

qt-promise-handler-test.cpp

/*
* This file is part of kazv.
* SPDX-FileCopyrightText: 2020-2021 Tusooa Zhu <tusooa@kazv.moe>
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
#include <libkazv-config.hpp>
#include <memory>
#include <vector>
#include <QTimer>
#include "qt-promise-handler-test.hpp"
#include "qt-promise-handler.hpp"
namespace
{
struct MockDataStruct
{
int i{};
};
}
void QtPromiseHandlerTest::testPromise()
{
QEventLoop loop;
QObject *obj = new QObject(&loop);
auto ph = QtPromiseHandler(std::ref(*obj));
std::vector<int> v;
auto p1 = ph.create<int>([&v](auto resolve) {
qDebug() << "p1";
v.push_back(1);
resolve(2);
});
auto p2 = p1.then([&v, &ph](int val) {
qDebug() << "p2";
v.push_back(val);
return ph.createResolved(3);
});
auto p3 = p2.then([&v, &ph](int val) {
qDebug() << "p3";
v.push_back(val);
return ph.createResolved(-1);
});
auto p4 = p3.then([](int val) {
qDebug() << "p4" << val;
[=] { QVERIFY(val == -1); }();
return 5;
});
auto p5 = p4.then([](int val) {
qDebug() << "p5" << val;
[=] { QVERIFY(val == 5); }();
return MockDataStruct{6};
});
auto p6 = p5.then([obj, &loop](MockDataStruct m) {
qDebug() << "p6" << m.i;
[=] { QVERIFY(m.i == 6); }();
obj->deleteLater();
loop.quit();
return 0;
});
QObject::connect(obj, &QObject::destroyed,
this, [&v] {
qDebug() << "QObject::destroyed()";
QVERIFY((v == std::vector<int>{ 1, 2, 3 }));
});
loop.exec();
}
void QtPromiseHandlerTest::testTimer()
{
QEventLoop loop;
QObject *obj = new QObject(&loop);
auto ph = QtPromiseHandler(std::ref(*obj));
auto pTimer = ph.create<int>([](auto resolve) {
QTimer::singleShot(300, [resolve]() { resolve(20); });
});
int i;
auto pTimer2 = pTimer.then([&i, &loop, obj](int val) -> int {
i = val;
obj->deleteLater();
loop.quit();
return 0;
});
QObject::connect(obj, &QObject::destroyed,
this, [&i] {
qDebug() << "QObject::destroyed()";
QVERIFY(i == 20);
});
loop.exec();
}
void QtPromiseHandlerTest::testStop()
{
QEventLoop loop;
QObject *obj = new QObject(&loop);
auto ph = QtPromiseHandler(std::ref(*obj));
auto pTimer = ph.create<int>([](auto resolve) {
QTimer::singleShot(500, [resolve]() { resolve(20); });
});
int i = 0;
auto pTimer2 = pTimer.then([&i, &loop, obj](int val) -> int {
qDebug() << "then-continuation";
i = val;
obj->deleteLater();
loop.quit();
return 0;
});
QTimer::singleShot(300, this, [obj]() {
qDebug() << "delete obj";
obj->deleteLater();
});
QObject::connect(obj, &QObject::destroyed,
this, [&i] {
qDebug() << "QObject::destroyed()";
});
QTimer::singleShot(2000, this, [&loop]() {
qDebug() << "stop loop";
loop.quit();
});
loop.exec();
}
QTEST_MAIN(QtPromiseHandlerTest)

File Metadata

Mime Type
text/x-c
Expires
Wed, May 14, 7:26 AM (1 d, 15 h)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
166729
Default Alt Text
qt-promise-handler-test.cpp (3 KB)

Event Timeline