#include "test_utilsmisc.h" #include #include "utils/misc.h" using namespace Utils::Misc; void TestUtilsMisc::initTestCase() {} void TestUtilsMisc::testRemoveIfStartsWith() { QString s = QStringLiteral("--*--testString"); QString result = removeIfStartsWith(s, QStringLiteral("--*--")); QString expected = QStringLiteral("testString"); QVERIFY(result == expected); } void TestUtilsMisc::testRemoveIfEndsWith() { QString s = QStringLiteral("testString--*--"); QString result = removeIfEndsWith(s, QStringLiteral("--*--")); QString expected = QStringLiteral("testString"); QVERIFY(result == expected); } void TestUtilsMisc::testPrependIfDoesNotStartWith() { QString s = QStringLiteral("testString"); QString result = prependIfDoesNotStartWith(s, QStringLiteral("--*--")); QString expected = QStringLiteral("--*--testString"); QVERIFY(result == expected); } void TestUtilsMisc::testAppendIfDoesNotEndWith() { QString s = QStringLiteral("testString"); QString result = appendIfDoesNotEndWith(s, QStringLiteral("--*--")); QString expected = QStringLiteral("testString--*--"); QVERIFY(result == expected); } void TestUtilsMisc::testStartDetachedProcess() { #ifdef Q_OS_UNIX auto result = startDetachedProcess("pwd", {}); QVERIFY2(result == true, "Failed to start detached process"); #else QSKIP("This test is skipped on non unix OS"); #endif } void TestUtilsMisc::testShorten() { QString s = QStringLiteral("A Long test string with lots of words"); const auto result = shorten(s, 10); QString expected = QStringLiteral("A Long ..."); QVERIFY(result == expected); } void TestUtilsMisc::testCycleTextCase() { // test empty string QString s = ""; QString result = cycleTextCase(s); QString expected = ""; QVERIFY(result == expected); // lower s = "lower case sentence"; result = cycleTextCase(s); expected = "LOWER CASE SENTENCE"; QVERIFY(result == expected); // upper s = "LOWER CASE SENTENCE"; result = cycleTextCase(s); expected = "Lower Case Sentence"; QVERIFY(result == expected); // start case s = "Lower Case Sentence"; result = cycleTextCase(s); expected = "Lower case sentence"; QVERIFY(result == expected); // sentence case s = "Lower case sentence"; result = cycleTextCase(s); expected = "lower case sentence"; QVERIFY(result == expected); // random 1 s = "LOWER CASE Sentence"; result = cycleTextCase(s); expected = "lower case sentence"; QVERIFY(result == expected); // random 2 s = "lower CASE Sentence"; result = cycleTextCase(s); expected = "lower case sentence"; QVERIFY(result == expected); } void TestUtilsMisc::testHtmlToMarkdown() { QString html = ""; html += ""; html += ""; html += "

Heading italic

"; html += "

Heading italic

"; html += "

Heading italic

"; html += "

Heading italicHeading *italic*"); const QString &t1 = "
  • [ ] task 1
  • "; const QString &r1 = parseTaskList(t1, true); QString expec = listTag + " task 1"; QVERIFY(r1 == expec); const QString &t2 = "
  • [x] task 2
  • "; const QString &r2 = parseTaskList(t2, true); expec = listTag + " task 2"; QVERIFY(r2 == expec); const QString &t3 = "
  • [x] task 3
  • "; const QString &r3 = parseTaskList(t3, false); expec = listTag + " ☑ task 3"; QVERIFY(r3 == expec); const QString &t4 = "
  • [ ] task 4
  • "; const QString &r4 = parseTaskList(t4, false); expec = listTag + " ☐ task 4"; QVERIFY(r4 == expec); } void TestUtilsMisc::testUnescapeHtml() { QString html = "

    hello

    \n

    hello

    "; QString result = unescapeHtml(html); QString expected = "hello\n\n\nhello"; QVERIFY(result == expected); } void TestUtilsMisc::testHtmlSpecialChars() { QString str = "& \" \' < >"; QString result = htmlspecialchars(str); QString expected = "& " ' < >"; QVERIFY(result == expected); } void TestUtilsMisc::testToHumanReadableByteSize() { qint64 bytes = 8712492; QString result = toHumanReadableByteSize(bytes); QString expected = "8.31 MB"; QVERIFY(result == expected); } void TestUtilsMisc::testTransformEvernoteImportCodeBlock() { QString content = R"( test
    This is a test note with some code blocks
    <?php

    phpinfo();

    ?>

    ]]>
    20181021T111619Z20181021T111738Zmyemail@example.comdesktop.winevernote.win32
    )"; QVERIFY(testEvernoteImportText(content) == R"(This is a test note with some code blocks ``` ```)"); } void TestUtilsMisc::testTransformEvernoteImportCodeBlock2() { QString content = R"( File manager

        /**
         * Gets the configuration path depending on the operation system
         *
         * @return bool|string
         */
        private static function getConfigPath()
        {
            $file_manager = new pm_ServerFileManager();
            if ($file_manager->fileExists('/etc/httpd/conf.d/pagespeed.conf')) {
                // CentOS
                return '/etc/httpd/conf.d/pagespeed.conf';
            } elseif ($file_manager->fileExists('/etc/apache2/mods-available/pagespeed.conf')) {
                // Ubuntu
                return '/etc/apache2/mods-available/pagespeed.conf';
            }
            return false;
        }

    ]]>
    20170703T093015Z20170703T093022Zmyemail@domain.comdesktop.winevernote.win32
    )"; QVERIFY(testEvernoteImportText(content) == R"(``` /** * Gets the configuration path depending on the operation system * * @return bool|string */ private static function getConfigPath() { $file_manager = new pm_ServerFileManager(); if ($file_manager->fileExists('/etc/httpd/conf.d/pagespeed.conf')) { // CentOS return '/etc/httpd/conf.d/pagespeed.conf'; } elseif ($file_manager->fileExists('/etc/apache2/mods-available/pagespeed.conf')) { // Ubuntu return '/etc/apache2/mods-available/pagespeed.conf'; } return false; } ```)"); } void TestUtilsMisc::testTransformEvernoteImportRussian() { QString content = R"( 15-3.1
    У меня дома две комнаты, кухня, туалет и ванна.
    ]]>
    20150714T065518Z20150714T073706Zmobile.android
    )"; QVERIFY(testEvernoteImportText(content) == R"(У меня дома две комнаты, кухня, туалет и ванна.)"); } void TestUtilsMisc::testTransformEvernoteImportHyperlinks() { QString content = R"( Fwd: Your 4 HIgh Value Trainings Access

    ]]>
    20151005T190855Z20151005T190915Z~ ReferenceR - PurchasesRP - Sean MizeRPSM - 4 High Value Trainings20151005T190849ZRick Smith <rick@netguerrilla.org>mail.smtp1
    )"; QVERIFY( testEvernoteImportText(content) == R"([4 High Value Trainings Access](https://seanmize.infusionsoft.com/app/linkClick/24286/45b5a4e4c9f46ab6/13909690/64482e72b8e684a3))"); } void TestUtilsMisc::testGetBaseUrlFromUrlString() { QString url = "https://www.example.com/path/to/file.html"; QString baseUrl = "https://www.example.com"; QString baseUrlWithBasePath = "https://www.example.com/path/to/"; QVERIFY(getBaseUrlFromUrlString(url) == baseUrl); QVERIFY(getBaseUrlFromUrlString(url, true) == baseUrlWithBasePath); } void TestUtilsMisc::testCreateAbsolutePathsInHtml() { QString url = "https://www.example.com/path/to/file.html"; QString html = R"(TestLink Link)"; QString expectedHtml = R"(TestLink Link)"; QVERIFY(createAbsolutePathsInHtml(html, url) == expectedHtml); } void TestUtilsMisc::testDetectFileFormatTxt() { QString text = "This is a plain text file.\nIt doesn't match any of the specific formats.\nJust regular " "text content."; QCOMPARE(detectFileFormat(text), QString("txt")); } void TestUtilsMisc::testDetectFileFormatJson() { QString text = R"({ "name": "John Doe", "age": 30, "email": "john@example.com", "address": { "street": "123 Main St", "city": "Anytown", "zip": "12345" }, "phoneNumbers": [ "555-1234", "555-5678" ] })"; QCOMPARE(detectFileFormat(text), QString("json")); } void TestUtilsMisc::testDetectFileFormatXml() { QString text = R"( John Doe 30 john@example.com Jane Smith 28 jane@example.com )"; QCOMPARE(detectFileFormat(text), QString("xml")); } void TestUtilsMisc::testDetectFileFormatXmlWithoutDeclaration() { QString text = R"(12399_AE_W_Rsa_1 0 SUCCESS 131506 )"; QCOMPARE(detectFileFormat(text), QString("xml")); } void TestUtilsMisc::testDetectFileFormatHtml() { QString text = R"( Sample Page

    Hello World

    This is a sample HTML page.

    )"; QCOMPARE(detectFileFormat(text), QString("html")); } void TestUtilsMisc::testDetectFileFormatCsv() { QString text = R"(Name,Age,Email,Department John Doe,30,john@example.com,Engineering Jane Smith,28,jane@example.com,Marketing Bob Johnson,35,bob@example.com,Finance Alice Williams,32,alice@example.com,HR)"; QCOMPARE(detectFileFormat(text), QString("csv")); } void TestUtilsMisc::testDetectFileFormatIni() { QString text = R"([Database] host=localhost port=3306 user=root password=secret [Application] debug=true log_level=info cache_enabled=1 ; This is a comment timeout=30)"; QCOMPARE(detectFileFormat(text), QString("ini")); } void TestUtilsMisc::testDetectFileFormatNix() { QString text = R"({ pkgs ? import {} }: with pkgs; stdenv.mkDerivation { name = "my-application"; version = "1.0.0"; src = fetchurl { url = "https://example.com/my-application-1.0.0.tar.gz"; sha256 = "0000000000000000000000000000000000000000000000000000"; }; buildInputs = [ gcc cmake zlib ]; configurePhase = '' cmake . ''; buildPhase = '' make ''; installPhase = '' make install ''; })"; QCOMPARE(detectFileFormat(text), QString("nix")); } void TestUtilsMisc::testDetectFileFormatYaml() { QString text = R"(name: project-config version: 1.0.0 description: Sample YAML configuration file environment: production: database: host: db.example.com port: 5432 user: admin password: secret cache: enabled: true ttl: 3600 development: database: host: localhost port: 5432 user: dev password: dev123 cache: enabled: false dependencies: - name: library1 version: "^2.0.0" - name: library2 version: "~1.5.0" logging: level: info format: json path: /var/log/app.log)"; QCOMPARE(detectFileFormat(text), QString("yaml")); } void TestUtilsMisc::testDetectFileFormatSql() { QString text = R"(CREATE TABLE employees ( employee_id SERIAL PRIMARY KEY, first_name VARCHAR(50) NOT NULL, last_name VARCHAR(50) NOT NULL, email VARCHAR(100) UNIQUE NOT NULL, hire_date DATE NOT NULL, salary NUMERIC(10, 2), department_id INTEGER REFERENCES departments(id) ); INSERT INTO employees (first_name, last_name, email, hire_date, salary, department_id) VALUES ('John', 'Doe', 'john.doe@example.com', '2023-01-15', 75000.00, 1), ('Jane', 'Smith', 'jane.smith@example.com', '2023-02-20', 82000.00, 2), ('Bob', 'Johnson', 'bob.johnson@example.com', '2023-03-10', 65000.00, 1); SELECT e.first_name, e.last_name, d.name AS department FROM employees e JOIN departments d ON e.department_id = d.id WHERE e.salary > 70000 ORDER BY e.last_name ASC;)"; QCOMPARE(detectFileFormat(text), QString("sql")); } void TestUtilsMisc::testDetectFileFormatJavaScript() { QString text = R"(// Sample JavaScript module for data processing import { formatDate } from './utils.js'; import * as math from 'mathjs'; const CONFIG = { precision: 2, dateFormat: 'YYYY-MM-DD', threshold: 0.5 }; class DataAnalyzer { constructor(data) { this.data = data; this.results = null; } preprocess() { // Filter out invalid entries return this.data.filter(item => item.value !== null && !isNaN(item.value)); } analyze() { const processed = this.preprocess(); // Calculate statistics const values = processed.map(item => item.value); const result = { mean: math.mean(values).toFixed(CONFIG.precision), median: math.median(values).toFixed(CONFIG.precision), stdDev: math.std(values).toFixed(CONFIG.precision), timestamp: formatDate(new Date(), CONFIG.dateFormat) }; this.results = result; return result; } generateReport() { if (!this.results) { this.analyze(); } return ` Data Analysis Report -------------------- Date: ${this.results.timestamp} Sample size: ${this.data.length} Mean value: ${this.results.mean} Median value: ${this.results.median} Standard deviation: ${this.results.stdDev} `; } } function processDataset(dataset) { const analyzer = new DataAnalyzer(dataset); const results = analyzer.analyze(); if (results.mean > CONFIG.threshold) { console.log("Warning: Mean value exceeds threshold"); } return analyzer.generateReport(); } export default { DataAnalyzer, processDataset };)"; QCOMPARE(detectFileFormat(text), QString("js")); } void TestUtilsMisc::testDetectFileFormatEdgeCases() { // Empty file QCOMPARE(detectFileFormat(""), QString("txt")); // Short text that doesn't match any format QCOMPARE(detectFileFormat("Hello world"), QString("txt")); // File with ambiguous format (INI vs CSV test case) QString ambiguousText = R"(zend_extension=xdebug.so xdebug.remote_enable=1 xdebug.remote_autostart=1)"; QCOMPARE(detectFileFormat(ambiguousText), QString("ini")); }