syncenginetestutils.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574
  1. /*
  2. * This software is in the public domain, furnished "as is", without technical
  3. * support, and with no warranty, express or implied, as to its usefulness for
  4. * any purpose.
  5. *
  6. */
  7. #pragma once
  8. #include "account.h"
  9. #include "common/result.h"
  10. #include "creds/abstractcredentials.h"
  11. #include "logger.h"
  12. #include "filesystem.h"
  13. #include "syncengine.h"
  14. #include "common/syncjournaldb.h"
  15. #include "common/syncjournalfilerecord.h"
  16. #include "common/vfs.h"
  17. #include "csync_exclude.h"
  18. #include <QDir>
  19. #include <QNetworkReply>
  20. #include <QMap>
  21. #include <QtTest>
  22. #include <cstring>
  23. #include <memory>
  24. #include <cookiejar.h>
  25. #include <QTimer>
  26. /*
  27. * TODO: In theory we should use QVERIFY instead of Q_ASSERT for testing, but this
  28. * only works when directly called from a QTest :-(
  29. */
  30. static const QUrl sRootUrl("owncloud://somehost/owncloud/remote.php/dav/");
  31. static const QUrl sRootUrl2("owncloud://somehost/owncloud/remote.php/dav/files/admin/");
  32. static const QUrl sUploadUrl("owncloud://somehost/owncloud/remote.php/dav/uploads/admin/");
  33. inline QString getFilePathFromUrl(const QUrl &url)
  34. {
  35. QString path = url.path();
  36. if (path.startsWith(sRootUrl2.path()))
  37. return path.mid(sRootUrl2.path().length());
  38. if (path.startsWith(sUploadUrl.path()))
  39. return path.mid(sUploadUrl.path().length());
  40. if (path.startsWith(sRootUrl.path()))
  41. return path.mid(sRootUrl.path().length());
  42. return {};
  43. }
  44. inline QByteArray generateEtag() {
  45. return QByteArray::number(QDateTime::currentDateTimeUtc().toMSecsSinceEpoch(), 16) + QByteArray::number(qrand(), 16);
  46. }
  47. inline QByteArray generateFileId() {
  48. return QByteArray::number(qrand(), 16);
  49. }
  50. class PathComponents : public QStringList {
  51. public:
  52. PathComponents(const char *path);
  53. PathComponents(const QString &path);
  54. PathComponents(const QStringList &pathComponents);
  55. PathComponents parentDirComponents() const;
  56. PathComponents subComponents() const &;
  57. PathComponents subComponents() && { removeFirst(); return std::move(*this); }
  58. QString pathRoot() const { return first(); }
  59. QString fileName() const { return last(); }
  60. };
  61. class FileModifier
  62. {
  63. public:
  64. virtual ~FileModifier() = default;
  65. virtual void remove(const QString &relativePath) = 0;
  66. virtual void insert(const QString &relativePath, qint64 size = 64, char contentChar = 'W') = 0;
  67. virtual void setContents(const QString &relativePath, char contentChar) = 0;
  68. virtual void appendByte(const QString &relativePath) = 0;
  69. virtual void mkdir(const QString &relativePath) = 0;
  70. virtual void rename(const QString &relativePath, const QString &relativeDestinationDirectory) = 0;
  71. virtual void setModTime(const QString &relativePath, const QDateTime &modTime) = 0;
  72. };
  73. class DiskFileModifier : public FileModifier
  74. {
  75. QDir _rootDir;
  76. public:
  77. DiskFileModifier(const QString &rootDirPath) : _rootDir(rootDirPath) { }
  78. void remove(const QString &relativePath) override;
  79. void insert(const QString &relativePath, qint64 size = 64, char contentChar = 'W') override;
  80. void setContents(const QString &relativePath, char contentChar) override;
  81. void appendByte(const QString &relativePath) override;
  82. void mkdir(const QString &relativePath) override;
  83. void rename(const QString &from, const QString &to) override;
  84. void setModTime(const QString &relativePath, const QDateTime &modTime) override;
  85. };
  86. class FileInfo : public FileModifier
  87. {
  88. public:
  89. static FileInfo A12_B12_C12_S12();
  90. FileInfo() = default;
  91. FileInfo(const QString &name) : name{name} { }
  92. FileInfo(const QString &name, qint64 size) : name{name}, isDir{false}, size{size} { }
  93. FileInfo(const QString &name, qint64 size, char contentChar) : name{name}, isDir{false}, size{size}, contentChar{contentChar} { }
  94. FileInfo(const QString &name, const std::initializer_list<FileInfo> &children);
  95. void addChild(const FileInfo &info);
  96. void remove(const QString &relativePath) override;
  97. void insert(const QString &relativePath, qint64 size = 64, char contentChar = 'W') override;
  98. void setContents(const QString &relativePath, char contentChar) override;
  99. void appendByte(const QString &relativePath) override;
  100. void mkdir(const QString &relativePath) override;
  101. void rename(const QString &oldPath, const QString &newPath) override;
  102. void setModTime(const QString &relativePath, const QDateTime &modTime) override;
  103. FileInfo *find(PathComponents pathComponents, const bool invalidateEtags = false);
  104. FileInfo *createDir(const QString &relativePath);
  105. FileInfo *create(const QString &relativePath, qint64 size, char contentChar);
  106. bool operator<(const FileInfo &other) const {
  107. return name < other.name;
  108. }
  109. bool operator==(const FileInfo &other) const;
  110. bool operator!=(const FileInfo &other) const {
  111. return !operator==(other);
  112. }
  113. QString path() const;
  114. void fixupParentPathRecursively();
  115. QString name;
  116. bool isDir = true;
  117. bool isShared = false;
  118. OCC::RemotePermissions permissions; // When uset, defaults to everything
  119. QDateTime lastModified = QDateTime::currentDateTimeUtc().addDays(-7);
  120. QByteArray etag = generateEtag();
  121. QByteArray fileId = generateFileId();
  122. QByteArray checksums;
  123. QByteArray extraDavProperties;
  124. qint64 size = 0;
  125. char contentChar = 'W';
  126. // Sorted by name to be able to compare trees
  127. QMap<QString, FileInfo> children;
  128. QString parentPath;
  129. FileInfo *findInvalidatingEtags(PathComponents pathComponents);
  130. friend inline QDebug operator<<(QDebug dbg, const FileInfo& fi) {
  131. return dbg << "{ " << fi.path() << ": " << fi.children;
  132. }
  133. };
  134. class FakeReply : public QNetworkReply
  135. {
  136. Q_OBJECT
  137. public:
  138. FakeReply(QObject *parent);
  139. virtual ~FakeReply();
  140. // useful to be public for testing
  141. using QNetworkReply::setRawHeader;
  142. };
  143. class FakePropfindReply : public FakeReply
  144. {
  145. Q_OBJECT
  146. public:
  147. QByteArray payload;
  148. FakePropfindReply(FileInfo &remoteRootFileInfo, QNetworkAccessManager::Operation op, const QNetworkRequest &request, QObject *parent);
  149. Q_INVOKABLE void respond();
  150. Q_INVOKABLE void respond404();
  151. void abort() override { }
  152. qint64 bytesAvailable() const override;
  153. qint64 readData(char *data, qint64 maxlen) override;
  154. };
  155. class FakePutReply : public FakeReply
  156. {
  157. Q_OBJECT
  158. FileInfo *fileInfo;
  159. public:
  160. FakePutReply(FileInfo &remoteRootFileInfo, QNetworkAccessManager::Operation op, const QNetworkRequest &request, const QByteArray &putPayload, QObject *parent);
  161. static FileInfo *perform(FileInfo &remoteRootFileInfo, const QNetworkRequest &request, const QByteArray &putPayload);
  162. Q_INVOKABLE virtual void respond();
  163. void abort() override;
  164. qint64 readData(char *, qint64) override { return 0; }
  165. };
  166. class FakeMkcolReply : public FakeReply
  167. {
  168. Q_OBJECT
  169. FileInfo *fileInfo;
  170. public:
  171. FakeMkcolReply(FileInfo &remoteRootFileInfo, QNetworkAccessManager::Operation op, const QNetworkRequest &request, QObject *parent);
  172. Q_INVOKABLE void respond();
  173. void abort() override { }
  174. qint64 readData(char *, qint64) override { return 0; }
  175. };
  176. class FakeDeleteReply : public FakeReply
  177. {
  178. Q_OBJECT
  179. public:
  180. FakeDeleteReply(FileInfo &remoteRootFileInfo, QNetworkAccessManager::Operation op, const QNetworkRequest &request, QObject *parent);
  181. Q_INVOKABLE void respond();
  182. void abort() override { }
  183. qint64 readData(char *, qint64) override { return 0; }
  184. };
  185. class FakeMoveReply : public FakeReply
  186. {
  187. Q_OBJECT
  188. public:
  189. FakeMoveReply(FileInfo &remoteRootFileInfo, QNetworkAccessManager::Operation op, const QNetworkRequest &request, QObject *parent);
  190. Q_INVOKABLE void respond();
  191. void abort() override { }
  192. qint64 readData(char *, qint64) override { return 0; }
  193. };
  194. class FakeGetReply : public FakeReply
  195. {
  196. Q_OBJECT
  197. public:
  198. const FileInfo *fileInfo;
  199. char payload;
  200. int size;
  201. bool aborted = false;
  202. FakeGetReply(FileInfo &remoteRootFileInfo, QNetworkAccessManager::Operation op, const QNetworkRequest &request, QObject *parent);
  203. Q_INVOKABLE void respond();
  204. void abort() override;
  205. qint64 bytesAvailable() const override;
  206. qint64 readData(char *data, qint64 maxlen) override;
  207. };
  208. class FakeGetWithDataReply : public FakeReply
  209. {
  210. Q_OBJECT
  211. public:
  212. const FileInfo *fileInfo;
  213. QByteArray payload;
  214. quint64 offset = 0;
  215. bool aborted = false;
  216. FakeGetWithDataReply(FileInfo &remoteRootFileInfo, const QByteArray &data, QNetworkAccessManager::Operation op, const QNetworkRequest &request, QObject *parent);
  217. Q_INVOKABLE void respond();
  218. void abort() override;
  219. qint64 bytesAvailable() const override;
  220. qint64 readData(char *data, qint64 maxlen) override;
  221. };
  222. class FakeChunkMoveReply : public FakeReply
  223. {
  224. Q_OBJECT
  225. FileInfo *fileInfo;
  226. public:
  227. FakeChunkMoveReply(FileInfo &uploadsFileInfo, FileInfo &remoteRootFileInfo,
  228. QNetworkAccessManager::Operation op, const QNetworkRequest &request,
  229. QObject *parent);
  230. static FileInfo *perform(FileInfo &uploadsFileInfo, FileInfo &remoteRootFileInfo, const QNetworkRequest &request);
  231. Q_INVOKABLE virtual void respond();
  232. Q_INVOKABLE void respondPreconditionFailed();
  233. void abort() override;
  234. qint64 readData(char *, qint64) override { return 0; }
  235. };
  236. class FakePayloadReply : public FakeReply
  237. {
  238. Q_OBJECT
  239. public:
  240. FakePayloadReply(QNetworkAccessManager::Operation op, const QNetworkRequest &request,
  241. const QByteArray &body, QObject *parent);
  242. void respond();
  243. void abort() override {}
  244. qint64 readData(char *buf, qint64 max) override;
  245. qint64 bytesAvailable() const override;
  246. QByteArray _body;
  247. };
  248. class FakeErrorReply : public FakeReply
  249. {
  250. Q_OBJECT
  251. public:
  252. FakeErrorReply(QNetworkAccessManager::Operation op, const QNetworkRequest &request,
  253. QObject *parent, int httpErrorCode, const QByteArray &body = QByteArray());
  254. Q_INVOKABLE virtual void respond();
  255. // make public to give tests easy interface
  256. using QNetworkReply::setError;
  257. using QNetworkReply::setAttribute;
  258. public slots:
  259. void slotSetFinished();
  260. public:
  261. void abort() override { }
  262. qint64 readData(char *buf, qint64 max) override;
  263. qint64 bytesAvailable() const override;
  264. QByteArray _body;
  265. };
  266. // A reply that never responds
  267. class FakeHangingReply : public FakeReply
  268. {
  269. Q_OBJECT
  270. public:
  271. FakeHangingReply(QNetworkAccessManager::Operation op, const QNetworkRequest &request, QObject *parent);
  272. void abort() override;
  273. qint64 readData(char *, qint64) override { return 0; }
  274. };
  275. // A delayed reply
  276. template <class OriginalReply>
  277. class DelayedReply : public OriginalReply
  278. {
  279. public:
  280. template <typename... Args>
  281. explicit DelayedReply(quint64 delayMS, Args &&... args)
  282. : OriginalReply(std::forward<Args>(args)...)
  283. , _delayMs(delayMS)
  284. {
  285. }
  286. quint64 _delayMs;
  287. void respond() override
  288. {
  289. QTimer::singleShot(_delayMs, static_cast<OriginalReply *>(this), [this] {
  290. // Explicit call to bases's respond();
  291. this->OriginalReply::respond();
  292. });
  293. }
  294. };
  295. class FakeQNAM : public QNetworkAccessManager
  296. {
  297. public:
  298. using Override = std::function<QNetworkReply *(Operation, const QNetworkRequest &, QIODevice *)>;
  299. private:
  300. FileInfo _remoteRootFileInfo;
  301. FileInfo _uploadFileInfo;
  302. // maps a path to an HTTP error
  303. QHash<QString, int> _errorPaths;
  304. // monitor requests and optionally provide custom replies
  305. Override _override;
  306. public:
  307. FakeQNAM(FileInfo initialRoot);
  308. FileInfo &currentRemoteState() { return _remoteRootFileInfo; }
  309. FileInfo &uploadState() { return _uploadFileInfo; }
  310. QHash<QString, int> &errorPaths() { return _errorPaths; }
  311. void setOverride(const Override &override) { _override = override; }
  312. protected:
  313. QNetworkReply *createRequest(Operation op, const QNetworkRequest &request,
  314. QIODevice *outgoingData = nullptr) override;
  315. };
  316. class FakeCredentials : public OCC::AbstractCredentials
  317. {
  318. QNetworkAccessManager *_qnam;
  319. public:
  320. FakeCredentials(QNetworkAccessManager *qnam) : _qnam{qnam} { }
  321. virtual QString authType() const { return "test"; }
  322. virtual QString user() const { return "admin"; }
  323. virtual QString password() const { return "password"; }
  324. virtual QNetworkAccessManager *createQNAM() const { return _qnam; }
  325. virtual bool ready() const { return true; }
  326. virtual void fetchFromKeychain() { }
  327. virtual void askFromUser() { }
  328. virtual bool stillValid(QNetworkReply *) { return true; }
  329. virtual void persist() { }
  330. virtual void invalidateToken() { }
  331. virtual void forgetSensitiveData() { }
  332. };
  333. class FakeFolder
  334. {
  335. QTemporaryDir _tempDir;
  336. DiskFileModifier _localModifier;
  337. // FIXME: Clarify ownership, double delete
  338. FakeQNAM *_fakeQnam;
  339. OCC::AccountPtr _account;
  340. std::unique_ptr<OCC::SyncJournalDb> _journalDb;
  341. std::unique_ptr<OCC::SyncEngine> _syncEngine;
  342. public:
  343. FakeFolder(const FileInfo &fileTemplate, const OCC::Optional<FileInfo> &localFileInfo = {}, const QString &remotePath = {});
  344. void switchToVfs(QSharedPointer<OCC::Vfs> vfs);
  345. OCC::AccountPtr account() const { return _account; }
  346. OCC::SyncEngine &syncEngine() const { return *_syncEngine; }
  347. OCC::SyncJournalDb &syncJournal() const { return *_journalDb; }
  348. FileModifier &localModifier() { return _localModifier; }
  349. FileInfo &remoteModifier() { return _fakeQnam->currentRemoteState(); }
  350. FileInfo currentLocalState();
  351. FileInfo currentRemoteState() { return _fakeQnam->currentRemoteState(); }
  352. FileInfo &uploadState() { return _fakeQnam->uploadState(); }
  353. FileInfo dbState() const;
  354. struct ErrorList {
  355. FakeQNAM *_qnam;
  356. void append(const QString &path, int error = 500)
  357. { _qnam->errorPaths().insert(path, error); }
  358. void clear() { _qnam->errorPaths().clear(); }
  359. };
  360. ErrorList serverErrorPaths() { return {_fakeQnam}; }
  361. void setServerOverride(const FakeQNAM::Override &override) { _fakeQnam->setOverride(override); }
  362. QString localPath() const;
  363. void scheduleSync();
  364. void execUntilBeforePropagation();
  365. void execUntilItemCompleted(const QString &relativePath);
  366. bool execUntilFinished() {
  367. QSignalSpy spy(_syncEngine.get(), SIGNAL(finished(bool)));
  368. bool ok = spy.wait(3600000);
  369. Q_ASSERT(ok && "Sync timed out");
  370. return spy[0][0].toBool();
  371. }
  372. bool syncOnce() {
  373. scheduleSync();
  374. return execUntilFinished();
  375. }
  376. private:
  377. static void toDisk(QDir &dir, const FileInfo &templateFi);
  378. static void fromDisk(QDir &dir, FileInfo &templateFi);
  379. };
  380. /* Return the FileInfo for a conflict file for the specified relative filename */
  381. inline const FileInfo *findConflict(FileInfo &dir, const QString &filename)
  382. {
  383. QFileInfo info(filename);
  384. const FileInfo *parentDir = dir.find(info.path());
  385. if (!parentDir)
  386. return nullptr;
  387. QString start = info.baseName() + " (conflicted copy";
  388. for (const auto &item : parentDir->children) {
  389. if (item.name.startsWith(start)) {
  390. return &item;
  391. }
  392. }
  393. return nullptr;
  394. }
  395. struct ItemCompletedSpy : QSignalSpy {
  396. explicit ItemCompletedSpy(FakeFolder &folder)
  397. : QSignalSpy(&folder.syncEngine(), &OCC::SyncEngine::itemCompleted)
  398. {}
  399. OCC::SyncFileItemPtr findItem(const QString &path) const;
  400. };
  401. // QTest::toString overloads
  402. namespace OCC {
  403. inline char *toString(const SyncFileStatus &s) {
  404. return QTest::toString(QString("SyncFileStatus(" + s.toSocketAPIString() + ")"));
  405. }
  406. }
  407. inline void addFiles(QStringList &dest, const FileInfo &fi)
  408. {
  409. if (fi.isDir) {
  410. dest += QString("%1 - dir").arg(fi.path());
  411. foreach (const FileInfo &fi, fi.children)
  412. addFiles(dest, fi);
  413. } else {
  414. dest += QString("%1 - %2 %3-bytes").arg(fi.path()).arg(fi.size).arg(fi.contentChar);
  415. }
  416. }
  417. inline QString toStringNoElide(const FileInfo &fi)
  418. {
  419. QStringList files;
  420. foreach (const FileInfo &fi, fi.children)
  421. addFiles(files, fi);
  422. files.sort();
  423. return QString("FileInfo with %1 files(\n\t%2\n)").arg(files.size()).arg(files.join("\n\t"));
  424. }
  425. inline char *toString(const FileInfo &fi)
  426. {
  427. return QTest::toString(toStringNoElide(fi));
  428. }
  429. inline void addFilesDbData(QStringList &dest, const FileInfo &fi)
  430. {
  431. // could include etag, permissions etc, but would need extra work
  432. if (fi.isDir) {
  433. dest += QString("%1 - %2 %3 %4").arg(
  434. fi.name,
  435. fi.isDir ? "dir" : "file",
  436. QString::number(fi.lastModified.toSecsSinceEpoch()),
  437. fi.fileId);
  438. foreach (const FileInfo &fi, fi.children)
  439. addFilesDbData(dest, fi);
  440. } else {
  441. dest += QString("%1 - %2 %3 %4 %5").arg(
  442. fi.name,
  443. fi.isDir ? "dir" : "file",
  444. QString::number(fi.size),
  445. QString::number(fi.lastModified.toSecsSinceEpoch()),
  446. fi.fileId);
  447. }
  448. }
  449. inline char *printDbData(const FileInfo &fi)
  450. {
  451. QStringList files;
  452. foreach (const FileInfo &fi, fi.children)
  453. addFilesDbData(files, fi);
  454. return QTest::toString(QString("FileInfo with %1 files(%2)").arg(files.size()).arg(files.join(", ")));
  455. }