1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636
|
/*
* SPDX-FileCopyrightText: 2021 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "gui/tray/unifiedsearchresultslistmodel.h"
#include "account.h"
#include "accountstate.h"
#include "syncenginetestutils.h"
#include <QAbstractItemModelTester>
#include <QDesktopServices>
#include <QSignalSpy>
#include <QTest>
namespace {
/**
* @brief The FakeDesktopServicesUrlHandler
* overrides QDesktopServices::openUrl
**/
class FakeDesktopServicesUrlHandler : public QObject
{
Q_OBJECT
public:
FakeDesktopServicesUrlHandler(QObject *parent = nullptr)
: QObject(parent)
{}
public:
signals:
void resultClicked(const QUrl &url);
};
/**
* @brief The FakeProvider
* is a simple structure that represents initial list of providers and their properties
**/
class FakeProvider
{
public:
QString _id;
QString _name;
qint32 _order = std::numeric_limits<qint32>::max();
quint32 _numItemsToInsert = 5; // how many fake results to insert
};
// this will be used when initializing fake search results data for each provider
static const QVector<FakeProvider> fakeProvidersInitInfo = {
{QStringLiteral("settings_apps"), QStringLiteral("Apps"), -50, 10},
{QStringLiteral("talk-message"), QStringLiteral("Messages"), -2, 17},
{QStringLiteral("files"), QStringLiteral("Files"), 5, 3},
{QStringLiteral("deck"), QStringLiteral("Deck"), 10, 5},
{QStringLiteral("comments"), QStringLiteral("Comments"), 10, 2},
{QStringLiteral("mail"), QStringLiteral("Mails"), 10, 15},
{QStringLiteral("calendar"), QStringLiteral("Events"), 30, 11}
};
static QByteArray fake404Response = R"(
{"ocs":{"meta":{"status":"failure","statuscode":404,"message":"Invalid query, please check the syntax. API specifications are here: http:\/\/www.freedesktop.org\/wiki\/Specifications\/open-collaboration-services.\n"},"data":[]}}
)";
static QByteArray fake400Response = R"(
{"ocs":{"meta":{"status":"failure","statuscode":400,"message":"Parameter is incorrect.\n"},"data":[]}}
)";
static QByteArray fake500Response = R"(
{"ocs":{"meta":{"status":"failure","statuscode":500,"message":"Internal Server Error.\n"},"data":[]}}
)";
/**
* @brief The FakeSearchResultsStorage
* emulates the real server storage that contains all the results that UnifiedSearchListmodel will search for
**/
class FakeSearchResultsStorage
{
class Provider
{
public:
class SearchResult
{
public:
QString _thumbnailUrl;
QString _title;
QString _subline;
QString _resourceUrl;
QString _icon;
bool _rounded;
};
QString _id;
QString _name;
qint32 _order = std::numeric_limits<qint32>::max();
qint32 _cursor = 0;
bool _isPaginated = false;
QVector<SearchResult> _results;
};
FakeSearchResultsStorage() = default;
public:
static FakeSearchResultsStorage *instance()
{
if (!_instance) {
_instance = new FakeSearchResultsStorage();
_instance->init();
}
return _instance;
};
static void destroy()
{
if (_instance) {
delete _instance;
}
_instance = nullptr;
}
void init()
{
if (!_searchResultsData.isEmpty()) {
return;
}
_metaSuccess = {{QStringLiteral("status"), QStringLiteral("ok")}, {QStringLiteral("statuscode"), 200},
{QStringLiteral("message"), QStringLiteral("OK")}};
initProvidersResponse();
initSearchResultsData();
}
// initialize the JSON response containing the fake list of providers and their properties
void initProvidersResponse()
{
QList<QVariant> providersList;
for (const auto &fakeProviderInitInfo : fakeProvidersInitInfo) {
providersList.push_back(QVariantMap{
{QStringLiteral("id"), fakeProviderInitInfo._id},
{QStringLiteral("name"), fakeProviderInitInfo._name},
{QStringLiteral("order"), fakeProviderInitInfo._order},
});
}
const QVariantMap ocsMap = {
{QStringLiteral("meta"), _metaSuccess},
{QStringLiteral("data"), providersList}
};
_providersResponse =
QJsonDocument::fromVariant(QVariantMap{{QStringLiteral("ocs"), ocsMap}}).toJson(QJsonDocument::Compact);
}
// init the map of fake search results for each provider
void initSearchResultsData()
{
for (const auto &fakeProvider : fakeProvidersInitInfo) {
auto &providerData = _searchResultsData[fakeProvider._id];
providerData._id = fakeProvider._id;
providerData._name = fakeProvider._name;
providerData._order = fakeProvider._order;
if (fakeProvider._numItemsToInsert > pageSize) {
providerData._isPaginated = true;
}
for (quint32 i = 0; i < fakeProvider._numItemsToInsert; ++i) {
providerData._results.push_back(
{"http://example.de/avatar/john/64", QString(QStringLiteral("John Doe in ") + fakeProvider._name),
QString(QStringLiteral("We a discussion about ") + fakeProvider._name
+ QStringLiteral(" already. But, let's have a follow up tomorrow afternoon.")),
"http://example.de/call/abcde12345#message_12345", QStringLiteral("icon-talk"), true});
}
}
}
const QList<QVariant> resultsForProvider(const QString &providerId, int cursor)
{
QList<QVariant> list;
const auto results = resultsForProviderAsVector(providerId, cursor);
if (results.isEmpty()) {
return list;
}
for (const auto &result : results) {
list.push_back(QVariantMap{
{"thumbnailUrl", result._thumbnailUrl},
{"title", result._title},
{"subline", result._subline},
{"resourceUrl", result._resourceUrl},
{"icon", result._icon},
{"rounded", result._rounded}
});
}
return list;
}
const QVector<Provider::SearchResult> resultsForProviderAsVector(const QString &providerId, int cursor)
{
QVector<Provider::SearchResult> results;
const auto provider = _searchResultsData.value(providerId, Provider());
if (provider._id.isEmpty() || cursor > provider._results.size()) {
return results;
}
const int n = cursor + pageSize > provider._results.size()
? 0
: cursor + pageSize;
for (int i = cursor; i < n; ++i) {
results.push_back(provider._results[i]);
}
return results;
}
const QByteArray queryProvider(const QString &providerId, const QString &searchTerm, int cursor)
{
if (!_searchResultsData.contains(providerId)) {
return fake404Response;
}
if (searchTerm == QStringLiteral("[HTTP500]")) {
return fake500Response;
}
if (searchTerm == QStringLiteral("[empty]")) {
const QVariantMap dataMap = {{QStringLiteral("name"), _searchResultsData[providerId]._name},
{QStringLiteral("isPaginated"), false}, {QStringLiteral("cursor"), 0},
{QStringLiteral("entries"), QVariantList{}}};
const QVariantMap ocsMap = {{QStringLiteral("meta"), _metaSuccess}, {QStringLiteral("data"), dataMap}};
return QJsonDocument::fromVariant(QVariantMap{{QStringLiteral("ocs"), ocsMap}})
.toJson(QJsonDocument::Compact);
}
const auto provider = _searchResultsData.value(providerId, Provider());
const auto nextCursor = cursor + pageSize;
const QVariantMap dataMap = {{QStringLiteral("name"), _searchResultsData[providerId]._name},
{QStringLiteral("isPaginated"), _searchResultsData[providerId]._isPaginated},
{QStringLiteral("cursor"), nextCursor},
{QStringLiteral("entries"), resultsForProvider(providerId, cursor)}};
const QVariantMap ocsMap = {{QStringLiteral("meta"), _metaSuccess}, {QStringLiteral("data"), dataMap}};
return QJsonDocument::fromVariant(QVariantMap{{QStringLiteral("ocs"), ocsMap}}).toJson(QJsonDocument::Compact);
}
[[nodiscard]] const QByteArray &fakeProvidersResponseJson() const { return _providersResponse; }
private:
static FakeSearchResultsStorage *_instance;
static const int pageSize = 5;
QMap<QString, Provider> _searchResultsData;
QByteArray _providersResponse = fake404Response;
QVariantMap _metaSuccess;
};
FakeSearchResultsStorage *FakeSearchResultsStorage::_instance = nullptr;
}
class TestUnifiedSearchListmodel : public QObject
{
Q_OBJECT
public:
TestUnifiedSearchListmodel() = default;
QScopedPointer<FakeQNAM> fakeQnam;
OCC::AccountPtr account;
QScopedPointer<OCC::AccountState> accountState;
QScopedPointer<OCC::UnifiedSearchResultsListModel> model;
QScopedPointer<QAbstractItemModelTester> modelTester;
QScopedPointer<FakeDesktopServicesUrlHandler> fakeDesktopServicesUrlHandler;
static const int searchResultsReplyDelay = 100;
private slots:
void initTestCase()
{
OCC::Logger::instance()->setLogFlush(true);
OCC::Logger::instance()->setLogDebug(true);
QStandardPaths::setTestModeEnabled(true);
fakeQnam.reset(new FakeQNAM({}));
account = OCC::Account::create();
account->setCredentials(new FakeCredentials{fakeQnam.data()});
account->setUrl(QUrl(("http://example.de")));
accountState.reset(new OCC::AccountState(account));
fakeQnam->setOverride([this](QNetworkAccessManager::Operation op, const QNetworkRequest &req, QIODevice *device) {
Q_UNUSED(device);
QNetworkReply *reply = nullptr;
const auto urlQuery = QUrlQuery(req.url());
const auto format = urlQuery.queryItemValue(QStringLiteral("format"));
const auto cursor = urlQuery.queryItemValue(QStringLiteral("cursor")).toInt();
const auto searchTerm = urlQuery.queryItemValue(QStringLiteral("term"));
const auto path = req.url().path();
if (!req.url().toString().startsWith(accountState->account()->url().toString())) {
reply = new FakeErrorReply(op, req, this, 404, fake404Response);
}
if (format != QStringLiteral("json")) {
reply = new FakeErrorReply(op, req, this, 400, fake400Response);
}
// handle fetch of providers list
if (path.startsWith(QStringLiteral("/ocs/v2.php/search/providers")) && searchTerm.isEmpty()) {
reply = new FakePayloadReply(op, req,
FakeSearchResultsStorage::instance()->fakeProvidersResponseJson(), fakeQnam.data());
// handle search for provider
} else if (path.startsWith(QStringLiteral("/ocs/v2.php/search/providers")) && !searchTerm.isEmpty()) {
const auto pathSplit = path.mid(QString(QStringLiteral("/ocs/v2.php/search/providers")).size())
.split(QLatin1Char('/'), Qt::SkipEmptyParts);
if (!pathSplit.isEmpty() && path.contains(pathSplit.first())) {
reply = new FakePayloadReply(op, req,
FakeSearchResultsStorage::instance()->queryProvider(pathSplit.first(), searchTerm, cursor),
searchResultsReplyDelay, fakeQnam.data());
}
}
if (!reply) {
return qobject_cast<QNetworkReply*>(new FakeErrorReply(op, req, this, 404, QByteArrayLiteral("{error: \"Not found!\"}")));
}
return reply;
});
model.reset(new OCC::UnifiedSearchResultsListModel(accountState.data()));
modelTester.reset(new QAbstractItemModelTester(model.data()));
fakeDesktopServicesUrlHandler.reset(new FakeDesktopServicesUrlHandler);
}
void testSetSearchTermStartStopSearch()
{
// make sure the model is empty
model->setSearchTerm(QStringLiteral(""));
QVERIFY(model->rowCount() == 0);
// #1 test setSearchTerm actually sets the search term and the signal is emitted
QSignalSpy searhTermChanged(model.data(), &OCC::UnifiedSearchResultsListModel::searchTermChanged);
model->setSearchTerm(QStringLiteral("dis"));
QCOMPARE(searhTermChanged.count(), 1);
QCOMPARE(model->searchTerm(), QStringLiteral("dis"));
// #2 test setSearchTerm actually sets the search term and the signal is emitted
searhTermChanged.clear();
model->setSearchTerm(model->searchTerm() + QStringLiteral("cuss"));
QCOMPARE(model->searchTerm(), QStringLiteral("discuss"));
QCOMPARE(searhTermChanged.count(), 1);
// #3 test that model has not started search yet
QVERIFY(!model->isSearchInProgress());
// #4 test that model has started the search after specific delay
QSignalSpy searchInProgressChanged(model.data(), &OCC::UnifiedSearchResultsListModel::isSearchInProgressChanged);
// allow search jobs to get created within the model
QVERIFY(searchInProgressChanged.wait());
QCOMPARE(searchInProgressChanged.count(), 1);
QVERIFY(model->isSearchInProgress());
// #5 test that model has stopped the search after setting empty search term
model->setSearchTerm(QStringLiteral(""));
QVERIFY(!model->isSearchInProgress());
}
void testSetSearchTermResultsFound()
{
// make sure the model is empty
model->setSearchTerm(QStringLiteral(""));
QVERIFY(model->rowCount() == 0);
// test that search term gets set, search gets started and enough results get returned
model->setSearchTerm(model->searchTerm() + QStringLiteral("discuss"));
QSignalSpy searchInProgressChanged(
model.data(), &OCC::UnifiedSearchResultsListModel::isSearchInProgressChanged);
QVERIFY(searchInProgressChanged.wait());
// make sure search has started
QCOMPARE(searchInProgressChanged.count(), 1);
QVERIFY(model->isSearchInProgress());
QVERIFY(searchInProgressChanged.wait());
// make sure search has finished
QVERIFY(!model->isSearchInProgress());
QVERIFY(model->rowCount() > 0);
}
void testSetSearchTermResultsNotFound()
{
// make sure the model is empty
model->setSearchTerm(QStringLiteral(""));
QVERIFY(model->rowCount() == 0);
// test that search term gets set, search gets started and enough results get returned
model->setSearchTerm(model->searchTerm() + QStringLiteral("[empty]"));
QSignalSpy searchInProgressChanged(
model.data(), &OCC::UnifiedSearchResultsListModel::isSearchInProgressChanged);
QVERIFY(searchInProgressChanged.wait());
// make sure search has started
QCOMPARE(searchInProgressChanged.count(), 1);
QVERIFY(model->isSearchInProgress());
QVERIFY(searchInProgressChanged.wait());
// make sure search has finished
QVERIFY(!model->isSearchInProgress());
QVERIFY(model->rowCount() == 0);
}
void testFetchMoreClicked()
{
// make sure the model is empty
model->setSearchTerm(QStringLiteral(""));
QVERIFY(model->rowCount() == 0);
QSignalSpy searchInProgressChanged(
model.data(), &OCC::UnifiedSearchResultsListModel::isSearchInProgressChanged);
// test that search term gets set, search gets started and enough results get returned
model->setSearchTerm(model->searchTerm() + QStringLiteral("whatever"));
QVERIFY(searchInProgressChanged.wait());
// make sure search has started
QVERIFY(model->isSearchInProgress());
QVERIFY(searchInProgressChanged.wait());
// make sure search has finished
QVERIFY(!model->isSearchInProgress());
const auto numRowsInModelPrev = model->rowCount();
// test fetch more results
QSignalSpy currentFetchMoreInProgressProviderIdChanged(
model.data(), &OCC::UnifiedSearchResultsListModel::currentFetchMoreInProgressProviderIdChanged);
QSignalSpy rowsInserted(model.data(), &OCC::UnifiedSearchResultsListModel::rowsInserted);
for (int i = 0; i < model->rowCount(); ++i) {
const auto type = model->data(model->index(i), OCC::UnifiedSearchResultsListModel::DataRole::TypeRole);
if (type == OCC::UnifiedSearchResult::Type::FetchMoreTrigger) {
const auto providerId =
model->data(model->index(i), OCC::UnifiedSearchResultsListModel::DataRole::ProviderIdRole)
.toString();
model->fetchMoreTriggerClicked(providerId);
break;
}
}
// make sure the currentFetchMoreInProgressProviderId was set back and forth and correct number fows has been inserted
QCOMPARE(currentFetchMoreInProgressProviderIdChanged.count(), 1);
const auto providerIdFetchMoreTriggered = model->currentFetchMoreInProgressProviderId();
QVERIFY(!providerIdFetchMoreTriggered.isEmpty());
QVERIFY(currentFetchMoreInProgressProviderIdChanged.wait());
QVERIFY(model->currentFetchMoreInProgressProviderId().isEmpty());
QCOMPARE(rowsInserted.count(), 1);
const auto arguments = rowsInserted.takeFirst();
QVERIFY(arguments.size() > 0);
const auto first = arguments.at(0).toInt();
const auto last = arguments.at(1).toInt();
const int numInsertedExpected = last - first;
QCOMPARE(model->rowCount() - numRowsInModelPrev, numInsertedExpected);
// make sure the FetchMoreTrigger gets removed when no more results available
if (!providerIdFetchMoreTriggered.isEmpty()) {
currentFetchMoreInProgressProviderIdChanged.clear();
rowsInserted.clear();
QSignalSpy rowsRemoved(model.data(), &OCC::UnifiedSearchResultsListModel::rowsRemoved);
for (int i = 0; i < 10; ++i) {
model->fetchMoreTriggerClicked(providerIdFetchMoreTriggered);
QVERIFY(currentFetchMoreInProgressProviderIdChanged.wait());
if (rowsRemoved.count() > 0) {
break;
}
}
QCOMPARE(rowsRemoved.count(), 1);
bool isFetchMoreTriggerFound = false;
for (int i = 0; i < model->rowCount(); ++i) {
const auto type = model->data(model->index(i), OCC::UnifiedSearchResultsListModel::DataRole::TypeRole);
const auto providerId = model->data(model->index(i), OCC::UnifiedSearchResultsListModel::DataRole::ProviderIdRole)
.toString();
if (type == OCC::UnifiedSearchResult::Type::FetchMoreTrigger
&& providerId == providerIdFetchMoreTriggered) {
isFetchMoreTriggerFound = true;
break;
}
}
QVERIFY(!isFetchMoreTriggerFound);
}
}
void testSearchResultlicked()
{
// make sure the model is empty
model->setSearchTerm(QStringLiteral(""));
QVERIFY(model->rowCount() == 0);
// test that search term gets set, search gets started and enough results get returned
model->setSearchTerm(model->searchTerm() + QStringLiteral("discuss"));
QSignalSpy searchInProgressChanged(
model.data(), &OCC::UnifiedSearchResultsListModel::isSearchInProgressChanged);
QVERIFY(searchInProgressChanged.wait());
// make sure search has started
QCOMPARE(searchInProgressChanged.count(), 1);
QVERIFY(model->isSearchInProgress());
QVERIFY(searchInProgressChanged.wait());
// make sure search has finished and some results has been received
QVERIFY(!model->isSearchInProgress());
QVERIFY(model->rowCount() != 0);
QDesktopServices::setUrlHandler("http", fakeDesktopServicesUrlHandler.data(), "resultClicked");
QDesktopServices::setUrlHandler("https", fakeDesktopServicesUrlHandler.data(), "resultClicked");
QSignalSpy resultClicked(fakeDesktopServicesUrlHandler.data(), &FakeDesktopServicesUrlHandler::resultClicked);
// test click on a result item
QString urlForClickedResult;
for (int i = 0; i < model->rowCount(); ++i) {
const auto type = model->data(model->index(i), OCC::UnifiedSearchResultsListModel::DataRole::TypeRole);
if (type == OCC::UnifiedSearchResult::Type::Default) {
const auto providerId =
model->data(model->index(i), OCC::UnifiedSearchResultsListModel::DataRole::ProviderIdRole)
.toString();
urlForClickedResult = model->data(model->index(i), OCC::UnifiedSearchResultsListModel::DataRole::ResourceUrlRole).toString();
if (!providerId.isEmpty() && !urlForClickedResult.isEmpty()) {
model->resultClicked(providerId, QUrl(urlForClickedResult));
break;
}
}
}
QCOMPARE(resultClicked.count(), 1);
const auto arguments = resultClicked.takeFirst();
const auto urlOpenTriggeredViaDesktopServices = arguments.at(0).toString();
QCOMPARE(urlOpenTriggeredViaDesktopServices, urlForClickedResult);
}
void testSetSearchTermResultsError()
{
// make sure the model is empty
model->setSearchTerm(QStringLiteral(""));
QVERIFY(model->rowCount() == 0);
QSignalSpy errorStringChanged(model.data(), &OCC::UnifiedSearchResultsListModel::errorStringChanged);
QSignalSpy searchInProgressChanged(
model.data(), &OCC::UnifiedSearchResultsListModel::isSearchInProgressChanged);
model->setSearchTerm(model->searchTerm() + QStringLiteral("[HTTP500]"));
QVERIFY(searchInProgressChanged.wait());
// make sure search has started
QVERIFY(model->isSearchInProgress());
QVERIFY(searchInProgressChanged.wait());
// make sure search has finished
QVERIFY(!model->isSearchInProgress());
// make sure the model is empty and an error string has been set
QVERIFY(model->rowCount() == 0);
QVERIFY(errorStringChanged.count() > 0);
QVERIFY(!model->errorString().isEmpty());
}
void cleanupTestCase()
{
FakeSearchResultsStorage::destroy();
}
};
QTEST_MAIN(TestUnifiedSearchListmodel)
#include "testunifiedsearchlistmodel.moc"
|