FreeCAD WebAssembly development snapshot
Some checks failed
FreeCAD master CI / Prepare (push) Has been cancelled
FreeCAD master CI / Pixi (push) Has been cancelled
FreeCAD master CI / Ubuntu (push) Has been cancelled
FreeCAD master CI / Windows (push) Has been cancelled
FreeCAD master CI / Lint (push) Has been cancelled
FreeCAD master CI / WrapUp (push) Has been cancelled
CodeQL Advanced / Analyze (actions) (push) Has been cancelled
CodeQL Advanced / Analyze (python) (push) Has been cancelled
Scorecard supply-chain security / Scorecard analysis (push) Has been cancelled
Stale Issues / stale (push) Has been cancelled
Some checks failed
FreeCAD master CI / Prepare (push) Has been cancelled
FreeCAD master CI / Pixi (push) Has been cancelled
FreeCAD master CI / Ubuntu (push) Has been cancelled
FreeCAD master CI / Windows (push) Has been cancelled
FreeCAD master CI / Lint (push) Has been cancelled
FreeCAD master CI / WrapUp (push) Has been cancelled
CodeQL Advanced / Analyze (actions) (push) Has been cancelled
CodeQL Advanced / Analyze (python) (push) Has been cancelled
Scorecard supply-chain security / Scorecard analysis (push) Has been cancelled
Stale Issues / stale (push) Has been cancelled
This commit is contained in:
59
tests/src/App/Application.cpp
Normal file
59
tests/src/App/Application.cpp
Normal file
@@ -0,0 +1,59 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
#define FC_OS_MACOSX 1
|
||||
#include "App/ProgramOptionsUtilities.h"
|
||||
|
||||
#include <src/App/InitApplication.h>
|
||||
|
||||
|
||||
using namespace App::Util;
|
||||
|
||||
using Spr = std::pair<std::string, std::string>;
|
||||
|
||||
|
||||
class ApplicationTest: public ::testing::Test
|
||||
{
|
||||
protected:
|
||||
static void SetUpTestSuite()
|
||||
{
|
||||
tests::initApplication();
|
||||
}
|
||||
};
|
||||
|
||||
TEST_F(ApplicationTest, fCustomSyntaxLookup)
|
||||
{
|
||||
Spr res {customSyntax("-display")};
|
||||
Spr exp {"display", "null"};
|
||||
EXPECT_EQ(res, exp);
|
||||
};
|
||||
TEST_F(ApplicationTest, fCustomSyntaxMac)
|
||||
{
|
||||
Spr res {customSyntax("-psn_stuff")};
|
||||
Spr exp {"psn", "stuff"};
|
||||
EXPECT_EQ(res, exp);
|
||||
};
|
||||
TEST_F(ApplicationTest, fCustomSyntaxWidgetCount)
|
||||
{
|
||||
Spr res {customSyntax("-widgetcount")};
|
||||
Spr exp {"widgetcount", ""};
|
||||
EXPECT_EQ(res, exp);
|
||||
}
|
||||
TEST_F(ApplicationTest, fCustomSyntaxNotFound)
|
||||
{
|
||||
Spr res {customSyntax("-displayx")};
|
||||
Spr exp {"", ""};
|
||||
EXPECT_EQ(res, exp);
|
||||
};
|
||||
TEST_F(ApplicationTest, fCustomSyntaxAmpersand)
|
||||
{
|
||||
Spr res {customSyntax("@freddie")};
|
||||
Spr exp {"response-file", "freddie"};
|
||||
EXPECT_EQ(res, exp);
|
||||
};
|
||||
TEST_F(ApplicationTest, fCustomSyntaxEmptyIn)
|
||||
{
|
||||
Spr res {customSyntax("")};
|
||||
Spr exp {"", ""};
|
||||
EXPECT_EQ(res, exp);
|
||||
};
|
||||
800
tests/src/App/ApplicationDirectories.cpp
Normal file
800
tests/src/App/ApplicationDirectories.cpp
Normal file
@@ -0,0 +1,800 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
#include <App/ApplicationDirectories.h>
|
||||
|
||||
#include <random>
|
||||
#include <fstream>
|
||||
#include "Base/Exception.h"
|
||||
|
||||
/* NOLINTBEGIN(
|
||||
readability-magic-numbers,
|
||||
cppcoreguidelines-avoid-magic-numbers,
|
||||
readability-function-cognitive-complexity
|
||||
) */
|
||||
|
||||
namespace fs = std::filesystem;
|
||||
|
||||
static fs::path MakeUniqueTempDir()
|
||||
{
|
||||
constexpr int maxTries = 128;
|
||||
const fs::path base = fs::temp_directory_path();
|
||||
std::random_device rd;
|
||||
std::mt19937_64 gen(rd());
|
||||
std::uniform_int_distribution<unsigned long long> dist;
|
||||
|
||||
for (int i = 0; i < maxTries; ++i) {
|
||||
auto name = "app_directories_test-" + std::to_string(dist(gen));
|
||||
fs::path candidate = base / name;
|
||||
std::error_code ec;
|
||||
if (fs::create_directory(candidate, ec)) {
|
||||
return candidate;
|
||||
}
|
||||
if (ec && ec != std::make_error_code(std::errc::file_exists)) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
throw std::runtime_error("Failed to create unique temp directory");
|
||||
}
|
||||
|
||||
/// A subclass to expose protected members for unit testing
|
||||
class ApplicationDirectoriesTestClass: public App::ApplicationDirectories
|
||||
{
|
||||
using App::ApplicationDirectories::ApplicationDirectories;
|
||||
|
||||
public:
|
||||
void wrapAppendVersionIfPossible(const fs::path& basePath, std::vector<std::string>& subdirs) const
|
||||
{
|
||||
appendVersionIfPossible(basePath, subdirs);
|
||||
}
|
||||
|
||||
std::tuple<int, int> wrapExtractVersionFromConfigMap(
|
||||
const std::map<std::string, std::string>& config
|
||||
)
|
||||
{
|
||||
return extractVersionFromConfigMap(config);
|
||||
}
|
||||
|
||||
static std::filesystem::path wrapSanitizePath(const std::string& pathAsString)
|
||||
{
|
||||
return sanitizePath(pathAsString);
|
||||
}
|
||||
};
|
||||
|
||||
class ApplicationDirectoriesTest: public ::testing::Test
|
||||
{
|
||||
protected:
|
||||
void SetUp() override
|
||||
{
|
||||
_tempDir = MakeUniqueTempDir();
|
||||
}
|
||||
|
||||
std::map<std::string, std::string> generateConfig(
|
||||
const std::map<std::string, std::string>& overrides
|
||||
) const
|
||||
{
|
||||
std::map<std::string, std::string> config {
|
||||
{"AppHomePath", _tempDir.string()},
|
||||
{"ExeVendor", "Vendor"},
|
||||
{"ExeName", "Test"},
|
||||
{"BuildVersionMajor", "4"},
|
||||
{"BuildVersionMinor", "2"}
|
||||
};
|
||||
for (const auto& override : overrides) {
|
||||
config[override.first] = override.second;
|
||||
}
|
||||
return config;
|
||||
}
|
||||
|
||||
std::unique_ptr<ApplicationDirectoriesTestClass> makeAppDirsForVersion(int major, int minor)
|
||||
{
|
||||
auto configuration = generateConfig(
|
||||
{{"BuildVersionMajor", std::to_string(major)},
|
||||
{"BuildVersionMinor", std::to_string(minor)}}
|
||||
);
|
||||
return std::make_unique<ApplicationDirectoriesTestClass>(configuration);
|
||||
}
|
||||
|
||||
fs::path makePathForVersion(const fs::path& base, int major, int minor)
|
||||
{
|
||||
return base / App::ApplicationDirectories::versionStringForPath(major, minor);
|
||||
}
|
||||
|
||||
void TearDown() override
|
||||
{
|
||||
fs::remove_all(_tempDir);
|
||||
}
|
||||
|
||||
fs::path tempDir()
|
||||
{
|
||||
return _tempDir;
|
||||
}
|
||||
|
||||
private:
|
||||
fs::path _tempDir;
|
||||
};
|
||||
|
||||
namespace fs = std::filesystem;
|
||||
|
||||
|
||||
TEST_F(ApplicationDirectoriesTest, usingCurrentVersionConfigTrueWhenDirMatchesVersion)
|
||||
{
|
||||
// Arrange
|
||||
constexpr int major = 3;
|
||||
constexpr int minor = 7;
|
||||
const fs::path testPath = fs::path("some_kind_of_config")
|
||||
/ App::ApplicationDirectories::versionStringForPath(major, minor);
|
||||
|
||||
// Act: generate a directory structure with the same version
|
||||
auto appDirs = makeAppDirsForVersion(major, minor);
|
||||
|
||||
// Assert
|
||||
EXPECT_TRUE(appDirs->usingCurrentVersionConfig(testPath));
|
||||
}
|
||||
|
||||
TEST_F(ApplicationDirectoriesTest, usingCurrentVersionConfigFalseWhenDirDoesntMatchVersion)
|
||||
{
|
||||
// Arrange
|
||||
constexpr int major = 3;
|
||||
constexpr int minor = 7;
|
||||
const fs::path testPath = fs::path("some_kind_of_config")
|
||||
/ App::ApplicationDirectories::versionStringForPath(major, minor);
|
||||
|
||||
// Act: generate a directory structure with the same version
|
||||
auto configuration = generateConfig(
|
||||
{{"BuildVersionMajor", std::to_string(major + 1)},
|
||||
{"BuildVersionMinor", std::to_string(minor)}}
|
||||
);
|
||||
auto appDirs = std::make_unique<App::ApplicationDirectories>(configuration);
|
||||
|
||||
// Assert
|
||||
EXPECT_FALSE(appDirs->usingCurrentVersionConfig(testPath));
|
||||
}
|
||||
|
||||
// Exact current version (hits: major==currentMajor path; inner if true)
|
||||
TEST_F(ApplicationDirectoriesTest, isVersionedPathMatchesCurrentMajorAndMinor)
|
||||
{
|
||||
auto appDirs = makeAppDirsForVersion(5, 4);
|
||||
fs::path p = makePathForVersion(tempDir(), 5, 4);
|
||||
EXPECT_TRUE(appDirs->isVersionedPath(p));
|
||||
}
|
||||
|
||||
// Lower minor within the same major (major==currentMajor path; iterates down to a smaller minor)
|
||||
TEST_F(ApplicationDirectoriesTest, isVersionedPathMatchesLowerMinorSameMajor)
|
||||
{
|
||||
auto appDirs = makeAppDirsForVersion(5, 4);
|
||||
fs::path p = makePathForVersion(tempDir(), 5, 2);
|
||||
EXPECT_TRUE(appDirs->isVersionedPath(p));
|
||||
}
|
||||
|
||||
// Lower major (major!=currentMajor path)
|
||||
TEST_F(ApplicationDirectoriesTest, isVersionedPathMatchesLowerMajorAnyMinor)
|
||||
{
|
||||
auto appDirs = makeAppDirsForVersion(5, 4);
|
||||
fs::path p = makePathForVersion(tempDir(), 4, 7);
|
||||
EXPECT_TRUE(appDirs->isVersionedPath(p));
|
||||
}
|
||||
|
||||
// Boundary: minor==0 within the same major
|
||||
TEST_F(ApplicationDirectoriesTest, isVersionedPathMatchesZeroMinorSameMajor)
|
||||
{
|
||||
auto appDirs = makeAppDirsForVersion(5, 4);
|
||||
fs::path p = makePathForVersion(tempDir(), 5, 0);
|
||||
EXPECT_TRUE(appDirs->isVersionedPath(p));
|
||||
}
|
||||
|
||||
// Negative: higher minor than current for the same major is never iterated
|
||||
TEST_F(ApplicationDirectoriesTest, isVersionedPathDoesNotMatchHigherMinorSameMajor)
|
||||
{
|
||||
auto appDirs = makeAppDirsForVersion(5, 4);
|
||||
fs::path p = makePathForVersion(tempDir(), 5, 5);
|
||||
EXPECT_FALSE(appDirs->isVersionedPath(p));
|
||||
}
|
||||
|
||||
// Negative: higher major than current is never iterated; also covers "non-version" style
|
||||
TEST_F(ApplicationDirectoriesTest, isVersionedPathDoesNotMatchHigherMajorOrRandomName)
|
||||
{
|
||||
auto appDirs = makeAppDirsForVersion(5, 4);
|
||||
|
||||
fs::path higherMajor = makePathForVersion(tempDir(), 6, 1);
|
||||
EXPECT_FALSE(appDirs->isVersionedPath(higherMajor));
|
||||
|
||||
fs::path randomName = tempDir() / "not-a-version";
|
||||
EXPECT_FALSE(appDirs->isVersionedPath(randomName));
|
||||
}
|
||||
|
||||
// Convenience: path under base for a version folder name.
|
||||
fs::path versionedPath(const fs::path& base, int major, int minor)
|
||||
{
|
||||
return base / App::ApplicationDirectories::versionStringForPath(major, minor);
|
||||
}
|
||||
|
||||
// Create a regular file (used to prove non-directories are ignored).
|
||||
void touchFile(const fs::path& p)
|
||||
{
|
||||
fs::create_directories(p.parent_path());
|
||||
std::ofstream ofs(p.string());
|
||||
ofs << "x";
|
||||
}
|
||||
|
||||
// The exact current version exists -> returned immediately (current-major branch).
|
||||
TEST_F(ApplicationDirectoriesTest, mostRecentAvailReturnsExactCurrentVersionIfDirectoryExists)
|
||||
{
|
||||
auto appDirs = makeAppDirsForVersion(5, 4);
|
||||
fs::create_directories(versionedPath(tempDir(), 5, 4));
|
||||
|
||||
EXPECT_EQ(
|
||||
appDirs->mostRecentAvailableConfigVersion(tempDir()),
|
||||
App::ApplicationDirectories::versionStringForPath(5, 4)
|
||||
);
|
||||
}
|
||||
|
||||
// No exact match in the current major: choose the highest available minor <= current
|
||||
// and prefer the current major over lower majors.
|
||||
TEST_F(ApplicationDirectoriesTest, mostRecentAvailPrefersSameMajorAndPicksHighestLowerMinor)
|
||||
{
|
||||
auto appDirs = makeAppDirsForVersion(5, 4);
|
||||
fs::create_directories(versionedPath(tempDir(), 5, 1));
|
||||
fs::create_directories(versionedPath(tempDir(), 5, 3));
|
||||
fs::create_directories(versionedPath(tempDir(), 4, 99)); // distractor in lower major
|
||||
|
||||
EXPECT_EQ(
|
||||
appDirs->mostRecentAvailableConfigVersion(tempDir()),
|
||||
App::ApplicationDirectories::versionStringForPath(5, 3)
|
||||
);
|
||||
}
|
||||
|
||||
// No directories in current major: scan next lower major from 99 downward,
|
||||
// returning the highest available minor present (demonstrates descending search).
|
||||
TEST_F(ApplicationDirectoriesTest, mostRecentAvailForLowerMajorPicksHighestAvailableMinor)
|
||||
{
|
||||
auto appDirs = makeAppDirsForVersion(5, 4);
|
||||
fs::create_directories(versionedPath(tempDir(), 4, 3));
|
||||
fs::create_directories(versionedPath(tempDir(), 4, 42));
|
||||
|
||||
EXPECT_EQ(
|
||||
appDirs->mostRecentAvailableConfigVersion(tempDir()),
|
||||
App::ApplicationDirectories::versionStringForPath(4, 42)
|
||||
);
|
||||
}
|
||||
|
||||
// If the candidate path exists but is a regular file, it must be ignored and
|
||||
// the search must fall back to the next available directory.
|
||||
TEST_F(ApplicationDirectoriesTest, mostRecentAvailSkipsFilesAndFallsBackToNextDirectory)
|
||||
{
|
||||
auto appDirs = makeAppDirsForVersion(5, 4);
|
||||
touchFile(versionedPath(tempDir(), 5, 4)); // file at the current version
|
||||
fs::create_directories(versionedPath(tempDir(), 5, 3)); // directory at next lower minor
|
||||
|
||||
EXPECT_EQ(
|
||||
appDirs->mostRecentAvailableConfigVersion(tempDir()),
|
||||
App::ApplicationDirectories::versionStringForPath(5, 3)
|
||||
);
|
||||
}
|
||||
|
||||
// Higher minor in the current major is not considered (loop starts at the current minor);
|
||||
// should fall through to the lower major when nothing <= the current minor exists.
|
||||
TEST_F(ApplicationDirectoriesTest, mostRecentAvailIgnoresHigherMinorThanCurrentInSameMajor)
|
||||
{
|
||||
auto appDirs = makeAppDirsForVersion(5, 4);
|
||||
fs::create_directories(versionedPath(tempDir(), 5, 7)); // higher than the current minor; ignored
|
||||
fs::create_directories(versionedPath(tempDir(), 4, 1)); // fallback target
|
||||
|
||||
EXPECT_EQ(
|
||||
appDirs->mostRecentAvailableConfigVersion(tempDir()),
|
||||
App::ApplicationDirectories::versionStringForPath(4, 1)
|
||||
);
|
||||
}
|
||||
|
||||
// No candidates anywhere -> empty string returned.
|
||||
TEST_F(ApplicationDirectoriesTest, mostRecentAvailReturnsEmptyStringWhenNoVersionsPresent)
|
||||
{
|
||||
auto appDirs = makeAppDirsForVersion(5, 4);
|
||||
EXPECT_EQ(appDirs->mostRecentAvailableConfigVersion(tempDir()), "");
|
||||
}
|
||||
|
||||
|
||||
// The current version directory exists -> returned immediately
|
||||
TEST_F(ApplicationDirectoriesTest, mostRecentConfigReturnsCurrentVersionDirectoryIfPresent)
|
||||
{
|
||||
auto appDirs = makeAppDirsForVersion(5, 4);
|
||||
fs::create_directories(versionedPath(tempDir(), 5, 4));
|
||||
|
||||
fs::path got = appDirs->mostRecentConfigFromBase(tempDir());
|
||||
EXPECT_EQ(got, versionedPath(tempDir(), 5, 4));
|
||||
}
|
||||
|
||||
// The current version missing -> falls back to most recent available in same major
|
||||
TEST_F(ApplicationDirectoriesTest, mostRecentConfigFallsBackToMostRecentInSameMajorWhenCurrentMissing)
|
||||
{
|
||||
auto appDirs = makeAppDirsForVersion(5, 4);
|
||||
// There is no directory called "5.4"; provide candidates 5.3 and 5.1; also a distractor in a
|
||||
// lower major.
|
||||
fs::create_directories(versionedPath(tempDir(), 5, 1));
|
||||
fs::create_directories(versionedPath(tempDir(), 5, 3));
|
||||
fs::create_directories(versionedPath(tempDir(), 4, 99));
|
||||
|
||||
fs::path got = appDirs->mostRecentConfigFromBase(tempDir());
|
||||
EXPECT_EQ(got, versionedPath(tempDir(), 5, 3));
|
||||
}
|
||||
|
||||
// The current version path exists as a file (not directory) -> ignored, fallback used
|
||||
TEST_F(ApplicationDirectoriesTest, mostRecentConfigSkipsFileAtCurrentVersionAndFallsBack)
|
||||
{
|
||||
auto appDirs = makeAppDirsForVersion(5, 4);
|
||||
touchFile(versionedPath(tempDir(), 5, 4)); // file, not dir
|
||||
fs::create_directories(versionedPath(tempDir(), 5, 2));
|
||||
|
||||
fs::path got = appDirs->mostRecentConfigFromBase(tempDir());
|
||||
EXPECT_EQ(got, versionedPath(tempDir(), 5, 2));
|
||||
}
|
||||
|
||||
// There are no eligible versions in the current major -> choose the highest available in lower
|
||||
// majors
|
||||
TEST_F(ApplicationDirectoriesTest, mostRecentConfigFallsBackToHighestVersionInLowerMajors)
|
||||
{
|
||||
auto appDirs = makeAppDirsForVersion(5, 4);
|
||||
|
||||
// No 5.x minor <= 4 exists. (Optionally add a higher minor to prove it's ignored.)
|
||||
fs::create_directories(versionedPath(tempDir(), 5, 7)); // ignored (higher than current minor)
|
||||
|
||||
// Provide multiple lower-major candidates; should pick 4.90 over 3.99.
|
||||
fs::create_directories(versionedPath(tempDir(), 4, 3));
|
||||
fs::create_directories(versionedPath(tempDir(), 4, 90));
|
||||
fs::create_directories(versionedPath(tempDir(), 3, 99));
|
||||
|
||||
fs::path got = appDirs->mostRecentConfigFromBase(tempDir());
|
||||
EXPECT_EQ(got, versionedPath(tempDir(), 4, 90));
|
||||
}
|
||||
|
||||
// There is nothing available anywhere -> returns startingPath
|
||||
TEST_F(ApplicationDirectoriesTest, mostRecentConfigReturnsStartingPathWhenNoVersionedConfigExists)
|
||||
{
|
||||
auto appDirs = makeAppDirsForVersion(5, 4);
|
||||
fs::path got = appDirs->mostRecentConfigFromBase(tempDir());
|
||||
EXPECT_EQ(got, tempDir());
|
||||
}
|
||||
|
||||
// True: exact current version directory
|
||||
TEST_F(ApplicationDirectoriesTest, usingCurrentVersionExactVersionDir)
|
||||
{
|
||||
auto appDirs = makeAppDirsForVersion(5, 4);
|
||||
fs::create_directories(versionedPath(tempDir(), 5, 4));
|
||||
|
||||
EXPECT_TRUE(appDirs->usingCurrentVersionConfig(versionedPath(tempDir(), 5, 4)));
|
||||
}
|
||||
|
||||
// True: current version directory with trailing separator (exercises filename().empty() branch)
|
||||
TEST_F(ApplicationDirectoriesTest, usingCurrentVersionVersionDirWithTrailingSlash)
|
||||
{
|
||||
auto appDirs = makeAppDirsForVersion(5, 4);
|
||||
fs::create_directories(versionedPath(tempDir(), 5, 4));
|
||||
fs::path p = versionedPath(tempDir(), 5, 4) / ""; // ensure trailing separator
|
||||
|
||||
EXPECT_TRUE(appDirs->usingCurrentVersionConfig(p));
|
||||
}
|
||||
|
||||
// False: a file inside the current version directory (filename != version string)
|
||||
TEST_F(ApplicationDirectoriesTest, usingCurrentVersionFileInsideVersionDirIsFalse)
|
||||
{
|
||||
auto appDirs = makeAppDirsForVersion(5, 4);
|
||||
fs::path filePath = versionedPath(tempDir(), 5, 4) / "config.yaml";
|
||||
touchFile(filePath);
|
||||
|
||||
EXPECT_FALSE(appDirs->usingCurrentVersionConfig(filePath));
|
||||
}
|
||||
|
||||
// False: lower version directory
|
||||
TEST_F(ApplicationDirectoriesTest, usingCurrentVersionLowerVersionDirIsFalse)
|
||||
{
|
||||
auto appDirs = makeAppDirsForVersion(5, 4);
|
||||
fs::create_directories(versionedPath(tempDir(), 5, 3));
|
||||
|
||||
EXPECT_FALSE(appDirs->usingCurrentVersionConfig(versionedPath(tempDir(), 5, 3)));
|
||||
}
|
||||
|
||||
// False: higher version directory
|
||||
TEST_F(ApplicationDirectoriesTest, usingCurrentVersionHigherVersionDirIsFalse)
|
||||
{
|
||||
auto appDirs = makeAppDirsForVersion(5, 4);
|
||||
fs::create_directories(versionedPath(tempDir(), 6, 0));
|
||||
|
||||
EXPECT_FALSE(appDirs->usingCurrentVersionConfig(versionedPath(tempDir(), 6, 0)));
|
||||
}
|
||||
|
||||
// False: non-version directory (e.g., base dir)
|
||||
TEST_F(ApplicationDirectoriesTest, usingCurrentVersionNonVersionDirIsFalse)
|
||||
{
|
||||
auto appDirs = makeAppDirsForVersion(5, 4);
|
||||
fs::create_directories(tempDir());
|
||||
|
||||
EXPECT_FALSE(appDirs->usingCurrentVersionConfig(tempDir()));
|
||||
}
|
||||
|
||||
void writeFile(const fs::path& p, std::string_view contents)
|
||||
{
|
||||
fs::create_directories(p.parent_path());
|
||||
std::ofstream ofs(p.string(), std::ios::binary);
|
||||
ofs << contents;
|
||||
}
|
||||
|
||||
std::string readFile(const fs::path& p)
|
||||
{
|
||||
std::ifstream ifs(p.string(), std::ios::binary);
|
||||
return {std::istreambuf_iterator<char>(ifs), {}};
|
||||
}
|
||||
|
||||
// Creates destination and copies flat files over
|
||||
TEST_F(ApplicationDirectoriesTest, migrateConfigCreatesDestinationAndCopiesFiles)
|
||||
{
|
||||
// Arrange
|
||||
fs::path oldPath = tempDir() / "old";
|
||||
fs::path newPath = tempDir() / "new";
|
||||
writeFile(oldPath / "a.txt", "alpha");
|
||||
writeFile(oldPath / "b.ini", "bravo");
|
||||
|
||||
// Act
|
||||
App::ApplicationDirectories::migrateConfig(oldPath, newPath);
|
||||
|
||||
// Assert
|
||||
ASSERT_TRUE(fs::exists(newPath));
|
||||
ASSERT_TRUE(fs::is_directory(newPath));
|
||||
|
||||
EXPECT_TRUE(fs::exists(newPath / "a.txt"));
|
||||
EXPECT_TRUE(fs::exists(newPath / "b.ini"));
|
||||
EXPECT_EQ(readFile(newPath / "a.txt"), "alpha");
|
||||
EXPECT_EQ(readFile(newPath / "b.ini"), "bravo");
|
||||
|
||||
EXPECT_TRUE(fs::exists(oldPath / "a.txt"));
|
||||
EXPECT_TRUE(fs::exists(oldPath / "b.ini"));
|
||||
}
|
||||
|
||||
// newPath is a subdirectory of oldPath -> skip copying newPath into itself
|
||||
TEST_F(ApplicationDirectoriesTest, migrateConfigSkipsSelfWhenNewIsSubdirectoryOfOld)
|
||||
{
|
||||
// Arrange
|
||||
fs::path oldPath = tempDir() / "container";
|
||||
fs::path newPath = oldPath / "migrated";
|
||||
writeFile(oldPath / "c.yaml", "charlie");
|
||||
writeFile(oldPath / "d.cfg", "delta");
|
||||
|
||||
// Act
|
||||
App::ApplicationDirectories::migrateConfig(oldPath, newPath);
|
||||
|
||||
// Assert
|
||||
ASSERT_TRUE(fs::exists(newPath));
|
||||
ASSERT_TRUE(fs::is_directory(newPath));
|
||||
EXPECT_TRUE(fs::exists(newPath / "c.yaml"));
|
||||
EXPECT_TRUE(fs::exists(newPath / "d.cfg"));
|
||||
|
||||
// Do not copy the destination back into itself (no nested 'migrated/migrated')
|
||||
EXPECT_FALSE(fs::exists(newPath / newPath.filename()));
|
||||
}
|
||||
|
||||
// oldPath empty -> still creates the destination and does nothing else
|
||||
TEST_F(ApplicationDirectoriesTest, migrateConfigEmptyOldPathJustCreatesDestination)
|
||||
{
|
||||
fs::path oldPath = tempDir() / "empty_old";
|
||||
fs::path newPath = tempDir() / "dest_only";
|
||||
|
||||
fs::create_directories(oldPath);
|
||||
App::ApplicationDirectories::migrateConfig(oldPath, newPath);
|
||||
|
||||
ASSERT_TRUE(fs::exists(newPath));
|
||||
ASSERT_TRUE(fs::is_directory(newPath));
|
||||
|
||||
// No files expected
|
||||
bool hasEntries = (fs::directory_iterator(newPath) != fs::directory_iterator {});
|
||||
EXPECT_FALSE(hasEntries);
|
||||
}
|
||||
|
||||
// Case: recursively copy nested directories and files
|
||||
TEST_F(ApplicationDirectoriesTest, migrateConfigRecursivelyCopiesDirectoriesAndFiles)
|
||||
{
|
||||
fs::path oldPath = tempDir() / "old_tree";
|
||||
fs::path newPath = tempDir() / "new_tree";
|
||||
|
||||
// old_tree/
|
||||
// config/
|
||||
// env/
|
||||
// a.txt
|
||||
// empty_dir/
|
||||
writeFile(oldPath / "config" / "env" / "a.txt", "alpha");
|
||||
fs::create_directories(oldPath / "empty_dir");
|
||||
|
||||
App::ApplicationDirectories::migrateConfig(oldPath, newPath);
|
||||
|
||||
// Expect structure replicated under newPath
|
||||
ASSERT_TRUE(fs::exists(newPath));
|
||||
EXPECT_TRUE(fs::exists(newPath / "config"));
|
||||
EXPECT_TRUE(fs::exists(newPath / "config" / "env"));
|
||||
EXPECT_TRUE(fs::exists(newPath / "config" / "env" / "a.txt"));
|
||||
EXPECT_EQ(readFile(newPath / "config" / "env" / "a.txt"), "alpha");
|
||||
|
||||
// Empty directories should be created as well
|
||||
EXPECT_TRUE(fs::exists(newPath / "empty_dir"));
|
||||
EXPECT_TRUE(fs::is_directory(newPath / "empty_dir"));
|
||||
}
|
||||
|
||||
// Case: newPath is subdir of oldPath -> recursively copy, but do NOT copy newPath into itself
|
||||
TEST_F(ApplicationDirectoriesTest, migrateConfigNewPathSubdirRecursivelyCopiesAndSkipsSelf)
|
||||
{
|
||||
fs::path oldPath = tempDir() / "src_tree";
|
||||
fs::path newPath = oldPath / "migrated"; // destination under source
|
||||
|
||||
// src_tree/
|
||||
// folderA/
|
||||
// child/
|
||||
// f.txt
|
||||
writeFile(oldPath / "folderA" / "child" / "f.txt", "filedata");
|
||||
|
||||
App::ApplicationDirectories::migrateConfig(oldPath, newPath);
|
||||
|
||||
// Copied recursively into destination
|
||||
EXPECT_TRUE(fs::exists(newPath / "folderA" / "child" / "f.txt"));
|
||||
EXPECT_EQ(readFile(newPath / "folderA" / "child" / "f.txt"), "filedata");
|
||||
|
||||
// Do not copy the destination back into itself (no migrated/migrated)
|
||||
EXPECT_FALSE(fs::exists(newPath / newPath.filename()));
|
||||
}
|
||||
|
||||
// Versioned input: `path` == base/<some older version>` -> newPath == base/<current>
|
||||
TEST_F(ApplicationDirectoriesTest, migrateAllPathsVersionedInputChoosesParentPlusCurrent)
|
||||
{
|
||||
auto appDirs = makeAppDirsForVersion(5, 4);
|
||||
|
||||
fs::path base = tempDir() / "v_branch";
|
||||
fs::path older = versionedPath(base, 5, 1); // versioned input (isVersionedPath == true)
|
||||
fs::create_directories(older);
|
||||
writeFile(older / "sentinel.txt", "s");
|
||||
|
||||
std::vector<fs::path> inputs {older};
|
||||
appDirs->migrateAllPaths(inputs);
|
||||
|
||||
fs::path expectedDest = versionedPath(base, 5, 4);
|
||||
EXPECT_TRUE(fs::exists(expectedDest));
|
||||
EXPECT_TRUE(fs::is_directory(expectedDest));
|
||||
}
|
||||
|
||||
// Non-versioned input: `path` == base -> newPath == base/<current>
|
||||
TEST_F(ApplicationDirectoriesTest, migrateAllPathsNonVersionedInputAppendsCurrent)
|
||||
{
|
||||
auto appDirs = makeAppDirsForVersion(5, 4);
|
||||
|
||||
fs::path base = tempDir() / "plain_base";
|
||||
fs::create_directories(base);
|
||||
writeFile(base / "config.yaml", "x");
|
||||
|
||||
std::vector<fs::path> inputs {base};
|
||||
appDirs->migrateAllPaths(inputs);
|
||||
|
||||
fs::path expectedDest = versionedPath(base, 5, 4);
|
||||
EXPECT_TRUE(fs::exists(expectedDest));
|
||||
EXPECT_TRUE(fs::is_directory(expectedDest));
|
||||
}
|
||||
|
||||
// Pre-existing destination -> throws Base::RuntimeError
|
||||
TEST_F(ApplicationDirectoriesTest, migrateAllPathsIgnoresIfDestinationAlreadyExists_NonVersioned)
|
||||
{
|
||||
auto appDirs = makeAppDirsForVersion(5, 4);
|
||||
|
||||
fs::path base = tempDir() / "exists_case";
|
||||
fs::create_directories(base);
|
||||
fs::path dest = versionedPath(base, 5, 4);
|
||||
fs::create_directories(dest); // destination already exists
|
||||
|
||||
std::vector<fs::path> inputs {base};
|
||||
|
||||
ASSERT_NO_THROW(appDirs->migrateAllPaths(inputs));
|
||||
}
|
||||
|
||||
// Multiple inputs: one versioned, one non-versioned -> both destinations created
|
||||
TEST_F(ApplicationDirectoriesTest, migrateAllPathsProcessesMultipleInputs)
|
||||
{
|
||||
auto appDirs = makeAppDirsForVersion(5, 4);
|
||||
|
||||
// Versioned input A: baseA/5.2
|
||||
fs::path baseA = tempDir() / "multiA";
|
||||
fs::path olderA = versionedPath(baseA, 5, 2);
|
||||
fs::create_directories(olderA);
|
||||
writeFile(olderA / "a.txt", "a");
|
||||
|
||||
// Non-versioned input B: baseB
|
||||
fs::path baseB = tempDir() / "multiB";
|
||||
fs::create_directories(baseB);
|
||||
writeFile(baseB / "b.txt", "b");
|
||||
|
||||
std::vector<fs::path> inputs {olderA, baseB};
|
||||
appDirs->migrateAllPaths(inputs);
|
||||
|
||||
EXPECT_TRUE(fs::exists(versionedPath(baseA, 5, 4))); // parent_path() / current
|
||||
EXPECT_TRUE(fs::exists(versionedPath(baseB, 5, 4))); // base / current
|
||||
}
|
||||
|
||||
// Already versioned (final component is a version) -> no change
|
||||
TEST_F(ApplicationDirectoriesTest, appendVecAlreadyVersionedBails)
|
||||
{
|
||||
auto appDirs = makeAppDirsForVersion(5, 4);
|
||||
|
||||
fs::path base = tempDir() / "bail_vec";
|
||||
std::vector<std::string> sub {
|
||||
"configs",
|
||||
App::ApplicationDirectories::versionStringForPath(5, 2)
|
||||
}; // versioned tail
|
||||
fs::create_directories(base / sub[0] / sub[1]);
|
||||
|
||||
auto before = sub;
|
||||
appDirs->wrapAppendVersionIfPossible(base, sub);
|
||||
EXPECT_EQ(sub, before); // unchanged
|
||||
}
|
||||
|
||||
// Base exists & current version dir present -> append current
|
||||
TEST_F(ApplicationDirectoriesTest, appendVecBaseExistsAppendsCurrentWhenPresent)
|
||||
{
|
||||
auto appDirs = makeAppDirsForVersion(5, 4);
|
||||
|
||||
fs::path base = tempDir() / "vec_current";
|
||||
std::vector<std::string> sub {"configs"};
|
||||
fs::create_directories(base / "configs");
|
||||
fs::create_directories(versionedPath(base / "configs", 5, 4));
|
||||
|
||||
appDirs->wrapAppendVersionIfPossible(base, sub);
|
||||
|
||||
ASSERT_EQ(sub.size(), 2u);
|
||||
EXPECT_EQ(sub.back(), App::ApplicationDirectories::versionStringForPath(5, 4));
|
||||
}
|
||||
|
||||
// Base exists, no current; lower minors exist -> append highest ≤ current in same major
|
||||
TEST_F(ApplicationDirectoriesTest, appendVecPicksHighestLowerMinorInSameMajor)
|
||||
{
|
||||
auto appDirs = makeAppDirsForVersion(5, 4);
|
||||
|
||||
fs::path base = tempDir() / "vec_lower_minor";
|
||||
std::vector<std::string> sub {"configs"};
|
||||
fs::create_directories(versionedPath(base / "configs", 5, 1));
|
||||
fs::create_directories(versionedPath(base / "configs", 5, 3));
|
||||
// distractor in lower major
|
||||
fs::create_directories(versionedPath(base / "configs", 4, 99));
|
||||
|
||||
appDirs->wrapAppendVersionIfPossible(base, sub);
|
||||
|
||||
ASSERT_EQ(sub.size(), 2u);
|
||||
EXPECT_EQ(sub.back(), App::ApplicationDirectories::versionStringForPath(5, 3));
|
||||
}
|
||||
|
||||
// Base exists, nothing in current major; lower major exists -> append highest available lower major
|
||||
TEST_F(ApplicationDirectoriesTest, appendVecFallsBackToLowerMajor)
|
||||
{
|
||||
auto appDirs = makeAppDirsForVersion(5, 4);
|
||||
|
||||
fs::path base = tempDir() / "vec_lower_major";
|
||||
std::vector<std::string> sub {"configs"};
|
||||
fs::create_directories(versionedPath(base / "configs", 4, 90));
|
||||
fs::create_directories(versionedPath(base / "configs", 3, 99));
|
||||
|
||||
appDirs->wrapAppendVersionIfPossible(base, sub);
|
||||
|
||||
ASSERT_EQ(sub.size(), 2u);
|
||||
EXPECT_EQ(sub.back(), App::ApplicationDirectories::versionStringForPath(4, 90));
|
||||
}
|
||||
|
||||
// Base exists but contains no versioned subdirs -> append nothing (vector unchanged)
|
||||
TEST_F(ApplicationDirectoriesTest, appendVecNoVersionedChildrenLeavesVectorUnchanged)
|
||||
{
|
||||
auto appDirs = makeAppDirsForVersion(5, 4);
|
||||
|
||||
fs::path base = tempDir() / "vec_noversions";
|
||||
std::vector<std::string> sub {"configs"};
|
||||
fs::create_directories(base / "configs"); // but no versioned children
|
||||
|
||||
auto before = sub;
|
||||
appDirs->wrapAppendVersionIfPossible(base, sub);
|
||||
EXPECT_EQ(sub, before);
|
||||
}
|
||||
|
||||
// Base does not exist -> append current version string
|
||||
TEST_F(ApplicationDirectoriesTest, appendVecBaseMissingAppendsCurrentSuffix)
|
||||
{
|
||||
auto appDirs = makeAppDirsForVersion(5, 4);
|
||||
|
||||
fs::path base = tempDir() / "vec_missing";
|
||||
std::vector<std::string> sub {"configs"}; // base/configs doesn't exist
|
||||
|
||||
appDirs->wrapAppendVersionIfPossible(base, sub);
|
||||
|
||||
ASSERT_EQ(sub.size(), 2u);
|
||||
EXPECT_EQ(sub.back(), App::ApplicationDirectories::versionStringForPath(5, 4));
|
||||
}
|
||||
|
||||
// Happy path: exact integers
|
||||
TEST_F(ApplicationDirectoriesTest, extractVersionSucceedsWithPlainIntegers)
|
||||
{
|
||||
auto appDirs = makeAppDirsForVersion(5, 4);
|
||||
std::map<std::string, std::string> m {{"BuildVersionMajor", "7"}, {"BuildVersionMinor", "2"}};
|
||||
auto [maj, min] = appDirs->wrapExtractVersionFromConfigMap(m);
|
||||
EXPECT_EQ(maj, 7);
|
||||
EXPECT_EQ(min, 2);
|
||||
}
|
||||
|
||||
// Whitespace tolerated by std::stoi
|
||||
TEST_F(ApplicationDirectoriesTest, extractVersionSucceedsWithWhitespace)
|
||||
{
|
||||
auto appDirs = makeAppDirsForVersion(5, 4);
|
||||
std::map<std::string, std::string> m {
|
||||
{"BuildVersionMajor", " 10 "},
|
||||
{"BuildVersionMinor", "\t3\n"}
|
||||
};
|
||||
auto [maj, min] = appDirs->wrapExtractVersionFromConfigMap(m);
|
||||
EXPECT_EQ(maj, 10);
|
||||
EXPECT_EQ(min, 3);
|
||||
}
|
||||
|
||||
// Missing major key -> rethrows as Base::RuntimeError
|
||||
TEST_F(ApplicationDirectoriesTest, extractVersionMissingMajorThrowsRuntimeError)
|
||||
{
|
||||
auto appDirs = makeAppDirsForVersion(5, 4);
|
||||
std::map<std::string, std::string> m {{"BuildVersionMinor", "1"}};
|
||||
EXPECT_THROW(appDirs->wrapExtractVersionFromConfigMap(m), Base::RuntimeError);
|
||||
}
|
||||
|
||||
// Missing minor key -> rethrows as Base::RuntimeError
|
||||
TEST_F(ApplicationDirectoriesTest, extractVersionMissingMinorThrowsRuntimeError)
|
||||
{
|
||||
auto appDirs = makeAppDirsForVersion(5, 4);
|
||||
std::map<std::string, std::string> m {{"BuildVersionMajor", "1"}};
|
||||
EXPECT_THROW(appDirs->wrapExtractVersionFromConfigMap(m), Base::RuntimeError);
|
||||
}
|
||||
|
||||
// Non-numeric -> std::stoi throws invalid_argument, rethrown as Base::RuntimeError
|
||||
TEST_F(ApplicationDirectoriesTest, extractVersionNonNumericThrowsRuntimeError)
|
||||
{
|
||||
auto appDirs = makeAppDirsForVersion(5, 4);
|
||||
std::map<std::string, std::string> m {{"BuildVersionMajor", "abc"}, {"BuildVersionMinor", "2"}};
|
||||
EXPECT_THROW(appDirs->wrapExtractVersionFromConfigMap(m), Base::RuntimeError);
|
||||
}
|
||||
|
||||
// Overflow -> std::stoi throws out_of_range, rethrown as Base::RuntimeError
|
||||
TEST_F(ApplicationDirectoriesTest, extractVersionOverflowThrowsRuntimeError)
|
||||
{
|
||||
auto appDirs = makeAppDirsForVersion(5, 4);
|
||||
std::map<std::string, std::string> m {
|
||||
{"BuildVersionMajor", "9999999999999999999999999"},
|
||||
{"BuildVersionMinor", "1"}
|
||||
};
|
||||
EXPECT_THROW(appDirs->wrapExtractVersionFromConfigMap(m), Base::RuntimeError);
|
||||
}
|
||||
|
||||
// Document current behavior: negative numbers are accepted and returned as-is
|
||||
TEST_F(ApplicationDirectoriesTest, extractVersionNegativeNumbersPassThrough)
|
||||
{
|
||||
auto appDirs = makeAppDirsForVersion(5, 4);
|
||||
std::map<std::string, std::string> m {{"BuildVersionMajor", "-2"}, {"BuildVersionMinor", "-7"}};
|
||||
auto [maj, min] = appDirs->wrapExtractVersionFromConfigMap(m);
|
||||
EXPECT_EQ(maj, -2);
|
||||
EXPECT_EQ(min, -7);
|
||||
}
|
||||
|
||||
|
||||
TEST_F(ApplicationDirectoriesTest, sanitizeRemovesNullCharacterAtEnd)
|
||||
{
|
||||
std::string input = std::string("valid_path") + '\0' + "junk_after";
|
||||
std::filesystem::path result = ApplicationDirectoriesTestClass::wrapSanitizePath(input);
|
||||
|
||||
EXPECT_EQ(result.string(), "valid_path");
|
||||
EXPECT_EQ(result.string().find('\0'), std::string::npos);
|
||||
}
|
||||
|
||||
TEST_F(ApplicationDirectoriesTest, sanitizeReturnsUnchangedIfNoNullCharacter)
|
||||
{
|
||||
std::string input = "clean_path/without_nulls";
|
||||
std::filesystem::path result = ApplicationDirectoriesTestClass::wrapSanitizePath(input);
|
||||
|
||||
EXPECT_EQ(result.string(), input);
|
||||
EXPECT_EQ(result.string().find('\0'), std::string::npos);
|
||||
}
|
||||
|
||||
/* NOLINTEND(
|
||||
readability-magic-numbers,
|
||||
cppcoreguidelines-avoid-magic-numbers,
|
||||
readability-function-cognitive-complexity
|
||||
) */
|
||||
567
tests/src/App/BackupPolicy.cpp
Normal file
567
tests/src/App/BackupPolicy.cpp
Normal file
@@ -0,0 +1,567 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
/****************************************************************************
|
||||
* Copyright (c) 2025 The FreeCAD project association AISBL *
|
||||
* *
|
||||
* This file is part of FreeCAD. *
|
||||
* *
|
||||
* FreeCAD is free software: you can redistribute it and/or modify it *
|
||||
* under the terms of the GNU Lesser General Public License as *
|
||||
* published by the Free Software Foundation, either version 2.1 of the *
|
||||
* License, or (at your option) any later version. *
|
||||
* *
|
||||
* FreeCAD is distributed in the hope that it will be useful, but *
|
||||
* WITHOUT ANY WARRANTY; without even the implied warranty of *
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
|
||||
* Lesser General Public License for more details. *
|
||||
* *
|
||||
* You should have received a copy of the GNU Lesser General Public *
|
||||
* License along with FreeCAD. If not, see *
|
||||
* <https://www.gnu.org/licenses/>. *
|
||||
* *
|
||||
***************************************************************************/
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
#include <gmock/gmock.h>
|
||||
|
||||
#include "InitApplication.h"
|
||||
|
||||
#include <App/BackupPolicy.h>
|
||||
|
||||
#include <filesystem>
|
||||
#include <array>
|
||||
#include <fstream>
|
||||
#include <random>
|
||||
#include <regex>
|
||||
#include <string>
|
||||
|
||||
#if defined(__cpp_lib_chrono) && __cpp_lib_chrono >= 201907L && defined(_LIBCPP_VERSION) \
|
||||
&& _LIBCPP_VERSION >= 13000
|
||||
// Apple's clang compiler did not support timezones fully until a quite recent version:
|
||||
// before removing this preprocessor check, verify that it compiles on our oldest-supported
|
||||
// macOS version.
|
||||
# define CAN_USE_CHRONO_AND_FORMAT
|
||||
# include <chrono>
|
||||
# include <format>
|
||||
#endif
|
||||
|
||||
|
||||
class BackupPolicyTest: public ::testing::Test
|
||||
{
|
||||
protected:
|
||||
static void SetUpTestSuite()
|
||||
{
|
||||
tests::initApplication();
|
||||
}
|
||||
|
||||
void SetUp() override
|
||||
{
|
||||
_tempDir = std::filesystem::temp_directory_path() / ("fc_backup_policy-" + randomString(16));
|
||||
std::filesystem::create_directory(_tempDir);
|
||||
}
|
||||
|
||||
void TearDown() override
|
||||
{
|
||||
std::filesystem::remove_all(_tempDir);
|
||||
}
|
||||
|
||||
void apply(const std::string& sourcename, const std::string& targetname)
|
||||
{
|
||||
_policy.apply(sourcename, targetname);
|
||||
}
|
||||
|
||||
void setPolicyTerms(App::BackupPolicy::Policy p, int count, bool useExt, const std::string& fmt)
|
||||
{
|
||||
_policy.setPolicy(p);
|
||||
_policy.setNumberOfFiles(count);
|
||||
_policy.useBackupExtension(useExt);
|
||||
_policy.setDateFormat(fmt);
|
||||
}
|
||||
|
||||
// Create a named temporary file: returns the full path to the new file. Deleted by the TearDown
|
||||
// method at the end of the test.
|
||||
std::filesystem::path createTempFile(const std::string& filename)
|
||||
{
|
||||
std::filesystem::path p = _tempDir / filename;
|
||||
std::ofstream fileStream(p.string());
|
||||
fileStream << "Test data";
|
||||
fileStream.close();
|
||||
return p;
|
||||
}
|
||||
|
||||
|
||||
protected:
|
||||
std::string randomString(size_t length)
|
||||
{
|
||||
static constexpr std::string_view chars = "0123456789"
|
||||
"abcdefghijklmnopqrstuvwxyz"
|
||||
"ABCDEFGHIJKLMNOPQRSTUVWXYZ";
|
||||
|
||||
std::random_device rd;
|
||||
std::mt19937 gen(rd());
|
||||
std::uniform_int_distribution<> dis(0, static_cast<int>(chars.size()) - 1);
|
||||
|
||||
std::string result;
|
||||
result.reserve(length);
|
||||
|
||||
std::ranges::generate_n(std::back_inserter(result), length, [&]() { return chars[dis(gen)]; });
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
std::string filenameFromDateFormatString(const std::string& fmt)
|
||||
{
|
||||
#if CAN_USE_CHRONO_AND_FORMAT
|
||||
std::chrono::zoned_time local_time {
|
||||
std::chrono::current_zone(),
|
||||
std::chrono::system_clock::now()
|
||||
};
|
||||
std::string fmt_str = "{:" + fmt + "}";
|
||||
std::string result = std::vformat(fmt_str, std::make_format_args(local_time));
|
||||
#else
|
||||
std::time_t now = std::time(nullptr);
|
||||
std::tm local_tm {};
|
||||
# if defined(_WIN32)
|
||||
localtime_s(&local_tm, &now); // Windows
|
||||
# else
|
||||
localtime_r(&now, &local_tm); // POSIX
|
||||
# endif
|
||||
constexpr size_t bufferLength = 128;
|
||||
std::array<char, bufferLength> buffer {};
|
||||
size_t bytes = std::strftime(buffer.data(), bufferLength, fmt.c_str(), &local_tm);
|
||||
if (bytes == 0) {
|
||||
throw std::runtime_error("failed to format time");
|
||||
}
|
||||
std::string result {buffer.data()};
|
||||
#endif
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
std::filesystem::path getTempPath()
|
||||
{
|
||||
return _tempDir;
|
||||
}
|
||||
|
||||
private:
|
||||
App::BackupPolicy _policy;
|
||||
std::filesystem::path _tempDir;
|
||||
};
|
||||
|
||||
TEST_F(BackupPolicyTest, StandardSourceDoesNotExist)
|
||||
{
|
||||
// Arrange
|
||||
setPolicyTerms(App::BackupPolicy::Policy::Standard, 1, false, "%Y-%m-%d_%H-%M-%S");
|
||||
|
||||
// Act & Assert
|
||||
EXPECT_THROW(apply("nonexistent.fcstd", "backup.fcstd"), Base::FileException);
|
||||
}
|
||||
|
||||
TEST_F(BackupPolicyTest, StandardWithZeroFilesDeletesExisting)
|
||||
{
|
||||
// Arrange
|
||||
setPolicyTerms(App::BackupPolicy::Policy::Standard, 0, false, "%Y-%m-%d_%H-%M-%S");
|
||||
auto source = createTempFile("source.fcstd");
|
||||
auto target = createTempFile("target.fcstd");
|
||||
|
||||
// Act
|
||||
apply(source.string(), target.string());
|
||||
|
||||
// Assert
|
||||
GTEST_SKIP(); // Can't test on a real filesystem, too much caching for reliable results
|
||||
EXPECT_FALSE(std::filesystem::exists(target));
|
||||
}
|
||||
|
||||
TEST_F(BackupPolicyTest, StandardWithOneFileNoPreviousBackups)
|
||||
{
|
||||
// Arrange
|
||||
setPolicyTerms(App::BackupPolicy::Policy::Standard, 1, false, "%Y-%m-%d_%H-%M-%S");
|
||||
auto source = createTempFile("source.fcstd");
|
||||
auto target = createTempFile("target.fcstd");
|
||||
|
||||
// Act
|
||||
apply(source.string(), target.string());
|
||||
|
||||
// Assert
|
||||
EXPECT_TRUE(std::filesystem::exists(target.string() + "1"));
|
||||
}
|
||||
|
||||
TEST_F(BackupPolicyTest, StandardWithOneFileOnePreviousBackup)
|
||||
{
|
||||
// Arrange
|
||||
setPolicyTerms(App::BackupPolicy::Policy::Standard, 1, false, "%Y-%m-%d_%H-%M-%S");
|
||||
auto source = createTempFile("source.fcstd");
|
||||
auto target = createTempFile("target.fcstd");
|
||||
auto backup = createTempFile("target.fcstd1");
|
||||
|
||||
// Act
|
||||
apply(source.string(), target.string());
|
||||
|
||||
// Assert
|
||||
EXPECT_TRUE(std::filesystem::exists(backup));
|
||||
EXPECT_FALSE(std::filesystem::exists(target.string() + "2"));
|
||||
}
|
||||
|
||||
TEST_F(BackupPolicyTest, StandardWithTwoFilesOnePreviousBackup)
|
||||
{
|
||||
// Arrange
|
||||
setPolicyTerms(App::BackupPolicy::Policy::Standard, 2, false, "%Y-%m-%d_%H-%M-%S");
|
||||
auto source = createTempFile("source.fcstd");
|
||||
auto target = createTempFile("target.fcstd");
|
||||
auto backup = createTempFile("target.fcstd1");
|
||||
|
||||
// Act
|
||||
apply(source.string(), target.string());
|
||||
|
||||
// Assert
|
||||
EXPECT_TRUE(std::filesystem::exists(backup));
|
||||
EXPECT_TRUE(std::filesystem::exists(target.string() + "2"));
|
||||
}
|
||||
|
||||
TEST_F(BackupPolicyTest, StandardWithTwoFilesOnePreviousBackupUnexpectedSuffix)
|
||||
{
|
||||
// Arrange
|
||||
setPolicyTerms(App::BackupPolicy::Policy::Standard, 2, false, "%Y-%m-%d_%H-%M-%S");
|
||||
auto source = createTempFile("source.fcstd");
|
||||
auto target = createTempFile("target.fcstd");
|
||||
auto backup = createTempFile("target.fcstd1");
|
||||
auto weird = createTempFile("target.fcstd2a");
|
||||
|
||||
// Act
|
||||
apply(source.string(), target.string());
|
||||
|
||||
// Assert
|
||||
EXPECT_TRUE(std::filesystem::exists(backup));
|
||||
EXPECT_TRUE(std::filesystem::exists(target.string() + "2"));
|
||||
EXPECT_TRUE(std::filesystem::exists(weird));
|
||||
}
|
||||
|
||||
TEST_F(BackupPolicyTest, StandardWithTwoFilesOnePreviousBackupOutOfSequenceNumber)
|
||||
{
|
||||
// Arrange
|
||||
setPolicyTerms(App::BackupPolicy::Policy::Standard, 2, false, "%Y-%m-%d_%H-%M-%S");
|
||||
auto source = createTempFile("source.fcstd");
|
||||
auto target = createTempFile("target.fcstd");
|
||||
auto backup = createTempFile("target.fcstd1");
|
||||
auto weird = createTempFile("target.fcstd999");
|
||||
|
||||
// Act
|
||||
apply(source.string(), target.string());
|
||||
|
||||
// Assert
|
||||
EXPECT_TRUE(std::filesystem::exists(backup));
|
||||
bool check1 = std::filesystem::exists(target.string() + "2");
|
||||
bool check2 = std::filesystem::exists(weird);
|
||||
EXPECT_NE(check1, check2); // Only one or the other can exist (we don't know which because it
|
||||
// depends on file modification date)
|
||||
}
|
||||
|
||||
TEST_F(BackupPolicyTest, StandardWithFCBakSet)
|
||||
{
|
||||
// Arrange
|
||||
setPolicyTerms(App::BackupPolicy::Policy::Standard, 1, true, "%Y-%m-%d_%H-%M-%S");
|
||||
auto source = createTempFile("source.fcstd");
|
||||
auto target = createTempFile("target.fcstd");
|
||||
|
||||
// Act
|
||||
apply(source.string(), target.string());
|
||||
|
||||
// Assert
|
||||
EXPECT_TRUE(std::filesystem::exists(target.string() + "1")); // No FCBak extension for Standard
|
||||
}
|
||||
|
||||
TEST_F(BackupPolicyTest, TimestampSourceDoesNotExist)
|
||||
{
|
||||
// Arrange
|
||||
setPolicyTerms(App::BackupPolicy::Policy::TimeStamp, 1, false, "%Y-%m-%d_%H-%M-%S");
|
||||
|
||||
// Act & Assert
|
||||
EXPECT_THROW(apply("nonexistent.fcstd", "backup.fcstd"), Base::FileException);
|
||||
}
|
||||
|
||||
TEST_F(BackupPolicyTest, TimestampNoSourceGiven)
|
||||
{
|
||||
// Arrange
|
||||
setPolicyTerms(App::BackupPolicy::Policy::TimeStamp, 1, false, "%Y-%m-%d_%H-%M-%S");
|
||||
auto target = createTempFile("target.fcstd");
|
||||
|
||||
// Act & Assert
|
||||
EXPECT_THROW(apply("nonexistent.fcstd", target.string()), Base::FileException);
|
||||
}
|
||||
|
||||
TEST_F(BackupPolicyTest, TimestampNoTargetGiven)
|
||||
{
|
||||
// Arrange
|
||||
setPolicyTerms(App::BackupPolicy::Policy::TimeStamp, 1, false, "%Y-%m-%d_%H-%M-%S");
|
||||
auto source = createTempFile("source.fcstd");
|
||||
|
||||
// Act & Assert
|
||||
EXPECT_THROW(apply(source.string(), ""), Base::FileException);
|
||||
}
|
||||
|
||||
TEST_F(BackupPolicyTest, TimestampWithZeroFilesDeletesExisting)
|
||||
{
|
||||
// Arrange
|
||||
setPolicyTerms(App::BackupPolicy::Policy::TimeStamp, 0, false, "%Y-%m-%d_%H-%M-%S");
|
||||
auto source = createTempFile("source.fcstd");
|
||||
auto target = createTempFile("target.fcstd");
|
||||
|
||||
// Act
|
||||
apply(source.string(), target.string());
|
||||
|
||||
// Assert
|
||||
GTEST_SKIP(); // Can't test on a real filesystem, too much caching for reliable results
|
||||
EXPECT_FALSE(std::filesystem::exists(target));
|
||||
}
|
||||
|
||||
TEST_F(BackupPolicyTest, TimestampWithOneFileAndNoneExistingNotFCBakCreatesNumberedFile)
|
||||
{
|
||||
// Arrange
|
||||
setPolicyTerms(App::BackupPolicy::Policy::TimeStamp, 1, false, "%Y-%m-%d");
|
||||
auto source = createTempFile("source.fcstd");
|
||||
auto target = createTempFile("target.fcstd");
|
||||
|
||||
// Act
|
||||
apply(source.string(), target.string());
|
||||
|
||||
// Assert
|
||||
// Without the .FCBak extension, the date stuff is completely ignored, even if the policy is set
|
||||
// to "Timestamp"
|
||||
EXPECT_TRUE(std::filesystem::exists(target.string() + "1"));
|
||||
}
|
||||
|
||||
TEST_F(BackupPolicyTest, TimestampSourceHasNoExtension)
|
||||
{
|
||||
// Arrange
|
||||
setPolicyTerms(App::BackupPolicy::Policy::TimeStamp, 1, true, "%Y-%m-%d");
|
||||
auto source = createTempFile("source");
|
||||
auto target = createTempFile("target.fcstd");
|
||||
|
||||
// Act
|
||||
apply(source.string(), target.string());
|
||||
|
||||
// Assert
|
||||
auto expected = "target." + filenameFromDateFormatString("%Y-%m-%d") + ".FCBak";
|
||||
EXPECT_TRUE(std::filesystem::exists(getTempPath() / expected));
|
||||
}
|
||||
|
||||
TEST_F(BackupPolicyTest, TimestampTargetHasNoExtension)
|
||||
{
|
||||
// Arrange
|
||||
setPolicyTerms(App::BackupPolicy::Policy::TimeStamp, 1, true, "%Y-%m-%d");
|
||||
auto source = createTempFile("source.fcstd");
|
||||
auto target = createTempFile("target");
|
||||
|
||||
// Act
|
||||
apply(source.string(), target.string());
|
||||
|
||||
// Assert
|
||||
auto expected = "target." + filenameFromDateFormatString("%Y-%m-%d") + ".FCBak";
|
||||
EXPECT_TRUE(std::filesystem::exists(getTempPath() / expected));
|
||||
}
|
||||
|
||||
TEST_F(BackupPolicyTest, TimestampWithOneFileAndNoneExistingFCBakCreatesDatedFile)
|
||||
{
|
||||
// Arrange
|
||||
setPolicyTerms(App::BackupPolicy::Policy::TimeStamp, 1, true, "%Y-%m-%d");
|
||||
auto source = createTempFile("source.fcstd");
|
||||
auto target = createTempFile("target.fcstd");
|
||||
|
||||
// Act
|
||||
apply(source.string(), target.string());
|
||||
|
||||
// Assert
|
||||
auto expected = "target." + filenameFromDateFormatString("%Y-%m-%d") + ".FCBak";
|
||||
EXPECT_TRUE(std::filesystem::exists(getTempPath() / expected));
|
||||
}
|
||||
|
||||
TEST_F(BackupPolicyTest, TimestampReplacesDotsWithDashes)
|
||||
{
|
||||
// Arrange
|
||||
setPolicyTerms(App::BackupPolicy::Policy::TimeStamp, 1, true, "%Y.%m.%d");
|
||||
auto source = createTempFile("source.fcstd");
|
||||
auto target = createTempFile("target.fcstd");
|
||||
|
||||
// Act
|
||||
apply(source.string(), target.string());
|
||||
|
||||
// Assert
|
||||
auto expected = "target." + filenameFromDateFormatString("%Y-%m-%d") + ".FCBak";
|
||||
EXPECT_TRUE(std::filesystem::exists(getTempPath() / expected));
|
||||
}
|
||||
|
||||
TEST_F(BackupPolicyTest, DISABLED_TimestampWithInvalidFormatStringThrows)
|
||||
{
|
||||
// THIS TEST IS DISABLED BECAUSE THE CURRENT CODE DOES NOT CORRECTLY HANDLE INVALID FORMAT
|
||||
// OPERATIONS, AND GENERATES UNEXPECTED FILENAMES WHEN GIVEN ONE. FIXME.
|
||||
|
||||
// Arrange
|
||||
setPolicyTerms(App::BackupPolicy::Policy::TimeStamp, 1, true, "%Q-%W-%E");
|
||||
auto source = createTempFile("source.fcstd");
|
||||
auto target = createTempFile("target.fcstd");
|
||||
|
||||
// Act and Assert
|
||||
EXPECT_THROW(apply(source.string(), target.string()), Base::FileException);
|
||||
}
|
||||
|
||||
TEST_F(BackupPolicyTest, DISABLED_TimestampWithAbsurdlyLongFormatStringThrows)
|
||||
{
|
||||
// THIS TEST IS DISABLED BECAUSE THE CURRENT CODE DOES NOT CORRECTLY HANDLE OVER-LENGTH FORMAT
|
||||
// OPERATIONS, AND GENERATES AN INVALID FILENAME. FIXME.
|
||||
|
||||
// Arrange
|
||||
setPolicyTerms(
|
||||
App::BackupPolicy::Policy::TimeStamp,
|
||||
1,
|
||||
true,
|
||||
"%A, %B %d, %Y at %H:%M:%S %Z (Day %j of the year, Week %U/%W) — This is a "
|
||||
"verbose date string for demonstration purposes."
|
||||
);
|
||||
auto source = createTempFile("source.fcstd");
|
||||
auto target = createTempFile("target.fcstd");
|
||||
|
||||
// Act and Assert
|
||||
EXPECT_THROW(apply(source.string(), target.string()), Base::FileException);
|
||||
}
|
||||
|
||||
TEST_F(BackupPolicyTest, TimestampDetectsOldBackupFormat)
|
||||
{
|
||||
// Arrange
|
||||
setPolicyTerms(App::BackupPolicy::Policy::TimeStamp, 1, true, "%Y-%m-%d");
|
||||
auto source = createTempFile("source.fcstd");
|
||||
auto target = createTempFile("target.fcstd");
|
||||
auto backup = createTempFile("target.fcstd12345");
|
||||
|
||||
// Act
|
||||
apply(source.string(), target.string());
|
||||
|
||||
// Assert
|
||||
bool check1 = std::filesystem::exists(
|
||||
getTempPath() / ("target." + filenameFromDateFormatString("%Y-%m-%d") + ".FCBak")
|
||||
);
|
||||
bool check2 = std::filesystem::exists(backup);
|
||||
EXPECT_NE(check1, check2);
|
||||
}
|
||||
|
||||
TEST_F(BackupPolicyTest, TimestampDetectsOldBackupFormatIgnoresOther)
|
||||
{
|
||||
// Arrange
|
||||
setPolicyTerms(App::BackupPolicy::Policy::TimeStamp, 1, true, "%Y-%m-%d");
|
||||
auto source = createTempFile("source.fcstd");
|
||||
auto target = createTempFile("target.fcstd");
|
||||
auto backup = createTempFile("target.fcstd12345");
|
||||
auto weird = createTempFile("target.fcstd12345abc");
|
||||
|
||||
// Act
|
||||
apply(source.string(), target.string());
|
||||
|
||||
// Assert
|
||||
bool check1 = std::filesystem::exists(
|
||||
getTempPath() / ("target." + filenameFromDateFormatString("%Y-%m-%d") + ".FCBak")
|
||||
);
|
||||
bool check2 = std::filesystem::exists(backup);
|
||||
EXPECT_NE(check1, check2);
|
||||
EXPECT_TRUE(std::filesystem::exists(weird));
|
||||
}
|
||||
|
||||
TEST_F(BackupPolicyTest, TimestampDetectsAndRetainsOldBackupWhenAllowed)
|
||||
{
|
||||
// Arrange
|
||||
setPolicyTerms(App::BackupPolicy::Policy::TimeStamp, 2, true, "%Y-%m-%d");
|
||||
auto source = createTempFile("source.fcstd");
|
||||
auto target = createTempFile("target.fcstd");
|
||||
auto backup = createTempFile("target.fcstd12345");
|
||||
|
||||
// Act
|
||||
apply(source.string(), target.string());
|
||||
|
||||
// Assert
|
||||
EXPECT_TRUE(
|
||||
std::filesystem::exists(
|
||||
getTempPath() / ("target." + filenameFromDateFormatString("%Y-%m-%d") + ".FCBak")
|
||||
)
|
||||
);
|
||||
EXPECT_TRUE(std::filesystem::exists(backup));
|
||||
}
|
||||
|
||||
TEST_F(BackupPolicyTest, TimestampFormatStringEndsWithSpace)
|
||||
{
|
||||
// Arrange
|
||||
setPolicyTerms(App::BackupPolicy::Policy::TimeStamp, 1, true, "%Y-%m-%d ");
|
||||
auto source = createTempFile("source.fcstd");
|
||||
auto target = createTempFile("target.fcstd");
|
||||
|
||||
// Act
|
||||
apply(source.string(), target.string());
|
||||
|
||||
// Assert (the space is stripped, and an index is added)
|
||||
EXPECT_TRUE(
|
||||
std::filesystem::exists(
|
||||
getTempPath() / ("target." + filenameFromDateFormatString("%Y-%m-%d") + "1.FCBak")
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
TEST_F(BackupPolicyTest, TimestampFormatStringEndsWithDash)
|
||||
{
|
||||
// Arrange
|
||||
setPolicyTerms(App::BackupPolicy::Policy::TimeStamp, 1, true, "%Y-%m-%d-");
|
||||
auto source = createTempFile("source.fcstd");
|
||||
auto target = createTempFile("target.fcstd");
|
||||
|
||||
// Act
|
||||
apply(source.string(), target.string());
|
||||
|
||||
// Assert (the dash is left, and an index is added)
|
||||
EXPECT_TRUE(
|
||||
std::filesystem::exists(
|
||||
getTempPath() / ("target." + filenameFromDateFormatString("%Y-%m-%d") + "-1.FCBak")
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
TEST_F(BackupPolicyTest, TimestampFormatFileAlreadyExists)
|
||||
{
|
||||
// Arrange
|
||||
setPolicyTerms(App::BackupPolicy::Policy::TimeStamp, 2, true, "%Y-%m-%d");
|
||||
auto source = createTempFile("source.fcstd");
|
||||
auto target = createTempFile("target.fcstd");
|
||||
auto backup = createTempFile("target." + filenameFromDateFormatString("%Y-%m-%d") + ".FCBak");
|
||||
|
||||
// Act
|
||||
apply(source.string(), target.string());
|
||||
|
||||
// Assert (An index is appended)
|
||||
EXPECT_TRUE(std::filesystem::exists(backup));
|
||||
EXPECT_TRUE(
|
||||
std::filesystem::exists(
|
||||
getTempPath() / ("target." + filenameFromDateFormatString("%Y-%m-%d") + "-1.FCBak")
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
TEST_F(BackupPolicyTest, TimestampFormatFileAlreadyExistsMultipleTimes)
|
||||
{
|
||||
// Arrange
|
||||
setPolicyTerms(App::BackupPolicy::Policy::TimeStamp, 5, true, "%Y-%m-%d");
|
||||
auto source = createTempFile("source.fcstd");
|
||||
auto target = createTempFile("target.fcstd");
|
||||
auto backup = createTempFile("target." + filenameFromDateFormatString("%Y-%m-%d") + ".FCBak");
|
||||
auto backup1 = createTempFile("target." + filenameFromDateFormatString("%Y-%m-%d") + "-1.FCBak");
|
||||
auto backup2 = createTempFile("target." + filenameFromDateFormatString("%Y-%m-%d") + "-2.FCBak");
|
||||
auto backup3 = createTempFile("target." + filenameFromDateFormatString("%Y-%m-%d") + "-3.FCBak");
|
||||
|
||||
// Act
|
||||
apply(source.string(), target.string());
|
||||
|
||||
// Assert (An index is appended)
|
||||
EXPECT_TRUE(std::filesystem::exists(backup));
|
||||
EXPECT_TRUE(std::filesystem::exists(backup1));
|
||||
EXPECT_TRUE(std::filesystem::exists(backup2));
|
||||
EXPECT_TRUE(std::filesystem::exists(backup3));
|
||||
EXPECT_TRUE(
|
||||
std::filesystem::exists(
|
||||
getTempPath() / ("target." + filenameFromDateFormatString("%Y-%m-%d") + "-4.FCBak")
|
||||
)
|
||||
);
|
||||
}
|
||||
10
tests/src/App/Branding.cpp
Normal file
10
tests/src/App/Branding.cpp
Normal file
@@ -0,0 +1,10 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include "App/Branding.h"
|
||||
|
||||
TEST(Branding, one)
|
||||
{
|
||||
QString ss {};
|
||||
}
|
||||
37
tests/src/App/CMakeLists.txt
Normal file
37
tests/src/App/CMakeLists.txt
Normal file
@@ -0,0 +1,37 @@
|
||||
# SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
add_executable(App_tests_run
|
||||
Application.cpp
|
||||
ApplicationDirectories.cpp
|
||||
BackupPolicy.cpp
|
||||
Branding.cpp
|
||||
ComplexGeoData.cpp
|
||||
Document.cpp
|
||||
DocumentObject.cpp
|
||||
DocumentObserver.cpp
|
||||
Expression.cpp
|
||||
ExpressionParser.cpp
|
||||
ElementMap.cpp
|
||||
ElementNamingUtils.cpp
|
||||
IndexedName.cpp
|
||||
License.cpp
|
||||
MappedElement.cpp
|
||||
MappedName.cpp
|
||||
Metadata.cpp
|
||||
ProjectFile.cpp
|
||||
Property.h
|
||||
Property.cpp
|
||||
PropertyExpressionEngine.cpp
|
||||
StringHasher.cpp
|
||||
VarSet.cpp
|
||||
VRMLObject.cpp
|
||||
)
|
||||
|
||||
target_compile_definitions(App_tests_run PRIVATE DATADIR="${CMAKE_SOURCE_DIR}/data")
|
||||
|
||||
target_link_libraries(App_tests_run PRIVATE
|
||||
GTest::gtest_main
|
||||
GTest::gmock_main
|
||||
${Google_Tests_LIBS}
|
||||
FreeCADApp
|
||||
)
|
||||
494
tests/src/App/ComplexGeoData.cpp
Normal file
494
tests/src/App/ComplexGeoData.cpp
Normal file
@@ -0,0 +1,494 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include <array>
|
||||
#include <boost/core/ignore_unused.hpp>
|
||||
|
||||
#include <App/Application.h>
|
||||
#include <App/ComplexGeoData.h>
|
||||
#include <Base/BoundBox.h>
|
||||
#include <Base/Writer.h>
|
||||
#include <src/App/InitApplication.h>
|
||||
|
||||
|
||||
class ConcreteComplexGeoDataForTesting: public Data::ComplexGeoData
|
||||
{
|
||||
public:
|
||||
std::vector<const char*> getElementTypes() const override
|
||||
{
|
||||
return {"EDGE"};
|
||||
}
|
||||
|
||||
unsigned long countSubElements(const char* Type) const override
|
||||
{
|
||||
(void)Type;
|
||||
return 0;
|
||||
}
|
||||
|
||||
Data::Segment* getSubElement(const char* Type, unsigned long number) const override
|
||||
{
|
||||
(void)number;
|
||||
(void)Type;
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
void setTransform(const Base::Matrix4D& rclTrf) override
|
||||
{
|
||||
(void)rclTrf;
|
||||
}
|
||||
|
||||
Base::Matrix4D getTransform() const override
|
||||
{
|
||||
return {};
|
||||
}
|
||||
|
||||
void transformGeometry(const Base::Matrix4D& rclMat) override
|
||||
{
|
||||
(void)rclMat;
|
||||
}
|
||||
|
||||
Base::BoundBox3d getBoundBox() const override
|
||||
{
|
||||
return Base::BoundBox3d();
|
||||
}
|
||||
};
|
||||
|
||||
class ComplexGeoDataTest: public ::testing::Test
|
||||
{
|
||||
protected:
|
||||
static void SetUpTestSuite()
|
||||
{
|
||||
tests::initApplication();
|
||||
}
|
||||
|
||||
void SetUp() override
|
||||
{
|
||||
_docName = App::GetApplication().getUniqueDocumentName("test");
|
||||
App::GetApplication().newDocument(_docName.c_str(), "testUser");
|
||||
}
|
||||
|
||||
void TearDown() override
|
||||
{
|
||||
App::GetApplication().closeDocument(_docName.c_str());
|
||||
}
|
||||
|
||||
ConcreteComplexGeoDataForTesting& cgd()
|
||||
{
|
||||
return _complexGeoData;
|
||||
}
|
||||
|
||||
std::tuple<Data::IndexedName, Data::MappedName> createMappedName(const std::string& name)
|
||||
{
|
||||
auto elementMap = std::make_shared<Data::ElementMap>();
|
||||
cgd().resetElementMap(elementMap);
|
||||
auto mappedName = Data::MappedName(name.c_str());
|
||||
auto indexedName = Data::IndexedName(_complexGeoData.getElementTypes().front(), 1);
|
||||
elementMap->setElementName(indexedName, mappedName, 0);
|
||||
return std::make_tuple(indexedName, mappedName);
|
||||
}
|
||||
|
||||
private:
|
||||
ConcreteComplexGeoDataForTesting _complexGeoData;
|
||||
std::string _docName;
|
||||
};
|
||||
|
||||
// NOLINTBEGIN(readability-magic-numbers)
|
||||
|
||||
TEST_F(ComplexGeoDataTest, getIndexedNameNoName) // NOLINT
|
||||
{
|
||||
// Arrange & Act
|
||||
auto result = cgd().getIndexedName(Data::MappedName());
|
||||
|
||||
// Assert
|
||||
EXPECT_FALSE(result);
|
||||
}
|
||||
|
||||
TEST_F(ComplexGeoDataTest, getIndexedNameNoElementMap) // NOLINT
|
||||
{
|
||||
// Arrange & Act
|
||||
auto result = cgd().getIndexedName(Data::MappedName("TestName"));
|
||||
|
||||
// Assert
|
||||
EXPECT_TRUE(result);
|
||||
}
|
||||
|
||||
TEST_F(ComplexGeoDataTest, getMappedNameNoElement) // NOLINT
|
||||
{
|
||||
// Arrange & Act
|
||||
auto result = cgd().getMappedName(Data::IndexedName {});
|
||||
|
||||
// Assert
|
||||
EXPECT_FALSE(result);
|
||||
}
|
||||
|
||||
TEST_F(ComplexGeoDataTest, getMappedNameDisallowUnmappedNoMap) // NOLINT
|
||||
{
|
||||
// Arrange & Act
|
||||
auto result = cgd().getMappedName(Data::IndexedName {"TestName"}, false);
|
||||
|
||||
// Assert
|
||||
EXPECT_FALSE(result);
|
||||
}
|
||||
|
||||
TEST_F(ComplexGeoDataTest, getMappedNameDisallowUnmappedWithMap) // NOLINT
|
||||
{
|
||||
// Arrange
|
||||
auto elementMap = std::make_shared<Data::ElementMap>();
|
||||
cgd().resetElementMap(elementMap);
|
||||
auto mappedName = Data::MappedName("TestMappedName");
|
||||
auto indexedName = Data::IndexedName("EDGE", 1);
|
||||
elementMap->setElementName(indexedName, mappedName, 0);
|
||||
|
||||
// Act
|
||||
auto result = cgd().getMappedName(indexedName, false);
|
||||
|
||||
// Assert
|
||||
EXPECT_TRUE(result);
|
||||
EXPECT_EQ(mappedName, result);
|
||||
}
|
||||
|
||||
TEST_F(ComplexGeoDataTest, getMappedNameDisallowUnmappedMissingFromMap) // NOLINT
|
||||
{
|
||||
// Arrange
|
||||
auto mappedName = Data::MappedName("NotTheTestName");
|
||||
cgd().getIndexedName(mappedName); // Put it in the map
|
||||
|
||||
// Act
|
||||
auto result = cgd().getMappedName(Data::IndexedName {"TestName"}, false);
|
||||
|
||||
// Assert
|
||||
EXPECT_FALSE(result);
|
||||
}
|
||||
|
||||
TEST_F(ComplexGeoDataTest, getMappedNameAllowUnmapped) // NOLINT
|
||||
{
|
||||
// Arrange & Act
|
||||
auto result = cgd().getMappedName(Data::IndexedName {"TestName"}, true);
|
||||
|
||||
// Assert
|
||||
EXPECT_TRUE(result);
|
||||
}
|
||||
|
||||
TEST_F(ComplexGeoDataTest, getElementNameGivenIndexedName) // NOLINT
|
||||
{
|
||||
// Arrange
|
||||
const char* name {"EDGE123"};
|
||||
auto indexedName = cgd().getIndexedName(Data::MappedName(name));
|
||||
|
||||
// Act
|
||||
auto result = cgd().getElementName(name);
|
||||
|
||||
// Assert
|
||||
EXPECT_EQ(result.index, indexedName);
|
||||
}
|
||||
|
||||
TEST_F(ComplexGeoDataTest, getElementNameGivenMappedName) // NOLINT
|
||||
{
|
||||
// Arrange
|
||||
const char* name {"EDGE123"};
|
||||
auto mappedName = cgd().getMappedName(Data::IndexedName(name));
|
||||
|
||||
// Act
|
||||
auto result = cgd().getElementName(name);
|
||||
|
||||
// Assert
|
||||
EXPECT_EQ(result.name, mappedName);
|
||||
}
|
||||
|
||||
TEST_F(ComplexGeoDataTest, getElementMappedNamesNoMapNoUnmapped) // NOLINT
|
||||
{
|
||||
// Arrange
|
||||
// Do not create an element map
|
||||
auto indexedName = Data::IndexedName("EDGE1");
|
||||
|
||||
// Act
|
||||
auto result = cgd().getElementMappedNames(indexedName, false);
|
||||
|
||||
// Assert
|
||||
EXPECT_TRUE(result.empty());
|
||||
}
|
||||
|
||||
TEST_F(ComplexGeoDataTest, getElementMappedNamesWithMapNoUnmapped) // NOLINT
|
||||
{
|
||||
// Arrange
|
||||
auto elementMap = std::make_shared<Data::ElementMap>();
|
||||
cgd().resetElementMap(elementMap);
|
||||
auto mappedName = Data::MappedName("TestMappedName");
|
||||
auto indexedName = Data::IndexedName("EDGE", 1);
|
||||
elementMap->setElementName(indexedName, mappedName, 0);
|
||||
|
||||
// Act
|
||||
auto result = cgd().getElementMappedNames(indexedName, false);
|
||||
|
||||
// Assert
|
||||
EXPECT_FALSE(result.empty());
|
||||
EXPECT_EQ(result[0].first, mappedName);
|
||||
}
|
||||
|
||||
TEST_F(ComplexGeoDataTest, getElementMappedNamesNoMapWithUnmapped) // NOLINT
|
||||
{
|
||||
// Do not create an element map
|
||||
auto indexedName = Data::IndexedName("EDGE1");
|
||||
|
||||
// Act
|
||||
auto result = cgd().getElementMappedNames(indexedName, true);
|
||||
|
||||
// Assert
|
||||
EXPECT_FALSE(result.empty());
|
||||
}
|
||||
|
||||
|
||||
TEST_F(ComplexGeoDataTest, getElementMappedNamesWithMapWithUnmapped) // NOLINT
|
||||
{
|
||||
// Arrange
|
||||
Data::MappedName mappedName;
|
||||
Data::IndexedName indexedName;
|
||||
std::tie(indexedName, mappedName) = createMappedName("TestMappedName");
|
||||
auto unmappedName = Data::IndexedName("EDGE", 2);
|
||||
|
||||
// Act
|
||||
auto result = cgd().getElementMappedNames(unmappedName, true);
|
||||
|
||||
// Assert
|
||||
EXPECT_FALSE(result.empty());
|
||||
EXPECT_NE(result[0].first, mappedName);
|
||||
}
|
||||
|
||||
TEST_F(ComplexGeoDataTest, elementTypeValidIndexName) // NOLINT
|
||||
{
|
||||
// Arrange
|
||||
auto indexedName = Data::IndexedName("EDGE", 1);
|
||||
|
||||
// Act
|
||||
char elementType = cgd().elementType(indexedName);
|
||||
|
||||
// Assert
|
||||
EXPECT_EQ(elementType, 'E');
|
||||
}
|
||||
|
||||
TEST_F(ComplexGeoDataTest, elementTypeInvalidIndexedName) // NOLINT
|
||||
{
|
||||
// Arrange
|
||||
auto indexedName = Data::IndexedName("INVALID", 1); // Not in the element type list
|
||||
|
||||
// Act
|
||||
char elementType = cgd().elementType(indexedName);
|
||||
|
||||
// Assert
|
||||
EXPECT_EQ(elementType, 0);
|
||||
}
|
||||
|
||||
TEST_F(ComplexGeoDataTest, elementTypeCharEmptyName) // NOLINT
|
||||
{
|
||||
// Arrange & Act
|
||||
char elementType = cgd().elementType(nullptr);
|
||||
|
||||
// Assert
|
||||
EXPECT_EQ(elementType, 0);
|
||||
}
|
||||
|
||||
TEST_F(ComplexGeoDataTest, elementTypeCharIndexedName) // NOLINT
|
||||
{
|
||||
// Arrange & Act
|
||||
char elementType = cgd().elementType("EDGE1");
|
||||
|
||||
// Assert
|
||||
EXPECT_EQ(elementType, 'E');
|
||||
}
|
||||
|
||||
TEST_F(ComplexGeoDataTest, elementTypeCharMappedNameNoPrefix) // NOLINT
|
||||
{
|
||||
// Arrange
|
||||
int size {0};
|
||||
Data::MappedName mappedName;
|
||||
Data::IndexedName indexedName;
|
||||
std::tie(indexedName, mappedName) = createMappedName("TestMappedName:;");
|
||||
|
||||
// Act
|
||||
char elementType = cgd().elementType(mappedName.toConstString(0, size));
|
||||
|
||||
// Assert
|
||||
EXPECT_EQ(elementType, 'E');
|
||||
}
|
||||
|
||||
TEST_F(ComplexGeoDataTest, elementTypeCharMappedNameWithPrefix) // NOLINT
|
||||
{
|
||||
// Arrange
|
||||
int size {0};
|
||||
Data::MappedName mappedName;
|
||||
Data::IndexedName indexedName;
|
||||
std::string name(Data::ELEMENT_MAP_PREFIX);
|
||||
name.append("TestMappedElement:;");
|
||||
std::tie(indexedName, mappedName) = createMappedName(name);
|
||||
|
||||
// Act
|
||||
char elementType = cgd().elementType(mappedName.toConstString(0, size));
|
||||
|
||||
// Assert
|
||||
EXPECT_EQ(elementType, 'E');
|
||||
}
|
||||
|
||||
TEST_F(ComplexGeoDataTest, resetElementMapNoArgument) // NOLINT
|
||||
{
|
||||
// Arrange & Act
|
||||
cgd().resetElementMap();
|
||||
|
||||
// Assert
|
||||
EXPECT_EQ(cgd().getElementMapSize(), 0);
|
||||
}
|
||||
|
||||
TEST_F(ComplexGeoDataTest, resetElementMapWithArgument) // NOLINT
|
||||
{
|
||||
// Arrange
|
||||
auto elementMap = std::make_shared<Data::ElementMap>();
|
||||
auto mappedName = Data::MappedName("TestMappedName");
|
||||
auto indexedName = Data::IndexedName("EDGE", 1);
|
||||
elementMap->setElementName(indexedName, mappedName, 0);
|
||||
|
||||
// Act
|
||||
cgd().resetElementMap(elementMap);
|
||||
|
||||
// Assert
|
||||
EXPECT_EQ(cgd().getElementMapSize(), 1);
|
||||
}
|
||||
|
||||
TEST_F(ComplexGeoDataTest, setAndGetElementMap) // NOLINT
|
||||
{
|
||||
// Arrange
|
||||
auto elementMap = std::make_shared<Data::ElementMap>();
|
||||
cgd().resetElementMap(elementMap);
|
||||
std::vector<Data::MappedElement> vecMappedElements;
|
||||
auto mappedNameA = Data::MappedName("TestMappedNameA");
|
||||
auto indexedNameA = Data::IndexedName("EDGE", 1);
|
||||
vecMappedElements.emplace_back(indexedNameA, mappedNameA);
|
||||
auto mappedNameB = Data::MappedName("TestMappedNameB");
|
||||
auto indexedNameB = Data::IndexedName("EDGE", 2);
|
||||
vecMappedElements.emplace_back(indexedNameB, mappedNameB);
|
||||
|
||||
// Act
|
||||
auto emptyElementMap = cgd().getElementMap();
|
||||
cgd().setElementMap(vecMappedElements);
|
||||
auto resultingElementMap = cgd().getElementMap();
|
||||
|
||||
// Assert
|
||||
EXPECT_TRUE(emptyElementMap.empty());
|
||||
EXPECT_EQ(resultingElementMap.size(), vecMappedElements.size());
|
||||
}
|
||||
|
||||
TEST_F(ComplexGeoDataTest, getElementMapSize) // NOLINT
|
||||
{
|
||||
// Arrange
|
||||
auto elementMap = std::make_shared<Data::ElementMap>();
|
||||
auto mappedName = Data::MappedName("TestMappedName");
|
||||
auto indexedName = Data::IndexedName("EDGE", 1);
|
||||
elementMap->setElementName(indexedName, mappedName, 0);
|
||||
cgd().resetElementMap(elementMap);
|
||||
|
||||
// Act
|
||||
auto result = cgd().getElementMapSize();
|
||||
|
||||
// Assert
|
||||
EXPECT_EQ(result, 1);
|
||||
}
|
||||
|
||||
TEST_F(ComplexGeoDataTest, flushElementMap) // NOLINT
|
||||
{
|
||||
// Does nothing in the base class
|
||||
}
|
||||
|
||||
TEST_F(ComplexGeoDataTest, saveWithNoElementMap) // NOLINT
|
||||
{
|
||||
// Arrange
|
||||
Base::StringWriter writer;
|
||||
cgd().resetElementMap();
|
||||
|
||||
// Act
|
||||
cgd().Save(writer);
|
||||
|
||||
// Assert - With no element map, that element of the XML is empty
|
||||
EXPECT_TRUE(writer.getString().find("<ElementMap/>") != std::string::npos);
|
||||
}
|
||||
|
||||
TEST_F(ComplexGeoDataTest, saveWithElementMap)
|
||||
{
|
||||
// Arrange
|
||||
Base::StringWriter writer;
|
||||
auto map = createMappedName("SomeElement");
|
||||
|
||||
// Act
|
||||
cgd().Save(writer);
|
||||
|
||||
// Assert
|
||||
EXPECT_TRUE(writer.getString().find("<ElementMap ") != std::string::npos);
|
||||
EXPECT_TRUE(writer.getString().find("<ElementMap2 ") != std::string::npos);
|
||||
EXPECT_TRUE(writer.getString().find(" file=") == std::string::npos); // No persistence name set
|
||||
// TODO: assert that the elementmap was written in "raw" mode
|
||||
}
|
||||
|
||||
TEST_F(ComplexGeoDataTest, saveWithPersistenceFilename)
|
||||
{
|
||||
// Arrange
|
||||
Base::StringWriter writer;
|
||||
auto map = createMappedName("SomeElement");
|
||||
cgd().setPersistenceFileName("some_file_name.txt");
|
||||
|
||||
// Act
|
||||
cgd().Save(writer);
|
||||
|
||||
// Assert
|
||||
EXPECT_TRUE(writer.getString().find(" file=") != std::string::npos);
|
||||
EXPECT_TRUE(writer.getString().find("some_file_name.txt") != std::string::npos);
|
||||
}
|
||||
|
||||
TEST_F(ComplexGeoDataTest, saveDocFileWithNoElementMap)
|
||||
{
|
||||
// Arrange
|
||||
Base::StringWriter writer;
|
||||
cgd().resetElementMap(nullptr); // Force undefined map
|
||||
|
||||
// Act
|
||||
cgd().SaveDocFile(writer);
|
||||
|
||||
// Assert -- no element map tag if no element map
|
||||
EXPECT_TRUE(writer.getString().find("BeginElementMap") == std::string::npos);
|
||||
}
|
||||
|
||||
TEST_F(ComplexGeoDataTest, saveDocFileWithElementMap)
|
||||
{
|
||||
// Arrange
|
||||
Base::StringWriter writer;
|
||||
auto map = createMappedName("SomeElement");
|
||||
|
||||
// Act
|
||||
cgd().SaveDocFile(writer);
|
||||
|
||||
// Assert -- must begin a v1 ElementMap
|
||||
EXPECT_TRUE(writer.getString().find("BeginElementMap v1") != std::string::npos);
|
||||
}
|
||||
|
||||
TEST_F(ComplexGeoDataTest, restoreStream)
|
||||
{}
|
||||
|
||||
TEST_F(ComplexGeoDataTest, traceElement)
|
||||
{ // This test barely scratches the surface; see the ToposhapeExtension traceElement test for more
|
||||
Data::MappedName mappedName;
|
||||
Data::IndexedName indexedName;
|
||||
std::string name(Data::ELEMENT_MAP_PREFIX);
|
||||
name.append("TestMappedElement:;");
|
||||
std::tie(indexedName, mappedName) = createMappedName(name);
|
||||
|
||||
// Arrange
|
||||
Data::TraceCallback cb =
|
||||
[name](const Data::MappedName& elementname, int offset, long encodedTag, long tag) {
|
||||
boost::ignore_unused(offset);
|
||||
boost::ignore_unused(encodedTag);
|
||||
boost::ignore_unused(tag);
|
||||
EXPECT_STREQ(elementname.toString().c_str(), name.substr(1).c_str());
|
||||
return false;
|
||||
};
|
||||
// Act
|
||||
cgd().traceElement(mappedName, cb);
|
||||
}
|
||||
|
||||
// NOLINTEND(readability-magic-numbers)
|
||||
97
tests/src/App/Document.cpp
Normal file
97
tests/src/App/Document.cpp
Normal file
@@ -0,0 +1,97 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
#include <gmock/gmock.h>
|
||||
|
||||
#include "App/Application.h"
|
||||
#include "App/Document.h"
|
||||
#include "App/StringHasher.h"
|
||||
#include "Base/Writer.h"
|
||||
#include <src/App/InitApplication.h>
|
||||
|
||||
using ::testing::Eq;
|
||||
using ::testing::Ne;
|
||||
|
||||
// NOLINTBEGIN(readability-magic-numbers)
|
||||
|
||||
class FakeWriter: public Base::Writer
|
||||
{
|
||||
void writeFiles() override
|
||||
{}
|
||||
std::ostream& Stream() override
|
||||
{
|
||||
return std::cout;
|
||||
}
|
||||
};
|
||||
|
||||
class DocumentTest: public ::testing::Test
|
||||
{
|
||||
protected:
|
||||
static void SetUpTestSuite()
|
||||
{
|
||||
tests::initApplication();
|
||||
}
|
||||
|
||||
void SetUp() override
|
||||
{
|
||||
_docName = App::GetApplication().getUniqueDocumentName("test");
|
||||
_doc = App::GetApplication().newDocument(_docName.c_str(), "testUser");
|
||||
}
|
||||
|
||||
void TearDown() override
|
||||
{
|
||||
App::GetApplication().closeDocument(_docName.c_str());
|
||||
}
|
||||
|
||||
App::Document* doc()
|
||||
{
|
||||
return _doc;
|
||||
}
|
||||
|
||||
private:
|
||||
std::string _docName;
|
||||
App::Document* _doc {};
|
||||
};
|
||||
|
||||
|
||||
TEST_F(DocumentTest, addStringHasherIndicatesUnwrittenWhenNew)
|
||||
{
|
||||
// Arrange
|
||||
App::StringHasherRef hasher(new App::StringHasher);
|
||||
|
||||
// Act
|
||||
auto addResult = doc()->addStringHasher(hasher);
|
||||
|
||||
// Assert
|
||||
EXPECT_TRUE(addResult.first);
|
||||
EXPECT_THAT(addResult.second, Ne(-1));
|
||||
}
|
||||
|
||||
TEST_F(DocumentTest, addStringHasherIndicatesAlreadyWritten)
|
||||
{
|
||||
// Arrange
|
||||
App::StringHasherRef hasher(new App::StringHasher);
|
||||
doc()->addStringHasher(hasher);
|
||||
|
||||
// Act
|
||||
auto addResult = doc()->addStringHasher(hasher);
|
||||
|
||||
// Assert
|
||||
EXPECT_FALSE(addResult.first);
|
||||
}
|
||||
|
||||
TEST_F(DocumentTest, getStringHasherGivesExpectedHasher)
|
||||
{
|
||||
// Arrange
|
||||
App::StringHasherRef hasher(new App::StringHasher);
|
||||
auto pair = doc()->addStringHasher(hasher);
|
||||
int index = pair.second;
|
||||
|
||||
// Act
|
||||
auto foundHasher = doc()->getStringHasher(index);
|
||||
|
||||
// Assert
|
||||
EXPECT_EQ(hasher, foundHasher);
|
||||
}
|
||||
|
||||
// NOLINTEND(readability-magic-numbers)
|
||||
158
tests/src/App/DocumentObject.cpp
Normal file
158
tests/src/App/DocumentObject.cpp
Normal file
@@ -0,0 +1,158 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
#include "gtest/gtest.h"
|
||||
#include <gmock/gmock.h>
|
||||
|
||||
#include <src/App/InitApplication.h>
|
||||
|
||||
#include <App/Application.h>
|
||||
#include <App/Document.h>
|
||||
#include <App/DocumentObject.h>
|
||||
#include <App/GeoFeatureGroupExtension.h>
|
||||
#include <Base/Interpreter.h>
|
||||
|
||||
using namespace App;
|
||||
|
||||
// NOLINTBEGIN(readability-magic-numbers,cppcoreguidelines-avoid-magic-numbers)
|
||||
|
||||
class DocumentObjectTest: public ::testing::Test
|
||||
{
|
||||
protected:
|
||||
static void SetUpTestSuite()
|
||||
{
|
||||
tests::initApplication();
|
||||
}
|
||||
|
||||
void SetUp() override
|
||||
{
|
||||
_docName = App::GetApplication().getUniqueDocumentName("test");
|
||||
_doc = App::GetApplication().newDocument(_docName.c_str(), "testUser");
|
||||
}
|
||||
|
||||
void TearDown() override
|
||||
{
|
||||
App::GetApplication().closeDocument(_docName.c_str());
|
||||
}
|
||||
|
||||
// NOLINTBEGIN(cppcoreguidelines-non-private-member-variables-in-classes)
|
||||
std::string _docName {};
|
||||
App::Document* _doc {};
|
||||
// NOLINTEND(cppcoreguidelines-non-private-member-variables-in-classes)
|
||||
};
|
||||
|
||||
|
||||
TEST_F(DocumentObjectTest, getSubObjectList)
|
||||
{
|
||||
// Arrange
|
||||
|
||||
// The name of a Part::Box added to the document
|
||||
auto boxName {_doc->addObject("Part::Box")->getNameInDocument()};
|
||||
// The name of a Part::Cylinder added to the document
|
||||
auto cylName {_doc->addObject("Part::Cylinder")->getNameInDocument()};
|
||||
// An App::Part object added to the document
|
||||
auto part {_doc->addObject("App::Part")};
|
||||
// The name of the App::Part added to the document
|
||||
auto partName {part->getNameInDocument()};
|
||||
// The name of the object used as argument for the calls of DocumentObject::getSubObjectList()
|
||||
auto subName {std::string()};
|
||||
|
||||
// A vector of int used as argument for the call of DocumentObject::getSubObjectList() with
|
||||
// argument flatten not set (or set to false)
|
||||
auto sizesNoFlatten {std::vector<int>()};
|
||||
// A vector of int used as argument for the call of DocumentObject::getSubObjectList() with
|
||||
// argument flatten set to true
|
||||
auto sizesFlatten {std::vector<int>()};
|
||||
// A helper string used to compose the argument of some calls of
|
||||
// Base::Interpreter().runString()
|
||||
auto cmd {std::string()};
|
||||
|
||||
// Performing a fusion to create an object that will be searched with the calls of
|
||||
// DocumentObject::getSubObjectList()
|
||||
Base::Interpreter().runString("from BOPTools import BOPFeatures");
|
||||
Base::Interpreter().runString("bp = BOPFeatures.BOPFeatures(App.activeDocument())");
|
||||
cmd = "bp.make_multi_fuse([\"";
|
||||
cmd += boxName;
|
||||
cmd += "\", \"";
|
||||
cmd += cylName;
|
||||
cmd += "\", ])";
|
||||
Base::Interpreter().runString(cmd.c_str());
|
||||
Base::Interpreter().runString("App.ActiveDocument.recompute()");
|
||||
// The name of the fusion object
|
||||
auto fuseName {_doc->getObject("Fusion")->getNameInDocument()};
|
||||
|
||||
// Defining the name of the object that will be searched with the calls of
|
||||
// DocumentObject::getSubObjectList()
|
||||
subName = fuseName;
|
||||
subName += ".";
|
||||
subName += boxName;
|
||||
subName += ".Edge1";
|
||||
|
||||
// Adding the fusion to the App::Part object to test the differences between calling
|
||||
// DocumentObject::getSubObjectList() with the flatten argument set to false or set to true
|
||||
cmd = "App.ActiveDocument.getObject(\"";
|
||||
cmd += partName;
|
||||
cmd += "\").addObject(App.ActiveDocument.getObject(\"";
|
||||
cmd += fuseName;
|
||||
cmd += "\"))";
|
||||
Base::Interpreter().runString(cmd.c_str());
|
||||
Base::Interpreter().runString("App.ActiveDocument.recompute()");
|
||||
|
||||
// A vector of DocumentObjects used to store the result of the call to
|
||||
// DocumentObject::getSubObjectList() without the subname parameter
|
||||
auto docSubObjsNoSubName {std::vector<DocumentObject*>()};
|
||||
// A vector of DocumentObjects used to store the result of the call to
|
||||
// DocumentObject::getSubObjectList() with only the subname parameter
|
||||
auto docSubObjsWithSubName {std::vector<DocumentObject*>()};
|
||||
// A vector of DocumentObjects used to store the result of the call to
|
||||
// DocumentObject::getSubObjectList() with the parameters subname and subsizes
|
||||
auto docSubObjsWithSubSizes {std::vector<DocumentObject*>()};
|
||||
// A vector of DocumentObjects used to store the result of the call to
|
||||
// DocumentObject::getSubObjectList() with the flatten parameter set to true
|
||||
auto docSubObjsFlatten {std::vector<DocumentObject*>()};
|
||||
|
||||
// Act
|
||||
docSubObjsNoSubName = part->getSubObjectList(nullptr);
|
||||
docSubObjsWithSubName = part->getSubObjectList(subName.c_str());
|
||||
docSubObjsWithSubSizes = part->getSubObjectList(subName.c_str(), &sizesNoFlatten);
|
||||
docSubObjsFlatten = part->getSubObjectList(subName.c_str(), &sizesFlatten, true);
|
||||
|
||||
// Assert
|
||||
|
||||
// If DocumentObject::getSubObjectList() is called without giving the subname argument it
|
||||
// returns a vector with only one entry, corresponding to the object that called the method
|
||||
EXPECT_EQ(docSubObjsNoSubName.size(), 1);
|
||||
EXPECT_EQ(docSubObjsNoSubName[0]->getID(), _doc->getObject(partName)->getID());
|
||||
|
||||
// If DocumentObject::getSubObjectList() is called with the subname argument it returns a vector
|
||||
// with one entry for each sub object in the subname plus one entry with the object that called
|
||||
// the method
|
||||
EXPECT_EQ(docSubObjsWithSubName.size(), 3);
|
||||
EXPECT_EQ(docSubObjsWithSubName[0]->getID(), _doc->getObject(partName)->getID());
|
||||
EXPECT_EQ(docSubObjsWithSubName[1]->getID(), _doc->getObject(fuseName)->getID());
|
||||
EXPECT_EQ(docSubObjsWithSubName[2]->getID(), _doc->getObject(boxName)->getID());
|
||||
|
||||
// If DocumentObject::getSubObjectList() is called with the subsizes argument it returns the
|
||||
// same vector of the previous case and the subsizes argument stores the positions in the
|
||||
// subname string corresponding to start of the sub objects names.
|
||||
// The position takes into account also the '.' in the subname
|
||||
EXPECT_EQ(docSubObjsWithSubSizes.size(), 3);
|
||||
EXPECT_EQ(docSubObjsWithSubSizes[0]->getID(), _doc->getObject(partName)->getID());
|
||||
EXPECT_EQ(docSubObjsWithSubSizes[1]->getID(), _doc->getObject(fuseName)->getID());
|
||||
EXPECT_EQ(docSubObjsWithSubSizes[2]->getID(), _doc->getObject(boxName)->getID());
|
||||
EXPECT_EQ(sizesNoFlatten.size(), 3);
|
||||
EXPECT_EQ(sizesNoFlatten[0], 0);
|
||||
EXPECT_EQ(sizesNoFlatten[1], strlen(fuseName) + 1);
|
||||
EXPECT_EQ(sizesNoFlatten[2], strlen(fuseName) + strlen(boxName) + 2);
|
||||
|
||||
// If DocumentObject::getSubObjectList() is called with the flattened argument set to true, it
|
||||
// returns a vector with all the sub objects in the subname that don't belong to the same
|
||||
// App::GeoFeatureGroupExtension object, plus one entry with the object that called the method
|
||||
EXPECT_EQ(docSubObjsFlatten.size(), 2);
|
||||
EXPECT_EQ(docSubObjsFlatten[0]->getID(), _doc->getObject(partName)->getID());
|
||||
EXPECT_EQ(docSubObjsFlatten[1]->getID(), _doc->getObject(boxName)->getID());
|
||||
EXPECT_EQ(sizesFlatten.size(), 2);
|
||||
EXPECT_EQ(sizesFlatten[0], 0);
|
||||
EXPECT_EQ(sizesFlatten[1], strlen(fuseName) + strlen(boxName) + 2);
|
||||
}
|
||||
|
||||
// NOLINTEND(readability-magic-numbers, cppcoreguidelines-avoid-magic-numbers)
|
||||
551
tests/src/App/DocumentObserver.cpp
Normal file
551
tests/src/App/DocumentObserver.cpp
Normal file
@@ -0,0 +1,551 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
#include "gtest/gtest.h"
|
||||
#include <gmock/gmock.h>
|
||||
|
||||
#include <src/App/InitApplication.h>
|
||||
|
||||
#include <App/Application.h>
|
||||
#include <App/Document.h>
|
||||
#include <App/DocumentObject.h>
|
||||
#include <App/DocumentObserver.h>
|
||||
#include <App/ElementNamingUtils.h>
|
||||
#include <Base/Interpreter.h>
|
||||
|
||||
using namespace App;
|
||||
using namespace Data;
|
||||
|
||||
class DISABLED_DocumentObserverTest: public ::testing::Test
|
||||
{
|
||||
protected:
|
||||
static void SetUpTestSuite()
|
||||
{
|
||||
tests::initApplication();
|
||||
}
|
||||
|
||||
void SetUp() override
|
||||
{
|
||||
_docName = App::GetApplication().getUniqueDocumentName("test");
|
||||
_doc = App::GetApplication().newDocument(_docName.c_str(), "testUser");
|
||||
}
|
||||
|
||||
void TearDown() override
|
||||
{
|
||||
App::GetApplication().closeDocument(_docName.c_str());
|
||||
}
|
||||
|
||||
// NOLINTBEGIN(cppcoreguidelines-non-private-member-variables-in-classes)
|
||||
std::string _docName {};
|
||||
App::Document* _doc {};
|
||||
// NOLINTEND(cppcoreguidelines-non-private-member-variables-in-classes)
|
||||
};
|
||||
|
||||
TEST_F(DISABLED_DocumentObserverTest, hasSubObject)
|
||||
{
|
||||
// Arrange
|
||||
|
||||
// An App::SubObjectT() object with a subname that doesn't contain a sub object name
|
||||
auto subObjTWithoutSubObj {SubObjectT()};
|
||||
// An App::SubObjectT() object with a subname that contains a sub object name
|
||||
auto subObjTWithSubObj {SubObjectT()};
|
||||
|
||||
// A subname that doesn't contain a sub object name
|
||||
auto subObjTNameWithoutSubObj {"Line"};
|
||||
// A subname that contains a sub object name
|
||||
auto subObjTNameWithSubObj {std::string()};
|
||||
subObjTNameWithSubObj += subObjTNameWithoutSubObj;
|
||||
subObjTNameWithSubObj += ".Edge1";
|
||||
|
||||
// A variable used to store the result of the call to the method SubObjectT::hasSubObject() by
|
||||
// the object subObjTWithoutSubObj
|
||||
auto hasNoSubObj {false};
|
||||
// A variable used to store the result of the call to the method SubObjectT::hasSubObject() by
|
||||
// the object subObjTWithSubObj
|
||||
auto hasSubObj {false};
|
||||
|
||||
// Setting the subnames of the App::SubObjectT() objects defined previously
|
||||
subObjTWithoutSubObj.setSubName(subObjTNameWithoutSubObj);
|
||||
subObjTWithSubObj.setSubName(subObjTNameWithSubObj.c_str());
|
||||
|
||||
// Act
|
||||
|
||||
hasNoSubObj = subObjTWithoutSubObj.hasSubObject();
|
||||
hasSubObj = subObjTWithSubObj.hasSubObject();
|
||||
|
||||
// Assert
|
||||
|
||||
// The subname of subObjTWithoutSubObj doesn't contain the name of a sub object, therefore
|
||||
// hasNoSubObj should be false
|
||||
EXPECT_FALSE(hasNoSubObj);
|
||||
|
||||
// The subname of subObjTWithSubObj doesn't contain the name of a sub object, therefore
|
||||
// hasSubObj should be true
|
||||
EXPECT_TRUE(hasSubObj);
|
||||
}
|
||||
|
||||
TEST_F(DISABLED_DocumentObserverTest, hasSubElement)
|
||||
{
|
||||
// Arrange
|
||||
|
||||
// An App::SubObjectT() object with a subname that doesn't contain a sub element name
|
||||
auto subObjTWithoutSubEl {SubObjectT()};
|
||||
// An App::SubObjectT() object with a subname that contains a sub element name
|
||||
auto subObjTWithSubEl {SubObjectT()};
|
||||
|
||||
// A subname that doesn't contain a sub element name
|
||||
auto subObjTNameWithoutSubEl {"Sketch."};
|
||||
// A subname that contains a sub element name
|
||||
auto subObjTNameWithSubEl {std::string()};
|
||||
subObjTNameWithSubEl += subObjTNameWithoutSubEl;
|
||||
subObjTNameWithSubEl += ELEMENT_MAP_PREFIX;
|
||||
subObjTNameWithSubEl += "e1.ExternalEdge1";
|
||||
|
||||
// A variable used to store the result of the call to the method SubObjectT::hasSubElement() by
|
||||
// the object subObjTWithoutSubEl
|
||||
auto hasNoSubEl {false};
|
||||
// A variable used to store the result of the call to the method SubObjectT::hasSubElement() by
|
||||
// the object subObjTWithSubEl
|
||||
auto hasSubEl {false};
|
||||
|
||||
// Setting the subnames of the App::SubObjectT() objects defined previously
|
||||
subObjTWithoutSubEl.setSubName(subObjTNameWithoutSubEl);
|
||||
subObjTWithSubEl.setSubName(subObjTNameWithSubEl.c_str());
|
||||
|
||||
// Act
|
||||
|
||||
hasNoSubEl = subObjTWithoutSubEl.hasSubElement();
|
||||
hasSubEl = subObjTWithSubEl.hasSubElement();
|
||||
|
||||
// Assert
|
||||
|
||||
// The subname of subObjTWithoutSubEl doesn't contain the name of a sub element, therefore
|
||||
// hasNoSubEl should be false
|
||||
EXPECT_FALSE(hasNoSubEl);
|
||||
|
||||
// The subname of subObjTWithSubEl doesn't contain the name of a sub element, therefore hasSubEl
|
||||
// should be true
|
||||
EXPECT_TRUE(hasSubEl);
|
||||
}
|
||||
|
||||
TEST_F(DISABLED_DocumentObserverTest, normalize)
|
||||
{
|
||||
// Arrange
|
||||
|
||||
// A Part::Box added to the document
|
||||
auto box {_doc->addObject("Part::Box")};
|
||||
// The name of the Part::Box added to the document
|
||||
auto boxName {box->getNameInDocument()};
|
||||
// Changing the label of the Part::Box to test the differences between calling
|
||||
// SubObjectT::normalized() with the options argument set to
|
||||
// SubObjectT::NormalizeOption::KeepSubName or set to other values
|
||||
box->Label.setValue("Cube");
|
||||
// The label of the Part::Box added to the document
|
||||
auto boxLabel {box->Label.getValue()};
|
||||
// The name of a Part::Cylinder added to the document
|
||||
auto cylName {_doc->addObject("Part::Cylinder")->getNameInDocument()};
|
||||
// An App::Part added to the document
|
||||
auto part {_doc->addObject("App::Part")};
|
||||
// The name of the App::Part added to the document
|
||||
auto partName {part->getNameInDocument()};
|
||||
// An App::LinkGroup added to the document
|
||||
auto lGrp {_doc->addObject("App::LinkGroup")};
|
||||
// The name of the App::LinkGroup added to the document
|
||||
auto lGrpName {lGrp->getNameInDocument()};
|
||||
// The name of the object used as argument for various calls of the constructors of
|
||||
// App::SubObjectT objects
|
||||
auto subName {std::string()};
|
||||
// A helper string used to compose the argument of some calls of
|
||||
// Base::Interpreter().runString()
|
||||
auto cmd {std::string()};
|
||||
|
||||
// Performing a fusion to create an object that will be added to the App::Part object and
|
||||
// linked inside the App::LinkGroup object
|
||||
Base::Interpreter().runString("from BOPTools import BOPFeatures");
|
||||
Base::Interpreter().runString("bp = BOPFeatures.BOPFeatures(App.activeDocument())");
|
||||
cmd = "bp.make_multi_fuse([\"";
|
||||
cmd += boxName;
|
||||
cmd += "\", \"";
|
||||
cmd += cylName;
|
||||
cmd += "\", ])";
|
||||
Base::Interpreter().runString(cmd.c_str());
|
||||
Base::Interpreter().runString("App.ActiveDocument.recompute()");
|
||||
// The name of the fusion object
|
||||
auto fuseName {_doc->getObject("Fusion")->getNameInDocument()};
|
||||
|
||||
// Adding the fusion to the App::Part object to test the differences between calling
|
||||
// SubObjectT::normalize() with the options argument set to
|
||||
// SubObjectT::NormalizeOption::NoFlatten or set to other values
|
||||
cmd = "App.ActiveDocument.getObject(\"";
|
||||
cmd += partName;
|
||||
cmd += "\").addObject(App.ActiveDocument.getObject(\"";
|
||||
cmd += fuseName;
|
||||
cmd += "\"))";
|
||||
Base::Interpreter().runString(cmd.c_str());
|
||||
Base::Interpreter().runString("App.ActiveDocument.recompute()");
|
||||
|
||||
// Adding the fusion to the App::LinkGroup object to test SubObjectT::normalize() with the
|
||||
// options argument set to SubObjectT::NormalizeOption::ConvertIndex
|
||||
cmd = "App.ActiveDocument.getObject(\"";
|
||||
cmd += lGrpName;
|
||||
cmd += "\").setLink(App.ActiveDocument.getObject(\"";
|
||||
cmd += partName;
|
||||
cmd += "\"))";
|
||||
Base::Interpreter().runString(cmd.c_str());
|
||||
Base::Interpreter().runString("App.ActiveDocument.recompute()");
|
||||
|
||||
// Defining the name of the object that will be used as argument for various calls of the
|
||||
// constructors of App::SubObjectT objects
|
||||
subName = partName;
|
||||
subName += ".";
|
||||
subName += fuseName;
|
||||
subName += ".";
|
||||
subName += boxName;
|
||||
subName += ".Edge1";
|
||||
|
||||
// An empty App::SubObjectT object
|
||||
auto subObjTEmpty {SubObjectT()};
|
||||
// An App::SubObjectT object without sub objects
|
||||
auto subObjTWithoutSubObj {SubObjectT(box, boxName)};
|
||||
// An App::SubObjectT object with sub objects
|
||||
auto subObjTWithSubObj {SubObjectT(lGrp, subName.c_str())};
|
||||
// An App::SubObjectT object used to test SubObjectT::normalize() with the option argument set
|
||||
// to SubObjectT::NormalizeOption::NoElement
|
||||
auto subObjTWithoutEl {SubObjectT(lGrp, subName.c_str())};
|
||||
// An App::SubObjectT object used to test SubObjectT::normalize() with the option argument set
|
||||
// to SubObjectT::NormalizeOption::NoFlatten
|
||||
auto subObjTNoFlatten {SubObjectT(lGrp, subName.c_str())};
|
||||
// An App::SubObjectT object used to test SubObjectT::normalize() with the option argument set
|
||||
// to SubObjectT::NormalizeOption::KeepSubName
|
||||
// The subName is modified replacing "Part__Box" with "$Cube" to test the effect of using
|
||||
// SubObjectT::NormalizeOption::KeepSubName, that is leaving the "$Cube" instead of replacing it
|
||||
// with the name of the DocumentObject with that label ("Part__Box")
|
||||
auto subObjTKeepSubName {SubObjectT(
|
||||
lGrp,
|
||||
subName
|
||||
.replace(
|
||||
strlen(partName) + strlen(fuseName) + 2,
|
||||
strlen(boxName),
|
||||
std::string("$").append(boxLabel).c_str()
|
||||
)
|
||||
.c_str()
|
||||
)};
|
||||
// An App::SubObjectT object used to test SubObjectT::normalize() with the option argument set
|
||||
// to SubObjectT::NormalizeOption::ConvertIndex
|
||||
// The subName is modified replacing "App_Part" with "0" to test the effect of using
|
||||
// SubObjectT::NormalizeOption::ConvertIndex, that is replacing the "0" with the name of the
|
||||
// DocumentObject at position 0 of lGrp
|
||||
auto subObjTConvertIndex {SubObjectT(lGrp, subName.replace(0, strlen(partName), "0").c_str())};
|
||||
|
||||
// A bool variable used to store the result of subObjTEmpty.normalize()
|
||||
auto normalizeEmpty {false};
|
||||
// A bool variable used to store the result of subObjTWithoutSubObj.normalize()
|
||||
auto normalizeWithoutSubObj {false};
|
||||
// A bool variable used to store the result of subObjTWithSubObj.normalize()
|
||||
auto normalizeWithSubObj {false};
|
||||
// A bool variable used to store the result of subObjTWithoutEl.normalize()
|
||||
auto normalizeWithoutEl {false};
|
||||
// A bool variable used to store the result of subObjTNoFlatten.normalize()
|
||||
auto normalizeNoFlatten {false};
|
||||
// A bool variable used to store the result of subObjTKeepSubName.normalize()
|
||||
auto normalizeKeepSubName {false};
|
||||
// A bool variable used to store the result of subObjTConvertIndex.normalize()
|
||||
auto normalizeConvertIndex {false};
|
||||
|
||||
// Act
|
||||
|
||||
normalizeEmpty = subObjTEmpty.normalize();
|
||||
normalizeWithoutSubObj = subObjTWithoutSubObj.normalize();
|
||||
normalizeWithSubObj = subObjTWithSubObj.normalize();
|
||||
normalizeWithoutEl = subObjTWithoutEl.normalize(SubObjectT::NormalizeOption::NoElement);
|
||||
normalizeNoFlatten = subObjTNoFlatten.normalize(SubObjectT::NormalizeOption::NoFlatten);
|
||||
normalizeKeepSubName = subObjTKeepSubName.normalize(SubObjectT::NormalizeOption::KeepSubName);
|
||||
normalizeConvertIndex = subObjTConvertIndex.normalize(SubObjectT::NormalizeOption::ConvertIndex);
|
||||
|
||||
// Assert
|
||||
|
||||
// In this case calling SubObjectT::normalize() doesn't have effect as subObjTEmpty has been
|
||||
// initialized with an empty constructor
|
||||
EXPECT_FALSE(normalizeEmpty);
|
||||
|
||||
// In this case calling SubObjectT::normalize() doesn't have effect as subObjTWithoutSubObj
|
||||
// hasn't any sub objects
|
||||
EXPECT_FALSE(normalizeWithoutSubObj);
|
||||
|
||||
// In this case calling SubObjectT::normalize() changes subObjTWithSubObj subname in this way:
|
||||
// The "Fusion." part of the of the original subname is removed because the
|
||||
// SubObjectT::NormalizeOption::NoFlatten flag isn't set;
|
||||
// The "Edge1" part of the of the original subname is kept because the
|
||||
// SubObjectT::NormalizeOption::NoElement flag isn't set;
|
||||
EXPECT_TRUE(normalizeWithSubObj);
|
||||
|
||||
// In this case calling SubObjectT::normalize() changes subObjTWithoutEl subname in this way:
|
||||
// The "Fusion." part of the of the original subname is removed because the
|
||||
// SubObjectT::NormalizeOption::NoFlatten flag isn't set;
|
||||
// The "Edge1" part of the of the original subname is removed because the
|
||||
// SubObjectT::NormalizeOption::NoElement flag is set;
|
||||
EXPECT_TRUE(normalizeWithoutEl);
|
||||
|
||||
// In this case calling SubObjectT::normalize() doesn't have effect as neither the
|
||||
// DocumentObject referenced nor the subname of subObjTNoFlatten are changed
|
||||
EXPECT_FALSE(normalizeNoFlatten);
|
||||
|
||||
// In this case calling SubObjectT::normalize() changes subObjTKeepSubName subname in this way:
|
||||
// The "Fusion." part of the of the original subname is removed because the
|
||||
// SubObjectT::NormalizeOption::NoFlatten flag isn't set;
|
||||
// The "$Cube." part of the of the original subname is kept because the
|
||||
// SubObjectT::NormalizeOption::KeepSubName flag is set;
|
||||
// The "Edge1" part of the of the original subname is kept because the
|
||||
// SubObjectT::NormalizeOption::NoElement flag isn't set;
|
||||
EXPECT_TRUE(normalizeKeepSubName);
|
||||
|
||||
// In this case calling SubObjectT::normalize() changes subObjTConvertIndex subname in this way:
|
||||
// The "0." part of the of the original subname is replaced with "App__Part" because the
|
||||
// SubObjectT::NormalizeOption::ConvertIndex flag is set;
|
||||
// The "Fusion." part of the of the original subname is removed because the
|
||||
// SubObjectT::NormalizeOption::NoFlatten flag isn't set;
|
||||
// The "$Cube." part of the of the original subname is replaced with "Part__Box." because the
|
||||
// SubObjectT::NormalizeOption::KeepSubName flag isn't set;
|
||||
// The "Edge1" part of the of the original subname is kept because the
|
||||
// SubObjectT::NormalizeOption::NoElement flag isn't set;
|
||||
EXPECT_TRUE(normalizeConvertIndex);
|
||||
}
|
||||
|
||||
TEST_F(DISABLED_DocumentObserverTest, normalized)
|
||||
{
|
||||
// Arrange
|
||||
|
||||
// A Part::Box added to the document
|
||||
auto box {_doc->addObject("Part::Box")};
|
||||
// The name of the Part::Box added to the document
|
||||
auto boxName {box->getNameInDocument()};
|
||||
// Changing the label of the Part::Box to test the differences between calling
|
||||
// SubObjectT::normalized() with the options argument set to
|
||||
// SubObjectT::NormalizeOption::KeepSubName or set to other values
|
||||
box->Label.setValue("Cube");
|
||||
// The label of the Part::Box added to the document
|
||||
auto boxLabel {box->Label.getValue()};
|
||||
// The name of a Part::Cylinder added to the document
|
||||
auto cylName {_doc->addObject("Part::Cylinder")->getNameInDocument()};
|
||||
// An App::Part added to the document
|
||||
auto part {_doc->addObject("App::Part")};
|
||||
// The name of the App::Part added to the document
|
||||
auto partName {part->getNameInDocument()};
|
||||
// An App::LinkGroup added to the document
|
||||
auto lGrp {_doc->addObject("App::LinkGroup")};
|
||||
// The name of the App::LinkGroup added to the document
|
||||
auto lGrpName {lGrp->getNameInDocument()};
|
||||
|
||||
// The name of the object used as argument for various calls of the constructors of
|
||||
// App::SubObjectT objects
|
||||
auto subName {std::string()};
|
||||
// A helper string used to compose the argument of some calls of
|
||||
// Base::Interpreter().runString()
|
||||
auto cmd {std::string()};
|
||||
|
||||
// Performing a fusion to create an object that will be added to the App::Part object and
|
||||
// linked inside the App::LinkGroup object
|
||||
Base::Interpreter().runString("from BOPTools import BOPFeatures");
|
||||
Base::Interpreter().runString("bp = BOPFeatures.BOPFeatures(App.activeDocument())");
|
||||
cmd = "bp.make_multi_fuse([\"";
|
||||
cmd += boxName;
|
||||
cmd += "\", \"";
|
||||
cmd += cylName;
|
||||
cmd += "\", ])";
|
||||
Base::Interpreter().runString(cmd.c_str());
|
||||
Base::Interpreter().runString("App.ActiveDocument.recompute()");
|
||||
// The name of the fusion object
|
||||
auto fuseName {_doc->getObject("Fusion")->getNameInDocument()};
|
||||
|
||||
// Adding the fusion to the App::Part object to test the differences between calling
|
||||
// SubObjectT::normalized() with the options argument set to
|
||||
// SubObjectT::NormalizeOption::NoFlatten or set to other values
|
||||
cmd = "App.ActiveDocument.getObject(\"";
|
||||
cmd += partName;
|
||||
cmd += "\").addObject(App.ActiveDocument.getObject(\"";
|
||||
cmd += fuseName;
|
||||
cmd += "\"))";
|
||||
Base::Interpreter().runString(cmd.c_str());
|
||||
Base::Interpreter().runString("App.ActiveDocument.recompute()");
|
||||
|
||||
// Creating a Link Array with the App::Part object added to the document to test
|
||||
// SubObjectT::normalized() with the options argument set to
|
||||
// SubObjectT::NormalizeOption::ConvertIndex or set to other values
|
||||
Base::Interpreter().runString("import Draft");
|
||||
cmd = "_obj = Draft.make_ortho_array(App.ActiveDocument.";
|
||||
cmd += partName;
|
||||
cmd += ", v_x=FreeCAD.Vector(100.0, 0.0, 0.0), v_y=FreeCAD.Vector(0.0, 100.0, 0.0), "
|
||||
"v_z=FreeCAD.Vector(0.0, 0.0, 100.0), n_x=2, n_y=2, n_z=1, use_link=True)";
|
||||
Base::Interpreter().runString(cmd.c_str());
|
||||
cmd = "_obj.Fuse = False";
|
||||
Base::Interpreter().runString(cmd.c_str());
|
||||
cmd = "Draft.autogroup(_obj)";
|
||||
Base::Interpreter().runString(cmd.c_str());
|
||||
Base::Interpreter().runString("App.ActiveDocument.recompute()");
|
||||
auto lArr {_doc->getObject("Array")};
|
||||
auto lArrName {lArr->getNameInDocument()};
|
||||
|
||||
// Adding the Link Array to the App::LinkGroup object to test SubObjectT::normalized() with the
|
||||
// options argument set to SubObjectT::NormalizeOption::ConvertIndex or set to other values
|
||||
cmd = "App.ActiveDocument.getObject(\"";
|
||||
cmd += lGrpName;
|
||||
cmd += "\").setLink(App.ActiveDocument.getObject(\"";
|
||||
cmd += lArrName;
|
||||
cmd += "\"))";
|
||||
Base::Interpreter().runString(cmd.c_str());
|
||||
Base::Interpreter().runString("App.ActiveDocument.recompute()");
|
||||
|
||||
// Defining the name of the object that will be used as argument for various calls of the
|
||||
// constructors of App::SubObjectT objects
|
||||
subName = "0.";
|
||||
subName += "3.";
|
||||
subName += fuseName;
|
||||
subName += ".";
|
||||
subName += "$";
|
||||
subName += boxLabel;
|
||||
subName += ".";
|
||||
subName += "Edge1";
|
||||
|
||||
// An empty App::SubObjectT object
|
||||
auto subObjTEmpty {SubObjectT()};
|
||||
// An App::SubObjectT object without sub objects
|
||||
auto subObjTWithoutSubObj {SubObjectT(box, boxName)};
|
||||
// An App::SubObjectT object with sub objects
|
||||
auto subObjTWithSubObj {SubObjectT(lGrp, subName.c_str())};
|
||||
// An App::SubObjectT object used to test SubObjectT::normalized() with the option argument set
|
||||
// to SubObjectT::NormalizeOption::NoElement
|
||||
auto subObjTWithoutEl {SubObjectT(lGrp, subName.c_str())};
|
||||
// An App::SubObjectT object used to test SubObjectT::normalized() with the option argument set
|
||||
// to SubObjectT::NormalizeOption::NoFlatten
|
||||
auto subObjTNoFlatten {SubObjectT(lGrp, subName.c_str())};
|
||||
// An App::SubObjectT object used to test SubObjectT::normalized() with the option argument set
|
||||
// to SubObjectT::NormalizeOption::KeepSubName
|
||||
auto subObjTKeepSubName {SubObjectT(lGrp, subName.c_str())};
|
||||
// An App::SubObjectT object used to test SubObjectT::normalized() with the option argument set
|
||||
// to SubObjectT::NormalizeOption::ConvertIndex
|
||||
auto subObjTConvertIndex {SubObjectT(lGrp, subName.c_str())};
|
||||
|
||||
// An App::SubObjectT object used to store the result of subObjTEmpty.normalized()
|
||||
auto subObjTEmptyNormalized {SubObjectT()};
|
||||
// An App::SubObjectT object used to store the result of subObjTWithoutSubObj.normalized()
|
||||
auto subObjTWithoutSubObjNormalized {SubObjectT()};
|
||||
// An App::SubObjectT object used to store the result of subObjTWithSubObj.normalized()
|
||||
auto subObjTWithSubObjNormalized {SubObjectT()};
|
||||
// An App::SubObjectT object used to store the result of subObjTWithoutEl.normalized()
|
||||
auto subObjTWithoutElNormalized {SubObjectT()};
|
||||
// An App::SubObjectT object used to store the result of subObjTNoFlatten.normalized()
|
||||
auto subObjTNoFlattenNormalized {SubObjectT()};
|
||||
// An App::SubObjectT object used to store the result of subObjTKeepSubName.normalized()
|
||||
auto subObjTKeepSubNameNormalized {SubObjectT()};
|
||||
// An App::SubObjectT object used to store the result of subObjTConvertIndex.normalized()
|
||||
auto subObjTConvertIndexNormalized {SubObjectT()};
|
||||
|
||||
// Act
|
||||
|
||||
subObjTEmptyNormalized = subObjTEmpty.normalized();
|
||||
subObjTWithoutSubObjNormalized = subObjTWithoutSubObj.normalized();
|
||||
subObjTWithSubObjNormalized = subObjTWithSubObj.normalized();
|
||||
subObjTWithoutElNormalized = subObjTWithoutEl.normalized(SubObjectT::NormalizeOption::NoElement);
|
||||
subObjTNoFlattenNormalized = subObjTNoFlatten.normalized(SubObjectT::NormalizeOption::NoFlatten);
|
||||
subObjTKeepSubNameNormalized = subObjTKeepSubName.normalized(
|
||||
SubObjectT::NormalizeOption::KeepSubName
|
||||
);
|
||||
subObjTConvertIndexNormalized = subObjTConvertIndex.normalized(
|
||||
SubObjectT::NormalizeOption::ConvertIndex
|
||||
);
|
||||
|
||||
// Assert
|
||||
|
||||
// In this case calling SubObjectT::normalized() doesn't have effect as subObjTEmpty has been
|
||||
// initialized with an empty constructor
|
||||
EXPECT_EQ(subObjTEmpty.getSubName(), subObjTEmptyNormalized.getSubName());
|
||||
|
||||
// In this case calling SubObjectT::normalized() doesn't have effect as subObjTWithoutSubObj
|
||||
// hasn't any sub objects
|
||||
EXPECT_EQ(subObjTWithoutSubObj.getSubName(), subObjTWithoutSubObjNormalized.getSubName());
|
||||
|
||||
// In this case calling SubObjectT::normalized() changes subObjTWithSubObj subname in this way:
|
||||
// The "0." part of the of the original subname is kept because the
|
||||
// SubObjectT::NormalizeOption::ConvertIndex flag isn't set;
|
||||
// The "3." part of the of the original subname is kept because the
|
||||
// SubObjectT::NormalizeOption::ConvertIndex flag isn't set;
|
||||
// The "Fusion." part of the of the original subname is removed because the
|
||||
// SubObjectT::NormalizeOption::NoFlatten flag isn't set;
|
||||
// The "$Cube." part of the of the original subname is replaced with "Part__Box." because the
|
||||
// SubObjectT::NormalizeOption::KeepSubName flag isn't set;
|
||||
// The "Edge1" part of the of the original subname is kept because the
|
||||
// SubObjectT::NormalizeOption::NoElement flag isn't set;
|
||||
EXPECT_NE(subObjTWithSubObjNormalized.getSubName().find("0."), std::string::npos);
|
||||
EXPECT_EQ(subObjTWithSubObjNormalized.getSubName().find(fuseName), std::string::npos);
|
||||
EXPECT_EQ(subObjTWithSubObjNormalized.getSubName().find(boxLabel), std::string::npos);
|
||||
EXPECT_NE(subObjTWithSubObjNormalized.getSubName().find(boxName), std::string::npos);
|
||||
EXPECT_NE(subObjTWithSubObjNormalized.getSubName().find("Edge1"), std::string::npos);
|
||||
|
||||
// In this case calling SubObjectT::normalized() changes subObjTWithoutEl subname in this way:
|
||||
// The "0." part of the of the original subname is kept because the
|
||||
// SubObjectT::NormalizeOption::ConvertIndex flag isn't set;
|
||||
// The "3." part of the of the original subname is kept because the
|
||||
// SubObjectT::NormalizeOption::ConvertIndex flag isn't set;
|
||||
// The "Fusion." part of the of the original subname is removed because the
|
||||
// SubObjectT::NormalizeOption::NoFlatten flag isn't set;
|
||||
// The "$Cube." part of the of the original subname is replaced with "Part__Box." because the
|
||||
// SubObjectT::NormalizeOption::KeepSubName flag isn't set;
|
||||
// The "Edge1" part of the of the original subname is removed because the
|
||||
// SubObjectT::NormalizeOption::NoElement flag is set;
|
||||
EXPECT_NE(subObjTWithoutElNormalized.getSubName().find("0."), std::string::npos);
|
||||
EXPECT_EQ(subObjTWithoutElNormalized.getSubName().find(fuseName), std::string::npos);
|
||||
EXPECT_EQ(subObjTWithoutElNormalized.getSubName().find(boxLabel), std::string::npos);
|
||||
EXPECT_NE(subObjTWithoutElNormalized.getSubName().find(boxName), std::string::npos);
|
||||
EXPECT_EQ(subObjTWithoutElNormalized.getSubName().find("Edge1"), std::string::npos);
|
||||
|
||||
// In this case calling SubObjectT::normalized() changes subObjTNoFlatten subname in this way:
|
||||
// The "0." part of the of the original subname is kept because the
|
||||
// SubObjectT::NormalizeOption::ConvertIndex flag isn't set;
|
||||
// The "3." part of the of the original subname is kept because the
|
||||
// SubObjectT::NormalizeOption::ConvertIndex flag isn't set;
|
||||
// The "Fusion." part of the of the original subname is kept because the
|
||||
// SubObjectT::NormalizeOption::NoFlatten flag is set;
|
||||
// The "$Cube." part of the of the original subname is replaced with "Part__Box." because the
|
||||
// SubObjectT::NormalizeOption::KeepSubName flag isn't set;
|
||||
// The "Edge1" part of the of the original subname is kept because the
|
||||
// SubObjectT::NormalizeOption::NoElement flag isn't set;
|
||||
EXPECT_NE(subObjTNoFlattenNormalized.getSubName().find("0."), std::string::npos);
|
||||
EXPECT_NE(subObjTNoFlattenNormalized.getSubName().find(fuseName), std::string::npos);
|
||||
EXPECT_EQ(subObjTNoFlattenNormalized.getSubName().find(boxLabel), std::string::npos);
|
||||
EXPECT_NE(subObjTNoFlattenNormalized.getSubName().find(boxName), std::string::npos);
|
||||
EXPECT_NE(subObjTNoFlattenNormalized.getSubName().find("Edge1"), std::string::npos);
|
||||
|
||||
// In this case calling SubObjectT::normalized() changes subObjTKeepSubName subname in this way:
|
||||
// The "0." part of the of the original subname is kept because the
|
||||
// SubObjectT::NormalizeOption::ConvertIndex flag isn't set;
|
||||
// The "3." part of the of the original subname is kept because the
|
||||
// SubObjectT::NormalizeOption::ConvertIndex flag isn't set;
|
||||
// The "Fusion." part of the of the original subname is removed because the
|
||||
// SubObjectT::NormalizeOption::NoFlatten flag isn't set;
|
||||
// The "$Cube." part of the of the original subname is kept because the
|
||||
// SubObjectT::NormalizeOption::KeepSubName flag is set;
|
||||
// The "Edge1" part of the of the original subname is kept because the
|
||||
// SubObjectT::NormalizeOption::NoElement flag isn't set;
|
||||
EXPECT_NE(subObjTKeepSubNameNormalized.getSubName().find("0."), std::string::npos);
|
||||
EXPECT_EQ(subObjTKeepSubNameNormalized.getSubName().find(fuseName), std::string::npos);
|
||||
EXPECT_NE(subObjTKeepSubNameNormalized.getSubName().find(boxLabel), std::string::npos);
|
||||
EXPECT_NE(subObjTKeepSubNameNormalized.getSubName().find("Edge1"), std::string::npos);
|
||||
|
||||
// In this case calling SubObjectT::normalized() changes subObjTConvertIndex in this way:
|
||||
// The "0." part of the of the original subname is replaced with "Array." because the
|
||||
// SubObjectT::NormalizeOption::ConvertIndex flag is set;
|
||||
// The "3." part of the of the original subname is kept even if the
|
||||
// SubObjectT::NormalizeOption::ConvertIndex flag is set because it refers to a specific
|
||||
// DocumentObject of the "Array." DocumentObject;
|
||||
// The "Fusion." part of the of the original subname is removed because the
|
||||
// SubObjectT::NormalizeOption::NoFlatten flag isn't set;
|
||||
// The "$Cube." part of the of the original subname is replaced with "Part__Box." because the
|
||||
// SubObjectT::NormalizeOption::KeepSubName flag isn't set;
|
||||
// The "Edge1" part of the of the original subname is kept because the
|
||||
// SubObjectT::NormalizeOption::NoElement flag isn't set;
|
||||
EXPECT_EQ(subObjTConvertIndexNormalized.getSubName().find("0."), std::string::npos);
|
||||
EXPECT_NE(subObjTConvertIndexNormalized.getSubName().find(lArrName), std::string::npos);
|
||||
EXPECT_EQ(subObjTConvertIndexNormalized.getSubName().find(fuseName), std::string::npos);
|
||||
EXPECT_EQ(subObjTConvertIndexNormalized.getSubName().find(boxLabel), std::string::npos);
|
||||
EXPECT_NE(subObjTConvertIndexNormalized.getSubName().find(boxName), std::string::npos);
|
||||
EXPECT_NE(subObjTConvertIndexNormalized.getSubName().find("Edge1"), std::string::npos);
|
||||
}
|
||||
563
tests/src/App/ElementMap.cpp
Normal file
563
tests/src/App/ElementMap.cpp
Normal file
@@ -0,0 +1,563 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include <App/Application.h>
|
||||
#include <App/ElementMap.h>
|
||||
#include <src/App/InitApplication.h>
|
||||
|
||||
// NOLINTBEGIN(readability-magic-numbers)
|
||||
|
||||
|
||||
// this is a "holder" class used for simpler testing of ElementMap in the context of a class
|
||||
class LessComplexPart
|
||||
{
|
||||
public:
|
||||
LessComplexPart(long tag, const std::string& nameStr, App::StringHasherRef hasher)
|
||||
: elementMapPtr(std::make_shared<Data::ElementMap>())
|
||||
, Tag(tag)
|
||||
, name(nameStr)
|
||||
{
|
||||
// object also have Vertexes etc and the face count varies; but that is not important
|
||||
// here since we are not testing a real model
|
||||
// the "MappedName" is left blank for now
|
||||
Data::IndexedName face1("Face", 1);
|
||||
Data::IndexedName face2("Face", 2);
|
||||
Data::IndexedName face3("Face", 3);
|
||||
Data::IndexedName face4("Face", 4);
|
||||
Data::IndexedName face5("Face", 5);
|
||||
Data::IndexedName face6("Face", 6);
|
||||
elementMapPtr->hasher = hasher;
|
||||
elementMapPtr->setElementName(face1, Data::MappedName(face1), Tag);
|
||||
elementMapPtr->setElementName(face2, Data::MappedName(face2), Tag);
|
||||
elementMapPtr->setElementName(face3, Data::MappedName(face3), Tag);
|
||||
elementMapPtr->setElementName(face4, Data::MappedName(face4), Tag);
|
||||
elementMapPtr->setElementName(face5, Data::MappedName(face5), Tag);
|
||||
elementMapPtr->setElementName(face6, Data::MappedName(face6), Tag);
|
||||
}
|
||||
|
||||
Data::ElementMapPtr elementMapPtr;
|
||||
mutable long Tag;
|
||||
Data::MappedName name;
|
||||
};
|
||||
|
||||
class ElementMapTest: public ::testing::Test
|
||||
{
|
||||
protected:
|
||||
static void SetUpTestSuite()
|
||||
{
|
||||
tests::initApplication();
|
||||
}
|
||||
|
||||
void SetUp() override
|
||||
{
|
||||
_docName = App::GetApplication().getUniqueDocumentName("test");
|
||||
App::GetApplication().newDocument(_docName.c_str(), "testUser");
|
||||
_sids = &_sid;
|
||||
_hasher = Base::Reference<App::StringHasher>(new App::StringHasher);
|
||||
ASSERT_EQ(_hasher.getRefCount(), 1);
|
||||
}
|
||||
|
||||
void TearDown() override
|
||||
{
|
||||
App::GetApplication().closeDocument(_docName.c_str());
|
||||
}
|
||||
|
||||
std::string _docName;
|
||||
Data::ElementIDRefs _sid;
|
||||
QVector<App::StringIDRef>* _sids;
|
||||
App::StringHasherRef _hasher;
|
||||
};
|
||||
|
||||
TEST_F(ElementMapTest, defaultConstruction)
|
||||
{
|
||||
// Act
|
||||
Data::ElementMap elementMap = Data::ElementMap();
|
||||
|
||||
// Assert
|
||||
EXPECT_EQ(elementMap.size(), 0);
|
||||
}
|
||||
|
||||
TEST_F(ElementMapTest, setElementNameDefaults)
|
||||
{
|
||||
// Arrange
|
||||
Data::ElementMap elementMap;
|
||||
Data::IndexedName element("Edge", 1);
|
||||
Data::MappedName mappedName("TEST");
|
||||
|
||||
// Act
|
||||
auto resultName = elementMap.setElementName(element, mappedName, 0);
|
||||
auto mappedToElement = elementMap.find(element);
|
||||
|
||||
// Assert
|
||||
EXPECT_EQ(resultName, mappedName);
|
||||
EXPECT_EQ(mappedToElement, mappedName);
|
||||
}
|
||||
|
||||
TEST_F(ElementMapTest, setElementNameNoOverwrite)
|
||||
{
|
||||
// Arrange
|
||||
Data::ElementMap elementMap;
|
||||
Data::IndexedName element("Edge", 1);
|
||||
Data::MappedName mappedName("TEST");
|
||||
Data::MappedName anotherMappedName("ANOTHERTEST");
|
||||
|
||||
// Act
|
||||
auto resultName = elementMap.setElementName(element, mappedName, 0);
|
||||
auto resultName2 = elementMap.setElementName(element, anotherMappedName, 0, _sids, false);
|
||||
auto mappedToElement = elementMap.find(element);
|
||||
auto findAllResult = elementMap.findAll(element);
|
||||
|
||||
// Assert
|
||||
EXPECT_EQ(resultName, mappedName);
|
||||
EXPECT_EQ(resultName2, anotherMappedName);
|
||||
EXPECT_EQ(mappedToElement, mappedName);
|
||||
EXPECT_EQ(findAllResult.size(), 2);
|
||||
EXPECT_EQ(findAllResult[0].first, mappedName);
|
||||
EXPECT_EQ(findAllResult[1].first, anotherMappedName);
|
||||
}
|
||||
|
||||
TEST_F(ElementMapTest, setElementNameWithOverwrite)
|
||||
{
|
||||
// Arrange
|
||||
Data::ElementMap elementMap;
|
||||
Data::IndexedName element("Edge", 1);
|
||||
Data::MappedName mappedName("TEST");
|
||||
Data::MappedName anotherMappedName("ANOTHERTEST");
|
||||
|
||||
// Act
|
||||
auto resultName = elementMap.setElementName(element, mappedName, 0);
|
||||
auto resultName2 = elementMap.setElementName(element, anotherMappedName, 0, _sids, true);
|
||||
auto mappedToElement = elementMap.find(element);
|
||||
auto findAllResult = elementMap.findAll(element);
|
||||
|
||||
// Assert
|
||||
EXPECT_EQ(resultName, mappedName);
|
||||
EXPECT_EQ(resultName2, anotherMappedName);
|
||||
EXPECT_EQ(mappedToElement, anotherMappedName);
|
||||
EXPECT_EQ(findAllResult.size(), 1);
|
||||
EXPECT_EQ(findAllResult[0].first, anotherMappedName);
|
||||
}
|
||||
|
||||
TEST_F(ElementMapTest, setElementNameWithHashing)
|
||||
{
|
||||
// Arrange
|
||||
Data::ElementMap elementMap;
|
||||
std::ostringstream ss;
|
||||
Data::IndexedName element("Edge", 1);
|
||||
Data::MappedName elementNameHolder(element); // Will get modified by the encoder
|
||||
const Data::MappedName expectedName(element);
|
||||
|
||||
// Act
|
||||
elementMap.encodeElementName(element.getType()[0], elementNameHolder, ss, nullptr, 0, nullptr, 0);
|
||||
auto resultName = elementMap.setElementName(element, elementNameHolder, 0, _sids);
|
||||
auto mappedToElement = elementMap.find(element);
|
||||
|
||||
// Assert
|
||||
EXPECT_EQ(resultName, expectedName);
|
||||
EXPECT_EQ(mappedToElement, expectedName);
|
||||
}
|
||||
|
||||
TEST_F(ElementMapTest, eraseMappedName)
|
||||
{
|
||||
// Arrange
|
||||
Data::ElementMap elementMap;
|
||||
Data::IndexedName element("Edge", 1);
|
||||
Data::MappedName mappedName("TEST");
|
||||
Data::MappedName anotherMappedName("ANOTHERTEST");
|
||||
elementMap.setElementName(element, mappedName, 0);
|
||||
elementMap.setElementName(element, anotherMappedName, 0);
|
||||
|
||||
// Act
|
||||
auto sizeBefore = elementMap.size();
|
||||
auto findAllBefore = elementMap.findAll(element);
|
||||
|
||||
elementMap.erase(anotherMappedName);
|
||||
auto sizeAfter = elementMap.size();
|
||||
auto findAllAfter = elementMap.findAll(element);
|
||||
|
||||
elementMap.erase(anotherMappedName);
|
||||
auto sizeAfterRepeat = elementMap.size();
|
||||
auto findAllAfterRepeat = elementMap.findAll(element);
|
||||
|
||||
// Assert
|
||||
EXPECT_EQ(sizeBefore, 2);
|
||||
EXPECT_EQ(findAllBefore.size(), 2);
|
||||
EXPECT_EQ(findAllBefore[0].first, mappedName);
|
||||
EXPECT_EQ(findAllBefore[1].first, anotherMappedName);
|
||||
|
||||
EXPECT_EQ(sizeAfter, 1);
|
||||
EXPECT_EQ(findAllAfter.size(), 1);
|
||||
EXPECT_EQ(findAllAfter[0].first, mappedName);
|
||||
|
||||
EXPECT_EQ(sizeAfterRepeat, 1);
|
||||
EXPECT_EQ(findAllAfterRepeat.size(), 1);
|
||||
EXPECT_EQ(findAllAfterRepeat[0].first, mappedName);
|
||||
}
|
||||
|
||||
TEST_F(ElementMapTest, eraseIndexedName)
|
||||
{
|
||||
// Arrange
|
||||
// Create two elements, edge1 and edge2, that have two mapped names each.
|
||||
Data::ElementMap elementMap;
|
||||
|
||||
Data::IndexedName element("Edge", 1);
|
||||
Data::MappedName mappedName("TEST");
|
||||
Data::MappedName anotherMappedName("ANOTHERTEST");
|
||||
elementMap.setElementName(element, mappedName, 0);
|
||||
elementMap.setElementName(element, anotherMappedName, 0);
|
||||
|
||||
Data::IndexedName element2("Edge", 2);
|
||||
Data::MappedName mappedName2("TEST2");
|
||||
Data::MappedName anotherMappedName2("ANOTHERTEST2");
|
||||
elementMap.setElementName(element2, mappedName2, 0);
|
||||
elementMap.setElementName(element2, anotherMappedName2, 0);
|
||||
|
||||
// Act
|
||||
auto sizeBefore = elementMap.size();
|
||||
auto findAllBefore = elementMap.findAll(element2);
|
||||
|
||||
elementMap.erase(element2);
|
||||
auto sizeAfter = elementMap.size();
|
||||
auto findAllAfter = elementMap.findAll(element2);
|
||||
|
||||
elementMap.erase(element2);
|
||||
auto sizeAfterRepeat = elementMap.size();
|
||||
auto findAllAfterRepeat = elementMap.findAll(element2);
|
||||
|
||||
// Assert
|
||||
EXPECT_EQ(sizeBefore, 4);
|
||||
EXPECT_EQ(findAllBefore.size(), 2);
|
||||
EXPECT_EQ(findAllBefore[0].first, mappedName2);
|
||||
EXPECT_EQ(findAllBefore[1].first, anotherMappedName2);
|
||||
|
||||
EXPECT_EQ(sizeAfter, 2);
|
||||
EXPECT_EQ(findAllAfter.size(), 0);
|
||||
|
||||
EXPECT_EQ(sizeAfterRepeat, 2);
|
||||
EXPECT_EQ(findAllAfterRepeat.size(), 0);
|
||||
}
|
||||
|
||||
TEST_F(ElementMapTest, findMappedName)
|
||||
{
|
||||
// Arrange
|
||||
// Create two elements, edge1 and edge2, that have two mapped names each.
|
||||
Data::ElementMap elementMap;
|
||||
|
||||
Data::IndexedName element("Edge", 1);
|
||||
Data::MappedName mappedName("TEST");
|
||||
Data::MappedName anotherMappedName("ANOTHERTEST");
|
||||
elementMap.setElementName(element, mappedName, 0);
|
||||
elementMap.setElementName(element, anotherMappedName, 0);
|
||||
|
||||
Data::IndexedName element2("Edge", 2);
|
||||
Data::MappedName mappedName2("TEST2");
|
||||
Data::MappedName anotherMappedName2("ANOTHERTEST2");
|
||||
elementMap.setElementName(element2, mappedName2, 0);
|
||||
elementMap.setElementName(element2, anotherMappedName2, 0);
|
||||
|
||||
// Act
|
||||
auto findResult = elementMap.find(mappedName);
|
||||
auto findResult2 = elementMap.find(mappedName2);
|
||||
|
||||
// Assert
|
||||
EXPECT_EQ(findResult, element);
|
||||
EXPECT_EQ(findResult2, element2);
|
||||
}
|
||||
|
||||
TEST_F(ElementMapTest, findIndexedName)
|
||||
{
|
||||
// Arrange
|
||||
// Create two elements, edge1 and edge2, that have two mapped names each.
|
||||
Data::ElementMap elementMap;
|
||||
|
||||
Data::IndexedName element("Edge", 1);
|
||||
Data::MappedName mappedName("TEST");
|
||||
Data::MappedName anotherMappedName("ANOTHERTEST");
|
||||
elementMap.setElementName(element, mappedName, 0);
|
||||
elementMap.setElementName(element, anotherMappedName, 0);
|
||||
|
||||
Data::IndexedName element2("Edge", 2);
|
||||
Data::MappedName mappedName2("TEST2");
|
||||
Data::MappedName anotherMappedName2("ANOTHERTEST2");
|
||||
elementMap.setElementName(element2, mappedName2, 0);
|
||||
elementMap.setElementName(element2, anotherMappedName2, 0);
|
||||
|
||||
// Act
|
||||
// they return the first mapped name
|
||||
auto findResult = elementMap.find(element);
|
||||
auto findResult2 = elementMap.find(element2);
|
||||
|
||||
// Assert
|
||||
EXPECT_EQ(findResult, mappedName);
|
||||
EXPECT_EQ(findResult2, mappedName2);
|
||||
}
|
||||
|
||||
TEST_F(ElementMapTest, findAll)
|
||||
{
|
||||
// Arrange
|
||||
// Create two elements, edge1 and edge2, that have two mapped names each.
|
||||
Data::ElementMap elementMap;
|
||||
|
||||
Data::IndexedName element("Edge", 1);
|
||||
Data::MappedName mappedName("TEST");
|
||||
Data::MappedName anotherMappedName("ANOTHERTEST");
|
||||
elementMap.setElementName(element, mappedName, 0);
|
||||
elementMap.setElementName(element, anotherMappedName, 0);
|
||||
|
||||
Data::IndexedName element2("Edge", 2);
|
||||
Data::MappedName mappedName2("TEST2");
|
||||
Data::MappedName anotherMappedName2("ANOTHERTEST2");
|
||||
elementMap.setElementName(element2, mappedName2, 0);
|
||||
elementMap.setElementName(element2, anotherMappedName2, 0);
|
||||
|
||||
// Act
|
||||
// they return the first mapped name
|
||||
auto findResult = elementMap.findAll(element);
|
||||
auto findResult2 = elementMap.findAll(element2);
|
||||
|
||||
// Assert
|
||||
EXPECT_EQ(findResult.size(), 2);
|
||||
EXPECT_EQ(findResult[0].first, mappedName);
|
||||
EXPECT_EQ(findResult[1].first, anotherMappedName);
|
||||
EXPECT_EQ(findResult2.size(), 2);
|
||||
EXPECT_EQ(findResult2[0].first, mappedName2);
|
||||
EXPECT_EQ(findResult2[1].first, anotherMappedName2);
|
||||
}
|
||||
|
||||
TEST_F(ElementMapTest, mimicOnePart)
|
||||
{
|
||||
// Arrange
|
||||
// pattern: new doc, create Cube
|
||||
// for a single part, there is no "naming algo" to speak of
|
||||
std::ostringstream ss;
|
||||
auto docName = "Unnamed";
|
||||
LessComplexPart cube(1L, "Box", _hasher);
|
||||
|
||||
// Act
|
||||
auto children = cube.elementMapPtr->getAll();
|
||||
ss << docName << "#" << cube.name << "."
|
||||
<< cube.elementMapPtr->find(Data::IndexedName("Face", 6));
|
||||
|
||||
// Assert
|
||||
EXPECT_EQ(children.size(), 6);
|
||||
EXPECT_EQ(children[0].index.toString(), "Face1");
|
||||
EXPECT_EQ(children[0].name.toString(), "Face1");
|
||||
EXPECT_EQ(children[1].index.toString(), "Face2");
|
||||
EXPECT_EQ(children[1].name.toString(), "Face2");
|
||||
EXPECT_EQ(children[2].index.toString(), "Face3");
|
||||
EXPECT_EQ(children[2].name.toString(), "Face3");
|
||||
EXPECT_EQ(children[3].index.toString(), "Face4");
|
||||
EXPECT_EQ(children[3].name.toString(), "Face4");
|
||||
EXPECT_EQ(children[4].index.toString(), "Face5");
|
||||
EXPECT_EQ(children[4].name.toString(), "Face5");
|
||||
EXPECT_EQ(children[5].index.toString(), "Face6");
|
||||
EXPECT_EQ(children[5].name.toString(), "Face6");
|
||||
EXPECT_EQ(ss.str(), "Unnamed#Box.Face6");
|
||||
}
|
||||
|
||||
TEST_F(ElementMapTest, mimicSimpleUnion)
|
||||
{
|
||||
// Arrange
|
||||
// pattern: new doc, create Cube, create Cylinder, Union of both (Cube first)
|
||||
std::ostringstream ss;
|
||||
std::ostringstream finalSs;
|
||||
const char* docName = "Unnamed";
|
||||
|
||||
LessComplexPart cube(1L, "Box", _hasher);
|
||||
LessComplexPart cylinder(2L, "Cylinder", _hasher);
|
||||
// Union (Fusion) operation via the Part Workbench
|
||||
LessComplexPart unionPart(3L, "Fusion", _hasher);
|
||||
|
||||
// we are only going to simulate one face for testing purpose
|
||||
Data::IndexedName uface3("Face", 3);
|
||||
auto PartOp = "FUS"; // Part::OpCodes::Fuse;
|
||||
|
||||
// Act
|
||||
// act: simulate a union/fuse operation
|
||||
auto parent = cube.elementMapPtr->getAll()[5];
|
||||
Data::MappedName postfixHolder(std::string(Data::POSTFIX_MOD) + "2");
|
||||
unionPart.elementMapPtr->encodeElementName(
|
||||
postfixHolder[0],
|
||||
postfixHolder,
|
||||
ss,
|
||||
nullptr,
|
||||
unionPart.Tag,
|
||||
nullptr,
|
||||
unionPart.Tag
|
||||
);
|
||||
auto postfixStr = postfixHolder.toString() + Data::ELEMENT_MAP_PREFIX + PartOp;
|
||||
|
||||
// act: with the fuse op, name against the cube's Face6
|
||||
Data::MappedName uface3Holder(parent.index);
|
||||
// we will invoke the encoder for face 3
|
||||
unionPart.elementMapPtr->encodeElementName(
|
||||
uface3Holder[0],
|
||||
uface3Holder,
|
||||
ss,
|
||||
nullptr,
|
||||
unionPart.Tag,
|
||||
postfixStr.c_str(),
|
||||
cube.Tag
|
||||
);
|
||||
unionPart.elementMapPtr->setElementName(uface3, uface3Holder, unionPart.Tag, nullptr, true);
|
||||
|
||||
// act: generate a full toponame string for testing purposes
|
||||
finalSs << docName << "#" << unionPart.name;
|
||||
finalSs << ".";
|
||||
finalSs << Data::ELEMENT_MAP_PREFIX + unionPart.elementMapPtr->find(uface3).toString();
|
||||
finalSs << ".";
|
||||
finalSs << uface3;
|
||||
|
||||
// Assert
|
||||
EXPECT_EQ(postfixStr, ":M2;FUS");
|
||||
EXPECT_EQ(unionPart.elementMapPtr->find(uface3).toString(), "Face6;:M2;FUS;:H1:8,F");
|
||||
EXPECT_EQ(finalSs.str(), "Unnamed#Fusion.;Face6;:M2;FUS;:H1:8,F.Face3");
|
||||
|
||||
// explanation of "Fusion.;Face6;:M2;FUS;:H2:3,F.Face3" toponame
|
||||
// Note: every postfix is prefixed by semicolon
|
||||
// Note: the start/middle/end are separated by periods
|
||||
//
|
||||
// "Fusion" means that we are on the "Fusion" object.
|
||||
// "." we are done with the first part
|
||||
// ";Face6" means default inheritance comes from face 6 of the parent (which is a cube)
|
||||
// ";:M2" means that a Workbench op has happened. "M" is the "Mod" directory in the source tree?
|
||||
// ";FUS" means that a Fusion operation has happened. Notice the lack of a colon.
|
||||
// ";:H2" means the subtending object (cylinder) has a tag of 2
|
||||
// ":3" means the writing position is 3; literally how far into the current postfix we are
|
||||
// ",F" means are of type "F" which is short for "Face" of Face3 of Fusion.
|
||||
// "." we are done with the second part
|
||||
// "Face3" is the localized name
|
||||
}
|
||||
|
||||
TEST_F(ElementMapTest, mimicOperationAgainstSelf)
|
||||
{
|
||||
// Arrange
|
||||
// pattern: new doc, create Cube, Mystery Op with self as target
|
||||
std::ostringstream ss;
|
||||
LessComplexPart finalPart(99L, "MysteryOp", _hasher);
|
||||
// we are only going to simulate one face for testing purpose
|
||||
Data::IndexedName uface3("Face", 3);
|
||||
auto PartOp = "MYS";
|
||||
auto ownFace6 = finalPart.elementMapPtr->getAll()[5];
|
||||
Data::MappedName uface3Holder(ownFace6.index);
|
||||
auto workbenchId = std::string(Data::POSTFIX_MOD) + "9999";
|
||||
|
||||
// Act
|
||||
// act: with the mystery op, name against its own Face6 for some reason
|
||||
Data::MappedName postfixHolder(workbenchId);
|
||||
finalPart.elementMapPtr->encodeElementName(
|
||||
postfixHolder[0],
|
||||
postfixHolder,
|
||||
ss,
|
||||
nullptr,
|
||||
finalPart.Tag,
|
||||
nullptr,
|
||||
finalPart.Tag
|
||||
);
|
||||
auto postfixStr = postfixHolder.toString() + Data::ELEMENT_MAP_PREFIX + PartOp;
|
||||
// we will invoke the encoder for face 3
|
||||
finalPart.elementMapPtr->encodeElementName(
|
||||
uface3Holder[0],
|
||||
uface3Holder,
|
||||
ss,
|
||||
nullptr,
|
||||
finalPart.Tag,
|
||||
postfixStr.c_str(),
|
||||
finalPart.Tag
|
||||
);
|
||||
// override not forced
|
||||
finalPart.elementMapPtr->setElementName(uface3, uface3Holder, finalPart.Tag, nullptr, false);
|
||||
|
||||
// Assert
|
||||
EXPECT_EQ(postfixStr, ":M9999;MYS");
|
||||
EXPECT_EQ(finalPart.elementMapPtr->find(uface3).toString(), "Face3"); // override not forced
|
||||
EXPECT_EQ(uface3Holder.toString(), "Face6;:M9999;MYS;:H63:b,F");
|
||||
// explaining ";Face6;:M2;MYS;:H2:3,F" name:
|
||||
//
|
||||
// ";Face6" means default inheritance comes from face 6 of the ownFace6 (which is itself)
|
||||
// ";:M9999" means that a Workbench op happened. "M" is the "Mod" directory in the source tree?
|
||||
// ";MYS" means that a "Mystery" operation has happened. Notice the lack of a colon.
|
||||
// ";:H63" means the subtending object (cylinder) has a tag of 99 (63 in hex)
|
||||
// ":b" means the writing position is b (hex); literally how far into the current postfix we are
|
||||
// ",F" means are of type "F" which is short for "Face" of Face3 of Fusion.
|
||||
}
|
||||
|
||||
TEST_F(ElementMapTest, hasChildElementMapTest)
|
||||
{
|
||||
// Arrange
|
||||
Data::ElementMap::MappedChildElements child
|
||||
= {Data::IndexedName("face", 1), 2, 7, 4L, Data::ElementMapPtr(), QByteArray(""), _sid};
|
||||
std::vector<Data::ElementMap::MappedChildElements> children = {child};
|
||||
LessComplexPart cubeFull(3L, "FullBox", _hasher);
|
||||
cubeFull.elementMapPtr->addChildElements(cubeFull.Tag, children);
|
||||
//
|
||||
LessComplexPart cubeWithoutChildren(2L, "EmptyBox", _hasher);
|
||||
|
||||
// Act
|
||||
bool resultFull = cubeFull.elementMapPtr->hasChildElementMap();
|
||||
bool resultWhenEmpty = cubeWithoutChildren.elementMapPtr->hasChildElementMap();
|
||||
|
||||
// Assert
|
||||
EXPECT_TRUE(resultFull);
|
||||
EXPECT_FALSE(resultWhenEmpty);
|
||||
}
|
||||
|
||||
TEST_F(ElementMapTest, hashChildMapsTest)
|
||||
{
|
||||
// Arrange
|
||||
LessComplexPart cube(1L, "Box", _hasher);
|
||||
auto childOneName = Data::IndexedName("Ping", 1);
|
||||
Data::ElementMap::MappedChildElements childOne = {
|
||||
childOneName,
|
||||
2,
|
||||
7,
|
||||
3L,
|
||||
Data::ElementMapPtr(),
|
||||
QByteArray("abcdefghij"), // postfix must be 10 or more bytes to invoke hasher
|
||||
_sid
|
||||
};
|
||||
std::vector<Data::ElementMap::MappedChildElements> children = {childOne};
|
||||
cube.elementMapPtr->addChildElements(cube.Tag, children);
|
||||
auto before = _hasher->getIDMap();
|
||||
|
||||
// Act
|
||||
cube.elementMapPtr->hashChildMaps(cube.Tag);
|
||||
|
||||
// Assert
|
||||
auto after = _hasher->getIDMap();
|
||||
EXPECT_EQ(before.size(), 0);
|
||||
EXPECT_EQ(after.size(), 1);
|
||||
}
|
||||
|
||||
TEST_F(ElementMapTest, addAndGetChildElementsTest)
|
||||
{
|
||||
// Arrange
|
||||
LessComplexPart cube(1L, "Box", _hasher);
|
||||
Data::ElementMap::MappedChildElements childOne = {
|
||||
Data::IndexedName("Ping", 1),
|
||||
2,
|
||||
7,
|
||||
3L,
|
||||
Data::ElementMapPtr(),
|
||||
QByteArray("abcdefghij"), // postfix must be 10 or more bytes to invoke hasher
|
||||
_sid
|
||||
};
|
||||
Data::ElementMap::MappedChildElements childTwo
|
||||
= {Data::IndexedName("Pong", 2), 2, 7, 4L, Data::ElementMapPtr(), QByteArray("abc"), _sid};
|
||||
std::vector<Data::ElementMap::MappedChildElements> children = {childOne, childTwo};
|
||||
|
||||
// Act
|
||||
cube.elementMapPtr->addChildElements(cube.Tag, children);
|
||||
auto result = cube.elementMapPtr->getChildElements();
|
||||
|
||||
// Assert
|
||||
EXPECT_EQ(result.size(), 2);
|
||||
EXPECT_TRUE(std::any_of(result.begin(), result.end(), [](Data::ElementMap::MappedChildElements e) {
|
||||
return e.indexedName.toString() == "Ping1";
|
||||
}));
|
||||
EXPECT_TRUE(std::any_of(result.begin(), result.end(), [](Data::ElementMap::MappedChildElements e) {
|
||||
return e.indexedName.toString() == "Pong2";
|
||||
}));
|
||||
}
|
||||
// NOLINTEND(readability-magic-numbers)
|
||||
87
tests/src/App/ElementNamingUtils.cpp
Normal file
87
tests/src/App/ElementNamingUtils.cpp
Normal file
@@ -0,0 +1,87 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include <App/Application.h>
|
||||
#include <App/ElementMap.h>
|
||||
#include <src/App/InitApplication.h>
|
||||
|
||||
// NOLINTBEGIN(readability-magic-numbers)
|
||||
|
||||
|
||||
class ElementNamingUtilsTest: public ::testing::Test
|
||||
{
|
||||
protected:
|
||||
static void SetUpTestSuite()
|
||||
{
|
||||
tests::initApplication();
|
||||
}
|
||||
|
||||
void SetUp() override
|
||||
{
|
||||
_docName = App::GetApplication().getUniqueDocumentName("test");
|
||||
App::GetApplication().newDocument(_docName.c_str(), "testUser");
|
||||
_sids = &_sid;
|
||||
_hasher = Base::Reference<App::StringHasher>(new App::StringHasher);
|
||||
ASSERT_EQ(_hasher.getRefCount(), 1);
|
||||
}
|
||||
|
||||
void TearDown() override
|
||||
{
|
||||
App::GetApplication().closeDocument(_docName.c_str());
|
||||
}
|
||||
|
||||
std::string _docName;
|
||||
Data::ElementIDRefs _sid;
|
||||
QVector<App::StringIDRef>* _sids;
|
||||
App::StringHasherRef _hasher;
|
||||
};
|
||||
|
||||
TEST_F(ElementNamingUtilsTest, findElementName)
|
||||
{
|
||||
// Act
|
||||
Data::ElementMap elementMap = Data::ElementMap();
|
||||
auto name1 = Data::findElementName("Edge1");
|
||||
auto name2 = Data::findElementName(
|
||||
";g5v2;SKT;:Had6,V;:G;OFS;:Had6:7,V;:G;OFS;:Had6:7,V;WIR;:"
|
||||
"Had6:4,V;:G;XTR;:Had6:7,E;:H,E.Face1.Edge2"
|
||||
);
|
||||
auto name3 = Data::findElementName("An.Example.Assembly.Edge3");
|
||||
auto name4 = Data::findElementName(".Edge4");
|
||||
|
||||
// Assert
|
||||
EXPECT_STREQ(name1, "Edge1");
|
||||
EXPECT_STREQ(
|
||||
name2,
|
||||
";g5v2;SKT;:Had6,V;:G;OFS;:Had6:7,V;:G;OFS;:Had6:7,V;WIR;:"
|
||||
"Had6:4,V;:G;XTR;:Had6:7,E;:H,E.Face1.Edge2"
|
||||
);
|
||||
EXPECT_STREQ(name3, "Edge3");
|
||||
EXPECT_STREQ(name4, "Edge4");
|
||||
}
|
||||
|
||||
TEST_F(ElementNamingUtilsTest, indexOfElement)
|
||||
{
|
||||
// Valid cases
|
||||
EXPECT_EQ(Data::indexOfElement("Edge1", "Edge"), 1);
|
||||
EXPECT_EQ(Data::indexOfElement("Edge12", "Edge"), 12);
|
||||
EXPECT_EQ(Data::indexOfElement("Edge999", "Edge"), 999);
|
||||
|
||||
// Prefix mismatch
|
||||
EXPECT_EQ(Data::indexOfElement("Node5", "Edge"), 0);
|
||||
|
||||
// Missing numeric suffix
|
||||
EXPECT_EQ(Data::indexOfElement("Edge", "Edge"), 0);
|
||||
|
||||
// Non-numeric suffix
|
||||
EXPECT_EQ(Data::indexOfElement("EdgeX", "Edge"), 0);
|
||||
EXPECT_EQ(Data::indexOfElement("Edge12X", "Edge"), 0);
|
||||
|
||||
// Zero or invalid index
|
||||
EXPECT_EQ(Data::indexOfElement("Edge0", "Edge"), 0);
|
||||
|
||||
// Degenerate inputs
|
||||
EXPECT_EQ(Data::indexOfElement("", "Edge"), 0);
|
||||
EXPECT_EQ(Data::indexOfElement("123", ""), 0);
|
||||
}
|
||||
// NOLINTEND(readability-magic-numbers)
|
||||
415
tests/src/App/Expression.cpp
Normal file
415
tests/src/App/Expression.cpp
Normal file
@@ -0,0 +1,415 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
/***************************************************************************
|
||||
* Copyright (c) 2023 Werner Mayer <wmayer[at]users.sourceforge.net> *
|
||||
* Copyright (c) 2025 Pieter Hijma <info@pieterhijma.net> *
|
||||
* *
|
||||
* This file is part of FreeCAD. *
|
||||
* *
|
||||
* FreeCAD is free software: you can redistribute it and/or modify it *
|
||||
* under the terms of the GNU Lesser General Public License as *
|
||||
* published by the Free Software Foundation, either version 2.1 of the *
|
||||
* License, or (at your option) any later version. *
|
||||
* *
|
||||
* FreeCAD is distributed in the hope that it will be useful, but *
|
||||
* WITHOUT ANY WARRANTY; without even the implied warranty of *
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
|
||||
* Lesser General Public License for more details. *
|
||||
* *
|
||||
* You should have received a copy of the GNU Lesser General Public *
|
||||
* License along with FreeCAD. If not, see *
|
||||
* <https://www.gnu.org/licenses/>. *
|
||||
* *
|
||||
**************************************************************************/
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include <src/App/InitApplication.h>
|
||||
|
||||
#include "App/Document.h"
|
||||
#include "App/DocumentObject.h"
|
||||
#include "App/Expression.h"
|
||||
#include "App/ExpressionParser.h"
|
||||
#include "App/ExpressionTokenizer.h"
|
||||
|
||||
// +------------------------------------------------+
|
||||
// | Note: For more expression related tests, see: |
|
||||
// | src/Mod/Spreadsheet/TestSpreadsheet.py |
|
||||
// +------------------------------------------------+
|
||||
|
||||
class Expression: public ::testing::Test
|
||||
{
|
||||
protected:
|
||||
static void SetUpTestSuite()
|
||||
{
|
||||
tests::initApplication();
|
||||
}
|
||||
};
|
||||
|
||||
// clang-format off
|
||||
TEST_F(Expression, tokenize)
|
||||
{
|
||||
EXPECT_EQ(App::ExpressionTokenizer().perform(QStringLiteral(""), 10), QString());
|
||||
// 0.0000 deg-
|
||||
EXPECT_EQ(App::ExpressionTokenizer().perform(QString::fromUtf8("0.00000 \xC2\xB0-"), 10), QString());
|
||||
EXPECT_EQ(App::ExpressionTokenizer().perform(QString::fromUtf8("0.00000 \xC2\xB0-s"), 11), QStringLiteral("s"));
|
||||
EXPECT_EQ(App::ExpressionTokenizer().perform(QString::fromUtf8("0.00000 \xC2\xB0-ss"), 12), QStringLiteral("ss"));
|
||||
EXPECT_EQ(App::ExpressionTokenizer().perform(QStringLiteral("0.00000 deg"), 5), QString());
|
||||
EXPECT_EQ(App::ExpressionTokenizer().perform(QStringLiteral("0.00000 deg"), 11), QStringLiteral("deg"));
|
||||
}
|
||||
|
||||
TEST_F(Expression, tokenizeCompletion)
|
||||
{
|
||||
EXPECT_EQ(App::ExpressionTokenizer().perform(QStringLiteral("My Cube"), 7), QStringLiteral("MyCube"));
|
||||
EXPECT_EQ(App::ExpressionTokenizer().perform(QStringLiteral("My Cube0"), 8), QStringLiteral("MyCube0"));
|
||||
EXPECT_EQ(App::ExpressionTokenizer().perform(QStringLiteral("My Cube 0"), 9), QStringLiteral("MyCube0"));
|
||||
EXPECT_EQ(App::ExpressionTokenizer().perform(QStringLiteral("My Cube1"), 8), QStringLiteral("MyCube1"));
|
||||
EXPECT_EQ(App::ExpressionTokenizer().perform(QStringLiteral("My Cube 1"), 9), QStringLiteral("MyCube1"));
|
||||
}
|
||||
|
||||
TEST_F(Expression, tokenizeQuantity)
|
||||
{
|
||||
auto result = App::ExpressionParser::tokenize("0.00000 deg");
|
||||
EXPECT_EQ(result.size(), 2);
|
||||
EXPECT_EQ(std::get<0>(result[0]), App::ExpressionParser::NUM);
|
||||
EXPECT_EQ(std::get<1>(result[0]), 0);
|
||||
EXPECT_EQ(std::get<2>(result[0]), "0.00000");
|
||||
EXPECT_EQ(std::get<0>(result[1]), App::ExpressionParser::UNIT);
|
||||
EXPECT_EQ(std::get<1>(result[1]), 8);
|
||||
EXPECT_EQ(std::get<2>(result[1]), "deg");
|
||||
}
|
||||
|
||||
TEST_F(Expression, tokenizeFunc)
|
||||
{
|
||||
auto result = App::ExpressionParser::tokenize("sin(0.00000)");
|
||||
EXPECT_EQ(result.size(), 3);
|
||||
EXPECT_EQ(std::get<0>(result[0]), App::ExpressionParser::FUNC);
|
||||
EXPECT_EQ(std::get<1>(result[0]), 0);
|
||||
EXPECT_EQ(std::get<2>(result[0]), "sin(");
|
||||
EXPECT_EQ(std::get<0>(result[1]), App::ExpressionParser::NUM);
|
||||
EXPECT_EQ(std::get<1>(result[1]), 4);
|
||||
EXPECT_EQ(std::get<2>(result[1]), "0.00000");
|
||||
EXPECT_EQ(std::get<1>(result[2]), 11);
|
||||
EXPECT_EQ(std::get<2>(result[2]), ")");
|
||||
}
|
||||
|
||||
TEST_F(Expression, tokenizeOne)
|
||||
{
|
||||
auto result = App::ExpressionParser::tokenize("1");
|
||||
EXPECT_EQ(result.size(), 1);
|
||||
EXPECT_EQ(std::get<0>(result[0]), App::ExpressionParser::ONE);
|
||||
EXPECT_EQ(std::get<1>(result[0]), 0);
|
||||
EXPECT_EQ(std::get<2>(result[0]), "1");
|
||||
}
|
||||
|
||||
TEST_F(Expression, tokenizeNum)
|
||||
{
|
||||
auto result = App::ExpressionParser::tokenize("1.2341");
|
||||
EXPECT_EQ(result.size(), 1);
|
||||
EXPECT_EQ(std::get<0>(result[0]), App::ExpressionParser::NUM);
|
||||
EXPECT_EQ(std::get<1>(result[0]), 0);
|
||||
EXPECT_EQ(std::get<2>(result[0]), "1.2341");
|
||||
}
|
||||
|
||||
TEST_F(Expression, tokenizeID)
|
||||
{
|
||||
auto result = App::ExpressionParser::tokenize("Something");
|
||||
EXPECT_EQ(result.size(), 1);
|
||||
EXPECT_EQ(std::get<0>(result[0]), App::ExpressionParser::IDENTIFIER);
|
||||
EXPECT_EQ(std::get<1>(result[0]), 0);
|
||||
EXPECT_EQ(std::get<2>(result[0]), "Something");
|
||||
}
|
||||
|
||||
TEST_F(Expression, tokenizeUnit)
|
||||
{
|
||||
auto result = App::ExpressionParser::tokenize("km");
|
||||
EXPECT_EQ(result.size(), 1);
|
||||
EXPECT_EQ(std::get<0>(result[0]), App::ExpressionParser::UNIT);
|
||||
EXPECT_EQ(std::get<1>(result[0]), 0);
|
||||
EXPECT_EQ(std::get<2>(result[0]), "km");
|
||||
}
|
||||
|
||||
TEST_F(Expression, tokenizeUSUnit)
|
||||
{
|
||||
auto result = App::ExpressionParser::tokenize("\"");
|
||||
EXPECT_EQ(result.size(), 1);
|
||||
EXPECT_EQ(std::get<0>(result[0]), App::ExpressionParser::USUNIT);
|
||||
EXPECT_EQ(std::get<1>(result[0]), 0);
|
||||
EXPECT_EQ(std::get<2>(result[0]), "\"");
|
||||
}
|
||||
|
||||
TEST_F(Expression, tokenizeInt)
|
||||
{
|
||||
auto result = App::ExpressionParser::tokenize("123456");
|
||||
EXPECT_EQ(result.size(), 1);
|
||||
EXPECT_EQ(std::get<0>(result[0]), App::ExpressionParser::INTEGER);
|
||||
EXPECT_EQ(std::get<1>(result[0]), 0);
|
||||
EXPECT_EQ(std::get<2>(result[0]), "123456");
|
||||
}
|
||||
|
||||
TEST_F(Expression, tokenizePi)
|
||||
{
|
||||
auto result = App::ExpressionParser::tokenize("pi");
|
||||
EXPECT_EQ(result.size(), 1);
|
||||
EXPECT_EQ(std::get<0>(result[0]), App::ExpressionParser::CONSTANT);
|
||||
EXPECT_EQ(std::get<1>(result[0]), 0);
|
||||
EXPECT_EQ(std::get<2>(result[0]), "pi");
|
||||
}
|
||||
|
||||
TEST_F(Expression, tokenizeE)
|
||||
{
|
||||
auto result = App::ExpressionParser::tokenize("e");
|
||||
EXPECT_EQ(result.size(), 1);
|
||||
EXPECT_EQ(std::get<0>(result[0]), App::ExpressionParser::CONSTANT);
|
||||
EXPECT_EQ(std::get<1>(result[0]), 0);
|
||||
EXPECT_EQ(std::get<2>(result[0]), "e");
|
||||
}
|
||||
|
||||
TEST_F(Expression, tokenizeConstant)
|
||||
{
|
||||
auto result = App::ExpressionParser::tokenize("True False true false None");
|
||||
EXPECT_EQ(result.size(), 5);
|
||||
EXPECT_EQ(std::get<0>(result[0]), App::ExpressionParser::CONSTANT);
|
||||
EXPECT_EQ(std::get<1>(result[0]), 0);
|
||||
EXPECT_EQ(std::get<2>(result[0]), "True");
|
||||
EXPECT_EQ(std::get<0>(result[1]), App::ExpressionParser::CONSTANT);
|
||||
EXPECT_EQ(std::get<0>(result[2]), App::ExpressionParser::CONSTANT);
|
||||
EXPECT_EQ(std::get<0>(result[3]), App::ExpressionParser::CONSTANT);
|
||||
EXPECT_EQ(std::get<0>(result[4]), App::ExpressionParser::CONSTANT);
|
||||
}
|
||||
|
||||
TEST_F(Expression, tokenizeEqual)
|
||||
{
|
||||
auto result = App::ExpressionParser::tokenize("==");
|
||||
EXPECT_EQ(result.size(), 1);
|
||||
EXPECT_EQ(std::get<0>(result[0]), App::ExpressionParser::EQ);
|
||||
EXPECT_EQ(std::get<1>(result[0]), 0);
|
||||
EXPECT_EQ(std::get<2>(result[0]), "==");
|
||||
}
|
||||
|
||||
TEST_F(Expression, tokenizeNotEqual)
|
||||
{
|
||||
auto result = App::ExpressionParser::tokenize("!=");
|
||||
EXPECT_EQ(result.size(), 1);
|
||||
EXPECT_EQ(std::get<0>(result[0]), App::ExpressionParser::NEQ);
|
||||
EXPECT_EQ(std::get<1>(result[0]), 0);
|
||||
EXPECT_EQ(std::get<2>(result[0]), "!=");
|
||||
}
|
||||
|
||||
TEST_F(Expression, tokenizeLessThan)
|
||||
{
|
||||
auto result = App::ExpressionParser::tokenize("<");
|
||||
EXPECT_EQ(result.size(), 1);
|
||||
EXPECT_EQ(std::get<0>(result[0]), App::ExpressionParser::LT);
|
||||
EXPECT_EQ(std::get<1>(result[0]), 0);
|
||||
EXPECT_EQ(std::get<2>(result[0]), "<");
|
||||
}
|
||||
|
||||
TEST_F(Expression, tokenizeLessThanEqual)
|
||||
{
|
||||
auto result = App::ExpressionParser::tokenize("<=");
|
||||
EXPECT_EQ(result.size(), 1);
|
||||
EXPECT_EQ(std::get<0>(result[0]), App::ExpressionParser::LTE);
|
||||
EXPECT_EQ(std::get<1>(result[0]), 0);
|
||||
EXPECT_EQ(std::get<2>(result[0]), "<=");
|
||||
}
|
||||
|
||||
TEST_F(Expression, tokenizeGreaterThan)
|
||||
{
|
||||
auto result = App::ExpressionParser::tokenize(">");
|
||||
EXPECT_EQ(result.size(), 1);
|
||||
EXPECT_EQ(std::get<0>(result[0]), App::ExpressionParser::GT);
|
||||
EXPECT_EQ(std::get<1>(result[0]), 0);
|
||||
EXPECT_EQ(std::get<2>(result[0]), ">");
|
||||
}
|
||||
|
||||
TEST_F(Expression, tokenizeGreaterThanEqual)
|
||||
{
|
||||
auto result = App::ExpressionParser::tokenize(">=");
|
||||
EXPECT_EQ(result.size(), 1);
|
||||
EXPECT_EQ(std::get<0>(result[0]), App::ExpressionParser::GTE);
|
||||
EXPECT_EQ(std::get<1>(result[0]), 0);
|
||||
EXPECT_EQ(std::get<2>(result[0]), ">=");
|
||||
}
|
||||
|
||||
TEST_F(Expression, tokenizeMinus)
|
||||
{
|
||||
auto result = App::ExpressionParser::tokenize("1-1");
|
||||
EXPECT_EQ(result.size(), 3);
|
||||
EXPECT_EQ(std::get<0>(result[1]), App::ExpressionParser::MINUSSIGN);
|
||||
EXPECT_EQ(std::get<1>(result[1]), 1);
|
||||
EXPECT_EQ(std::get<2>(result[1]), "-");
|
||||
}
|
||||
|
||||
TEST_F(Expression, tokenizeCell1)
|
||||
{
|
||||
auto result = App::ExpressionParser::tokenize("$A$12");
|
||||
EXPECT_EQ(result.size(), 1);
|
||||
EXPECT_EQ(std::get<0>(result[0]), App::ExpressionParser::CELLADDRESS);
|
||||
EXPECT_EQ(std::get<1>(result[0]), 0);
|
||||
EXPECT_EQ(std::get<2>(result[0]), "$A$12");
|
||||
}
|
||||
|
||||
TEST_F(Expression, tokenizeCell2)
|
||||
{
|
||||
auto result = App::ExpressionParser::tokenize("A$12");
|
||||
EXPECT_EQ(result.size(), 1);
|
||||
EXPECT_EQ(std::get<0>(result[0]), App::ExpressionParser::CELLADDRESS);
|
||||
EXPECT_EQ(std::get<1>(result[0]), 0);
|
||||
EXPECT_EQ(std::get<2>(result[0]), "A$12");
|
||||
}
|
||||
|
||||
TEST_F(Expression, tokenizeCell3)
|
||||
{
|
||||
auto result = App::ExpressionParser::tokenize("$A12");
|
||||
EXPECT_EQ(result.size(), 1);
|
||||
EXPECT_EQ(std::get<0>(result[0]), App::ExpressionParser::CELLADDRESS);
|
||||
EXPECT_EQ(std::get<1>(result[0]), 0);
|
||||
EXPECT_EQ(std::get<2>(result[0]), "$A12");
|
||||
}
|
||||
|
||||
TEST_F(Expression, tokenizeString)
|
||||
{
|
||||
auto result = App::ExpressionParser::tokenize("<<Test>>");
|
||||
EXPECT_EQ(result.size(), 1);
|
||||
EXPECT_EQ(std::get<0>(result[0]), App::ExpressionParser::STRING);
|
||||
EXPECT_EQ(std::get<1>(result[0]), 0);
|
||||
EXPECT_EQ(std::get<2>(result[0]), "<<Test>>");
|
||||
}
|
||||
|
||||
TEST_F(Expression, tokenizeExponent)
|
||||
{
|
||||
// TODO
|
||||
}
|
||||
|
||||
TEST_F(Expression, tokenizeNumAndUnit)
|
||||
{
|
||||
// TODO
|
||||
}
|
||||
|
||||
TEST_F(Expression, tokenizePos)
|
||||
{
|
||||
// TODO
|
||||
}
|
||||
|
||||
TEST_F(Expression, tokenizeNeg)
|
||||
{
|
||||
// TODO
|
||||
}
|
||||
|
||||
TEST_F(Expression, tokenizePi_rad)
|
||||
{
|
||||
EXPECT_EQ(App::ExpressionTokenizer().perform(QStringLiteral("p"), 1), QStringLiteral("p"));
|
||||
EXPECT_EQ(App::ExpressionTokenizer().perform(QStringLiteral("pi"), 2), QString());
|
||||
EXPECT_EQ(App::ExpressionTokenizer().perform(QStringLiteral("pi "), 3), QString());
|
||||
EXPECT_EQ(App::ExpressionTokenizer().perform(QStringLiteral("pi r"), 4), QStringLiteral("r"));
|
||||
EXPECT_EQ(App::ExpressionTokenizer().perform(QStringLiteral("pi ra"), 5), QStringLiteral("ra"));
|
||||
EXPECT_EQ(App::ExpressionTokenizer().perform(QStringLiteral("pi rad"), 6), QStringLiteral("rad"));
|
||||
EXPECT_EQ(App::ExpressionTokenizer().perform(QStringLiteral("pi rad"), 2), QString());
|
||||
}
|
||||
|
||||
TEST_F(Expression, toString)
|
||||
{
|
||||
App::UnitExpression expr{nullptr, Base::Quantity{}, "pi rad"};
|
||||
EXPECT_EQ(expr.toString(), "pi rad");
|
||||
}
|
||||
|
||||
TEST_F(Expression, test_pi_rad)
|
||||
{
|
||||
auto constant = std::make_unique<App::ConstantExpression>(nullptr, "pi");
|
||||
auto unit = std::make_unique<App::UnitExpression>(nullptr, Base::Quantity{}, "rad");
|
||||
auto op = std::make_unique<App::OperatorExpression>(nullptr, constant.get(), App::OperatorExpression::UNIT, unit.get());
|
||||
EXPECT_EQ(op->toString(), "pi rad");
|
||||
op.release();
|
||||
}
|
||||
|
||||
TEST_F(Expression, test_e_rad)
|
||||
{
|
||||
auto constant = std::make_unique<App::ConstantExpression>(nullptr, "e");
|
||||
auto unit = std::make_unique<App::UnitExpression>(nullptr, Base::Quantity{}, "rad");
|
||||
auto op = std::make_unique<App::OperatorExpression>(nullptr, constant.get(), App::OperatorExpression::UNIT, unit.get());
|
||||
EXPECT_EQ(op->toString(), "e rad");
|
||||
op.release();
|
||||
}
|
||||
|
||||
class Evaluate: public ::testing::Test
|
||||
{
|
||||
protected:
|
||||
static void SetUpTestSuite()
|
||||
{
|
||||
tests::initApplication();
|
||||
}
|
||||
|
||||
void SetUp() override
|
||||
{
|
||||
_doc_name = App::GetApplication().getUniqueDocumentName("test");
|
||||
_this_doc = App::GetApplication().newDocument(_doc_name.c_str(), "testUser");
|
||||
_this_obj = _this_doc->addObject("App::VarSet");
|
||||
}
|
||||
|
||||
void TearDown() override
|
||||
{
|
||||
App::GetApplication().closeDocument(_doc_name.c_str());
|
||||
}
|
||||
|
||||
App::DocumentObject* this_obj() { return _this_obj; }
|
||||
|
||||
private:
|
||||
std::string _doc_name;
|
||||
App::Document* _this_doc {};
|
||||
App::DocumentObject* _this_obj {};
|
||||
};
|
||||
|
||||
// Various test for evaluating and simplifying expressions
|
||||
// Each "evaluate" test has an equivalent "simplify" test
|
||||
TEST_F(Evaluate, test_evaluate_simple)
|
||||
{
|
||||
App::ExpressionPtr e = App::ExpressionParser::parse(this_obj(), "1 + 2");
|
||||
App::ExpressionPtr evaluated = e->eval();
|
||||
EXPECT_EQ(e->toString(), "1 + 2");
|
||||
EXPECT_EQ(evaluated->toString(), "3");
|
||||
}
|
||||
|
||||
TEST_F(Evaluate, test_simplify_simple)
|
||||
{
|
||||
App::ExpressionPtr e = App::ExpressionParser::parse(this_obj(), "1 + 2");
|
||||
App::ExpressionPtr simplified = e->simplify();
|
||||
EXPECT_EQ(e->toString(), "1 + 2");
|
||||
EXPECT_EQ(simplified->toString(), "3");
|
||||
}
|
||||
|
||||
TEST_F(Evaluate, test_evaluate_function)
|
||||
{
|
||||
App::ExpressionPtr e = App::ExpressionParser::parse(this_obj(), "sqrt(4)");
|
||||
App::ExpressionPtr evaluated = e->eval();
|
||||
EXPECT_EQ(e->toString(), "sqrt(4)");
|
||||
EXPECT_EQ(evaluated->toString(), "2");
|
||||
}
|
||||
|
||||
TEST_F(Evaluate, test_simplify_function)
|
||||
{
|
||||
App::ExpressionPtr e = App::ExpressionParser::parse(this_obj(), "sqrt(4)");
|
||||
App::ExpressionPtr simplified = e->simplify();
|
||||
EXPECT_EQ(e->toString(), "sqrt(4)");
|
||||
EXPECT_EQ(simplified->toString(), "2");
|
||||
}
|
||||
|
||||
TEST_F(Evaluate, test_evaluate_refer_to_var)
|
||||
{
|
||||
auto* prop = freecad_cast<App::PropertyFloat*>(this_obj()->addDynamicProperty("App::PropertyFloat", "Var"));
|
||||
prop->setValue(2.0);
|
||||
App::ExpressionPtr e = App::ExpressionParser::parse(this_obj(), "sqrt(2 + Var)");
|
||||
App::ExpressionPtr evaluated = e->eval();
|
||||
EXPECT_EQ(e->toString(), "sqrt(2 + Var)");
|
||||
EXPECT_EQ(evaluated->toString(), "2");
|
||||
}
|
||||
|
||||
TEST_F(Evaluate, test_simplify_refer_to_var)
|
||||
{
|
||||
auto* prop = freecad_cast<App::PropertyFloat*>(this_obj()->addDynamicProperty("App::PropertyFloat", "Var"));
|
||||
prop->setValue(2.0);
|
||||
App::ExpressionPtr e = App::ExpressionParser::parse(this_obj(), "sqrt(2 + Var)");
|
||||
App::ExpressionPtr simplified = e->simplify();
|
||||
EXPECT_EQ(e->toString(), "sqrt(2 + Var)");
|
||||
EXPECT_EQ(simplified->toString(), "sqrt(2 + Var)");
|
||||
}
|
||||
// clang-format on
|
||||
330
tests/src/App/ExpressionParser.cpp
Normal file
330
tests/src/App/ExpressionParser.cpp
Normal file
@@ -0,0 +1,330 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
#include <gmock/gmock.h>
|
||||
|
||||
#include "Base/Quantity.h"
|
||||
|
||||
#include "App/Application.h"
|
||||
#include "App/Document.h"
|
||||
#include "App/DocumentObject.h"
|
||||
#include "App/Expression.h"
|
||||
#include "App/ExpressionParser.h"
|
||||
|
||||
#include "src/App/InitApplication.h"
|
||||
|
||||
using namespace testing;
|
||||
|
||||
// the following two PrintTo functions are optional but provide for *much*
|
||||
// nicer error messages and make debugging test failures much easier
|
||||
namespace Base
|
||||
{
|
||||
void PrintTo(const Quantity& qty, std::ostream* os)
|
||||
{
|
||||
*os << qty.toString(QuantityFormat(QuantityFormat::NumberFormat::Fixed));
|
||||
}
|
||||
} // namespace Base
|
||||
|
||||
namespace boost
|
||||
{
|
||||
void PrintTo(const boost::any& e, std::ostream* os)
|
||||
{
|
||||
*os << "any (";
|
||||
if (e.type() == typeid(Base::Quantity)) {
|
||||
const auto& qty = App::any_cast<const Base::Quantity>(e);
|
||||
*os << "Quantity=";
|
||||
PrintTo(qty, os);
|
||||
}
|
||||
else if (e.type() == typeid(double)) {
|
||||
*os << "double=" << App::any_cast<const double>(e);
|
||||
}
|
||||
else if (e.type() == typeid(long)) {
|
||||
*os << "long=" << App::any_cast<const long>(e);
|
||||
}
|
||||
else if (e.type() == typeid(std::string)) {
|
||||
*os << "string=\"" << App::any_cast<const std::string>(e) << "\"";
|
||||
}
|
||||
else if (e.type() == typeid(Base::ParserError)) {
|
||||
const auto& err = App::any_cast<const Base::ParserError>(e);
|
||||
*os << "ParserError=\"" << err.what() << "\"";
|
||||
}
|
||||
else {
|
||||
*os << "unknown type=" << e.type().name();
|
||||
}
|
||||
*os << ")";
|
||||
}
|
||||
} // namespace boost
|
||||
|
||||
namespace App::ExpressionParser::Test
|
||||
{
|
||||
|
||||
class ExpressionParserTest: public ::testing::Test
|
||||
{
|
||||
protected:
|
||||
static void SetUpTestSuite()
|
||||
{
|
||||
tests::initApplication();
|
||||
}
|
||||
|
||||
void SetUp() override
|
||||
{
|
||||
docName = App::GetApplication().getUniqueDocumentName("test");
|
||||
thisDoc = App::GetApplication().newDocument(docName.c_str(), "testUser");
|
||||
thisObj = thisDoc->addObject("Sketcher::SketchObject", "Sketch");
|
||||
}
|
||||
|
||||
void TearDown() override
|
||||
{
|
||||
App::GetApplication().closeDocument(docName.c_str());
|
||||
}
|
||||
|
||||
// clang-format off
|
||||
std::string doc_name() { return docName; }
|
||||
App::Document* this_doc() { return thisDoc; }
|
||||
App::DocumentObject* this_obj() { return thisObj; }
|
||||
// clang-format on
|
||||
|
||||
Base::Quantity parse_expression_text_as_quantity(const char* expression_text)
|
||||
{
|
||||
const auto expression = parse(thisObj, expression_text);
|
||||
return App::any_cast<Base::Quantity>(expression->getValueAsAny());
|
||||
}
|
||||
|
||||
Base::Quantity parse_quantity_text_as_quantity(const char* quantity_text)
|
||||
{
|
||||
return Base::Quantity::parse(quantity_text);
|
||||
}
|
||||
|
||||
boost::any parseExpr(const char* text)
|
||||
{
|
||||
try {
|
||||
const auto expression = parse(thisObj, text);
|
||||
ExpressionPtr simplified = expression->simplify();
|
||||
return simplified->getValueAsAny();
|
||||
}
|
||||
catch (const Base::ParserError& e) {
|
||||
return e;
|
||||
}
|
||||
catch (const Expression::Exception& e) {
|
||||
return e;
|
||||
}
|
||||
catch (const Base::ExpressionError& e) {
|
||||
return e;
|
||||
}
|
||||
catch (const Base::RuntimeError& e) {
|
||||
return e;
|
||||
}
|
||||
catch (const Base::Exception& e) {
|
||||
// provide a much friendlier error message before failing
|
||||
EXPECT_TRUE(false) << "Unexpected Base::Exception when parsing \"" << text
|
||||
<< "\": " << e.what();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
std::string docName;
|
||||
App::Document* thisDoc {};
|
||||
App::DocumentObject* thisObj {};
|
||||
};
|
||||
|
||||
// clang-format off
|
||||
static constexpr auto IsQuantity = [](auto m) { return AnyWith<Base::Quantity>(m); };
|
||||
static constexpr auto IsDouble = [](auto m) { return AnyWith<double>(m); };
|
||||
static constexpr auto IsLong = [](auto m) { return AnyWith<long>(m); };
|
||||
static constexpr auto IsString = [](auto m) { return AnyWith<std::string>(m); };
|
||||
static constexpr auto IsParserError = [](auto m) { return AnyWith<Base::ParserError>(m); };
|
||||
static constexpr auto IsRuntimeError = [](auto m) { return AnyWith<Base::RuntimeError>(m); };
|
||||
static constexpr auto IsExpressionException = [](auto m) { return AnyWith<Expression::Exception>(m); };
|
||||
static constexpr auto IsExpressionError = [](auto m) { return AnyWith<Base::ExpressionError>(m); };
|
||||
static Base::Quantity mm3(double val) { return Base::Quantity(val, Base::Unit::Volume); }
|
||||
static Base::Quantity mm2(double val) { return Base::Quantity(val, Base::Unit::Area); }
|
||||
static Base::Quantity mm(double val) { return Base::Quantity(val, Base::Unit::Length); }
|
||||
// clang-format on
|
||||
|
||||
// https://github.com/FreeCAD/FreeCAD/issues/11965
|
||||
TEST_F(ExpressionParserTest, functionPARSEQUANT)
|
||||
{
|
||||
// clang-format off
|
||||
EXPECT_ANY_THROW(App::ExpressionParser::parse(this_obj(), "parsequant()")) << "should not parse empty";
|
||||
|
||||
EXPECT_NO_THROW(App::ExpressionParser::parse(this_obj(), "parsequant(1 mm)")) << "should parse simple quantity";
|
||||
EXPECT_NO_THROW(App::ExpressionParser::parse(this_obj(), "parsequant(<<(1 + 2) m>>)")) << "should parse literal quantity";
|
||||
EXPECT_NO_THROW(App::ExpressionParser::parse(this_obj(), "parsequant(str(1 m + 2 mm))")) << "should parse str-function quantity";
|
||||
|
||||
EXPECT_ANY_THROW(parse_quantity_text_as_quantity("parsequant(1 mm)")) << "should not treat parsequant-function as quantity";
|
||||
EXPECT_EQ(parse_quantity_text_as_quantity("1 mm"), parse_quantity_text_as_quantity("1 mm")) << "equality sanity check";
|
||||
EXPECT_NE(parse_quantity_text_as_quantity("1 mm"), parse_quantity_text_as_quantity("2 mm")) << "inequality sanity check";
|
||||
|
||||
std::initializer_list<std::pair<const char*,const char*>> expression_vs_quantity_list = {
|
||||
// length
|
||||
{ "1 mm", "1 mm" },
|
||||
{ "parsequant(1 mm)", "1 mm" },
|
||||
{ "parsequant(<<(1 + 2) m>>)", "3000 mm" },
|
||||
{ "parsequant(str(1 m + 2 mm))", "1002 mm"},
|
||||
// angle
|
||||
{ "10 deg", "10 deg" },
|
||||
{ "parsequant(10 deg)", "10 deg" },
|
||||
{ "parsequant(<<(10 + 20) deg>>)", "30 deg" },
|
||||
{ "parsequant(str(10 deg + 20 deg))", "30 deg" },
|
||||
// mass
|
||||
{ "10 g", "10 g" },
|
||||
{ "parsequant(10 g)", "10 g" },
|
||||
{ "parsequant(<<(10 + 20) kg>>)", "30000 g" },
|
||||
{ "parsequant(str(10 kg + 20010 g))", "30.01 kg" },
|
||||
};
|
||||
|
||||
for (const auto& [expression_text, quantity_text] : expression_vs_quantity_list) {
|
||||
auto expression_result = parse_expression_text_as_quantity(expression_text);
|
||||
auto quantity_result = parse_quantity_text_as_quantity(quantity_text);
|
||||
|
||||
EXPECT_EQ(expression_result, quantity_result) << "mismatch:"
|
||||
" expression_text='" + std::string(expression_text) + "'"
|
||||
" quantity_text='" + std::string(quantity_text) + "'"
|
||||
" expression_representation='" + expression_result.getUserString() + "'"
|
||||
" quantity_representation='" + quantity_result.getUserString() + "'"
|
||||
;
|
||||
}
|
||||
// clang-format on
|
||||
}
|
||||
|
||||
TEST_F(ExpressionParserTest, isTokenAConstant)
|
||||
{
|
||||
for (const auto& constant : {"pi", "e", "True", "False", "true", "false", "None"}) {
|
||||
EXPECT_TRUE(isTokenAConstant(constant))
|
||||
<< "\"" << constant << "\" did not evaluate as a constant";
|
||||
}
|
||||
|
||||
for (const auto& nonConstant : {"PI", "E", "TRUE", "FALSE", "NONE", "none"}) {
|
||||
EXPECT_FALSE(isTokenAConstant(nonConstant))
|
||||
<< "\"" << nonConstant << "\" evaluated as a constant";
|
||||
}
|
||||
}
|
||||
|
||||
TEST_F(ExpressionParserTest, simpleExpressionsParse)
|
||||
{
|
||||
static constexpr auto IsMm = [](auto m) {
|
||||
return IsQuantity(mm(m));
|
||||
};
|
||||
|
||||
EXPECT_THAT(parseExpr("0 mm"), IsMm(0));
|
||||
EXPECT_THAT(parseExpr("-5 mm"), IsMm(-5)) << "leading minus sign";
|
||||
EXPECT_THAT(parseExpr("+5 mm"), IsMm(5)) << "leading plus sign";
|
||||
EXPECT_THAT(parseExpr("1.25 mm"), IsMm(1.25)) << "decimal";
|
||||
EXPECT_THAT(parseExpr("1.0e3 mm"), IsMm(1000)) << "scientific notation";
|
||||
EXPECT_THAT(parseExpr("1mm + 1mm"), IsMm(2)) << "adding same units";
|
||||
EXPECT_THAT(parseExpr("5mm +- 1mm"), IsMm(4))
|
||||
<< "adding same units with poorly separate negation sign";
|
||||
EXPECT_THAT(parseExpr("1mm * 3"), IsMm(3)) << "multiplying units by factor";
|
||||
EXPECT_THAT(parseExpr("1 m"), IsMm(1000)) << "different units";
|
||||
EXPECT_THAT(parseExpr("1 m + 25 mm"), IsMm(1025)) << "addition with unit conversion";
|
||||
EXPECT_THAT(parseExpr("(5mm + 1cm) / 3"), IsMm(5))
|
||||
<< "parenthesised arithmetic with different units";
|
||||
|
||||
EXPECT_THAT(parseExpr("10 deg"), IsQuantity(Base::Quantity(10, Base::Unit::Angle)))
|
||||
<< "angle literal";
|
||||
EXPECT_THAT(parseExpr("360 deg + pi rad"), IsQuantity(Base::Quantity(540, Base::Unit::Angle)))
|
||||
<< "mixed angle units";
|
||||
|
||||
EXPECT_THAT(parseExpr("True mm"), IsQuantity(mm(1))) << "boolean constant treated as scalar";
|
||||
}
|
||||
|
||||
TEST_F(ExpressionParserTest, badExpressionsDoNotParse)
|
||||
{
|
||||
EXPECT_THAT(parseExpr("mm"), IsExpressionException(_))
|
||||
<< "only units - cannot evaludate to a value";
|
||||
EXPECT_THAT(parseExpr("-"), IsParserError(_)) << "only operator";
|
||||
EXPECT_THAT(parseExpr("10 bogusunits"), IsParserError(_));
|
||||
EXPECT_THAT(parseExpr("1.25 mm kg"), IsParserError(_)) << "units separated by space";
|
||||
EXPECT_THAT(parseExpr("*1"), IsParserError(_)) << "operator then unit";
|
||||
EXPECT_THAT(parseExpr("sqrt"), IsRuntimeError(_))
|
||||
<< "function without arguments fails ObjectIdentifier resolution";
|
||||
EXPECT_THAT(parseExpr("sqrt()"), IsParserError(_)) << "function with empty arguments";
|
||||
EXPECT_THAT(parseExpr("sqrt(1, 2)"), IsExpressionError(_))
|
||||
<< "function with too many arguments";
|
||||
}
|
||||
|
||||
TEST_F(ExpressionParserTest, expressionsWithMultiplyDivideParse)
|
||||
{
|
||||
EXPECT_THAT(parseExpr("1 mm * 2 cm"), IsQuantity(mm2(20))) << "mixed-unit multiplication";
|
||||
EXPECT_THAT(parseExpr("2 cm * 1 mm"), IsQuantity(mm2(20))) << "multiplication commutativity";
|
||||
EXPECT_THAT(parseExpr("(1 m - 750 mm) * 3"), IsQuantity(mm(750)))
|
||||
<< "binary arithmetic surrounded by another operator";
|
||||
EXPECT_THAT(parseExpr("(5 mm)^2"), IsQuantity(mm2(25)))
|
||||
<< "power operator applied to parenthesised unit";
|
||||
EXPECT_THAT(
|
||||
parseExpr("24 V / (2 A)"),
|
||||
IsQuantity(Base::Quantity(12'000'000, Base::Unit::ElectricalResistance))
|
||||
) << "division of electrical quantities";
|
||||
}
|
||||
|
||||
TEST_F(ExpressionParserTest, expressionsWithUnitsMultipliedDontParse_LikelyBug)
|
||||
{
|
||||
// https://github.com/FreeCAD/FreeCAD/issues/14471
|
||||
// https://github.com/FreeCAD/FreeCAD/issues/26470
|
||||
EXPECT_THAT(parseExpr("10 mm * kg"), IsParserError(_));
|
||||
EXPECT_THAT(parseExpr("1234000.00 mm*kg/s^2"), IsParserError(_));
|
||||
}
|
||||
|
||||
TEST_F(ExpressionParserTest, dimensionlessExpressionsParseAsLongOrDouble)
|
||||
{
|
||||
EXPECT_THAT(parseExpr("0"), IsLong(0)) << "bare zero parses as long";
|
||||
EXPECT_THAT(parseExpr("1 / 2"), IsDouble(0.5)) << "simple fraction parses as double";
|
||||
EXPECT_THAT(parseExpr("40 mm / (2 cm)"), IsLong(2.0))
|
||||
<< "dimensionless ratio of like units parses as long";
|
||||
}
|
||||
|
||||
TEST_F(ExpressionParserTest, expressionsWithFunctionsParse)
|
||||
{
|
||||
EXPECT_THAT(parseExpr("sqrt(9 mm^2)"), IsQuantity(mm(3)))
|
||||
<< "function invocation with unit exponent";
|
||||
EXPECT_THAT(parseExpr("pow(2 mm, 3)"), IsQuantity(mm3(8)))
|
||||
<< "power function returning a cubic unit";
|
||||
EXPECT_THAT(parseExpr("sum(1 mm, 2 mm, 3 mm)"), IsQuantity(mm(6)))
|
||||
<< "aggregate function operating on quantities";
|
||||
EXPECT_THAT(parseExpr("list(1 mm, 2 mm)[0]"), IsParserError(_))
|
||||
<< "indexing into list-valued expression";
|
||||
EXPECT_THAT(parseExpr("<<(Line 1\\nLine 2)>>"), IsString("(Line 1\nLine 2)"))
|
||||
<< "multiline literal string";
|
||||
EXPECT_THAT(parseExpr("atan2(1 mm, 1 mm)"), IsQuantity(Base::Quantity(45, Base::Unit::Angle)))
|
||||
<< "trigonometric helper";
|
||||
}
|
||||
|
||||
TEST_F(ExpressionParserTest, DISABLED_expressionsParseAsPyObjectWrapper)
|
||||
{
|
||||
// PyObjectWrapper is internal to Expression.cpp, so we can't test for it
|
||||
// directly, even though some expressions return this
|
||||
// I've left this test here to document this fact, and as a way to ask for
|
||||
// help during code review on why this type exists / why it is private
|
||||
// The below all parse as PyObjectWrapper currently
|
||||
EXPECT_THAT(parseExpr("vector(1 mm, 2 mm, 3 mm)"), Not(IsParserError(_)))
|
||||
<< "vector-valued expression of lengths";
|
||||
EXPECT_THAT(parseExpr("vector(1, 0, 0) * 5 mm"), Not(IsParserError(_)))
|
||||
<< "mixed dimensionless and dimensional operands";
|
||||
}
|
||||
|
||||
TEST_F(ExpressionParserTest, expressionsThatLookValidButDoNotParse)
|
||||
{
|
||||
// Documenting current behaviour
|
||||
// Note, for some/all of these, it's not clear to me whether it's intended that
|
||||
// it doesn't parse
|
||||
EXPECT_THAT(parseExpr("pow(2, 3) * mm^3"), IsParserError(_))
|
||||
<< "combining dimensionless math with explicit units";
|
||||
EXPECT_THAT(parseExpr("(vector(1 mm,2 mm,3 mm)[0]) * 2"), IsParserError(_))
|
||||
<< "extract component before arithmetic";
|
||||
}
|
||||
|
||||
TEST_F(ExpressionParserTest, canParseProperties)
|
||||
{
|
||||
EXPECT_THAT(parseExpr("Placement.Base.x"), IsQuantity(mm(0)))
|
||||
<< "self-reference to owning object's placement";
|
||||
|
||||
this_obj()->addDynamicProperty("App::PropertyFloat", "Foo");
|
||||
EXPECT_THAT(parseExpr("Sketch.Foo"), IsDouble(0)) << "Property on object";
|
||||
|
||||
this_obj()->addDynamicProperty("App::PropertyQuantity", "Bar");
|
||||
EXPECT_THAT(parseExpr("Sketch.Bar"), IsQuantity(Base::Quantity()))
|
||||
<< "PropertyQuantity on object";
|
||||
}
|
||||
|
||||
} // namespace App::ExpressionParser::Test
|
||||
604
tests/src/App/IndexedName.cpp
Normal file
604
tests/src/App/IndexedName.cpp
Normal file
@@ -0,0 +1,604 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include "App/IndexedName.h"
|
||||
|
||||
#include <sstream>
|
||||
|
||||
// NOLINTBEGIN(readability-magic-numbers)
|
||||
|
||||
class IndexedNameTest: public ::testing::Test
|
||||
{
|
||||
protected:
|
||||
// void SetUp() override {}
|
||||
|
||||
// void TearDown() override {}
|
||||
|
||||
// Create and return a list of invalid IndexedNames
|
||||
static std::vector<Data::IndexedName> givenInvalidIndexedNames()
|
||||
{
|
||||
return std::vector<Data::IndexedName> {
|
||||
Data::IndexedName(),
|
||||
Data::IndexedName("", 1),
|
||||
Data::IndexedName("INVALID42NAME", 1),
|
||||
Data::IndexedName(".EDGE", 1)
|
||||
};
|
||||
}
|
||||
|
||||
// Create and return a list of valid IndexedNames
|
||||
static std::vector<Data::IndexedName> givenValidIndexedNames()
|
||||
{
|
||||
return std::vector<Data::IndexedName> {
|
||||
Data::IndexedName("NAME"),
|
||||
Data::IndexedName("NAME1"),
|
||||
Data::IndexedName("NAME", 1),
|
||||
Data::IndexedName("NAME_WITH_UNDERSCORES12345")
|
||||
};
|
||||
}
|
||||
|
||||
// An arbitrary list of C strings used for testing some types of construction
|
||||
// NOLINTNEXTLINE cppcoreguidelines-non-private-member-variables-in-classes
|
||||
std::vector<const char*> allowedTypes {"VERTEX", "EDGE", "FACE", "WIRE"};
|
||||
};
|
||||
|
||||
TEST_F(IndexedNameTest, defaultConstruction)
|
||||
{
|
||||
// Act
|
||||
auto indexedName = Data::IndexedName();
|
||||
|
||||
// Assert
|
||||
EXPECT_STREQ(indexedName.getType(), "");
|
||||
EXPECT_EQ(indexedName.getIndex(), 0);
|
||||
}
|
||||
|
||||
TEST_F(IndexedNameTest, nameOnlyConstruction)
|
||||
{
|
||||
// Act
|
||||
auto indexedName = Data::IndexedName("TestName");
|
||||
|
||||
// Assert
|
||||
EXPECT_STREQ(indexedName.getType(), "TestName");
|
||||
EXPECT_EQ(indexedName.getIndex(), 0);
|
||||
}
|
||||
|
||||
TEST_F(IndexedNameTest, nameAndIndexConstruction)
|
||||
{
|
||||
// Arrange
|
||||
const int testIndex {42};
|
||||
|
||||
// Act
|
||||
auto indexedName = Data::IndexedName("TestName", testIndex);
|
||||
|
||||
// Assert
|
||||
EXPECT_STREQ(indexedName.getType(), "TestName");
|
||||
EXPECT_EQ(indexedName.getIndex(), testIndex);
|
||||
}
|
||||
|
||||
TEST_F(IndexedNameTest, nameAndIndexConstructionWithOverride)
|
||||
{
|
||||
// Arrange
|
||||
const int testIndex {42};
|
||||
|
||||
// Act
|
||||
auto indexedName = Data::IndexedName("TestName17", testIndex);
|
||||
|
||||
// Assert
|
||||
EXPECT_STREQ(indexedName.getType(), "TestName");
|
||||
EXPECT_EQ(indexedName.getIndex(), testIndex);
|
||||
}
|
||||
|
||||
// Names must only contain ASCII letters and underscores (but may end with a number)
|
||||
TEST_F(IndexedNameTest, constructionInvalidCharInName)
|
||||
{
|
||||
// Arrange
|
||||
constexpr int lastASCIICode {127};
|
||||
std::vector<char> illegalCharacters = {};
|
||||
for (int code = 1; code <= lastASCIICode; ++code) {
|
||||
if ((std::isalnum(code) == 0) && code != '_') {
|
||||
illegalCharacters.push_back(char(code));
|
||||
}
|
||||
}
|
||||
for (auto illegalChar : illegalCharacters) {
|
||||
std::string testName {"TestName"};
|
||||
testName += illegalChar;
|
||||
|
||||
// Act
|
||||
auto indexedName = Data::IndexedName(testName.c_str(), 1);
|
||||
|
||||
// Assert
|
||||
EXPECT_STREQ(indexedName.getType(), "") << "Expected empty name when given " << testName;
|
||||
}
|
||||
}
|
||||
|
||||
// Names must not contain numbers in the middle:
|
||||
TEST_F(IndexedNameTest, constructionNumberInName)
|
||||
{
|
||||
// Arrange
|
||||
const int testIndex {42};
|
||||
std::string testName;
|
||||
testName += "Test" + std::to_string(testIndex) + "Name";
|
||||
|
||||
// Act
|
||||
auto indexedName = Data::IndexedName(testName.c_str(), testIndex);
|
||||
|
||||
// Assert
|
||||
EXPECT_STREQ(indexedName.getType(), "");
|
||||
}
|
||||
|
||||
TEST_F(IndexedNameTest, nameAndTypeListConstructionWithoutAllowOthers)
|
||||
{
|
||||
// Act
|
||||
auto indexedName = Data::IndexedName("EDGE19", allowedTypes, false);
|
||||
|
||||
// Assert
|
||||
EXPECT_STREQ(indexedName.getType(), "EDGE");
|
||||
EXPECT_EQ(indexedName.getIndex(), 19);
|
||||
|
||||
// Act
|
||||
indexedName = Data::IndexedName("EDGES_ARE_REALLY_GREAT19", allowedTypes, false);
|
||||
|
||||
// Assert
|
||||
EXPECT_STREQ(indexedName.getType(), "");
|
||||
EXPECT_EQ(indexedName.getIndex(), 19);
|
||||
|
||||
// Act
|
||||
indexedName = Data::IndexedName("NOT_IN_THE_LIST42", allowedTypes, false);
|
||||
|
||||
// Assert
|
||||
EXPECT_STREQ(indexedName.getType(), "");
|
||||
}
|
||||
|
||||
TEST_F(IndexedNameTest, nameAndTypeListConstructionWithAllowOthers)
|
||||
{
|
||||
// Act
|
||||
auto indexedName = Data::IndexedName("NOT_IN_THE_LIST42", allowedTypes, true);
|
||||
|
||||
// Assert
|
||||
EXPECT_STREQ(indexedName.getType(), "NOT_IN_THE_LIST");
|
||||
EXPECT_EQ(indexedName.getIndex(), 42);
|
||||
}
|
||||
|
||||
// Check that the same memory location is used for two names that are not in the allowedTypes list
|
||||
TEST_F(IndexedNameTest, nameAndTypeListConstructionReusedMemoryCheck)
|
||||
{
|
||||
// Arrange
|
||||
auto indexedName1 = Data::IndexedName("NOT_IN_THE_LIST42", allowedTypes, true);
|
||||
auto indexedName2 = Data::IndexedName("NOT_IN_THE_LIST43", allowedTypes, true);
|
||||
|
||||
// Act & Assert
|
||||
EXPECT_EQ(indexedName1.getType(), indexedName2.getType());
|
||||
}
|
||||
|
||||
TEST_F(IndexedNameTest, byteArrayConstruction)
|
||||
{
|
||||
// Arrange
|
||||
QByteArray qba {"EDGE42"};
|
||||
|
||||
// Act
|
||||
auto indexedName = Data::IndexedName(qba);
|
||||
|
||||
// Assert
|
||||
EXPECT_STREQ(indexedName.getType(), "EDGE");
|
||||
EXPECT_EQ(indexedName.getIndex(), 42);
|
||||
}
|
||||
|
||||
TEST_F(IndexedNameTest, copyConstruction)
|
||||
{
|
||||
// Arrange
|
||||
auto indexedName = Data::IndexedName("EDGE42");
|
||||
|
||||
// Act
|
||||
auto indexedNameCopy {indexedName};
|
||||
|
||||
// Assert
|
||||
EXPECT_EQ(indexedName, indexedNameCopy);
|
||||
}
|
||||
|
||||
TEST_F(IndexedNameTest, streamInsertionOperator)
|
||||
{
|
||||
// Arrange
|
||||
auto indexedName = Data::IndexedName("EDGE42");
|
||||
std::stringstream ss;
|
||||
|
||||
// Act
|
||||
ss << indexedName;
|
||||
|
||||
// Assert
|
||||
EXPECT_EQ(ss.str(), std::string {"EDGE42"});
|
||||
}
|
||||
|
||||
TEST_F(IndexedNameTest, compoundAssignmentOperator)
|
||||
{
|
||||
// NOTE: Only += is defined for this class
|
||||
|
||||
// Arrange
|
||||
constexpr int base {42};
|
||||
constexpr int offset {10};
|
||||
auto indexedName = Data::IndexedName("EDGE", base);
|
||||
|
||||
// Act
|
||||
indexedName += offset;
|
||||
|
||||
// Assert
|
||||
EXPECT_EQ(indexedName.getIndex(), 52);
|
||||
}
|
||||
|
||||
TEST_F(IndexedNameTest, preincrementOperator)
|
||||
{
|
||||
// Arrange
|
||||
auto indexedName = Data::IndexedName("EDGE42");
|
||||
|
||||
// Act
|
||||
++indexedName;
|
||||
|
||||
// Assert
|
||||
EXPECT_EQ(indexedName.getIndex(), 43);
|
||||
}
|
||||
|
||||
TEST_F(IndexedNameTest, predecrementOperator)
|
||||
{
|
||||
// Arrange
|
||||
auto indexedName = Data::IndexedName("EDGE42");
|
||||
|
||||
// Act
|
||||
--indexedName;
|
||||
|
||||
// Assert
|
||||
EXPECT_EQ(indexedName.getIndex(), 41);
|
||||
}
|
||||
|
||||
TEST_F(IndexedNameTest, comparisonOperators)
|
||||
{
|
||||
// Arrange
|
||||
auto indexedName1 = Data::IndexedName("EDGE42");
|
||||
auto indexedName2 = Data::IndexedName("EDGE42");
|
||||
|
||||
// Act & Assert
|
||||
EXPECT_EQ(indexedName1.compare(indexedName2), 0);
|
||||
EXPECT_TRUE(indexedName1 == indexedName2);
|
||||
EXPECT_FALSE(indexedName1 != indexedName2);
|
||||
EXPECT_FALSE(indexedName1 < indexedName2);
|
||||
|
||||
// Arrange
|
||||
auto indexedName3 = Data::IndexedName("EDGE42");
|
||||
auto indexedName4 = Data::IndexedName("FACE42");
|
||||
|
||||
// Act & Assert
|
||||
EXPECT_LT(indexedName3.compare(indexedName4), 0);
|
||||
EXPECT_FALSE(indexedName3 == indexedName4);
|
||||
EXPECT_TRUE(indexedName3 != indexedName4);
|
||||
EXPECT_TRUE(indexedName3 < indexedName4);
|
||||
|
||||
// Arrange
|
||||
auto indexedName5 = Data::IndexedName("FACE42");
|
||||
auto indexedName6 = Data::IndexedName("EDGE42");
|
||||
|
||||
// Act & Assert
|
||||
EXPECT_GT(indexedName5.compare(indexedName6), 0);
|
||||
EXPECT_FALSE(indexedName5 == indexedName6);
|
||||
EXPECT_TRUE(indexedName5 != indexedName6);
|
||||
EXPECT_FALSE(indexedName5 < indexedName6);
|
||||
|
||||
// Arrange
|
||||
auto indexedName7 = Data::IndexedName("EDGE41");
|
||||
auto indexedName8 = Data::IndexedName("EDGE42");
|
||||
|
||||
// Act & Assert
|
||||
EXPECT_LT(indexedName7.compare(indexedName8), 0);
|
||||
EXPECT_FALSE(indexedName7 == indexedName8);
|
||||
EXPECT_TRUE(indexedName7 != indexedName8);
|
||||
EXPECT_TRUE(indexedName7 < indexedName8);
|
||||
|
||||
// Arrange
|
||||
auto indexedName9 = Data::IndexedName("EDGE43");
|
||||
auto indexedName10 = Data::IndexedName("EDGE42");
|
||||
|
||||
// Act & Assert
|
||||
EXPECT_GT(indexedName9.compare(indexedName10), 0);
|
||||
EXPECT_FALSE(indexedName9 == indexedName10);
|
||||
EXPECT_TRUE(indexedName9 != indexedName10);
|
||||
EXPECT_FALSE(indexedName9 < indexedName10);
|
||||
|
||||
// Arrange
|
||||
auto indexedName11 = Data::IndexedName("EDGE2");
|
||||
auto indexedName12 = Data::IndexedName("EDGE12");
|
||||
|
||||
// Act & Assert
|
||||
EXPECT_LT(indexedName11.compare(indexedName12), 0);
|
||||
EXPECT_FALSE(indexedName11 == indexedName12);
|
||||
EXPECT_TRUE(indexedName11 != indexedName12);
|
||||
EXPECT_TRUE(indexedName11 < indexedName12);
|
||||
}
|
||||
|
||||
TEST_F(IndexedNameTest, subscriptOperator)
|
||||
{
|
||||
// Arrange
|
||||
auto indexedName = Data::IndexedName("EDGE42");
|
||||
|
||||
// Act & Assert
|
||||
EXPECT_EQ(indexedName[0], 'E');
|
||||
EXPECT_EQ(indexedName[1], 'D');
|
||||
EXPECT_EQ(indexedName[2], 'G');
|
||||
EXPECT_EQ(indexedName[3], 'E');
|
||||
}
|
||||
|
||||
TEST_F(IndexedNameTest, getType)
|
||||
{
|
||||
// Arrange
|
||||
auto indexedName = Data::IndexedName("EDGE42");
|
||||
|
||||
// Act & Assert
|
||||
EXPECT_STREQ(indexedName.getType(), "EDGE");
|
||||
}
|
||||
|
||||
TEST_F(IndexedNameTest, setIndex)
|
||||
{
|
||||
// Arrange
|
||||
auto indexedName = Data::IndexedName("EDGE42");
|
||||
EXPECT_EQ(indexedName.getIndex(), 42);
|
||||
|
||||
// Act
|
||||
indexedName.setIndex(1);
|
||||
|
||||
// Assert
|
||||
EXPECT_EQ(indexedName.getIndex(), 1);
|
||||
}
|
||||
|
||||
TEST_F(IndexedNameTest, isNullTrue)
|
||||
{
|
||||
// Arrange
|
||||
auto invalidNames = givenInvalidIndexedNames();
|
||||
for (const auto& name : invalidNames) {
|
||||
|
||||
// Act & Assert
|
||||
EXPECT_TRUE(name.isNull());
|
||||
}
|
||||
}
|
||||
|
||||
TEST_F(IndexedNameTest, isNullFalse)
|
||||
{
|
||||
// Arrange
|
||||
auto validNames = givenValidIndexedNames();
|
||||
for (const auto& name : validNames) {
|
||||
|
||||
// Act & Assert
|
||||
EXPECT_FALSE(name.isNull());
|
||||
}
|
||||
}
|
||||
|
||||
TEST_F(IndexedNameTest, booleanConversionFalse)
|
||||
{
|
||||
// Arrange
|
||||
auto invalidNames = givenInvalidIndexedNames();
|
||||
for (const auto& name : invalidNames) {
|
||||
|
||||
// Act & Assert
|
||||
EXPECT_FALSE(static_cast<bool>(name));
|
||||
}
|
||||
|
||||
// Usage example:
|
||||
auto indexedName = Data::IndexedName(".EDGE", 1); // Invalid name
|
||||
if (indexedName) {
|
||||
FAIL() << "indexedName as a boolean should have been false for an invalid name";
|
||||
}
|
||||
}
|
||||
|
||||
TEST_F(IndexedNameTest, booleanConversionTrue)
|
||||
{
|
||||
// Arrange
|
||||
auto validNames = givenValidIndexedNames();
|
||||
for (const auto& name : validNames) {
|
||||
|
||||
// Act & Assert
|
||||
EXPECT_TRUE(static_cast<bool>(name));
|
||||
}
|
||||
}
|
||||
|
||||
TEST_F(IndexedNameTest, fromConst)
|
||||
{
|
||||
// Arrange
|
||||
const int testIndex {42};
|
||||
|
||||
// Act
|
||||
auto indexedName = Data::IndexedName::fromConst("TestName", testIndex);
|
||||
|
||||
// Assert
|
||||
EXPECT_STREQ(indexedName.getType(), "TestName");
|
||||
EXPECT_EQ(indexedName.getIndex(), testIndex);
|
||||
}
|
||||
|
||||
TEST_F(IndexedNameTest, appendToStringBufferEmptyBuffer)
|
||||
{
|
||||
// Arrange
|
||||
std::string bufferStartedEmpty;
|
||||
Data::IndexedName testName("TEST_NAME", 1);
|
||||
|
||||
// Act
|
||||
testName.appendToStringBuffer(bufferStartedEmpty);
|
||||
|
||||
// Assert
|
||||
EXPECT_EQ(bufferStartedEmpty, "TEST_NAME1");
|
||||
}
|
||||
|
||||
TEST_F(IndexedNameTest, appendToStringBufferNonEmptyBuffer)
|
||||
{
|
||||
// Arrange
|
||||
std::string bufferWithData {"DATA"};
|
||||
Data::IndexedName testName("TEST_NAME", 1);
|
||||
|
||||
// Act
|
||||
testName.appendToStringBuffer(bufferWithData);
|
||||
|
||||
// Assert
|
||||
EXPECT_EQ(bufferWithData, "DATATEST_NAME1");
|
||||
}
|
||||
|
||||
TEST_F(IndexedNameTest, appendToStringBufferZeroIndex)
|
||||
{
|
||||
// Arrange
|
||||
std::string bufferStartedEmpty;
|
||||
Data::IndexedName testName("TEST_NAME", 0);
|
||||
|
||||
// Act
|
||||
testName.appendToStringBuffer(bufferStartedEmpty);
|
||||
|
||||
// Assert
|
||||
EXPECT_EQ(bufferStartedEmpty, "TEST_NAME");
|
||||
}
|
||||
|
||||
TEST_F(IndexedNameTest, toString)
|
||||
{
|
||||
// Arrange
|
||||
Data::IndexedName testName("TEST_NAME", 1);
|
||||
|
||||
// Act
|
||||
auto result = testName.toString();
|
||||
|
||||
// Assert
|
||||
EXPECT_EQ(result, "TEST_NAME1");
|
||||
}
|
||||
|
||||
TEST_F(IndexedNameTest, toStringNoIndex)
|
||||
{
|
||||
// Arrange
|
||||
Data::IndexedName testName("TEST_NAME", 0);
|
||||
|
||||
// Act
|
||||
auto result = testName.toString();
|
||||
|
||||
// Assert
|
||||
EXPECT_EQ(result, "TEST_NAME");
|
||||
}
|
||||
|
||||
TEST_F(IndexedNameTest, assignmentOperator)
|
||||
{
|
||||
// Arrange
|
||||
const int testIndex1 {42};
|
||||
const int testIndex2 {24};
|
||||
auto indexedName1 = Data::IndexedName::fromConst("TestName", testIndex1);
|
||||
auto indexedName2 = Data::IndexedName::fromConst("TestName2", testIndex2);
|
||||
EXPECT_NE(indexedName1, indexedName2); // Ensure the test is set up correctly
|
||||
|
||||
// Act
|
||||
indexedName1 = indexedName2;
|
||||
|
||||
// Assert
|
||||
EXPECT_EQ(indexedName1, indexedName2);
|
||||
}
|
||||
|
||||
|
||||
class ByteArrayTest: public ::testing::Test
|
||||
{
|
||||
protected:
|
||||
// void SetUp() override {}
|
||||
|
||||
// void TearDown() override {}
|
||||
};
|
||||
|
||||
TEST_F(ByteArrayTest, QByteArrayConstruction)
|
||||
{
|
||||
// Arrange
|
||||
QByteArray testQBA("Data in a QByteArray");
|
||||
|
||||
// Act
|
||||
Data::ByteArray testByteArray(testQBA);
|
||||
|
||||
// Assert
|
||||
EXPECT_EQ(testQBA, testByteArray.bytes);
|
||||
}
|
||||
|
||||
TEST_F(ByteArrayTest, CopyConstruction)
|
||||
{
|
||||
// Arrange
|
||||
QByteArray testQBA("Data in a QByteArray");
|
||||
Data::ByteArray originalByteArray(testQBA);
|
||||
|
||||
// Act
|
||||
// NOLINTNEXTLINE performance-unnecessary-copy-initialization
|
||||
Data::ByteArray copiedByteArray(originalByteArray);
|
||||
|
||||
// Assert
|
||||
EXPECT_EQ(originalByteArray, copiedByteArray);
|
||||
}
|
||||
|
||||
TEST_F(ByteArrayTest, MoveConstruction)
|
||||
{
|
||||
// Arrange
|
||||
QByteArray testQBA("Data in a QByteArray");
|
||||
Data::ByteArray originalByteArray(testQBA);
|
||||
const auto* originalDataLocation = originalByteArray.bytes.constData();
|
||||
|
||||
// Act
|
||||
Data::ByteArray copiedByteArray(std::move(originalByteArray));
|
||||
|
||||
// Assert
|
||||
EXPECT_EQ(testQBA, copiedByteArray.bytes);
|
||||
EXPECT_EQ(originalDataLocation, copiedByteArray.bytes.constData());
|
||||
}
|
||||
|
||||
TEST_F(ByteArrayTest, ensureUnshared)
|
||||
{
|
||||
// Arrange
|
||||
QByteArray testQBA("Data in a QByteArray");
|
||||
Data::ByteArray originalByteArray(testQBA);
|
||||
const auto* originalDataLocation = originalByteArray.bytes.constData();
|
||||
Data::ByteArray copiedByteArray(originalByteArray);
|
||||
|
||||
// Act
|
||||
copiedByteArray.ensureUnshared();
|
||||
|
||||
// Assert
|
||||
EXPECT_EQ(testQBA, copiedByteArray.bytes);
|
||||
EXPECT_NE(originalDataLocation, copiedByteArray.bytes.constData());
|
||||
}
|
||||
|
||||
TEST_F(ByteArrayTest, equalityOperator)
|
||||
{
|
||||
// Arrange
|
||||
QByteArray testQBA1("Data in a QByteArray");
|
||||
QByteArray testQBA2("Data in a QByteArray");
|
||||
QByteArray testQBA3("Not the same data in a QByteArray");
|
||||
Data::ByteArray byteArray1(testQBA1);
|
||||
Data::ByteArray byteArray2(testQBA2);
|
||||
Data::ByteArray byteArray3(testQBA3);
|
||||
|
||||
// Act & Assert
|
||||
EXPECT_TRUE(byteArray1 == byteArray2);
|
||||
EXPECT_FALSE(byteArray1 == byteArray3);
|
||||
}
|
||||
|
||||
TEST_F(ByteArrayTest, assignmentOperator)
|
||||
{
|
||||
// Arrange
|
||||
QByteArray testQBA1("Data in a QByteArray");
|
||||
QByteArray testQBA2("Different data in a QByteArray");
|
||||
Data::ByteArray originalByteArray(testQBA1);
|
||||
Data::ByteArray newByteArray(testQBA2);
|
||||
ASSERT_FALSE(originalByteArray == newByteArray);
|
||||
|
||||
// Act
|
||||
newByteArray = originalByteArray;
|
||||
|
||||
// Assert
|
||||
EXPECT_TRUE(originalByteArray == newByteArray);
|
||||
}
|
||||
|
||||
TEST_F(ByteArrayTest, moveAssignmentOperator)
|
||||
{
|
||||
// Arrange
|
||||
QByteArray testQBA1("Data in a QByteArray");
|
||||
QByteArray testQBA2("Different data in a QByteArray");
|
||||
Data::ByteArray originalByteArray(testQBA1);
|
||||
const auto* originalByteArrayLocation = originalByteArray.bytes.constData();
|
||||
Data::ByteArray newByteArray(testQBA2);
|
||||
ASSERT_FALSE(originalByteArray == newByteArray);
|
||||
|
||||
// Act
|
||||
newByteArray = std::move(originalByteArray);
|
||||
|
||||
// Assert
|
||||
EXPECT_EQ(originalByteArrayLocation, newByteArray.bytes.constData());
|
||||
}
|
||||
|
||||
// NOLINTEND(readability-magic-numbers)
|
||||
20
tests/src/App/InitApplication.h
Normal file
20
tests/src/App/InitApplication.h
Normal file
@@ -0,0 +1,20 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <App/Application.h>
|
||||
|
||||
namespace tests
|
||||
{
|
||||
|
||||
static void initApplication()
|
||||
{
|
||||
if (App::Application::GetARGC() == 0) {
|
||||
constexpr int argc = 1;
|
||||
std::array<const char*, argc> argv {"FreeCAD"};
|
||||
App::Application::Config()["ExeName"] = "FreeCAD";
|
||||
App::Application::init(argc, const_cast<char**>(argv.data())); // NOLINT
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace tests
|
||||
48
tests/src/App/License.cpp
Normal file
48
tests/src/App/License.cpp
Normal file
@@ -0,0 +1,48 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include "App/License.h"
|
||||
|
||||
TEST(License, isLicenseEmpty)
|
||||
{
|
||||
EXPECT_EQ(App::findLicense(""), -1);
|
||||
}
|
||||
|
||||
TEST(License, isLicenseNull)
|
||||
{
|
||||
EXPECT_EQ(App::findLicense(nullptr), -1);
|
||||
}
|
||||
|
||||
TEST(License, isLicenseYesStr)
|
||||
{
|
||||
EXPECT_EQ(App::findLicense("CC_BY_40"), 1);
|
||||
}
|
||||
|
||||
TEST(License, UnknownIdentifier)
|
||||
{
|
||||
int index {App::findLicense("junk")};
|
||||
EXPECT_EQ(index, -1);
|
||||
}
|
||||
|
||||
TEST(License, direct)
|
||||
{
|
||||
int posn {App::findLicense("CC_BY_40")};
|
||||
App::TLicenseArr tt {
|
||||
"CC_BY_40",
|
||||
"Creative Commons Attribution 4.0",
|
||||
"https://creativecommons.org/licenses/by/4.0/"
|
||||
};
|
||||
EXPECT_STREQ(App::licenseItems.at(posn).at(0), tt.at(0));
|
||||
EXPECT_STREQ(App::licenseItems.at(posn).at(1), tt.at(1));
|
||||
EXPECT_STREQ(App::licenseItems.at(posn).at(2), tt.at(2));
|
||||
}
|
||||
|
||||
TEST(License, findLicenseByIdent)
|
||||
{
|
||||
App::TLicenseArr arr {App::licenseItems.at(App::findLicense("CC_BY_40"))};
|
||||
|
||||
EXPECT_STREQ(arr.at(App::posnOfIdentifier), "CC_BY_40");
|
||||
EXPECT_STREQ(arr.at(App::posnOfFullName), "Creative Commons Attribution 4.0");
|
||||
EXPECT_STREQ(arr.at(App::posnOfUrl), "https://creativecommons.org/licenses/by/4.0/");
|
||||
}
|
||||
320
tests/src/App/MappedElement.cpp
Normal file
320
tests/src/App/MappedElement.cpp
Normal file
@@ -0,0 +1,320 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
#include <utility>
|
||||
#include <map>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
|
||||
#include "App/IndexedName.h"
|
||||
#include "App/MappedElement.h"
|
||||
|
||||
class MappedElementTest: public ::testing::Test
|
||||
{
|
||||
protected:
|
||||
// void SetUp() override {}
|
||||
|
||||
// void TearDown() override {}
|
||||
|
||||
// NOLINTNEXTLINE(bugprone-easily-swappable-parameters)
|
||||
static Data::MappedElement givenMappedElement(const char* index, const char* name)
|
||||
{
|
||||
Data::IndexedName indexedName {index};
|
||||
Data::MappedName mappedName {name};
|
||||
return {indexedName, mappedName};
|
||||
}
|
||||
};
|
||||
|
||||
TEST_F(MappedElementTest, constructFromNameAndIndex)
|
||||
{
|
||||
// Arrange
|
||||
Data::IndexedName indexedName {"EDGE1"};
|
||||
Data::MappedName mappedName {"OTHER_NAME"};
|
||||
|
||||
// Act
|
||||
Data::MappedElement mappedElement {indexedName, mappedName};
|
||||
|
||||
// Assert
|
||||
EXPECT_EQ(mappedElement.index, indexedName);
|
||||
EXPECT_EQ(mappedElement.name, mappedName);
|
||||
}
|
||||
|
||||
TEST_F(MappedElementTest, moveConstructor)
|
||||
{
|
||||
// Arrange
|
||||
auto originalMappedElement = givenMappedElement("EDGE1", "OTHER_NAME");
|
||||
auto originalName = originalMappedElement.name;
|
||||
auto originalIndex = originalMappedElement.index;
|
||||
|
||||
// Act
|
||||
Data::MappedElement newMappedElement {std::move(originalMappedElement)};
|
||||
|
||||
// Assert
|
||||
EXPECT_EQ(originalName, newMappedElement.name);
|
||||
EXPECT_EQ(originalIndex, newMappedElement.index);
|
||||
}
|
||||
|
||||
TEST_F(MappedElementTest, assignmentOperator)
|
||||
{
|
||||
// Arrange
|
||||
auto mappedElementA = givenMappedElement("EDGE1", "OTHER_NAME");
|
||||
auto mappedElementB = givenMappedElement("EDGE2", "ANOTHER_NAME");
|
||||
EXPECT_NE(mappedElementA, mappedElementB); // Verify test setup
|
||||
|
||||
// Act
|
||||
mappedElementA = mappedElementB;
|
||||
|
||||
// Assert
|
||||
EXPECT_EQ(mappedElementA, mappedElementB);
|
||||
}
|
||||
|
||||
TEST_F(MappedElementTest, moveAssignmentOperator)
|
||||
{
|
||||
// Arrange
|
||||
auto mappedElementA = givenMappedElement("EDGE1", "OTHER_NAME");
|
||||
auto mappedElementB = givenMappedElement("EDGE2", "ANOTHER_NAME");
|
||||
EXPECT_NE(mappedElementA, mappedElementB); // Verify test setup
|
||||
|
||||
// Act
|
||||
mappedElementA = std::move(mappedElementB);
|
||||
|
||||
// Assert
|
||||
EXPECT_EQ(mappedElementA.name.toString(), "ANOTHER_NAME");
|
||||
EXPECT_EQ(mappedElementA.index.toString(), "EDGE2");
|
||||
}
|
||||
|
||||
TEST_F(MappedElementTest, equalityOperatorsWhenNotEqual)
|
||||
{
|
||||
// Arrange
|
||||
auto mappedElementA = givenMappedElement("EDGE1", "OTHER_NAME");
|
||||
auto mappedElementB = givenMappedElement("EDGE2", "ANOTHER_NAME");
|
||||
|
||||
// Act
|
||||
bool aAndBAreEqual = mappedElementA == mappedElementB;
|
||||
bool aAndBAreNotEqual = mappedElementA != mappedElementB;
|
||||
|
||||
// Assert
|
||||
EXPECT_TRUE(aAndBAreNotEqual);
|
||||
EXPECT_FALSE(aAndBAreEqual);
|
||||
}
|
||||
|
||||
TEST_F(MappedElementTest, equalityOperatorsWhenEqual)
|
||||
{
|
||||
// Arrange
|
||||
auto mappedElementA = givenMappedElement("EDGE1", "OTHER_NAME");
|
||||
auto mappedElementB = givenMappedElement("EDGE1", "OTHER_NAME");
|
||||
|
||||
// Act
|
||||
bool aAndBAreEqual = mappedElementA == mappedElementB;
|
||||
bool aAndBAreNotEqual = mappedElementA != mappedElementB;
|
||||
|
||||
// Assert
|
||||
EXPECT_FALSE(aAndBAreNotEqual);
|
||||
EXPECT_TRUE(aAndBAreEqual);
|
||||
}
|
||||
|
||||
TEST_F(MappedElementTest, lessThanOperator)
|
||||
{
|
||||
// Index is compared first, then mappedName
|
||||
|
||||
// Arrange
|
||||
auto mappedElement1A = givenMappedElement("EDGE1", "A");
|
||||
auto mappedElement1B = givenMappedElement("EDGE1", "B");
|
||||
auto mappedElement2A = givenMappedElement("EDGE2", "A");
|
||||
auto mappedElement2B = givenMappedElement("EDGE2", "B");
|
||||
auto mappedElement2BDuplicate = givenMappedElement("EDGE2", "B");
|
||||
|
||||
// Act & Assert
|
||||
EXPECT_TRUE(mappedElement1A < mappedElement1B);
|
||||
EXPECT_TRUE(mappedElement1A < mappedElement2A);
|
||||
EXPECT_TRUE(mappedElement1B < mappedElement2A);
|
||||
EXPECT_FALSE(mappedElement2A < mappedElement1B);
|
||||
EXPECT_FALSE(mappedElement2B < mappedElement2BDuplicate);
|
||||
}
|
||||
|
||||
TEST_F(MappedElementTest, comparatorBothAreZeroSize)
|
||||
{
|
||||
// Arrange
|
||||
Data::MappedName mappedName1 {""};
|
||||
Data::MappedName mappedName2 {""};
|
||||
auto comp = Data::ElementNameComparator();
|
||||
|
||||
// Act & Assert
|
||||
EXPECT_FALSE(comp(mappedName1, mappedName2));
|
||||
}
|
||||
|
||||
TEST_F(MappedElementTest, comparatorOneIsZeroSize)
|
||||
{
|
||||
// Arrange
|
||||
Data::MappedName mappedName1 {""};
|
||||
Data::MappedName mappedName2 {"#12345"};
|
||||
auto comp = Data::ElementNameComparator();
|
||||
|
||||
// Act & Assert
|
||||
EXPECT_TRUE(comp(mappedName1, mappedName2));
|
||||
}
|
||||
|
||||
TEST_F(MappedElementTest, comparatorBothStartWithHexDigitsThatDiffer)
|
||||
{
|
||||
// Arrange
|
||||
Data::MappedName mappedName1 {"#fed;B"};
|
||||
Data::MappedName mappedName2 {"#abcdef;A"};
|
||||
auto comp = Data::ElementNameComparator();
|
||||
|
||||
// Act & Assert
|
||||
EXPECT_TRUE(comp(mappedName1, mappedName2));
|
||||
}
|
||||
|
||||
TEST_F(MappedElementTest, comparatorBothStartWithTheSameHexDigits)
|
||||
{
|
||||
// Arrange
|
||||
Data::MappedName mappedName1 {"#12345;B"};
|
||||
Data::MappedName mappedName2 {"#12345;A"};
|
||||
auto comp = Data::ElementNameComparator();
|
||||
|
||||
// Act & Assert
|
||||
EXPECT_FALSE(comp(mappedName1, mappedName2));
|
||||
}
|
||||
|
||||
TEST_F(MappedElementTest, comparatorHexWithoutTerminator)
|
||||
{
|
||||
// Arrange
|
||||
Data::MappedName mappedName1 {"#fed"};
|
||||
Data::MappedName mappedName2 {"#abcdef"};
|
||||
auto comp = Data::ElementNameComparator();
|
||||
|
||||
// Act & Assert
|
||||
EXPECT_TRUE(comp(mappedName1, mappedName2));
|
||||
}
|
||||
|
||||
TEST_F(MappedElementTest, comparatorHexWithoutTerminatorSameLength)
|
||||
{
|
||||
// Arrange
|
||||
Data::MappedName mappedName1 {"#fed"};
|
||||
Data::MappedName mappedName2 {"#abc"};
|
||||
auto comp = Data::ElementNameComparator();
|
||||
|
||||
// Act & Assert
|
||||
EXPECT_FALSE(comp(mappedName1, mappedName2));
|
||||
}
|
||||
|
||||
TEST_F(MappedElementTest, comparatorNoHexDigitsLexicalCompare)
|
||||
{
|
||||
// Arrange
|
||||
Data::MappedName mappedName1 {"A"};
|
||||
Data::MappedName mappedName2 {"B"};
|
||||
auto comp = Data::ElementNameComparator();
|
||||
|
||||
// Act & Assert
|
||||
EXPECT_TRUE(comp(mappedName1, mappedName2));
|
||||
}
|
||||
|
||||
TEST_F(MappedElementTest, comparatorNoHexDigitsSameStringNumericCompare)
|
||||
{
|
||||
// Arrange
|
||||
Data::MappedName mappedName1 {"Edge123456;"};
|
||||
Data::MappedName mappedName2 {"Edge321;"};
|
||||
auto comp = Data::ElementNameComparator();
|
||||
|
||||
// Act & Assert
|
||||
EXPECT_FALSE(comp(mappedName1, mappedName2));
|
||||
}
|
||||
|
||||
TEST_F(MappedElementTest, comparatorIntegerWithoutTerminatorIsBroken)
|
||||
{
|
||||
// Arrange
|
||||
Data::MappedName mappedName1 {"Edge123456"};
|
||||
Data::MappedName mappedName2 {"Edge321"};
|
||||
auto comp = Data::ElementNameComparator();
|
||||
|
||||
// Act & Assert
|
||||
EXPECT_FALSE(comp(mappedName1, mappedName2));
|
||||
}
|
||||
|
||||
TEST_F(MappedElementTest, comparatorThreeComplexHexNamesInMap)
|
||||
{
|
||||
// Arrange
|
||||
Data::MappedName name1("#19c9:e;:U;FUS;:Hce4:7,E");
|
||||
Data::MappedName name2("#1dadb:11;:L#1061a;FUS;:H:d,E");
|
||||
Data::MappedName name3("#1dae6:8;:L#1dae4;FUS;:H:d,E");
|
||||
|
||||
std::map<Data::MappedName, int, Data::ElementNameComparator> testMap;
|
||||
testMap[name1] = 1;
|
||||
testMap[name2] = 2;
|
||||
testMap[name3] = 3;
|
||||
|
||||
// Assert: map should have 3 unique keys
|
||||
EXPECT_EQ(testMap.size(), 3);
|
||||
|
||||
// Collect keys in order
|
||||
std::vector<std::string> keys;
|
||||
for (const auto& kv : testMap) {
|
||||
keys.push_back(kv.first.toString());
|
||||
}
|
||||
|
||||
// Print for debug (optional)
|
||||
// for (const auto& k : keys) std::cout << k << std::endl;
|
||||
|
||||
// The expected order depends on your comparator logic.
|
||||
// If you want to check the exact order, set it here:
|
||||
// (Replace with the correct expected order if needed)
|
||||
std::vector<std::string> expectedOrder = {
|
||||
"#19c9:e;:U;FUS;:Hce4:7,E",
|
||||
"#1dadb:11;:L#1061a;FUS;:H:d,E",
|
||||
"#1dae6:8;:L#1dae4;FUS;:H:d,E"
|
||||
};
|
||||
|
||||
EXPECT_EQ(keys, expectedOrder);
|
||||
}
|
||||
|
||||
TEST_F(MappedElementTest, comparatorLargerWorkedExampleWithMap)
|
||||
{
|
||||
// Arrange
|
||||
Data::MappedName name0("Edge123;:U;FUS;:Hce4:7,E");
|
||||
Data::MappedName name1("#1dad:e;:U;FUS;:Hce4:7,E");
|
||||
Data::MappedName name2("#1dadb:11;:L#1061a;FUS;:H:d,E");
|
||||
Data::MappedName name3("#1dae6:8;:L#1dae4;FUS;:H:d,E");
|
||||
Data::MappedName name4("Edge999;;:L#1dae4;FUS;:H:d,E");
|
||||
Data::MappedName name5("g4v2;SKT;:H1234,F;:H5678:2,E;:G0(g1;SKT;:H9012,E);XTR;:H3456:2,F");
|
||||
|
||||
|
||||
std::map<Data::MappedName, int, Data::ElementNameComparator> testMap;
|
||||
testMap[name0] = 1;
|
||||
testMap[name1] = 2;
|
||||
testMap[name2] = 3;
|
||||
testMap[name3] = 4;
|
||||
testMap[name0] = 5; // Duplicate, should not affect size
|
||||
testMap[name1] = 6; // Duplicate, should not affect size
|
||||
testMap[name4] = 7; // New entry
|
||||
testMap[name4] = 8; // Duplicate, should not affect size
|
||||
testMap[name2] = 9; // Duplicate, should not affect size
|
||||
testMap[name3] = 10; // Duplicate, should not affect size
|
||||
testMap[name5] = 11;
|
||||
|
||||
// Assert: map should have 5 unique keys
|
||||
EXPECT_EQ(testMap.size(), 6);
|
||||
|
||||
// Collect keys in order
|
||||
std::vector<std::string> keys;
|
||||
for (const auto& kv : testMap) {
|
||||
keys.push_back(kv.first.toString());
|
||||
}
|
||||
|
||||
// Print for debug (optional)
|
||||
// for (const auto& k : keys) std::cout << k << std::endl;
|
||||
|
||||
// The expected order depends on your comparator logic.
|
||||
// If you want to check the exact order, set it here:
|
||||
// (Replace with the correct expected order if needed)
|
||||
std::vector<std::string> expectedOrder = {
|
||||
"Edge123;:U;FUS;:Hce4:7,E",
|
||||
"Edge999;;:L#1dae4;FUS;:H:d,E",
|
||||
"g4v2;SKT;:H1234,F;:H5678:2,E;:G0(g1;SKT;:H9012,E);XTR;:H3456:2,F",
|
||||
"#1dad:e;:U;FUS;:Hce4:7,E",
|
||||
"#1dadb:11;:L#1061a;FUS;:H:d,E",
|
||||
"#1dae6:8;:L#1dae4;FUS;:H:d,E"
|
||||
};
|
||||
|
||||
EXPECT_EQ(keys, expectedOrder);
|
||||
}
|
||||
963
tests/src/App/MappedName.cpp
Normal file
963
tests/src/App/MappedName.cpp
Normal file
@@ -0,0 +1,963 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include "App/ComplexGeoData.h"
|
||||
#include "App/MappedName.h"
|
||||
|
||||
#include <string>
|
||||
|
||||
// NOLINTBEGIN(readability-magic-numbers)
|
||||
|
||||
TEST(MappedName, defaultConstruction)
|
||||
{
|
||||
// Act
|
||||
Data::MappedName mappedName;
|
||||
|
||||
// Assert
|
||||
EXPECT_EQ(mappedName.isRaw(), false);
|
||||
EXPECT_EQ(mappedName.empty(), true);
|
||||
EXPECT_EQ(mappedName.size(), 0);
|
||||
EXPECT_EQ(mappedName.dataBytes(), QByteArray());
|
||||
EXPECT_EQ(mappedName.postfixBytes(), QByteArray());
|
||||
}
|
||||
|
||||
TEST(MappedName, namedConstruction)
|
||||
{
|
||||
// Act
|
||||
Data::MappedName mappedName("TEST");
|
||||
|
||||
// Assert
|
||||
EXPECT_EQ(mappedName.isRaw(), false);
|
||||
EXPECT_EQ(mappedName.empty(), false);
|
||||
EXPECT_EQ(mappedName.size(), 4);
|
||||
EXPECT_EQ(mappedName.dataBytes(), QByteArray("TEST"));
|
||||
EXPECT_EQ(mappedName.postfixBytes(), QByteArray());
|
||||
}
|
||||
|
||||
TEST(MappedName, namedConstructionWithMaxSize)
|
||||
{
|
||||
// Act
|
||||
Data::MappedName mappedName("TEST", 2);
|
||||
|
||||
// Assert
|
||||
EXPECT_EQ(mappedName.isRaw(), false);
|
||||
EXPECT_EQ(mappedName.empty(), false);
|
||||
EXPECT_EQ(mappedName.size(), 2);
|
||||
EXPECT_EQ(mappedName.dataBytes(), QByteArray("TE"));
|
||||
EXPECT_EQ(mappedName.postfixBytes(), QByteArray());
|
||||
}
|
||||
|
||||
TEST(MappedName, namedConstructionDiscardPrefix)
|
||||
{
|
||||
// Arrange
|
||||
std::string name = std::string(Data::ELEMENT_MAP_PREFIX) + "TEST";
|
||||
|
||||
// Act
|
||||
Data::MappedName mappedName(name.c_str());
|
||||
|
||||
// Assert
|
||||
EXPECT_EQ(mappedName.isRaw(), false);
|
||||
EXPECT_EQ(mappedName.empty(), false);
|
||||
EXPECT_EQ(mappedName.size(), 4);
|
||||
EXPECT_EQ(mappedName.dataBytes(), QByteArray("TEST"));
|
||||
EXPECT_EQ(mappedName.postfixBytes(), QByteArray());
|
||||
}
|
||||
|
||||
TEST(MappedName, stringNamedConstruction)
|
||||
{
|
||||
// Act
|
||||
Data::MappedName mappedName(std::string("TEST"));
|
||||
|
||||
// Assert
|
||||
EXPECT_EQ(mappedName.isRaw(), false);
|
||||
EXPECT_EQ(mappedName.empty(), false);
|
||||
EXPECT_EQ(mappedName.size(), 4);
|
||||
EXPECT_EQ(mappedName.dataBytes(), QByteArray("TEST"));
|
||||
EXPECT_EQ(mappedName.postfixBytes(), QByteArray());
|
||||
}
|
||||
|
||||
TEST(MappedName, stringNamedConstructionDiscardPrefix)
|
||||
{
|
||||
// Arrange
|
||||
std::string name = std::string(Data::ELEMENT_MAP_PREFIX) + "TEST";
|
||||
|
||||
// Act
|
||||
Data::MappedName mappedName(name);
|
||||
|
||||
// Assert
|
||||
EXPECT_EQ(mappedName.isRaw(), false);
|
||||
EXPECT_EQ(mappedName.empty(), false);
|
||||
EXPECT_EQ(mappedName.size(), 4);
|
||||
EXPECT_EQ(mappedName.dataBytes(), QByteArray("TEST"));
|
||||
EXPECT_EQ(mappedName.postfixBytes(), QByteArray());
|
||||
}
|
||||
|
||||
TEST(MappedName, constructFromIndexedNameNoIndex)
|
||||
{
|
||||
// Arrange
|
||||
Data::IndexedName indexedName {"INDEXED_NAME"};
|
||||
|
||||
// Act
|
||||
Data::MappedName mappedName {indexedName};
|
||||
|
||||
// Assert
|
||||
EXPECT_EQ(mappedName.dataBytes().constData(), indexedName.getType()); // shared memory
|
||||
EXPECT_EQ(mappedName.isRaw(), true);
|
||||
}
|
||||
|
||||
TEST(MappedName, constructFromIndexedNameWithIndex)
|
||||
{
|
||||
// Arrange
|
||||
Data::IndexedName indexedName {"INDEXED_NAME", 1};
|
||||
|
||||
// Act
|
||||
Data::MappedName mappedName {indexedName};
|
||||
|
||||
// Assert
|
||||
EXPECT_NE(mappedName.dataBytes().constData(), indexedName.getType()); // NOT shared memory
|
||||
EXPECT_EQ(mappedName.isRaw(), false);
|
||||
EXPECT_EQ(mappedName.toString(), indexedName.toString());
|
||||
}
|
||||
|
||||
TEST(MappedName, copyConstructor)
|
||||
{
|
||||
// Arrange
|
||||
Data::MappedName temp("TEST");
|
||||
|
||||
// Act
|
||||
Data::MappedName mappedName(temp);
|
||||
|
||||
// Assert
|
||||
EXPECT_EQ(mappedName.isRaw(), false);
|
||||
EXPECT_EQ(mappedName.empty(), false);
|
||||
EXPECT_EQ(mappedName.size(), 4);
|
||||
EXPECT_EQ(mappedName.dataBytes(), QByteArray("TEST"));
|
||||
EXPECT_EQ(mappedName.postfixBytes(), QByteArray());
|
||||
}
|
||||
|
||||
TEST(MappedName, copyConstructorWithPostfix)
|
||||
{
|
||||
// Arrange
|
||||
Data::MappedName temp("TEST");
|
||||
|
||||
// Act
|
||||
Data::MappedName mappedName(temp, "POSTFIXTEST");
|
||||
|
||||
// Assert
|
||||
EXPECT_EQ(mappedName.isRaw(), false);
|
||||
EXPECT_EQ(mappedName.empty(), false);
|
||||
EXPECT_EQ(mappedName.size(), 15);
|
||||
EXPECT_EQ(mappedName.dataBytes(), QByteArray("TEST"));
|
||||
EXPECT_EQ(mappedName.postfixBytes(), QByteArray("POSTFIXTEST"));
|
||||
|
||||
// Act
|
||||
Data::MappedName mappedName2(mappedName, "ANOTHERPOSTFIX");
|
||||
|
||||
// Assert
|
||||
EXPECT_EQ(mappedName2.isRaw(), false);
|
||||
EXPECT_EQ(mappedName2.empty(), false);
|
||||
EXPECT_EQ(mappedName2.size(), 29);
|
||||
EXPECT_EQ(mappedName2.dataBytes(), QByteArray("TESTPOSTFIXTEST"));
|
||||
EXPECT_EQ(mappedName2.postfixBytes(), QByteArray("ANOTHERPOSTFIX"));
|
||||
}
|
||||
|
||||
TEST(MappedName, copyConstructorStartpos)
|
||||
{
|
||||
// Arrange
|
||||
Data::MappedName temp(Data::MappedName("TEST"), "POSTFIXTEST");
|
||||
|
||||
// Act
|
||||
Data::MappedName mappedName(temp, 2, -1);
|
||||
|
||||
// Assert
|
||||
EXPECT_EQ(mappedName.isRaw(), false);
|
||||
EXPECT_EQ(mappedName.empty(), false);
|
||||
EXPECT_EQ(mappedName.size(), 13);
|
||||
EXPECT_EQ(mappedName.dataBytes(), QByteArray("ST"));
|
||||
EXPECT_EQ(mappedName.postfixBytes(), QByteArray("POSTFIXTEST"));
|
||||
}
|
||||
|
||||
TEST(MappedName, copyConstructorStartposAndSize)
|
||||
{
|
||||
// Arrange
|
||||
Data::MappedName temp(Data::MappedName("TEST"), "POSTFIXTEST");
|
||||
|
||||
// Act
|
||||
Data::MappedName mappedName(temp, 2, 6);
|
||||
|
||||
// Assert
|
||||
EXPECT_EQ(mappedName.isRaw(), false);
|
||||
EXPECT_EQ(mappedName.empty(), false);
|
||||
EXPECT_EQ(mappedName.size(), 6);
|
||||
EXPECT_EQ(mappedName.dataBytes(), QByteArray("ST"));
|
||||
EXPECT_EQ(mappedName.postfixBytes(), QByteArray("POST"));
|
||||
}
|
||||
|
||||
TEST(MappedName, moveConstructor)
|
||||
{
|
||||
// Arrange
|
||||
Data::MappedName temp(Data::MappedName("TEST"), "POSTFIXTEST");
|
||||
|
||||
// Act
|
||||
Data::MappedName mappedName(std::move(temp));
|
||||
|
||||
// Assert
|
||||
EXPECT_EQ(mappedName.isRaw(), false);
|
||||
EXPECT_EQ(mappedName.empty(), false);
|
||||
EXPECT_EQ(mappedName.size(), 15);
|
||||
EXPECT_EQ(mappedName.dataBytes(), QByteArray("TEST"));
|
||||
EXPECT_EQ(mappedName.postfixBytes(), QByteArray("POSTFIXTEST"));
|
||||
}
|
||||
|
||||
TEST(MappedName, fromRawData)
|
||||
{
|
||||
// Act
|
||||
Data::MappedName mappedName = Data::MappedName::fromRawData("TESTTEST", 8);
|
||||
|
||||
// Assert
|
||||
EXPECT_EQ(mappedName.isRaw(), true);
|
||||
EXPECT_EQ(mappedName.empty(), false);
|
||||
EXPECT_EQ(mappedName.size(), 8);
|
||||
EXPECT_EQ(mappedName.dataBytes(), QByteArray("TESTTEST", 8));
|
||||
EXPECT_EQ(mappedName.postfixBytes(), QByteArray());
|
||||
}
|
||||
|
||||
TEST(MappedName, fromRawDataQByteArray)
|
||||
{
|
||||
// Arrange
|
||||
QByteArray testByteArray("TESTTEST", 8);
|
||||
|
||||
// Act
|
||||
Data::MappedName mappedName = Data::MappedName::fromRawData(testByteArray);
|
||||
|
||||
// Assert
|
||||
EXPECT_EQ(mappedName.isRaw(), true);
|
||||
EXPECT_EQ(mappedName.empty(), false);
|
||||
EXPECT_EQ(mappedName.size(), 8);
|
||||
EXPECT_EQ(mappedName.dataBytes(), QByteArray("TESTTEST", 8));
|
||||
EXPECT_EQ(mappedName.postfixBytes(), QByteArray());
|
||||
}
|
||||
|
||||
TEST(MappedName, fromRawDataCopy)
|
||||
{
|
||||
// Arrange
|
||||
QByteArray testByteArray("TESTTEST", 8);
|
||||
Data::MappedName temp = Data::MappedName::fromRawData(testByteArray);
|
||||
temp.append("TESTPOSTFIX");
|
||||
temp.compact(); // Always call compact before accessing data!
|
||||
|
||||
// Act
|
||||
Data::MappedName mappedName = Data::MappedName::fromRawData(temp, 0);
|
||||
|
||||
// Assert
|
||||
EXPECT_EQ(mappedName.isRaw(), true);
|
||||
EXPECT_EQ(mappedName.empty(), false);
|
||||
EXPECT_EQ(mappedName.size(), 19);
|
||||
EXPECT_EQ(mappedName.dataBytes(), QByteArray("TESTTEST", 8));
|
||||
EXPECT_EQ(mappedName.postfixBytes(), QByteArray("TESTPOSTFIX"));
|
||||
}
|
||||
|
||||
TEST(MappedName, fromRawDataCopyStartposAndSize)
|
||||
{
|
||||
// Arrange
|
||||
QByteArray testByteArray("TESTTEST", 8);
|
||||
Data::MappedName temp = Data::MappedName::fromRawData(testByteArray);
|
||||
temp.append("ABCDEFGHIJKLM"); // postfix
|
||||
temp.compact(); // Always call compact before accessing data!
|
||||
|
||||
// Act
|
||||
Data::MappedName mappedName = Data::MappedName::fromRawData(temp, 2, 13);
|
||||
|
||||
// Assert
|
||||
EXPECT_EQ(mappedName.isRaw(), true);
|
||||
EXPECT_EQ(mappedName.empty(), false);
|
||||
EXPECT_EQ(mappedName.size(), 13);
|
||||
EXPECT_EQ(mappedName.dataBytes(), QByteArray("STTEST", 6));
|
||||
EXPECT_EQ(mappedName.postfixBytes(), QByteArray("ABCDEFG"));
|
||||
}
|
||||
|
||||
TEST(MappedName, assignmentOperator)
|
||||
{
|
||||
// Arrange
|
||||
Data::MappedName temp(Data::MappedName("TEST"), "POSTFIXTEST");
|
||||
|
||||
// Act
|
||||
Data::MappedName mappedName = temp;
|
||||
|
||||
// Assert
|
||||
EXPECT_EQ(mappedName.isRaw(), false);
|
||||
EXPECT_EQ(mappedName.empty(), false);
|
||||
EXPECT_EQ(mappedName.size(), 15);
|
||||
EXPECT_EQ(mappedName.dataBytes(), QByteArray("TEST"));
|
||||
EXPECT_EQ(mappedName.postfixBytes(), QByteArray("POSTFIXTEST"));
|
||||
}
|
||||
|
||||
TEST(MappedName, assignmentOperatorString)
|
||||
{
|
||||
// Arrange
|
||||
Data::MappedName mappedName;
|
||||
|
||||
// Act
|
||||
mappedName = std::string("TEST");
|
||||
|
||||
// Assert
|
||||
EXPECT_EQ(mappedName.isRaw(), false);
|
||||
EXPECT_EQ(mappedName.empty(), false);
|
||||
EXPECT_EQ(mappedName.size(), 4);
|
||||
EXPECT_EQ(mappedName.dataBytes(), QByteArray("TEST"));
|
||||
EXPECT_EQ(mappedName.postfixBytes(), QByteArray());
|
||||
}
|
||||
|
||||
TEST(MappedName, assignmentOperatorConstCharPtr)
|
||||
{
|
||||
// Arrange
|
||||
Data::MappedName mappedName;
|
||||
|
||||
// Act
|
||||
mappedName = "TEST";
|
||||
|
||||
// Assert
|
||||
EXPECT_EQ(mappedName.isRaw(), false);
|
||||
EXPECT_EQ(mappedName.empty(), false);
|
||||
EXPECT_EQ(mappedName.size(), 4);
|
||||
EXPECT_EQ(mappedName.dataBytes(), QByteArray("TEST"));
|
||||
EXPECT_EQ(mappedName.postfixBytes(), QByteArray());
|
||||
}
|
||||
|
||||
TEST(MappedName, assignmentOperatorMove)
|
||||
{
|
||||
// Arrange
|
||||
Data::MappedName temp(Data::MappedName("TEST"), "POSTFIXTEST");
|
||||
|
||||
// Act
|
||||
Data::MappedName mappedName = std::move(temp);
|
||||
|
||||
// Assert
|
||||
EXPECT_EQ(mappedName.isRaw(), false);
|
||||
EXPECT_EQ(mappedName.empty(), false);
|
||||
EXPECT_EQ(mappedName.size(), 15);
|
||||
EXPECT_EQ(mappedName.dataBytes(), QByteArray("TEST"));
|
||||
EXPECT_EQ(mappedName.postfixBytes(), QByteArray("POSTFIXTEST"));
|
||||
}
|
||||
|
||||
TEST(MappedName, streamInsertionOperator)
|
||||
{
|
||||
// Arrange
|
||||
Data::MappedName mappedName(Data::MappedName("TEST"), "POSTFIXTEST");
|
||||
std::stringstream ss;
|
||||
|
||||
// Act
|
||||
ss << mappedName;
|
||||
|
||||
// Assert
|
||||
EXPECT_EQ(ss.str(), std::string("TESTPOSTFIXTEST"));
|
||||
}
|
||||
|
||||
TEST(MappedName, comparisonOperators)
|
||||
{
|
||||
// Arrange
|
||||
Data::MappedName mappedName1(Data::MappedName("TEST"), "POSTFIXTEST");
|
||||
Data::MappedName mappedName2(Data::MappedName("TEST"), "POSTFIXTEST");
|
||||
Data::MappedName mappedName3(Data::MappedName("TESTPOST"), "FIXTEST");
|
||||
Data::MappedName mappedName4(Data::MappedName("THIS"), "ISDIFFERENT");
|
||||
|
||||
// Act & Assert
|
||||
EXPECT_EQ(mappedName1 == mappedName1, true);
|
||||
EXPECT_EQ(mappedName1 == mappedName2, true);
|
||||
EXPECT_EQ(mappedName1 == mappedName3, true);
|
||||
EXPECT_EQ(mappedName1 == mappedName4, false);
|
||||
|
||||
EXPECT_EQ(mappedName1 != mappedName1, false);
|
||||
EXPECT_EQ(mappedName1 != mappedName2, false);
|
||||
EXPECT_EQ(mappedName1 != mappedName3, false);
|
||||
EXPECT_EQ(mappedName1 != mappedName4, true);
|
||||
}
|
||||
|
||||
TEST(MappedName, additionOperators)
|
||||
{
|
||||
// Arrange
|
||||
Data::MappedName mappedName(Data::MappedName("TEST"), "POSTFIXTEST");
|
||||
QByteArray post3("POST3");
|
||||
|
||||
// Act
|
||||
mappedName += "POST1";
|
||||
mappedName += std::string("POST2");
|
||||
mappedName += post3;
|
||||
mappedName += Data::MappedName("POST4");
|
||||
|
||||
// Assert
|
||||
EXPECT_EQ(mappedName.isRaw(), false);
|
||||
EXPECT_EQ(mappedName.empty(), false);
|
||||
EXPECT_EQ(mappedName.size(), 35);
|
||||
EXPECT_EQ(mappedName.dataBytes(), QByteArray("TEST"));
|
||||
EXPECT_EQ(mappedName.postfixBytes(), QByteArray("POSTFIXTESTPOST1POST2POST3POST4"));
|
||||
|
||||
// Arrange
|
||||
mappedName = Data::MappedName(Data::MappedName("TEST"), "POSTFIXTEST");
|
||||
QByteArray post8("POST8");
|
||||
|
||||
// Act
|
||||
mappedName = mappedName + Data::MappedName("POST5");
|
||||
mappedName = mappedName + "POST6";
|
||||
mappedName = mappedName + std::string("POST7");
|
||||
mappedName = mappedName + post8;
|
||||
|
||||
// Assert
|
||||
EXPECT_EQ(mappedName.isRaw(), false);
|
||||
EXPECT_EQ(mappedName.empty(), false);
|
||||
EXPECT_EQ(mappedName.size(), 35);
|
||||
EXPECT_EQ(mappedName.dataBytes(), QByteArray("TEST"));
|
||||
EXPECT_EQ(mappedName.postfixBytes(), QByteArray("POSTFIXTESTPOST5POST6POST7POST8"));
|
||||
}
|
||||
|
||||
TEST(MappedName, append)
|
||||
{
|
||||
// Arrange
|
||||
Data::MappedName mappedName;
|
||||
|
||||
// Act
|
||||
mappedName.append("TEST");
|
||||
|
||||
// Assert
|
||||
EXPECT_EQ(mappedName.isRaw(), false);
|
||||
EXPECT_EQ(mappedName.empty(), false);
|
||||
EXPECT_EQ(mappedName.size(), 4);
|
||||
EXPECT_EQ(mappedName.dataBytes(), QByteArray("TEST"));
|
||||
EXPECT_EQ(mappedName.postfixBytes(), QByteArray(""));
|
||||
|
||||
// Act
|
||||
mappedName.append("POSTFIX");
|
||||
|
||||
// Assert
|
||||
EXPECT_EQ(mappedName.isRaw(), false);
|
||||
EXPECT_EQ(mappedName.empty(), false);
|
||||
EXPECT_EQ(mappedName.size(), 11);
|
||||
EXPECT_EQ(mappedName.dataBytes(), QByteArray("TEST"));
|
||||
EXPECT_EQ(mappedName.postfixBytes(), QByteArray("POSTFIX"));
|
||||
|
||||
// Act
|
||||
mappedName.append("ANOTHERPOSTFIX", 5);
|
||||
|
||||
// Assert
|
||||
EXPECT_EQ(mappedName.isRaw(), false);
|
||||
EXPECT_EQ(mappedName.empty(), false);
|
||||
EXPECT_EQ(mappedName.size(), 16);
|
||||
EXPECT_EQ(mappedName.dataBytes(), QByteArray("TEST"));
|
||||
EXPECT_EQ(mappedName.postfixBytes(), QByteArray("POSTFIXANOTH"));
|
||||
}
|
||||
|
||||
TEST(MappedName, appendMappedNameObj)
|
||||
{
|
||||
// Arrange
|
||||
Data::MappedName mappedName;
|
||||
Data::MappedName temp(Data::MappedName("TEST"), "POSTFIXTEST");
|
||||
|
||||
// Act
|
||||
mappedName.append(temp);
|
||||
|
||||
// Assert
|
||||
EXPECT_EQ(mappedName.isRaw(), false);
|
||||
EXPECT_EQ(mappedName.empty(), false);
|
||||
EXPECT_EQ(mappedName.size(), 15);
|
||||
EXPECT_EQ(mappedName.dataBytes(), QByteArray("TEST"));
|
||||
EXPECT_EQ(mappedName.postfixBytes(), QByteArray("POSTFIXTEST"));
|
||||
|
||||
// Act
|
||||
mappedName.append(temp, 2, 7);
|
||||
|
||||
// Assert
|
||||
EXPECT_EQ(mappedName.isRaw(), false);
|
||||
EXPECT_EQ(mappedName.empty(), false);
|
||||
EXPECT_EQ(mappedName.size(), 22);
|
||||
EXPECT_EQ(mappedName.dataBytes(), QByteArray("TEST"));
|
||||
EXPECT_EQ(mappedName.postfixBytes(), QByteArray("POSTFIXTESTSTPOSTF"));
|
||||
}
|
||||
|
||||
TEST(MappedName, toString)
|
||||
{
|
||||
// Arrange
|
||||
Data::MappedName mappedName(Data::MappedName("TEST"), "POSTFIXTEST");
|
||||
|
||||
// Act & Assert
|
||||
EXPECT_EQ(mappedName.toString(0), "TESTPOSTFIXTEST");
|
||||
EXPECT_EQ(mappedName.toString(0), std::string("TESTPOSTFIXTEST"));
|
||||
EXPECT_EQ(mappedName.toString(2, 8), "STPOSTFI");
|
||||
EXPECT_EQ(mappedName.toString(2, 8), std::string("STPOSTFI"));
|
||||
}
|
||||
|
||||
TEST(MappedName, toConstString)
|
||||
{
|
||||
// Arrange
|
||||
Data::MappedName mappedName(Data::MappedName("TEST"), "POSTFIXTEST");
|
||||
int size {0};
|
||||
|
||||
// Act
|
||||
const char* temp = mappedName.toConstString(0, size);
|
||||
|
||||
// Assert
|
||||
EXPECT_EQ(QByteArray(temp, size), QByteArray("TEST"));
|
||||
EXPECT_EQ(size, 4);
|
||||
|
||||
// Act
|
||||
const char* temp2 = mappedName.toConstString(7, size);
|
||||
|
||||
// Assert
|
||||
EXPECT_EQ(QByteArray(temp2, size), QByteArray("TFIXTEST"));
|
||||
EXPECT_EQ(size, 8);
|
||||
}
|
||||
|
||||
TEST(MappedName, toRawBytes)
|
||||
{
|
||||
// Arrange
|
||||
Data::MappedName mappedName(Data::MappedName("TEST"), "POSTFIXTEST");
|
||||
|
||||
// Act & Assert
|
||||
EXPECT_EQ(mappedName.toRawBytes(), QByteArray("TESTPOSTFIXTEST"));
|
||||
EXPECT_EQ(mappedName.toRawBytes(3), QByteArray("TPOSTFIXTEST"));
|
||||
EXPECT_EQ(mappedName.toRawBytes(7, 3), QByteArray("TFI"));
|
||||
EXPECT_EQ(mappedName.toRawBytes(502, 5), QByteArray());
|
||||
}
|
||||
|
||||
TEST(MappedName, toIndexedNameASCIIOnly)
|
||||
{
|
||||
// Arrange
|
||||
Data::MappedName mappedName {"MAPPED_NAME"};
|
||||
|
||||
// Act
|
||||
auto indexedName = mappedName.toIndexedName();
|
||||
|
||||
// Assert
|
||||
EXPECT_FALSE(indexedName.isNull());
|
||||
}
|
||||
|
||||
TEST(MappedName, toIndexedNameInvalid)
|
||||
{
|
||||
// Arrange
|
||||
Data::MappedName mappedName {"MAPPED-NAME"};
|
||||
|
||||
// Act
|
||||
auto indexedName = mappedName.toIndexedName();
|
||||
|
||||
// Assert
|
||||
EXPECT_TRUE(indexedName.isNull());
|
||||
}
|
||||
|
||||
TEST(MappedName, appendToBuffer)
|
||||
{
|
||||
// Arrange
|
||||
Data::MappedName mappedName(Data::MappedName("TEST"), "POSTFIXTEST");
|
||||
std::string buffer("STUFF");
|
||||
|
||||
// Act
|
||||
mappedName.appendToBuffer(buffer);
|
||||
|
||||
// Assert
|
||||
EXPECT_EQ(buffer, std::string("STUFFTESTPOSTFIXTEST"));
|
||||
|
||||
// Act
|
||||
mappedName.appendToBuffer(buffer, 2, 7);
|
||||
|
||||
// Assert
|
||||
EXPECT_EQ(buffer, std::string("STUFFTESTPOSTFIXTESTSTPOSTF"));
|
||||
}
|
||||
|
||||
TEST(MappedName, appendToBufferWithPrefix)
|
||||
{
|
||||
// Arrange
|
||||
Data::MappedName mappedName(Data::MappedName("TEST"), "POSTFIXTEST");
|
||||
std::string buffer("STUFF");
|
||||
std::string elemMapPrefix = Data::ELEMENT_MAP_PREFIX;
|
||||
|
||||
// Act
|
||||
mappedName.appendToBufferWithPrefix(buffer);
|
||||
|
||||
// Assert
|
||||
EXPECT_EQ(buffer, std::string("STUFF") + elemMapPrefix + std::string("TESTPOSTFIXTEST"));
|
||||
|
||||
// Arrange
|
||||
Data::MappedName mappedName2("TEST"); // If mappedName does not have a postfix and is a valid
|
||||
// indexedName: prefix is not added
|
||||
|
||||
// Act
|
||||
mappedName2.appendToBufferWithPrefix(buffer);
|
||||
|
||||
// Assert
|
||||
EXPECT_EQ(
|
||||
buffer,
|
||||
std::string("STUFF") + elemMapPrefix + std::string("TESTPOSTFIXTEST")
|
||||
+ /*missing prefix*/ std::string("TEST")
|
||||
);
|
||||
}
|
||||
|
||||
TEST(MappedName, toPrefixedString)
|
||||
{
|
||||
// Arrange
|
||||
Data::MappedName mappedName(Data::MappedName("TEST"), "POSTFIXTEST");
|
||||
std::string buffer("STUFF");
|
||||
std::string elemMapPrefix = Data::ELEMENT_MAP_PREFIX;
|
||||
|
||||
// Act
|
||||
buffer += mappedName.toPrefixedString();
|
||||
|
||||
// Assert
|
||||
EXPECT_EQ(buffer, std::string("STUFF") + elemMapPrefix + std::string("TESTPOSTFIXTEST"));
|
||||
|
||||
// Arrange
|
||||
Data::MappedName mappedName2("TEST"); // If mappedName does not have a postfix and is a valid
|
||||
// indexedName: prefix is not added
|
||||
|
||||
// Act
|
||||
buffer += mappedName2.toPrefixedString();
|
||||
|
||||
// Assert
|
||||
EXPECT_EQ(
|
||||
buffer,
|
||||
std::string("STUFF") + elemMapPrefix + std::string("TESTPOSTFIXTEST")
|
||||
+ /*missing prefix*/ std::string("TEST")
|
||||
);
|
||||
}
|
||||
|
||||
TEST(MappedName, toBytes)
|
||||
{
|
||||
// Arrange
|
||||
Data::MappedName mappedName(Data::MappedName("TEST"), "POSTFIXTEST");
|
||||
|
||||
// Act & Assert
|
||||
EXPECT_EQ(mappedName.toBytes(), QByteArray("TESTPOSTFIXTEST"));
|
||||
}
|
||||
|
||||
TEST(MappedName, compare)
|
||||
{
|
||||
// Arrange
|
||||
Data::MappedName mappedName1(Data::MappedName("TEST"), "POSTFIXTEST");
|
||||
Data::MappedName mappedName2(Data::MappedName("TEST"), "POSTFIXTEST");
|
||||
Data::MappedName mappedName3(Data::MappedName("TESTPOST"), "FIXTEST");
|
||||
Data::MappedName mappedName4(Data::MappedName("THIS"), "ISDIFFERENT");
|
||||
Data::MappedName mappedName5(Data::MappedName("SH"), "ORTHER");
|
||||
Data::MappedName mappedName6(Data::MappedName("VERYVERYVERY"), "VERYMUCHLONGER");
|
||||
|
||||
// Act & Assert
|
||||
EXPECT_EQ(mappedName1.compare(mappedName1), 0);
|
||||
EXPECT_EQ(mappedName1.compare(mappedName2), 0);
|
||||
EXPECT_EQ(mappedName1.compare(mappedName3), 0);
|
||||
EXPECT_EQ(mappedName1.compare(mappedName4), -1);
|
||||
EXPECT_EQ(mappedName1.compare(mappedName5), 1);
|
||||
EXPECT_EQ(mappedName1.compare(mappedName6), -1);
|
||||
|
||||
EXPECT_EQ(mappedName1 < mappedName1, false);
|
||||
EXPECT_EQ(mappedName1 < mappedName2, false);
|
||||
EXPECT_EQ(mappedName1 < mappedName3, false);
|
||||
EXPECT_EQ(mappedName1 < mappedName4, true);
|
||||
EXPECT_EQ(mappedName1 < mappedName5, false);
|
||||
EXPECT_EQ(mappedName1 < mappedName6, true);
|
||||
}
|
||||
|
||||
TEST(MappedName, subscriptOperator)
|
||||
{
|
||||
// Arrange
|
||||
Data::MappedName mappedName(Data::MappedName("TEST"), "POSTFIXTEST");
|
||||
|
||||
// Act & Assert
|
||||
EXPECT_EQ(mappedName[0], 'T');
|
||||
EXPECT_EQ(mappedName[1], 'E');
|
||||
EXPECT_EQ(mappedName[2], 'S');
|
||||
EXPECT_EQ(mappedName[3], 'T');
|
||||
EXPECT_EQ(mappedName[4], 'P');
|
||||
EXPECT_EQ(mappedName[5], 'O');
|
||||
EXPECT_EQ(mappedName[6], 'S');
|
||||
EXPECT_EQ(mappedName[7], 'T');
|
||||
EXPECT_EQ(mappedName[8], 'F');
|
||||
EXPECT_EQ(mappedName[9], 'I');
|
||||
}
|
||||
|
||||
TEST(MappedName, copy)
|
||||
{
|
||||
// Arrange
|
||||
Data::MappedName mappedName(Data::MappedName("TEST"), "POSTFIXTEST");
|
||||
|
||||
// Act
|
||||
Data::MappedName mappedName2 = mappedName.copy();
|
||||
|
||||
// Assert
|
||||
EXPECT_EQ(mappedName, mappedName2);
|
||||
}
|
||||
|
||||
TEST(MappedName, compact)
|
||||
{
|
||||
// Arrange
|
||||
Data::MappedName mappedName = Data::MappedName::fromRawData("TESTTEST", 8);
|
||||
|
||||
// Act
|
||||
mappedName.compact();
|
||||
|
||||
// Assert
|
||||
EXPECT_EQ(mappedName.isRaw(), false);
|
||||
EXPECT_EQ(mappedName.empty(), false);
|
||||
EXPECT_EQ(mappedName.size(), 8);
|
||||
EXPECT_EQ(mappedName.dataBytes(), QByteArray("TESTTEST", 8));
|
||||
EXPECT_EQ(mappedName.postfixBytes(), QByteArray());
|
||||
}
|
||||
|
||||
TEST(MappedName, boolOperator)
|
||||
{
|
||||
// Arrange
|
||||
Data::MappedName mappedName;
|
||||
|
||||
// Act & Assert
|
||||
EXPECT_EQ((bool)mappedName, false);
|
||||
|
||||
// Arrange
|
||||
mappedName.append("TEST");
|
||||
|
||||
// Act & Assert
|
||||
EXPECT_EQ((bool)mappedName, true);
|
||||
}
|
||||
|
||||
TEST(MappedName, clear)
|
||||
{
|
||||
// Arrange
|
||||
Data::MappedName mappedName(Data::MappedName("TEST"), "POSTFIXTEST");
|
||||
|
||||
// Act
|
||||
mappedName.clear();
|
||||
|
||||
// Assert
|
||||
EXPECT_EQ(mappedName.empty(), true);
|
||||
}
|
||||
|
||||
TEST(MappedName, find)
|
||||
{
|
||||
// Arrange
|
||||
Data::MappedName mappedName(Data::MappedName("TEST"), "POSTFIXTEST");
|
||||
|
||||
// Act & Assert
|
||||
EXPECT_EQ(mappedName.find(nullptr), -1);
|
||||
EXPECT_EQ(mappedName.find(""), 0);
|
||||
EXPECT_EQ(mappedName.find(std::string("")), 0);
|
||||
EXPECT_EQ(mappedName.find("TEST"), 0);
|
||||
EXPECT_EQ(mappedName.find("STPO"), -1); // sentence must be fully contained in data or postfix
|
||||
EXPECT_EQ(mappedName.find("POST"), 4);
|
||||
EXPECT_EQ(mappedName.find("POST", 4), 4);
|
||||
EXPECT_EQ(mappedName.find("POST", 5), -1);
|
||||
|
||||
EXPECT_EQ(mappedName.rfind("ST"), 13);
|
||||
EXPECT_EQ(mappedName.rfind("ST", 15), 13);
|
||||
EXPECT_EQ(mappedName.rfind("ST", 14), 13);
|
||||
EXPECT_EQ(mappedName.rfind("ST", 13), 13);
|
||||
EXPECT_EQ(mappedName.rfind("ST", 12), 6);
|
||||
EXPECT_EQ(mappedName.rfind("ST", 11), 6);
|
||||
EXPECT_EQ(mappedName.rfind("ST", 10), 6);
|
||||
EXPECT_EQ(mappedName.rfind("ST", 9), 6);
|
||||
EXPECT_EQ(mappedName.rfind("ST", 8), 6);
|
||||
EXPECT_EQ(mappedName.rfind("ST", 7), 6);
|
||||
EXPECT_EQ(mappedName.rfind("ST", 6), 6);
|
||||
EXPECT_EQ(mappedName.rfind("ST", 5), 2);
|
||||
EXPECT_EQ(mappedName.rfind("ST", 4), 2);
|
||||
EXPECT_EQ(mappedName.rfind("ST", 3), 2);
|
||||
EXPECT_EQ(mappedName.rfind("ST", 2), 2);
|
||||
EXPECT_EQ(mappedName.rfind("ST", 1), -1);
|
||||
EXPECT_EQ(mappedName.rfind("ST", 0), -1);
|
||||
}
|
||||
|
||||
TEST(MappedName, rfind)
|
||||
{
|
||||
// Arrange
|
||||
Data::MappedName mappedName(Data::MappedName("TEST"), "POSTFIXTEST");
|
||||
|
||||
// Act & Assert
|
||||
EXPECT_EQ(mappedName.rfind(nullptr), -1);
|
||||
EXPECT_EQ(mappedName.rfind(""), mappedName.size());
|
||||
EXPECT_EQ(mappedName.rfind(std::string("")), mappedName.size());
|
||||
EXPECT_EQ(mappedName.rfind("TEST"), 11);
|
||||
EXPECT_EQ(mappedName.rfind("STPO"), -1); // sentence must be fully contained in data or postfix
|
||||
EXPECT_EQ(mappedName.rfind("POST"), 4);
|
||||
EXPECT_EQ(mappedName.rfind("POST", 4), 4);
|
||||
EXPECT_EQ(mappedName.rfind("POST", 3), -1);
|
||||
|
||||
EXPECT_EQ(mappedName.rfind("ST"), 13);
|
||||
EXPECT_EQ(mappedName.rfind("ST", 0), -1);
|
||||
EXPECT_EQ(mappedName.rfind("ST", 1), -1);
|
||||
EXPECT_EQ(mappedName.rfind("ST", 2), 2);
|
||||
EXPECT_EQ(mappedName.rfind("ST", 3), 2);
|
||||
EXPECT_EQ(mappedName.rfind("ST", 4), 2);
|
||||
EXPECT_EQ(mappedName.rfind("ST", 5), 2);
|
||||
EXPECT_EQ(mappedName.rfind("ST", 6), 6);
|
||||
EXPECT_EQ(mappedName.rfind("ST", 7), 6);
|
||||
EXPECT_EQ(mappedName.rfind("ST", 8), 6);
|
||||
EXPECT_EQ(mappedName.rfind("ST", 9), 6);
|
||||
EXPECT_EQ(mappedName.rfind("ST", 10), 6);
|
||||
EXPECT_EQ(mappedName.rfind("ST", 11), 6);
|
||||
EXPECT_EQ(mappedName.rfind("ST", 12), 6);
|
||||
EXPECT_EQ(mappedName.rfind("ST", 13), 13);
|
||||
EXPECT_EQ(mappedName.rfind("ST", 14), 13);
|
||||
EXPECT_EQ(mappedName.rfind("ST", 15), 13);
|
||||
}
|
||||
|
||||
TEST(MappedName, endswith)
|
||||
{
|
||||
// Arrange
|
||||
Data::MappedName mappedName("TEST");
|
||||
|
||||
// Act & Assert
|
||||
EXPECT_EQ(mappedName.endsWith(nullptr), false);
|
||||
EXPECT_EQ(mappedName.endsWith("TEST"), true);
|
||||
EXPECT_EQ(mappedName.endsWith(std::string("TEST")), true);
|
||||
EXPECT_EQ(mappedName.endsWith("WASD"), false);
|
||||
|
||||
// Arrange
|
||||
mappedName.append("POSTFIX");
|
||||
|
||||
// Act & Assert
|
||||
EXPECT_EQ(mappedName.endsWith(nullptr), false);
|
||||
EXPECT_EQ(mappedName.endsWith("TEST"), false);
|
||||
EXPECT_EQ(mappedName.endsWith("FIX"), true);
|
||||
}
|
||||
|
||||
TEST(MappedName, startsWith)
|
||||
{
|
||||
// Arrange
|
||||
Data::MappedName mappedName;
|
||||
|
||||
// Act & Assert
|
||||
EXPECT_EQ(mappedName.startsWith(nullptr), false);
|
||||
EXPECT_EQ(mappedName.startsWith(QByteArray()), true);
|
||||
EXPECT_EQ(mappedName.startsWith(""), true);
|
||||
EXPECT_EQ(mappedName.startsWith(std::string("")), true);
|
||||
EXPECT_EQ(mappedName.startsWith("WASD"), false);
|
||||
|
||||
// Arrange
|
||||
mappedName.append("TEST");
|
||||
|
||||
// Act & Assert
|
||||
EXPECT_EQ(mappedName.startsWith(nullptr), false);
|
||||
EXPECT_EQ(mappedName.startsWith(QByteArray()), true);
|
||||
EXPECT_EQ(mappedName.startsWith("TEST"), true);
|
||||
EXPECT_EQ(mappedName.startsWith(std::string("TEST")), true);
|
||||
EXPECT_EQ(mappedName.startsWith("WASD"), false);
|
||||
}
|
||||
|
||||
TEST(MappedName, findTagInElementNameHexPositiveIndexNonrecursive)
|
||||
{
|
||||
// The non-recursive version will find just the last tag, prefixed by the POSTFIX_TAG (";:H").
|
||||
// It consists of a tag (stored in hexadecimal) and a length (also stored in hex), separated by
|
||||
// a colon. In this example, we expect the get ;:H1b:10,F as our element, which is a tag of
|
||||
// 0x1b and an indicated length of 0x10 (16 bytes). So the output length is the position of the
|
||||
// tag (36) minus the indicated length, giving 20.
|
||||
|
||||
// Arrange
|
||||
Data::MappedName mappedName("#94;:G0;XTR;:H19:8,F;:H1a,F;BND:-1:0;:H1b:10,F");
|
||||
long tagOutput {0};
|
||||
int lenOutput {0};
|
||||
std::string postfix;
|
||||
char type {0};
|
||||
|
||||
// Act
|
||||
int result = mappedName.findTagInElementName(&tagOutput, &lenOutput, &postfix, &type, false, false);
|
||||
|
||||
// Assert
|
||||
EXPECT_EQ(result, 36); // The location of the tag
|
||||
EXPECT_EQ(tagOutput, 0x1b); // The tag
|
||||
EXPECT_EQ(lenOutput, 20); // The calculated length based on the tag's length parameter
|
||||
EXPECT_EQ(postfix, ";:H1b:10,F");
|
||||
EXPECT_EQ(type, 'F'); // F=Face
|
||||
}
|
||||
|
||||
TEST(MappedName, findTagInElementNameDecPositiveIndexNonrecursive)
|
||||
{
|
||||
// Test backwards compatibility with the older style decimal tag storage.
|
||||
|
||||
// Arrange
|
||||
Data::MappedName mappedName("#94;:G0;XTR;:T19:8,F;:T26,F;BND:-1:0;:T27:16,F");
|
||||
long tagOutput {0};
|
||||
int lenOutput {0};
|
||||
std::string postfix;
|
||||
char type {0};
|
||||
|
||||
// Act
|
||||
int result = mappedName.findTagInElementName(&tagOutput, &lenOutput, &postfix, &type, false, false);
|
||||
|
||||
// Assert
|
||||
EXPECT_EQ(result, 36); // The location of the tag
|
||||
EXPECT_EQ(tagOutput, 27); // The tag
|
||||
EXPECT_EQ(lenOutput, 16); // The specified length
|
||||
EXPECT_EQ(postfix, ";:T27:16,F");
|
||||
EXPECT_EQ(type, 'F'); // F=Face
|
||||
}
|
||||
|
||||
TEST(MappedName, findTagInElementNameHexNegativeIndexNonrecursive)
|
||||
{
|
||||
// Test handling a negative index that is flipped to positive
|
||||
|
||||
// Arrange
|
||||
Data::MappedName mappedName("#94;:G0;XTR;:H19:8,F;:H1a,F;BND:-1:0;:H-1b:10,F");
|
||||
long tagOutput {0};
|
||||
int lenOutput {0};
|
||||
std::string postfix;
|
||||
char type {0};
|
||||
|
||||
// Act
|
||||
int result = mappedName.findTagInElementName(&tagOutput, &lenOutput, &postfix, &type, false, false);
|
||||
|
||||
// Assert
|
||||
EXPECT_EQ(result, 36); // The location of the tag
|
||||
EXPECT_EQ(tagOutput, 0x1b); // The tag is returned positive, even though it was input negative
|
||||
EXPECT_EQ(lenOutput, 20); // The calculated length based on the tag's length parameter
|
||||
EXPECT_EQ(postfix, ";:H-1b:10,F");
|
||||
EXPECT_EQ(type, 'F'); // F=Face
|
||||
}
|
||||
|
||||
TEST(MappedName, findTagInElementNameHexExpectedNegativeIndexNonrecursive)
|
||||
{
|
||||
// Test handling an untransformed negative index
|
||||
|
||||
// Arrange
|
||||
Data::MappedName mappedName("#94;:G0;XTR;:H19:8,F;:H1a,F;BND:-1:0;:H-1b:10,F");
|
||||
long tagOutput {0};
|
||||
int lenOutput {0};
|
||||
std::string postfix;
|
||||
char type {0};
|
||||
|
||||
// Act
|
||||
int result = mappedName.findTagInElementName(&tagOutput, &lenOutput, &postfix, &type, true, false);
|
||||
|
||||
// Assert
|
||||
EXPECT_EQ(result, 36); // The location of the tag
|
||||
EXPECT_EQ(tagOutput, -0x1b); // The tag is returned negative
|
||||
EXPECT_EQ(lenOutput, 20); // The calculated length based on the tag's length parameter
|
||||
EXPECT_EQ(postfix, ";:H-1b:10,F");
|
||||
EXPECT_EQ(type, 'F'); // F=Face
|
||||
}
|
||||
|
||||
TEST(MappedName, findTagInElementNameRecursive)
|
||||
{
|
||||
// Test the recursive resolution of the name
|
||||
|
||||
// Arrange
|
||||
Data::MappedName mappedName("#94;:G0;XTR;:H19:8,F;:H1a,F;BND:-1:0;:H1b:10,F");
|
||||
long tagOutput {0};
|
||||
int lenOutput {0};
|
||||
std::string postfix;
|
||||
char type {0};
|
||||
|
||||
// Act
|
||||
int result = mappedName.findTagInElementName(&tagOutput, &lenOutput, &postfix, &type, false, true);
|
||||
|
||||
// Assert
|
||||
EXPECT_EQ(result, 36); // The location of the tag
|
||||
EXPECT_EQ(tagOutput, 0x1b); // The tag
|
||||
EXPECT_EQ(lenOutput, 27); // Now includes the next tag, from the recursive search
|
||||
EXPECT_EQ(postfix, ";:H1b:10,F");
|
||||
EXPECT_EQ(type, 'F'); // F=Face
|
||||
}
|
||||
|
||||
TEST(MappedName, hash)
|
||||
{
|
||||
// Arrange
|
||||
Data::MappedName mappedName(Data::MappedName("TEST"), "POSTFIXTEST");
|
||||
|
||||
// Act & Assert
|
||||
EXPECT_EQ(mappedName.hash(), qHash(QByteArray("TEST"), qHash(QByteArray("POSTFIXTEST"))));
|
||||
}
|
||||
|
||||
// NOLINTEND(readability-magic-numbers)
|
||||
239
tests/src/App/Metadata.cpp
Normal file
239
tests/src/App/Metadata.cpp
Normal file
@@ -0,0 +1,239 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
/**************************************************************************
|
||||
* *
|
||||
* Copyright (c) 2021-2023 FreeCAD Project Association *
|
||||
* *
|
||||
* This file is part of FreeCAD. *
|
||||
* *
|
||||
* FreeCAD is free software: you can redistribute it and/or modify it *
|
||||
* under the terms of the GNU Lesser General Public License as *
|
||||
* published by the Free Software Foundation, either version 2.1 of the *
|
||||
* License, or (at your option) any later version. *
|
||||
* *
|
||||
* FreeCAD is distributed in the hope that it will be useful, but *
|
||||
* WITHOUT ANY WARRANTY; without even the implied warranty of *
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
|
||||
* Lesser General Public License for more details. *
|
||||
* *
|
||||
* You should have received a copy of the GNU Lesser General Public *
|
||||
* License along with FreeCAD. If not, see *
|
||||
* <https://www.gnu.org/licenses/>. *
|
||||
* *
|
||||
***************************************************************************/
|
||||
|
||||
// NOLINTNEXTLINE
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include "App/Metadata.h"
|
||||
#include <xercesc/util/PlatformUtils.hpp>
|
||||
|
||||
// NOLINTBEGIN(readability-named-parameter)
|
||||
|
||||
TEST(ContactTest, ContactDefaultConstruction)
|
||||
{
|
||||
auto contact = App::Meta::Contact();
|
||||
ASSERT_EQ(contact.name, "");
|
||||
ASSERT_EQ(contact.email, "");
|
||||
}
|
||||
|
||||
TEST(ContactTest, ContactParameterConstruction)
|
||||
{
|
||||
auto contact = App::Meta::Contact("Name", "email@some.com");
|
||||
ASSERT_EQ(contact.name, "Name");
|
||||
ASSERT_EQ(contact.email, "email@some.com");
|
||||
}
|
||||
|
||||
TEST(ContactTest, ContactNullDomNodeConstruction)
|
||||
{
|
||||
auto contact = App::Meta::Contact(nullptr);
|
||||
ASSERT_EQ(contact.name, "");
|
||||
ASSERT_EQ(contact.email, "");
|
||||
}
|
||||
|
||||
TEST(ContactTest, ContactOperatorEquality)
|
||||
{
|
||||
auto contact1 = App::Meta::Contact("Name", "Email");
|
||||
auto contact2 = App::Meta::Contact("Name", "Email");
|
||||
auto contact3 = App::Meta::Contact("NotName", "Email");
|
||||
auto contact4 = App::Meta::Contact("Name", "NotEmail");
|
||||
ASSERT_TRUE(contact1 == contact2);
|
||||
ASSERT_FALSE(contact1 == contact3);
|
||||
ASSERT_FALSE(contact1 == contact4);
|
||||
}
|
||||
|
||||
TEST(LicenseTest, LicenseDefaultConstruction)
|
||||
{
|
||||
auto contact = App::Meta::License();
|
||||
ASSERT_EQ(contact.name, "");
|
||||
ASSERT_EQ(contact.file, "");
|
||||
}
|
||||
|
||||
TEST(LicenseTest, LicenseParameterConstruction)
|
||||
{
|
||||
auto contact = App::Meta::License("Name", "path/to/file");
|
||||
ASSERT_EQ(contact.name, "Name");
|
||||
ASSERT_EQ(contact.file, "path/to/file");
|
||||
}
|
||||
|
||||
TEST(LicenseTest, LicenseNullDomNodeConstruction)
|
||||
{
|
||||
auto contact = App::Meta::License(nullptr);
|
||||
ASSERT_EQ(contact.name, "");
|
||||
ASSERT_EQ(contact.file, "");
|
||||
}
|
||||
|
||||
TEST(LicenseTest, LicenseOperatorEquality)
|
||||
{
|
||||
auto license1 = App::Meta::License("Name", "path/to/file");
|
||||
auto license2 = App::Meta::License("Name", "path/to/file");
|
||||
auto license3 = App::Meta::License("NotName", "path/to/file");
|
||||
auto license4 = App::Meta::License("Name", "not/path/to/file");
|
||||
ASSERT_TRUE(license1 == license2);
|
||||
ASSERT_FALSE(license1 == license3);
|
||||
ASSERT_FALSE(license1 == license4);
|
||||
}
|
||||
|
||||
TEST(UrlTest, UrlDefaultConstruction)
|
||||
{
|
||||
auto url = App::Meta::Url();
|
||||
ASSERT_EQ(url.location, "");
|
||||
ASSERT_EQ(url.type, App::Meta::UrlType::website);
|
||||
}
|
||||
|
||||
TEST(UrlTest, UrlParameterConstruction)
|
||||
{
|
||||
auto url = App::Meta::Url("https://some.url", App::Meta::UrlType::documentation);
|
||||
ASSERT_EQ(url.location, "https://some.url");
|
||||
ASSERT_EQ(url.type, App::Meta::UrlType::documentation);
|
||||
}
|
||||
|
||||
TEST(UrlTest, UrlNullDomNodeConstruction)
|
||||
{
|
||||
auto url = App::Meta::Url(nullptr);
|
||||
ASSERT_EQ(url.location, "");
|
||||
}
|
||||
|
||||
TEST(UrlTest, UrlOperatorEquality)
|
||||
{
|
||||
auto url1 = App::Meta::Url("https://some.url", App::Meta::UrlType::documentation);
|
||||
auto url2 = App::Meta::Url("https://some.url", App::Meta::UrlType::documentation);
|
||||
auto url3 = App::Meta::Url("https://not.some.url", App::Meta::UrlType::documentation);
|
||||
auto url4 = App::Meta::Url("https://some.url", App::Meta::UrlType::website);
|
||||
ASSERT_TRUE(url1 == url2);
|
||||
ASSERT_FALSE(url1 == url3);
|
||||
ASSERT_FALSE(url1 == url4);
|
||||
}
|
||||
|
||||
TEST(VersionTest, VersionDefaultConstruction)
|
||||
{
|
||||
auto version = App::Meta::Version();
|
||||
ASSERT_EQ(version.major, 0);
|
||||
ASSERT_EQ(version.minor, 0);
|
||||
ASSERT_EQ(version.patch, 0);
|
||||
ASSERT_EQ(version.suffix, "");
|
||||
}
|
||||
|
||||
TEST(VersionTest, VersionParameterConstruction)
|
||||
{
|
||||
auto version = App::Meta::Version(1, 2, 3, "delta");
|
||||
ASSERT_EQ(version.major, 1);
|
||||
ASSERT_EQ(version.minor, 2);
|
||||
ASSERT_EQ(version.patch, 3);
|
||||
ASSERT_EQ(version.suffix, "delta");
|
||||
}
|
||||
|
||||
TEST(VersionTest, VersionStringConstruction)
|
||||
{
|
||||
auto version = App::Meta::Version("1.2.3delta");
|
||||
ASSERT_EQ(version.major, 1);
|
||||
ASSERT_EQ(version.minor, 2);
|
||||
ASSERT_EQ(version.patch, 3);
|
||||
ASSERT_EQ(version.suffix, "delta");
|
||||
}
|
||||
|
||||
TEST(VersionTest, VersionOperatorEqual)
|
||||
{
|
||||
auto version1 = App::Meta::Version(1, 2, 3, "delta");
|
||||
auto version2 = App::Meta::Version(1, 2, 3, "delta");
|
||||
auto version3 = App::Meta::Version(1, 3, 3, "delta");
|
||||
auto version4 = App::Meta::Version(1, 2, 4, "delta");
|
||||
auto version5 = App::Meta::Version(1, 2, 3, "gamma");
|
||||
ASSERT_EQ(version1, version2);
|
||||
ASSERT_NE(version1, version3);
|
||||
ASSERT_NE(version1, version4);
|
||||
ASSERT_NE(version1, version5);
|
||||
}
|
||||
|
||||
TEST(VersionTest, VersionOperatorComparison)
|
||||
{
|
||||
auto version_2_3_4_delta = App::Meta::Version(2, 3, 4, "delta");
|
||||
auto version_1_3_4_delta = App::Meta::Version(1, 3, 4, "delta");
|
||||
auto version_3_3_4_delta = App::Meta::Version(3, 3, 4, "delta");
|
||||
auto version_2_2_4_delta = App::Meta::Version(2, 2, 4, "delta");
|
||||
auto version_2_4_4_delta = App::Meta::Version(2, 4, 4, "delta");
|
||||
auto version_2_3_3_delta = App::Meta::Version(2, 3, 3, "delta");
|
||||
// NOLINTNEXTLINE Five is not really a "magic number" in this test
|
||||
auto version_2_3_5_delta = App::Meta::Version(2, 3, 5, "delta");
|
||||
auto version_2_3_4_epsilon = App::Meta::Version(2, 3, 4, "epsilon");
|
||||
auto version_2_3_4_beta = App::Meta::Version(2, 3, 4, "beta");
|
||||
ASSERT_GT(version_2_3_4_delta, version_1_3_4_delta);
|
||||
ASSERT_LT(version_2_3_4_delta, version_3_3_4_delta);
|
||||
ASSERT_GT(version_2_3_4_delta, version_2_2_4_delta);
|
||||
ASSERT_LT(version_2_3_4_delta, version_2_4_4_delta);
|
||||
ASSERT_GT(version_2_3_4_delta, version_2_3_3_delta);
|
||||
ASSERT_LT(version_2_3_4_delta, version_2_3_5_delta);
|
||||
ASSERT_GT(version_2_3_4_delta, version_2_3_4_beta);
|
||||
ASSERT_LT(version_2_3_4_delta, version_2_3_4_epsilon);
|
||||
}
|
||||
|
||||
// TODO: Test Dependency
|
||||
// TODO: Test GenericMetadata
|
||||
|
||||
class MetadataTest: public ::testing::Test
|
||||
{
|
||||
protected:
|
||||
void SetUp() override
|
||||
{
|
||||
XERCES_CPP_NAMESPACE::XMLPlatformUtils::Initialize();
|
||||
}
|
||||
void TearDown() override
|
||||
{
|
||||
XERCES_CPP_NAMESPACE::XMLPlatformUtils::Terminate();
|
||||
}
|
||||
std::string GivenSimpleMetadataXMLString()
|
||||
{
|
||||
std::ostringstream stream;
|
||||
stream << "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"no\" ?>\n"
|
||||
<< "<package format=\"1\" xmlns=\"https://wiki.freecad.org/Package_Metadata\">\n"
|
||||
<< " <name>" << _name << "</name>\n"
|
||||
<< " <description>" << _description << "</description>\n"
|
||||
<< " <version>" << _version << "</version>\n"
|
||||
<< " <date>2022-01-07</date>\n"
|
||||
<< " <url type=\"repository\" "
|
||||
"branch=\"main\">https://github.com/FreeCAD/FreeCAD</url>\n"
|
||||
<< "</package>";
|
||||
return stream.str();
|
||||
}
|
||||
|
||||
void AssertMetadataMatches(App::Metadata& testObject)
|
||||
{
|
||||
ASSERT_EQ(testObject.name(), _name);
|
||||
ASSERT_EQ(testObject.description(), _description);
|
||||
ASSERT_EQ(testObject.version(), App::Meta::Version(_version));
|
||||
}
|
||||
|
||||
private:
|
||||
std::string _name = "TestAddon";
|
||||
std::string _description = "A package.xml file for unit testing.";
|
||||
std::string _version = "1.2.3beta";
|
||||
};
|
||||
|
||||
TEST_F(MetadataTest, MetadataInMemoryConstruction)
|
||||
{
|
||||
auto xml = GivenSimpleMetadataXMLString();
|
||||
auto testObject = App::Metadata(std::string {xml});
|
||||
AssertMetadataMatches(testObject);
|
||||
}
|
||||
|
||||
// NOLINTEND(readability-named-parameter)
|
||||
134
tests/src/App/ProjectFile.cpp
Normal file
134
tests/src/App/ProjectFile.cpp
Normal file
@@ -0,0 +1,134 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include "InitApplication.h"
|
||||
#include <App/ProjectFile.h>
|
||||
#include <App/InventorObject.h>
|
||||
#include <Base/Stream.h>
|
||||
#include <Base/Type.h>
|
||||
|
||||
// NOLINTBEGIN
|
||||
class ProjectFileTest: public ::testing::Test
|
||||
{
|
||||
protected:
|
||||
static void SetUpTestSuite()
|
||||
{
|
||||
tests::initApplication();
|
||||
}
|
||||
void SetUp() override
|
||||
{}
|
||||
void TearDown() override
|
||||
{}
|
||||
std::string fileName() const
|
||||
{
|
||||
std::string resDir(DATADIR);
|
||||
resDir.append("/tests/ProjectTest.FCStd");
|
||||
return resDir;
|
||||
}
|
||||
std::string imageFileName() const
|
||||
{
|
||||
return {"thumbnails/Thumbnail.png"};
|
||||
}
|
||||
std::list<std::string> getInventorObjects() const
|
||||
{
|
||||
return {"Body"};
|
||||
}
|
||||
Base::Type getInventorId() const
|
||||
{
|
||||
return App::InventorObject::getClassTypeId();
|
||||
}
|
||||
};
|
||||
|
||||
TEST_F(ProjectFileTest, loadInvalid)
|
||||
{
|
||||
App::ProjectFile proj("non-existing.FCStd");
|
||||
EXPECT_FALSE(proj.loadDocument());
|
||||
}
|
||||
|
||||
TEST_F(ProjectFileTest, loadDocument)
|
||||
{
|
||||
App::ProjectFile proj(fileName());
|
||||
EXPECT_TRUE(proj.loadDocument());
|
||||
}
|
||||
|
||||
TEST_F(ProjectFileTest, getObjects)
|
||||
{
|
||||
App::ProjectFile proj(fileName());
|
||||
EXPECT_TRUE(proj.loadDocument());
|
||||
std::list<App::ProjectFile::Object> objs = proj.getObjects();
|
||||
EXPECT_EQ(objs.size(), 1);
|
||||
}
|
||||
|
||||
TEST_F(ProjectFileTest, getPropertyFiles)
|
||||
{
|
||||
App::ProjectFile proj(fileName());
|
||||
EXPECT_TRUE(proj.loadDocument());
|
||||
std::list<App::ProjectFile::PropertyFile> files = proj.getPropertyFiles("Body");
|
||||
EXPECT_EQ(files.size(), 0);
|
||||
}
|
||||
|
||||
TEST_F(ProjectFileTest, getMetadata)
|
||||
{
|
||||
App::ProjectFile proj(fileName());
|
||||
EXPECT_TRUE(proj.loadDocument());
|
||||
auto metadata = proj.getMetadata();
|
||||
EXPECT_EQ(std::string("No comment"), metadata.comment);
|
||||
EXPECT_EQ(std::string("John Doe & Jane Roe"), metadata.company);
|
||||
EXPECT_EQ(std::string("John Doe"), metadata.createdBy);
|
||||
EXPECT_EQ(std::string("2024-03-08T10:53:31Z"), metadata.creationDate);
|
||||
EXPECT_EQ(std::string("ProjectTest"), metadata.label);
|
||||
EXPECT_EQ(std::string("John Doe"), metadata.lastModifiedBy);
|
||||
EXPECT_EQ(std::string("2024-03-08T11:03:44Z"), metadata.lastModifiedDate);
|
||||
EXPECT_EQ(std::string("Public Domain"), metadata.license);
|
||||
EXPECT_EQ(std::string("https://en.wikipedia.org/wiki/Public_domain"), metadata.licenseURL);
|
||||
EXPECT_EQ(std::string("0.22R36329 (Git)"), metadata.programVersion);
|
||||
EXPECT_EQ(std::string("6847155d-dcc3-4dea-92c9-c4d32d6a3055"), metadata.uuid);
|
||||
}
|
||||
|
||||
TEST_F(ProjectFileTest, getObjectsOfType)
|
||||
{
|
||||
App::ProjectFile proj(fileName());
|
||||
EXPECT_TRUE(proj.loadDocument());
|
||||
std::list<std::string> objs = proj.getObjectsOfType(getInventorId());
|
||||
EXPECT_EQ(objs, getInventorObjects());
|
||||
}
|
||||
|
||||
TEST_F(ProjectFileTest, restoreObject)
|
||||
{
|
||||
App::ProjectFile proj(fileName());
|
||||
EXPECT_TRUE(proj.loadDocument());
|
||||
App::InventorObject obj;
|
||||
EXPECT_TRUE(proj.restoreObject("Body", &obj, false));
|
||||
EXPECT_EQ(obj.Label.getStrValue(), std::string("Body"));
|
||||
}
|
||||
|
||||
TEST_F(ProjectFileTest, getTypeId)
|
||||
{
|
||||
App::ProjectFile proj(fileName());
|
||||
EXPECT_TRUE(proj.loadDocument());
|
||||
Base::Type id = proj.getTypeId("Body");
|
||||
EXPECT_EQ(id, getInventorId());
|
||||
}
|
||||
|
||||
TEST_F(ProjectFileTest, getThumbnailBuffer)
|
||||
{
|
||||
App::ProjectFile proj(fileName());
|
||||
std::stringstream str;
|
||||
proj.readInputFileDirect(imageFileName(), str);
|
||||
std::string buffer = str.str();
|
||||
EXPECT_EQ(buffer.size(), 2857);
|
||||
}
|
||||
|
||||
TEST_F(ProjectFileTest, getThumbnailFile)
|
||||
{
|
||||
App::ProjectFile proj(fileName());
|
||||
Base::FileInfo fi(Base::FileInfo::getTempFileName());
|
||||
Base::ofstream file(fi, std::ios::out | std::ios::binary);
|
||||
proj.readInputFileDirect(imageFileName(), file);
|
||||
file.flush();
|
||||
file.close();
|
||||
EXPECT_EQ(fi.size(), 2857);
|
||||
fi.deleteFile();
|
||||
}
|
||||
// NOLINTEND
|
||||
441
tests/src/App/Property.cpp
Normal file
441
tests/src/App/Property.cpp
Normal file
@@ -0,0 +1,441 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
/****************************************************************************
|
||||
* Copyright (c) 2024 Werner Mayer <wmayer[at]users.sourceforge.net> *
|
||||
* Copyright (c) 2025 Pieter Hijma <info@pieterhijma.net> *
|
||||
* *
|
||||
* This file is part of the FreeCAD CAx development system. *
|
||||
* *
|
||||
* This library is free software; you can redistribute it and/or *
|
||||
* modify it under the terms of the GNU Library General Public *
|
||||
* License as published by the Free Software Foundation; either *
|
||||
* version 2 of the License, or (at your option) any later version. *
|
||||
* *
|
||||
* This library is distributed in the hope that it will be useful, *
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
|
||||
* GNU Library General Public License for more details. *
|
||||
* *
|
||||
* You should have received a copy of the GNU Library General Public *
|
||||
* License along with this library; see the file COPYING.LIB. If not, *
|
||||
* write to the Free Software Foundation, Inc., 59 Temple Place, *
|
||||
* Suite 330, Boston, MA 02111-1307, USA *
|
||||
* *
|
||||
****************************************************************************/
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include <FCConfig.h>
|
||||
|
||||
#include <Base/Writer.h>
|
||||
#include <Base/Reader.h>
|
||||
#include <Base/Interpreter.h>
|
||||
|
||||
#include <App/Application.h>
|
||||
#include <App/Document.h>
|
||||
#include <App/Expression.h>
|
||||
#include <App/ObjectIdentifier.h>
|
||||
#include <App/PropertyLinks.h>
|
||||
#include <App/PropertyStandard.h>
|
||||
#include <App/VarSet.h>
|
||||
|
||||
#include <src/App/InitApplication.h>
|
||||
|
||||
#include <xercesc/util/PlatformUtils.hpp>
|
||||
|
||||
#include "Property.h"
|
||||
|
||||
TEST(PropertyLink, TestSetValues)
|
||||
{
|
||||
App::PropertyLinkSubList prop;
|
||||
std::vector<App::DocumentObject*> objs {nullptr, nullptr};
|
||||
std::vector<const char*> subs {"Sub1", "Sub2"};
|
||||
prop.setValues(objs, subs);
|
||||
const auto& sub = prop.getSubValues();
|
||||
EXPECT_EQ(sub.size(), 2);
|
||||
EXPECT_EQ(sub[0], "Sub1");
|
||||
EXPECT_EQ(sub[1], "Sub2");
|
||||
}
|
||||
|
||||
class PropertyFloatTest: public ::testing::Test
|
||||
{
|
||||
protected:
|
||||
static void SetUpTestSuite()
|
||||
{
|
||||
XERCES_CPP_NAMESPACE::XMLPlatformUtils::Initialize();
|
||||
}
|
||||
};
|
||||
|
||||
TEST_F(PropertyFloatTest, testWriteRead)
|
||||
{
|
||||
#if defined(FC_OS_LINUX) || defined(FC_OS_BSD)
|
||||
setlocale(LC_ALL, "");
|
||||
setlocale(LC_NUMERIC, "C"); // avoid rounding of floating point numbers
|
||||
#endif
|
||||
double value = 1.2345;
|
||||
App::PropertyFloat prop;
|
||||
prop.setValue(value);
|
||||
Base::StringWriter writer;
|
||||
prop.Save(writer);
|
||||
|
||||
std::string str = "<?xml version='1.0' encoding='utf-8'?>\n";
|
||||
str.append("<Property name='Length' type='App::PropertyFloat'>\n");
|
||||
str.append(writer.getString());
|
||||
str.append("</Property>\n");
|
||||
|
||||
std::stringstream data(str);
|
||||
Base::XMLReader reader("Document.xml", data);
|
||||
App::PropertyFloat prop2;
|
||||
prop2.Restore(reader);
|
||||
EXPECT_DOUBLE_EQ(prop2.getValue(), value);
|
||||
}
|
||||
|
||||
std::string RenameProperty::_docName;
|
||||
App::Document* RenameProperty::_doc {nullptr};
|
||||
|
||||
// Tests whether we can rename a property
|
||||
TEST_F(RenameProperty, renameProperty)
|
||||
{
|
||||
// Act
|
||||
bool isRenamed = varSet->renameDynamicProperty(prop, "NewName");
|
||||
|
||||
// Assert
|
||||
EXPECT_TRUE(isRenamed);
|
||||
EXPECT_STREQ(varSet->getPropertyName(prop), "NewName");
|
||||
EXPECT_EQ(prop->getValue(), Value);
|
||||
EXPECT_EQ(varSet->getDynamicPropertyByName("Variable"), nullptr);
|
||||
EXPECT_EQ(varSet->getDynamicPropertyByName("NewName"), prop);
|
||||
}
|
||||
|
||||
// Tests whether we can rename a property from Python
|
||||
TEST_F(RenameProperty, renamePropertyPython)
|
||||
{
|
||||
// Act
|
||||
Base::Interpreter().runString(
|
||||
"App.ActiveDocument.getObject('VarSet').renameProperty('Variable', 'NewName')"
|
||||
);
|
||||
|
||||
// Assert
|
||||
EXPECT_STREQ(varSet->getPropertyName(prop), "NewName");
|
||||
EXPECT_EQ(prop->getValue(), Value);
|
||||
EXPECT_EQ(varSet->getDynamicPropertyByName("Variable"), nullptr);
|
||||
EXPECT_EQ(varSet->getDynamicPropertyByName("NewName"), prop);
|
||||
}
|
||||
|
||||
// Tests whether we can rename a property in a chain
|
||||
TEST_F(RenameProperty, renamePropertyChain)
|
||||
{
|
||||
// Act 1
|
||||
bool isRenamed = varSet->renameDynamicProperty(prop, "Name1");
|
||||
|
||||
// Assert 1
|
||||
EXPECT_TRUE(isRenamed);
|
||||
EXPECT_STREQ(varSet->getPropertyName(prop), "Name1");
|
||||
EXPECT_EQ(varSet->getDynamicPropertyByName("Variable"), nullptr);
|
||||
EXPECT_EQ(varSet->getDynamicPropertyByName("Name1"), prop);
|
||||
|
||||
// Act 2
|
||||
auto prop1 = freecad_cast<App::PropertyInteger*>(varSet->getDynamicPropertyByName("Name1"));
|
||||
isRenamed = varSet->renameDynamicProperty(prop1, "Name2");
|
||||
|
||||
// Assert 2
|
||||
EXPECT_TRUE(isRenamed);
|
||||
EXPECT_EQ(prop, prop1);
|
||||
EXPECT_STREQ(varSet->getPropertyName(prop1), "Name2");
|
||||
EXPECT_EQ(varSet->getDynamicPropertyByName("Name1"), nullptr);
|
||||
EXPECT_EQ(varSet->getDynamicPropertyByName("Name2"), prop1);
|
||||
}
|
||||
|
||||
// Tests whether we can rename a static property
|
||||
TEST_F(RenameProperty, renameStaticProperty)
|
||||
{
|
||||
// Arrange
|
||||
App::Property* prop = varSet->getPropertyByName("Label");
|
||||
|
||||
// Act
|
||||
bool isRenamed = varSet->renameDynamicProperty(prop, "MyLabel");
|
||||
|
||||
// Assert
|
||||
EXPECT_FALSE(isRenamed);
|
||||
EXPECT_STREQ(varSet->getPropertyName(prop), "Label");
|
||||
EXPECT_EQ(varSet->getDynamicPropertyByName("MyLabel"), nullptr);
|
||||
}
|
||||
|
||||
// Tests whether we can rename a static property from Python
|
||||
TEST_F(RenameProperty, renameStaticPropertyPython)
|
||||
{
|
||||
// Arrange
|
||||
App::Property* prop = varSet->getPropertyByName("Label");
|
||||
|
||||
// Act / Assert
|
||||
EXPECT_THROW(
|
||||
Base::Interpreter().runString(
|
||||
"App.ActiveDocument.getObject('VarSet006').renameProperty('Label', 'NewName')"
|
||||
),
|
||||
Base::Exception
|
||||
);
|
||||
|
||||
// Assert
|
||||
EXPECT_STREQ(varSet->getPropertyName(prop), "Label");
|
||||
EXPECT_EQ(varSet->getDynamicPropertyByName("NewName"), nullptr);
|
||||
}
|
||||
|
||||
// Tests whether we can rename a locked property
|
||||
TEST_F(RenameProperty, renameLockedProperty)
|
||||
{
|
||||
// Arrange
|
||||
prop->setStatus(App::Property::LockDynamic, true);
|
||||
|
||||
// Act / Assert
|
||||
EXPECT_THROW(varSet->renameDynamicProperty(prop, "NewName"), Base::RuntimeError);
|
||||
|
||||
// Assert
|
||||
EXPECT_STREQ(varSet->getPropertyName(prop), "Variable");
|
||||
EXPECT_EQ(prop->getValue(), Value);
|
||||
EXPECT_EQ(varSet->getDynamicPropertyByName("Variable"), prop);
|
||||
EXPECT_EQ(varSet->getDynamicPropertyByName("NewName"), nullptr);
|
||||
}
|
||||
|
||||
// Tests whether we can rename to a property that already exists
|
||||
TEST_F(RenameProperty, renameToExistingProperty)
|
||||
{
|
||||
// Arrange
|
||||
App::Property* prop2 = varSet->addDynamicProperty("App::PropertyInteger", "Variable2", "Variables");
|
||||
|
||||
// Act / Assert
|
||||
EXPECT_THROW(varSet->renameDynamicProperty(prop2, "Variable"), Base::NameError);
|
||||
|
||||
// Assert
|
||||
EXPECT_STREQ(varSet->getPropertyName(prop), "Variable");
|
||||
EXPECT_STREQ(varSet->getPropertyName(prop2), "Variable2");
|
||||
EXPECT_EQ(prop->getValue(), Value);
|
||||
EXPECT_EQ(varSet->getDynamicPropertyByName("Variable"), prop);
|
||||
EXPECT_EQ(varSet->getDynamicPropertyByName("Variable2"), prop2);
|
||||
}
|
||||
|
||||
// Tests whether we can rename to a property that is invalid
|
||||
TEST_F(RenameProperty, renameToInvalidProperty)
|
||||
{
|
||||
// Act / Assert
|
||||
EXPECT_THROW(varSet->renameDynamicProperty(prop, "0Variable"), Base::NameError);
|
||||
|
||||
// Assert
|
||||
EXPECT_STREQ(varSet->getPropertyName(prop), "Variable");
|
||||
EXPECT_EQ(prop->getValue(), Value);
|
||||
EXPECT_EQ(varSet->getDynamicPropertyByName("Variable"), prop);
|
||||
EXPECT_EQ(varSet->getDynamicPropertyByName("0Variable"), nullptr);
|
||||
}
|
||||
|
||||
// Tests whether we can rename a property that is used in an expression in the same container
|
||||
TEST_F(RenameProperty, updateExpressionSameContainer)
|
||||
{
|
||||
// Arrange
|
||||
const auto* prop2 = freecad_cast<App::PropertyInteger*>(
|
||||
varSet->addDynamicProperty("App::PropertyInteger", "Variable2", "Variables")
|
||||
);
|
||||
|
||||
App::ObjectIdentifier path(*prop2);
|
||||
std::shared_ptr<App::Expression> expr(App::Expression::parse(varSet, "Variable"));
|
||||
varSet->setExpression(path, expr);
|
||||
varSet->ExpressionEngine.execute();
|
||||
|
||||
// Assert before the rename
|
||||
EXPECT_EQ(prop->getValue(), Value);
|
||||
EXPECT_EQ(prop2->getValue(), Value);
|
||||
|
||||
// Act
|
||||
bool isRenamed = varSet->renameDynamicProperty(prop, "NewName");
|
||||
varSet->ExpressionEngine.execute();
|
||||
|
||||
// Assert after the rename
|
||||
EXPECT_TRUE(isRenamed);
|
||||
EXPECT_STREQ(varSet->getPropertyName(prop), "NewName");
|
||||
EXPECT_EQ(prop->getValue(), Value);
|
||||
EXPECT_EQ(varSet->getDynamicPropertyByName("Variable"), nullptr);
|
||||
EXPECT_EQ(varSet->getDynamicPropertyByName("NewName"), prop);
|
||||
EXPECT_EQ(prop2->getValue(), Value);
|
||||
}
|
||||
|
||||
// Tests whether we can rename a property that is used in an expression in a different container
|
||||
TEST_F(RenameProperty, updateExpressionDifferentContainer)
|
||||
{
|
||||
// Arrange
|
||||
auto* varSet2 = freecad_cast<App::VarSet*>(_doc->addObject("App::VarSet", "VarSet2"));
|
||||
const auto* prop2 = freecad_cast<App::PropertyInteger*>(
|
||||
varSet2->addDynamicProperty("App::PropertyInteger", "Variable2", "Variables")
|
||||
);
|
||||
|
||||
App::ObjectIdentifier path(*prop2);
|
||||
std::shared_ptr<App::Expression> expr(App::Expression::parse(varSet, "VarSet.Variable"));
|
||||
varSet2->setExpression(path, expr);
|
||||
varSet2->ExpressionEngine.execute();
|
||||
|
||||
// Assert before the rename
|
||||
EXPECT_EQ(prop->getValue(), Value);
|
||||
EXPECT_EQ(prop2->getValue(), Value);
|
||||
|
||||
// Act
|
||||
bool isRenamed = varSet->renameDynamicProperty(prop, "NewName");
|
||||
varSet2->ExpressionEngine.execute();
|
||||
|
||||
// Assert after the rename
|
||||
EXPECT_TRUE(isRenamed);
|
||||
EXPECT_STREQ(varSet->getPropertyName(prop), "NewName");
|
||||
EXPECT_EQ(prop->getValue(), Value);
|
||||
EXPECT_EQ(varSet->getDynamicPropertyByName("Variable"), nullptr);
|
||||
EXPECT_EQ(varSet->getDynamicPropertyByName("NewName"), prop);
|
||||
EXPECT_EQ(prop2->getValue(), Value);
|
||||
|
||||
// Tear down
|
||||
_doc->removeObject(varSet2->getNameInDocument());
|
||||
}
|
||||
|
||||
// Tests whether we can rename a property that is used in an expression in a different document
|
||||
TEST_F(RenameProperty, updateExpressionDifferentDocument)
|
||||
{
|
||||
// Arrange
|
||||
std::string docName = App::GetApplication().getUniqueDocumentName("test2");
|
||||
App::Document* doc = App::GetApplication().newDocument(docName.c_str(), "testUser");
|
||||
|
||||
auto* varSet2 = freecad_cast<App::VarSet*>(doc->addObject("App::VarSet", "VarSet2"));
|
||||
const auto* prop2 = freecad_cast<App::PropertyInteger*>(
|
||||
varSet2->addDynamicProperty("App::PropertyInteger", "Variable2", "Variables")
|
||||
);
|
||||
|
||||
App::ObjectIdentifier path(*prop2);
|
||||
std::shared_ptr<App::Expression> expr(App::Expression::parse(varSet, "test#VarSet.Variable"));
|
||||
_doc->saveAs("test.FCStd");
|
||||
doc->saveAs("test2.FCStd");
|
||||
varSet2->setExpression(path, expr);
|
||||
varSet2->ExpressionEngine.execute();
|
||||
|
||||
// Assert before the rename
|
||||
EXPECT_EQ(prop->getValue(), Value);
|
||||
EXPECT_EQ(prop2->getValue(), Value);
|
||||
|
||||
// Act
|
||||
bool isRenamed = varSet->renameDynamicProperty(prop, "NewName");
|
||||
varSet2->ExpressionEngine.execute();
|
||||
|
||||
// Assert after the rename
|
||||
EXPECT_TRUE(isRenamed);
|
||||
EXPECT_STREQ(varSet->getPropertyName(prop), "NewName");
|
||||
EXPECT_EQ(prop->getValue(), Value);
|
||||
EXPECT_EQ(varSet->getDynamicPropertyByName("Variable"), nullptr);
|
||||
EXPECT_EQ(varSet->getDynamicPropertyByName("NewName"), prop);
|
||||
EXPECT_EQ(prop2->getValue(), Value);
|
||||
|
||||
// Tear down
|
||||
doc->removeObject(varSet2->getNameInDocument());
|
||||
}
|
||||
|
||||
// Test if we can rename a property which value is the result of an expression
|
||||
TEST_F(RenameProperty, renamePropertyWithExpression)
|
||||
{
|
||||
// Arrange
|
||||
auto* prop2 = freecad_cast<App::PropertyInteger*>(
|
||||
varSet->addDynamicProperty("App::PropertyInteger", "Variable2", "Variables")
|
||||
);
|
||||
prop2->setValue(Value);
|
||||
|
||||
App::ObjectIdentifier path(*prop);
|
||||
std::shared_ptr<App::Expression> expr(App::Expression::parse(varSet, "Variable2"));
|
||||
varSet->setExpression(path, expr);
|
||||
varSet->ExpressionEngine.execute();
|
||||
|
||||
// Assert before the rename
|
||||
EXPECT_EQ(prop2->getValue(), Value);
|
||||
EXPECT_EQ(prop->getValue(), Value);
|
||||
|
||||
// Act
|
||||
bool isRenamed = varSet->renameDynamicProperty(prop, "NewName");
|
||||
varSet->ExpressionEngine.execute();
|
||||
|
||||
// Assert after the rename
|
||||
EXPECT_TRUE(isRenamed);
|
||||
EXPECT_STREQ(varSet->getPropertyName(prop), "NewName");
|
||||
EXPECT_EQ(prop->getValue(), Value);
|
||||
EXPECT_EQ(varSet->getDynamicPropertyByName("Variable"), nullptr);
|
||||
EXPECT_EQ(varSet->getDynamicPropertyByName("NewName"), prop);
|
||||
|
||||
// Act
|
||||
prop2->setValue(Value + 1);
|
||||
varSet->ExpressionEngine.execute();
|
||||
|
||||
// Assert
|
||||
EXPECT_EQ(prop2->getValue(), Value + 1);
|
||||
EXPECT_EQ(prop->getValue(), Value + 1);
|
||||
}
|
||||
|
||||
// Tests whether we can rename a property and undo it
|
||||
TEST_F(RenameProperty, undoRenameProperty)
|
||||
{
|
||||
// Arrange
|
||||
_doc->setUndoMode(1);
|
||||
|
||||
// Act
|
||||
bool isRenamed = false;
|
||||
{
|
||||
_doc->openTransaction("Rename Property");
|
||||
isRenamed = varSet->renameDynamicProperty(prop, "NewName");
|
||||
_doc->commitTransaction();
|
||||
}
|
||||
|
||||
// Assert
|
||||
EXPECT_TRUE(isRenamed);
|
||||
EXPECT_STREQ(varSet->getPropertyName(prop), "NewName");
|
||||
EXPECT_EQ(prop->getValue(), Value);
|
||||
EXPECT_EQ(varSet->getDynamicPropertyByName("Variable"), nullptr);
|
||||
EXPECT_EQ(varSet->getDynamicPropertyByName("NewName"), prop);
|
||||
|
||||
// Act: Undo the rename
|
||||
bool undone = _doc->undo();
|
||||
|
||||
// Assert: The property should be back to its original name and value
|
||||
EXPECT_TRUE(undone);
|
||||
EXPECT_STREQ(varSet->getPropertyName(prop), "Variable");
|
||||
EXPECT_EQ(prop->getValue(), Value);
|
||||
EXPECT_EQ(varSet->getDynamicPropertyByName("Variable"), prop);
|
||||
EXPECT_EQ(varSet->getDynamicPropertyByName("NewName"), nullptr);
|
||||
}
|
||||
|
||||
|
||||
// Tests whether we can rename a property, undo, and redo it
|
||||
TEST_F(RenameProperty, redoRenameProperty)
|
||||
{
|
||||
// Arrange
|
||||
_doc->setUndoMode(1);
|
||||
|
||||
// Act
|
||||
bool isRenamed = false;
|
||||
{
|
||||
_doc->openTransaction("Rename Property");
|
||||
isRenamed = varSet->renameDynamicProperty(prop, "NewName");
|
||||
_doc->commitTransaction();
|
||||
}
|
||||
|
||||
// Assert
|
||||
EXPECT_TRUE(isRenamed);
|
||||
EXPECT_STREQ(varSet->getPropertyName(prop), "NewName");
|
||||
EXPECT_EQ(prop->getValue(), Value);
|
||||
EXPECT_EQ(varSet->getDynamicPropertyByName("Variable"), nullptr);
|
||||
EXPECT_EQ(varSet->getDynamicPropertyByName("NewName"), prop);
|
||||
|
||||
// Act: Undo the rename
|
||||
bool undone = _doc->undo();
|
||||
|
||||
// Assert: The property should be back to its original name and value
|
||||
EXPECT_TRUE(undone);
|
||||
EXPECT_STREQ(varSet->getPropertyName(prop), "Variable");
|
||||
EXPECT_EQ(prop->getValue(), Value);
|
||||
EXPECT_EQ(varSet->getDynamicPropertyByName("Variable"), prop);
|
||||
EXPECT_EQ(varSet->getDynamicPropertyByName("NewName"), nullptr);
|
||||
|
||||
// Act: Redo the rename
|
||||
bool redone = _doc->redo();
|
||||
EXPECT_TRUE(redone);
|
||||
EXPECT_STREQ(varSet->getPropertyName(prop), "NewName");
|
||||
EXPECT_EQ(prop->getValue(), Value);
|
||||
EXPECT_EQ(varSet->getDynamicPropertyByName("Variable"), nullptr);
|
||||
EXPECT_EQ(varSet->getDynamicPropertyByName("NewName"), prop);
|
||||
}
|
||||
69
tests/src/App/Property.h
Normal file
69
tests/src/App/Property.h
Normal file
@@ -0,0 +1,69 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
/****************************************************************************
|
||||
* Copyright (c) 2025 Pieter Hijma <info@pieterhijma.net> *
|
||||
* *
|
||||
* This file is part of the FreeCAD CAx development system. *
|
||||
* *
|
||||
* This library is free software; you can redistribute it and/or *
|
||||
* modify it under the terms of the GNU Library General Public *
|
||||
* License as published by the Free Software Foundation; either *
|
||||
* version 2 of the License, or (at your option) any later version. *
|
||||
* *
|
||||
* This library is distributed in the hope that it will be useful, *
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
|
||||
* GNU Library General Public License for more details. *
|
||||
* *
|
||||
* You should have received a copy of the GNU Library General Public *
|
||||
* License along with this library; see the file COPYING.LIB. If not, *
|
||||
* write to the Free Software Foundation, Inc., 59 Temple Place, *
|
||||
* Suite 330, Boston, MA 02111-1307, USA *
|
||||
* *
|
||||
****************************************************************************/
|
||||
#pragma once
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include <App/Document.h>
|
||||
#include <App/PropertyStandard.h>
|
||||
#include <App/VarSet.h>
|
||||
|
||||
#include <src/App/InitApplication.h>
|
||||
|
||||
class RenameProperty: public ::testing::Test
|
||||
{
|
||||
protected:
|
||||
static void SetUpTestSuite()
|
||||
{
|
||||
tests::initApplication();
|
||||
_docName = App::GetApplication().getUniqueDocumentName("test");
|
||||
_doc = App::GetApplication().newDocument(_docName.c_str(), "testUser");
|
||||
}
|
||||
|
||||
void SetUp() override
|
||||
{
|
||||
varSet = freecad_cast<App::VarSet*>(_doc->addObject("App::VarSet", "VarSet"));
|
||||
prop = freecad_cast<App::PropertyInteger*>(
|
||||
varSet->addDynamicProperty("App::PropertyInteger", "Variable", "Variables")
|
||||
);
|
||||
prop->setValue(Value);
|
||||
}
|
||||
|
||||
void TearDown() override
|
||||
{
|
||||
_doc->removeObject(varSet->getNameInDocument());
|
||||
}
|
||||
|
||||
static void TearDownTestSuite()
|
||||
{
|
||||
App::GetApplication().closeDocument(_docName.c_str());
|
||||
}
|
||||
|
||||
const long Value = 123;
|
||||
App::VarSet* varSet {};
|
||||
App::PropertyInteger* prop {};
|
||||
|
||||
static std::string _docName;
|
||||
static App::Document* _doc;
|
||||
};
|
||||
95
tests/src/App/PropertyExpressionEngine.cpp
Normal file
95
tests/src/App/PropertyExpressionEngine.cpp
Normal file
@@ -0,0 +1,95 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include "Base/Quantity.h"
|
||||
|
||||
#include "App/Application.h"
|
||||
#include "App/Document.h"
|
||||
#include "App/DocumentObject.h"
|
||||
#include "App/Expression.h"
|
||||
#include "App/ObjectIdentifier.h"
|
||||
#include "App/PropertyExpressionEngine.h"
|
||||
|
||||
#include "src/App/InitApplication.h"
|
||||
|
||||
// clang-format off
|
||||
|
||||
class PropertyExpressionEngineTest: public ::testing::Test
|
||||
{
|
||||
protected:
|
||||
static void SetUpTestSuite()
|
||||
{
|
||||
tests::initApplication();
|
||||
}
|
||||
|
||||
void SetUp() override
|
||||
{
|
||||
_doc_name = App::GetApplication().getUniqueDocumentName("test");
|
||||
_this_doc = App::GetApplication().newDocument(_doc_name.c_str(), "testUser");
|
||||
_this_obj = _this_doc -> addObject("Sketcher::SketchObject");
|
||||
_source_name = std::string("this_origin");
|
||||
_source_prop = _this_obj -> addDynamicProperty("App::PropertyString", _source_name.c_str()); // property with length as string
|
||||
_target_name = std::string("this_length");
|
||||
_target_prop = _this_obj -> addDynamicProperty("App::PropertyLength", _target_name.c_str()); // property with reference to source
|
||||
}
|
||||
|
||||
void TearDown() override
|
||||
{
|
||||
App::GetApplication().closeDocument(_doc_name.c_str());
|
||||
}
|
||||
|
||||
std::string doc_name() { return _doc_name; }
|
||||
App::Document* this_doc() { return _this_doc; }
|
||||
App::DocumentObject* this_obj() { return _this_obj; }
|
||||
std::string source_name() { return _source_name; }
|
||||
App::Property* source_prop() { return _source_prop; }
|
||||
std::string target_name() { return _target_name; }
|
||||
App::Property* target_prop() { return _target_prop; }
|
||||
|
||||
private:
|
||||
std::string _doc_name;
|
||||
App::Document* _this_doc {};
|
||||
App::DocumentObject* _this_obj {};
|
||||
std::string _source_name;
|
||||
App::Property* _source_prop {};
|
||||
std::string _target_name;
|
||||
App::Property* _target_prop {};
|
||||
};
|
||||
|
||||
// https://github.com/FreeCAD/FreeCAD/issues/11965
|
||||
TEST_F(PropertyExpressionEngineTest, executeCrossPropertyReference)
|
||||
{
|
||||
auto source_text = std::string("1.5 m"); // provided in source
|
||||
auto target_text = std::string("1500 mm"); // expected in target
|
||||
|
||||
auto source_path = App::ObjectIdentifier::parse(this_obj(), source_name());
|
||||
source_prop()->setPathValue(source_path, source_text);
|
||||
|
||||
auto target_expr = "parsequant(" + source_name() + ")"; // Solution B: parsequant() function
|
||||
|
||||
auto target_path = App::ObjectIdentifier::parse(this_obj(), target_name());
|
||||
std::shared_ptr<App::Expression> target_rule(App::Expression::parse(this_obj(), target_expr));
|
||||
this_obj()->setExpression(target_path, target_rule);
|
||||
|
||||
this_obj() -> ExpressionEngine.execute();
|
||||
|
||||
auto source_entry = source_prop() -> getPathValue(source_path);
|
||||
ASSERT_TRUE(source_entry.type() == typeid(std::string));
|
||||
auto source_value = App::any_cast<std::string>(source_entry);
|
||||
|
||||
auto target_entry = target_prop() -> getPathValue(target_path);
|
||||
ASSERT_TRUE(target_entry.type() == typeid(Base::Quantity));
|
||||
auto target_quant = App::any_cast<Base::Quantity>(target_entry);
|
||||
auto target_value = target_quant.getValue();
|
||||
auto target_unit = target_quant.getUnit().getString();
|
||||
|
||||
auto verify_quant = Base::Quantity::parse(target_text);
|
||||
|
||||
EXPECT_EQ(target_quant, verify_quant) << ""
|
||||
"expecting equal: source_text='" + source_text + "' target_text='" + target_text + "'"
|
||||
"instead produced: target_value='" + std::to_string(target_value) + "' target_unit='" + target_unit + "'"
|
||||
;
|
||||
}
|
||||
|
||||
// clang-format on
|
||||
1588
tests/src/App/StringHasher.cpp
Normal file
1588
tests/src/App/StringHasher.cpp
Normal file
File diff suppressed because it is too large
Load Diff
97
tests/src/App/VRMLObject.cpp
Normal file
97
tests/src/App/VRMLObject.cpp
Normal file
@@ -0,0 +1,97 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
/***************************************************************************
|
||||
* Copyright (c) 2024 Werner Mayer <wmayer[at]users.sourceforge.net> *
|
||||
* *
|
||||
* This file is part of FreeCAD. *
|
||||
* *
|
||||
* FreeCAD is free software: you can redistribute it and/or modify it *
|
||||
* under the terms of the GNU Lesser General Public License as *
|
||||
* published by the Free Software Foundation, either version 2.1 of the *
|
||||
* License, or (at your option) any later version. *
|
||||
* *
|
||||
* FreeCAD is distributed in the hope that it will be useful, but *
|
||||
* WITHOUT ANY WARRANTY; without even the implied warranty of *
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
|
||||
* Lesser General Public License for more details. *
|
||||
* *
|
||||
* You should have received a copy of the GNU Lesser General Public *
|
||||
* License along with FreeCAD. If not, see *
|
||||
* <https://www.gnu.org/licenses/>. *
|
||||
* *
|
||||
**************************************************************************/
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
#include "gmock/gmock.h"
|
||||
|
||||
#include <App/Application.h>
|
||||
#include <App/Document.h>
|
||||
#include <App/VRMLObject.h>
|
||||
#include <Base/FileInfo.h>
|
||||
#include <src/App/InitApplication.h>
|
||||
|
||||
// NOLINTBEGIN
|
||||
|
||||
class VRMLObjectTest: public ::testing::Test
|
||||
{
|
||||
protected:
|
||||
static void SetUpTestSuite()
|
||||
{
|
||||
tests::initApplication();
|
||||
}
|
||||
|
||||
void SetUp() override
|
||||
{
|
||||
document = App::GetApplication().openDocument(fileName().c_str());
|
||||
}
|
||||
|
||||
void TearDown() override
|
||||
{
|
||||
if (document) {
|
||||
App::GetApplication().closeDocument(document->getName());
|
||||
}
|
||||
}
|
||||
|
||||
std::string fileName() const
|
||||
{
|
||||
std::string resDir(DATADIR);
|
||||
resDir.append("/tests/TestVRMLTextures.FCStd");
|
||||
return resDir;
|
||||
}
|
||||
|
||||
App::Document* getDocument() const
|
||||
{
|
||||
return document;
|
||||
}
|
||||
|
||||
private:
|
||||
App::Document* document {};
|
||||
};
|
||||
|
||||
TEST_F(VRMLObjectTest, loadVRMLWithTextures)
|
||||
{
|
||||
App::Document* doc = getDocument();
|
||||
ASSERT_TRUE(doc);
|
||||
|
||||
auto vrml = dynamic_cast<App::VRMLObject*>(doc->getActiveObject());
|
||||
ASSERT_TRUE(vrml);
|
||||
|
||||
auto res = vrml->Resources.getValues();
|
||||
EXPECT_EQ(res.size(), 6);
|
||||
EXPECT_EQ(res[0], std::string("FreeCAD/FreeCAD1.png"));
|
||||
EXPECT_EQ(res[1], std::string("FreeCAD/FreeCAD2.png"));
|
||||
EXPECT_EQ(res[2], std::string("FreeCAD/FreeCAD3.png"));
|
||||
EXPECT_EQ(res[3], std::string("FreeCAD/FreeCAD4.png"));
|
||||
EXPECT_EQ(res[4], std::string("FreeCAD/FreeCAD5.png"));
|
||||
EXPECT_EQ(res[5], std::string("FreeCAD/FreeCAD6.png"));
|
||||
|
||||
auto url = vrml->Urls.getValues();
|
||||
EXPECT_EQ(url.size(), 6);
|
||||
for (const auto& it : url) {
|
||||
Base::FileInfo fi(it);
|
||||
EXPECT_TRUE(fi.isFile());
|
||||
EXPECT_TRUE(fi.exists());
|
||||
}
|
||||
}
|
||||
|
||||
// NOLINTEND
|
||||
100
tests/src/App/VarSet.cpp
Normal file
100
tests/src/App/VarSet.cpp
Normal file
@@ -0,0 +1,100 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
/****************************************************************************
|
||||
* Copyright (c) 2024 Ondsel <development@ondsel.com> *
|
||||
* *
|
||||
* This file is part of the FreeCAD CAx development system. *
|
||||
* *
|
||||
* This library is free software; you can redistribute it and/or *
|
||||
* modify it under the terms of the GNU Library General Public *
|
||||
* License as published by the Free Software Foundation; either *
|
||||
* version 2 of the License, or (at your option) any later version. *
|
||||
* *
|
||||
* This library is distributed in the hope that it will be useful, *
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
|
||||
* GNU Library General Public License for more details. *
|
||||
* *
|
||||
* You should have received a copy of the GNU Library General Public *
|
||||
* License along with this library; see the file COPYING.LIB. If not, *
|
||||
* write to the Free Software Foundation, Inc., 59 Temple Place, *
|
||||
* Suite 330, Boston, MA 02111-1307, USA *
|
||||
* *
|
||||
****************************************************************************/
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
#include "gmock/gmock.h"
|
||||
|
||||
#include <App/Application.h>
|
||||
#include "App/Document.h"
|
||||
#include <App/VarSet.h>
|
||||
#include <src/App/InitApplication.h>
|
||||
|
||||
using ::testing::NotNull;
|
||||
|
||||
// NOLINTBEGIN(readability-magic-numbers)
|
||||
|
||||
class VarSet: public ::testing::Test
|
||||
{
|
||||
protected:
|
||||
static void SetUpTestSuite()
|
||||
{
|
||||
tests::initApplication();
|
||||
}
|
||||
|
||||
void SetUp() override
|
||||
{
|
||||
_docName = App::GetApplication().getUniqueDocumentName("test");
|
||||
_doc = App::GetApplication().newDocument(_docName.c_str(), "testUser");
|
||||
}
|
||||
|
||||
void TearDown() override
|
||||
{
|
||||
App::GetApplication().closeDocument(_docName.c_str());
|
||||
}
|
||||
|
||||
App::Document* doc()
|
||||
{
|
||||
return _doc;
|
||||
}
|
||||
|
||||
private:
|
||||
std::string _docName;
|
||||
App::Document* _doc {};
|
||||
};
|
||||
|
||||
// Tests whether we can create a VarSet
|
||||
TEST_F(VarSet, createVarSet)
|
||||
{
|
||||
// Arrange
|
||||
const char* nameVarSet = "VarSet";
|
||||
|
||||
// Act
|
||||
doc()->addObject("App::VarSet", nameVarSet);
|
||||
auto varSet = dynamic_cast<App::VarSet*>(doc()->getObject(nameVarSet));
|
||||
|
||||
// Assert
|
||||
EXPECT_THAT(varSet, NotNull());
|
||||
}
|
||||
|
||||
// Tests whether we can add a property to a VarSet
|
||||
TEST_F(VarSet, addProperty)
|
||||
{
|
||||
// Arrange
|
||||
const char* nameVarSet = "VarSet001";
|
||||
const long VALUE = 123;
|
||||
|
||||
doc()->addObject("App::VarSet", nameVarSet);
|
||||
auto varSet = dynamic_cast<App::VarSet*>(doc()->getObject(nameVarSet));
|
||||
|
||||
// Act
|
||||
auto prop = dynamic_cast<App::PropertyInteger*>(
|
||||
varSet->addDynamicProperty("App::PropertyInteger", "Variable", "Variables")
|
||||
);
|
||||
prop->setValue(VALUE);
|
||||
|
||||
// Assert
|
||||
EXPECT_EQ(prop->getValue(), VALUE);
|
||||
}
|
||||
|
||||
// NOLINTEND(readability-magic-numbers)
|
||||
Reference in New Issue
Block a user