File indexing completed on 2024-12-01 04:35:28

0001 /*
0002    SPDX-FileCopyrightText: 2017-2024 Laurent Montel <montel@kde.org>
0003 
0004    SPDX-License-Identifier: LGPL-2.0-or-later
0005 */
0006 
0007 #pragma once
0008 
0009 #include <QDebug>
0010 #include <QJsonArray>
0011 #include <QJsonDocument>
0012 #include <QJsonObject>
0013 #include <QProcess>
0014 #include <QString>
0015 #include <QTest>
0016 
0017 namespace AutoTestHelper
0018 {
0019 void diffFile(const QString &refFile, const QString &generatedFile)
0020 {
0021     QProcess proc;
0022 #ifdef _WIN32
0023     QStringList args = QStringList() << QStringLiteral("Compare-Object") << QString(QStringLiteral("(Get-Content %1)")).arg(refFile)
0024                                      << QString(QStringLiteral("(Get-Content %1)")).arg(generatedFile);
0025 
0026     proc.start(QStringLiteral("powershell"), args);
0027     QVERIFY(proc.waitForFinished());
0028 
0029     auto pStdOut = proc.readAllStandardOutput();
0030     if (pStdOut.size()) {
0031         qDebug() << "Files are different, diff output message:\n" << pStdOut.toStdString().c_str();
0032     }
0033 
0034     QCOMPARE(pStdOut.size(), 0);
0035 #else
0036     // compare to reference file
0037     const QStringList args = QStringList() << QStringLiteral("-u") << refFile << generatedFile;
0038 
0039     proc.setProcessChannelMode(QProcess::ForwardedChannels);
0040     proc.start(QStringLiteral("diff"), args);
0041     QVERIFY(proc.waitForFinished());
0042     QCOMPARE(proc.exitCode(), 0);
0043 #endif
0044 }
0045 
0046 void compareFile(const QString &repo, const QByteArray &data, const QString &name)
0047 {
0048     const QString refFile = QLatin1String(RUQOLA_DATA_DIR) + repo + name + QStringLiteral(".ref");
0049     const QString generatedFile = QLatin1String(RUQOLA_BINARY_DATA_DIR) + repo + name + QStringLiteral("-generated.ref");
0050     QDir().mkpath(QLatin1String(RUQOLA_BINARY_DATA_DIR) + repo + name);
0051     // Create generated file
0052     QFile f(generatedFile);
0053     QVERIFY(f.open(QIODevice::WriteOnly | QIODevice::Truncate));
0054     f.write(data);
0055     f.close();
0056 
0057     diffFile(refFile, generatedFile);
0058 }
0059 
0060 QJsonDocument loadJsonDocument(const QString &originalJsonFile)
0061 {
0062     QFile f(originalJsonFile);
0063     [&]() {
0064         QVERIFY(f.open(QIODevice::ReadOnly));
0065     }();
0066     const auto content = f.readAll();
0067     f.close();
0068 
0069     QJsonParseError error;
0070     const auto doc = QJsonDocument::fromJson(content, &error);
0071     [&]() {
0072         QVERIFY2(!error.error, qPrintable(error.errorString()));
0073     }();
0074     return doc;
0075 }
0076 
0077 QJsonObject loadJsonObject(const QString &originalJsonFile)
0078 {
0079     return loadJsonDocument(originalJsonFile).object();
0080 }
0081 
0082 QJsonArray loadJsonArrayObject(const QString &originalJsonFile)
0083 {
0084     return loadJsonDocument(originalJsonFile).array();
0085 }
0086 }