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

This commit is contained in:
2026-08-20 07:00:53 +08:00
commit b5a086fda5
12718 changed files with 7841410 additions and 0 deletions

View 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);
};

View 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
) */

View 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")
)
);
}

View 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 {};
}

View 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
)

View 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)

View 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)

View 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)

View 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);
}

View 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)

View 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)

View 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

View 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

View 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)

View 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
View 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/");
}

View 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);
}

View 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
View 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)

View 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
View 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
View 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;
};

View 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

File diff suppressed because it is too large Load Diff

View 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
View 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)

83
tests/src/Base/Axis.cpp Normal file
View File

@@ -0,0 +1,83 @@
#include <gtest/gtest.h>
#include <Base/Axis.h>
#include <Base/Placement.h>
#include <Base/Rotation.h>
#include <src/App/InitApplication.h>
class Axis: public ::testing::Test
{
protected:
static void SetUpTestSuite()
{
tests::initApplication();
}
};
TEST_F(Axis, TestDefault)
{
Base::Axis axis;
EXPECT_EQ(axis.getBase(), Base::Vector3d());
EXPECT_EQ(axis.getDirection(), Base::Vector3d());
}
TEST_F(Axis, TestCustom)
{
Base::Axis axis(Base::Vector3d(0, 0, 1), Base::Vector3d(1, 1, 1));
EXPECT_EQ(axis.getBase(), Base::Vector3d(0, 0, 1));
EXPECT_EQ(axis.getDirection(), Base::Vector3d(1, 1, 1));
}
TEST_F(Axis, TestSetter)
{
Base::Axis axis;
axis.setBase(Base::Vector3d(0, 0, 1));
axis.setDirection(Base::Vector3d(1, 1, 1));
EXPECT_EQ(axis.getBase(), Base::Vector3d(0, 0, 1));
EXPECT_EQ(axis.getDirection(), Base::Vector3d(1, 1, 1));
}
TEST_F(Axis, TestAssign)
{
Base::Axis axis;
Base::Axis move;
axis.setBase(Base::Vector3d(0, 0, 1));
axis.setDirection(Base::Vector3d(1, 1, 1));
move = std::move(axis); // NOLINT
EXPECT_EQ(move.getBase(), Base::Vector3d(0, 0, 1));
EXPECT_EQ(move.getDirection(), Base::Vector3d(1, 1, 1));
}
TEST_F(Axis, TestReverse)
{
Base::Axis axis(Base::Vector3d(0, 0, 1), Base::Vector3d(1, 1, 1));
axis.reverse();
EXPECT_EQ(axis.getBase(), Base::Vector3d(0, 0, 1));
EXPECT_EQ(axis.getDirection(), Base::Vector3d(-1, -1, -1));
}
TEST_F(Axis, TestReversed)
{
Base::Axis axis(Base::Vector3d(0, 0, 1), Base::Vector3d(1, 1, 1));
Base::Axis rev(axis.reversed());
EXPECT_EQ(axis.getDirection(), Base::Vector3d(1, 1, 1));
EXPECT_EQ(rev.getBase(), Base::Vector3d(0, 0, 1));
EXPECT_EQ(rev.getDirection(), Base::Vector3d(-1, -1, -1));
}
TEST_F(Axis, TestMove)
{
Base::Axis axis(Base::Vector3d(0, 0, 1), Base::Vector3d(1, 1, 1));
axis.move(Base::Vector3d(1, 2, 3));
EXPECT_EQ(axis.getBase(), Base::Vector3d(1, 2, 4));
EXPECT_EQ(axis.getDirection(), Base::Vector3d(1, 1, 1));
}
TEST_F(Axis, TestMult)
{
Base::Axis axis(Base::Vector3d(0, 0, 1), Base::Vector3d(0, 0, 1));
axis *= Base::Placement(Base::Vector3d(1, 1, 1), Base::Rotation(1, 0, 0, 0));
EXPECT_EQ(axis.getBase(), Base::Vector3d(1, 1, 0));
EXPECT_EQ(axis.getDirection(), Base::Vector3d(0, 0, -1));
}

94
tests/src/Base/Base64.cpp Normal file
View File

@@ -0,0 +1,94 @@
/*
Copyright (C) 2004-2008 René Nyffenegger
This source code is provided 'as-is', without any express or implied
warranty. In no event will the author be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this source code must not be misrepresented; you must not
claim that you wrote the original source code. If you use this source code
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original source code.
3. This notice may not be removed or altered from any source distribution.
René Nyffenegger rene.nyffenegger@adp-gmbh.ch
NOTICE: This test has been modified from the original code to remove output to stdout, and to split
the tests into individual parts.
*/
#include "Base/Base64.h"
#include <gtest/gtest.h>
using namespace Base;
// NOLINTBEGIN(cppcoreguidelines-pro-type-reinterpret-cast)
TEST(Base64, encode)
{
const std::string str = "René Nyffenegger\n"
"http://www.renenyffenegger.ch\n"
"passion for data\n";
auto encoded = base64_encode(reinterpret_cast<const unsigned char*>(str.c_str()), str.length());
auto decoded = base64_decode(std::string(encoded));
ASSERT_EQ(decoded, str);
}
TEST(Base64, exactlyFourBytes)
{
// Test all possibilities of fill bytes (none, one =, two ==)
// References calculated with: https://www.base64encode.org/
std::string rest0_original = "abc";
// std::string rest0_reference = "YWJj";
std::string rest0_encoded = base64_encode(
reinterpret_cast<const unsigned char*>(rest0_original.c_str()),
rest0_original.length()
);
std::string rest0_decoded = base64_decode(rest0_encoded);
ASSERT_EQ(rest0_decoded, rest0_original);
}
TEST(Base64, twoEqualsSignsPadding)
{
std::string rest1_original = "abcd";
// std::string rest1_reference = "YWJjZA==";
std::string rest1_encoded = base64_encode(
reinterpret_cast<const unsigned char*>(rest1_original.c_str()),
rest1_original.length()
);
std::string rest1_decoded = base64_decode(rest1_encoded);
ASSERT_EQ(rest1_decoded, rest1_original);
}
TEST(Base64, oneEqualsSignPadding)
{
std::string rest2_original = "abcde";
// std::string rest2_reference = "YWJjZGU=";
std::string rest2_encoded = base64_encode(
reinterpret_cast<const unsigned char*>(rest2_original.c_str()),
rest2_original.length()
);
std::string rest2_decoded = base64_decode(rest2_encoded);
ASSERT_EQ(rest2_decoded, rest2_original);
}
// NOLINTEND(cppcoreguidelines-pro-type-reinterpret-cast)

View File

@@ -0,0 +1,31 @@
// SPDX-License-Identifier: LGPL-2.1-or-later
#include <gtest/gtest.h>
#include <Base/Bitmask.h>
enum class TestFlagEnum
{
Flag1,
Flag2,
Flag3
};
class BitmaskTest: public ::testing::Test
{
protected:
// void SetUp() override {};
// void TearDown() override {};
};
TEST_F(BitmaskTest, toUnderlyingType)
{
// Arrange
Base::Flags<TestFlagEnum> flag1 {TestFlagEnum::Flag1};
// Act
auto result = flag1.toUnderlyingType();
// Assert
EXPECT_EQ(typeid(result), typeid(int));
}

308
tests/src/Base/BoundBox.cpp Normal file
View File

@@ -0,0 +1,308 @@
#include <gtest/gtest.h>
#ifdef WIN32
# define WIN32_LEAN_AND_MEAN
# ifndef NOMINMAX
# define NOMINMAX
# endif
# include <Windows.h>
#endif
#include <Base/BoundBox.h>
#include <boost/beast/core/span.hpp>
// NOLINTBEGIN(cppcoreguidelines-*,readability-*)
TEST(BoundBox, TestDefault)
{
Base::BoundBox3d box;
EXPECT_EQ(box.IsValid(), false);
}
TEST(BoundBox, TestVoid)
{
Base::BoundBox3d box;
EXPECT_EQ(box.IsValid(), false);
box.Add(Base::Vector3d(0, 0, 0));
EXPECT_EQ(box.IsValid(), true);
box.SetVoid();
EXPECT_EQ(box.IsValid(), false);
}
TEST(BoundBox, TestCopy)
{
Base::BoundBox3d box;
box.Add(Base::Vector3d(0, 0, 0));
box.Add(Base::Vector3d(1, 1, 1));
Base::BoundBox3d copy(box);
EXPECT_EQ(copy.IsValid(), true);
EXPECT_EQ(copy.MinX, 0);
EXPECT_EQ(copy.MinY, 0);
EXPECT_EQ(copy.MinZ, 0);
EXPECT_EQ(copy.MaxX, 1);
EXPECT_EQ(copy.MaxY, 1);
EXPECT_EQ(copy.MaxZ, 1);
}
TEST(BoundBox, TestAssign)
{
Base::BoundBox3d box;
box.Add(Base::Vector3d(0, 0, 0));
box.Add(Base::Vector3d(1, 1, 1));
Base::BoundBox3d copy;
copy = box;
EXPECT_EQ(copy.IsValid(), true);
EXPECT_EQ(copy.MinX, 0);
EXPECT_EQ(copy.MinY, 0);
EXPECT_EQ(copy.MinZ, 0);
EXPECT_EQ(copy.MaxX, 1);
EXPECT_EQ(copy.MaxY, 1);
EXPECT_EQ(copy.MaxZ, 1);
}
TEST(BoundBox, TestPoints)
{
std::array<Base::Vector3d, 1> pts;
Base::BoundBox3d box(pts.data(), pts.size());
EXPECT_EQ(box.IsValid(), true);
EXPECT_EQ(box.MinX, 0);
EXPECT_EQ(box.MinY, 0);
EXPECT_EQ(box.MinZ, 0);
EXPECT_EQ(box.MaxX, 0);
EXPECT_EQ(box.MaxY, 0);
EXPECT_EQ(box.MaxZ, 0);
}
TEST(BoundBox, TestDistance)
{
Base::BoundBox3d box(Base::Vector3d(0, 0, 0), 0.5);
EXPECT_EQ(box.IsValid(), true);
EXPECT_EQ(box.MinX, -0.5);
EXPECT_EQ(box.MinY, -0.5);
EXPECT_EQ(box.MinZ, -0.5);
EXPECT_EQ(box.MaxX, 0.5);
EXPECT_EQ(box.MaxY, 0.5);
EXPECT_EQ(box.MaxZ, 0.5);
}
Base::BoundBox3d createBox(boost::beast::span<Base::Vector3d> span)
{
return {span.data(), span.size()};
}
TEST(BoundBox, TestEmptySpan)
{
Base::BoundBox3d box = createBox({});
EXPECT_EQ(box.IsValid(), false);
}
TEST(BoundBox, TestNonEmptySpan)
{
std::vector<Base::Vector3d> points = {
Base::Vector3d {1.0, 0.0, 0.0},
Base::Vector3d {0.0, 1.0, 0.0},
Base::Vector3d {0.0, 0.0, 1.0}
};
Base::BoundBox3d box = createBox({points.data(), 2});
EXPECT_EQ(box.IsValid(), true);
EXPECT_EQ(box.MinX, 0);
EXPECT_EQ(box.MinY, 0);
EXPECT_EQ(box.MinZ, 0);
EXPECT_EQ(box.MaxX, 1);
EXPECT_EQ(box.MaxY, 1);
EXPECT_EQ(box.MaxZ, 0);
}
TEST(BoundBox, TestArray)
{
std::vector<Base::Vector3d> points = {
Base::Vector3d {1.0, 0.0, 0.0},
Base::Vector3d {0.0, 1.0, 0.0},
Base::Vector3d {0.0, 0.0, 1.0}
};
Base::BoundBox3d box(points.data(), points.size());
EXPECT_EQ(box.IsValid(), true);
EXPECT_EQ(box.MinX, 0);
EXPECT_EQ(box.MinY, 0);
EXPECT_EQ(box.MinZ, 0);
EXPECT_EQ(box.MaxX, 1);
EXPECT_EQ(box.MaxY, 1);
EXPECT_EQ(box.MaxZ, 1);
}
TEST(BoundBox, TestIntersect)
{
Base::BoundBox3d box1;
Base::BoundBox3d box2;
Base::BoundBox3d box3;
EXPECT_EQ(box1.Intersect(box1), false);
box1.Add(Base::Vector3d(0, 0, 0));
EXPECT_EQ(box1.Intersect(box1), true);
EXPECT_EQ(box1.Intersect(box2), false);
EXPECT_EQ(box2.Intersect(box1), false);
box1.Add(Base::Vector3d(1, 1, 1));
box2.Add(Base::Vector3d(0.5, 0.5, 0.5));
box2.Add(Base::Vector3d(1.5, 1.5, 1.5));
EXPECT_EQ(box1.Intersect(box2), true);
EXPECT_EQ(box2.Intersect(box1), true);
EXPECT_EQ(box1 && box2, true);
EXPECT_EQ(box2 && box1, true);
box3 = box1.Intersected(box2);
EXPECT_EQ(box3.IsValid(), true);
}
TEST(BoundBox, TestIntersect2D)
{
Base::BoundBox3d box1;
box1.Add(Base::Vector3d(0, 0, 0));
box1.Add(Base::Vector3d(1, 1, 1));
Base::BoundBox2d box2;
box2.Add(Base::Vector2d(0.5, 0.5));
box2.Add(Base::Vector2d(1.5, 1.5));
EXPECT_EQ(box1.Intersect(box2), true);
EXPECT_EQ(box1 && box2, true);
}
TEST(BoundBox, TestUnite)
{
Base::BoundBox3d box1;
Base::BoundBox3d box2;
Base::BoundBox3d box3;
box1.Add(Base::Vector3d(0, 0, 0));
box2.Add(Base::Vector3d(1, 1, 1));
box3 = box1.United(box2);
EXPECT_EQ(box3.IsValid(), true);
EXPECT_EQ(box3.MinX, 0);
EXPECT_EQ(box3.MinY, 0);
EXPECT_EQ(box3.MinZ, 0);
EXPECT_EQ(box3.MaxX, 1);
EXPECT_EQ(box3.MaxY, 1);
EXPECT_EQ(box3.MaxZ, 1);
box1.Add(box2);
EXPECT_EQ(box1.IsValid(), true);
EXPECT_EQ(box1.MinX, 0);
EXPECT_EQ(box1.MinY, 0);
EXPECT_EQ(box1.MinZ, 0);
EXPECT_EQ(box1.MaxX, 1);
EXPECT_EQ(box1.MaxY, 1);
EXPECT_EQ(box1.MaxZ, 1);
}
TEST(BoundBox, TestAdd)
{
Base::BoundBox3d box1;
Base::BoundBox3d box2;
box1.Add(Base::Vector3d(0, 0, 0));
box2.Add(Base::Vector3d(1, 1, 1));
box1.Add(box2);
EXPECT_EQ(box1.IsInBox(box2), true);
EXPECT_EQ(box1.IsInBox(Base::Vector3d(0, 0, 0)), true);
EXPECT_EQ(box1.IsInBox(Base::Vector3d(1, 1, 1)), true);
}
TEST(BoundBox, TestCenter)
{
Base::BoundBox3d box;
box.Add(Base::Vector3d(0, 0, 0));
box.Add(Base::Vector3d(1, 1, 1));
EXPECT_EQ(box.GetCenter(), Base::Vector3d(0.5, 0.5, 0.5));
}
TEST(BoundBox, TestMinimum)
{
Base::BoundBox3d box;
box.Add(Base::Vector3d(0, 0, 0));
box.Add(Base::Vector3d(1, 1, 1));
EXPECT_EQ(box.GetMinimum(), Base::Vector3d(0, 0, 0));
}
TEST(BoundBox, TestMaximum)
{
Base::BoundBox3d box;
box.Add(Base::Vector3d(0, 0, 0));
box.Add(Base::Vector3d(1, 1, 1));
EXPECT_EQ(box.GetMaximum(), Base::Vector3d(1, 1, 1));
}
TEST(BoundBox, TestDiagonalLength)
{
Base::BoundBox3d box;
box.Add(Base::Vector3d(0, 0, 0));
box.Add(Base::Vector3d(1, 1, 1));
EXPECT_GT(box.CalcDiagonalLength(), 1.7);
EXPECT_LT(box.CalcDiagonalLength(), 1.8);
}
TEST(BoundBox, TestVolume)
{
Base::BoundBox3d box;
EXPECT_LT(box.Volume(), 0.0);
box.Add(Base::Vector3d(0, 0, 0));
EXPECT_EQ(box.Volume(), 0.0);
box.Add(Base::Vector3d(1, 1, 1));
EXPECT_GT(box.Volume(), 0.0);
}
TEST(BoundBox, TestDiagonalEnlarge)
{
Base::BoundBox3d box;
box.Add(Base::Vector3d(1, 1, 1));
box.Enlarge(0.5);
EXPECT_EQ(box.LengthX(), 1.0);
EXPECT_EQ(box.LengthY(), 1.0);
EXPECT_EQ(box.LengthZ(), 1.0);
}
TEST(BoundBox, TestDiagonalShrink)
{
Base::BoundBox3d box;
box.Add(Base::Vector3d(0, 0, 0));
box.Add(Base::Vector3d(4, 6, 8));
box.Shrink(0.5);
EXPECT_EQ(box.LengthX(), 3.0);
EXPECT_EQ(box.LengthY(), 5.0);
EXPECT_EQ(box.LengthZ(), 7.0);
}
TEST(BoundBox, TestDiagonalMove)
{
Base::BoundBox3d box;
box.Add(Base::Vector3d(0, 0, 0));
box.MoveX(1.0);
box.MoveY(2.0);
box.MoveZ(3.0);
EXPECT_EQ(box.MinX, 1);
EXPECT_EQ(box.MinY, 2);
EXPECT_EQ(box.MinZ, 3);
EXPECT_EQ(box.MaxX, 1);
EXPECT_EQ(box.MaxY, 2);
EXPECT_EQ(box.MaxZ, 3);
}
TEST(BoundBox, TestDiagonalScale)
{
Base::BoundBox3d box;
box.Add(Base::Vector3d(0, 0, 0));
box.Add(Base::Vector3d(1, 2, 3));
box.ScaleX(0.5);
box.ScaleY(1.0);
box.ScaleZ(2.0);
EXPECT_EQ(box.MinX, 0);
EXPECT_EQ(box.MinY, 0);
EXPECT_EQ(box.MinZ, 0);
EXPECT_EQ(box.MaxX, 0.5);
EXPECT_EQ(box.MaxY, 2.0);
EXPECT_EQ(box.MaxZ, 6.0);
}
// NOLINTEND(cppcoreguidelines-*,readability-*)

View File

@@ -0,0 +1,10 @@
#include <gtest/gtest.h>
#include <Base/Builder3D.h>
TEST(Builder3D, openInventor)
{
Base::Builder3D builder;
builder.beginSeparator();
builder.endSeparator();
}

View File

@@ -0,0 +1,43 @@
add_executable(Base_tests_run
Axis.cpp
Base64.cpp
Bitmask.cpp
BoundBox.cpp
Builder3D.cpp
Color.cpp
CoordinateSystem.cpp
DualNumber.cpp
DualQuaternion.cpp
FileInfo.cpp
Handle.cpp
Matrix.cpp
Parameter.cpp
Placement.cpp
Quantity.cpp
Reader.cpp
Rotation.cpp
SchemaTests.cpp
ServiceProvider.cpp
Stream.cpp
TimeInfo.cpp
Tools.cpp
Tools2D.cpp
Tools3D.cpp
UnlimitedUnsigned.cpp
UniqueNameManager.cpp
Unit.cpp
Vector3D.cpp
ViewProj.cpp
Writer.cpp
XMLTools.cpp
)
setup_qt_test(InventorBuilder)
target_link_libraries(Base_tests_run PRIVATE
GTest::gtest_main
GTest::gmock_main
${Google_Tests_LIBS}
FreeCADApp
ICU::uc ICU::i18n
)

248
tests/src/Base/Color.cpp Normal file
View File

@@ -0,0 +1,248 @@
#include <gtest/gtest.h>
#include <cmath>
#include "Base/Color.h"
// NOLINTBEGIN
TEST(TestColor, equal)
{
int red = 85;
int green = 170;
int blue = 255;
Base::Color color(red / 255.0F, green / 255.0F, blue / 255.0F);
uint32_t packed = color.getPackedValue();
Base::Color color2 {packed};
EXPECT_EQ(color, color2);
}
TEST(TestColor, round)
{
for (int index = 0; index < 256; index++) {
float value = static_cast<float>(index) / 255.0F;
EXPECT_EQ(std::lround(value * 255.0F), index);
}
}
TEST(TestColor, packedValue)
{
int red = 85;
int green = 170;
int blue = 255;
Base::Color color(red / 255.0F, green / 255.0F, blue / 255.0F);
uint32_t packed = color.getPackedValue();
Base::Color color2 {packed};
EXPECT_EQ(std::lround(color2.r * 255.0F), 85);
EXPECT_EQ(std::lround(color2.g * 255.0F), 170);
EXPECT_EQ(std::lround(color2.b * 255.0F), 255);
}
TEST(TestColor, packedRGB)
{
int red = 85;
int green = 170;
int blue = 255;
Base::Color color(red / 255.0F, green / 255.0F, blue / 255.0F);
uint32_t packed = color.getPackedRGB();
Base::Color color2;
color2.setPackedRGB(packed);
EXPECT_EQ(std::lround(color2.r * 255.0F), 85);
EXPECT_EQ(std::lround(color2.g * 255.0F), 170);
EXPECT_EQ(std::lround(color2.b * 255.0F), 255);
}
TEST(TestColor, packedARGB)
{
int red = 85;
int green = 170;
int blue = 255;
int alpha = 127;
Base::Color color(red / 255.0F, green / 255.0F, blue / 255.0F, alpha / 255.0F);
uint32_t packed = color.getPackedARGB();
Base::Color color2;
color2.setPackedARGB(packed);
EXPECT_EQ(std::lround(color2.r * 255.0F), 85);
EXPECT_EQ(std::lround(color2.g * 255.0F), 170);
EXPECT_EQ(std::lround(color2.b * 255.0F), 255);
EXPECT_EQ(std::lround(color2.a * 255.0F), 127);
}
struct IntColor
{
IntColor(int red, int green, int blue, int alpha = 0)
: red_ {red}
, green_ {green}
, blue_ {blue}
, alpha_ {alpha}
{}
float redF() const
{
return static_cast<float>(red_) / 255.0F;
}
float greenF() const
{
return static_cast<float>(green_) / 255.0F;
}
float blueF() const
{
return static_cast<float>(blue_) / 255.0F;
}
float alphaF() const
{
return static_cast<float>(alpha_) / 255.0F;
}
int red() const
{
return red_;
}
int green() const
{
return green_;
}
int blue() const
{
return blue_;
}
int alpha() const
{
return alpha_;
}
private:
int red_ {};
int green_ {};
int blue_ {};
int alpha_ {};
};
TEST(TestColor, asPackedRGB)
{
int red = 85;
int green = 170;
int blue = 255;
IntColor intColor {red, green, blue};
uint32_t packed = Base::Color::asPackedRGB<IntColor>(intColor);
EXPECT_EQ(packed, 1437269760);
}
TEST(TestColor, fromPackedRGB)
{
int red = 85;
int green = 170;
int blue = 255;
Base::Color color(red / 255.0F, green / 255.0F, blue / 255.0F);
IntColor intColor = Base::Color::fromPackedRGB<IntColor>(color.getPackedRGB());
EXPECT_EQ(intColor.red(), red);
EXPECT_EQ(intColor.green(), green);
EXPECT_EQ(intColor.blue(), blue);
}
TEST(TestColor, asPackedRGBA)
{
int red = 85;
int green = 170;
int blue = 255;
int alpha = 127;
IntColor intColor {red, green, blue, alpha};
uint32_t packed = Base::Color::asPackedRGBA<IntColor>(intColor);
EXPECT_EQ(packed, 1437269887);
}
TEST(TestColor, fromPackedRGBA)
{
int red = 85;
int green = 170;
int blue = 255;
int alpha = 127;
Base::Color color(red / 255.0F, green / 255.0F, blue / 255.0F, alpha / 255.0F);
IntColor intColor = Base::Color::fromPackedRGBA<IntColor>(color.getPackedValue());
EXPECT_EQ(intColor.red(), red);
EXPECT_EQ(intColor.green(), green);
EXPECT_EQ(intColor.blue(), blue);
EXPECT_EQ(intColor.alpha(), alpha);
}
TEST(TestColor, setValue)
{
int red = 85;
int green = 170;
int blue = 255;
IntColor intColor {red, green, blue};
Base::Color color {};
color.setValue<IntColor>(intColor);
EXPECT_FLOAT_EQ(color.r, 85.0F / 255.0F);
EXPECT_FLOAT_EQ(color.g, 170.0F / 255.0F);
EXPECT_FLOAT_EQ(color.b, 255.0F / 255.0F);
}
TEST(TestColor, asValue)
{
int red = 85;
int green = 170;
int blue = 255;
Base::Color color(red / 255.0F, green / 255.0F, blue / 255.0F);
IntColor intColor = color.asValue<IntColor>();
EXPECT_EQ(intColor.red(), 85);
EXPECT_EQ(intColor.green(), 170);
EXPECT_EQ(intColor.blue(), 255);
}
TEST(TestColor, asHexString)
{
int red = 85;
int green = 170;
int blue = 255;
Base::Color color(red / 255.0F, green / 255.0F, blue / 255.0F);
EXPECT_EQ(color.asHexString(), "#55AAFF");
}
TEST(TestColor, fromHexString)
{
Base::Color color;
EXPECT_FALSE(color.fromHexString(std::string("")));
EXPECT_FALSE(color.fromHexString(std::string("abcdef")));
EXPECT_TRUE(color.fromHexString(std::string("#abcdef")));
EXPECT_TRUE(color.fromHexString(std::string("#ABCDEF")));
EXPECT_FALSE(color.fromHexString(std::string("#abcde")));
EXPECT_FALSE(color.fromHexString(std::string("#abcdeff")));
EXPECT_FALSE(color.fromHexString(std::string("#abcdeffff")));
EXPECT_TRUE(color.fromHexString(std::string("#55AAFF")));
EXPECT_FLOAT_EQ(color.r, 85.0F / 255.0F);
EXPECT_FLOAT_EQ(color.g, 170.0F / 255.0F);
EXPECT_FLOAT_EQ(color.b, 255.0F / 255.0F);
EXPECT_FLOAT_EQ(color.a, 255.0F / 255.0F);
}
// NOLINTEND

View File

@@ -0,0 +1,151 @@
#include <gtest/gtest.h>
#include <Base/CoordinateSystem.h>
#include <Base/Exception.h>
#include <Base/Placement.h>
// NOLINTBEGIN
TEST(CoordinateSystem, TestDefault)
{
Base::CoordinateSystem cs;
EXPECT_EQ(cs.getPosition(), Base::Vector3d(0, 0, 0));
EXPECT_EQ(cs.getXDirection(), Base::Vector3d(1, 0, 0));
EXPECT_EQ(cs.getYDirection(), Base::Vector3d(0, 1, 0));
EXPECT_EQ(cs.getZDirection(), Base::Vector3d(0, 0, 1));
}
TEST(CoordinateSystem, TestSetAxisFailure)
{
Base::CoordinateSystem cs;
EXPECT_THROW(cs.setAxes(Base::Vector3d(0, 0, 1), Base::Vector3d(0, 0, 1)), Base::ValueError);
}
TEST(CoordinateSystem, TestSetAxis)
{
Base::CoordinateSystem cs;
Base::Axis axis;
axis.setBase(Base::Vector3d(1, 2, 3));
axis.setDirection(Base::Vector3d(1, 1, 1));
cs.setAxes(axis, Base::Vector3d(0, 0, 1));
EXPECT_EQ(cs.getPosition(), Base::Vector3d(1, 2, 3));
EXPECT_EQ(cs.getXDirection(), Base::Vector3d(-1, -1, 2).Normalize());
EXPECT_EQ(cs.getYDirection(), Base::Vector3d(1, -1, 0).Normalize());
EXPECT_EQ(cs.getZDirection(), Base::Vector3d(1, 1, 1).Normalize());
}
TEST(CoordinateSystem, TestSetXDir)
{
Base::CoordinateSystem cs;
cs.setXDirection(Base::Vector3d(1, 1, 1));
EXPECT_EQ(cs.getXDirection(), Base::Vector3d(1, 1, 0).Normalize());
EXPECT_EQ(cs.getYDirection(), Base::Vector3d(-1, 1, 0).Normalize());
EXPECT_EQ(cs.getZDirection(), Base::Vector3d(0, 0, 1).Normalize());
}
TEST(CoordinateSystem, TestSetYDir)
{
Base::CoordinateSystem cs;
cs.setYDirection(Base::Vector3d(1, 1, 1));
EXPECT_EQ(cs.getXDirection(), Base::Vector3d(1, -1, 0).Normalize());
EXPECT_EQ(cs.getYDirection(), Base::Vector3d(1, 1, 0).Normalize());
EXPECT_EQ(cs.getZDirection(), Base::Vector3d(0, 0, 1).Normalize());
}
TEST(CoordinateSystem, TestSetZDir)
{
Base::CoordinateSystem cs;
cs.setZDirection(Base::Vector3d(1, 1, 1));
EXPECT_EQ(cs.getXDirection(), Base::Vector3d(2, -1, -1).Normalize());
EXPECT_EQ(cs.getYDirection(), Base::Vector3d(0, 1, -1).Normalize());
EXPECT_EQ(cs.getZDirection(), Base::Vector3d(1, 1, 1).Normalize());
}
TEST(CoordinateSystem, TestTransformPlacement)
{
Base::CoordinateSystem cs;
Base::CoordinateSystem csT;
Base::Placement plm;
plm.setPosition(Base::Vector3d(1, 2, 3));
plm.setRotation(Base::Rotation(1, 1, 2, 2));
csT.transform(plm);
Base::Placement dis = cs.displacement(csT);
EXPECT_EQ(plm.isSame(dis, 1e-15), true);
Base::Placement disT = csT.displacement(cs);
EXPECT_EQ(plm.inverse().isSame(disT, 1e-15), true);
}
TEST(CoordinateSystem, TestMultTransformPlacement)
{
Base::CoordinateSystem cs;
Base::CoordinateSystem csT;
Base::Placement plm;
plm.setPosition(Base::Vector3d(1, 2, 3));
plm.setRotation(Base::Rotation(1, 1, 2, 2));
csT.transform(plm);
csT.transform(plm);
plm = plm * plm;
Base::Placement dis = cs.displacement(csT);
EXPECT_EQ(plm.isSame(dis, 0.001), true);
Base::Placement disT = csT.displacement(cs);
EXPECT_EQ(plm.inverse().isSame(disT, 0.001), true);
}
TEST(CoordinateSystem, TestTransformRotation)
{
Base::CoordinateSystem cs;
Base::CoordinateSystem csT;
Base::Rotation rot(1, 1, 2, 2);
csT.transform(rot);
Base::Placement dis = cs.displacement(csT);
EXPECT_EQ(rot.isSame(dis.getRotation(), 1e-15), true);
Base::Placement disT = csT.displacement(cs);
EXPECT_EQ(rot.inverse().isSame(disT.getRotation(), 1e-15), true);
}
TEST(CoordinateSystem, TestTransformPoint)
{
Base::CoordinateSystem cs;
Base::CoordinateSystem csT;
Base::Placement plm;
plm.setPosition(Base::Vector3d(1, 2, 3));
plm.setRotation(Base::Rotation(1, 1, 2, 2));
csT.transform(plm);
Base::Vector3d src(-1, 5, 3), dst;
plm.inverse().multVec(src, dst);
csT.transformTo(src);
EXPECT_EQ(src, dst);
}
TEST(CoordinateSystem, TestSetPlacement)
{
Base::CoordinateSystem cs;
Base::CoordinateSystem csT;
Base::Placement plm;
plm.setPosition(Base::Vector3d(1, 2, 3));
plm.setRotation(Base::Rotation(1, 1, 2, 2));
csT.transform(plm);
csT.transform(plm);
csT.transform(plm);
csT.setPlacement(plm);
Base::Placement dis = cs.displacement(csT);
EXPECT_EQ(plm.isSame(dis, 1e-15), true);
Base::Placement disT = csT.displacement(cs);
EXPECT_EQ(plm.inverse().isSame(disT, 1e-15), true);
}
// NOLINTEND

View File

@@ -0,0 +1,103 @@
#include <gtest/gtest.h>
#include <Base/DualNumber.h>
TEST(DualNumber, TestDefault)
{
Base::DualNumber dn;
EXPECT_EQ(dn.re, 0.0);
EXPECT_EQ(dn.du, 0.0);
}
TEST(DualNumber, TestNonDefault)
{
Base::DualNumber dn(1.0);
EXPECT_EQ(dn.re, 1.0);
EXPECT_EQ(dn.du, 0.0);
Base::DualNumber dn2(1.0, 2.0);
EXPECT_EQ(dn2.re, 1.0);
EXPECT_EQ(dn2.du, 2.0);
}
TEST(DualNumber, TestNegate)
{
Base::DualNumber dn(-Base::DualNumber(1.0, 2.0));
EXPECT_EQ(dn.re, -1.0);
EXPECT_EQ(dn.du, -2.0);
}
TEST(DualNumber, TestPlus)
{
Base::DualNumber dn1(1.0, 2.0);
Base::DualNumber dn2(2.0, -1.0);
Base::DualNumber dn3 = dn1 + dn2;
EXPECT_EQ(dn3.re, 3.0);
EXPECT_EQ(dn3.du, 1.0);
Base::DualNumber dn4 = dn1 + 2.0;
EXPECT_EQ(dn4.re, 3.0);
EXPECT_EQ(dn4.du, 2.0);
Base::DualNumber dn5 = 2.0 + dn1;
EXPECT_EQ(dn5.re, 3.0);
EXPECT_EQ(dn5.du, 2.0);
}
TEST(DualNumber, TestMinus)
{
Base::DualNumber dn1(1.0, 2.0);
Base::DualNumber dn2(2.0, -1.0);
Base::DualNumber dn3 = dn1 - dn2;
EXPECT_EQ(dn3.re, -1.0);
EXPECT_EQ(dn3.du, 3.0);
Base::DualNumber dn4 = dn1 - 2.0;
EXPECT_EQ(dn4.re, -1.0);
EXPECT_EQ(dn4.du, 2.0);
Base::DualNumber dn5 = 2.0 - dn1;
EXPECT_EQ(dn5.re, 1.0);
EXPECT_EQ(dn5.du, -2.0);
}
TEST(DualNumber, TestMultiply)
{
Base::DualNumber dn1(1.0, 2.0);
Base::DualNumber dn2(2.0, -1.0);
Base::DualNumber dn3 = dn1 * dn2;
EXPECT_EQ(dn3.re, 2.0);
EXPECT_EQ(dn3.du, 3.0);
Base::DualNumber dn4 = dn1 * 2.0;
EXPECT_EQ(dn4.re, 2.0);
EXPECT_EQ(dn4.du, 4.0);
Base::DualNumber dn5 = 2.0 * dn1;
EXPECT_EQ(dn5.re, 2.0);
EXPECT_EQ(dn5.du, 4.0);
}
TEST(DualNumber, TestDivide)
{
Base::DualNumber dn1(1.0, 2.0);
Base::DualNumber dn2(2.0, -1.0);
Base::DualNumber dn3 = dn1 / dn2;
EXPECT_EQ(dn3.re, 0.5);
EXPECT_EQ(dn3.du, 1.25);
Base::DualNumber dn4 = dn1 / 2.0;
EXPECT_EQ(dn4.re, 0.5);
EXPECT_EQ(dn4.du, 1.0);
}
TEST(DualNumber, TestPow)
{
Base::DualNumber dn1(3.0, 2.0);
Base::DualNumber dn2 = Base::pow(dn1, 2.0);
EXPECT_EQ(dn2.re, 9.0);
EXPECT_EQ(dn2.du, 12.0);
}

View File

@@ -0,0 +1,266 @@
#include <gtest/gtest.h>
#include <Base/DualQuaternion.h>
#include <Base/Tools.h>
TEST(DualQuaternion, TestDefault)
{
Base::DualQuat qq;
EXPECT_EQ(qq.x.re, 0.0);
EXPECT_EQ(qq.x.du, 0.0);
EXPECT_EQ(qq.y.re, 0.0);
EXPECT_EQ(qq.y.du, 0.0);
EXPECT_EQ(qq.z.re, 0.0);
EXPECT_EQ(qq.z.du, 0.0);
EXPECT_EQ(qq.w.re, 0.0);
EXPECT_EQ(qq.w.du, 0.0);
}
TEST(DualQuaternion, TestFromDouble)
{
Base::DualQuat qq(1.0, 2.0, 3.0, 4.0);
EXPECT_EQ(qq.x.re, 1.0);
EXPECT_EQ(qq.x.du, 0.0);
EXPECT_EQ(qq.y.re, 2.0);
EXPECT_EQ(qq.y.du, 0.0);
EXPECT_EQ(qq.z.re, 3.0);
EXPECT_EQ(qq.z.du, 0.0);
EXPECT_EQ(qq.w.re, 4.0);
EXPECT_EQ(qq.w.du, 0.0);
}
TEST(DualQuaternion, TestFromDoubles)
{
Base::DualQuat qq(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0);
EXPECT_EQ(qq.x.re, 1.0);
EXPECT_EQ(qq.x.du, 5.0);
EXPECT_EQ(qq.y.re, 2.0);
EXPECT_EQ(qq.y.du, 6.0);
EXPECT_EQ(qq.z.re, 3.0);
EXPECT_EQ(qq.z.du, 7.0);
EXPECT_EQ(qq.w.re, 4.0);
EXPECT_EQ(qq.w.du, 8.0);
}
TEST(DualQuaternion, TestFromDual)
{
Base::DualNumber dn(1.0, 2.0);
Base::DualQuat qq(dn, dn, dn, dn);
EXPECT_EQ(qq.x.re, 1.0);
EXPECT_EQ(qq.x.du, 2.0);
EXPECT_EQ(qq.y.re, 1.0);
EXPECT_EQ(qq.y.du, 2.0);
EXPECT_EQ(qq.z.re, 1.0);
EXPECT_EQ(qq.z.du, 2.0);
EXPECT_EQ(qq.w.re, 1.0);
EXPECT_EQ(qq.w.du, 2.0);
}
TEST(DualQuaternion, TestIdentity)
{
Base::DualQuat qq = Base::DualQuat::identity();
EXPECT_EQ(qq.x.re, 0.0);
EXPECT_EQ(qq.x.du, 0.0);
EXPECT_EQ(qq.y.re, 0.0);
EXPECT_EQ(qq.y.du, 0.0);
EXPECT_EQ(qq.z.re, 0.0);
EXPECT_EQ(qq.z.du, 0.0);
EXPECT_EQ(qq.w.re, 1.0);
EXPECT_EQ(qq.w.du, 0.0);
}
TEST(DualQuaternion, TestReal)
{
Base::DualQuat qq = Base::DualQuat(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0).real();
EXPECT_EQ(qq.x.re, 1.0);
EXPECT_EQ(qq.x.du, 0.0);
EXPECT_EQ(qq.y.re, 2.0);
EXPECT_EQ(qq.y.du, 0.0);
EXPECT_EQ(qq.z.re, 3.0);
EXPECT_EQ(qq.z.du, 0.0);
EXPECT_EQ(qq.w.re, 4.0);
EXPECT_EQ(qq.w.du, 0.0);
}
TEST(DualQuaternion, TestDual)
{
Base::DualQuat qq = Base::DualQuat(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0).dual();
EXPECT_EQ(qq.x.re, 5.0);
EXPECT_EQ(qq.x.du, 0.0);
EXPECT_EQ(qq.y.re, 6.0);
EXPECT_EQ(qq.y.du, 0.0);
EXPECT_EQ(qq.z.re, 7.0);
EXPECT_EQ(qq.z.du, 0.0);
EXPECT_EQ(qq.w.re, 8.0);
EXPECT_EQ(qq.w.du, 0.0);
}
TEST(DualQuaternion, TestConjugate)
{
Base::DualQuat qq = Base::DualQuat(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0).conj();
EXPECT_EQ(qq.x.re, -1.0);
EXPECT_EQ(qq.x.du, -5.0);
EXPECT_EQ(qq.y.re, -2.0);
EXPECT_EQ(qq.y.du, -6.0);
EXPECT_EQ(qq.z.re, -3.0);
EXPECT_EQ(qq.z.du, -7.0);
EXPECT_EQ(qq.w.re, 4.0);
EXPECT_EQ(qq.w.du, 8.0);
}
TEST(DualQuaternion, TestVec)
{
Base::DualQuat qq = Base::DualQuat(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0).vec();
EXPECT_EQ(qq.x.re, 1.0);
EXPECT_EQ(qq.x.du, 5.0);
EXPECT_EQ(qq.y.re, 2.0);
EXPECT_EQ(qq.y.du, 6.0);
EXPECT_EQ(qq.z.re, 3.0);
EXPECT_EQ(qq.z.du, 7.0);
EXPECT_EQ(qq.w.re, 0.0);
EXPECT_EQ(qq.w.du, 0.0);
}
TEST(DualQuaternion, TestLength)
{
Base::DualQuat qq = Base::DualQuat(0.0, 0.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0);
EXPECT_DOUBLE_EQ(qq.length(), 5.0);
}
TEST(DualQuaternion, TestTheta)
{
Base::DualQuat qq = Base::DualQuat(0.0, 0.0, 3.0, 3.0, 5.0, 6.0, 7.0, 8.0);
EXPECT_DOUBLE_EQ(qq.theta(), Base::toRadians(90.0));
}
TEST(DualQuaternion, TestDot)
{
Base::DualQuat qq1 = Base::DualQuat(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0);
Base::DualQuat qq2 = Base::DualQuat(1.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 2.0);
double dot = Base::DualQuat::dot(qq1, qq2);
EXPECT_DOUBLE_EQ(dot, 10.0);
}
TEST(DualQuaternion, TestNegate)
{
Base::DualQuat qq = Base::DualQuat(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0);
Base::DualQuat dn(-qq);
EXPECT_EQ(dn.x.re, -1.0);
EXPECT_EQ(dn.x.du, -5.0);
EXPECT_EQ(dn.y.re, -2.0);
EXPECT_EQ(dn.y.du, -6.0);
EXPECT_EQ(dn.z.re, -3.0);
EXPECT_EQ(dn.z.du, -7.0);
EXPECT_EQ(dn.w.re, -4.0);
EXPECT_EQ(dn.w.du, -8.0);
}
TEST(DualQuaternion, TestPlus)
{
Base::DualQuat qq1 = Base::DualQuat(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0);
Base::DualQuat qq2 = Base::DualQuat(1.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 2.0);
Base::DualQuat qq3 = qq1 + qq2;
EXPECT_EQ(qq3.x.re, 2.0);
EXPECT_EQ(qq3.x.du, 7.0);
EXPECT_EQ(qq3.y.re, 3.0);
EXPECT_EQ(qq3.y.du, 8.0);
EXPECT_EQ(qq3.z.re, 4.0);
EXPECT_EQ(qq3.z.du, 9.0);
EXPECT_EQ(qq3.w.re, 5.0);
EXPECT_EQ(qq3.w.du, 10.0);
}
TEST(DualQuaternion, TestMinus)
{
Base::DualQuat qq1 = Base::DualQuat(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0);
Base::DualQuat qq2 = Base::DualQuat(1.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 2.0);
Base::DualQuat qq3 = qq1 - qq2;
EXPECT_EQ(qq3.x.re, 0.0);
EXPECT_EQ(qq3.x.du, 3.0);
EXPECT_EQ(qq3.y.re, 1.0);
EXPECT_EQ(qq3.y.du, 4.0);
EXPECT_EQ(qq3.z.re, 2.0);
EXPECT_EQ(qq3.z.du, 5.0);
EXPECT_EQ(qq3.w.re, 3.0);
EXPECT_EQ(qq3.w.du, 6.0);
}
TEST(DualQuaternion, TestMultiplyQuat)
{
Base::DualQuat qq1 = Base::DualQuat(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0);
Base::DualQuat qq2 = Base::DualQuat(1.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 2.0);
Base::DualQuat qq3 = qq1 * qq2;
EXPECT_EQ(qq3.x.re, 4.0);
EXPECT_EQ(qq3.x.du, 20.0);
EXPECT_EQ(qq3.y.re, 8.0);
EXPECT_EQ(qq3.y.du, 32.0);
EXPECT_EQ(qq3.z.re, 6.0);
EXPECT_EQ(qq3.z.du, 26.0);
EXPECT_EQ(qq3.w.re, -2.0);
EXPECT_EQ(qq3.w.du, -14.0);
}
TEST(DualQuaternion, TestMultiplyNumber)
{
Base::DualQuat qq1 = Base::DualQuat(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0);
Base::DualNumber dn1(1.0, 2.0);
Base::DualQuat qq4 = qq1 * dn1;
EXPECT_EQ(qq4.x.re, 1.0);
EXPECT_EQ(qq4.x.du, 7.0);
EXPECT_EQ(qq4.y.re, 2.0);
EXPECT_EQ(qq4.y.du, 10.0);
EXPECT_EQ(qq4.z.re, 3.0);
EXPECT_EQ(qq4.z.du, 13.0);
EXPECT_EQ(qq4.w.re, 4.0);
EXPECT_EQ(qq4.w.du, 16.0);
Base::DualQuat qq5 = dn1 * qq1;
EXPECT_EQ(qq5.x.re, 1.0);
EXPECT_EQ(qq5.x.du, 7.0);
EXPECT_EQ(qq5.y.re, 2.0);
EXPECT_EQ(qq5.y.du, 10.0);
EXPECT_EQ(qq5.z.re, 3.0);
EXPECT_EQ(qq5.z.du, 13.0);
EXPECT_EQ(qq5.w.re, 4.0);
EXPECT_EQ(qq5.w.du, 16.0);
}
TEST(DualQuaternion, TestMultiplyScalar)
{
Base::DualQuat qq1 = Base::DualQuat(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0);
Base::DualQuat qq4 = qq1 * 2.0;
EXPECT_EQ(qq4.x.re, 2.0);
EXPECT_EQ(qq4.x.du, 10.0);
EXPECT_EQ(qq4.y.re, 4.0);
EXPECT_EQ(qq4.y.du, 12.0);
EXPECT_EQ(qq4.z.re, 6.0);
EXPECT_EQ(qq4.z.du, 14.0);
EXPECT_EQ(qq4.w.re, 8.0);
EXPECT_EQ(qq4.w.du, 16.0);
Base::DualQuat qq5 = 2.0 * qq1;
EXPECT_EQ(qq5.x.re, 2.0);
EXPECT_EQ(qq5.x.du, 10.0);
EXPECT_EQ(qq5.y.re, 4.0);
EXPECT_EQ(qq5.y.du, 12.0);
EXPECT_EQ(qq5.z.re, 6.0);
EXPECT_EQ(qq5.z.du, 14.0);
EXPECT_EQ(qq5.w.re, 8.0);
EXPECT_EQ(qq5.w.du, 16.0);
}
TEST(DualQuaternion, TestPow)
{
const double epsilon = 1e-12;
Base::DualQuat qq1 = Base::DualQuat(1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0);
Base::DualQuat qq2 = qq1.pow(2.0);
EXPECT_NEAR(qq2.x.re, 0.0, epsilon);
EXPECT_NEAR(qq2.x.du, 0.0, epsilon);
EXPECT_NEAR(qq2.y.re, 0.0, epsilon);
EXPECT_NEAR(qq2.y.du, 0.0, epsilon);
EXPECT_NEAR(qq2.z.re, 0.0, epsilon);
EXPECT_NEAR(qq2.z.du, 0.0, epsilon);
EXPECT_NEAR(qq2.w.re, -1.0, epsilon);
EXPECT_NEAR(qq2.w.du, 0.0, epsilon);
}

248
tests/src/Base/FileInfo.cpp Normal file
View File

@@ -0,0 +1,248 @@
#include <gtest/gtest.h>
#include <Base/FileInfo.h>
#include <Base/Stream.h>
#include <Base/TimeInfo.h>
#include <filesystem>
class FileInfoTest: public ::testing::Test
{
protected:
FileInfoTest()
{
tmp.setFile(Base::FileInfo::getTempPath() + "fctest");
tmp.createDirectory();
file.setFile(tmp.filePath() + "/test.txt");
dir.setFile(tmp.filePath() + "/subdir");
}
void SetUp() override
{
Base::ofstream str(file, std::ios::out);
str << "Test\n";
str.close();
dir.createDirectory();
}
void TearDown() override
{
EXPECT_TRUE(file.deleteFile());
EXPECT_TRUE(dir.deleteDirectory());
}
protected:
Base::FileInfo tmp;
Base::FileInfo file;
Base::FileInfo dir;
};
TEST_F(FileInfoTest, TestDirectoryPath)
{
Base::FileInfo relfile("nofile.txt");
relfile.setFile(relfile.dirPath());
EXPECT_TRUE(relfile.exists());
}
TEST_F(FileInfoTest, TestExistsDirectory)
{
EXPECT_TRUE(tmp.exists());
}
TEST_F(FileInfoTest, TestCreateDirectory)
{
Base::FileInfo path;
path.setFile(tmp.filePath() + "/subdir1/subdir2");
EXPECT_FALSE(path.createDirectory());
}
TEST_F(FileInfoTest, TestDirectoryContent)
{
auto content = tmp.getDirectoryContent();
EXPECT_EQ(content.size(), 2);
EXPECT_TRUE(content[0].exists());
EXPECT_TRUE(content[1].exists());
}
TEST_F(FileInfoTest, TestCheckPermission)
{
EXPECT_TRUE(file.isReadable());
EXPECT_TRUE(file.isWritable());
}
TEST_F(FileInfoTest, TestCheckNoPermission)
{
std::string path = tmp.filePath();
Base::FileInfo nofile(path + "/nofile");
EXPECT_FALSE(nofile.isReadable());
EXPECT_FALSE(nofile.isWritable());
}
TEST_F(FileInfoTest, TestSetPermission)
{
file.setPermissions(Base::FileInfo::ReadOnly);
EXPECT_TRUE(file.isReadable());
EXPECT_FALSE(file.isWritable());
file.setPermissions(Base::FileInfo::WriteOnly);
EXPECT_FALSE(file.isReadable());
EXPECT_TRUE(file.isWritable());
file.setPermissions(Base::FileInfo::ReadWrite);
EXPECT_TRUE(file.isReadable());
EXPECT_TRUE(file.isWritable());
}
TEST_F(FileInfoTest, TestCheckFile)
{
EXPECT_TRUE(file.isFile());
EXPECT_FALSE(dir.isFile());
std::string path = tmp.filePath();
Base::FileInfo file2(path + "/file2");
EXPECT_TRUE(file2.isFile());
}
TEST_F(FileInfoTest, TestCheckDirectory)
{
EXPECT_FALSE(file.isDir());
EXPECT_TRUE(dir.isDir());
std::string path = tmp.filePath();
Base::FileInfo file2(path + "/file2");
EXPECT_FALSE(file2.isDir());
}
TEST_F(FileInfoTest, TestSize)
{
EXPECT_EQ(file.size(), 5);
}
TEST_F(FileInfoTest, TestLastModified)
{
EXPECT_FALSE(file.lastModified().isNull());
std::string path = tmp.filePath();
Base::FileInfo nofile(path + "/nofile.txt");
EXPECT_TRUE(nofile.lastModified().isNull());
}
TEST_F(FileInfoTest, TestDeleteFile)
{
std::string path = tmp.filePath();
Base::FileInfo file2(path + "/nofile.txt");
EXPECT_FALSE(file2.deleteFile());
}
TEST_F(FileInfoTest, TestRenameFile)
{
std::string path = tmp.filePath();
Base::FileInfo file2(path + "/file2");
EXPECT_FALSE(file2.renameFile((path + "/file3").c_str()));
EXPECT_TRUE(file.renameFile((path + "/file2").c_str()));
}
TEST_F(FileInfoTest, TestCopyFile)
{
std::string path = tmp.filePath();
Base::FileInfo copy(path + "/copy.txt");
EXPECT_TRUE(file.copyTo(copy.filePath().c_str()));
EXPECT_TRUE(copy.deleteFile());
}
// Tests for pathToString / stringToPath UTF-8 round-trip (PR #28222)
class FileInfoPathConversionTest: public ::testing::Test
{
};
TEST_F(FileInfoPathConversionTest, RoundTripAsciiPath)
{
std::string utf8 = "/some/simple/path";
auto fsPath = Base::FileInfo::stringToPath(utf8);
std::string result = Base::FileInfo::pathToString(fsPath);
EXPECT_EQ(result, utf8);
}
TEST_F(FileInfoPathConversionTest, RoundTripNonAsciiPath)
{
// German umlaut, common in Windows usernames (the exact bug scenario)
std::string utf8 = "/home/m\xc3\xbcller/Documents"; // müller in UTF-8
auto fsPath = Base::FileInfo::stringToPath(utf8);
std::string result = Base::FileInfo::pathToString(fsPath);
EXPECT_EQ(result, utf8);
}
TEST_F(FileInfoPathConversionTest, RoundTripChineseCharacters)
{
// CJK characters: 用户 (user) in UTF-8
std::string utf8 = "/home/\xe7\x94\xa8\xe6\x88\xb7/data";
auto fsPath = Base::FileInfo::stringToPath(utf8);
std::string result = Base::FileInfo::pathToString(fsPath);
EXPECT_EQ(result, utf8);
}
TEST_F(FileInfoPathConversionTest, RoundTripAccentedCharacters)
{
// French accented characters: café in UTF-8
std::string utf8 = "/tmp/caf\xc3\xa9/file.txt";
auto fsPath = Base::FileInfo::stringToPath(utf8);
std::string result = Base::FileInfo::pathToString(fsPath);
EXPECT_EQ(result, utf8);
}
TEST_F(FileInfoPathConversionTest, RoundTripEmptyString)
{
std::string utf8;
auto fsPath = Base::FileInfo::stringToPath(utf8);
std::string result = Base::FileInfo::pathToString(fsPath);
EXPECT_EQ(result, utf8);
}
TEST_F(FileInfoPathConversionTest, PathToStringPreservesUtf8)
{
// Construct a path from a wide string directly and verify pathToString produces valid UTF-8
std::filesystem::path p = Base::FileInfo::stringToPath("/tmp/\xc3\xa4\xc3\xb6\xc3\xbc"); // äöü
std::string result = Base::FileInfo::pathToString(p);
// Verify the UTF-8 bytes are preserved
EXPECT_NE(result.find("\xc3\xa4"), std::string::npos); // ä
EXPECT_NE(result.find("\xc3\xb6"), std::string::npos); // ö
EXPECT_NE(result.find("\xc3\xbc"), std::string::npos); // ü
}
TEST_F(FileInfoPathConversionTest, StringToPathProducesValidPath)
{
// Verify that stringToPath produces a path that can be appended to
std::string utf8 = "/home/\xc3\xbc\x73\x65r"; // üser
auto fsPath = Base::FileInfo::stringToPath(utf8);
auto child = fsPath / "subdir";
std::string childStr = Base::FileInfo::pathToString(child);
// The child path should contain both the parent with non-ASCII and the appended segment
EXPECT_NE(childStr.find("\xc3\xbc"), std::string::npos);
EXPECT_NE(childStr.find("subdir"), std::string::npos);
}
#ifdef _WIN32 // NOTE FC_OS_WIN32 is not available in the test code
TEST_F(FileInfoPathConversionTest, WidePathToUtf8)
{
// Simulate a path obtained from the Windows OS (e.g. GetModuleFileNameW), which arrives as a
// UTF-16 wide string. Verify pathToString encodes it as UTF-8.
// L"C:\\Users\\müller" -- ü is U+00FC
std::filesystem::path widePath(L"C:\\Users\\m\u00FCller\\Documents");
std::string result = Base::FileInfo::pathToString(widePath);
// Must contain the UTF-8 encoding of ü (0xC3 0xBC), not the ANSI mangled version
EXPECT_NE(result.find("\xc3\xbc"), std::string::npos);
EXPECT_NE(result.find("Documents"), std::string::npos);
}
TEST_F(FileInfoPathConversionTest, NaivePathStringLosesNonAscii)
{
// Demonstrate the actual bug: on Windows, fs::path::string() converts to the ANSI codepage,
// which mangles non-ASCII characters. This is what the old code did (before PR #28222) and why
// pathToString is needed.
std::filesystem::path widePath(L"C:\\Users\\m\u00FCller");
std::string naive = widePath.string(); // ANSI codepage on Windows
std::string safe = Base::FileInfo::pathToString(widePath); // UTF-8
// The naive .string() result will differ from the correct UTF-8 encoding
EXPECT_NE(naive, safe);
}
#endif

72
tests/src/Base/Handle.cpp Normal file
View File

@@ -0,0 +1,72 @@
#include <gtest/gtest.h>
#include <Base/Handle.h>
class Data: public Base::Handled
{
int myValue {};
public:
int getValue() const
{
return myValue;
}
void setValue(int val)
{
myValue = val;
}
};
TEST(Reference, TestNull)
{
Base::Reference<Data> data;
EXPECT_EQ(data.getRefCount(), 0);
}
TEST(Reference, TestConstructor)
{
Base::Reference<Data> data(new Data);
EXPECT_EQ(data.getRefCount(), 1);
}
TEST(Reference, TestCopy)
{
Base::Reference<Data> data(new Data);
Base::Reference<Data> copy(data);
EXPECT_EQ(data.getRefCount(), 2);
EXPECT_EQ(copy.getRefCount(), 2);
EXPECT_EQ(data, copy);
EXPECT_EQ(data.isValid(), true);
EXPECT_EQ(copy.isValid(), true);
EXPECT_EQ(data.isNull(), false);
EXPECT_EQ(copy.isNull(), false);
}
TEST(Reference, TestAssignRaw)
{
Base::Reference<Data> data = new Data();
EXPECT_EQ(data->getValue(), 0);
EXPECT_EQ(data.getRefCount(), 1);
}
TEST(Reference, TestAssignRef)
{
Base::Reference<Data> data = new Data();
Base::Reference<Data> copy;
copy = data;
EXPECT_EQ(data.getRefCount(), 2);
EXPECT_EQ(copy.getRefCount(), 2);
EXPECT_EQ(data, copy);
EXPECT_EQ(data.isValid(), true);
EXPECT_EQ(copy.isValid(), true);
EXPECT_EQ(data.isNull(), false);
EXPECT_EQ(copy.isNull(), false);
}
TEST(Reference, TestRefHandle)
{
Base::Reference<Data> data = new Data();
data->ref();
EXPECT_EQ(data.getRefCount(), 2);
data->unref();
EXPECT_EQ(data.getRefCount(), 1);
}

View File

@@ -0,0 +1,765 @@
#include <Base/Builder3D.h>
#include <Inventor/SoDB.h>
#include <Inventor/SoInput.h>
#include <Inventor/nodes/SoSeparator.h>
#include <QDebug>
#include <QTest>
#include <sstream>
Q_DECLARE_METATYPE(Base::Vector3f)
Q_DECLARE_METATYPE(Base::ColorRGB)
Q_DECLARE_METATYPE(Base::Line3f)
Q_DECLARE_METATYPE(Base::BindingElement::Binding)
Q_DECLARE_METATYPE(Base::DrawStyle)
Q_DECLARE_METATYPE(Base::DrawStyle::Style)
Q_DECLARE_METATYPE(Base::PolygonOffset)
Q_DECLARE_METATYPE(Base::PolygonOffset::Style)
class testInventorBuilder: public QObject
{
Q_OBJECT
public:
testInventorBuilder()
: builder(output)
{}
~testInventorBuilder() override = default;
SoNode* loadBuffer(const std::string& buffer)
{
SoInput in;
in.setBuffer((void*)buffer.c_str(), buffer.size());
return SoDB::readAll(&in);
}
private Q_SLOTS:
void initTestCase()
{
SoDB::init();
}
void initTestCase_data()
{}
void cleanupTestCase()
{
SoDB::finish();
}
void init()
{}
void cleanup()
{
// clear the buffer
output.str(std::string());
}
void test_Invalid()
{
SoNode* node = loadBuffer("Hello, World");
QCOMPARE(node, nullptr);
}
void test_Output()
{
std::stringstream str;
Base::InventorBuilder builder(str);
QCOMPARE(str.str().c_str(), "#Inventor V2.1 ascii \n\n");
}
void test_MaterialBinding_data()
{
// clang-format off
QTest::addColumn<Base::BindingElement::Binding>("input");
QTest::addColumn<QString>("result");
QTest::newRow("MaterialBinding") << Base::BindingElement::Binding::Overall
<< "MaterialBinding { value OVERALL } \n";
QTest::newRow("MaterialBinding") << Base::BindingElement::Binding::PerPart
<< "MaterialBinding { value PER_PART } \n";
QTest::newRow("MaterialBinding") << Base::BindingElement::Binding::PerPartIndexed
<< "MaterialBinding { value PER_PART_INDEXED } \n";
QTest::newRow("MaterialBinding") << Base::BindingElement::Binding::PerFace
<< "MaterialBinding { value PER_FACE } \n";
QTest::newRow("MaterialBinding") << Base::BindingElement::Binding::PerFaceIndexed
<< "MaterialBinding { value PER_FACE_INDEXED } \n";
QTest::newRow("MaterialBinding") << Base::BindingElement::Binding::PerVertex
<< "MaterialBinding { value PER_VERTEX } \n";
QTest::newRow("MaterialBinding") << Base::BindingElement::Binding::PerVertexIndexed
<< "MaterialBinding { value PER_VERTEX_INDEXED } \n";
QTest::newRow("MaterialBinding") << Base::BindingElement::Binding::Default
<< "MaterialBinding { value OVERALL } \n";
QTest::newRow("MaterialBinding") << Base::BindingElement::Binding::None
<< "MaterialBinding { value OVERALL } \n";
// clang-format on
}
void test_MaterialBinding()
{
QFETCH(Base::BindingElement::Binding, input);
QFETCH(QString, result);
Base::MaterialBindingItem item;
item.setValue(input);
builder.addNode(item);
QString string = QString::fromStdString(output.str());
QCOMPARE(string, result);
}
void test_Label_data()
{
auto result =
R"(Label {
label "FreeCAD"
}
)";
QTest::addColumn<QString>("input");
QTest::addColumn<QString>("result");
QTest::newRow("Label") << "FreeCAD" << result;
}
void test_Label()
{
QFETCH(QString, input);
QFETCH(QString, result);
Base::LabelItem item {input.toStdString()};
builder.addNode(item);
QString string = QString::fromStdString(output.str());
QCOMPARE(string, result);
}
void test_Info_data()
{
auto result =
R"(Info {
string "FreeCAD"
}
)";
QTest::addColumn<QString>("input");
QTest::addColumn<QString>("result");
QTest::newRow("Info") << "FreeCAD" << result;
}
void test_Info()
{
QFETCH(QString, input);
QFETCH(QString, result);
Base::InfoItem item {input.toStdString()};
builder.addNode(item);
QString string = QString::fromStdString(output.str());
QCOMPARE(string, result);
}
void test_Text2_data()
{
auto result = "Text2 { string \"FreeCAD\" }\n";
QTest::addColumn<QString>("input");
QTest::addColumn<QString>("result");
QTest::newRow("Text2") << "FreeCAD" << result;
}
void test_Text2()
{
QFETCH(QString, input);
QFETCH(QString, result);
Base::Text2Item item {input.toStdString()};
builder.addNode(item);
QString string = QString::fromStdString(output.str());
QCOMPARE(string, result);
}
void test_BaseColor_data()
{
auto result =
R"(BaseColor {
rgb 0.21 0.3 0.4
}
)";
QTest::addColumn<Base::ColorRGB>("input");
QTest::addColumn<QString>("result");
QTest::newRow("BaseColor") << Base::ColorRGB {0.21F, 0.3F, 0.4F} << result;
}
void test_BaseColor()
{
QFETCH(Base::ColorRGB, input);
QFETCH(QString, result);
Base::BaseColorItem item {input};
builder.addNode(item);
QString string = QString::fromStdString(output.str());
QCOMPARE(string, result);
}
void test_Material_data()
{
auto result =
R"(Material {
diffuseColor 1 0 0
}
)";
QTest::addColumn<Base::ColorRGB>("input");
QTest::addColumn<QString>("result");
QTest::newRow("Material") << Base::ColorRGB {1, 0, 0} << result;
}
void test_Material()
{
QFETCH(Base::ColorRGB, input);
QFETCH(QString, result);
Base::MaterialItem item;
item.setDiffuseColor({input});
builder.addNode(item);
QString string = QString::fromStdString(output.str());
QCOMPARE(string, result);
}
void test_Materials_data()
{
auto result =
R"(Material {
diffuseColor [
1 0 0
0 1 0
0 0 1
]
}
)";
QTest::addColumn<Base::ColorRGB>("input1");
QTest::addColumn<Base::ColorRGB>("input2");
QTest::addColumn<Base::ColorRGB>("input3");
QTest::addColumn<QString>("result");
QTest::newRow("Material") << Base::ColorRGB {1, 0, 0} << Base::ColorRGB {0, 1, 0}
<< Base::ColorRGB {0, 0, 1} << result;
}
void test_Materials()
{
QFETCH(Base::ColorRGB, input1);
QFETCH(Base::ColorRGB, input2);
QFETCH(Base::ColorRGB, input3);
QFETCH(QString, result);
Base::MaterialItem item;
item.setDiffuseColor({input1, input2, input3});
builder.addNode(item);
QString string = QString::fromStdString(output.str());
QCOMPARE(string, result);
SoNode* node = loadBuffer(output.str());
QVERIFY(node != nullptr);
QVERIFY(node->getRefCount() == 0);
}
void test_DrawStyle_data()
{
auto result =
R"(DrawStyle {
style FILLED
pointSize 3
lineWidth 3
linePattern 0xf0f0
}
)";
QTest::addColumn<Base::DrawStyle::Style>("styleEnum");
QTest::addColumn<ushort>("pointSize");
QTest::addColumn<ushort>("lineWidth");
QTest::addColumn<ushort>("linePattern");
QTest::addColumn<QString>("result");
QTest::newRow("DrawStyle")
<< Base::DrawStyle::Style::Filled << ushort(3) << ushort(3) << ushort(0xf0f0) << result;
}
void test_DrawStyle()
{
QFETCH(Base::DrawStyle::Style, styleEnum);
QFETCH(ushort, pointSize);
QFETCH(ushort, lineWidth);
QFETCH(ushort, linePattern);
QFETCH(QString, result);
Base::DrawStyleItem item;
Base::DrawStyle style;
style.style = styleEnum;
style.pointSize = pointSize;
style.lineWidth = lineWidth;
style.linePattern = linePattern;
item.setValue(style);
builder.addNode(item);
QString string = QString::fromStdString(output.str());
QCOMPARE(string, result);
}
void test_ShapeHints_data()
{
auto result =
R"(ShapeHints {
creaseAngle 0.5
vertexOrdering UNKNOWN_ORDERING
shapeType UNKNOWN_SHAPE_TYPE
}
)";
QTest::addColumn<float>("input");
QTest::addColumn<QString>("result");
QTest::newRow("ShapeHints") << 0.5F << result;
}
void test_ShapeHints()
{
QFETCH(float, input);
QFETCH(QString, result);
Base::ShapeHintsItem item {input};
builder.addNode(item);
QString string = QString::fromStdString(output.str());
QCOMPARE(string, result);
}
void test_PolygonOffset_data()
{
auto result =
R"(PolygonOffset {
factor 2
units 1
styles FILLED
on FALSE
}
)";
QTest::addColumn<Base::PolygonOffset::Style>("styleEnum");
QTest::addColumn<float>("factor");
QTest::addColumn<float>("units");
QTest::addColumn<bool>("on");
QTest::addColumn<QString>("result");
QTest::newRow("PolygonOffset")
<< Base::PolygonOffset::Style::Filled << 2.0F << 1.0F << false << result;
}
void test_PolygonOffset()
{
QFETCH(Base::PolygonOffset::Style, styleEnum);
QFETCH(float, factor);
QFETCH(float, units);
QFETCH(bool, on);
QFETCH(QString, result);
Base::PolygonOffsetItem item;
Base::PolygonOffset offset;
offset.factor = factor;
offset.units = units;
offset.style = styleEnum;
offset.on = on;
item.setValue(offset);
builder.addNode(item);
QString string = QString::fromStdString(output.str());
QCOMPARE(string, result);
}
void test_PointSet_data()
{
auto result = "PointSet { }\n";
QTest::addColumn<QString>("result");
QTest::newRow("PointSet") << result;
}
void test_PointSet()
{
QFETCH(QString, result);
Base::PointSetItem item;
builder.addNode(item);
QString string = QString::fromStdString(output.str());
QCOMPARE(string, result);
}
void test_LineSet_data()
{
auto result = "LineSet { }\n";
QTest::addColumn<QString>("result");
QTest::newRow("LineSet") << result;
}
void test_LineSet()
{
QFETCH(QString, result);
Base::LineSetItem item;
builder.addNode(item);
QString string = QString::fromStdString(output.str());
QCOMPARE(string, result);
}
void test_FaceSet_data()
{
QTest::addColumn<int>("num");
QTest::newRow("FaceSet") << 2;
}
void test_FaceSet()
{
QFETCH(int, num);
Base::FaceSetItem item {{num}};
builder.addNode(item);
SoNode* node = loadBuffer(output.str());
QVERIFY(node != nullptr);
}
void test_IndexedLineSet_data()
{
QTest::addColumn<int>("c1");
QTest::addColumn<int>("c2");
QTest::addColumn<int>("c3");
QTest::newRow("IndexedLineSet") << 0 << 1 << 2;
}
void test_IndexedLineSet()
{
QFETCH(int, c1);
QFETCH(int, c2);
QFETCH(int, c3);
Base::IndexedLineSetItem item {{c1, c2, c3}};
builder.addNode(item);
SoNode* node = loadBuffer(output.str());
QVERIFY(node != nullptr);
}
void test_IndexedFaceSet_data()
{
QTest::addColumn<int>("c1");
QTest::addColumn<int>("c2");
QTest::addColumn<int>("c3");
QTest::addColumn<int>("c4");
QTest::newRow("IndexedFaceSet") << 0 << 1 << 2 << -1;
}
void test_IndexedFaceSet()
{
QFETCH(int, c1);
QFETCH(int, c2);
QFETCH(int, c3);
QFETCH(int, c4);
Base::IndexedFaceSetItem item {{c1, c2, c3, c4}};
builder.addNode(item);
SoNode* node = loadBuffer(output.str());
QVERIFY(node != nullptr);
}
void test_Transform()
{
Base::Placement plm;
Base::TransformItem item {plm};
builder.addNode(item);
SoNode* node = loadBuffer(output.str());
QVERIFY(node != nullptr);
}
void test_Normal_data()
{
auto result =
R"(Normal {
vector 1 0 0.5
}
)";
QTest::addColumn<Base::Vector3f>("input");
QTest::addColumn<QString>("result");
QTest::newRow("Normal") << Base::Vector3f {1, 0, 0.5} << result;
}
void test_Normal()
{
QFETCH(Base::Vector3f, input);
QFETCH(QString, result);
builder.addNode(Base::NormalItem {{input}});
QString string = QString::fromStdString(output.str());
QCOMPARE(string, result);
}
void test_LineItem_data()
{
QTest::addColumn<Base::Line3f>("line");
QTest::addColumn<Base::DrawStyle>("style");
QTest::newRow("LineItem") << Base::Line3f {} << Base::DrawStyle {};
}
void test_LineItem()
{
QFETCH(Base::Line3f, line);
QFETCH(Base::DrawStyle, style);
Base::LineItem item {line, style};
builder.addNode(item);
SoNode* node = loadBuffer(output.str());
QVERIFY(node != nullptr);
}
void test_MultiLineItem_data()
{
QTest::addColumn<Base::Vector3f>("p1");
QTest::addColumn<Base::Vector3f>("p2");
QTest::addColumn<Base::Vector3f>("p3");
QTest::addColumn<Base::DrawStyle>("style");
QTest::newRow("MultiLineItem") << Base::Vector3f {0, 0, 0} << Base::Vector3f {1, 0, 0}
<< Base::Vector3f {1, 1, 0} << Base::DrawStyle {};
}
void test_MultiLineItem()
{
QFETCH(Base::Vector3f, p1);
QFETCH(Base::Vector3f, p2);
QFETCH(Base::Vector3f, p3);
QFETCH(Base::DrawStyle, style);
Base::MultiLineItem item {{p1, p2, p3}, style};
builder.addNode(item);
SoNode* node = loadBuffer(output.str());
QVERIFY(node != nullptr);
}
void test_ArrowItem_data()
{
QTest::addColumn<Base::Line3f>("line");
QTest::addColumn<Base::DrawStyle>("style");
QTest::newRow("Arrow") << Base::Line3f {Base::Vector3f {0, 0, 10}, Base::Vector3f {}}
<< Base::DrawStyle {};
}
void test_ArrowItem()
{
QFETCH(Base::Line3f, line);
QFETCH(Base::DrawStyle, style);
Base::ArrowItem item {line, style};
builder.addNode(item);
SoNode* node = loadBuffer(output.str());
QVERIFY(node != nullptr);
}
void test_BoundingBoxItem_data()
{
QTest::addColumn<Base::Vector3f>("p1");
QTest::addColumn<Base::Vector3f>("p2");
QTest::addColumn<Base::DrawStyle>("style");
QTest::newRow("BoundingBoxItem")
<< Base::Vector3f {0, 0, 0} << Base::Vector3f {1, 1, 1} << Base::DrawStyle {};
}
void test_BoundingBoxItem()
{
QFETCH(Base::Vector3f, p1);
QFETCH(Base::Vector3f, p2);
QFETCH(Base::DrawStyle, style);
Base::BoundingBoxItem item {p1, p2, style};
builder.addNode(item);
SoNode* node = loadBuffer(output.str());
QVERIFY(node != nullptr);
}
void test_Coordinate3Item_data()
{
QTest::addColumn<Base::Vector3f>("p1");
QTest::addColumn<Base::Vector3f>("p2");
QTest::addColumn<Base::Vector3f>("p3");
QTest::newRow("Coordinate3Item")
<< Base::Vector3f {0, 0, 0} << Base::Vector3f {1, 0, 0} << Base::Vector3f {1, 1, 0};
}
void test_Coordinate3Item()
{
QFETCH(Base::Vector3f, p1);
QFETCH(Base::Vector3f, p2);
QFETCH(Base::Vector3f, p3);
Base::Coordinate3Item item {{p1, p2, p3}};
builder.addNode(item);
SoNode* node = loadBuffer(output.str());
QVERIFY(node != nullptr);
}
void test_PointItem_data()
{
QTest::addColumn<Base::Vector3f>("point");
QTest::addColumn<Base::DrawStyle>("style");
QTest::newRow("PointItem") << Base::Vector3f {} << Base::DrawStyle {};
}
void test_PointItem()
{
QFETCH(Base::Vector3f, point);
QFETCH(Base::DrawStyle, style);
Base::PointItem item {point, style};
builder.addNode(item);
SoNode* node = loadBuffer(output.str());
QVERIFY(node != nullptr);
}
void test_NormalBinding_data()
{
// clang-format off
QTest::addColumn<Base::BindingElement::Binding>("input");
QTest::addColumn<QString>("result");
QTest::newRow("NormalBinding") << Base::BindingElement::Binding::Overall
<< "NormalBinding { value OVERALL }\n";
QTest::newRow("NormalBinding") << Base::BindingElement::Binding::PerPart
<< "NormalBinding { value PER_PART }\n";
QTest::newRow("NormalBinding") << Base::BindingElement::Binding::PerPartIndexed
<< "NormalBinding { value PER_PART_INDEXED }\n";
QTest::newRow("NormalBinding") << Base::BindingElement::Binding::PerFace
<< "NormalBinding { value PER_FACE }\n";
QTest::newRow("NormalBinding") << Base::BindingElement::Binding::PerFaceIndexed
<< "NormalBinding { value PER_FACE_INDEXED }\n";
QTest::newRow("NormalBinding") << Base::BindingElement::Binding::PerVertex
<< "NormalBinding { value PER_VERTEX }\n";
QTest::newRow("NormalBinding") << Base::BindingElement::Binding::PerVertexIndexed
<< "NormalBinding { value PER_VERTEX_INDEXED }\n";
QTest::newRow("NormalBinding") << Base::BindingElement::Binding::Default
<< "NormalBinding { value OVERALL }\n";
QTest::newRow("NormalBinding") << Base::BindingElement::Binding::None
<< "NormalBinding { value OVERALL }\n";
// clang-format on
}
void test_NormalBinding()
{
QFETCH(Base::BindingElement::Binding, input);
QFETCH(QString, result);
Base::NormalBindingItem item;
item.setValue(input);
builder.addNode(item);
QString string = QString::fromStdString(output.str());
QCOMPARE(string, result);
}
void test_Cylinder_data()
{
auto result =
R"(Cylinder {
radius 3
height 7
parts (SIDES | TOP | BOTTOM)
}
)";
QTest::addColumn<float>("radius");
QTest::addColumn<float>("height");
QTest::addColumn<QString>("result");
QTest::newRow("Cylinder") << 3.0F << 7.0F << result;
}
void test_Cylinder()
{
QFETCH(float, radius);
QFETCH(float, height);
QFETCH(QString, result);
Base::CylinderItem item;
item.setRadius(radius);
item.setHeight(height);
builder.addNode(item);
QString string = QString::fromStdString(output.str());
QCOMPARE(string, result);
}
void test_Cone_data()
{
auto result = "Cone { bottomRadius 2 height 10 }\n";
QTest::addColumn<float>("radius");
QTest::addColumn<float>("height");
QTest::addColumn<QString>("result");
QTest::newRow("Cone") << 2.0F << 10.0F << result;
}
void test_Cone()
{
QFETCH(float, radius);
QFETCH(float, height);
QFETCH(QString, result);
Base::ConeItem item;
item.setBottomRadius(radius);
item.setHeight(height);
builder.addNode(item);
QString string = QString::fromStdString(output.str());
QCOMPARE(string, result);
}
void test_Sphere_data()
{
auto result = "Sphere { radius 4 }\n";
QTest::addColumn<float>("input");
QTest::addColumn<QString>("result");
QTest::newRow("Sphere") << 4.0F << result;
}
void test_Sphere()
{
QFETCH(float, input);
QFETCH(QString, result);
Base::SphereItem item;
item.setRadius(input);
builder.addNode(item);
QString string = QString::fromStdString(output.str());
QCOMPARE(string, result);
}
void test_NurbsSurface_data()
{
QTest::addColumn<float>("knot1");
QTest::addColumn<float>("knot2");
QTest::addColumn<int>("poles");
QTest::newRow("Nurbs") << 0.0F << 1.0F << 2;
}
void test_NurbsSurface()
{
QFETCH(float, knot1);
QFETCH(float, knot2);
QFETCH(int, poles);
Base::NurbsSurfaceItem item;
item.setKnotVector({knot1, knot2}, {knot1, knot2});
item.setControlPoints(poles, poles);
builder.addNode(item);
SoNode* node = loadBuffer(output.str());
QVERIFY(node != nullptr);
}
private:
std::stringstream output;
Base::InventorBuilder builder;
};
QTEST_GUILESS_MAIN(testInventorBuilder)
#include "InventorBuilder.moc"

577
tests/src/Base/Matrix.cpp Normal file
View File

@@ -0,0 +1,577 @@
#include <gtest/gtest.h>
#include <Base/Matrix.h>
#include <Base/Rotation.h>
#include <Base/Tools.h>
// NOLINTBEGIN(cppcoreguidelines-*,readability-magic-numbers)
// clang-format off
TEST(Matrix, TestShearing)
{
Base::Matrix4D mat;
mat.setRow(1, Base::Vector3d(0, 1, 1));
EXPECT_EQ(mat.hasScale(), Base::ScaleType::Other);
}
TEST(Matrix, TestMultLeftRight)
{
Base::Matrix4D mat1;
mat1.rotX(1.0);
Base::Matrix4D mat2;
mat2.scale(1.0, 2.0, 3.0);
EXPECT_EQ((mat1 * mat2).hasScale(), Base::ScaleType::NonUniformRight);
EXPECT_EQ((mat2 * mat1).hasScale(), Base::ScaleType::NonUniformLeft);
}
TEST(Matrix, TestNoScale)
{
Base::Matrix4D mat;
mat.rotX(1.0);
mat.scale(1.0);
EXPECT_EQ(mat.hasScale(), Base::ScaleType::NoScaling);
}
TEST(Matrix, TestUniformScalePlusTwo)
{
Base::Matrix4D mat;
mat.rotX(1.0);
mat.scale(2.0);
EXPECT_EQ(mat.hasScale(), Base::ScaleType::Uniform);
}
TEST(Matrix, TestUniformScaleRight)
{
Base::Matrix4D mat;
mat.rotX(1.0);
Base::Matrix4D scale;
scale.scale(2.0);
mat = mat * scale;
EXPECT_EQ(mat.hasScale(), Base::ScaleType::Uniform);
}
TEST(Matrix, TestNonUniformScaleRight)
{
Base::Matrix4D mat;
mat.rotX(1.0);
Base::Matrix4D scale;
scale.scale(2.0, 1.0, 2.0);
mat = mat * scale;
EXPECT_EQ(mat.hasScale(), Base::ScaleType::NonUniformRight);
}
TEST(Matrix, TestUniformScaleMinusOne)
{
Base::Matrix4D mat;
mat.scale(-1.0);
EXPECT_EQ(mat.hasScale(), Base::ScaleType::Uniform);
}
TEST(Matrix, TestUniformScaleMinusTwo)
{
Base::Matrix4D mat;
mat.scale(-2.0);
EXPECT_EQ(mat.hasScale(), Base::ScaleType::Uniform);
}
TEST(Matrix, TestNonUniformScaleLeftOne)
{
Base::Matrix4D mat;
mat.rotX(1.0);
mat.scale(1.0, -1.0, 1.0);
// A scale(1,-1,1) is like scale(-1,-1,-1) * rotation
EXPECT_EQ(mat.hasScale(), Base::ScaleType::Uniform);
}
TEST(Matrix, TestNonUniformScaleLeftTwo)
{
Base::Matrix4D mat;
mat.rotX(1.0);
mat.scale(2.0, -2.0, 2.0);
EXPECT_EQ(mat.hasScale(), Base::ScaleType::Uniform);
}
TEST(Matrix, TestDiagonal)
{
Base::Matrix4D mat;
mat.scale(2.0, 2.0, 2.0);
Base::Vector3d diag = mat.diagonal();
EXPECT_EQ(diag.x + diag.y + diag.z, 6.0);
}
TEST(Matrix, TestColRow)
{
Base::Matrix4D mat;
EXPECT_EQ(mat.getCol(0), Base::Vector3d(1, 0, 0));
EXPECT_EQ(mat.getCol(1), Base::Vector3d(0, 1, 0));
EXPECT_EQ(mat.getCol(2), Base::Vector3d(0, 0, 1));
EXPECT_EQ(mat.getRow(0), Base::Vector3d(1, 0, 0));
EXPECT_EQ(mat.getRow(1), Base::Vector3d(0, 1, 0));
EXPECT_EQ(mat.getRow(2), Base::Vector3d(0, 0, 1));
}
TEST(Matrix, TestColRowMisc)
{
Base::Matrix4D mat{1.0, 2.0, 3.0, 0.0,
3.0, 1.0, 2.0, 2.0,
2.0, 3.0, 1.0, 1.0,
0.0, 0.0, 0.0, 1.0};
EXPECT_EQ(mat.getCol(0), Base::Vector3d(1.0, 3.0, 2.0));
EXPECT_EQ(mat.getCol(1), Base::Vector3d(2.0, 1.0, 3.0));
EXPECT_EQ(mat.getCol(2), Base::Vector3d(3.0, 2.0, 1.0));
EXPECT_EQ(mat.getRow(0), Base::Vector3d(1.0, 2.0, 3.0));
EXPECT_EQ(mat.getRow(1), Base::Vector3d(3.0, 1.0, 2.0));
EXPECT_EQ(mat.getRow(2), Base::Vector3d(2.0, 3.0, 1.0));
}
TEST(Matrix, TestUnity)
{
Base::Matrix4D mat;
EXPECT_EQ(mat.isUnity(), true);
mat.nullify();
EXPECT_EQ(mat.isUnity(), false);
mat.setToUnity();
EXPECT_EQ(mat.isUnity(), true);
}
TEST(Matrix, TestNull)
{
Base::Matrix4D mat;
EXPECT_EQ(mat.isNull(), false);
mat.nullify();
EXPECT_EQ(mat.isNull(), true);
}
TEST(Matrix, TestMultVec)
{
Base::Matrix4D mat{1.0, 2.0, 3.0, 0.0,
2.0, 3.0, 1.0, 1.0,
3.0, 1.0, 2.0, 2.0,
0.0, 0.0, 0.0, 1.0};
Base::Vector3d vec1{1,1,3};
vec1 = mat * vec1;
EXPECT_EQ(vec1, Base::Vector3d(12.0, 9.0, 12.0));
Base::Vector3d vec2 {1, 1, 1};
mat.multVec(vec2, vec2);
EXPECT_EQ(vec2, Base::Vector3d(6.0, 7.0, 8.0));
Base::Vector3f vec3{1.0F,1.0F,3.0F};
vec3 = mat * vec3;
EXPECT_EQ(vec3, Base::Vector3f(12.0F, 9.0F, 12.0F));
Base::Vector3f vec4 {1.0F, 1.0F, 1.0F};
mat.multVec(vec4, vec4);
EXPECT_EQ(vec4, Base::Vector3f(6.0F, 7.0F, 8.0F));
Base::Vector3f vec5 {1.0F, 1.0F, 1.0F};
vec5 *= mat;
EXPECT_EQ(vec5, Base::Vector3f(6.0F, 7.0F, 8.0F));
}
TEST(Matrix, TestMult)
{
Base::Matrix4D mat1{1.0, 2.0, 3.0, 0.0,
2.0, 3.0, 1.0, 1.0,
3.0, 1.0, 2.0, 2.0,
0.0, 0.0, 0.0, 1.0};
Base::Matrix4D mat2{1.0, 2.0, 3.0, 0.0,
3.0, 1.0, 2.0, 1.0,
2.0, 3.0, 1.0, 2.0,
0.0, 0.0, 0.0, 1.0};
Base::Matrix4D mat3 = mat1 * mat2;
Base::Matrix4D mat4{13.0, 13.0, 10.0, 8.0,
13.0, 10.0, 13.0, 6.0,
10.0, 13.0, 13.0, 7.0,
0.0, 0.0, 0.0, 1.0};
EXPECT_EQ(mat3, mat4);
EXPECT_NE(mat3, Base::Matrix4D());
}
TEST(Matrix, TestMultAssign)
{
Base::Matrix4D mat1{1.0, 2.0, 3.0, 0.0,
2.0, 3.0, 1.0, 1.0,
3.0, 1.0, 2.0, 2.0,
0.0, 0.0, 0.0, 1.0};
Base::Matrix4D mat2{1.0, 2.0, 3.0, 0.0,
3.0, 1.0, 2.0, 1.0,
2.0, 3.0, 1.0, 2.0,
0.0, 0.0, 0.0, 1.0};
mat1 *= mat2;
Base::Matrix4D mat4{13.0, 13.0, 10.0, 8.0,
13.0, 10.0, 13.0, 6.0,
10.0, 13.0, 13.0, 7.0,
0.0, 0.0, 0.0, 1.0};
EXPECT_EQ(mat1, mat4);
}
TEST(Matrix, TestAdd)
{
Base::Matrix4D mat1{1.0, 2.0, 3.0, 0.0,
2.0, 3.0, 1.0, 1.0,
3.0, 1.0, 2.0, 2.0,
0.0, 0.0, 0.0, 1.0};
Base::Matrix4D mat2{1.0, 2.0, 3.0, 0.0,
3.0, 1.0, 2.0, 1.0,
2.0, 3.0, 1.0, 2.0,
0.0, 0.0, 0.0, 1.0};
Base::Matrix4D mat3 = mat1 + mat2;
Base::Matrix4D mat4{2.0, 4.0, 6.0, 0.0,
5.0, 4.0, 3.0, 2.0,
5.0, 4.0, 3.0, 4.0,
0.0, 0.0, 0.0, 2.0};
EXPECT_EQ(mat3, mat4);
}
TEST(Matrix, TestAddAssign)
{
Base::Matrix4D mat1{1.0, 2.0, 3.0, 0.0,
2.0, 3.0, 1.0, 1.0,
3.0, 1.0, 2.0, 2.0,
0.0, 0.0, 0.0, 1.0};
Base::Matrix4D mat2{1.0, 2.0, 3.0, 0.0,
3.0, 1.0, 2.0, 1.0,
2.0, 3.0, 1.0, 2.0,
0.0, 0.0, 0.0, 1.0};
mat1 += mat2;
Base::Matrix4D mat4{2.0, 4.0, 6.0, 0.0,
5.0, 4.0, 3.0, 2.0,
5.0, 4.0, 3.0, 4.0,
0.0, 0.0, 0.0, 2.0};
EXPECT_EQ(mat1, mat4);
}
TEST(Matrix, TestSub)
{
Base::Matrix4D mat1{1.0, 2.0, 3.0, 0.0,
2.0, 3.0, 1.0, 1.0,
3.0, 1.0, 2.0, 2.0,
0.0, 0.0, 0.0, 1.0};
Base::Matrix4D mat2{1.0, 2.0, 3.0, 0.0,
3.0, 1.0, 2.0, 1.0,
2.0, 3.0, 1.0, 2.0,
0.0, 0.0, 0.0, 1.0};
Base::Matrix4D mat3 = mat1 - mat2;
Base::Matrix4D mat4{0.0, 0.0, 0.0, 0.0,
-1.0, 2.0, -1.0, 0.0,
1.0, -2.0, 1.0, 0.0,
0.0, 0.0, 0.0, 0.0};
EXPECT_EQ(mat3, mat4);
}
TEST(Matrix, TestSubAssign)
{
Base::Matrix4D mat1{1.0, 2.0, 3.0, 0.0,
2.0, 3.0, 1.0, 1.0,
3.0, 1.0, 2.0, 2.0,
0.0, 0.0, 0.0, 1.0};
Base::Matrix4D mat2{1.0, 2.0, 3.0, 0.0,
3.0, 1.0, 2.0, 1.0,
2.0, 3.0, 1.0, 2.0,
0.0, 0.0, 0.0, 1.0};
mat1 -= mat2;
Base::Matrix4D mat4{0.0, 0.0, 0.0, 0.0,
-1.0, 2.0, -1.0, 0.0,
1.0, -2.0, 1.0, 0.0,
0.0, 0.0, 0.0, 0.0};
EXPECT_EQ(mat1, mat4);
}
TEST(Matrix, TestHatOperator)
{
Base::Vector3d vec{1.0, 2.0, 3.0};
Base::Matrix4D mat1;
mat1.Hat(vec);
Base::Matrix4D mat2{0.0, -vec.z, vec.y, 0.0,
vec.z, 0.0, -vec.x, 0.0,
-vec.y, vec.x, 0.0, 0.0,
0.0, 0.0, 0.0, 1.0};
EXPECT_EQ(mat1, mat2);
}
TEST(Matrix, TestHatOperatorFloat)
{
Base::Vector3f vec{1.0, 2.0, 3.0};
Base::Matrix4D mat1;
mat1.Hat(vec);
Base::Matrix4D mat2{0.0F, -vec.z, vec.y, 0.0F,
vec.z, 0.0F, -vec.x, 0.0F,
-vec.y, vec.x, 0.0F, 0.0F,
0.0F, 0.0F, 0.0F, 1.0F};
EXPECT_EQ(mat1, mat2);
}
TEST(Matrix, TestDyadic)
{
Base::Vector3d vec{1.0, 2.0, 3.0};
Base::Matrix4D mat1;
mat1.Outer(vec, vec);
Base::Matrix4D mat2{1.0, 2.0, 3.0, 0.0,
2.0, 4.0, 6.0, 0.0,
3.0, 6.0, 9.0, 0.0,
0.0, 0.0, 0.0, 1.0};
EXPECT_EQ(mat1, mat2);
}
TEST(Matrix, TestDyadicFloat)
{
Base::Vector3f vec{1.0F, 2.0F, 3.0F};
Base::Matrix4D mat1;
mat1.Outer(vec, vec);
Base::Matrix4D mat2{1.0, 2.0, 3.0, 0.0,
2.0, 4.0, 6.0, 0.0,
3.0, 6.0, 9.0, 0.0,
0.0, 0.0, 0.0, 1.0};
EXPECT_EQ(mat1, mat2);
}
TEST(Matrix, TestDecomposeScale)
{
Base::Matrix4D mat;
mat.scale(1.0, 2.0, 3.0);
auto res = mat.decompose();
EXPECT_TRUE(res[0].isUnity());
EXPECT_EQ(res[1], mat);
EXPECT_TRUE(res[2].isUnity());
EXPECT_TRUE(res[3].isUnity());
}
TEST(Matrix, TestDecomposeRotation)
{
Base::Matrix4D mat;
mat.rotX(1.0);
mat.rotY(1.0);
mat.rotZ(1.0);
auto res = mat.decompose();
EXPECT_TRUE(res[0].isUnity(1e-12));
EXPECT_TRUE(res[1].isUnity(1e-12));
EXPECT_EQ(res[2], mat);
EXPECT_TRUE(res[3].isUnity(1e-12));
}
TEST(Matrix, TestDecomposeMove)
{
Base::Matrix4D mat;
mat.move(1.0, 2.0, 3.0);
auto res = mat.decompose();
EXPECT_TRUE(res[0].isUnity());
EXPECT_TRUE(res[1].isUnity());
EXPECT_TRUE(res[2].isUnity());
EXPECT_EQ(res[3], mat);
}
TEST(Matrix, TestDecomposeMoveFloat)
{
Base::Matrix4D mat;
mat.move(Base::Vector3f(1.0F, 2.0F, 3.0F));
auto res = mat.decompose();
EXPECT_TRUE(res[0].isUnity());
EXPECT_TRUE(res[1].isUnity());
EXPECT_TRUE(res[2].isUnity());
EXPECT_EQ(res[3], mat);
}
TEST(Matrix, TestDecompose)
{
Base::Matrix4D mat;
mat[0][0] = 1.0;
mat[0][3] = 1.0;
mat[1][3] = 2.0;
mat[2][3] = 3.0;
auto res = mat.decompose();
Base::Matrix4D mul = res[3] * res[2] * res[1] * res[0];
EXPECT_EQ(mul, mat);
// shearing
EXPECT_DOUBLE_EQ(res[0].determinant3(), 1.0);
// rotation
EXPECT_DOUBLE_EQ(res[2].determinant3(), 1.0);
// translation
EXPECT_DOUBLE_EQ(res[2].determinant3(), 1.0);
}
TEST(Matrix, TestRotLine)
{
Base::Vector3d axis{1.0, 2.0, 3.0};
double angle = 1.2345;
Base::Matrix4D mat1;
Base::Matrix4D mat2;
mat1.rotLine(axis, angle);
Base::Rotation rot(axis, angle);
rot.getValue(mat2);
EXPECT_EQ(mat1, mat2);
}
TEST(Matrix, TestRotAxisFormula) //NOLINT
{
// R = I + sin(alpha)*P + (1-cos(alpha))*P^2
// with P = hat operator of a vector
Base::Vector3d axis{1.0, 2.0, 3.0};
double angle = 1.2345;
Base::Matrix4D mat1;
Base::Matrix4D mat2;
mat1.rotLine(axis, angle);
double fsin = std::sin(angle);
double fcos = std::cos(angle);
Base::Matrix4D unit;
Base::Matrix4D hat;
Base::Matrix4D hat2;
axis.Normalize();
hat.Hat(axis);
hat2 = hat * hat;
mat2 = unit + hat * fsin + hat2 * (1 - fcos);
EXPECT_DOUBLE_EQ(mat1[0][0], mat2[0][0]);
EXPECT_DOUBLE_EQ(mat1[0][1], mat2[0][1]);
EXPECT_DOUBLE_EQ(mat1[0][2], mat2[0][2]);
EXPECT_DOUBLE_EQ(mat1[1][0], mat2[1][0]);
EXPECT_DOUBLE_EQ(mat1[1][1], mat2[1][1]);
EXPECT_DOUBLE_EQ(mat1[1][2], mat2[1][2]);
EXPECT_DOUBLE_EQ(mat1[2][0], mat2[2][0]);
EXPECT_DOUBLE_EQ(mat1[2][1], mat2[2][1]);
EXPECT_DOUBLE_EQ(mat1[2][2], mat2[2][2]);
}
TEST(Matrix, TestTransform)
{
Base::Matrix4D mat;
mat.rotZ(Base::toRadians(90.0));
Base::Matrix4D unity;
unity.transform(Base::Vector3d(10.0, 0.0, 0.0), mat);
Base::Matrix4D mov{0.0, -1.0, 0.0, 10.0,
1.0, 0.0, 0.0, -10.0,
0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 1.0};
EXPECT_EQ(unity, mov);
}
TEST(Matrix, TestTransformFloat)
{
Base::Matrix4D mat;
mat.rotZ(Base::toRadians(90.0));
Base::Matrix4D mat2;
mat2.transform(Base::Vector3f(10.0F, 0.0F, 0.0F), mat);
Base::Matrix4D mov{0.0, -1.0, 0.0, 10.0,
1.0, 0.0, 0.0, -10.0,
0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 1.0};
EXPECT_EQ(mat2, mov);
}
TEST(Matrix, TestInverseOrthogonal)
{
Base::Matrix4D mat;
mat.rotZ(Base::toRadians(90.0));
Base::Matrix4D mat2;
mat2.transform(Base::Vector3d(10.0, 0.0, 0.0), mat);
mat2.inverseOrthogonal();
Base::Matrix4D mov{0.0, 1.0, 0.0, 10.0,
-1.0, 0.0, 0.0, 10.0,
0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 1.0};
EXPECT_EQ(mat2, mov);
}
TEST(Matrix, TestTranspose)
{
Base::Matrix4D mat{1.0, 2.0, 3.0, 4.0,
5.0, 6.0, 7.0, 8.0,
9.0, 1.0, 2.0, 3.0,
4.0, 5.0, 6.0, 7.0};
Base::Matrix4D trp{1.0, 5.0, 9.0, 4.0,
2.0, 6.0, 1.0, 5.0,
3.0, 7.0, 2.0, 6.0,
4.0, 8.0, 3.0, 7.0};
mat.transpose();
EXPECT_EQ(mat, trp);
}
TEST(Matrix, TestTrace)
{
Base::Matrix4D mat{1.0, 2.0, 3.0, 4.0,
5.0, 6.0, 7.0, 8.0,
9.0, 1.0, 2.0, 3.0,
4.0, 5.0, 6.0, 7.0};
EXPECT_DOUBLE_EQ(mat.trace(), 16.0);
EXPECT_DOUBLE_EQ(mat.trace3(), 9.0);
}
TEST(Matrix, TestSetAndGetMatrix)
{
Base::Matrix4D mat{1.0, 2.0, 3.0, 0.0,
2.0, 4.0, 6.0, 0.0,
3.0, 6.0, 9.0, 0.0,
0.0, 0.0, 0.0, 1.0};
std::array<double, 16> values;
mat.getMatrix(values.data());
Base::Matrix4D inp;
inp.setMatrix(values.data());
EXPECT_EQ(mat, inp);
}
TEST(Matrix, TestSetAndGetGLMatrix)
{
Base::Matrix4D mat{1.0, 2.0, 3.0, 0.0,
2.0, 4.0, 6.0, 0.0,
3.0, 6.0, 9.0, 0.0,
0.0, 0.0, 0.0, 1.0};
std::array<double, 16> values;
mat.getGLMatrix(values.data());
Base::Matrix4D inp;
inp.setGLMatrix(values.data());
EXPECT_EQ(mat, inp);
}
TEST(Matrix, TestToAndFromString)
{
Base::Matrix4D mat{1.0, 2.0, 3.0, 0.0,
2.0, 4.0, 6.0, 0.0,
3.0, 6.0, 9.0, 0.0,
0.0, 0.0, 0.0, 1.0};
std::string str = mat.toString();
Base::Matrix4D inp;
inp.fromString(str);
EXPECT_EQ(mat, inp);
}
// clang-format on
// NOLINTEND(cppcoreguidelines-*,readability-magic-numbers)

View File

@@ -0,0 +1,465 @@
#include <gtest/gtest.h>
#include <boost/core/ignore_unused.hpp>
#include <QLockFile>
#include <Base/FileInfo.h>
#include <Base/Parameter.h>
class FakeObserver: public ParameterGrp::ObserverType
{
public:
void clearNotifications()
{
notify = 0;
}
int getCountNotifications() const
{
return notify;
}
void attachSelf(ParameterGrp::handle hGrp)
{
hGrp->Attach(this);
}
void detachSelf(ParameterGrp::handle hGrp)
{
hGrp->Detach(this);
}
void OnChange(ParameterGrp::SubjectType& rCaller, ParameterGrp::MessageType Reason) override
{
boost::ignore_unused(rCaller);
boost::ignore_unused(Reason);
notify++;
}
private:
int notify {};
};
class ParameterTest: public ::testing::Test
{
protected:
static void SetUpTestSuite()
{
ParameterManager::Init();
}
ParameterTest()
{
fi.setFile(Base::FileInfo::getTempFileName() + ".cfg");
}
void SetUp() override
{
config = ParameterManager::Create();
}
void TearDown() override
{
if (fi.exists()) {
fi.deleteFile();
}
}
Base::Reference<ParameterManager> getConfig() const
{
return config;
}
Base::Reference<ParameterManager> getCreateConfig()
{
config->CreateDocument();
return config;
}
std::string getFileName() const
{
return fi.filePath();
}
FakeObserver& getObserver()
{
return observer;
}
private:
Base::FileInfo fi;
FakeObserver observer;
Base::Reference<ParameterManager> config;
};
// NOLINTBEGIN(cppcoreguidelines-*,readability-*)
TEST_F(ParameterTest, TestValid)
{
auto cfg = getConfig();
EXPECT_EQ(cfg.isValid(), true);
EXPECT_EQ(cfg.isNull(), false);
}
TEST_F(ParameterTest, TestCreate)
{
auto cfg = getCreateConfig();
cfg->CheckDocument();
EXPECT_TRUE(cfg->IsEmpty());
}
TEST_F(ParameterTest, TestGroup)
{
auto cfg = getCreateConfig();
auto grp = cfg->GetGroup("TopLevelGroup");
EXPECT_EQ(grp->Parent(), static_cast<ParameterGrp*>(cfg));
EXPECT_EQ(grp->Manager(), static_cast<ParameterGrp*>(cfg));
EXPECT_FALSE(cfg->IsEmpty());
EXPECT_TRUE(grp->IsEmpty());
EXPECT_TRUE(cfg->HasGroup("TopLevelGroup"));
EXPECT_FALSE(cfg->HasGroup("Group"));
EXPECT_EQ(cfg->GetGroups().size(), 1);
}
TEST_F(ParameterTest, TestGroupName)
{
auto cfg = getCreateConfig();
auto grp = cfg->GetGroup("TopLevelGroup");
EXPECT_STREQ(grp->GetGroupName(), "TopLevelGroup");
}
TEST_F(ParameterTest, TestEmptyGroupName)
{
auto cfg = getCreateConfig();
EXPECT_THROW(cfg->GetGroup(nullptr), Base::ValueError);
EXPECT_THROW(cfg->GetGroup(""), Base::ValueError);
EXPECT_THROW(cfg->GetGroup("///////"), Base::ValueError);
}
TEST_F(ParameterTest, TestGroupNames)
{
auto cfg = getCreateConfig();
auto grp1 = cfg->GetGroup("////Sub1/////Sub2/////");
auto grp2 = cfg->GetGroup("Sub1/Sub2");
EXPECT_STREQ(grp1->GetGroupName(), "Sub2");
EXPECT_STREQ(grp2->GetGroupName(), "Sub2");
}
TEST_F(ParameterTest, TestPath)
{
auto cfg = getCreateConfig();
auto grp1 = cfg->GetGroup("TopLevelGroup");
auto sub1 = grp1->GetGroup("Sub1");
auto sub2 = sub1->GetGroup("Sub2");
EXPECT_EQ(sub2->GetPath(), "TopLevelGroup/Sub1/Sub2");
}
TEST_F(ParameterTest, TestBool)
{
auto cfg = getCreateConfig();
auto grp = cfg->GetGroup("TopLevelGroup");
grp->SetBool("Parameter1", false);
grp->SetBool("Parameter2", true);
EXPECT_EQ(grp->GetBool("Parameter1", true), false);
EXPECT_EQ(grp->GetBool("Parameter3", true), true);
EXPECT_EQ(grp->GetBool("Parameter3", false), false);
EXPECT_TRUE(grp->GetBools("Test").empty());
EXPECT_EQ(grp->GetBools().size(), 2);
EXPECT_EQ(grp->GetBools().at(0), false);
EXPECT_EQ(grp->GetBools().at(1), true);
EXPECT_EQ(grp->GetBoolMap().size(), 2);
grp->RemoveBool("Parameter1");
EXPECT_EQ(grp->GetBools().size(), 1);
}
TEST_F(ParameterTest, TestInt)
{
auto cfg = getCreateConfig();
auto grp = cfg->GetGroup("TopLevelGroup");
grp->SetInt("Parameter1", -15);
grp->SetInt("Parameter2", 25);
EXPECT_EQ(grp->GetInt("Parameter1", 2), -15);
EXPECT_EQ(grp->GetInt("Parameter3", 2), 2);
EXPECT_EQ(grp->GetInt("Parameter3", 4), 4);
EXPECT_TRUE(grp->GetInts("Test").empty());
EXPECT_EQ(grp->GetInts().size(), 2);
EXPECT_EQ(grp->GetInts().at(0), -15);
EXPECT_EQ(grp->GetInts().at(1), 25);
EXPECT_EQ(grp->GetIntMap().size(), 2);
grp->RemoveInt("Parameter1");
EXPECT_EQ(grp->GetInts().size(), 1);
}
TEST_F(ParameterTest, TestUnsigned)
{
auto cfg = getCreateConfig();
auto grp = cfg->GetGroup("TopLevelGroup");
grp->SetUnsigned("Parameter1", 15);
grp->SetUnsigned("Parameter2", 25);
EXPECT_EQ(grp->GetUnsigned("Parameter1", 2), 15);
EXPECT_EQ(grp->GetUnsigned("Parameter3", 2), 2);
EXPECT_EQ(grp->GetUnsigned("Parameter3", 4), 4);
EXPECT_TRUE(grp->GetUnsigneds("Test").empty());
EXPECT_EQ(grp->GetUnsigneds().size(), 2);
EXPECT_EQ(grp->GetUnsigneds().at(0), 15);
EXPECT_EQ(grp->GetUnsigneds().at(1), 25);
EXPECT_EQ(grp->GetUnsignedMap().size(), 2);
grp->RemoveUnsigned("Parameter1");
EXPECT_EQ(grp->GetUnsigneds().size(), 1);
}
TEST_F(ParameterTest, TestFloat)
{
auto cfg = getCreateConfig();
auto grp = cfg->GetGroup("TopLevelGroup");
grp->SetFloat("Parameter1", 1.5);
grp->SetFloat("Parameter2", 2.5);
EXPECT_EQ(grp->GetFloat("Parameter1", 2.0), 1.5);
EXPECT_EQ(grp->GetFloat("Parameter3", 2.0), 2.0);
EXPECT_EQ(grp->GetFloat("Parameter3", 4.0), 4.0);
EXPECT_TRUE(grp->GetFloats("Test").empty());
EXPECT_EQ(grp->GetFloats().size(), 2);
EXPECT_EQ(grp->GetFloats().at(0), 1.5);
EXPECT_EQ(grp->GetFloats().at(1), 2.5);
EXPECT_EQ(grp->GetFloatMap().size(), 2);
grp->RemoveFloat("Parameter1");
EXPECT_EQ(grp->GetFloats().size(), 1);
}
TEST_F(ParameterTest, TestString)
{
auto cfg = getCreateConfig();
auto grp = cfg->GetGroup("TopLevelGroup");
grp->SetASCII("Parameter1", "Value1");
grp->SetASCII("Parameter2", "Value2");
EXPECT_EQ(grp->GetASCII("Parameter1", "Value3"), "Value1");
EXPECT_EQ(grp->GetASCII("Parameter3", "Value3"), "Value3");
EXPECT_EQ(grp->GetASCII("Parameter3", "Value4"), "Value4");
EXPECT_TRUE(grp->GetASCIIs("Test").empty());
EXPECT_EQ(grp->GetASCIIs().size(), 2);
EXPECT_EQ(grp->GetASCIIs().at(0), "Value1");
EXPECT_EQ(grp->GetASCIIs().at(1), "Value2");
EXPECT_EQ(grp->GetASCIIMap().size(), 2);
grp->RemoveASCII("Parameter1");
EXPECT_EQ(grp->GetASCIIs().size(), 1);
}
TEST_F(ParameterTest, TestCopy)
{
auto cfg = getCreateConfig();
auto grp = cfg->GetGroup("TopLevelGroup");
auto sub2 = grp->GetGroup("Sub1/Sub2");
sub2->SetFloat("Parameter", 1.5);
auto sub3 = grp->GetGroup("Sub3");
sub3->SetFloat("AnotherParameter", 2.5);
sub2->copyTo(sub3);
EXPECT_TRUE(sub3->GetFloats("Test").empty());
EXPECT_EQ(sub3->GetFloats().size(), 1);
EXPECT_EQ(sub3->GetFloats().at(0), 1.5);
// Test that old parameter has been removed
EXPECT_TRUE(sub3->GetFloats("AnotherParameter").empty());
}
TEST_F(ParameterTest, TestInsert)
{
auto cfg = getCreateConfig();
auto grp = cfg->GetGroup("TopLevelGroup");
auto sub2 = grp->GetGroup("Sub1/Sub2");
sub2->SetFloat("Parameter", 1.5);
auto sub3 = grp->GetGroup("Sub3");
sub3->SetFloat("AnotherParameter", 2.5);
sub2->insertTo(sub3);
EXPECT_EQ(sub3->GetFloats().size(), 2);
EXPECT_EQ(sub3->GetFloats("AnotherParameter").size(), 1);
}
TEST_F(ParameterTest, TestRevert)
{
auto cfg = getCreateConfig();
auto grp = cfg->GetGroup("TopLevelGroup");
auto sub1 = grp->GetGroup("Sub1/Sub/Sub");
sub1->SetFloat("Float", 1.5);
auto sub2 = grp->GetGroup("Sub2/Sub/Sub");
sub2->SetFloat("Float", 1.5);
grp->GetGroup("Sub1")->revert(grp->GetGroup("Sub2"));
EXPECT_EQ(sub1->GetFloat("Float", 0.0), 0.0);
EXPECT_EQ(sub1->GetFloat("Float", 2.0), 2.0);
EXPECT_EQ(sub2->GetFloat("Float", 2.0), 1.5);
}
TEST_F(ParameterTest, TestRemoveGroup)
{
auto cfg = getCreateConfig();
auto grp = cfg->GetGroup("TopLevelGroup");
auto sub1 = grp->GetGroup("Sub1");
auto sub2 = sub1->GetGroup("Sub2/Sub/Sub");
sub2->SetFloat("Float", 1.5);
sub1->RemoveGrp("Sub2");
sub2->SetInt("Int", 2);
EXPECT_EQ(sub2->GetInt("Int", 0), 2);
EXPECT_EQ(sub2->GetInt("Int", 1), 2);
cfg->CheckDocument();
}
TEST_F(ParameterTest, TestRenameGroup)
{
auto cfg = getCreateConfig();
auto grp = cfg->GetGroup("TopLevelGroup");
auto sub1 = grp->GetGroup("Sub1");
auto sub2 = sub1->GetGroup("Sub2/Sub/Sub");
sub2->SetFloat("Float", 1.5);
sub1->RenameGrp("Sub2", "Sub3");
sub2->SetInt("Int", 2);
EXPECT_EQ(sub2->GetInt("Int", 0), 2);
EXPECT_EQ(sub2->GetInt("Int", 1), 2);
cfg->CheckDocument();
}
TEST_F(ParameterTest, TestSaveRestoreRef)
{
auto cfg = getCreateConfig();
auto grp = cfg->GetGroup("TopLevelGroup/Sub1/Sub2");
grp->SetFloat("Float", 1.0);
cfg->CheckDocument();
std::string fn = getFileName();
cfg->exportTo(fn.c_str());
cfg->importFrom(fn.c_str());
auto grp2 = cfg->GetGroup("TopLevelGroup/Sub1/Sub2");
EXPECT_EQ(grp, grp2);
grp2->SetFloat("Float", 2.0);
cfg->exportTo(fn.c_str());
}
TEST_F(ParameterTest, TestSaveRestoreNoRef)
{
auto cfg = getCreateConfig();
auto grp = cfg->GetGroup("TopLevelGroup/Sub1/Sub2");
grp->SetFloat("Float", 1.0);
grp = nullptr;
cfg->CheckDocument();
std::string fn = getFileName();
cfg->exportTo(fn.c_str());
cfg->importFrom(fn.c_str());
auto grp2 = cfg->GetGroup("TopLevelGroup/Sub1/Sub2");
EXPECT_NE(grp, grp2);
grp2->SetFloat("Float", 2.0);
cfg->exportTo(fn.c_str());
}
TEST_F(ParameterTest, TestGroupRef)
{
auto cfg = getCreateConfig();
cfg->GetGroup("TopLevelGroup");
std::string fn = getFileName();
cfg->exportTo(fn.c_str());
// keep reference to prevent the deletion of the group node
auto grp = cfg->GetGroup("TopLevelGroup/Sub1/Sub2");
cfg->importFrom(fn.c_str());
auto top = cfg->GetGroup("TopLevelGroup");
EXPECT_TRUE(top->HasGroup("Sub1"));
}
TEST_F(ParameterTest, TestGroupNoRef)
{
auto cfg = getCreateConfig();
cfg->GetGroup("TopLevelGroup");
std::string fn = getFileName();
cfg->exportTo(fn.c_str());
// nullify reference to delete the group node
auto grp = cfg->GetGroup("TopLevelGroup/Sub1/Sub2");
grp = nullptr;
cfg->importFrom(fn.c_str());
auto top = cfg->GetGroup("TopLevelGroup");
EXPECT_FALSE(top->HasGroup("Sub1"));
}
TEST_F(ParameterTest, TestObserverRef)
{
auto cfg = getCreateConfig();
cfg->GetGroup("TopLevelGroup");
std::string fn = getFileName();
cfg->exportTo(fn.c_str());
auto grp = cfg->GetGroup("TopLevelGroup/Sub1/Sub2");
auto& obs = getObserver();
obs.attachSelf(grp);
grp->SetFloat("Float", 1.0);
EXPECT_EQ(obs.getCountNotifications(), 1);
obs.clearNotifications();
cfg->importFrom(fn.c_str());
grp->SetFloat("Float", 2.0);
EXPECT_EQ(obs.getCountNotifications(), 3);
obs.detachSelf(grp);
}
TEST_F(ParameterTest, TestObserverNoRef)
{
auto cfg = getCreateConfig();
cfg->GetGroup("TopLevelGroup");
std::string fn = getFileName();
cfg->exportTo(fn.c_str());
auto grp = cfg->GetGroup("TopLevelGroup/Sub1/Sub2");
auto& obs = getObserver();
obs.attachSelf(grp);
grp = nullptr;
cfg->importFrom(fn.c_str());
auto grp2 = cfg->GetGroup("TopLevelGroup/Sub1/Sub2");
grp2->SetFloat("Float", 2.0);
EXPECT_EQ(obs.getCountNotifications(), 1);
}
TEST_F(ParameterTest, TestLockFile)
{
std::string fn = getFileName();
fn.append(".lock");
QLockFile lockFile1(QString::fromStdString(fn));
EXPECT_TRUE(lockFile1.tryLock(100));
EXPECT_TRUE(lockFile1.isLocked());
QLockFile lockFile2(QString::fromStdString(fn));
EXPECT_FALSE(lockFile2.tryLock(100));
EXPECT_FALSE(lockFile2.isLocked());
lockFile1.unlock();
EXPECT_TRUE(lockFile2.lock());
EXPECT_FALSE(lockFile1.tryLock(500));
lockFile2.unlock();
}
// NOLINTEND(cppcoreguidelines-*,readability-*)

View File

@@ -0,0 +1,215 @@
#include <gtest/gtest.h>
#include <Base/DualQuaternion.h>
#include <Base/Matrix.h>
#include <Base/Placement.h>
#include <Base/Tools.h>
static const double epsilon = 1e-9;
TEST(Placement, TestDefault)
{
Base::Placement plm;
EXPECT_EQ(plm.getPosition().IsNull(), true);
EXPECT_EQ(plm.getRotation().isNull(), false);
EXPECT_EQ(plm.getRotation().isIdentity(), true);
}
TEST(Placement, TestPosRot)
{
Base::Vector3d pos(1, 2, 3);
Base::Rotation rot(1, 1, 2, 2);
Base::Placement plm(pos, rot);
EXPECT_EQ(plm.getPosition(), pos);
EXPECT_EQ(plm.getRotation(), rot);
}
TEST(Placement, TestPosRotCnt)
{
Base::Vector3d pos(1, 2, 3);
Base::Rotation rot(1, 0, 0, 0);
Base::Vector3d cnt(4, 5, 6);
Base::Placement plm(pos, rot, cnt);
EXPECT_EQ(plm.getPosition(), Base::Vector3d(1, 12, 15));
EXPECT_EQ(plm.getRotation(), rot);
}
TEST(Placement, TestMatrix)
{
Base::Matrix4D mat;
mat.rotX(Base::toRadians(90.0));
mat.rotY(Base::toRadians(90.0));
mat.rotZ(Base::toRadians(90.0));
mat.setCol(3, Base::Vector3d(1, 2, 3));
Base::Placement plm(mat);
EXPECT_EQ(plm.getPosition(), Base::Vector3d(1, 2, 3));
Base::Vector3d axis;
double angle {};
plm.getRotation().getValue(axis, angle);
EXPECT_EQ(angle, Base::toRadians(90.0));
EXPECT_EQ(axis.IsEqual(Base::Vector3d(0, 1, 0), 0.001), true);
}
TEST(Placement, TestIdentity)
{
Base::Vector3d pos(1, 2, 3);
Base::Rotation rot(1, 0, 0, 0);
Base::Vector3d cnt(4, 5, 6);
Base::Placement plm(pos, rot, cnt);
Base::Placement mult = plm * plm.inverse();
EXPECT_EQ(mult.isIdentity(), true);
}
TEST(Placement, TestInvert)
{
Base::Vector3d pos(1, 2, 3);
Base::Rotation rot(1, 0, 0, 0);
Base::Vector3d cnt(4, 5, 6);
Base::Placement plm(pos, rot, cnt);
plm.invert();
EXPECT_EQ(plm.getPosition(), Base::Vector3d(-1, 12, 15));
EXPECT_EQ(plm.getRotation().isIdentity(), false);
EXPECT_EQ(plm.getRotation(), rot);
}
TEST(Placement, TestMove)
{
Base::Vector3d pos(1, 2, 3);
Base::Rotation rot(1, 0, 0, 0);
Base::Vector3d cnt(4, 5, 6);
Base::Placement plm(pos, rot, cnt);
plm.move(Base::Vector3d(-1, -12, -15));
EXPECT_EQ(plm.getPosition().IsNull(), true);
}
TEST(Placement, TestSame)
{
Base::Vector3d pos(1, 2, 3);
Base::Rotation rot(1, 0, 0, 0);
Base::Vector3d cnt(4, 5, 6);
Base::Placement plm(pos, rot, cnt);
EXPECT_EQ(plm.isSame(plm), true);
EXPECT_EQ(plm.isSame(plm, 0.001), true);
EXPECT_EQ(plm == plm, true);
Base::Placement plm2(plm * plm);
EXPECT_EQ(plm2.isSame(plm), false);
EXPECT_EQ(plm2.isSame(plm, 0.001), false);
EXPECT_EQ(plm2 == plm, false);
}
TEST(Placement, TestMultiply)
{
Base::Vector3d pos(1, 2, 3);
Base::Rotation rot(1, 0, 0, 0);
Base::Vector3d cnt(4, 5, 6);
Base::Placement plm(pos, rot, cnt);
Base::Placement plm2(plm * plm);
EXPECT_EQ(plm2.getRotation().isIdentity(), true);
}
TEST(Placement, TestMultRight)
{
Base::Vector3d pos1(1, 2, 3);
Base::Rotation rot1(1, 0, 0, 0);
Base::Placement plm1(pos1, rot1);
Base::Vector3d pos2(3, 2, 1);
Base::Rotation rot2(0, 1, 0, 0);
Base::Placement plm2(pos2, rot2);
plm1.multRight(plm2);
EXPECT_EQ(plm1.getRotation(), Base::Rotation(0, 0, 1, 0));
EXPECT_EQ(plm1.getPosition(), Base::Vector3d(4, 0, 2));
}
TEST(Placement, TestMultLeft)
{
Base::Vector3d pos1(1, 2, 3);
Base::Rotation rot1(1, 0, 0, 0);
Base::Placement plm1(pos1, rot1);
Base::Vector3d pos2(3, 2, 1);
Base::Rotation rot2(0, 1, 0, 0);
Base::Placement plm2(pos2, rot2);
plm1.multLeft(plm2);
EXPECT_EQ(plm1.getRotation(), Base::Rotation(0, 0, 1, 0));
EXPECT_EQ(plm1.getPosition(), Base::Vector3d(2, 4, -2));
}
TEST(Placement, TestMultVec)
{
Base::Vector3d pos(1, 2, 3);
Base::Rotation rot(1, 0, 0, 0);
Base::Placement plm(pos, rot);
Base::Vector3d vec {1, 1, 1};
plm.multVec(vec, vec);
EXPECT_EQ(vec, Base::Vector3d(2, 1, 2));
}
TEST(Placement, TestDualQuat)
{
Base::Vector3d pos(1, 2, 3);
Base::Rotation rot(1, 0, 0, 0);
Base::Placement plm(pos, rot);
Base::DualQuat qq = plm.toDualQuaternion();
Base::Placement plm2 = Base::Placement::fromDualQuaternion(qq);
EXPECT_EQ(plm.isSame(plm2), true);
}
TEST(Placement, TestPow)
{
Base::Vector3d axis1, axis2;
double angle1 {}, angle2 {};
Base::Vector3d pos(1, 4, 6);
Base::Rotation rot(1, 2, 3, 4);
Base::Placement plm(pos, rot);
rot.getValue(axis1, angle1);
Base::Placement plm2 = plm.pow(1.5);
plm2.getRotation().getValue(axis2, angle2);
EXPECT_DOUBLE_EQ(angle2, 1.5 * angle1);
EXPECT_EQ(axis1.IsEqual(axis2, 0.0001), true);
}
TEST(Placement, TestSlerp)
{
Base::Vector3d pos(1, 4, 6);
Base::Rotation rot1(1, 0, 0, 0);
Base::Rotation rot2(0, 1, 0, 0);
Base::Placement plm1(pos, rot1);
Base::Placement plm2(pos, rot2);
Base::Placement plm3 = Base::Placement::slerp(plm1, plm2, 0.0);
EXPECT_EQ(plm3.isSame(plm1), true);
Base::Placement plm4 = Base::Placement::slerp(plm1, plm2, 1.0);
EXPECT_EQ(plm4.isSame(plm2), true);
Base::Placement plm5 = Base::Placement::slerp(plm1, plm1, 0.5);
EXPECT_EQ(plm5.isSame(plm1), true);
Base::Placement plm6 = Base::Placement::slerp(plm1, plm2, 0.5);
EXPECT_EQ(plm6.getRotation().isSame(Base::Rotation(1, 1, 0, 0), epsilon), true);
EXPECT_EQ(plm6.getPosition().IsEqual(pos, epsilon), true);
}
TEST(Placement, TestSclerp)
{
Base::Vector3d pos(1, 4, 6);
Base::Rotation rot1(1, 0, 0, 0);
Base::Rotation rot2(0, 1, 0, 0);
Base::Placement plm1(pos, rot1);
Base::Placement plm2(pos, rot2);
Base::Placement plm3 = Base::Placement::sclerp(plm1, plm2, 0.0);
EXPECT_EQ(plm3.isSame(plm1), true);
Base::Placement plm4 = Base::Placement::sclerp(plm1, plm2, 1.0);
EXPECT_EQ(plm4.isSame(plm2, epsilon), true);
Base::Placement plm5 = Base::Placement::sclerp(plm1, plm1, 0.5);
EXPECT_EQ(plm5.isSame(plm1), true);
Base::Placement plm6 = Base::Placement::sclerp(plm1, plm2, 0.5);
EXPECT_EQ(plm6.getRotation().isSame(Base::Rotation(1, 1, 0, 0), epsilon), true);
EXPECT_EQ(plm6.getPosition().IsEqual(pos, epsilon), true);
}

280
tests/src/Base/Quantity.cpp Normal file
View File

@@ -0,0 +1,280 @@
#include <gtest/gtest.h>
#include <Base/Exception.h>
#include <Base/Quantity.h>
#include "Base/UnitsApi.h"
#include <QLocale>
using Base::ParserError;
using Base::Quantity;
using Base::Unit;
using Base::UnitsMismatchError;
TEST(BaseQuantity, TestValid)
{
const Quantity q1 {1.0, Unit::Length};
Quantity q2 {1.0, Unit::Area};
q2.setInvalid();
EXPECT_EQ(q1.isValid(), true);
EXPECT_EQ(q2.isValid(), false);
}
TEST(BaseQuantity, TestParse)
{
const Quantity q1 = Quantity::parse("1,234 kg");
constexpr auto val {1.2340};
EXPECT_EQ(q1, Quantity(val, Unit::Mass));
EXPECT_THROW(auto rew [[maybe_unused]] = Quantity::parse("1,234,500.12 kg"), ParserError);
}
TEST(BaseQuantity, TestNoDim)
{
const Quantity q1 {};
EXPECT_EQ(q1.pow(2), Quantity {0});
EXPECT_EQ(q1.isDimensionless(), true);
}
TEST(BaseQuantity, TestPowEQ1)
{
const Quantity q1 {2, Unit::Area};
const auto expect = Quantity {2, Unit::Area};
EXPECT_EQ(q1.pow(1), expect);
}
TEST(BaseQuantity, TestPowEQ0)
{
const Quantity q1 {2, Unit::Area};
EXPECT_EQ(q1.pow(0), Quantity {1});
}
TEST(BaseQuantity, TestPowGT1)
{
constexpr auto v2 {2};
constexpr auto v4 {4};
const Quantity q1 {v2, Unit::Length};
EXPECT_EQ(q1.pow(v2), Quantity(v4, Unit::Area));
}
TEST(BaseQuantity, TestPowLT1)
{
constexpr auto v8 {8};
constexpr auto v2 {2};
constexpr auto v3 {3.0};
const Quantity q1 {v8, Unit::Volume};
EXPECT_EQ(q1.pow(1.0 / v3), Quantity(v2, Unit::Length));
}
TEST(BaseQuantity, TestPow3DIV2)
{
constexpr auto v2 {2.0};
constexpr auto v3 {3.0};
constexpr auto v8 {8};
const Quantity unit {v8, Unit::Volume};
EXPECT_THROW(unit.pow(v3 / v2), UnitsMismatchError);
}
TEST(BaseQuantity, TestString)
{
constexpr auto v2 {2};
const Quantity q1 {v2, "kg*m/s^2"};
EXPECT_EQ(q1.getUnit(), Unit::Force);
const Quantity q2 {v2, "kg*m^2/s^2"};
EXPECT_EQ(q2.getUnit(), Unit::Work);
}
TEST(BaseQuantity, TestCopy)
{
const Quantity q1 {1.0, Unit::Length};
EXPECT_EQ(Quantity {q1}, q1);
}
TEST(BaseQuantity, TestEqual)
{
const Quantity q1 {1.0, Unit::Force};
const Quantity q2 {1.0, "kg*mm/s^2"};
EXPECT_EQ(q1 == q1, true);
EXPECT_EQ(q1 == q2, true);
}
TEST(BaseQuantity, TestNotEqual)
{
constexpr auto v2 {2.0};
const Quantity q1 {1.0, Unit::Force};
const Quantity q2 {v2, "kg*m/s^2"};
const Quantity q3 {1.0, Unit::Work};
EXPECT_EQ(q1 != q2, true);
EXPECT_EQ(q1 != q3, true);
}
TEST(BaseQuantity, TestLessOrGreater)
{
constexpr auto v2 {2.0};
Quantity q1 {1.0, Unit::Force};
Quantity q2 {v2, "kg*m/s^2"};
Quantity q3 {v2, Unit::Work};
EXPECT_EQ(q1 < q2, true);
EXPECT_EQ(q1 > q2, false);
EXPECT_EQ(q1 <= q1, true);
EXPECT_EQ(q1 >= q1, true);
EXPECT_THROW(auto res [[maybe_unused]] = (q1 < q3), UnitsMismatchError);
EXPECT_THROW(auto res [[maybe_unused]] = (q1 > q3), UnitsMismatchError);
EXPECT_THROW(auto res [[maybe_unused]] = (q1 <= q3), UnitsMismatchError);
EXPECT_THROW(auto res [[maybe_unused]] = (q1 >= q3), UnitsMismatchError);
}
TEST(BaseQuantity, TestAdd)
{
Quantity q1 {1.0, Unit::Length};
Quantity q2 {1.0, Unit::Area};
EXPECT_THROW(q1 + q2, UnitsMismatchError);
EXPECT_THROW(q1 += q2, UnitsMismatchError);
EXPECT_EQ(q1 + q1, Quantity(2, Unit::Length));
EXPECT_EQ(q1 += q1, Quantity(2, Unit::Length));
}
TEST(BaseQuantity, TestSub)
{
Quantity q1 {1.0, Unit::Length};
Quantity q2 {1.0, Unit::Area};
EXPECT_THROW(q1 - q2, UnitsMismatchError);
EXPECT_THROW(q1 -= q2, UnitsMismatchError);
EXPECT_EQ(q1 - q1, Quantity(0, Unit::Length));
EXPECT_EQ(q1 -= q1, Quantity(0, Unit::Length));
}
TEST(BaseQuantity, TestNeg)
{
const Quantity q1 {1.0, Unit::Length};
EXPECT_EQ(-q1, Quantity(-1.0, Unit::Length));
}
TEST(BaseQuantity, TestMult)
{
const Quantity q1 {1.0, Unit::Length};
const Quantity q2 {1.0, Unit::Area};
EXPECT_EQ(q1 * q2, Quantity(1.0, Unit::Volume));
EXPECT_EQ(q1 * 2.0, Quantity(2.0, Unit::Length));
}
TEST(BaseQuantity, TestDiv)
{
const Quantity q1 {1.0, Unit::Length};
const Quantity q2 {1.0, Unit::Area};
EXPECT_EQ(q1 / q2, Quantity(1.0, Unit::InverseLength));
EXPECT_EQ(q1 / 2.0, Quantity(0.5, Unit::Length));
}
TEST(BaseQuantity, TestPow)
{
constexpr auto v2 {2.0};
constexpr auto v4 {4};
Quantity q1 {v2, Unit::Length};
Quantity q2 {v2, Unit::Area};
Quantity q3 {0.0};
EXPECT_EQ(q1.pow(q3), Quantity {1});
EXPECT_EQ(q1.pow(v2), Quantity(v4, Unit::Area));
EXPECT_THROW(q1.pow(q2), UnitsMismatchError);
}
class BaseQuantityLoc: public ::testing::Test
{
protected:
void SetUp() override
{
QLocale loc(QLocale::C);
QLocale::setDefault(loc);
}
void TearDown() override
{}
};
TEST_F(BaseQuantityLoc, psi_parse_spaced)
{
const auto qParsed = Quantity::parse("1 psi");
EXPECT_EQ(qParsed.getValue(), 6.8947572931683609);
}
TEST_F(BaseQuantityLoc, psi_parse_no_space)
{
const auto qParsed = Quantity::parse("1psi");
EXPECT_EQ(qParsed.getValue(), 6.8947572931683609);
}
TEST_F(BaseQuantityLoc, psi_parse_user_str)
{
Base::UnitsApi::setSchema("Internal");
auto qParsed = Quantity::parse("1 psi");
auto format = qParsed.getFormat();
format.setPrecision(2);
qParsed.setFormat(format);
EXPECT_EQ(qParsed.getUserString(), "6894.76 Pa");
}
TEST_F(BaseQuantityLoc, psi_parse_safe_user_str)
{
Base::UnitsApi::setSchema("Internal");
auto qParsed = Quantity::parse("1 psi");
auto format = qParsed.getFormat();
format.setPrecision(2);
qParsed.setFormat(format);
EXPECT_EQ(qParsed.getSafeUserString(), "6894.76 Pa");
}
TEST_F(BaseQuantityLoc, psi_parse_unit_type)
{
const auto qParsed = Quantity::parse("1 psi");
EXPECT_EQ(qParsed.getUnit().getTypeString(), "Pressure");
}
TEST_F(BaseQuantityLoc, psi_to_Pa)
{
const auto result = Quantity::parse("1 psi").getValueAs(Quantity::Pascal);
const auto expect = 6894.7572931683608;
EXPECT_EQ(result, expect);
}
TEST_F(BaseQuantityLoc, psi_to_KPa)
{
const auto result = Quantity::parse("1 psi").getValueAs(Quantity::KiloPascal);
const auto expect = 6.8947572931683609;
EXPECT_EQ(result, expect);
}
TEST_F(BaseQuantityLoc, psi_to_MPa)
{
const auto result = Quantity::parse("1 psi").getValueAs(Quantity::MegaPascal);
const auto expect = 0.0068947572931683607;
EXPECT_EQ(result, expect);
}
TEST_F(BaseQuantityLoc, voltage_unit)
{
const auto qq = Quantity::parse("1e20 V");
EXPECT_EQ(qq.getUnit(), Unit::ElectricPotential);
}
TEST_F(BaseQuantityLoc, voltage_val)
{
const auto qq = Quantity::parse("1e20 V");
EXPECT_EQ(qq.getValue(), 1e+26);
}
TEST_F(BaseQuantityLoc, voltage_val_smaller)
{
const auto qq = Quantity::parse("1e3 V");
EXPECT_EQ(qq.getValue(), 1e+9);
}

618
tests/src/Base/Reader.cpp Normal file
View File

@@ -0,0 +1,618 @@
// SPDX-License-Identifier: LGPL-2.1-or-later
#include <gtest/gtest.h>
#include <QString>
#ifdef _MSC_VER
# pragma warning(disable : 4996)
# pragma warning(disable : 4305)
#endif
#include "Base/Exception.h"
#include "Base/Persistence.h"
#include "Base/Reader.h"
#include <array>
#include <filesystem>
#include <fstream>
#include <random>
#include <string>
#include <xercesc/util/PlatformUtils.hpp>
namespace fs = std::filesystem;
static std::string random_string(size_t length)
{
const std::string digits = "0123456789";
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> dis(0, static_cast<int>(digits.size()) - 1);
std::string result;
for (size_t i = 0; i < length; ++i) {
result += digits[dis(gen)];
}
return result;
}
class ReaderXML
{
public:
ReaderXML()
{
_tempDir = fs::temp_directory_path();
fs::path filename = std::string("unit_test_Reader-") + random_string(4) + std::string(".xml");
_tempFile = _tempDir / filename;
}
~ReaderXML()
{
if (inputStream.is_open()) {
inputStream.close();
}
if (fs::exists(_tempFile)) {
fs::remove(_tempFile);
}
}
Base::XMLReader* Reader()
{
return _reader.get();
}
void givenDataAsXMLStream(const std::string& data)
{
auto stringData = R"(<?xml version="1.0" encoding="UTF-8"?><document>)" + data
+ "</document>";
std::istringstream stream(stringData);
std::ofstream fileStream(_tempFile.string());
fileStream.write(stringData.data(), static_cast<std::streamsize>(stringData.length()));
fileStream.close();
inputStream.open(_tempFile.string());
_reader = std::make_unique<Base::XMLReader>(_tempFile.string().c_str(), inputStream);
}
private:
std::unique_ptr<Base::XMLReader> _reader;
fs::path _tempDir;
fs::path _tempFile;
std::ifstream inputStream;
};
class ReaderTest: public ::testing::Test
{
protected:
void SetUp() override
{
XERCES_CPP_NAMESPACE::XMLPlatformUtils::Initialize();
}
void TearDown() override
{}
};
TEST_F(ReaderTest, beginCharStreamNormal)
{
// Arrange
ReaderXML xml;
xml.givenDataAsXMLStream("<data>Test ASCII data</data>");
xml.Reader()->readElement("data");
// Act
auto& result = xml.Reader()->beginCharStream();
// Assert
EXPECT_TRUE(result.good());
}
TEST_F(ReaderTest, beginCharStreamOpenClose)
{
// Arrange
ReaderXML xml;
xml.givenDataAsXMLStream("<data id='12345' />");
xml.Reader()->readElement("data");
// Act
auto& result = xml.Reader()->beginCharStream(); // Not an error, even though there is no data
// Assert
EXPECT_TRUE(result.good());
}
TEST_F(ReaderTest, beginCharStreamAlreadyBegun)
{
// Arrange
ReaderXML xml;
xml.givenDataAsXMLStream("<data>Test ASCII data</data>");
xml.Reader()->readElement("data");
xml.Reader()->beginCharStream();
// Act & Assert
EXPECT_THROW(xml.Reader()->beginCharStream(), Base::XMLParseException); // NOLINT
}
TEST_F(ReaderTest, charStreamGood)
{
// Arrange
ReaderXML xml;
xml.givenDataAsXMLStream("<data>Test ASCII data</data>");
xml.Reader()->readElement("data");
xml.Reader()->beginCharStream();
// Act
auto& result = xml.Reader()->charStream();
// Assert
EXPECT_TRUE(result.good());
}
TEST_F(ReaderTest, charStreamBad)
{
// Arrange
ReaderXML xml;
xml.givenDataAsXMLStream("<data>Test ASCII data</data>");
xml.Reader()->readElement("data");
// Act & Assert
EXPECT_THROW(xml.Reader()->charStream(), Base::XMLParseException); // NOLINT
}
TEST_F(ReaderTest, endCharStreamGood)
{
// Arrange
ReaderXML xml;
xml.givenDataAsXMLStream("<data>Test ASCII data</data>");
xml.Reader()->readElement("data");
xml.Reader()->beginCharStream();
// Act & Assert
xml.Reader()->endCharStream(); // Does not throw
}
TEST_F(ReaderTest, endCharStreamBad)
{
// Arrange
ReaderXML xml;
xml.givenDataAsXMLStream("<data>Test ASCII data</data>");
xml.Reader()->readElement("data");
// Do not open the stream...
// Act & Assert
xml.Reader()->endCharStream(); // Does not throw, even with no open stream
}
TEST_F(ReaderTest, readDataSmallerThanBuffer)
{
// Arrange
constexpr size_t bufferSize {20};
std::string expectedData {"Test ASCII data"};
ReaderXML xml;
xml.givenDataAsXMLStream("<data>" + expectedData + "</data>");
xml.Reader()->readElement("data");
xml.Reader()->beginCharStream();
std::array<char, bufferSize> buffer {};
// Act
auto bytesRead = xml.Reader()->read(buffer.data(), bufferSize);
// Assert
EXPECT_STREQ(expectedData.c_str(), buffer.data());
EXPECT_EQ(expectedData.length(), bytesRead);
}
TEST_F(ReaderTest, readDataLargerThanBuffer)
{
// Arrange
constexpr size_t bufferSize {5};
std::string expectedData {"Test ASCII data"};
ReaderXML xml;
xml.givenDataAsXMLStream("<data>" + expectedData + "</data>");
xml.Reader()->readElement("data");
xml.Reader()->beginCharStream();
std::array<char, bufferSize> buffer {};
// Act
auto bytesRead = xml.Reader()->read(buffer.data(), bufferSize);
// Assert
for (size_t i = 0; i < bufferSize; ++i) {
EXPECT_EQ(expectedData[i], buffer.at(i));
}
EXPECT_EQ(bufferSize, bytesRead);
}
TEST_F(ReaderTest, readDataLargerThanBufferSecondRead)
{
// Arrange
constexpr size_t bufferSize {5};
std::string expectedData {"Test ASCII data"};
ReaderXML xml;
xml.givenDataAsXMLStream("<data>" + expectedData + "</data>");
xml.Reader()->readElement("data");
xml.Reader()->beginCharStream();
std::array<char, bufferSize> buffer {};
xml.Reader()->read(buffer.data(), bufferSize); // Read the first five bytes
// Act
auto bytesRead = xml.Reader()->read(buffer.data(), bufferSize); // Second five bytes
// Assert
for (size_t i = 0; i < bufferSize; ++i) {
EXPECT_EQ(expectedData[i + bufferSize], buffer.at(i));
}
EXPECT_EQ(bufferSize, bytesRead);
}
TEST_F(ReaderTest, readDataNotStarted)
{
// Arrange
constexpr size_t bufferSize {20};
std::string expectedData {"Test ASCII data"};
ReaderXML xml;
xml.givenDataAsXMLStream("<data>" + expectedData + "</data>");
xml.Reader()->readElement("data");
std::array<char, bufferSize> buffer {};
// Act
auto bytesRead = xml.Reader()->read(buffer.data(), bufferSize);
// Assert
EXPECT_EQ(-1, bytesRead); // Because we didn't call beginCharStream
}
TEST_F(ReaderTest, readNextStartElement)
{
auto xmlBody = R"(
<node1 attr='1'>Node1</node1>
<node2 attr='2'>Node2</node2>
)";
ReaderXML xml;
xml.givenDataAsXMLStream(xmlBody);
// start of document
EXPECT_TRUE(xml.Reader()->isStartOfDocument());
xml.Reader()->readElement("document");
EXPECT_STREQ(xml.Reader()->localName(), "document");
// next element
EXPECT_TRUE(xml.Reader()->readNextElement());
EXPECT_STREQ(xml.Reader()->localName(), "node1");
EXPECT_STREQ(xml.Reader()->getAttribute<const char*>("attr"), "1");
xml.Reader()->readEndElement("node1");
EXPECT_TRUE(xml.Reader()->isEndOfElement());
// next element
EXPECT_TRUE(xml.Reader()->readNextElement());
EXPECT_STREQ(xml.Reader()->localName(), "node2");
EXPECT_STREQ(xml.Reader()->getAttribute<const char*>("attr"), "2");
xml.Reader()->readEndElement("node2");
EXPECT_TRUE(xml.Reader()->isEndOfElement());
xml.Reader()->readEndElement("document");
EXPECT_TRUE(xml.Reader()->isEndOfDocument());
}
TEST_F(ReaderTest, readNextStartEndElement)
{
// Arrange
enum class TimesIGoToBed
{
Late,
Later,
VeryLate,
FreeCADDevLate // https://user-images.githubusercontent.com/12400097/235325792-606bffd6-6607-4542-a7d9-a04f12120666.png
};
auto xmlBody = R"(
<node1 attr='1'/>
<node2 attr='2'/>
<node3 attr='3'/>
<node4 attr='1'/>
<node5 attr='0'/>
<node5b attr='0xFF'/>
<node6 attr='asdaf'/>
<node7 attr="const char* is faster :'("/>
<node8 attr='8'/>
<node9 attr='9'/>
<node10 attr='10'/>
<node11 attr='11'/>
)";
ReaderXML xml;
xml.givenDataAsXMLStream(xmlBody);
// start of document
EXPECT_TRUE(xml.Reader()->isStartOfDocument());
xml.Reader()->readElement("document");
EXPECT_STREQ(xml.Reader()->localName(), "document");
// next element
EXPECT_TRUE(xml.Reader()->readNextElement());
EXPECT_STREQ(xml.Reader()->localName(), "node1");
EXPECT_STREQ(xml.Reader()->getAttribute<const char*>("attr"), "1");
// next element
EXPECT_TRUE(xml.Reader()->readNextElement());
EXPECT_STREQ(xml.Reader()->localName(), "node2");
EXPECT_STREQ(xml.Reader()->getAttribute<const char*>("attr"), "2");
// next element
EXPECT_TRUE(xml.Reader()->readNextElement());
EXPECT_STREQ(xml.Reader()->localName(), "node3");
EXPECT_EQ(xml.Reader()->getAttribute<TimesIGoToBed>("attr"), TimesIGoToBed::FreeCADDevLate);
// next element
EXPECT_TRUE(xml.Reader()->readNextElement());
EXPECT_STREQ(xml.Reader()->localName(), "node4");
EXPECT_EQ(xml.Reader()->getAttribute<bool>("attr"), true);
// next element
EXPECT_TRUE(xml.Reader()->readNextElement());
EXPECT_STREQ(xml.Reader()->localName(), "node5");
EXPECT_EQ(xml.Reader()->getAttribute<bool>("attr"), false);
// next element
EXPECT_TRUE(xml.Reader()->readNextElement());
EXPECT_STREQ(xml.Reader()->localName(), "node5b");
EXPECT_EQ(xml.Reader()->getAttribute<bool>("attr"), true);
// next element
EXPECT_TRUE(xml.Reader()->readNextElement());
EXPECT_STREQ(xml.Reader()->localName(), "node6");
EXPECT_EQ(xml.Reader()->getAttribute<bool>("attr"), true);
// next element
EXPECT_TRUE(xml.Reader()->readNextElement());
EXPECT_STREQ(xml.Reader()->localName(), "node7");
EXPECT_EQ(xml.Reader()->getAttribute<std::string>("attr"), std::string("const char* is faster :'("));
// next element
EXPECT_TRUE(xml.Reader()->readNextElement());
EXPECT_STREQ(xml.Reader()->localName(), "node8");
EXPECT_EQ(xml.Reader()->getAttribute<long>("attr"), 8);
// next element
EXPECT_TRUE(xml.Reader()->readNextElement());
EXPECT_STREQ(xml.Reader()->localName(), "node9");
EXPECT_EQ(xml.Reader()->getAttribute<unsigned long>("attr"), 9);
// next element
EXPECT_TRUE(xml.Reader()->readNextElement());
EXPECT_STREQ(xml.Reader()->localName(), "node10");
EXPECT_EQ(xml.Reader()->getAttribute<int>("attr"), 10);
// next element
EXPECT_TRUE(xml.Reader()->readNextElement());
EXPECT_STREQ(xml.Reader()->localName(), "node11");
EXPECT_EQ(xml.Reader()->getAttribute<QString>("attr"), QStringLiteral("11"));
EXPECT_FALSE(xml.Reader()->readNextElement());
EXPECT_TRUE(xml.Reader()->isEndOfDocument());
}
TEST_F(ReaderTest, charStreamBase64Encoded)
{
// Arrange
static constexpr size_t bufferSize {100};
std::array<char, bufferSize> buffer {};
ReaderXML xml;
xml.givenDataAsXMLStream("<data>RnJlZUNBRCByb2NrcyEg8J+qqPCfqqjwn6qo\n</data>");
xml.Reader()->readElement("data");
xml.Reader()->beginCharStream(Base::CharStreamFormat::Base64Encoded);
// Act
xml.Reader()->charStream().getline(buffer.data(), bufferSize);
xml.Reader()->endCharStream();
// Assert
// Conversion done using https://www.base64encode.org for testing purposes
EXPECT_EQ(std::string("FreeCAD rocks! 🪨🪨🪨"), std::string(buffer.data()));
}
TEST_F(ReaderTest, validDefaults)
{
// Arrange
enum class TimesIGoToBed
{
Late,
Later,
VeryLate,
FreeCADDevLate // https://user-images.githubusercontent.com/12400097/235325792-606bffd6-6607-4542-a7d9-a04f12120666.png
};
auto xmlBody = R"(
<node1 attr='1'/>
<node2 attr='2'/>
)";
ReaderXML xml;
xml.givenDataAsXMLStream(xmlBody);
// Act
const char* value2 = xml.Reader()->getAttribute<const char*>("missing", "expected value");
int value4 = xml.Reader()->getAttribute<long>("missing", -123);
unsigned value6 = xml.Reader()->getAttribute<unsigned long>("missing", 123);
double value8 = xml.Reader()->getAttribute<double>("missing", 1.234);
bool value12 = xml.Reader()->getAttribute<bool>("missing", 0);
bool value14 = xml.Reader()->getAttribute<bool>("missing", 1);
bool value16 = xml.Reader()->getAttribute<bool>("missing", -10);
bool value18 = xml.Reader()->getAttribute<bool>("missing", 10);
TimesIGoToBed value20 = xml.Reader()->getAttribute<TimesIGoToBed>("missing", TimesIGoToBed::Late);
// Assert
EXPECT_THROW({ xml.Reader()->getAttribute<const char*>("missing"); }, Base::XMLBaseException);
EXPECT_EQ(value2, "expected value");
EXPECT_THROW({ xml.Reader()->getAttribute<long>("missing"); }, Base::XMLBaseException);
EXPECT_EQ(value4, -123);
EXPECT_THROW({ xml.Reader()->getAttribute<unsigned long>("missing"); }, Base::XMLBaseException);
EXPECT_EQ(value6, 123);
EXPECT_THROW({ xml.Reader()->getAttribute<double>("missing"); }, Base::XMLBaseException);
EXPECT_NEAR(value8, 1.234, 0.001);
EXPECT_THROW({ xml.Reader()->getAttribute<int>("missing"); }, Base::XMLBaseException);
EXPECT_NEAR(value8, 1.234, 0.001);
EXPECT_THROW({ xml.Reader()->getAttribute<bool>("missing"); }, Base::XMLBaseException);
EXPECT_EQ(value12, false);
EXPECT_EQ(value14, true);
EXPECT_EQ(value16, true);
EXPECT_EQ(value18, true);
EXPECT_THROW({ xml.Reader()->getAttribute<TimesIGoToBed>("missing"); }, Base::XMLBaseException);
EXPECT_EQ(value20, TimesIGoToBed::Late);
}
TEST_F(ReaderTest, AsciiUnchanged)
{
std::string input = "Hello, world!";
std::string result = Base::Persistence::validateXMLString(input);
EXPECT_EQ(result, input);
}
TEST_F(ReaderTest, AllowedWhitespacePreserved)
{
std::string input = "a\tb\nc\rd";
std::string result = Base::Persistence::validateXMLString(input);
EXPECT_EQ(result, input);
}
TEST_F(ReaderTest, DisallowedC0ControlsBecomeUnderscore)
{
std::string input = "A";
input.push_back(char(0x00));
input.push_back(char(0x0F));
input.push_back(char(0x1B));
input += "Z";
std::string expected = "A___Z";
std::string result = Base::Persistence::validateXMLString(input);
EXPECT_EQ(result, expected);
}
TEST_F(ReaderTest, DelAndC1ControlsBecomeUnderscore)
{
std::string input;
input.push_back('X');
input.push_back(char(0x7F)); // DEL
// U+0086 (SSA) in UTF-8: 0xC2 0x86
input += std::string("\xC2\x86", 2);
input.push_back('Y');
std::string expected = "X__Y";
std::string result = Base::Persistence::validateXMLString(input);
EXPECT_EQ(result, expected);
}
namespace
{
// Minimal UTF-8 encoder -- not valid for full production use, test suite only!
static void append_cp_utf8(std::string& s, char32_t cp)
{
if (cp <= 0x7F) {
s.push_back(static_cast<char>(cp));
}
else if (cp <= 0x7FF) {
s.push_back(static_cast<char>(0xC0 | (cp >> 6)));
s.push_back(static_cast<char>(0x80 | (cp & 0x3F)));
}
else if (cp <= 0xFFFF) {
s.push_back(static_cast<char>(0xE0 | (cp >> 12)));
s.push_back(static_cast<char>(0x80 | ((cp >> 6) & 0x3F)));
s.push_back(static_cast<char>(0x80 | (cp & 0x3F)));
}
else {
s.push_back(static_cast<char>(0xF0 | (cp >> 18)));
s.push_back(static_cast<char>(0x80 | ((cp >> 12) & 0x3F)));
s.push_back(static_cast<char>(0x80 | ((cp >> 6) & 0x3F)));
s.push_back(static_cast<char>(0x80 | (cp & 0x3F)));
}
}
static std::string make_utf8(std::initializer_list<char32_t> cps)
{
std::string s;
for (char32_t cp : cps) {
append_cp_utf8(s, cp);
}
return s;
}
} // namespace
TEST_F(ReaderTest, BmpBoundaryAndNoncharacters)
{
std::string input;
input += "X";
input += make_utf8({0xFFFD}); // allowed
input += make_utf8({0xFFFE}); // disallowed
input += "Y";
std::string expected;
expected += "X";
expected += make_utf8({0xFFFD});
expected += "_";
expected += "Y";
std::string result = Base::Persistence::validateXMLString(input);
EXPECT_EQ(result, expected);
}
TEST_F(ReaderTest, NonBmpEmojiPreserved)
{
// 😀 U+1F600
std::string emoji = make_utf8({0x1F600});
std::string input = "A" + emoji + "B";
std::string result = Base::Persistence::validateXMLString(input);
EXPECT_EQ(result, input);
}
TEST_F(ReaderTest, ZwjSequencePreserved)
{
std::string family = make_utf8({0x1F468, 0x200D, 0x1F469, 0x200D, 0x1F467, 0x200D, 0x1F466});
std::string input = "X" + family + "Y";
std::string result = Base::Persistence::validateXMLString(input);
EXPECT_EQ(result, input);
}
TEST_F(ReaderTest, CombiningMarksPreserved)
{
std::string decomposed = std::string("caf") + make_utf8({0x0065, 0x0301}); // "café"
std::string result = Base::Persistence::validateXMLString(decomposed);
EXPECT_EQ(result, decomposed);
}
TEST_F(ReaderTest, PrivateUseAreaPreserved)
{
// Yes, actually permitted by XML (as far as I can determine - chennes)
std::string pua = make_utf8({0xE000});
std::string input = "A" + pua + "B";
std::string result = Base::Persistence::validateXMLString(input);
EXPECT_EQ(result, input);
}
TEST_F(ReaderTest, MixedContentSanitization)
{
std::string input;
input += "A";
input.push_back(char(0x1F)); // disallowed control -> '_'
input += make_utf8({0x1F602}); // 😂 allowed
input.push_back(char(0x00)); // disallowed control -> '_'
input += "Z";
std::string expected;
expected += "A";
expected += "_";
expected += make_utf8({0x1F602});
expected += "_";
expected += "Z";
std::string result = Base::Persistence::validateXMLString(input);
EXPECT_EQ(result, expected);
}
TEST_F(ReaderTest, validateXmlString)
{
std::string input = "abcde";
std::string output = input;
input.push_back(char(15));
output.push_back('_');
std::string result = Base::Persistence::validateXMLString(input);
EXPECT_EQ(output, result);
}

View File

@@ -0,0 +1,80 @@
#include <gtest/gtest.h>
#include <Base/Exception.h>
#include <Base/Matrix.h>
#include <Base/Rotation.h>
// NOLINTBEGIN(cppcoreguidelines-avoid-magic-numbers,readability-magic-numbers)
TEST(Rotation, TestNonUniformScaleLeft)
{
Base::Rotation rot;
rot.setYawPitchRoll(45.0, 0.0, 0.0);
Base::Matrix4D mat;
rot.getValue(mat);
Base::Matrix4D scale;
scale.scale(1.0, std::sqrt(3.0), 1.0);
Base::Rotation scaled_rot(scale * mat);
rot.setYawPitchRoll(60.0, 0.0, 0.0);
EXPECT_EQ(scaled_rot.isSame(rot, 1.0e-7), true);
EXPECT_EQ(rot.isSame(scaled_rot, 1.0e-7), true);
}
TEST(Rotation, TestNonUniformScaleRight)
{
Base::Rotation rot;
rot.setYawPitchRoll(20.0, 0.0, 0.0);
Base::Matrix4D mat;
rot.getValue(mat);
Base::Matrix4D scale;
scale.scale(2.0, 3.0, 4.0);
Base::Rotation scaled_rot(mat * scale);
EXPECT_EQ(scaled_rot.isSame(rot, 1.0e-7), true);
EXPECT_EQ(rot.isSame(scaled_rot, 1.0e-7), true);
}
TEST(Rotation, TestUniformScaleGT1)
{
Base::Rotation rot;
rot.setYawPitchRoll(20.0, 0.0, 0.0);
Base::Matrix4D mat;
rot.getValue(mat);
Base::Matrix4D scale;
scale.scale(3.0, 3.0, 3.0);
Base::Rotation scaled_rot(mat * scale);
EXPECT_EQ(scaled_rot.isSame(rot, 1.0e-7), true);
EXPECT_EQ(rot.isSame(scaled_rot, 1.0e-7), true);
}
TEST(Rotation, TestUniformScaleLT1)
{
Base::Matrix4D mat;
mat.scale(0.5);
Base::Rotation scaled_rot(mat);
EXPECT_EQ(scaled_rot.isSame(scaled_rot, 1.0e-7), true);
}
TEST(Rotation, TestRotationDecompose)
{
Base::Matrix4D mat;
mat.setCol(0, Base::Vector3d {1, 0, 0});
mat.setCol(1, Base::Vector3d {1, 1, 0});
mat.setCol(2, Base::Vector3d {0, 0, 1});
// decompose rotation part
EXPECT_TRUE(Base::Rotation {mat}.isIdentity());
}
// NOLINTEND(cppcoreguidelines-avoid-magic-numbers,readability-magic-numbers)

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,110 @@
#include <gtest/gtest.h>
#include <Base/ServiceProvider.h>
class SimpleService
{
public:
virtual ~SimpleService() = default;
virtual std::string foo() = 0;
SimpleService() = default;
SimpleService(const SimpleService& other) = delete;
SimpleService(SimpleService&& other) noexcept = delete;
SimpleService& operator=(const SimpleService& other) = delete;
SimpleService& operator=(SimpleService&& other) noexcept = delete;
};
class FirstServiceImplementation final: public SimpleService
{
public:
std::string foo() override
{
return "first";
}
};
class SecondServiceImplementation final: public SimpleService
{
public:
std::string foo() override
{
return "second";
}
};
TEST(ServiceProvider, provideEmptyImplementation)
{
// Arrange
Base::ServiceProvider serviceProvider;
// Act
auto implementation = serviceProvider.provide<SimpleService>();
// Assert
EXPECT_EQ(implementation, nullptr);
}
TEST(ServiceProvider, provideEmptyImplementationList)
{
// Arrange
Base::ServiceProvider serviceProvider;
// Act
const auto implementations = serviceProvider.all<SimpleService>();
// Assert
EXPECT_EQ(implementations.size(), 0);
}
TEST(ServiceProvider, provideImplementation)
{
// Arrange
Base::ServiceProvider serviceProvider;
serviceProvider.registerImplementation<SimpleService>(new FirstServiceImplementation);
// Act
auto implementation = serviceProvider.provide<SimpleService>();
// Assert
EXPECT_NE(implementation, nullptr);
EXPECT_EQ(implementation->foo(), "first");
}
TEST(ServiceProvider, provideLatestImplementation)
{
// Arrange
Base::ServiceProvider serviceProvider;
serviceProvider.registerImplementation<SimpleService>(new FirstServiceImplementation);
serviceProvider.registerImplementation<SimpleService>(new SecondServiceImplementation);
// Act
auto implementation = serviceProvider.provide<SimpleService>();
// Assert
EXPECT_NE(implementation, nullptr);
EXPECT_EQ(implementation->foo(), "second");
}
TEST(ServiceProvider, provideAllImplementations)
{
// Arrange
Base::ServiceProvider serviceProvider;
serviceProvider.registerImplementation<SimpleService>(new FirstServiceImplementation);
serviceProvider.registerImplementation<SimpleService>(new SecondServiceImplementation);
// Act
auto implementations = serviceProvider.all<SimpleService>();
auto it = implementations.begin();
// Assert
// Implementations should be available in order from the most recent one
EXPECT_EQ((*it)->foo(), "second");
++it;
EXPECT_EQ((*it)->foo(), "first");
++it;
EXPECT_EQ(it, implementations.end());
}

127
tests/src/Base/Stream.cpp Normal file
View File

@@ -0,0 +1,127 @@
// SPDX-License-Identifier: LGPL-2.1-or-later
#include <gtest/gtest.h>
#ifdef _MSC_VER
# pragma warning(disable : 4996)
#endif
#include "Base/Stream.h"
class TextOutputStreamTest: public ::testing::Test
{
protected:
void SetUp() override
{}
void TearDown() override
{}
};
TEST_F(TextOutputStreamTest, singleLineCharStar)
{
// Arrange
const std::string testString("Single line const char *");
std::ostringstream ss;
Base::TextOutputStream tos(ss);
// Act
tos << testString;
// Assert - the number of newlines in the string, a colon, the string, a newline
EXPECT_EQ(std::string("0:") + testString + "\n", ss.str());
}
TEST_F(TextOutputStreamTest, multiLineCharStar)
{
// Arrange
const std::string testString("Multi-line\nconst char *");
std::ostringstream ss;
Base::TextOutputStream tos(ss);
// Act
tos << testString; // Testing it with a string instead of a const char * -- failing right now
// Assert - the number of newlines in the string, a colon, the string, a newline
EXPECT_EQ(std::string("1:") + testString + "\n", ss.str());
}
TEST_F(TextOutputStreamTest, singleLineCharStarWithCarriageReturns)
{
// Arrange
const std::string testString("Single-line\rconst char *");
std::ostringstream ss;
Base::TextOutputStream tos(ss);
// Act
tos << testString;
// Assert - the number of newlines in the string, a colon, the string, a newline. Carriage
// returns are left alone because they aren't followed by a newline
EXPECT_EQ(std::string("0:") + testString + "\n", ss.str());
}
TEST_F(TextOutputStreamTest, multiLineCharStarWithCarriageReturnsAndNewlines)
{
// Arrange
const std::string testString("Multi-line\r\nconst char *");
const std::string testStringWithoutCR("Multi-line\nconst char *");
std::ostringstream ss;
Base::TextOutputStream tos(ss);
// Act
tos << testString;
// Assert - the number of newlines in the string, a colon, the string, a newline, but the string
// has been stripped of the carriage returns.
EXPECT_EQ(std::string("1:") + testStringWithoutCR + "\n", ss.str());
}
class TextStreamIntegrationTest: public ::testing::Test
{
protected:
void SetUp() override
{}
void TearDown() override
{}
};
TEST_F(TextStreamIntegrationTest, OutputThenInputSimpleMultiLine)
{
// Arrange
std::string multiLineString("One\nTwo\nThree");
// Act
std::ostringstream ssO;
Base::TextOutputStream tos(ssO);
tos << multiLineString;
std::istringstream ssI(ssO.str());
Base::TextInputStream tis(ssI);
std::string result;
tis >> result;
// Assert
EXPECT_EQ(multiLineString, result);
}
TEST_F(TextStreamIntegrationTest, OutputThenInputMultiLineWithCarriageReturns)
{
// Arrange
std::string multiLineString("One\r\nTwo\r\nThree");
std::string multiLineStringResult("One\nTwo\nThree");
// Act
std::ostringstream ssO;
Base::TextOutputStream tos(ssO);
tos << multiLineString;
std::istringstream ssI(ssO.str());
Base::TextInputStream tis(ssI);
std::string result;
tis >> result;
// Assert
EXPECT_EQ(multiLineStringResult, result);
}

View File

@@ -0,0 +1,35 @@
#include <gtest/gtest.h>
#include <Base/TimeInfo.h>
TEST(TimeInfo, TestDefault)
{
Base::TimeInfo ti;
EXPECT_FALSE(ti.isNull());
}
TEST(TimeInfo, TestNull)
{
Base::TimeInfo ti(Base::TimeInfo::null());
EXPECT_TRUE(ti.isNull());
}
TEST(TimeInfo, TestCompare)
{
Base::TimeInfo ti1;
Base::TimeInfo ti2(ti1);
ti2 += std::chrono::seconds(1);
EXPECT_TRUE(ti1 == ti1);
EXPECT_TRUE(ti1 != ti2);
EXPECT_TRUE(ti1 < ti2);
EXPECT_FALSE(ti1 > ti2);
EXPECT_TRUE(ti1 <= ti1);
EXPECT_TRUE(ti1 >= ti1);
}
TEST(TimeInfo, TestDiffTime)
{
Base::TimeInfo ti1;
Base::TimeInfo ti2(ti1);
ti2 += std::chrono::seconds(1000);
EXPECT_FLOAT_EQ(Base::TimeInfo::diffTimeF(ti1, ti2), 1000.0);
}

159
tests/src/Base/Tools.cpp Normal file
View File

@@ -0,0 +1,159 @@
#include <gtest/gtest.h>
#include <Base/Tools.h>
#include <bitset>
#include <vector>
// NOLINTBEGIN(cppcoreguidelines-*,readability-*)
TEST(Tools, TestIota)
{
Base::iotaGen<int> iota(1);
std::vector<int> vec(5);
std::generate(vec.begin(), vec.end(), iota);
std::vector<int> out = {1, 2, 3, 4, 5};
EXPECT_EQ(vec, out);
}
TEST(Tools, TestClamp)
{
EXPECT_EQ(Base::clamp<int>(2, 1, 3), 2);
EXPECT_EQ(Base::clamp<int>(4, 1, 3), 3);
EXPECT_EQ(Base::clamp<int>(0, 1, 3), 1);
EXPECT_DOUBLE_EQ(Base::clamp<double>(2, 1.5, 3.1), 2.0);
EXPECT_DOUBLE_EQ(Base::clamp<double>(4, 1.5, 3.1), 3.1);
EXPECT_DOUBLE_EQ(Base::clamp<double>(0, 1.5, 3.1), 1.5);
}
TEST(Tools, TestSignum)
{
EXPECT_EQ(Base::sgn<int>(0), 0);
EXPECT_EQ(Base::sgn<int>(2), 1);
EXPECT_EQ(Base::sgn<int>(-2), -1);
EXPECT_DOUBLE_EQ(Base::sgn<double>(0.1), 1.0);
EXPECT_DOUBLE_EQ(Base::sgn<double>(2.0), 1.0);
EXPECT_DOUBLE_EQ(Base::sgn<double>(-2.0), -1.0);
EXPECT_DOUBLE_EQ(Base::sgn<double>(0.0), 0.0);
}
TEST(Tools, TestRadian)
{
EXPECT_EQ(Base::toRadians<int>(90), 1);
EXPECT_DOUBLE_EQ(Base::toRadians<double>(180), std::numbers::pi);
EXPECT_DOUBLE_EQ(Base::toRadians<double>(90.0), std::numbers::pi / 2.0);
EXPECT_DOUBLE_EQ(Base::toRadians<double>(0.0), 0.0);
}
TEST(Tools, TestDegree)
{
EXPECT_EQ(Base::toDegrees<int>(3), 171);
EXPECT_DOUBLE_EQ(Base::toDegrees<double>(std::numbers::pi), 180.0);
EXPECT_DOUBLE_EQ(Base::toDegrees<double>(std::numbers::pi / 2.0), 90.0);
EXPECT_DOUBLE_EQ(Base::toDegrees<double>(0.0), 0.0);
}
TEST(Tools, TestToggle)
{
bool value = true;
{
Base::FlagToggler<bool> toggle(value);
EXPECT_EQ(value, false);
}
EXPECT_EQ(value, true);
}
TEST(Tools, TestStateLocker)
{
bool value = true;
{
Base::StateLocker lock(value);
EXPECT_EQ(value, true);
}
EXPECT_EQ(value, true);
{
Base::StateLocker lock(value, false);
EXPECT_EQ(value, false);
}
EXPECT_EQ(value, true);
}
TEST(Tools, TestBitsetLocker)
{
std::bitset<8> value;
{
Base::BitsetLocker<decltype(value)> lock(value, 1);
EXPECT_EQ(value.test(1), true);
}
EXPECT_EQ(value.test(1), false);
{
Base::BitsetLocker<decltype(value)> lock(value, 2, false);
EXPECT_EQ(value.test(2), false);
}
EXPECT_EQ(value.test(2), false);
value.set(3, true);
{
Base::BitsetLocker<decltype(value)> lock(value, 3, false);
EXPECT_EQ(value.test(3), false);
}
EXPECT_EQ(value.test(3), true);
}
TEST(BaseToolsSuite, TestQuote)
{
EXPECT_EQ(Base::Tools::quoted("Test"), "\"Test\"");
}
TEST(BaseToolsSuite, TestJoinList)
{
EXPECT_EQ(Base::Tools::joinList({"AB", "CD"}), "AB, CD, ");
}
TEST(BaseToolsSuite, TestEscapeQuotesFromString)
{
EXPECT_EQ(Base::Tools::escapeQuotesFromString("\'"), "\\\'");
EXPECT_EQ(Base::Tools::escapeQuotesFromString("\""), "\\\"");
EXPECT_EQ(Base::Tools::escapeQuotesFromString("\\"), "\\");
}
TEST(BaseToolsSuite, TestGetIdentifier)
{
// ASCII and edge cases
EXPECT_EQ(Base::Tools::getIdentifier("valid"), "valid");
EXPECT_EQ(Base::Tools::getIdentifier("_valid"), "_valid");
EXPECT_EQ(Base::Tools::getIdentifier("1invalid"), "_1invalid");
EXPECT_EQ(Base::Tools::getIdentifier(""), "_");
// Unicode letters (valid start and continue)
EXPECT_EQ(Base::Tools::getIdentifier("πValue"), "πValue"); // Greek lowercase
EXPECT_EQ(Base::Tools::getIdentifier("Δx"), "Δx"); // Greek uppercase
EXPECT_EQ(Base::Tools::getIdentifier("Džz"), "Džz"); // Titlecase letter
EXPECT_EQ(Base::Tools::getIdentifier("ʰindex"), "ʰindex"); // Modifier letter
EXPECT_EQ(Base::Tools::getIdentifier("名字"), "名字"); // CJK characters (Lo)
EXPECT_EQ(Base::Tools::getIdentifier("ⅨCount"), "ⅨCount"); // Letter number (Nl)
// Digits not valid as first char
EXPECT_EQ(Base::Tools::getIdentifier("٢ndPlace"), "_٢ndPlace"); // Arabic-Indic digit (Nd)
// Connector punctuation
EXPECT_EQ(Base::Tools::getIdentifier("valid_name"), "valid_name");
EXPECT_EQ(Base::Tools::getIdentifier("valid‿name"), "valid‿name");
EXPECT_EQ(Base::Tools::getIdentifier("valid﹍name"), "valid﹍name");
// Combining marks (Mn, Mc)
EXPECT_EQ(Base::Tools::getIdentifier("éclair"), "éclair"); // 'e' + combining acute accent (Mn)
EXPECT_EQ(Base::Tools::getIdentifier("devा"), "devा"); // Devanagari vowel sign (Mc)
// Invalid symbols
EXPECT_EQ(Base::Tools::getIdentifier("hello!"), "hello_");
EXPECT_EQ(Base::Tools::getIdentifier("foo-bar"), "foo_bar");
EXPECT_EQ(Base::Tools::getIdentifier("a🙂b"), "a_b"); // Emoji replaced
EXPECT_EQ(Base::Tools::getIdentifier("a*b&c"), "a_b_c");
// Edge: starts with underscore, includes mixed types
EXPECT_EQ(Base::Tools::getIdentifier("_नमस्ते123"), "_नमस्ते123");
// Starts with invalid character
EXPECT_EQ(Base::Tools::getIdentifier("💡idea"), "_idea");
// Full-width digit (U+FF11, looks like '1')
EXPECT_EQ(Base::Tools::getIdentifier("1start"), "_1start");
}
// NOLINTEND(cppcoreguidelines-*,readability-*)

View File

@@ -0,0 +1,87 @@
#include <gtest/gtest.h>
#include <Base/Tools2D.h>
class Line2D: public ::testing::Test
{
protected:
Line2D()
: pt1(0.0, 0.0)
, pt2(3.0, 4.0)
{}
void SetUp() override
{}
void TearDown() override
{}
Base::Vector2d GetFirst() const
{
return pt1;
}
Base::Vector2d GetSecond() const
{
return pt2;
}
Base::Line2d GetLine() const
{
Base::Line2d line(pt1, pt2);
return line;
}
private:
Base::Vector2d pt1, pt2;
};
TEST_F(Line2D, TestLength)
{
Base::Line2d line(GetLine());
EXPECT_DOUBLE_EQ(line.Length(), 5.0);
}
TEST_F(Line2D, TestPoints)
{
Base::Line2d line(GetLine());
EXPECT_EQ(line.clV1, GetFirst());
EXPECT_EQ(line.clV2, GetSecond());
}
TEST_F(Line2D, TestFromPos)
{
Base::Line2d line(GetLine());
EXPECT_EQ(line.FromPos(2.5), Base::Vector2d(1.5, 2.0));
}
TEST_F(Line2D, TestContains)
{
Base::Line2d line(GetLine());
EXPECT_EQ(line.Contains(Base::Vector2d(1.5, 2.0)), true);
}
TEST(Polygon2D, TestDefault)
{
Base::Polygon2d poly;
EXPECT_EQ(poly.GetCtVectors(), 0);
}
TEST(Polygon2D, TestAdd)
{
Base::Polygon2d poly;
poly.Add(Base::Vector2d());
EXPECT_EQ(poly.GetCtVectors(), 1);
}
TEST(Polygon2D, TestRemove)
{
Base::Polygon2d poly;
poly.Add(Base::Vector2d());
EXPECT_EQ(poly.GetCtVectors(), 1);
EXPECT_EQ(poly.Delete(1), false);
EXPECT_EQ(poly.Delete(0), true);
EXPECT_EQ(poly.GetCtVectors(), 0);
}
TEST(Polygon2D, TestClear)
{
Base::Polygon2d poly;
poly.Add(Base::Vector2d());
poly.DeleteAll();
EXPECT_EQ(poly.GetCtVectors(), 0);
}

View File

@@ -0,0 +1,94 @@
#include <gtest/gtest.h>
#include <Base/Tools3D.h>
#include <Base/Vector3D.h>
class Line3D: public ::testing::Test
{
protected:
Line3D()
: pt1(0, 0, 0)
, pt2(3, 4, 0)
{}
void SetUp() override
{}
void TearDown() override
{}
Base::Vector3d GetFirst() const
{
return pt1;
}
Base::Vector3d GetSecond() const
{
return pt2;
}
Base::Line3d GetLine() const
{
Base::Line3d line(pt1, pt2);
return line;
}
private:
Base::Vector3d pt1, pt2;
};
TEST_F(Line3D, TestLength)
{
Base::Line3d line(GetLine());
EXPECT_DOUBLE_EQ(line.Length(), 5.0);
}
TEST_F(Line3D, TestSqrLength)
{
Base::Line3d line(GetLine());
EXPECT_DOUBLE_EQ(line.SqrLength(), 25.0);
}
TEST_F(Line3D, TestPoints)
{
Base::Line3d line(GetLine());
EXPECT_EQ(line.GetBase(), GetFirst());
EXPECT_EQ(line.GetDirection(), GetSecond());
}
TEST_F(Line3D, TestFromPos)
{
Base::Line3d line(GetLine());
EXPECT_EQ(line.FromPos(2.5), Base::Vector3d(1.5, 2, 0));
}
TEST_F(Line3D, TestContains)
{
Base::Line3d line(GetLine());
EXPECT_EQ(line.Contains(Base::Vector3d(1.5, 2, 0)), true);
}
TEST(Polygon3D, TestDefault)
{
Base::Polygon3d poly;
EXPECT_EQ(poly.GetSize(), 0);
}
TEST(Polygon3D, TestAdd)
{
Base::Polygon3d poly;
poly.Add(Base::Vector3d());
EXPECT_EQ(poly.GetSize(), 1);
}
TEST(Polygon3D, TestRemove)
{
Base::Polygon3d poly;
poly.Add(Base::Vector3d());
EXPECT_EQ(poly.GetSize(), 1);
EXPECT_EQ(poly.Remove(1), false);
EXPECT_EQ(poly.Remove(0), true);
EXPECT_EQ(poly.GetSize(), 0);
}
TEST(Polygon3D, TestClear)
{
Base::Polygon3d poly;
poly.Add(Base::Vector3d());
poly.Clear();
EXPECT_EQ(poly.GetSize(), 0);
}

View File

@@ -0,0 +1,125 @@
/***************************************************************************
* Copyright (c) 2024 Kevin Martin <kpmartin@papertrail.ca> *
* *
* 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 <string>
#include <Base/UniqueNameManager.h>
// NOLINTBEGIN(cppcoreguidelines-*,readability-*)
TEST(UniqueNameManager, NonconflictingBaseNameReturnsSameName)
{
// Check that a model name that is a base name that does not conflict with
// any existing name returns the base name
EXPECT_EQ(Base::UniqueNameManager().makeUniqueName("Body"), "Body");
}
TEST(UniqueNameManager, NonconflictingUniqueNameReturnsBaseName)
{
// Check that a model name that is a unique name whose base name does not conflict with
// any existing name returns the base name
EXPECT_EQ(Base::UniqueNameManager().makeUniqueName("Body123"), "Body");
}
TEST(UniqueNameManager, ManyDigitsInModelNameIgnored)
{
// Check that the number of digits in the model name does not affect the number
// of digits in the returned name.
Base::UniqueNameManager manager;
manager.addExactName("Body");
EXPECT_EQ(manager.makeUniqueName("Body12345", 3), "Body001");
}
TEST(UniqueNameManager, ConflictingBaseNameReturnsUniqueName)
{
// Check that a model name that conflicts with an existing name returns a unique form of
// the base name
Base::UniqueNameManager manager;
manager.addExactName("Body");
EXPECT_EQ(manager.makeUniqueName("Body", 1), "Body1");
}
TEST(UniqueNameManager, ConflictingUniqueNameReturnsNewUniqueName)
{
// Check that a given unique name already in the collection causes the return of
// a new unique name.
Base::UniqueNameManager manager;
manager.addExactName("Body");
manager.addExactName("Body001");
EXPECT_EQ(manager.makeUniqueName("Body001", 3), "Body002");
}
TEST(UniqueNameManager, VerifyUniqueDigitCount)
{
// Check that when a unique name is generated it contains at least the specified number
// of inserted digits
Base::UniqueNameManager manager;
manager.addExactName("Body");
EXPECT_EQ(manager.makeUniqueName("Body", 3), "Body001");
}
TEST(UniqueNameManager, UniqueNameLargerThanAnyName)
{
// Check that the name returned is larger (using digits) that any wxisting name
// even if the given model name is not itself in the collection
Base::UniqueNameManager manager;
manager.addExactName("Body001");
EXPECT_EQ(manager.makeUniqueName("Body", 3), "Body002");
}
TEST(UniqueNameManager, Issue18504)
{
// Check that the management of spans of assigned unique digit values is
// correct
std::string name;
Base::UniqueNameManager manager;
manager.addExactName("Origin007");
manager.addExactName("Origin");
manager.addExactName("Origin008");
manager.addExactName("Origin010");
manager.addExactName("Origin011");
manager.addExactName("Origin013");
manager.addExactName("Origin016");
name = manager.makeUniqueName("Origin", 3);
manager.addExactName(name);
name = manager.makeUniqueName("Origin", 3);
manager.addExactName(name);
name = manager.makeUniqueName("Origin", 3);
EXPECT_NE(name, "Origin010");
}
TEST(UniqueNameManager, UniqueNameWithManyDigits)
{
// Check that names with many digits (value larger than max unsigned long) work
Base::UniqueNameManager manager;
manager.addExactName("Compound006002002002002");
EXPECT_EQ(manager.makeUniqueName("Compound", 3), "Compound006002002002003");
}
TEST(UniqueNameManager, UniqueNameWith9NDigits)
{
// Check that names with a multiple of 9 digits work. The manager chunks nine digits at a time
// so this boundary condition needs a test.
Base::UniqueNameManager manager;
manager.addExactName("Compound123456789");
EXPECT_EQ(manager.makeUniqueName("Compound", 3), "Compound123456790");
}
// NOLINTEND(cppcoreguidelines-*,readability-*)

157
tests/src/Base/Unit.cpp Normal file
View File

@@ -0,0 +1,157 @@
#include "Base/Unit.h"
#include <gtest/gtest.h>
#include <Base/Exception.h>
// NOLINTBEGIN
using namespace Base;
TEST(Unit, string_simple_numerator_no_denominator)
{
EXPECT_EQ(Unit::Length.getString(), "mm");
}
TEST(Unit, string_complex_numerator_no_denominator)
{
EXPECT_EQ(Unit::Area.getString(), "mm^2");
}
TEST(Unit, string_complex_single_denominator)
{
EXPECT_EQ(Unit::DissipationRate.getString(), "mm^2/s^3");
}
TEST(Unit, string_no_numerator)
{
EXPECT_EQ(Unit::InverseArea.getString(), "1/mm^2");
}
TEST(Unit, string_complex_multi_denominator)
{
EXPECT_EQ(Unit::MagneticFlux.getString(), "mm^2*kg/(s^2*A)");
}
TEST(Unit, type_string)
{
EXPECT_EQ(Unit::MagneticFlux.getTypeString(), "MagneticFlux");
}
TEST(Unit, TestEqual)
{
EXPECT_TRUE(Unit::Length == Unit::Length);
}
TEST(Unit, TestNotEqual)
{
EXPECT_TRUE(Unit::Length != Unit::Area);
}
TEST(Unit, multiply_One_is_One)
{
EXPECT_EQ(Unit::One * Unit::One, Unit::One);
}
TEST(Unit, TestMult)
{
constexpr UnitExponents arr {1, 1, 0, 0, 0, 0, 0, 0};
EXPECT_EQ(Unit::Mass * Unit::Length, Unit {arr});
}
TEST(Unit, div)
{
EXPECT_EQ(Unit::Area / Unit::Length, Unit::Length);
}
TEST(Unit, div_by_One_does_nothing)
{
EXPECT_EQ(Unit::Area / Unit::One, Unit::Area);
}
TEST(Unit, pow_0_is_One)
{
EXPECT_EQ(Unit::Area.pow(0), Unit::One);
}
TEST(Unit, pow_1_leaves_unit_unchanged)
{
EXPECT_EQ(Unit::Area.pow(1), Unit::Area);
}
TEST(Unit, pow_2_is_squared)
{
EXPECT_EQ(Unit::Length.pow(2), Unit::Area);
}
TEST(Unit, pow_3_is_cubed)
{
EXPECT_EQ(Unit::Length.pow(3), Unit::Volume);
}
TEST(Unit, pow_less_than_one)
{
EXPECT_EQ(Unit::Volume.pow(1.0 / 3.0), Unit::Length);
}
TEST(Unit, one_still_one_after_pow)
{
EXPECT_EQ(Unit::One.pow(2), Unit::One);
}
TEST(Unit, square_root)
{
EXPECT_EQ(Unit::Area.root(2), Unit::Length);
}
TEST(Unit, cube_root)
{
EXPECT_EQ(Unit::Volume.root(3), Unit::Length);
}
TEST(Unit, zero_root)
{
EXPECT_THROW([[maybe_unused]] auto res = Unit::Area.root(0), UnitsMismatchError);
}
TEST(Unit, one_root)
{
EXPECT_EQ(Unit::Area.root(1), Unit::Area);
}
TEST(Unit, TestPow3div2)
{
EXPECT_THROW([[maybe_unused]] auto res = Unit::Volume.pow(3.0 / 2.0), UnitsMismatchError);
}
TEST(Unit, overflow)
{
constexpr UnitExponents arr {99, 0, 0, 0, 0, 0, 0, 0};
EXPECT_THROW([[maybe_unused]] auto res = Unit {arr}, OverflowError);
}
TEST(Unit, underflow)
{
constexpr UnitExponents arr {-99, 0, 0, 0, 0, 0, 0, 0};
EXPECT_THROW([[maybe_unused]] auto res = Unit {arr}, UnderflowError);
}
TEST(Unit, representation_simple)
{
const std::string expect {"Unit: mm (1,0,0,0,0,0,0,0) [Length]"};
const auto actual = Unit::Length.representation();
EXPECT_EQ(actual, expect);
}
TEST(Unit, representation_complex)
{
const std::string expect {"Unit: mm^2*kg/(s^2*A) (2,1,-2,-1,0,0,0,0) [MagneticFlux]"};
const auto actual = Unit::MagneticFlux.representation();
EXPECT_EQ(actual, expect);
}
TEST(Unit, representation_no_name)
{
constexpr Unit unit {{1, 1}};
const std::string expect {"Unit: mm*kg (1,1,0,0,0,0,0,0)"};
const auto actual = unit.representation();
EXPECT_EQ(actual, expect);
}
// NOLINTEND

View File

@@ -0,0 +1,59 @@
/***************************************************************************
* Copyright (c) 2025 Kevin Martin <kpmartin@papertrail.ca> *
* *
* 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 <string>
#include <Base/UnlimitedUnsigned.h>
// NOLINTBEGIN(cppcoreguidelines-*,readability-*)
TEST(UnlimitedUnsigned, Basics)
{
// Check simple addition with carry and conversion from string
Base::UnlimitedUnsigned one(1);
auto nines = Base::UnlimitedUnsigned::fromString("999999999");
EXPECT_EQ(nines + one, Base::UnlimitedUnsigned::fromString("1000000000"));
}
TEST(UnlimitedUnsigned, ToString)
{
// Check toString on simple addition result
Base::UnlimitedUnsigned one(1);
auto nines = Base::UnlimitedUnsigned::fromString("999999999");
EXPECT_EQ((nines + one).toString(), "1000000000");
}
TEST(UnlimitedUnsigned, TestSubtraction1)
{
// Check subtraction and comparison with byte-sized number
EXPECT_EQ(
Base::UnlimitedUnsigned::fromString("6842357951")
- Base::UnlimitedUnsigned::fromString("6842357948"),
3
);
}
TEST(UnlimitedUnsigned, TestSubtraction2)
{
// Check subtraction and comparison
EXPECT_EQ(
Base::UnlimitedUnsigned::fromString("6842357951")
- Base::UnlimitedUnsigned::fromString("6000000000"),
Base::UnlimitedUnsigned::fromString("842357951")
);
}
// NOLINTEND(cppcoreguidelines-*,readability-*)

332
tests/src/Base/Vector3D.cpp Normal file
View File

@@ -0,0 +1,332 @@
#include <gtest/gtest.h>
#include <Base/Vector3D.h>
// NOLINTBEGIN
TEST(Vector, TestDefault)
{
Base::Vector3d vec;
EXPECT_EQ(vec.x, 0.0);
EXPECT_EQ(vec.y, 0.0);
EXPECT_EQ(vec.z, 0.0);
}
TEST(Vector, TestDefault2)
{
Base::Vector3d vec(1.0, 2.0, 3.0);
EXPECT_EQ(vec.x, 1.0);
EXPECT_EQ(vec.y, 2.0);
EXPECT_EQ(vec.z, 3.0);
}
TEST(Vector, TestCopy)
{
Base::Vector3d vec(1.0, 2.0, 3.0);
Base::Vector3d copy(vec);
EXPECT_EQ(copy.x, 1.0);
EXPECT_EQ(copy.y, 2.0);
EXPECT_EQ(copy.z, 3.0);
}
TEST(Vector, TestMove)
{
Base::Vector3d vec(1.0, 2.0, 3.0);
Base::Vector3d copy(std::move(vec));
EXPECT_EQ(copy.x, 1.0);
EXPECT_EQ(copy.y, 2.0);
EXPECT_EQ(copy.z, 3.0);
}
TEST(Vector, TestNull)
{
Base::Vector3d vec(1.0, 2.0, 3.0);
EXPECT_EQ(vec.IsNull(), false);
EXPECT_EQ(Base::Vector3d().IsNull(), true);
}
TEST(Vector, TestEqual)
{
Base::Vector3d vec(1.0, 2.0, 3.0);
EXPECT_EQ(vec.IsEqual(vec, 0), true);
EXPECT_EQ(Base::Vector3d().IsEqual(vec, 0), false);
}
TEST(Vector, TestIndex)
{
Base::Vector3d vec(1.0, 2.0, 3.0);
EXPECT_EQ(vec[0], 1.0);
EXPECT_EQ(vec[1], 2.0);
EXPECT_EQ(vec[2], 3.0);
vec[0] = 4.0;
EXPECT_EQ(vec[0], 4.0);
}
TEST(Vector, TestPlus)
{
Base::Vector3d vec = Base::Vector3d(1, 2, 3) + Base::Vector3d(4, 3, 1);
EXPECT_EQ(vec.x, 5.0);
EXPECT_EQ(vec.y, 5.0);
EXPECT_EQ(vec.z, 4.0);
}
TEST(Vector, TestPlusAssign)
{
Base::Vector3d vec(1, 2, 3);
vec += Base::Vector3d(4, 3, 1);
EXPECT_EQ(vec.x, 5.0);
EXPECT_EQ(vec.y, 5.0);
EXPECT_EQ(vec.z, 4.0);
}
TEST(Vector, TestMinus)
{
Base::Vector3d vec = Base::Vector3d(1, 2, 3) - Base::Vector3d(4, 3, 1);
EXPECT_EQ(vec.x, -3.0);
EXPECT_EQ(vec.y, -1.0);
EXPECT_EQ(vec.z, 2.0);
}
TEST(Vector, TestMinusAssign)
{
Base::Vector3d vec(1, 2, 3);
vec -= Base::Vector3d(4, 3, 1);
EXPECT_EQ(vec.x, -3.0);
EXPECT_EQ(vec.y, -1.0);
EXPECT_EQ(vec.z, 2.0);
}
TEST(Vector, TestNegative)
{
Base::Vector3d vec = -Base::Vector3d(4, 3, 1);
EXPECT_EQ(vec.x, -4.0);
EXPECT_EQ(vec.y, -3.0);
EXPECT_EQ(vec.z, -1.0);
}
TEST(Vector, TestScale)
{
Base::Vector3d vec(1, 2, 3);
vec = vec * 2.0;
EXPECT_EQ(vec.x, 2.0);
EXPECT_EQ(vec.y, 4.0);
EXPECT_EQ(vec.z, 6.0);
}
TEST(Vector, TestScaleAssign)
{
Base::Vector3d vec(1, 2, 3);
vec *= 2.0;
EXPECT_EQ(vec.x, 2.0);
EXPECT_EQ(vec.y, 4.0);
EXPECT_EQ(vec.z, 6.0);
}
TEST(Vector, TestDivScale)
{
Base::Vector3d vec(1, 2, 3);
vec = vec / 2.0;
EXPECT_EQ(vec.x, 0.5);
EXPECT_EQ(vec.y, 1.0);
EXPECT_EQ(vec.z, 1.5);
}
TEST(Vector, TestDivScaleAssign)
{
Base::Vector3d vec(1, 2, 3);
vec /= 2.0;
EXPECT_EQ(vec.x, 0.5);
EXPECT_EQ(vec.y, 1.0);
EXPECT_EQ(vec.z, 1.5);
}
TEST(Vector, TestScaleXYZ)
{
Base::Vector3d vec(1, 2, 3);
vec.Scale(1, 2, 3);
EXPECT_EQ(vec.x, 1.0);
EXPECT_EQ(vec.y, 4.0);
EXPECT_EQ(vec.z, 9.0);
}
TEST(Vector, TestMoveXYZ)
{
Base::Vector3d vec(1, 2, 3);
vec.Move(1, 2, 3);
EXPECT_EQ(vec.x, 2.0);
EXPECT_EQ(vec.y, 4.0);
EXPECT_EQ(vec.z, 6.0);
}
TEST(Vector, TestCopyAssign)
{
Base::Vector3d vec;
Base::Vector3d copy(1, 2, 3);
vec = copy;
EXPECT_EQ(vec.x, 1.0);
EXPECT_EQ(vec.y, 2.0);
EXPECT_EQ(vec.z, 3.0);
}
TEST(Vector, TestMoveAssign)
{
Base::Vector3d vec;
Base::Vector3d copy(1, 2, 3);
vec = std::move(copy);
EXPECT_EQ(vec.x, 1.0);
EXPECT_EQ(vec.y, 2.0);
EXPECT_EQ(vec.z, 3.0);
}
TEST(Vector, TestScalar)
{
Base::Vector3d vec1(1, 2, 3);
Base::Vector3d vec2(3, 2, 1);
double dot1 = vec1 * vec2;
double dot2 = vec2.Dot(vec1);
EXPECT_EQ(dot1, 10.0);
EXPECT_EQ(dot2, 10.0);
}
TEST(Vector, TestCross)
{
Base::Vector3d vec1(1, 2, 3);
Base::Vector3d vec2(3, 2, 1);
Base::Vector3d cross1 = vec1 % vec2;
Base::Vector3d cross2 = vec2.Cross(vec1);
EXPECT_EQ(cross1.x, -4.0);
EXPECT_EQ(cross1.y, 8.0);
EXPECT_EQ(cross1.z, -4.0);
EXPECT_EQ(cross2.x, 4.0);
EXPECT_EQ(cross2.y, -8.0);
EXPECT_EQ(cross2.z, 4.0);
}
TEST(Vector, TestCompare)
{
Base::Vector3d vec1(1, 2, 3);
Base::Vector3d vec2(1, 2, 1);
EXPECT_EQ(vec1 == vec2, false);
EXPECT_EQ(vec1 != vec2, true);
}
TEST(Vector, TestNormalize)
{
Base::Vector3d vec(1, 2, 3);
vec.Normalize();
EXPECT_EQ(vec.Length(), 1.0);
}
TEST(Vector, TestCSTransform)
{
Base::Vector3d vec(1, 2, 3);
vec.TransformToCoordinateSystem(
Base::Vector3d(1, 1, 1),
Base::Vector3d(0, 1, 0),
Base::Vector3d(1, 0, 0)
);
EXPECT_EQ(vec.x, 1);
EXPECT_EQ(vec.y, 0);
EXPECT_EQ(vec.z, -2);
}
TEST(Vector, TestLineSegment)
{
Base::Vector3d vec(1, 2, 3);
EXPECT_EQ(vec.IsOnLineSegment(Base::Vector3d(), Base::Vector3d(2, 4, 6)), true);
}
TEST(Vector, TestDistanceLineSegment)
{
Base::Vector3d vec(1, 2, 3);
EXPECT_EQ(vec.DistanceToLineSegment(Base::Vector3d(), Base::Vector3d(2, 4, 6)).Length(), 0.0);
}
TEST(Vector, TestProjectToPlane)
{
Base::Vector3d vec(1, 2, 3);
Base::Vector3d proj;
vec.ProjectToPlane(Base::Vector3d(1, 1, 1), Base::Vector3d(0, 0, 1), proj);
EXPECT_EQ(proj.x, 1);
EXPECT_EQ(proj.y, 2);
EXPECT_EQ(proj.z, 1);
}
TEST(Vector, TestDistanceToPlane)
{
Base::Vector3d vec(1, 2, 3);
double dist = vec.DistanceToPlane(Base::Vector3d(1, 1, 1), Base::Vector3d(0, 0, 1));
EXPECT_EQ(dist, 2);
}
TEST(Vector, TestAngle)
{
Base::Vector3d vec1(0, 0, 0.000001);
Base::Vector3d vec2(0, 0.000001, 0);
double angle = vec1.GetAngle(vec2);
EXPECT_EQ(angle, Base::float_traits<double>::pi() / 2);
}
TEST(Vector, TestIsNormal)
{
Base::Vector3d vec(1, 2, 3);
EXPECT_FALSE(vec.IsNormal(Base::Vector3d(1, 1, 1), 0.0));
EXPECT_FALSE(vec.IsNormal(Base::Vector3d(1, 2, 3), 0.0));
EXPECT_TRUE(vec.IsNormal(Base::Vector3d(3, 0, -1), 0.0));
}
TEST(Vector, TestIsNormalNullVector)
{
Base::Vector3d vec(1, 2, 3);
EXPECT_FALSE(vec.IsNormal(Base::Vector3d(0, 0, 0), 0.0));
}
TEST(Vector, TestIsNormalLongVectors)
{
Base::Vector3d vec(10000, 20000, 30000);
EXPECT_TRUE(vec.IsNormal(Base::Vector3d(30000, 0, -10001), 0.02));
}
TEST(Vector, TestIsNormalShortVectors)
{
Base::Vector3d vec(0.01, 0.02, 0.03);
EXPECT_FALSE(vec.IsNormal(Base::Vector3d(0.03, 0, -0.02), 0.02));
}
TEST(Vector, TestIsParallel)
{
Base::Vector3d vec(1, 2, 3);
EXPECT_FALSE(vec.IsParallel(Base::Vector3d(1, 1, 1), 0.0));
EXPECT_TRUE(vec.IsParallel(Base::Vector3d(1, 2, 3), 0.0));
EXPECT_TRUE(vec.IsParallel(Base::Vector3d(-1, -2, -3), 0.0));
EXPECT_FALSE(vec.IsParallel(Base::Vector3d(3, 0, -1), 0.0));
}
TEST(Vector, TestIsParallelNullVector)
{
Base::Vector3d vec(1, 2, 3);
EXPECT_FALSE(vec.IsParallel(Base::Vector3d(0, 0, 0), 0.0));
}
TEST(Vector, TestIsParallelLongVectors)
{
Base::Vector3d vec(10000, 20000, 30000);
EXPECT_TRUE(vec.IsParallel(Base::Vector3d(10000, 20000, 30001), 0.02));
}
TEST(Vector, TestIsParallelShortVectors)
{
Base::Vector3d vec(0.01, 0.02, 0.03);
EXPECT_FALSE(vec.IsParallel(Base::Vector3d(0.01, 0.02, 0.04), 0.02));
}
TEST(Vector, TestAngleOriented)
{
Base::Vector3d vec1(0.000001, 0, 0);
Base::Vector3d vec2(0, 0.000001, 0);
Base::Vector3d norm(0, 0, 0.000001);
double angle = vec1.GetAngleOriented(vec2, norm);
EXPECT_EQ(angle, Base::float_traits<double>::pi() * 0.5);
angle = vec2.GetAngleOriented(vec1, norm);
EXPECT_EQ(angle, Base::float_traits<double>::pi() * 1.5);
}
// NOLINTEND

View File

@@ -0,0 +1,23 @@
#include <gtest/gtest.h>
#include <Base/Placement.h>
#include <Base/ViewProj.h>
TEST(ViewProj, TestViewProjMatrix)
{
Base::Matrix4D mat;
Base::ViewProjMatrix proj(mat);
Base::Vector3d vec(1, 2, 3);
EXPECT_EQ(proj(vec), Base::Vector3d(1, 1.5, 2));
EXPECT_EQ(proj.inverse(Base::Vector3d(1, 1.5, 2)), vec);
}
TEST(ViewProj, TestViewOrthoProjMatrix)
{
Base::Matrix4D mat;
Base::ViewOrthoProjMatrix proj(mat);
Base::Vector3d vec(1, 2, 3);
EXPECT_EQ(proj(vec), vec);
EXPECT_EQ(proj.inverse(vec), vec);
}

131
tests/src/Base/Writer.cpp Normal file
View File

@@ -0,0 +1,131 @@
// SPDX-License-Identifier: LGPL-2.1-or-later
#include <gtest/gtest.h>
#include "Base/Exception.h"
#include "Base/Writer.h"
// Writer is designed to be a base class, so for testing we actually instantiate a StringWriter,
// which is derived from it
class WriterTest: public ::testing::Test
{
protected:
// void SetUp() override {}
// void TearDown() override {}
protected:
Base::StringWriter _writer;
};
TEST_F(WriterTest, insertTextSimple)
{
// Arrange
std::string testTextData {"Simple ASCII data"};
std::string expectedResult {"<![CDATA[" + testTextData + "]]>"};
// Act
_writer.insertText(testTextData);
// Assert
EXPECT_EQ(expectedResult, _writer.getString());
}
/// If the data happens to actually include an XML CDATA close marker, that needs to be "escaped" --
/// this is done by breaking it up into two separate CDATA sections, splitting apart the marker.
TEST_F(WriterTest, insertTextNeedsEscape)
{
// Arrange
std::string testDataA {"ASCII data with a close marker in it, like so: ]]"};
std::string testDataB {"> "};
std::string expectedResult {"<![CDATA[" + testDataA + "]]><![CDATA[" + testDataB + "]]>"};
// Act
_writer.insertText(testDataA + testDataB);
// Assert
EXPECT_EQ(expectedResult, _writer.getString());
}
TEST_F(WriterTest, insertNonAsciiData)
{
// Arrange
std::string testData {"\x01\x02\x03\x04\u0001F450😀"};
std::string expectedResult {"<![CDATA[" + testData + "]]>"};
// Act
_writer.insertText(testData);
// Assert
EXPECT_EQ(expectedResult, _writer.getString());
}
TEST_F(WriterTest, beginCharStream)
{
// Arrange & Act
auto& checkStream {_writer.beginCharStream()};
// Assert
EXPECT_TRUE(checkStream.good());
}
TEST_F(WriterTest, beginCharStreamTwice)
{
// Arrange
_writer.beginCharStream();
// Act & Assert
EXPECT_THROW(_writer.beginCharStream(), Base::RuntimeError);
}
TEST_F(WriterTest, endCharStream)
{
// Arrange
_writer.beginCharStream();
// Act
_writer.endCharStream();
// Assert
EXPECT_EQ("<![CDATA[]]>", _writer.getString());
}
TEST_F(WriterTest, endCharStreamTwice)
{
// Arrange
_writer.beginCharStream();
_writer.endCharStream();
// Act
_writer.endCharStream(); // Doesn't throw, or do anything at all
// Assert
EXPECT_EQ("<![CDATA[]]>", _writer.getString());
}
TEST_F(WriterTest, charStream)
{
// Arrange
auto& streamA {_writer.beginCharStream()};
// Act
auto& streamB {_writer.charStream()};
// Assert
EXPECT_EQ(&streamA, &streamB);
}
TEST_F(WriterTest, charStreamBase64Encoded)
{
// Arrange
_writer.beginCharStream(Base::CharStreamFormat::Base64Encoded);
std::string data {"FreeCAD rocks! 🪨🪨🪨"};
// Act
_writer.charStream() << data;
_writer.endCharStream();
// Assert
// Conversion done using https://www.base64encode.org for testing purposes
EXPECT_EQ(std::string("RnJlZUNBRCByb2NrcyEg8J+qqPCfqqjwn6qo\n"), _writer.getString());
}

View File

@@ -0,0 +1,79 @@
// SPDX-License-Identifier: LGPL-2.1-or-later
#include <gtest/gtest.h>
#include <Base/XMLTools.h>
class TestXMLTools: public testing::Test
{
};
TEST_F(TestXMLTools, EscapeXmlEmptyString)
{
EXPECT_EQ(XMLTools::escapeXml(""), "");
}
TEST_F(TestXMLTools, EscapeXmlNoChangesForSafeText)
{
EXPECT_EQ(XMLTools::escapeXml("abcXYZ_123"), "abcXYZ_123");
EXPECT_EQ(XMLTools::escapeXml("hello world"), "hello world");
EXPECT_EQ(XMLTools::escapeXml("line1\nline2\tend"), "line1\nline2\tend");
}
TEST_F(TestXMLTools, EscapeXmlEscapesAmpersand)
{
EXPECT_EQ(XMLTools::escapeXml("&"), "&amp;");
EXPECT_EQ(XMLTools::escapeXml("a&b"), "a&amp;b");
}
TEST_F(TestXMLTools, EscapeXmlEscapesLessThanAndGreaterThan)
{
EXPECT_EQ(XMLTools::escapeXml("<"), "&lt;");
EXPECT_EQ(XMLTools::escapeXml(">"), "&gt;");
EXPECT_EQ(XMLTools::escapeXml("a<b"), "a&lt;b");
EXPECT_EQ(XMLTools::escapeXml("a>b"), "a&gt;b");
EXPECT_EQ(XMLTools::escapeXml("a<b>c"), "a&lt;b&gt;c");
}
TEST_F(TestXMLTools, EscapeXmlEscapesQuotes)
{
EXPECT_EQ(XMLTools::escapeXml("\""), "&quot;");
EXPECT_EQ(XMLTools::escapeXml("'"), "&apos;");
EXPECT_EQ(XMLTools::escapeXml("a\"b"), "a&quot;b");
EXPECT_EQ(XMLTools::escapeXml("a'b"), "a&apos;b");
}
TEST_F(TestXMLTools, EscapeXmlEscapesAllFiveInOneString)
{
// input: & < > " '
EXPECT_EQ(XMLTools::escapeXml("&<>\"'"), "&amp;&lt;&gt;&quot;&apos;");
}
TEST_F(TestXMLTools, EscapeXmlDoesNotDoubleEscapeNewlyInsertedEntities)
{
// This test specifically catches the classic bug where you replace
// '<' with "&lt;" and then later replace '&' with "&amp;" and end up with "&amp;lt;".
EXPECT_EQ(XMLTools::escapeXml("<"), "&lt;");
EXPECT_EQ(XMLTools::escapeXml(">"), "&gt;");
EXPECT_EQ(XMLTools::escapeXml("\""), "&quot;");
EXPECT_EQ(XMLTools::escapeXml("'"), "&apos;");
}
TEST_F(TestXMLTools, EscapeXmlComplexMixedContent)
{
const std::string in = "Tom & Jerry <\"fun\"> 'n' games";
const std::string out = "Tom &amp; Jerry &lt;&quot;fun&quot;&gt; &apos;n&apos; games";
EXPECT_EQ(XMLTools::escapeXml(in), out);
}
TEST_F(TestXMLTools, EscapeXmlMultipleAdjacentCharacters)
{
EXPECT_EQ(XMLTools::escapeXml("&&&&"), "&amp;&amp;&amp;&amp;");
EXPECT_EQ(XMLTools::escapeXml("<<<<"), "&lt;&lt;&lt;&lt;");
EXPECT_EQ(XMLTools::escapeXml("\"\"''"), "&quot;&quot;&apos;&apos;");
}
TEST_F(TestXMLTools, EscapeXmlPreservesWhitespaceAndControlCommonInText)
{
EXPECT_EQ(XMLTools::escapeXml(" a \r\n b \t c "), " a \r\n b \t c ");
}

8
tests/src/CMakeLists.txt Normal file
View File

@@ -0,0 +1,8 @@
# SPDX-License-Identifier: LGPL-2.1-or-later
add_subdirectory(Base)
add_subdirectory(App)
add_subdirectory(Gui)
add_subdirectory(Misc)
add_subdirectory(Mod)
add_subdirectory(zipios++)

View File

@@ -0,0 +1,20 @@
// SPDX-License-Identifier: LGPL-2.1-or-later
#include <gtest/gtest.h>
#include "Gui/Assistant.h"
#include <src/App/InitApplication.h>
class Assistant: public ::testing::Test
{
protected:
static void SetUpTestSuite()
{
tests::initApplication();
}
};
TEST_F(Assistant, first)
{}

View File

@@ -0,0 +1,25 @@
# SPDX-License-Identifier: LGPL-2.1-or-later
add_subdirectory(Dialogs)
add_subdirectory(propertyeditor)
# Standard C++ GTest tests
add_executable(Gui_tests_run
Assistant.cpp
Camera.cpp
StyleParameters/StyleParametersApplicationTest.cpp
StyleParameters/ParserTest.cpp
StyleParameters/ParameterManagerTest.cpp
InputHintTest.cpp
)
# Qt tests
setup_qt_test(QuantitySpinBox)
target_link_libraries(Gui_tests_run PRIVATE
GTest::gtest_main
GTest::gmock_main
${Google_Tests_LIBS}
FreeCADApp
FreeCADGui
)

239
tests/src/Gui/Camera.cpp Normal file
View File

@@ -0,0 +1,239 @@
// SPDX-License-Identifier: LGPL-2.1-or-later
#include <gtest/gtest.h>
#include <array>
#include <cmath>
#include <Inventor/SbMatrix.h>
#include <Inventor/SbRotation.h>
#include <Inventor/SbViewVolume.h>
#include <Base/Converter.h>
#include <Base/Tools.h>
#include <Gui/Camera.h>
#include <Gui/Utilities.h>
#include <src/App/InitApplication.h>
/*
This comment was previously used to get the hard coded axonometric view quaternions
in the Camera class.
This has since been replaced with unit tests that verify the correctness of the
quaternion calculations.
The old code is kept for reference and to show how the quaternions were calculated.
---
Formulas to get quaternion for axonometric views:
\code
from math import sqrt, degrees, asin, atan
p1=App.Rotation(App.Vector(1,0,0),90)
p2=App.Rotation(App.Vector(0,0,1),alpha)
p3=App.Rotation(p2.multVec(App.Vector(1,0,0)),beta)
p4=p3.multiply(p2).multiply(p1)
from pivy import coin
c=Gui.ActiveDocument.ActiveView.getCameraNode()
c.orientation.setValue(*p4.Q)
\endcode
The angles alpha and beta depend on the type of axonometry
Isometric:
\code
alpha=45
beta=degrees(asin(-sqrt(1.0/3.0)))
\endcode
Dimetric:
\code
alpha=degrees(asin(sqrt(1.0/8.0)))
beta=degrees(-asin(1.0/3.0))
\endcode
Trimetric:
\code
alpha=30.0
beta=-35.0
\endcode
Verification code that the axonomtries are correct:
\code
from pivy import coin
c=Gui.ActiveDocument.ActiveView.getCameraNode()
vo=App.Vector(c.getViewVolume().getMatrix().multVecMatrix(coin.SbVec3f(0,0,0)).getValue())
vx=App.Vector(c.getViewVolume().getMatrix().multVecMatrix(coin.SbVec3f(10,0,0)).getValue())
vy=App.Vector(c.getViewVolume().getMatrix().multVecMatrix(coin.SbVec3f(0,10,0)).getValue())
vz=App.Vector(c.getViewVolume().getMatrix().multVecMatrix(coin.SbVec3f(0,0,10)).getValue())
(vx-vo).Length
(vy-vo).Length
(vz-vo).Length
# Projection
vo.z=0
vx.z=0
vy.z=0
vz.z=0
(vx-vo).Length
(vy-vo).Length
(vz-vo).Length
\endcode
See also:
http://www.mathematik.uni-marburg.de/~thormae/lectures/graphics1/graphics_6_2_ger_web.html#1
http://www.mathematik.uni-marburg.de/~thormae/lectures/graphics1/code_v2/Axonometric/qt/Axonometric.cpp
https://de.wikipedia.org/wiki/Arkussinus_und_Arkuskosinus
*/
using Base::convertTo;
using Base::Rotation;
using Base::toRadians;
using Base::Vector3d;
namespace
{
Rotation buildAxonometricRotation(double alphaRad, double betaRad)
{
const auto p1 = Rotation(Vector3d::UnitX, toRadians<float>(90.0));
const auto p2 = Rotation(Vector3d::UnitZ, alphaRad);
const auto p3 = Rotation(p2.multVec(Vector3d::UnitX), betaRad);
const auto p4 = p3 * p2 * p1;
return p4;
}
// Returns a tuple of 2D lengths of X, Y, Z unit vectors after applying rotation
std::array<double, 3> getProjectedLengths(const SbRotation& rot)
{
// Set up a simple view volume to test the projection of the unit vectors.
// The actual values don't matter much, as we are only interested in the
// relative lengths of the projected vectors.
SbViewVolume volume;
// left, right, bottom, top, near, far
volume.ortho(-10, 10, -10, 10, -10, 10);
volume.rotateCamera(rot);
const auto matrix = volume.getMatrix();
// Get the transformed unit vectors
SbVec3f vo, vx, vy, vz;
matrix.multVecMatrix(SbVec3f(0, 0, 0), vo);
matrix.multVecMatrix(SbVec3f(10, 0, 0), vx);
matrix.multVecMatrix(SbVec3f(0, 10, 0), vy);
matrix.multVecMatrix(SbVec3f(0, 0, 10), vz);
// Project to XY plane by setting Z to 0
vo[2] = 0;
vx[2] = 0;
vy[2] = 0;
vz[2] = 0;
// Return the lengths of the projected vectors
return {(vx - vo).length(), (vy - vo).length(), (vz - vo).length()};
}
} // namespace
class CameraPrecalculatedQuaternions: public ::testing::Test
{
protected:
static void SetUpTestSuite()
{
tests::initApplication();
}
};
TEST_F(CameraPrecalculatedQuaternions, testIsometric)
{
// Use the formula to get the isometric rotation
double alpha = toRadians(45.0f);
double beta = std::asin(-std::sqrt(1.0 / 3.0));
const Rotation actual = buildAxonometricRotation(alpha, beta);
const Rotation expected = convertTo<Rotation>(Gui::Camera::isometric());
EXPECT_TRUE(actual.isSame(expected, 1e-6));
}
TEST_F(CameraPrecalculatedQuaternions, testDimetric)
{
// Use the formula to get the dimetric rotation
double alpha = std::asin(std::sqrt(1.0 / 8.0));
double beta = -std::asin(1.0 / 3.0);
const Rotation actual = buildAxonometricRotation(alpha, beta);
const Rotation expected = convertTo<Rotation>(Gui::Camera::dimetric());
EXPECT_TRUE(actual.isSame(expected, 1e-6));
}
TEST_F(CameraPrecalculatedQuaternions, testTrimetric)
{
// Use the formula to get the trimetric rotation
double alpha = toRadians(30.0);
double beta = toRadians(-35.0);
const Rotation actual = buildAxonometricRotation(alpha, beta);
const Rotation expected = convertTo<Rotation>(Gui::Camera::trimetric());
EXPECT_TRUE(actual.isSame(expected, 1e-6));
}
class CameraRotation: public ::testing::Test
{
protected:
static void SetUpTestSuite()
{
tests::initApplication();
}
};
TEST_F(CameraRotation, testIsometricProjection)
{
auto rot = Gui::Camera::isometric();
auto lengths = getProjectedLengths(rot);
// In isometric, expect all lengths to be roughly equal
EXPECT_NEAR(lengths[0], lengths[1], 1e-6); // X == Y
EXPECT_NEAR(lengths[0], lengths[2], 1e-6); // X == Z
EXPECT_NEAR(lengths[1], lengths[2], 1e-6); // Y == Z
}
TEST_F(CameraRotation, testDimetricProjection)
{
const auto rot = Gui::Camera::dimetric();
const auto lengths = getProjectedLengths(rot);
// In dimetric, expect two lengths to be roughly equal, one different
const std::initializer_list<std::pair<double, double>> pairs = {
{lengths[0], lengths[1]},
{lengths[1], lengths[2]},
{lengths[0], lengths[2]},
};
constexpr double tolerance = 1e-6;
const auto isSimilar = [&](std::pair<double, double> lengths) -> bool {
return std::abs(lengths.first - lengths.second) < tolerance;
};
unsigned similarCount = std::ranges::count_if(pairs, isSimilar);
EXPECT_EQ(similarCount, 1); // Exactly two are equal
}
TEST_F(CameraRotation, testTrimetricProjection)
{
auto rot = Gui::Camera::trimetric();
auto lengths = getProjectedLengths(rot);
// In trimetric, all should differ significantly
EXPECT_GT(std::abs(lengths[0] - lengths[1]), 1e-3);
EXPECT_GT(std::abs(lengths[1] - lengths[2]), 1e-3);
EXPECT_GT(std::abs(lengths[0] - lengths[2]), 1e-3);
}

View File

@@ -0,0 +1 @@
setup_qt_test(DlgVersionMigrator)

View File

@@ -0,0 +1,265 @@
// SPDX-License-Identifier: LGPL-2.1-or-later
// SPDX-FileNotice: Part of the FreeCAD project.
/******************************************************************************
* *
* © 2026 The FreeCAD Project Association AISBL *
* *
* 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 <QDebug>
#include <QTest>
#include <fstream>
#include <iostream>
#include <App/Application.h>
#include "Gui/Dialogs/DlgVersionMigrator.h"
#include "App/ApplicationDirectories.h"
#include <src/App/InitApplication.h>
class TestablePathMigrationWorker: public Gui::Dialog::PathMigrationWorker
{
using Gui::Dialog::PathMigrationWorker::PathMigrationWorker;
public:
TestablePathMigrationWorker(std::string userConfigDir, std::string userAppDir, int major, int minor)
: PathMigrationWorker(userConfigDir, userAppDir, major, minor)
, testConfigDir(userConfigDir)
, testUserAppDir(userAppDir) {};
void testableReplaceOccurrencesInPreferences()
{
replaceOccurrencesInPreferences();
}
std::filesystem::path testableLocateNewPreferences()
{
return locateNewPreferences();
}
std::string testableGenerateNewUserAppPathString(const std::string& oldPath)
{
return generateNewUserAppPathString(oldPath);
}
static void testableReplaceInContents(
std::string& contents,
const std::string& oldString,
const std::string& newString
)
{
replaceInContents(contents, oldString, newString);
}
std::string getConfigDir()
{
return testConfigDir;
}
std::string getUserAppDir()
{
return testUserAppDir;
}
private:
std::string testConfigDir;
std::string testUserAppDir;
};
class testPathMigrationWorker final: public QObject
{
Q_OBJECT
public:
testPathMigrationWorker()
{
tests::initApplication();
}
private Q_SLOTS:
void init() // NOLINT
{}
void cleanup() // NOLINT
{}
void replaceInContents_data() // NOLINT
{
QTest::addColumn<QString>("contents");
QTest::addColumn<QString>("oldString");
QTest::addColumn<QString>("newString");
QTest::addColumn<QString>("expected");
// No-op / no matches
QTest::newRow("empty-contents") << "" << "a" << "b" << "";
QTest::newRow("no-match") << "abcdef" << "x" << "y" << "abcdef";
// Single match
QTest::newRow("single-match-middle") << "abcXYZdef" << "XYZ" << "Q" << "abcQdef";
QTest::newRow("single-match-begin") << "XYZdef" << "XYZ" << "Q" << "Qdef";
QTest::newRow("single-match-end") << "abcXYZ" << "XYZ" << "Q" << "abcQ";
// Multiple matches
QTest::newRow("multiple-separated") << "a1a2a3" << "a" << "b" << "b1b2b3";
QTest::newRow("multiple-words") << "foo bar foo" << "foo" << "x" << "x bar x";
// Adjacent / overlapping-looking cases (should replace non-overlapping occurrences)
QTest::newRow("adjacent") << "aaaa" << "aa" << "b" << "bb"; // "aa" + "aa"
QTest::newRow("pattern-repeats") << "ababab" << "ab" << "x" << "xxx";
// oldString longer/shorter than newString
QTest::newRow("shorten") << "abc123abc" << "abc" << "a" << "a123a";
QTest::newRow("expand") << "a-b-a-b" << "a" << "LONG" << "LONG-b-LONG-b";
// oldString == newString
QTest::newRow("old-equals-new") << "same same" << "same" << "same" << "same same";
// newString contains oldString (avoid infinite loop)
// Expected behavior for a correct implementation: only original matches are replaced.
QTest::newRow("new-contains-old") << "aa" << "a" << "aa" << "aaaa";
// oldString empty: treat empty oldString as no-op.
QTest::newRow("empty-oldString-noop") << "abc" << "" << "X" << "abc";
// newString empty: delete occurrences
QTest::newRow("delete-occurrences") << "bananas" << "na" << "" << "bas";
}
void replaceInContents() // NOLINT
{
QFETCH(QString, contents);
QFETCH(QString, oldString);
QFETCH(QString, newString);
QFETCH(QString, expected);
std::string c = contents.toStdString();
const std::string oldS = oldString.toStdString();
const std::string newS = newString.toStdString();
TestablePathMigrationWorker::testableReplaceInContents(c, oldS, newS);
QCOMPARE(QString::fromStdString(c), expected);
}
void replaceInContents_idempotent_when_old_not_present() // NOLINT
{
std::string c = "no matches here";
const std::string oldS = "ZZZ";
const std::string newS = "YYY";
TestablePathMigrationWorker::testableReplaceInContents(c, oldS, newS);
const std::string once = c;
// run twice: should stay identical
TestablePathMigrationWorker::testableReplaceInContents(c, oldS, newS);
QCOMPARE(QString::fromStdString(c), QString::fromStdString(once));
}
std::unique_ptr<TestablePathMigrationWorker> makeWorker(int major, int minor)
{
std::string userConfigDir = Base::FileInfo::pathToString(
std::filesystem::temp_directory_path() / "Config"
);
std::string userAppDataDir = Base::FileInfo::pathToString(
std::filesystem::temp_directory_path() / "AppData"
);
return std::make_unique<TestablePathMigrationWorker>(userConfigDir, userAppDataDir, major, minor);
}
void generateNewUserAppPathString_no_version_now()
{
auto worker = makeWorker(1, 1);
std::filesystem::path testPath = std::filesystem::temp_directory_path() / "foo" / "bar";
std::string oldPath = Base::FileInfo::pathToString(testPath);
std::string newPath = worker->testableGenerateNewUserAppPathString(oldPath);
std::string expectedAddition = App::ApplicationDirectories::versionStringForPath(1, 1);
std::string expectedPath = Base::FileInfo::pathToString(testPath / expectedAddition);
QCOMPARE(newPath, expectedPath);
}
void generateNewUserAppPathString_version_in_current()
{
auto worker = makeWorker(1, 1);
std::filesystem::path testPath = std::filesystem::temp_directory_path() / "foo" / "bar"
/ "v1-0";
std::string oldPath = Base::FileInfo::pathToString(testPath);
std::string newPath = worker->testableGenerateNewUserAppPathString(oldPath);
std::string expectedAddition = App::ApplicationDirectories::versionStringForPath(1, 1);
std::string expectedPath = Base::FileInfo::pathToString(
testPath.parent_path() / expectedAddition
);
QCOMPARE(newPath, expectedPath);
}
void locateNewPreferences()
{
auto worker = makeWorker(1, 1);
std::string configDir = worker->getConfigDir();
std::filesystem::path expectedNewPreferences = Base::FileInfo::stringToPath(configDir);
expectedNewPreferences = expectedNewPreferences / "v1-1" / "user.cfg";
std::string expectedNewPreferencesString = Base::FileInfo::pathToString(expectedNewPreferences);
std::string actualNewPreferencesString = Base::FileInfo::pathToString(
worker->testableLocateNewPreferences()
);
QCOMPARE(actualNewPreferencesString, expectedNewPreferencesString);
}
static void _writePreferencesTestData(std::ostream& stream, const std::string& pathToInject)
{
stream << "<FCParamGroup Name=\"Macro\">\n"
<< " <FCBool Name=\"LocalEnvironment\" Value=\"1\"/>\n"
<< " <FCText Name=\"MacroPath\">" << pathToInject << "</FCText>";
}
void replaceOccurrencesInPreferences()
{
auto worker = makeWorker(1, 1);
std::string configDir = worker->getConfigDir();
std::string userAppDir = worker->getUserAppDir();
std::filesystem::path newPrefs = Base::FileInfo::stringToPath(configDir);
newPrefs = newPrefs / "v1-1" / "user.cfg";
std::filesystem::create_directories(newPrefs.parent_path());
std::ofstream prefs(newPrefs);
_writePreferencesTestData(prefs, userAppDir);
prefs.close();
worker->testableReplaceOccurrencesInPreferences();
std::ifstream loadedPrefs(newPrefs, std::ios::in | std::ios::binary);
std::string modifiedPrefsData {
std::istreambuf_iterator<char>(loadedPrefs),
std::istreambuf_iterator<char>()
};
loadedPrefs.close();
auto expectedNewDir = Base::FileInfo::pathToString(
Base::FileInfo::stringToPath(userAppDir) / "v1-1"
);
Q_ASSERT(modifiedPrefsData.find(expectedNewDir) != std::string::npos);
}
};
QTEST_MAIN(testPathMigrationWorker)
#include "DlgVersionMigrator.moc"

View File

@@ -0,0 +1,90 @@
// SPDX-License-Identifier: LGPL-2.1-or-later
#include <gtest/gtest.h>
#include "Gui/InputHint.h"
using namespace Gui;
using enum InputHint::UserInput;
class InputHintTest: public ::testing::Test
{
protected:
enum class State : std::uint8_t
{
SeekFirst,
SeekSecond
};
enum class Method : std::uint8_t
{
FirstMethod,
SecondMethod
};
using StateMethod = std::pair<State, Method>;
// Constants for hints
static const InputHint firstHint;
static const InputHint secondHint;
static const InputHint firstMethodHint;
static const InputHint secondMethodHint;
static const InputHint thirdMethodHint;
static const InputHint fourthMethodHint;
};
// Define the constants
const InputHint InputHintTest::firstHint = {QString("First hint"), {{KeySpace}}};
const InputHint InputHintTest::secondHint = {QString("Second hint"), {{KeyEnter}}};
const InputHint InputHintTest::firstMethodHint = {QString("First method hint"), {{KeyA}}};
const InputHint InputHintTest::secondMethodHint = {QString("Second method hint"), {{KeyB}}};
const InputHint InputHintTest::thirdMethodHint = {QString("Third method hint"), {{KeyC}}};
const InputHint InputHintTest::fourthMethodHint = {QString("Fourth method hint"), {{KeyD}}};
TEST_F(InputHintTest, LookupHintsSimpleState)
{
// Arrange
std::list<InputHint> hintsSeekFirst = {firstHint};
std::list<InputHint> hintsSeekSecond = {secondHint};
HintTable<State> table = {
{.state = State::SeekFirst, .hints = hintsSeekFirst},
{.state = State::SeekSecond, .hints = hintsSeekSecond}
};
// Act
auto resultFirst = lookupHints(State::SeekFirst, table);
auto resultSecond = lookupHints(State::SeekSecond, table);
// Assert
EXPECT_EQ(resultFirst, hintsSeekFirst);
EXPECT_EQ(resultSecond, hintsSeekSecond);
}
TEST_F(InputHintTest, LookupHintsPairState)
{
// Arrange
std::list<InputHint> firstFirstHints = {firstMethodHint};
std::list<InputHint> firstSecondHints = {secondMethodHint};
std::list<InputHint> secondFirstHints = {thirdMethodHint};
std::list<InputHint> secondSecondHints = {fourthMethodHint};
HintTable<StateMethod> table = {
{.state = {State::SeekFirst, Method::FirstMethod}, .hints = firstFirstHints},
{.state = {State::SeekFirst, Method::SecondMethod}, .hints = firstSecondHints},
{.state = {State::SeekSecond, Method::FirstMethod}, .hints = secondFirstHints},
{.state = {State::SeekSecond, Method::SecondMethod}, .hints = secondSecondHints}
};
// Act
auto resultFirstFirst = lookupHints({State::SeekFirst, Method::FirstMethod}, table);
auto resultFirstSecond = lookupHints({State::SeekFirst, Method::SecondMethod}, table);
auto resultSecondFirst = lookupHints({State::SeekSecond, Method::FirstMethod}, table);
auto resultSecondSecond = lookupHints({State::SeekSecond, Method::SecondMethod}, table);
// Assert
EXPECT_EQ(resultFirstFirst, firstFirstHints);
EXPECT_EQ(resultFirstSecond, firstSecondHints);
EXPECT_EQ(resultSecondFirst, secondFirstHints);
EXPECT_EQ(resultSecondSecond, secondSecondHints);
}

View File

@@ -0,0 +1,76 @@
// SPDX-License-Identifier: LGPL-2.1-or-later
#include <QDebug>
#include <QTest>
#include <App/Application.h>
#include "Gui/QuantitySpinBox.h"
#include <src/App/InitApplication.h>
// NOLINTBEGIN(readability-magic-numbers)
class testQuantitySpinBox: public QObject
{
Q_OBJECT
public:
testQuantitySpinBox()
{
tests::initApplication();
qsb = std::make_unique<Gui::QuantitySpinBox>();
}
private Q_SLOTS:
void init()
{}
void cleanup()
{}
void test_SimpleBaseUnit() // NOLINT
{
auto result = qsb->valueFromText("1mm");
QCOMPARE(result, Base::Quantity(1, "mm"));
}
void test_UnitInNumerator() // NOLINT
{
auto result = qsb->valueFromText("1mm/10");
QCOMPARE(result, Base::Quantity(0.1, "mm"));
}
void test_UnitInDenominator() // NOLINT
{
auto result = qsb->valueFromText("1/10mm");
QCOMPARE(result, Base::Quantity(0.1, "mm"));
}
void test_KeepFormat() // NOLINT
{
auto quant = qsb->value();
auto format = quant.getFormat();
format.setPrecision(7);
quant.setFormat(format);
qsb->setValue(quant);
auto val1 = qsb->value();
QCOMPARE(val1.getFormat().getPrecision(), 7);
// format shouldn't change after setting a double
qsb->setValue(3.5);
auto val2 = qsb->value();
QCOMPARE(val2.getFormat().getPrecision(), 7);
}
private:
std::unique_ptr<Gui::QuantitySpinBox> qsb;
};
// NOLINTEND(readability-magic-numbers)
QTEST_MAIN(testQuantitySpinBox)
#include "QuantitySpinBox.moc"

View File

@@ -0,0 +1,355 @@
// SPDX-License-Identifier: LGPL-2.1-or-later
/****************************************************************************
* *
* Copyright (c) 2025 Kacper Donat <kacper@kadet.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 <Gui/Application.h>
#include <Gui/Utilities.h>
#include <Gui/StyleParameters/ParameterManager.h>
using namespace Gui::StyleParameters;
class ParameterManagerTest: public ::testing::Test
{
protected:
void SetUp() override
{
// Create test sources
auto source1 = std::make_unique<InMemoryParameterSource>(
std::list<Parameter> {
{"BaseSize", "8px"},
{"PrimaryColor", "#ff0000"},
{"SecondaryColor", "#00ff00"},
},
ParameterSource::Metadata {"Source 1"}
);
auto source2 = std::make_unique<InMemoryParameterSource>(
std::list<Parameter> {
{"BaseSize", "16px"}, // Override from source1
{"Margin", "@BaseSize * 2"},
{"Padding", "@BaseSize / 2"},
},
ParameterSource::Metadata {"Source 2"}
);
manager.addSource(source1.get());
manager.addSource(source2.get());
sources.push_back(std::move(source1));
sources.push_back(std::move(source2));
}
Gui::StyleParameters::ParameterManager manager;
std::vector<std::unique_ptr<ParameterSource>> sources;
};
// Test basic parameter resolution
TEST_F(ParameterManagerTest, BasicParameterResolution)
{
{
auto result = manager.resolve("BaseSize");
EXPECT_TRUE(result.has_value());
EXPECT_TRUE(std::holds_alternative<Numeric>(*result));
auto length = std::get<Numeric>(*result);
EXPECT_DOUBLE_EQ(length.value, 16.0); // Should get value from source2 (later source)
EXPECT_EQ(length.unit, "px");
}
{
auto result = manager.resolve("PrimaryColor");
EXPECT_TRUE(result.has_value());
EXPECT_TRUE(std::holds_alternative<Base::Color>(*result));
auto color = std::get<Base::Color>(*result);
EXPECT_EQ(color.r, 1);
EXPECT_EQ(color.g, 0);
EXPECT_EQ(color.b, 0);
}
{
auto result = manager.resolve("SecondaryColor");
EXPECT_TRUE(result.has_value());
EXPECT_TRUE(std::holds_alternative<Base::Color>(*result));
auto color = std::get<Base::Color>(*result);
EXPECT_EQ(color.r, 0);
EXPECT_EQ(color.g, 1);
EXPECT_EQ(color.b, 0);
}
}
// Test parameter references
TEST_F(ParameterManagerTest, ParameterReferences)
{
{
auto result = manager.resolve("Margin");
EXPECT_TRUE(std::holds_alternative<Numeric>(*result));
auto length = std::get<Numeric>(*result);
EXPECT_DOUBLE_EQ(length.value, 32.0); // @BaseSize * 2 = 16 * 2 = 32
EXPECT_EQ(length.unit, "px");
}
{
auto result = manager.resolve("Padding");
EXPECT_TRUE(std::holds_alternative<Numeric>(*result));
auto length = std::get<Numeric>(*result);
EXPECT_DOUBLE_EQ(length.value, 8.0); // @BaseSize / 2 = 16 / 2 = 8
EXPECT_EQ(length.unit, "px");
}
}
// Test caching
TEST_F(ParameterManagerTest, Caching)
{
// First resolution should cache the result
auto result1 = manager.resolve("BaseSize");
EXPECT_TRUE(std::holds_alternative<Numeric>(*result1));
// Second resolution should use cached value
auto result2 = manager.resolve("BaseSize");
EXPECT_TRUE(std::holds_alternative<Numeric>(*result2));
// Results should be identical
auto length1 = std::get<Numeric>(*result1);
auto length2 = std::get<Numeric>(*result2);
EXPECT_DOUBLE_EQ(length1.value, length2.value);
EXPECT_EQ(length1.unit, length2.unit);
}
// Test cache invalidation
TEST_F(ParameterManagerTest, CacheInvalidation)
{
// Initial resolution
auto result1 = manager.resolve("BaseSize");
EXPECT_TRUE(std::holds_alternative<Numeric>(*result1));
auto length1 = std::get<Numeric>(*result1);
EXPECT_DOUBLE_EQ(length1.value, 16.0);
// Reload should clear cache
manager.reload();
// Resolution after reload should work the same
auto result2 = manager.resolve("BaseSize");
EXPECT_TRUE(std::holds_alternative<Numeric>(*result2));
auto length2 = std::get<Numeric>(*result2);
EXPECT_DOUBLE_EQ(length2.value, 16.0);
EXPECT_EQ(length1.unit, length2.unit);
}
// Test source priority
TEST_F(ParameterManagerTest, SourcePriority)
{
// Create a third source with higher priority
auto source3 = std::make_unique<InMemoryParameterSource>(
std::list<Parameter> {
{"BaseSize", "24px"}, // Should override both previous sources
},
ParameterSource::Metadata {"Source 3"}
);
manager.addSource(source3.get());
sources.push_back(std::move(source3));
// Should get value from the latest source (highest priority)
auto result = manager.resolve("BaseSize");
EXPECT_TRUE(std::holds_alternative<Numeric>(*result));
auto length = std::get<Numeric>(*result);
EXPECT_DOUBLE_EQ(length.value, 24.0);
EXPECT_EQ(length.unit, "px");
}
// Test parameter listing
TEST_F(ParameterManagerTest, ParameterListing)
{
auto params = manager.parameters();
// Should contain all parameters from all sources
std::set<std::string> paramNames;
for (const auto& param : params) {
paramNames.insert(param.name);
}
EXPECT_TRUE(paramNames.contains("BaseSize"));
EXPECT_TRUE(paramNames.contains("PrimaryColor"));
EXPECT_TRUE(paramNames.contains("SecondaryColor"));
EXPECT_TRUE(paramNames.contains("Margin"));
EXPECT_TRUE(paramNames.contains("Padding"));
// Should not contain duplicates (BaseSize should appear only once)
EXPECT_EQ(paramNames.count("BaseSize"), 1);
}
// Test expression retrieval
TEST_F(ParameterManagerTest, ExpressionRetrieval)
{
{
auto expr = manager.expression("BaseSize");
EXPECT_TRUE(expr.has_value());
EXPECT_EQ(*expr, "16px");
}
{
auto expr = manager.expression("Margin");
EXPECT_TRUE(expr.has_value());
EXPECT_EQ(*expr, "@BaseSize * 2");
}
{
auto expr = manager.expression("NonExistent");
EXPECT_FALSE(expr.has_value());
}
}
// Test parameter retrieval
TEST_F(ParameterManagerTest, ParameterRetrieval)
{
{
auto param = manager.parameter("BaseSize");
EXPECT_TRUE(param.has_value());
EXPECT_EQ(param->name, "BaseSize");
EXPECT_EQ(param->value, "16px");
}
{
auto param = manager.parameter("NonExistent");
EXPECT_FALSE(param.has_value());
}
}
// Test source management
TEST_F(ParameterManagerTest, SourceManagement)
{
auto sources = manager.sources();
EXPECT_EQ(sources.size(), 2); // We added 2 sources in SetUp
// Test that we can access the sources
for (auto source : sources) {
EXPECT_NE(source, nullptr);
auto params = source->all();
EXPECT_FALSE(params.empty());
}
}
// Test circular reference detection
TEST_F(ParameterManagerTest, CircularReferenceDetection)
{
// Create a source with circular reference
auto circularSource = std::make_unique<InMemoryParameterSource>(
std::list<Parameter> {
{"A", "@B"},
{"B", "@A"},
},
ParameterSource::Metadata {"Circular Source"}
);
manager.addSource(circularSource.get());
sources.push_back(std::move(circularSource));
// Should handle circular reference gracefully
auto result = manager.resolve("A");
// Should return the expression string as fallback
EXPECT_TRUE(std::holds_alternative<std::string>(*result));
}
// Test complex expressions
TEST_F(ParameterManagerTest, ComplexExpressions)
{
// Create a source with complex expressions
auto complexSource = std::make_unique<InMemoryParameterSource>(
std::list<Parameter> {
{"ComplexMargin", "(@BaseSize + 4px) * 2"},
{"ComplexPadding", "(@BaseSize - 2px) / 2"},
{"ColorWithFunction", "lighten(@PrimaryColor, 20)"},
},
ParameterSource::Metadata {"Complex Source"}
);
manager.addSource(complexSource.get());
sources.push_back(std::move(complexSource));
{
auto result = manager.resolve("ComplexMargin");
EXPECT_TRUE(std::holds_alternative<Numeric>(*result));
auto length = std::get<Numeric>(*result);
EXPECT_DOUBLE_EQ(length.value, 40.0); // (16 + 4) * 2 = 20 * 2 = 40
EXPECT_EQ(length.unit, "px");
}
{
auto result = manager.resolve("ComplexPadding");
EXPECT_TRUE(std::holds_alternative<Numeric>(*result));
auto length = std::get<Numeric>(*result);
EXPECT_DOUBLE_EQ(length.value, 7.0); // (16 - 2) / 2 = 14 / 2 = 7
EXPECT_EQ(length.unit, "px");
}
{
auto result = manager.resolve("ColorWithFunction");
EXPECT_TRUE(std::holds_alternative<Base::Color>(*result));
auto color = std::get<Base::Color>(*result).asValue<QColor>();
// Should be lighter than the original red
EXPECT_GT(color.lightness(), QColor(0xff0000).lightness());
}
}
// Test error handling
TEST_F(ParameterManagerTest, ErrorHandling)
{
// Test non-existent parameter
auto result = manager.resolve("NonExistent");
EXPECT_FALSE(result.has_value());
// Test invalid expression
auto invalidSource = std::make_unique<InMemoryParameterSource>(
std::list<Parameter> {
{"Invalid", "invalid expression that will fail"},
},
ParameterSource::Metadata {"Invalid Source"}
);
manager.addSource(invalidSource.get());
sources.push_back(std::move(invalidSource));
// Should handle invalid expression gracefully
auto invalidResult = manager.resolve("Invalid");
// Should return the expression string as fallback
EXPECT_TRUE(invalidResult.has_value());
EXPECT_TRUE(std::holds_alternative<std::string>(*invalidResult));
}
DEFINE_STYLE_PARAMETER(BaseSize, Numeric(8, "px"));
TEST_F(ParameterManagerTest, ResolveParameterDefinition)
{
auto result = manager.resolve(BaseSize);
EXPECT_DOUBLE_EQ(result.value, 16);
EXPECT_EQ(result.unit, "px");
}
DEFINE_STYLE_PARAMETER(MarginSize, Numeric(16, "px"));
TEST_F(ParameterManagerTest, ResolveParameterDefinitionDefault)
{
auto result = manager.resolve(MarginSize);
EXPECT_DOUBLE_EQ(result.value, 16);
EXPECT_EQ(result.unit, "px");
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,97 @@
// SPDX-License-Identifier: LGPL-2.1-or-later
/****************************************************************************
* *
* Copyright (c) 2025 Kacper Donat <kacper@kadet.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 <QString>
#include "src/App/InitApplication.h"
#include <Gui/Application.h>
#include <Gui/StyleParameters/ParameterManager.h>
using namespace Gui;
class StyleParametersApplicationTest: public ::testing::Test
{
protected:
static Application* app;
static void SetUpTestSuite()
{
tests::initApplication();
app = new Application(true);
}
void SetUp() override
{
auto styleParamManager = app->styleParameterManager();
styleParamManager->addSource(new StyleParameters::InMemoryParameterSource(
{
{.name = "ColorPrimary", .value = "#ff0000"},
{.name = "FontSize", .value = "12px"},
{.name = "BoxWidth", .value = "100px"},
},
{.name = "Fixture Source"}
));
}
};
Application* StyleParametersApplicationTest::app = {};
// Test for replacing variables in QSS string
TEST_F(StyleParametersApplicationTest, ReplaceVariablesInQss)
{
QString qss = "QWidget { color: @ColorPrimary; font-size: @FontSize; width: @BoxWidth; }";
QString result = app->replaceVariablesInQss(qss);
EXPECT_EQ(result.toStdString(), "QWidget { color: #ff0000; font-size: 12px; width: 100px; }");
}
// Test if unknown variables remain unchanged
TEST_F(StyleParametersApplicationTest, ReplaceVariablesInQssWithUnknownVariable)
{
QString qss = "QWidget { color: @UnknownColor; margin: 10px; }";
QString result = app->replaceVariablesInQss(qss);
EXPECT_EQ(result.toStdString(), "QWidget { color: ; margin: 10px; }");
}
// Test with an empty QSS string
TEST_F(StyleParametersApplicationTest, ReplaceVariablesInQssWithEmptyString)
{
QString qss = "";
QString result = app->replaceVariablesInQss(qss);
EXPECT_EQ(result.toStdString(), "");
}
// Test replacing multiple occurrences of the same variable
TEST_F(StyleParametersApplicationTest, ReplaceVariablesInQssWithMultipleOccurrences)
{
QString qss = "QWidget { color: @ColorPrimary; background: @ColorPrimary; }";
QString result = app->replaceVariablesInQss(qss);
EXPECT_EQ(result.toStdString(), "QWidget { color: #ff0000; background: #ff0000; }");
}

View File

@@ -0,0 +1 @@
setup_qt_test(PropertyItem)

View File

@@ -0,0 +1,111 @@
// SPDX-License-Identifier: LGPL-2.1-or-later
#include <QDebug>
#include <QtTest/QTest>
#include <App/Application.h>
#include "Gui/propertyeditor/PropertyItem.h"
#include <src/App/InitApplication.h>
// NOLINTBEGIN(readability-magic-numbers)
class MockPropertyItem final: public Gui::PropertyEditor::PropertyItem
{
public:
MockPropertyItem() = default;
void setTestValue(const QVariant& v)
{
testValue = v;
}
QVariant lastSetValue() const
{
return storedSetValue;
}
protected:
QVariant value(const App::Property* /*prop*/) const override
{
return testValue;
}
void setValue(const QVariant& v) override
{
storedSetValue = v;
}
private:
QVariant testValue;
QVariant storedSetValue;
};
class testPropertyItem: public QObject
{
Q_OBJECT
public:
testPropertyItem()
{
tests::initApplication();
item.reset(new MockPropertyItem());
}
private Q_SLOTS:
void init()
{}
void cleanup()
{}
void test_camelCaseSplitsTwoWords() // NOLINT
{
item->setPropertyName(QLatin1String("CamelCase"));
QCOMPARE(item->propertyName(), QLatin1String("Camel Case"));
}
void test_camelCaseSplitsThreeWords() // NOLINT
{
item->setPropertyName(QLatin1String("ThreeWordProperty"));
QCOMPARE(item->propertyName(), QLatin1String("Three Word Property"));
}
void test_digitBeforeUppercaseNotSplit() // NOLINT
{
item->setPropertyName(QLatin1String("View3D"));
QCOMPARE(item->propertyName(), QLatin1String("View3D"));
}
void test_camelCaseSplitButNotDigit() // NOLINT
{
item->setPropertyName(QLatin1String("MyView3D"));
QCOMPARE(item->propertyName(), QLatin1String("My View3D"));
}
void test_consecutiveUppercaseNotSplit() // NOLINT
{
item->setPropertyName(QLatin1String("MyABC"));
QCOMPARE(item->propertyName(), QLatin1String("My ABC"));
}
void test_notCleverEnoughToSplitConsecutiveCaps() // NOLINT
{
item->setPropertyName(QLatin1String("MyABCOfDoom"));
QCOMPARE(item->propertyName(), QLatin1String("My ABCOf Doom"));
}
void test_underscoresArentTheSameAsSpaces() // NOLINT
{
item->setPropertyName(QLatin1String("Box_Length"));
QCOMPARE(item->propertyName(), QLatin1String("Box_Length"));
}
private:
std::unique_ptr<Gui::PropertyEditor::PropertyItem> item;
};
// NOLINTEND(readability-magic-numbers)
QTEST_MAIN(testPropertyItem)
#include "PropertyItem.moc"

View File

@@ -0,0 +1,12 @@
# SPDX-License-Identifier: LGPL-2.1-or-later
add_executable(Misc_tests_run
fmt.cpp
)
target_link_libraries(Misc_tests_run PRIVATE
GTest::gtest_main
GTest::gmock_main
${Google_Tests_LIBS}
fmt::fmt
)

34
tests/src/Misc/fmt.cpp Normal file
View File

@@ -0,0 +1,34 @@
// SPDX-License-Identifier: LGPL-2.1-or-later
#include <fmt/format.h>
#include <fmt/printf.h>
#include <gtest/gtest.h>
#include <stdexcept>
// NOLINTBEGIN
TEST(fmt, fail)
{
EXPECT_NE("abc", fmt::format("{}{}", "a", "b"));
}
TEST(fmt, pass)
{
EXPECT_EQ("ab", fmt::format("{}{}", "a", "b"));
}
TEST(fmt, print_pass)
{
EXPECT_EQ("12", fmt::sprintf("%s%d", "1", 2));
EXPECT_EQ("x", fmt::sprintf("%c", 'x'));
EXPECT_EQ("1.23 2", fmt::sprintf("%.2f %d", 1.23456, 2));
EXPECT_EQ("0.123456789012", fmt::sprintf("%.12f", 0.123456789012));
EXPECT_EQ("-1234", fmt::sprintf("%li", -1234L));
EXPECT_EQ("-1234567890", fmt::sprintf("%li", -1234567890L));
EXPECT_EQ("1234567890", fmt::sprintf("%li", 1234567890UL));
}
TEST(fmt, print_fail)
{
EXPECT_THROW(fmt::printf("%s%d", 1, 2), std::exception);
}
// NOLINTEND

View File

@@ -0,0 +1,55 @@
// SPDX-License-Identifier: LGPL-2.1-or-later
#include <gtest/gtest.h>
#include <FCConfig.h>
#include <App/Application.h>
#include <App/Document.h>
#include <App/Expression.h>
#include <App/ObjectIdentifier.h>
#include <Mod/Assembly/App/AssemblyObject.h>
#include <Mod/Assembly/App/JointGroup.h>
#include <src/App/InitApplication.h>
class AssemblyObjectTest: public ::testing::Test
{
protected:
static void SetUpTestSuite()
{
tests::initApplication();
}
void SetUp() override
{
_docName = App::GetApplication().getUniqueDocumentName("test");
auto _doc = App::GetApplication().newDocument(_docName.c_str(), "testUser");
_assemblyObj = _doc->addObject<Assembly::AssemblyObject>();
_jointGroupObj = _assemblyObj->addObject<Assembly::JointGroup>("jointGroupTest");
}
void TearDown() override
{
App::GetApplication().closeDocument(_docName.c_str());
}
Assembly::AssemblyObject* getObject()
{
return _assemblyObj;
}
private:
// TODO: use shared_ptr or something else here?
Assembly::AssemblyObject* _assemblyObj;
Assembly::JointGroup* _jointGroupObj;
std::string _docName;
};
TEST_F(AssemblyObjectTest, createAssemblyObject) // NOLINT
{
// Arrange
// Act
// Assert
}

View File

@@ -0,0 +1,5 @@
# SPDX-License-Identifier: LGPL-2.1-or-later
add_executable(Assembly_tests_run
AssemblyObject.cpp
)

View File

@@ -0,0 +1,15 @@
# SPDX-License-Identifier: LGPL-2.1-or-later
add_subdirectory(App)
if (NOT FREECAD_USE_EXTERNAL_ONDSELSOLVER)
target_include_directories(Assembly_tests_run PUBLIC
${CMAKE_SOURCE_DIR}/src/3rdParty/OndselSolver
)
endif ()
target_link_libraries(Assembly_tests_run
gtest_main
${Google_Tests_LIBS}
Assembly
)

View File

@@ -0,0 +1,35 @@
# SPDX-License-Identifier: LGPL-2.1-or-later
if(BUILD_ASSEMBLY)
add_subdirectory(Assembly)
endif(BUILD_ASSEMBLY)
if(BUILD_MATERIAL)
add_subdirectory(Material)
endif(BUILD_MATERIAL)
if(BUILD_MEASURE)
add_subdirectory(Measure)
endif(BUILD_MEASURE)
if(BUILD_MESH)
add_subdirectory(Mesh)
endif(BUILD_MESH)
if(BUILD_MESH_PART)
add_subdirectory(MeshPart)
endif(BUILD_MESH_PART)
if(BUILD_PART)
add_subdirectory(Part)
endif(BUILD_PART)
if(BUILD_PART_DESIGN)
add_subdirectory(PartDesign)
endif(BUILD_PART_DESIGN)
if(BUILD_POINTS)
add_subdirectory(Points)
endif(BUILD_POINTS)
if(BUILD_SKETCHER)
add_subdirectory(Sketcher)
endif(BUILD_SKETCHER)
if(BUILD_SPREADSHEET)
add_subdirectory(Spreadsheet)
endif()
if(BUILD_START)
add_subdirectory(Start)
endif()

View File

@@ -0,0 +1,37 @@
# SPDX-License-Identifier: LGPL-2.1-or-later
add_executable(Material_tests_run
TestMaterialCards.cpp
TestMaterialFilter.cpp
TestMaterialProperties.cpp
TestMaterials.cpp
TestMaterialValue.cpp
TestModel.cpp
TestModelProperties.cpp
)
target_include_directories(Material_tests_run SYSTEM PUBLIC
${QtCore_INCLUDE_DIRS}
)
set(MaterialTestData_Files
Materials/TestAcrylicLegacy.FCMat
Materials/TestAluminumAppearance.FCMat
Materials/TestAluminumMixed.FCMat
Materials/TestAluminumPhysical.FCMat
Materials/TestBrassAppearance.FCMat
)
ADD_CUSTOM_TARGET(MaterialTestData ALL
SOURCES ${MaterialTestData_Files}
)
fc_target_copy_resource(MaterialTestData
${CMAKE_CURRENT_SOURCE_DIR}
${CMAKE_BINARY_DIR}/tests
${MaterialTestData_Files})
# INSTALL(
# FILES ${MaterialTest_Files}
# DESTINATION Mod/Material/materialtests
# )

View File

@@ -0,0 +1,13 @@
; Acrylic
; Automatically generated by the Rocket Workbench
; information about the content of such cards can be found on the wiki:
; https://www.freecad.org/wiki/Material
[General]
Name = TestAcrylicLegacy
Description = Acrylic
KindOfMaterial = Solid
[Mechanical]
Density = 1190.0 kg/m^3
Hardness = 10

View File

@@ -0,0 +1,17 @@
---
# File created by ConvertFCMat.py
General:
UUID: "3c6d0407-66b3-48ea-a2e8-ee843edf0311"
Author: "David Carter"
License: "GPL-2.0-or-later"
Name: "TestAluminumAppearance"
Description: "Defines the Aluminum appearance properties"
AppearanceModels:
BasicRendering:
UUID: 'f006c7e4-35b7-43d5-bbf9-c5d572309e6e'
AmbientColor: "(0.3000, 0.3000, 0.3000, 1.0)"
DiffuseColor: "(0.3000, 0.3000, 0.3000, 1.0)"
EmissiveColor: "(0.0000, 0.0000, 0.0000, 1.0)"
Shininess: "0.0900"
SpecularColor: "(0.3000, 0.3000, 0.3000, 1.0)"
Transparency: "0.0"

View File

@@ -0,0 +1,33 @@
---
# File created by ConvertFCMat.py
General:
UUID: "5f546608-fcbb-40db-98d7-d8e104eb33ce"
Author: "M. Münch"
License: "LGPL-2.0-or-later"
Name: "TestAluminumMixed"
Inherits:
Aluminum:
UUID: "3c6d0407-66b3-48ea-a2e8-ee843edf0311"
Models:
Father:
UUID: '9cdda8b6-b606-4778-8f13-3934d8668e67'
Father: "Metal"
MaterialStandard:
UUID: '1e2c0088-904a-4537-925f-64064c07d700'
KindOfMaterial: "Aluminium"
MaterialNumber: "3.3535.26"
StandardCode: "DIN 1725"
LinearElastic:
UUID: '7b561d1d-fb9b-44f6-9da9-56a4f74d7536'
Density: "2700 kg/m^3"
PoissonRatio: "0.3"
ShearModulus: "27000 MPa"
UltimateStrain: "5"
UltimateTensileStrength: "250 MPa"
YieldStrength: "180 MPa"
YoungsModulus: "70000 MPa"
Thermal:
UUID: '9959d007-a970-4ea7-bae4-3eb1b8b883c7'
SpecificHeat: "900 J/kg/K"
ThermalConductivity: "150 W/m/K"
ThermalExpansionCoefficient: "23 µm/m/K"

View File

@@ -0,0 +1,30 @@
---
# File created by ConvertFCMat.py
General:
UUID: "a8e60089-550d-4370-8e7e-1734db12a3a9"
Author: "M. Münch"
License: "LGPL-2.0-or-later"
Name: "TestAluminumPhysical"
Models:
Father:
UUID: '9cdda8b6-b606-4778-8f13-3934d8668e67'
Father: "Metal"
MaterialStandard:
UUID: '1e2c0088-904a-4537-925f-64064c07d700'
KindOfMaterial: "Aluminium"
MaterialNumber: "3.3535.26"
StandardCode: "DIN 1725"
LinearElastic:
UUID: '7b561d1d-fb9b-44f6-9da9-56a4f74d7536'
Density: "2700 kg/m^3"
PoissonRatio: "0.3"
ShearModulus: "27000 MPa"
# UltimateStrain: "5"
UltimateTensileStrength: "250 MPa"
YieldStrength: "180 MPa"
YoungsModulus: "70000 MPa"
Thermal:
UUID: '9959d007-a970-4ea7-bae4-3eb1b8b883c7'
SpecificHeat: "900 J/kg/K"
ThermalConductivity: "150 W/m/K"
ThermalExpansionCoefficient: "23 µm/m/K"

View File

@@ -0,0 +1,17 @@
---
# File created by ConvertFCMat.py
General:
UUID: "fff3d5c8-98c3-4ee2-8fe5-7e17403c48fcc"
Author: "David Carter"
License: "GPL-2.0-or-later"
Name: "TestBrassAppearance"
Description: "Defines the Brass appearance properties"
AppearanceModels:
BasicRendering:
UUID: 'f006c7e4-35b7-43d5-bbf9-c5d572309e6e'
AmbientColor: "(0.3294, 0.2235, 0.0275, 1.0)"
DiffuseColor: "(0.7804, 0.5686, 0.1137, 1.0)"
EmissiveColor: "(0.0000, 0.0000, 0.0000, 1.0)"
Shininess: "0.2179"
SpecularColor: "(0.9922, 0.9412, 0.8078, 1.0)"
Transparency: "0.0"

View File

@@ -0,0 +1,199 @@
// SPDX-License-Identifier: LGPL-2.1-or-later
/***************************************************************************
* Copyright (c) 2023 David Carter <dcarter@david.carter.ca> *
* *
* 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 <QMetaType>
#include <QString>
#include <App/Application.h>
#include <Base/Quantity.h>
#include <Gui/MetaTypes.h>
#include <src/App/InitApplication.h>
#include <Mod/Material/App/MaterialLibrary.h>
#include <Mod/Material/App/MaterialManager.h>
#include <Mod/Material/App/MaterialValue.h>
#include <Mod/Material/App/Model.h>
#include <Mod/Material/App/ModelManager.h>
#include <Mod/Material/App/ModelUuids.h>
// clang-format off
class TestMaterialCards : public ::testing::Test {
protected:
static void SetUpTestSuite() {
if (App::Application::GetARGC() == 0) {
tests::initApplication();
}
}
void SetUp() override {
// Create a temporary library
QString libPath = QDir::tempPath() + QStringLiteral("/TestMaterialCards");
QDir libDir(libPath);
libDir.removeRecursively(); // Clear old run data
libDir.mkdir(libPath);
_library = std::make_shared<Materials::MaterialLibraryLocal>(QStringLiteral("Testing"),
libPath,
QStringLiteral(":/icons/preferences-general.svg"),
false);
_modelManager = &(Materials::ModelManager::getManager());
_materialManager = &(Materials::MaterialManager::getManager());
_testMaterialUUID = QStringLiteral("c6c64159-19c1-40b5-859c-10561f20f979");
}
// void TearDown() override {}
Materials::ModelManager* _modelManager;
Materials::MaterialManager* _materialManager;
std::shared_ptr<Materials::MaterialLibraryLocal> _library;
QString _testMaterialUUID;
};
TEST_F(TestMaterialCards, TestCopy)
{
ASSERT_NE(_modelManager, nullptr);
ASSERT_TRUE(_library);
// FAIL() << "Test library " << _library->getDirectoryPath().toStdString() << "\n";
auto testMaterial = _materialManager->getMaterial(_testMaterialUUID);
auto newMaterial = std::make_shared<Materials::Material>(*testMaterial);
EXPECT_EQ(testMaterial->getUUID(), _testMaterialUUID);
EXPECT_EQ(newMaterial->getUUID(), _testMaterialUUID);
// Save the material
_materialManager->saveMaterial(_library,
newMaterial,
QStringLiteral("/Test Material2.FCMat"),
false, // overwrite
true, // saveAsCopy
false); // saveInherited
EXPECT_EQ(newMaterial->getUUID(), _testMaterialUUID);
EXPECT_EQ(newMaterial->getName(), QStringLiteral("Test Material2"));
// Save it when it already exists throwing an error
EXPECT_THROW(_materialManager->saveMaterial(_library,
newMaterial,
QStringLiteral("/Test Material2.FCMat"),
false, // overwrite
true, // saveAsCopy
false) // saveInherited
, Materials::MaterialExists);
EXPECT_EQ(newMaterial->getUUID(), _testMaterialUUID);
EXPECT_EQ(newMaterial->getName(), QStringLiteral("Test Material2"));
// Overwrite the existing file
_materialManager->saveMaterial(_library,
newMaterial,
QStringLiteral("/Test Material2.FCMat"),
true, // overwrite
true, // saveAsCopy
false);// saveInherited
EXPECT_EQ(newMaterial->getUUID(), _testMaterialUUID);
EXPECT_EQ(newMaterial->getName(), QStringLiteral("Test Material2"));
// Save to a new file, inheritance mode
_materialManager->saveMaterial(_library,
newMaterial,
QStringLiteral("/Test Material3.FCMat"),
false, // overwrite
true, // saveAsCopy
true);// saveInherited
EXPECT_EQ(newMaterial->getUUID(), _testMaterialUUID);
EXPECT_EQ(newMaterial->getName(), QStringLiteral("Test Material3"));
// Save to a new file, inheritance mode. no copy
_materialManager->saveMaterial(_library,
newMaterial,
QStringLiteral("/Test Material4.FCMat"),
false, // overwrite
false, // saveAsCopy
true);// saveInherited
EXPECT_NE(newMaterial->getUUID(), _testMaterialUUID);
EXPECT_EQ(newMaterial->getName(), QStringLiteral("Test Material4"));
QString uuid1 = newMaterial->getUUID();
// Save to a new file, inheritance mode, testing overwrite, new copy
_materialManager->saveMaterial(_library,
newMaterial,
QStringLiteral("/Test Material5.FCMat"),
false, // overwrite
true, // saveAsCopy
true);// saveInherited
EXPECT_EQ(newMaterial->getUUID(), uuid1);
EXPECT_EQ(newMaterial->getName(), QStringLiteral("Test Material5"));
_materialManager->saveMaterial(_library,
newMaterial,
QStringLiteral("/Test Material5.FCMat"),
true, // overwrite
true, // saveAsCopy
true);// saveInherited
EXPECT_EQ(newMaterial->getUUID(), uuid1);
EXPECT_EQ(newMaterial->getName(), QStringLiteral("Test Material5"));
// Save to a new file, inheritance mode, testing overwrite as no copy, new copy
_materialManager->saveMaterial(_library,
newMaterial,
QStringLiteral("/Test Material6.FCMat"),
false, // overwrite
true, // saveAsCopy
true);// saveInherited
EXPECT_EQ(newMaterial->getUUID(), uuid1);
EXPECT_EQ(newMaterial->getName(), QStringLiteral("Test Material6"));
_materialManager->saveMaterial(_library,
newMaterial,
QStringLiteral("/Test Material6.FCMat"),
true, // overwrite
false, // saveAsCopy
true);// saveInherited
EXPECT_EQ(newMaterial->getUUID(), uuid1);
EXPECT_EQ(newMaterial->getName(), QStringLiteral("Test Material6"));
}
TEST_F(TestMaterialCards, TestColumns)
{
ASSERT_NE(_modelManager, nullptr);
ASSERT_TRUE(_library);
auto testMaterial = _materialManager->getMaterial(_testMaterialUUID);
EXPECT_TRUE(testMaterial->hasPhysicalProperty(QStringLiteral("TestArray2D")));
auto array2d = testMaterial->getPhysicalProperty(QStringLiteral("TestArray2D"))->getMaterialValue();
EXPECT_TRUE(array2d);
EXPECT_EQ(dynamic_cast<Materials::Array2D &>(*array2d).columns(), 2);
EXPECT_TRUE(testMaterial->hasPhysicalProperty(QStringLiteral("TestArray2D3Column")));
auto array2d3Column = testMaterial->getPhysicalProperty(QStringLiteral("TestArray2D3Column"))->getMaterialValue();
EXPECT_TRUE(array2d3Column);
EXPECT_EQ(dynamic_cast<Materials::Array2D &>(*array2d3Column).columns(), 3);
EXPECT_TRUE(testMaterial->hasPhysicalProperty(QStringLiteral("TestArray3D")));
auto array3d = testMaterial->getPhysicalProperty(QStringLiteral("TestArray3D"))->getMaterialValue();
EXPECT_TRUE(array3d);
EXPECT_EQ(dynamic_cast<Materials::Array3D &>(*array3d).columns(), 2);
}
// clang-format on

View File

@@ -0,0 +1,261 @@
// SPDX-License-Identifier: LGPL-2.1-or-later
/***************************************************************************
* Copyright (c) 2023 David Carter <dcarter@david.carter.ca> *
* *
* 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 <QMetaType>
#include <QString>
#include <App/Application.h>
#include <Base/Quantity.h>
#include <Gui/MetaTypes.h>
#include <src/App/InitApplication.h>
#include <Mod/Material/App/MaterialLibrary.h>
#include <Mod/Material/App/MaterialManager.h>
#include <Mod/Material/App/MaterialValue.h>
#include <Mod/Material/App/Model.h>
#include <Mod/Material/App/ModelManager.h>
#include <Mod/Material/App/ModelUuids.h>
// clang-format off
class TestMaterialFilter : public ::testing::Test {
protected:
static void SetUpTestSuite()
{
tests::initApplication();
}
void SetUp() override {
_modelManager = &(Materials::ModelManager::getManager());
_materialManager = &(Materials::MaterialManager::getManager());
// Use our test files as a custom directory
ParameterGrp::handle hGrp =
App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Material/Resources");
_customDir = hGrp->GetASCII("CustomMaterialsDir", "");
_useBuiltInDir = hGrp->GetBool("UseBuiltInMaterials", true);
_useWorkbenchDir = hGrp->GetBool("UseMaterialsFromWorkbenches", true);
_useUserDir = hGrp->GetBool("UseMaterialsFromConfigDir", true);
_useCustomDir = hGrp->GetBool("UseMaterialsFromCustomDir", false);
std::string testPath = App::Application::getHomePath() + "/tests/Materials/";
hGrp->SetASCII("CustomMaterialsDir", testPath);
hGrp->SetBool("UseBuiltInMaterials", false);
hGrp->SetBool("UseMaterialsFromWorkbenches", false);
hGrp->SetBool("UseMaterialsFromConfigDir", false);
hGrp->SetBool("UseMaterialsFromCustomDir", true);
auto param = App::GetApplication().GetParameterGroupByPath(
"User parameter:BaseApp/Preferences/Mod/Material/Editor");
param->SetBool("ShowFavorites", true);
param->SetBool("ShowRecent", true);
param->SetBool("ShowEmptyFolders", false);
param->SetBool("ShowEmptyLibraries", true);
param->SetBool("ShowLegacy", false);
_materialManager->refresh();
_library = _materialManager->getLibrary(QStringLiteral("Custom"));
}
void TearDown() override {
ParameterGrp::handle hGrp =
App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Material/Resources");
// Restore preferences
hGrp->SetASCII("CustomMaterialsDir", _customDir);
hGrp->SetBool("UseBuiltInMaterials", _useBuiltInDir);
hGrp->SetBool("UseMaterialsFromWorkbenches", _useWorkbenchDir);
hGrp->SetBool("UseMaterialsFromConfigDir", _useUserDir);
hGrp->SetBool("UseMaterialsFromCustomDir", _useCustomDir);
hGrp = App::GetApplication().GetParameterGroupByPath(
"User parameter:BaseApp/Preferences/Mod/Material/Editor");
hGrp->SetBool("ShowFavorites", _includeFavorites);
hGrp->SetBool("ShowRecent", _includeRecent);
hGrp->SetBool("ShowEmptyFolders", _includeFolders);
hGrp->SetBool("ShowEmptyLibraries", _includeLibraries);
hGrp->SetBool("ShowLegacy", _includeLegacy);
_materialManager->refresh();
}
Materials::ModelManager* _modelManager {};
Materials::MaterialManager* _materialManager {};
std::shared_ptr<Materials::MaterialLibrary> _library;
QString _testMaterialUUID;
std::string _customDir;
bool _useBuiltInDir {};
bool _useWorkbenchDir {};
bool _useUserDir {};
bool _useCustomDir {};
bool _includeFavorites {};
bool _includeRecent {};
bool _includeFolders {};
bool _includeLibraries {};
bool _includeLegacy {};
const char* UUIDAcrylicLegacy = ""; // This can't be known until it is loaded
const char* UUIDAluminumAppearance = "3c6d0407-66b3-48ea-a2e8-ee843edf0311";
const char* UUIDAluminumMixed = "5f546608-fcbb-40db-98d7-d8e104eb33ce";
const char* UUIDAluminumPhysical = "a8e60089-550d-4370-8e7e-1734db12a3a9";
const char* UUIDBrassAppearance = "fff3d5c8-98c3-4ee2-8fe5-7e17403c48fcc";
};
TEST_F(TestMaterialFilter, TestFilters)
{
ASSERT_NE(_modelManager, nullptr);
// First check that our materials are loading
auto material = _materialManager->getMaterial(QString::fromLatin1(UUIDAluminumAppearance));
ASSERT_TRUE(material);
ASSERT_EQ(material->getName(), QStringLiteral("TestAluminumAppearance"));
ASSERT_EQ(material->getUUID(), QString::fromLatin1(UUIDAluminumAppearance));
material = _materialManager->getMaterial(QString::fromLatin1(UUIDAluminumMixed));
ASSERT_TRUE(material);
ASSERT_EQ(material->getName(), QStringLiteral("TestAluminumMixed"));
ASSERT_EQ(material->getUUID(), QString::fromLatin1(UUIDAluminumMixed));
material = _materialManager->getMaterial(QString::fromLatin1(UUIDAluminumPhysical));
ASSERT_TRUE(material);
ASSERT_EQ(material->getName(), QStringLiteral("TestAluminumPhysical"));
ASSERT_EQ(material->getUUID(), QString::fromLatin1(UUIDAluminumPhysical));
material = _materialManager->getMaterial(QString::fromLatin1(UUIDBrassAppearance));
ASSERT_TRUE(material);
ASSERT_EQ(material->getName(), QStringLiteral("TestBrassAppearance"));
ASSERT_EQ(material->getUUID(), QString::fromLatin1(UUIDBrassAppearance));
material = _materialManager->getMaterialByPath(QStringLiteral("TestAcrylicLegacy.FCMat"),
QStringLiteral("Custom"));
ASSERT_TRUE(material);
ASSERT_EQ(material->getName(), QStringLiteral("TestAcrylicLegacy"));
ASSERT_EQ(material->getUUID().size(), 36); // We don't know the UUID
// Create an empty filter
Materials::MaterialFilter filter;
Materials::MaterialFilterOptions options;
ASSERT_TRUE(_library);
auto tree = _materialManager->getMaterialTree(*_library, filter, options);
ASSERT_EQ(tree->size(), 4);
options.setIncludeLegacy(true);
tree = _materialManager->getMaterialTree(*_library, filter, options);
ASSERT_EQ(tree->size(), 5);
// Create a basic rendering filter
filter.setName(QStringLiteral("Basic Appearance"));
filter.addRequiredComplete(Materials::ModelUUIDs::ModelUUID_Rendering_Basic);
options.setIncludeLegacy(false);
tree = _materialManager->getMaterialTree(*_library, filter, options);
ASSERT_EQ(tree->size(), 3);
options.setIncludeLegacy(true);
tree = _materialManager->getMaterialTree(*_library, filter, options);
ASSERT_EQ(tree->size(), 3);
// Create an advanced rendering filter
filter.clear();
filter.setName(QStringLiteral("Advanced Appearance"));
filter.addRequiredComplete(Materials::ModelUUIDs::ModelUUID_Rendering_Advanced);
options.setIncludeLegacy(false);
tree = _materialManager->getMaterialTree(*_library, filter, options);
ASSERT_EQ(tree->size(), 0);
options.setIncludeLegacy(true);
tree = _materialManager->getMaterialTree(*_library, filter, options);
ASSERT_EQ(tree->size(), 0);
// Create a Density filter
filter.clear();
filter.setName(QStringLiteral("Density"));
filter.addRequiredComplete(Materials::ModelUUIDs::ModelUUID_Mechanical_Density);
options.setIncludeLegacy(false);
tree = _materialManager->getMaterialTree(*_library, filter, options);
ASSERT_EQ(tree->size(), 2);
options.setIncludeLegacy(true);
tree = _materialManager->getMaterialTree(*_library, filter, options);
ASSERT_EQ(tree->size(), 3);
// Create a Hardness filter
filter.clear();
filter.setName(QStringLiteral("Hardness"));
filter.addRequiredComplete(Materials::ModelUUIDs::ModelUUID_Mechanical_Hardness);
options.setIncludeLegacy(false);
tree = _materialManager->getMaterialTree(*_library, filter, options);
ASSERT_EQ(tree->size(), 0);
options.setIncludeLegacy(true);
tree = _materialManager->getMaterialTree(*_library, filter, options);
ASSERT_EQ(tree->size(), 0);
// Create a Density and Basic Rendering filter
filter.clear();
filter.setName(QStringLiteral("Density and Basic Rendering"));
filter.addRequiredComplete(Materials::ModelUUIDs::ModelUUID_Rendering_Basic);
filter.addRequiredComplete(Materials::ModelUUIDs::ModelUUID_Mechanical_Density);
options.setIncludeLegacy(false);
tree = _materialManager->getMaterialTree(*_library, filter, options);
ASSERT_EQ(tree->size(), 1);
options.setIncludeLegacy(true);
tree = _materialManager->getMaterialTree(*_library, filter, options);
ASSERT_EQ(tree->size(), 1);
// Create a Linear Elastic filter
filter.clear();
filter.setName(QStringLiteral("Linear Elastic"));
filter.addRequiredComplete(Materials::ModelUUIDs::ModelUUID_Mechanical_LinearElastic);
options.setIncludeLegacy(false);
tree = _materialManager->getMaterialTree(*_library, filter, options);
ASSERT_EQ(tree->size(), 0);
options.setIncludeLegacy(true);
tree = _materialManager->getMaterialTree(*_library, filter, options);
ASSERT_EQ(tree->size(), 0);
filter.clear();
filter.setName(QStringLiteral("Linear Elastic"));
filter.addRequired(Materials::ModelUUIDs::ModelUUID_Mechanical_LinearElastic);
options.setIncludeLegacy(false);
tree = _materialManager->getMaterialTree(*_library, filter, options);
ASSERT_EQ(tree->size(), 2);
options.setIncludeLegacy(true);
tree = _materialManager->getMaterialTree(*_library, filter, options);
ASSERT_EQ(tree->size(), 2);
}

View File

@@ -0,0 +1,236 @@
// SPDX-License-Identifier: LGPL-2.1-or-later
/***************************************************************************
* Copyright (c) 2023 David Carter <dcarter@david.carter.ca> *
* *
* 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 <memory>
#include <QMetaType>
#include <QString>
#include <App/Application.h>
#include <Gui/MetaTypes.h>
#include <Mod/Material/App/MaterialManager.h>
#include <Mod/Material/App/Model.h>
#include <Mod/Material/App/ModelManager.h>
#include <Mod/Material/App/ModelUuids.h>
class TestMaterialProperties: public ::testing::Test
{
protected:
static void SetUpTestSuite()
{}
void SetUp() override
{
// 2D Properties
modelProp = Materials::ModelProperty(
QStringLiteral("Density"), // Name
QStringLiteral("D"), // Header
QStringLiteral("2DArray"), // Type
QStringLiteral(""), // Units
QStringLiteral(""), // URL
QStringLiteral("desc")
); // Description
modelProp1 = Materials::ModelProperty(
QStringLiteral("Temperature"),
QStringLiteral("T"),
QStringLiteral("Quantity"),
QStringLiteral("C"),
QStringLiteral(""),
QStringLiteral("desc1")
);
modelProp2 = Materials::ModelProperty(
QStringLiteral("Density"),
QStringLiteral("D"),
QStringLiteral("Quantity"),
QStringLiteral("kg/m^3"),
QStringLiteral("https://en.wikipedia.org/wiki/Density"),
QStringLiteral("desc2")
);
modelProp.addColumn(modelProp1);
modelProp.addColumn(modelProp2);
// 3D properties
model3DProp = Materials::ModelProperty(
QStringLiteral("StressStrain"), // Name
QStringLiteral("Stress / Strain"), // Header
QStringLiteral("3DArray"), // Type
QStringLiteral(""), // Units
QStringLiteral(""), // URL
QStringLiteral(
"3 Dimensional array showing stress and strain as a function of "
"temperature"
)
); // Description
model3DProp1 = Materials::ModelProperty(
QStringLiteral("Temperature"),
QStringLiteral("T"),
QStringLiteral("Quantity"),
QStringLiteral("C"),
QStringLiteral(""),
QStringLiteral("desc1")
);
model3DProp2 = Materials::ModelProperty(
QStringLiteral("Stress"),
QStringLiteral("Stress"),
QStringLiteral("Quantity"),
QStringLiteral("MPa"),
QStringLiteral(""),
QStringLiteral("desc2")
);
model3DProp3 = Materials::ModelProperty(
QStringLiteral("Strain"),
QStringLiteral("Strain"),
QStringLiteral("Quantity"),
QStringLiteral("MPa"),
QStringLiteral(""),
QStringLiteral("desc3")
);
model3DProp.addColumn(model3DProp1);
model3DProp.addColumn(model3DProp2);
model3DProp.addColumn(model3DProp3);
}
// void TearDown() override {}
Materials::ModelProperty modelProp;
Materials::ModelProperty modelProp1;
Materials::ModelProperty modelProp2;
Materials::ModelProperty model3DProp;
Materials::ModelProperty model3DProp1;
Materials::ModelProperty model3DProp2;
Materials::ModelProperty model3DProp3;
};
TEST_F(TestMaterialProperties, TestEmpty)
{
Materials::MaterialProperty prop;
EXPECT_EQ(prop.getType(), Materials::MaterialValue::None);
EXPECT_TRUE(prop.isNull());
auto variant = prop.getValue();
EXPECT_TRUE(variant.isNull());
EXPECT_FALSE(variant.canConvert<QString>());
EXPECT_TRUE(variant.toString().isNull());
EXPECT_TRUE(variant.toString().isEmpty());
EXPECT_EQ(variant.toString().size(), 0);
}
TEST_F(TestMaterialProperties, TestSingle)
{
Materials::MaterialProperty prop(modelProp1, QStringLiteral("sampleUUID"));
EXPECT_EQ(prop.getType(), Materials::MaterialValue::Quantity);
EXPECT_EQ(prop.getModelUUID(), QStringLiteral("sampleUUID"));
EXPECT_TRUE(prop.isNull());
auto variant = prop.getValue();
EXPECT_TRUE(variant.canConvert<Base::Quantity>());
EXPECT_FALSE(variant.value<Base::Quantity>().isValid());
EXPECT_FALSE(variant.canConvert<QString>());
EXPECT_TRUE(variant.toString().isNull());
EXPECT_TRUE(variant.toString().isEmpty());
EXPECT_EQ(variant.toString().size(), 0);
}
void check2DArray(Materials::MaterialProperty& prop)
{
EXPECT_EQ(prop.getType(), Materials::MaterialValue::Array2D);
EXPECT_EQ(prop.getModelUUID(), QStringLiteral("sampleUUID"));
EXPECT_TRUE(prop.isNull());
auto array = std::static_pointer_cast<Materials::Array2D>(prop.getMaterialValue());
EXPECT_EQ(array->rows(), 0);
auto variant = prop.getValue(); // Throw an error?
EXPECT_FALSE(variant.canConvert<QString>());
EXPECT_TRUE(variant.toString().isNull());
EXPECT_TRUE(variant.toString().isEmpty());
EXPECT_EQ(variant.toString().size(), 0);
// Check the columns
EXPECT_EQ(prop.columns(), 2);
}
TEST_F(TestMaterialProperties, Test2DArray)
{
Materials::MaterialProperty prop(modelProp, QStringLiteral("sampleUUID"));
check2DArray(prop);
}
TEST_F(TestMaterialProperties, Test2DArrayCopy)
{
Materials::MaterialProperty propBase(modelProp, QStringLiteral("sampleUUID"));
Materials::MaterialProperty prop(propBase);
check2DArray(prop);
}
TEST_F(TestMaterialProperties, Test2DArrayAssignment)
{
Materials::MaterialProperty propBase(modelProp, QStringLiteral("sampleUUID"));
Materials::MaterialProperty prop;
prop = propBase;
check2DArray(prop);
}
void check3DArray(Materials::MaterialProperty& prop)
{
EXPECT_EQ(prop.getType(), Materials::MaterialValue::Array3D);
EXPECT_EQ(prop.getModelUUID(), QStringLiteral("sampleUUID"));
EXPECT_TRUE(prop.isNull());
auto array = std::static_pointer_cast<Materials::Array3D>(prop.getMaterialValue());
EXPECT_EQ(array->depth(), 0);
auto variant = prop.getValue(); // Throw an error?
EXPECT_FALSE(variant.canConvert<QString>());
EXPECT_TRUE(variant.toString().isNull());
EXPECT_TRUE(variant.toString().isEmpty());
EXPECT_EQ(variant.toString().size(), 0);
// Check the columns
EXPECT_EQ(prop.columns(), 3);
}
TEST_F(TestMaterialProperties, Test3DArray)
{
Materials::MaterialProperty prop(model3DProp, QStringLiteral("sampleUUID"));
check3DArray(prop);
}
TEST_F(TestMaterialProperties, Test3DArrayCopy)
{
Materials::MaterialProperty propBase(model3DProp, QStringLiteral("sampleUUID"));
Materials::MaterialProperty prop(propBase);
check3DArray(prop);
}
TEST_F(TestMaterialProperties, Test3DArrayAssignment)
{
Materials::MaterialProperty propBase(model3DProp, QStringLiteral("sampleUUID"));
Materials::MaterialProperty prop;
prop = propBase;
check3DArray(prop);
}
// clang-format off
// clang-format on

View File

@@ -0,0 +1,281 @@
// SPDX-License-Identifier: LGPL-2.1-or-later
/***************************************************************************
* Copyright (c) 2023 David Carter <dcarter@david.carter.ca> *
* *
* 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 <QMetaType>
#include <QString>
#include <App/Application.h>
#include <Gui/MetaTypes.h>
#include <Mod/Material/App/MaterialManager.h>
#include <Mod/Material/App/Model.h>
#include <Mod/Material/App/ModelManager.h>
#include <Mod/Material/App/ModelUuids.h>
// clang-format off
class TestMaterialValue : public ::testing::Test {
protected:
static void SetUpTestSuite() {
}
};
TEST_F(TestMaterialValue, TestNoneType)
{
auto mat1 = Materials::MaterialValue();
EXPECT_EQ(mat1.getType(), Materials::MaterialValue::None);
EXPECT_TRUE(mat1.isNull());
auto variant = mat1.getValue();
EXPECT_TRUE(variant.isNull());
EXPECT_FALSE(variant.canConvert<QString>());
EXPECT_TRUE(variant.toString().isNull());
EXPECT_TRUE(variant.toString().isEmpty());
EXPECT_EQ(variant.toString().size(), 0);
}
TEST_F(TestMaterialValue, TestStringType)
{
auto mat1 = Materials::MaterialValue(Materials::MaterialValue::String);
EXPECT_EQ(mat1.getType(), Materials::MaterialValue::String);
EXPECT_TRUE(mat1.isNull());
auto variant = mat1.getValue();
EXPECT_TRUE(variant.isNull());
EXPECT_TRUE(variant.canConvert<QString>());
EXPECT_TRUE(variant.toString().isNull());
EXPECT_TRUE(variant.toString().isEmpty());
EXPECT_EQ(variant.toString().size(), 0);
}
TEST_F(TestMaterialValue, TestBooleanType)
{
auto mat1 = Materials::MaterialValue(Materials::MaterialValue::Boolean);
EXPECT_EQ(mat1.getType(), Materials::MaterialValue::Boolean);
EXPECT_TRUE(mat1.isNull());
auto variant = mat1.getValue();
EXPECT_TRUE(variant.isNull());
EXPECT_TRUE(variant.canConvert<bool>());
EXPECT_FALSE(variant.toString().isNull());
EXPECT_FALSE(variant.toString().isEmpty());
EXPECT_EQ(variant.toString().size(), 5);
EXPECT_EQ(variant.toString(), QStringLiteral("false"));
EXPECT_EQ(variant.toBool(), false);
}
TEST_F(TestMaterialValue, TestIntegerType)
{
auto mat1 = Materials::MaterialValue(Materials::MaterialValue::Integer);
EXPECT_EQ(mat1.getType(), Materials::MaterialValue::Integer);
EXPECT_TRUE(mat1.isNull());
auto variant = mat1.getValue();
EXPECT_TRUE(variant.isNull());
EXPECT_TRUE(variant.canConvert<int>());
EXPECT_FALSE(variant.toString().isNull());
EXPECT_FALSE(variant.toString().isEmpty());
EXPECT_EQ(variant.toString().size(), 1);
EXPECT_EQ(variant.toString(), QStringLiteral("0"));
EXPECT_EQ(variant.toInt(), 0);
}
TEST_F(TestMaterialValue, TestFloatType)
{
auto mat1 = Materials::MaterialValue(Materials::MaterialValue::Float);
EXPECT_EQ(mat1.getType(), Materials::MaterialValue::Float);
EXPECT_TRUE(mat1.isNull());
auto variant = mat1.getValue();
EXPECT_TRUE(variant.isNull());
EXPECT_TRUE(variant.canConvert<float>());
EXPECT_FALSE(variant.toString().isNull());
EXPECT_FALSE(variant.toString().isEmpty());
EXPECT_EQ(variant.toString().size(), 1);
EXPECT_EQ(variant.toString(), QStringLiteral("0"));
EXPECT_EQ(variant.toFloat(), 0);
}
TEST_F(TestMaterialValue, TestQuantityType)
{
auto mat1 = Materials::MaterialValue(Materials::MaterialValue::Quantity);
EXPECT_EQ(mat1.getType(), Materials::MaterialValue::Quantity);
EXPECT_TRUE(mat1.isNull());
auto variant = mat1.getValue();
EXPECT_FALSE(variant.isNull());
EXPECT_TRUE(variant.canConvert<Base::Quantity>());
EXPECT_TRUE(variant.toString().isNull());
EXPECT_TRUE(variant.toString().isEmpty());
EXPECT_EQ(variant.toString().size(), 0);
auto quantity = variant.value<Base::Quantity>();
EXPECT_FALSE(quantity.isValid());
EXPECT_EQ(quantity.getUserString(), "nan");
EXPECT_TRUE(std::isnan(quantity.getValue()));
// Test a copy
auto mat2 = Materials::MaterialValue(mat1);
EXPECT_EQ(mat2.getType(), Materials::MaterialValue::Quantity);
EXPECT_TRUE(mat2.isNull());
variant = mat2.getValue();
EXPECT_FALSE(variant.isNull());
EXPECT_TRUE(variant.canConvert<Base::Quantity>());
EXPECT_TRUE(variant.toString().isNull());
EXPECT_TRUE(variant.toString().isEmpty());
EXPECT_EQ(variant.toString().size(), 0);
quantity = variant.value<Base::Quantity>();
EXPECT_FALSE(quantity.isValid());
EXPECT_EQ(quantity.getUserString(), "nan");
EXPECT_TRUE(std::isnan(quantity.getValue()));
}
TEST_F(TestMaterialValue, TestListType)
{
auto mat1 = Materials::MaterialValue(Materials::MaterialValue::List);
EXPECT_EQ(mat1.getType(), Materials::MaterialValue::List);
EXPECT_TRUE(mat1.isNull());
auto variant = mat1.getValue();
EXPECT_TRUE(variant.value<QList<QVariant>>().isEmpty());
EXPECT_EQ(variant.value<QList<QVariant>>().size(), 0);
EXPECT_FALSE(variant.isNull());
EXPECT_FALSE(variant.canConvert<QVariant>());
EXPECT_TRUE(variant.toString().isNull());
EXPECT_TRUE(variant.toString().isEmpty());
EXPECT_EQ(variant.toString().size(), 0);
auto list = mat1.getList();
EXPECT_TRUE(list.isEmpty());
EXPECT_EQ(list.size(), 0);
}
TEST_F(TestMaterialValue, TestArray2DType)
{
EXPECT_THROW(auto mat1 = Materials::MaterialValue(Materials::MaterialValue::Array2D), Materials::InvalidMaterialType);
auto mat2 = Materials::Array2D();
EXPECT_EQ(mat2.getType(), Materials::MaterialValue::Array2D);
EXPECT_TRUE(mat2.isNull());
EXPECT_EQ(mat2.rows(), 0);
}
TEST_F(TestMaterialValue, TestArray3DType)
{
EXPECT_THROW(auto mat1 = Materials::MaterialValue(Materials::MaterialValue::Array3D), Materials::InvalidMaterialType);
auto mat2 = Materials::Array3D();
mat2.setColumns(2);
EXPECT_EQ(mat2.getType(), Materials::MaterialValue::Array3D);
EXPECT_TRUE(mat2.isNull());
EXPECT_EQ(mat2.depth(), 0);
EXPECT_EQ(mat2.rows(), 0);
EXPECT_EQ(mat2.rows(0), 0);
EXPECT_THROW(mat2.rows(1), Materials::InvalidIndex);
Base::Quantity quantity;
quantity.setInvalid();
EXPECT_EQ(mat2.addDepth(0, quantity), 0);
EXPECT_EQ(mat2.depth(), 1);
EXPECT_EQ(mat2.rows(0), 0);
EXPECT_THROW(mat2.rows(1), Materials::InvalidIndex);
EXPECT_EQ(mat2.addDepth(quantity), 1);
EXPECT_EQ(mat2.depth(), 2);
EXPECT_EQ(mat2.rows(1), 0);
EXPECT_THROW(mat2.addDepth(99, quantity), Materials::InvalidIndex);
EXPECT_EQ(mat2.addDepth(2, quantity), 2);
EXPECT_EQ(mat2.depth(), 3);
EXPECT_EQ(mat2.rows(2), 0);
// Add rows
auto row = std::make_shared<QList<Base::Quantity>>();
row->push_back(quantity);
row->push_back(quantity);
EXPECT_EQ(mat2.rows(0), 0);
EXPECT_EQ(mat2.rows(1), 0);
EXPECT_EQ(mat2.rows(2), 0);
mat2.addRow(0, row);
EXPECT_EQ(mat2.rows(0), 1);
EXPECT_EQ(mat2.rows(1), 0);
EXPECT_EQ(mat2.rows(2), 0);
mat2.addRow(1, row);
EXPECT_EQ(mat2.rows(0), 1);
EXPECT_EQ(mat2.rows(1), 1);
EXPECT_EQ(mat2.rows(2), 0);
mat2.addRow(2, row);
EXPECT_EQ(mat2.rows(0), 1);
EXPECT_EQ(mat2.rows(1), 1);
EXPECT_EQ(mat2.rows(2), 1);
EXPECT_EQ(mat2.currentDepth(), 0);
mat2.addRow(row);
EXPECT_EQ(mat2.rows(0), 2);
EXPECT_EQ(mat2.rows(1), 1);
EXPECT_EQ(mat2.rows(2), 1);
mat2.setCurrentDepth(2);
EXPECT_EQ(mat2.currentDepth(), 2);
mat2.addRow(row);
EXPECT_EQ(mat2.rows(0), 2);
EXPECT_EQ(mat2.rows(1), 1);
EXPECT_EQ(mat2.rows(2), 2);
quantity = Base::Quantity::parse("32 C");
mat2.setDepthValue(quantity);
EXPECT_FALSE(mat2.getDepthValue(0).isValid());
EXPECT_FALSE(mat2.getDepthValue(1).isValid());
EXPECT_TRUE(mat2.getDepthValue(2).isValid());
EXPECT_EQ(mat2.getDepthValue(2), Base::Quantity::parse("32 C"));
mat2.setDepthValue(0, Base::Quantity::parse("9.8 m/s/s"));
EXPECT_TRUE(mat2.getDepthValue(0).isValid());
EXPECT_FALSE(mat2.getDepthValue(1).isValid());
EXPECT_TRUE(mat2.getDepthValue(2).isValid());
EXPECT_EQ(mat2.getDepthValue(0), Base::Quantity::parse("9.8 m/s/s"));
EXPECT_EQ(mat2.getDepthValue(2), Base::Quantity::parse("32 C"));
mat2.setDepthValue(1, Base::Quantity::parse("120 MPa"));
EXPECT_TRUE(mat2.getDepthValue(0).isValid());
EXPECT_TRUE(mat2.getDepthValue(1).isValid());
EXPECT_TRUE(mat2.getDepthValue(2).isValid());
EXPECT_EQ(mat2.getDepthValue(0), Base::Quantity::parse("9.8 m/s/s"));
EXPECT_EQ(mat2.getDepthValue(1), Base::Quantity::parse("120 MPa"));
EXPECT_EQ(mat2.getDepthValue(2), Base::Quantity::parse("32 C"));
// Rows are currently empty
EXPECT_THROW(mat2.getValue(2, 0), Materials::InvalidIndex);
EXPECT_NO_THROW(mat2.getValue(0, 0));
EXPECT_FALSE(mat2.getValue(0, 0).isValid());
EXPECT_FALSE(mat2.getValue(0, 1).isValid());
// set to a valid quantity
mat2.setValue(0, 0, Base::Quantity::parse("120 MPa"));
EXPECT_TRUE(mat2.getValue(0, 0).isValid());
mat2.setValue(0, 1, Base::Quantity::parse("9.8 m/s/s"));
EXPECT_TRUE(mat2.getValue(0, 1).isValid());
EXPECT_THROW(mat2.setValue(0, 2, Base::Quantity::parse("32 C")), Materials::InvalidIndex);
}
// clang-format on

View File

@@ -0,0 +1,377 @@
// SPDX-License-Identifier: LGPL-2.1-or-later
/***************************************************************************
* Copyright (c) 2023 David Carter <dcarter@david.carter.ca> *
* *
* 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 <QLocale>
#include <QMetaType>
#include <QString>
#include <App/Application.h>
#include <Base/Interpreter.h>
#include <Base/Quantity.h>
#include <Gui/MetaTypes.h>
#include <src/App/InitApplication.h>
#include <Mod/Material/App/MaterialManager.h>
#include <Mod/Material/App/MaterialValue.h>
#include <Mod/Material/App/Model.h>
#include <Mod/Material/App/ModelManager.h>
#include <Mod/Material/App/ModelUuids.h>
#ifdef _MSC_VER
# pragma warning(disable : 4834)
#endif
// clang-format off
class TestMaterial : public ::testing::Test {
protected:
static void SetUpTestSuite() {
if (App::Application::GetARGC() == 0) {
tests::initApplication();
}
}
void SetUp() override {
Base::Interpreter().runString("import Part");
_modelManager = &(Materials::ModelManager::getManager());
_materialManager = &(Materials::MaterialManager::getManager());
}
// void TearDown() override {}
Materials::ModelManager* _modelManager;
Materials::MaterialManager* _materialManager;
};
TEST_F(TestMaterial, TestInstallation)
{
ASSERT_NE(_modelManager, nullptr);
// We should have loaded at least the system library
auto libraries = _materialManager->getLibraries();
ASSERT_GT(libraries->size(), 0);
// We should have at least one material
auto materials = _materialManager->getLocalMaterials();
ASSERT_GT(materials->size(), 0);
}
TEST_F(TestMaterial, TestMaterialsWithModel)
{
ASSERT_NE(_materialManager, nullptr);
auto materials = _materialManager->materialsWithModel(
QStringLiteral("f6f9e48c-b116-4e82-ad7f-3659a9219c50")); // IsotropicLinearElastic
EXPECT_GT(materials->size(), 0);
auto materialsComplete = _materialManager->materialsWithModelComplete(
QStringLiteral("f6f9e48c-b116-4e82-ad7f-3659a9219c50")); // IsotropicLinearElastic
EXPECT_LE(materialsComplete->size(), materials->size());
auto materialsLinearElastic = _materialManager->materialsWithModel(
QStringLiteral("7b561d1d-fb9b-44f6-9da9-56a4f74d7536")); // LinearElastic
// All LinearElastic models should be in IsotropicLinearElastic since it is inherited
EXPECT_LE(materialsLinearElastic->size(), materials->size());
for (auto &itp : *materialsLinearElastic) {
auto mat = itp.first;
EXPECT_NO_THROW(materials->at(mat));
}
}
TEST_F(TestMaterial, TestMaterialByPath)
{
ASSERT_NE(_materialManager, nullptr);
auto steel = _materialManager->getMaterialByPath(
QStringLiteral("Standard/Metal/Steel/CalculiX-Steel.FCMat"),
QStringLiteral("System"));
EXPECT_NE(&steel, nullptr);
EXPECT_EQ(steel->getName(), QStringLiteral("CalculiX-Steel"));
EXPECT_EQ(steel->getUUID(), QStringLiteral("92589471-a6cb-4bbc-b748-d425a17dea7d"));
// The same but with a leading '/'
auto steel2 = _materialManager->getMaterialByPath(
QStringLiteral("/Standard/Metal/Steel/CalculiX-Steel.FCMat"),
QStringLiteral("System"));
EXPECT_NE(&steel2, nullptr);
EXPECT_EQ(steel2->getName(), QStringLiteral("CalculiX-Steel"));
EXPECT_EQ(steel2->getUUID(), QStringLiteral("92589471-a6cb-4bbc-b748-d425a17dea7d"));
// Same with the library name as a prefix
auto steel3 = _materialManager->getMaterialByPath(
QStringLiteral("/System/Standard/Metal/Steel/CalculiX-Steel.FCMat"),
QStringLiteral("System"));
EXPECT_NE(&steel3, nullptr);
EXPECT_EQ(steel3->getName(), QStringLiteral("CalculiX-Steel"));
EXPECT_EQ(steel3->getUUID(), QStringLiteral("92589471-a6cb-4bbc-b748-d425a17dea7d"));
}
TEST_F(TestMaterial, TestAddPhysicalModel)
{
// Start with an empty material
Materials::Material material;
auto models = material.getPhysicalModels();
EXPECT_NE(&models, nullptr);
EXPECT_EQ(models->size(), 0);
// Add a model
material.addPhysical(Materials::ModelUUIDs::ModelUUID_Electromagnetic_Default);
models = material.getPhysicalModels();
EXPECT_EQ(models->size(), 1);
// Add a second model
material.addPhysical(Materials::ModelUUIDs::ModelUUID_Mechanical_LinearElastic);
models = material.getPhysicalModels();
EXPECT_EQ(models->size(), 2);
// Add an inherited model
material.addPhysical(Materials::ModelUUIDs::ModelUUID_Mechanical_IsotropicLinearElastic);
models = material.getPhysicalModels();
EXPECT_EQ(models->size(), 2);
// Add a super model
material.clearModels();
EXPECT_EQ(models->size(), 0);
material.addPhysical(Materials::ModelUUIDs::ModelUUID_Mechanical_IsotropicLinearElastic);
models = material.getPhysicalModels();
EXPECT_EQ(models->size(), 1);
material.addPhysical(Materials::ModelUUIDs::ModelUUID_Mechanical_LinearElastic);
models = material.getPhysicalModels();
EXPECT_EQ(models->size(), 1);
// Remove the inherited model
material.removePhysical(Materials::ModelUUIDs::ModelUUID_Mechanical_IsotropicLinearElastic);
models = material.getPhysicalModels();
EXPECT_EQ(models->size(), 1);
// Remove the super model
material.removePhysical(Materials::ModelUUIDs::ModelUUID_Mechanical_LinearElastic);
models = material.getPhysicalModels();
EXPECT_EQ(models->size(), 0);
}
TEST_F(TestMaterial, TestAddAppearanceModel)
{
// Start with an empty material
Materials::Material material;
auto models = material.getAppearanceModels();
EXPECT_NE(models, nullptr);
EXPECT_EQ(models->size(), 0);
// Add a model
material.addAppearance(Materials::ModelUUIDs::ModelUUID_Rendering_Vector);
models = material.getAppearanceModels();
EXPECT_EQ(models->size(), 1);
// Add a second model
material.addAppearance(Materials::ModelUUIDs::ModelUUID_Rendering_Advanced);
models = material.getAppearanceModels();
EXPECT_EQ(models->size(), 2);
// Add an inherited model
material.addAppearance(Materials::ModelUUIDs::ModelUUID_Rendering_Basic);
models = material.getAppearanceModels();
EXPECT_EQ(models->size(), 2);
// Add a super model
material.clearModels();
EXPECT_EQ(models->size(), 0);
material.addAppearance(Materials::ModelUUIDs::ModelUUID_Rendering_Basic);
models = material.getAppearanceModels();
EXPECT_EQ(models->size(), 1);
material.addAppearance(Materials::ModelUUIDs::ModelUUID_Rendering_Advanced);
models = material.getAppearanceModels();
EXPECT_EQ(models->size(), 1);
// Remove the inherited model
material.removeAppearance(Materials::ModelUUIDs::ModelUUID_Rendering_Basic);
models = material.getAppearanceModels();
EXPECT_EQ(models->size(), 1);
// Remove the super model
material.removeAppearance(Materials::ModelUUIDs::ModelUUID_Rendering_Advanced);
models = material.getAppearanceModels();
EXPECT_EQ(models->size(), 0);
}
QString parseQuantity(const std::string& value)
{
auto quantity = Base::Quantity::parse(value);
quantity.setFormat(Materials::MaterialValue::getQuantityFormat());
return QString::fromStdString(quantity.getUserString());
}
TEST_F(TestMaterial, TestCalculiXSteel)
{
ASSERT_NE(_materialManager, nullptr);
auto steel = _materialManager->getMaterial(QStringLiteral("92589471-a6cb-4bbc-b748-d425a17dea7d"));
EXPECT_EQ(steel->getName(), QStringLiteral("CalculiX-Steel"));
EXPECT_EQ(steel->getUUID(), QStringLiteral("92589471-a6cb-4bbc-b748-d425a17dea7d"));
EXPECT_TRUE(steel->hasPhysicalModel(Materials::ModelUUIDs::ModelUUID_Mechanical_Density)); // Density
EXPECT_TRUE(steel->hasPhysicalModel(Materials::ModelUUIDs::ModelUUID_Mechanical_IsotropicLinearElastic)); // IsotropicLinearElastic
EXPECT_TRUE(steel->hasPhysicalModel(Materials::ModelUUIDs::ModelUUID_Thermal_Default)); // Thermal
EXPECT_FALSE(steel->hasPhysicalModel(Materials::ModelUUIDs::ModelUUID_Mechanical_LinearElastic)); // Legacy linear elastic - Not in the model
EXPECT_TRUE(steel->hasAppearanceModel(Materials::ModelUUIDs::ModelUUID_Rendering_Basic)); // BasicRendering - inherited from Steel.FCMat
EXPECT_TRUE(steel->isPhysicalModelComplete(Materials::ModelUUIDs::ModelUUID_Mechanical_Density)); // Density
EXPECT_FALSE(steel->isPhysicalModelComplete(Materials::ModelUUIDs::ModelUUID_Mechanical_IsotropicLinearElastic)); // IsotropicLinearElastic - incomplete
EXPECT_FALSE(steel->isPhysicalModelComplete(Materials::ModelUUIDs::ModelUUID_Thermal_Default)); // Thermal
EXPECT_FALSE(steel->isPhysicalModelComplete(Materials::ModelUUIDs::ModelUUID_Mechanical_LinearElastic)); // Legacy linear elastic - Not in the model
EXPECT_TRUE(steel->isAppearanceModelComplete(Materials::ModelUUIDs::ModelUUID_Rendering_Basic)); // BasicRendering - inherited from Steel.FCMat
EXPECT_TRUE(steel->hasPhysicalProperty(QStringLiteral("Density")));
EXPECT_TRUE(steel->hasPhysicalProperty(QStringLiteral("BulkModulus")));
EXPECT_TRUE(steel->hasPhysicalProperty(QStringLiteral("PoissonRatio")));
EXPECT_TRUE(steel->hasPhysicalProperty(QStringLiteral("YoungsModulus")));
EXPECT_TRUE(steel->hasPhysicalProperty(QStringLiteral("ShearModulus")));
EXPECT_TRUE(steel->hasPhysicalProperty(QStringLiteral("SpecificHeat")));
EXPECT_TRUE(steel->hasPhysicalProperty(QStringLiteral("ThermalConductivity")));
EXPECT_TRUE(steel->hasPhysicalProperty(QStringLiteral("ThermalExpansionCoefficient")));
EXPECT_TRUE(steel->hasAppearanceProperty(QStringLiteral("AmbientColor")));
EXPECT_TRUE(steel->hasAppearanceProperty(QStringLiteral("DiffuseColor")));
EXPECT_TRUE(steel->hasAppearanceProperty(QStringLiteral("EmissiveColor")));
EXPECT_TRUE(steel->hasAppearanceProperty(QStringLiteral("Shininess")));
EXPECT_TRUE(steel->hasAppearanceProperty(QStringLiteral("SpecularColor")));
EXPECT_TRUE(steel->hasAppearanceProperty(QStringLiteral("Transparency")));
auto& properties = steel->getPhysicalProperties();
EXPECT_NO_THROW(properties.at(QStringLiteral("Density")));
EXPECT_NO_THROW(properties.at(QStringLiteral("BulkModulus"))); // This is different from the Python behaviour
EXPECT_NO_THROW(properties.at(QStringLiteral("PoissonRatio")));
EXPECT_NO_THROW(properties.at(QStringLiteral("YoungsModulus")));
EXPECT_NO_THROW(properties.at(QStringLiteral("ShearModulus")));
EXPECT_NO_THROW(properties.at(QStringLiteral("SpecificHeat")));
EXPECT_NO_THROW(properties.at(QStringLiteral("ThermalConductivity")));
EXPECT_NO_THROW(properties.at(QStringLiteral("ThermalExpansionCoefficient")));
EXPECT_THROW(properties.at(QStringLiteral("AmbientColor")), std::out_of_range);
EXPECT_THROW(properties.at(QStringLiteral("DiffuseColor")), std::out_of_range);
EXPECT_THROW(properties.at(QStringLiteral("EmissiveColor")), std::out_of_range);
EXPECT_THROW(properties.at(QStringLiteral("Shininess")), std::out_of_range);
EXPECT_THROW(properties.at(QStringLiteral("SpecularColor")), std::out_of_range);
EXPECT_THROW(properties.at(QStringLiteral("Transparency")), std::out_of_range);
auto& properties1 = steel->getAppearanceProperties();
EXPECT_THROW(properties1.at(QStringLiteral("Density")), std::out_of_range);
EXPECT_THROW(properties1.at(QStringLiteral("BulkModulus")), std::out_of_range);
EXPECT_THROW(properties1.at(QStringLiteral("PoissonRatio")), std::out_of_range);
EXPECT_THROW(properties1.at(QStringLiteral("YoungsModulus")), std::out_of_range);
EXPECT_THROW(properties1.at(QStringLiteral("ShearModulus")), std::out_of_range);
EXPECT_THROW(properties1.at(QStringLiteral("SpecificHeat")), std::out_of_range);
EXPECT_THROW(properties1.at(QStringLiteral("ThermalConductivity")), std::out_of_range);
EXPECT_THROW(properties1.at(QStringLiteral("ThermalExpansionCoefficient")), std::out_of_range);
EXPECT_NO_THROW(properties1.at(QStringLiteral("AmbientColor")));
EXPECT_NO_THROW(properties1.at(QStringLiteral("DiffuseColor")));
EXPECT_NO_THROW(properties1.at(QStringLiteral("EmissiveColor")));
EXPECT_NO_THROW(properties1.at(QStringLiteral("Shininess")));
EXPECT_NO_THROW(properties1.at(QStringLiteral("SpecularColor")));
EXPECT_NO_THROW(properties1.at(QStringLiteral("Transparency")));
EXPECT_FALSE(properties[QStringLiteral("Density")]->isNull());
EXPECT_TRUE(properties[QStringLiteral("BulkModulus")]->isNull());
EXPECT_FALSE(properties[QStringLiteral("PoissonRatio")]->isNull());
EXPECT_FALSE(properties[QStringLiteral("YoungsModulus")]->isNull());
EXPECT_TRUE(properties[QStringLiteral("ShearModulus")]->isNull());
EXPECT_FALSE(properties[QStringLiteral("SpecificHeat")]->isNull());
EXPECT_FALSE(properties[QStringLiteral("ThermalConductivity")]->isNull());
EXPECT_FALSE(properties[QStringLiteral("ThermalExpansionCoefficient")]->isNull());
EXPECT_FALSE(properties1[QStringLiteral("AmbientColor")]->isNull());
EXPECT_FALSE(properties1[QStringLiteral("DiffuseColor")]->isNull());
EXPECT_FALSE(properties1[QStringLiteral("EmissiveColor")]->isNull());
EXPECT_FALSE(properties1[QStringLiteral("Shininess")]->isNull());
EXPECT_FALSE(properties1[QStringLiteral("SpecularColor")]->isNull());
EXPECT_FALSE(properties1[QStringLiteral("Transparency")]->isNull());
QLocale locale;
EXPECT_EQ(properties[QStringLiteral("Density")]->getString(), parseQuantity("7900.00 kg/m^3"));
EXPECT_EQ(properties[QStringLiteral("PoissonRatio")]->getString(), locale.toString(0.3));
EXPECT_EQ(properties[QStringLiteral("YoungsModulus")]->getString(), parseQuantity("210.00 GPa"));
EXPECT_EQ(properties[QStringLiteral("SpecificHeat")]->getString(), parseQuantity("590.00 J/kg/K"));
EXPECT_EQ(properties[QStringLiteral("ThermalConductivity")]->getString(), parseQuantity("43.00 W/m/K"));
EXPECT_EQ(properties[QStringLiteral("ThermalExpansionCoefficient")]->getString(), parseQuantity("12.00 µm/m/K"));
EXPECT_EQ(properties1[QStringLiteral("AmbientColor")]->getString(), QStringLiteral("(0.0020, 0.0020, 0.0020, 1.0)"));
EXPECT_EQ(properties1[QStringLiteral("DiffuseColor")]->getString(), QStringLiteral("(0.0000, 0.0000, 0.0000, 1.0)"));
EXPECT_EQ(properties1[QStringLiteral("EmissiveColor")]->getString(), QStringLiteral("(0.0000, 0.0000, 0.0000, 1.0)"));
EXPECT_EQ(properties1[QStringLiteral("Shininess")]->getString(), locale.toString(0.06));
EXPECT_EQ(properties1[QStringLiteral("SpecularColor")]->getString(), QStringLiteral("(0.9800, 0.9800, 0.9800, 1.0)"));
EXPECT_EQ(properties1[QStringLiteral("Transparency")]->getString(), QStringLiteral("0"));
EXPECT_TRUE(properties[QStringLiteral("BulkModulus")]->getString().isEmpty());
EXPECT_TRUE(properties[QStringLiteral("ShearModulus")]->getString().isEmpty());
// These are the preferred method of access
//
EXPECT_DOUBLE_EQ(steel->getPhysicalQuantity(QStringLiteral("Density")).getValue(), 7.9e-06);
EXPECT_NEAR(steel->getPhysicalValue(QStringLiteral("PoissonRatio")).toDouble(), 0.3, 1e-6);
EXPECT_DOUBLE_EQ(steel->getPhysicalQuantity(QStringLiteral("YoungsModulus")).getValue(), 210000000.0);
EXPECT_DOUBLE_EQ(steel->getPhysicalQuantity(QStringLiteral("SpecificHeat")).getValue(), 590000000.0);
EXPECT_DOUBLE_EQ(steel->getPhysicalQuantity(QStringLiteral("ThermalConductivity")).getValue(), 43000.0);
EXPECT_DOUBLE_EQ(steel->getPhysicalQuantity(QStringLiteral("ThermalExpansionCoefficient")).getValue(), 1.2e-05);
EXPECT_EQ(steel->getAppearanceValue(QStringLiteral("AmbientColor")), QStringLiteral("(0.0020, 0.0020, 0.0020, 1.0)"));
EXPECT_EQ(steel->getAppearanceValue(QStringLiteral("DiffuseColor")), QStringLiteral("(0.0000, 0.0000, 0.0000, 1.0)"));
EXPECT_EQ(steel->getAppearanceValue(QStringLiteral("EmissiveColor")), QStringLiteral("(0.0000, 0.0000, 0.0000, 1.0)"));
EXPECT_NEAR(steel->getAppearanceValue(QStringLiteral("Shininess")).toDouble(), 0.06, 1e-6);
EXPECT_EQ(steel->getAppearanceValue(QStringLiteral("SpecularColor")), QStringLiteral("(0.9800, 0.9800, 0.9800, 1.0)"));
EXPECT_DOUBLE_EQ(steel->getAppearanceValue(QStringLiteral("Transparency")).toDouble(), 0.0);
EXPECT_EQ(steel->getPhysicalQuantity(QStringLiteral("Density")).getUserString(), parseQuantity("7900.00 kg/m^3").toStdString());
EXPECT_EQ(steel->getPhysicalQuantity(QStringLiteral("YoungsModulus")).getUserString(), parseQuantity("210.00 GPa").toStdString());
EXPECT_EQ(steel->getPhysicalQuantity(QStringLiteral("SpecificHeat")).getUserString(), parseQuantity("590.00 J/kg/K").toStdString());
EXPECT_EQ(steel->getPhysicalQuantity(QStringLiteral("ThermalConductivity")).getUserString(), parseQuantity("43.00 W/m/K").toStdString());
EXPECT_EQ(steel->getPhysicalQuantity(QStringLiteral("ThermalExpansionCoefficient")).getUserString(), parseQuantity("12.00 µm/m/K").toStdString());
}
TEST_F(TestMaterial, TestColumns)
{
// Start with an empty material
Materials::Material testMaterial;
auto models = testMaterial.getPhysicalModels();
EXPECT_NE(&models, nullptr);
EXPECT_EQ(models->size(), 0);
// Add a model
testMaterial.addPhysical(Materials::ModelUUIDs::ModelUUID_Test_Model);
models = testMaterial.getPhysicalModels();
EXPECT_EQ(models->size(), 1);
EXPECT_TRUE(testMaterial.hasPhysicalProperty(QStringLiteral("TestArray2D")));
auto array2d = testMaterial.getPhysicalProperty(QStringLiteral("TestArray2D"))->getMaterialValue();
EXPECT_TRUE(array2d);
EXPECT_EQ(dynamic_cast<Materials::Array2D &>(*array2d).columns(), 2);
EXPECT_TRUE(testMaterial.hasPhysicalProperty(QStringLiteral("TestArray2D3Column")));
auto array2d3Column = testMaterial.getPhysicalProperty(QStringLiteral("TestArray2D3Column"))->getMaterialValue();
EXPECT_TRUE(array2d3Column);
EXPECT_EQ(dynamic_cast<Materials::Array2D &>(*array2d3Column).columns(), 3);
EXPECT_TRUE(testMaterial.hasPhysicalProperty(QStringLiteral("TestArray3D")));
auto array3d = testMaterial.getPhysicalProperty(QStringLiteral("TestArray3D"))->getMaterialValue();
EXPECT_TRUE(array3d);
EXPECT_EQ(dynamic_cast<Materials::Array3D &>(*array3d).columns(), 2);
}
// clang-format on

View File

@@ -0,0 +1,136 @@
// SPDX-License-Identifier: LGPL-2.1-or-later
/***************************************************************************
* Copyright (c) 2023 David Carter <dcarter@david.carter.ca> *
* *
* 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 <QString>
#include <App/Application.h>
#include <src/App/InitApplication.h>
#include <Mod/Material/App/MaterialManager.h>
#include <Mod/Material/App/Model.h>
#include <Mod/Material/App/ModelManager.h>
// clang-format off
class TestModel : public ::testing::Test {
protected:
static void SetUpTestSuite() {
if (App::Application::GetARGC() == 0) {
tests::initApplication();
}
}
void SetUp() override {
_modelManager = &(Materials::ModelManager::getManager());
}
// void TearDown() override {}
Materials::ModelManager* _modelManager;
};
TEST_F(TestModel, TestApplication)
{
ASSERT_NO_THROW(App::GetApplication());
}
TEST_F(TestModel, TestResources)
{
try {
auto param = App::GetApplication().GetParameterGroupByPath(
"User parameter:BaseApp/Preferences/Mod/Material/Resources");
EXPECT_NE(param, nullptr);
}
catch (const std::exception &e)
{
FAIL() << "Exception: " << e.what() << "\n";
}
}
TEST_F(TestModel, TestInstallation)
{
ASSERT_NE(_modelManager, nullptr);
// We should have loaded at least the system library
auto libraries = _modelManager->getLibraries();
ASSERT_GT(libraries->size(), 0);
// We should have at least one model
auto models = _modelManager->getModels();
ASSERT_GT(models->size(), 0);
}
TEST_F(TestModel, TestModelLoad)
{
ASSERT_NE(_modelManager, nullptr);
auto density = _modelManager->getModel(QStringLiteral("454661e5-265b-4320-8e6f-fcf6223ac3af"));
EXPECT_EQ(density->getName(), QStringLiteral("Density"));
EXPECT_EQ(density->getUUID(), QStringLiteral("454661e5-265b-4320-8e6f-fcf6223ac3af"));
auto& prop = (*density)[QStringLiteral("Density")];
EXPECT_EQ(prop.getName(), QStringLiteral("Density"));
}
TEST_F(TestModel, TestModelByPath)
{
ASSERT_NE(_modelManager, nullptr);
auto linearElastic = _modelManager->getModelByPath(
QStringLiteral("Mechanical/LinearElastic.yml"),
QStringLiteral("System"));
EXPECT_NE(&linearElastic, nullptr);
EXPECT_EQ(linearElastic->getName(), QStringLiteral("Linear Elastic"));
EXPECT_EQ(linearElastic->getUUID(), QStringLiteral("7b561d1d-fb9b-44f6-9da9-56a4f74d7536"));
// The same but with a leading '/'
auto linearElastic2 = _modelManager->getModelByPath(
QStringLiteral("/Mechanical/LinearElastic.yml"),
QStringLiteral("System"));
EXPECT_NE(&linearElastic2, nullptr);
EXPECT_EQ(linearElastic2->getName(), QStringLiteral("Linear Elastic"));
EXPECT_EQ(linearElastic2->getUUID(), QStringLiteral("7b561d1d-fb9b-44f6-9da9-56a4f74d7536"));
// Same with the library name as a prefix
auto linearElastic3 = _modelManager->getModelByPath(
QStringLiteral("/System/Mechanical/LinearElastic.yml"),
QStringLiteral("System"));
EXPECT_NE(&linearElastic3, nullptr);
EXPECT_EQ(linearElastic3->getName(), QStringLiteral("Linear Elastic"));
EXPECT_EQ(linearElastic3->getUUID(), QStringLiteral("7b561d1d-fb9b-44f6-9da9-56a4f74d7536"));
// Test with the file system path
ASSERT_NO_THROW(linearElastic->getLibrary());
ASSERT_NO_THROW(linearElastic->getLibrary()->getName());
ASSERT_NO_THROW(linearElastic->getLibrary()->getDirectoryPath());
EXPECT_EQ(linearElastic->getLibrary()->getName(), QStringLiteral("System"));
QString path = linearElastic->getLibrary()->getDirectoryPath() + QStringLiteral("/Mechanical/LinearElastic.yml");
ASSERT_NO_THROW(_modelManager->getModelByPath(path));
auto linearElastic4 = _modelManager->getModelByPath(path);
EXPECT_NE(&linearElastic4, nullptr);
EXPECT_EQ(linearElastic4->getName(), QStringLiteral("Linear Elastic"));
EXPECT_EQ(linearElastic4->getUUID(), QStringLiteral("7b561d1d-fb9b-44f6-9da9-56a4f74d7536"));
}
// clang-format on

View File

@@ -0,0 +1,132 @@
// SPDX-License-Identifier: LGPL-2.1-or-later
/***************************************************************************
* Copyright (c) 2023 David Carter <dcarter@david.carter.ca> *
* *
* 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 <QMetaType>
#include <QString>
#include <App/Application.h>
#include <Gui/MetaTypes.h>
#include <Mod/Material/App/MaterialManager.h>
#include <Mod/Material/App/Model.h>
#include <Mod/Material/App/ModelManager.h>
#include <Mod/Material/App/ModelUuids.h>
// clang-format off
class TestModelProperties : public ::testing::Test {
protected:
static void SetUpTestSuite() {
}
};
TEST_F(TestModelProperties, TestEmpty)
{
auto prop = Materials::ModelProperty();
EXPECT_TRUE(prop.getName().isNull());
EXPECT_TRUE(prop.getPropertyType().isNull());
EXPECT_TRUE(prop.getUnits().isNull());
EXPECT_TRUE(prop.getURL().isNull());
EXPECT_TRUE(prop.getDescription().isNull());
EXPECT_TRUE(prop.getInheritance().isNull());
EXPECT_FALSE(prop.isInherited());
EXPECT_EQ(prop.columns(), 0);
}
TEST_F(TestModelProperties, TestBasic)
{
auto prop = Materials::ModelProperty(QStringLiteral("1"),
QStringLiteral("2"),
QStringLiteral("3"),
QStringLiteral("4"),
QStringLiteral("5"),
QStringLiteral("6"));
EXPECT_EQ(prop.getName(), QStringLiteral("1"));
EXPECT_EQ(prop.getDisplayName(), QStringLiteral("2"));
EXPECT_EQ(prop.getPropertyType(), QStringLiteral("3"));
EXPECT_EQ(prop.getUnits(), QStringLiteral("4"));
EXPECT_EQ(prop.getURL(), QStringLiteral("5"));
EXPECT_EQ(prop.getDescription(), QStringLiteral("6"));
EXPECT_TRUE(prop.getInheritance().isNull());
EXPECT_FALSE(prop.isInherited());
EXPECT_EQ(prop.columns(), 0);
prop.setInheritance(QStringLiteral("12345"));
EXPECT_EQ(prop.getInheritance(), QStringLiteral("12345"));
EXPECT_TRUE(prop.isInherited());
}
TEST_F(TestModelProperties, TestAddColumns)
{
auto prop = Materials::ModelProperty(QStringLiteral("1"),
QStringLiteral("2"),
QStringLiteral("3"),
QStringLiteral("4"),
QStringLiteral("5"),
QStringLiteral("6"));
auto prop1 = Materials::ModelProperty(QStringLiteral("10"),
QStringLiteral("9"),
QStringLiteral("8"),
QStringLiteral("7"),
QStringLiteral("6"),
QStringLiteral("5"));
auto prop2 = Materials::ModelProperty(QStringLiteral("a"),
QStringLiteral("b"),
QStringLiteral("c"),
QStringLiteral("d"),
QStringLiteral("e"),
QStringLiteral("f"));
EXPECT_EQ(prop.columns(), 0);
prop.addColumn(prop1);
EXPECT_EQ(prop.columns(), 1);
prop.addColumn(prop2);
EXPECT_EQ(prop.columns(), 2);
auto columns = prop.getColumns();
auto entry1 = columns.at(0);
EXPECT_EQ(entry1.getName(), QStringLiteral("10"));
EXPECT_EQ(entry1.getDisplayName(), QStringLiteral("9"));
EXPECT_EQ(entry1.getPropertyType(), QStringLiteral("8"));
EXPECT_EQ(entry1.getUnits(), QStringLiteral("7"));
EXPECT_EQ(entry1.getURL(), QStringLiteral("6"));
EXPECT_EQ(entry1.getDescription(), QStringLiteral("5"));
EXPECT_TRUE(entry1.getInheritance().isNull());
EXPECT_FALSE(entry1.isInherited());
EXPECT_EQ(entry1.columns(), 0);
auto entry2 = columns.at(1);
EXPECT_EQ(entry2.getName(), QStringLiteral("a"));
EXPECT_EQ(entry2.getDisplayName(), QStringLiteral("b"));
EXPECT_EQ(entry2.getPropertyType(), QStringLiteral("c"));
EXPECT_EQ(entry2.getUnits(), QStringLiteral("d"));
EXPECT_EQ(entry2.getURL(), QStringLiteral("e"));
EXPECT_EQ(entry2.getDescription(), QStringLiteral("f"));
EXPECT_TRUE(entry2.getInheritance().isNull());
EXPECT_FALSE(entry2.isInherited());
EXPECT_EQ(entry2.columns(), 0);
}
// clang-format on

View File

@@ -0,0 +1,9 @@
# SPDX-License-Identifier: LGPL-2.1-or-later
add_subdirectory(App)
target_link_libraries(Material_tests_run
gtest_main
${Google_Tests_LIBS}
Materials
)

View File

@@ -0,0 +1,9 @@
# SPDX-License-Identifier: LGPL-2.1-or-later
add_executable(Measure_tests_run
MeasureDistance.cpp
)
target_include_directories(Measure_tests_run PUBLIC
${CMAKE_BINARY_DIR}
)

View File

@@ -0,0 +1,71 @@
// SPDX-License-Identifier: LGPL-2.1-or-later
#include <src/App/InitApplication.h>
#include <App/Document.h>
#include <Mod/Measure/App/MeasureDistance.h>
#include <Mod/Part/App/PartFeature.h>
#include <gtest/gtest.h>
#include <BRepBuilderAPI_MakeEdge.hxx>
#include <gp_Circ.hxx>
#include <TopoDS_Edge.hxx>
#include <TopoDS_Wire.hxx>
class MeasureDistance: public ::testing::Test
{
protected:
static void SetUpTestSuite()
{
tests::initApplication();
}
void SetUp() override
{
document = App::GetApplication().newDocument("Measure");
}
void TearDown() override
{
App::GetApplication().closeDocument(document->getName());
}
App::Document* getDocument() const
{
return document;
}
TopoDS_Edge makeCircle(const gp_Pnt& pnt) const
{
gp_Circ circle;
circle.SetLocation(pnt);
circle.SetRadius(1.0);
BRepBuilderAPI_MakeEdge mkEdge(circle);
return mkEdge.Edge();
}
private:
App::Document* document {};
};
// NOLINTBEGIN
TEST_F(MeasureDistance, testCircleCircle)
{
App::Document* doc = getDocument();
auto p1 = doc->addObject<Part::Feature>("Shape1");
p1->Shape.setValue(makeCircle(gp_Pnt(0.0, 0.0, 0.0)));
auto p2 = doc->addObject<Part::Feature>("Shape2");
p2->Shape.setValue(makeCircle(gp_Pnt(3.0, 4.0, 0.0)));
auto md = doc->addObject<Measure::MeasureDistance>("Distance");
md->Element1.setValue(p1, {"Edge1"});
md->Element2.setValue(p2, {"Edge1"});
doc->recompute();
EXPECT_DOUBLE_EQ(md->Distance.getValue(), 5.0);
EXPECT_DOUBLE_EQ(md->DistanceX.getValue(), 3.0);
EXPECT_DOUBLE_EQ(md->DistanceY.getValue(), 4.0);
EXPECT_DOUBLE_EQ(md->DistanceZ.getValue(), 0.0);
EXPECT_EQ(md->Position1.getValue(), Base::Vector3d(0.0, 0.0, 0.0));
EXPECT_EQ(md->Position2.getValue(), Base::Vector3d(3.0, 4.0, 0.0));
}
// NOLINTEND

View File

@@ -0,0 +1,9 @@
# SPDX-License-Identifier: LGPL-2.1-or-later
add_subdirectory(App)
target_link_libraries(Measure_tests_run
gtest_main
${Google_Tests_LIBS}
Measure
)

View File

@@ -0,0 +1,11 @@
# SPDX-License-Identifier: LGPL-2.1-or-later
add_executable(Mesh_tests_run
Core/KDTree.cpp
Exporter.cpp
Importer.cpp
Mesh.cpp
MeshFeature.cpp
)
target_compile_definitions(Mesh_tests_run PRIVATE DATADIR="${CMAKE_SOURCE_DIR}/data")

View File

@@ -0,0 +1,95 @@
// SPDX-License-Identifier: LGPL-2.1-or-later
#include <gtest/gtest.h>
#include <Mod/Mesh/App/Core/KDTree.h>
// NOLINTBEGIN(cppcoreguidelines-*,readability-*)
class KDTreeTest: public ::testing::Test
{
protected:
void SetUp() override
{
points.emplace_back(0.F, 0.F, 0.F);
points.emplace_back(0.F, 0.F, 1.F);
points.emplace_back(0.F, 1.F, 0.F);
points.emplace_back(0.F, 1.F, 1.F);
points.emplace_back(1.F, 0.F, 0.F);
points.emplace_back(1.F, 0.F, 1.F);
points.emplace_back(1.F, 1.F, 0.F);
points.emplace_back(1.F, 1.F, 1.F);
}
void TearDown() override
{}
const std::vector<Base::Vector3f>& GetPoints() const
{
return points;
}
private:
std::vector<Base::Vector3f> points;
};
TEST_F(KDTreeTest, TestKDTreeEmpty)
{
MeshCore::MeshKDTree tree;
EXPECT_EQ(tree.IsEmpty(), true);
}
TEST_F(KDTreeTest, TestKDTreeNearestEmpty)
{
MeshCore::MeshKDTree tree;
Base::Vector3f pnt;
Base::Vector3f nor;
float dist;
EXPECT_EQ(tree.FindNearest(pnt, nor, dist), MeshCore::POINT_INDEX_MAX);
}
TEST_F(KDTreeTest, TestKDTreeNearest)
{
MeshCore::MeshKDTree tree;
tree.AddPoints(GetPoints());
EXPECT_EQ(tree.IsEmpty(), false);
Base::Vector3f nor;
float dist;
EXPECT_EQ(tree.FindNearest(Base::Vector3f(0.9F, 0.1F, 0.1F), nor, dist), 4);
}
TEST_F(KDTreeTest, TestKDTreeNearestMaxDist)
{
MeshCore::MeshKDTree tree;
tree.AddPoints(GetPoints());
EXPECT_EQ(tree.IsEmpty(), false);
Base::Vector3f nor;
float dist;
EXPECT_EQ(
tree.FindNearest(Base::Vector3f(0.9F, 0.1F, 0.1F), 0.0F, nor, dist),
MeshCore::POINT_INDEX_MAX
);
}
TEST_F(KDTreeTest, TestKDTreeFindExact)
{
MeshCore::MeshKDTree tree;
tree.AddPoints(GetPoints());
EXPECT_EQ(tree.FindExact(Base::Vector3f(0.1F, 0, 0)), MeshCore::POINT_INDEX_MAX);
EXPECT_EQ(tree.FindExact(Base::Vector3f(0, 0, 0)), 0);
}
TEST_F(KDTreeTest, TestKDTreeFindRange)
{
MeshCore::MeshKDTree tree;
tree.AddPoints(GetPoints());
std::vector<MeshCore::PointIndex> index;
std::vector<MeshCore::PointIndex> result = {0, 4};
tree.FindInRange(Base::Vector3f(0.5F, 0, 0), 0.6F, index);
EXPECT_EQ(index, result);
}
// NOLINTEND(cppcoreguidelines-*,readability-*)

View File

@@ -0,0 +1,152 @@
// SPDX-License-Identifier: LGPL-2.1-or-later
#include <gtest/gtest.h>
#include <Base/FileInfo.h>
#include <Base/Interpreter.h>
#include <App/Document.h>
#include <App/Part.h>
#include <src/App/InitApplication.h>
#include <Mod/Mesh/App/Exporter.h>
#include <Mod/Mesh/App/FeatureMeshSolid.h>
#include <Mod/Mesh/App/Mesh.h>
class ExporterTest: public ::testing::Test
{
protected:
static void SetUpTestSuite()
{
tests::initApplication();
}
void SetUp() override
{
document = App::GetApplication().newDocument("MeshExport");
fileInfo.setFile(Base::FileInfo::getTempFileName() + ".stl");
const double value = 10.0;
cube1 = document->addObject<Mesh::Cube>("Cube1");
cube1->Length.setValue(value);
cube1->Width.setValue(value);
cube1->Height.setValue(value);
cube2 = document->addObject<Mesh::Cube>("Cube2");
cube2->Length.setValue(value);
cube2->Width.setValue(value);
cube2->Height.setValue(value);
document->recompute();
}
void TearDown() override
{
App::GetApplication().closeDocument(document->getName());
fileInfo.deleteFile();
}
App::Document* getDocument() const
{
return document;
}
std::vector<App::DocumentObject*> getObjects() const
{
return {cube1, cube2};
}
App::DocumentObject* getMesh2() const
{
return cube2;
}
void setPlacementTo2ndCube(const Base::Placement& plm)
{
cube2->Placement.setValue(plm);
}
std::string getFileName() const
{
return fileInfo.filePath();
}
private:
Base::FileInfo fileInfo;
App::Document* document {};
Mesh::Cube* cube1 {};
Mesh::Cube* cube2 {};
};
// NOLINTBEGIN(cppcoreguidelines-*,readability-*)
TEST_F(ExporterTest, TestSingleMesh)
{
Base::Placement plm;
plm.setPosition(Base::Vector3d(10, 5, 2));
setPlacementTo2ndCube(plm);
// add extra scope because the file will be written when destroying the exporter
{
Mesh::MergeExporter exporter(getFileName(), MeshCore::MeshIO::Format::STL);
exporter.addObject(getMesh2(), 0.1F);
}
Mesh::MeshObject kernel;
EXPECT_TRUE(kernel.load(getFileName().c_str()));
auto bbox = kernel.getBoundBox();
EXPECT_DOUBLE_EQ(bbox.MinX, 5.0);
EXPECT_DOUBLE_EQ(bbox.MaxX, 15.0);
EXPECT_DOUBLE_EQ(bbox.MinY, 0.0);
EXPECT_DOUBLE_EQ(bbox.MaxY, 10.0);
EXPECT_DOUBLE_EQ(bbox.MinZ, -3.0);
EXPECT_DOUBLE_EQ(bbox.MaxZ, 7.0);
}
// Test for https://github.com/FreeCAD/FreeCAD/pull/11539
TEST_F(ExporterTest, TestMultipleMeshes)
{
Base::Placement plm;
plm.setPosition(Base::Vector3d(10, 5, 2));
setPlacementTo2ndCube(plm);
// add extra scope because the file will be written when destroying the exporter
{
Mesh::MergeExporter exporter(getFileName(), MeshCore::MeshIO::Format::STL);
for (auto obj : getObjects()) {
exporter.addObject(obj, 0.1F);
}
}
Mesh::MeshObject kernel;
EXPECT_TRUE(kernel.load(getFileName().c_str()));
auto bbox = kernel.getBoundBox();
EXPECT_DOUBLE_EQ(bbox.MinX, -5.0);
EXPECT_DOUBLE_EQ(bbox.MaxX, 15.0);
EXPECT_DOUBLE_EQ(bbox.MinY, -5.0);
EXPECT_DOUBLE_EQ(bbox.MaxY, 10.0);
EXPECT_DOUBLE_EQ(bbox.MinZ, -5.0);
EXPECT_DOUBLE_EQ(bbox.MaxZ, 7.0);
}
TEST_F(ExporterTest, TestMeshesInPart)
{
Base::Placement plm;
plm.setPosition(Base::Vector3d(10, 5, 2));
setPlacementTo2ndCube(plm);
// add extra scope because the file will be written when destroying the exporter
{
auto part = getDocument()->addObject<App::Part>("Part");
part->placement().setValue(plm);
part->addObjects(getObjects());
Mesh::MergeExporter exporter(getFileName(), MeshCore::MeshIO::Format::STL);
exporter.addObject(part, 0.1F);
}
Mesh::MeshObject kernel;
EXPECT_TRUE(kernel.load(getFileName().c_str()));
auto bbox = kernel.getBoundBox();
EXPECT_DOUBLE_EQ(bbox.MinX, 5.0);
EXPECT_DOUBLE_EQ(bbox.MaxX, 25.0);
EXPECT_DOUBLE_EQ(bbox.MinY, 0.0);
EXPECT_DOUBLE_EQ(bbox.MaxY, 15.0);
EXPECT_DOUBLE_EQ(bbox.MinZ, -3.0);
EXPECT_DOUBLE_EQ(bbox.MaxZ, 9.0);
}
// NOLINTEND(cppcoreguidelines-*,readability-*)

View File

@@ -0,0 +1,56 @@
// SPDX-License-Identifier: LGPL-2.1-or-later
#include <gtest/gtest.h>
#include <Base/FileInfo.h>
#include <Mod/Mesh/App/Core/IO/Reader3MF.h>
#include <Mod/Mesh/App/Core/IO/ReaderOBJ.h>
#include <xercesc/util/PlatformUtils.hpp>
#include <zipios++/fcoll.h>
class ImporterTest: public ::testing::Test
{
protected:
static void SetUpTestSuite()
{
XERCES_CPP_NAMESPACE::XMLPlatformUtils::Initialize();
}
};
// NOLINTBEGIN(cppcoreguidelines-*,readability-*)
TEST_F(ImporterTest, Test3MF)
{
std::string file(DATADIR);
file.append("/tests/mesh.3mf");
MeshCore::Reader3MF reader(file);
EXPECT_EQ(reader.Load(), true);
std::vector<int> ids = reader.GetMeshIds();
std::sort(ids.begin(), ids.end());
EXPECT_EQ(ids.size(), 2);
const MeshCore::MeshKernel& mesh1 = reader.GetMesh(ids[0]);
EXPECT_EQ(mesh1.CountPoints(), 8);
EXPECT_EQ(mesh1.CountEdges(), 18);
EXPECT_EQ(mesh1.CountFacets(), 12);
const MeshCore::MeshKernel& mesh2 = reader.GetMesh(ids[1]);
EXPECT_EQ(mesh2.CountPoints(), 652);
EXPECT_EQ(mesh2.CountEdges(), 1950);
EXPECT_EQ(mesh2.CountFacets(), 1300);
}
TEST_F(ImporterTest, TestOBJ)
{
std::string file(DATADIR);
file.append("/tests/mesh.obj");
MeshCore::MeshKernel kernel;
MeshCore::ReaderOBJ reader(kernel, nullptr);
EXPECT_EQ(reader.Load(file), true);
EXPECT_EQ(kernel.CountPoints(), 8);
EXPECT_EQ(kernel.CountFacets(), 12);
}
// NOLINTEND(cppcoreguidelines-*,readability-*)

View File

@@ -0,0 +1,111 @@
// SPDX-License-Identifier: LGPL-2.1-or-later
#include <gtest/gtest.h>
#include <Mod/Mesh/App/Mesh.h>
#include <Mod/Mesh/App/Core/Grid.h>
#include <src/App/InitApplication.h>
class MeshTest: public ::testing::Test
{
protected:
static void SetUpTestSuite()
{
tests::initApplication();
}
};
// NOLINTBEGIN(cppcoreguidelines-*,readability-*)
TEST_F(MeshTest, TestDefault)
{
MeshCore::MeshKernel kernel;
Base::Vector3f p1 {0, 0, 0};
Base::Vector3f p2 {0, 0, 1};
Base::Vector3f p3 {0, 1, 0};
kernel.AddFacet(MeshCore::MeshGeomFacet(p1, p2, p3));
EXPECT_EQ(kernel.CountPoints(), 3);
EXPECT_EQ(kernel.CountEdges(), 3);
EXPECT_EQ(kernel.CountFacets(), 1);
}
TEST_F(MeshTest, TestGrid1OfPlanarMesh)
{
MeshCore::MeshKernel kernel;
Base::Vector3f p1 {0, 0, 0};
Base::Vector3f p2 {1, 0, 0};
Base::Vector3f p3 {0, 1, 0};
Base::Vector3f p4 {1, 1, 0};
kernel.AddFacet(MeshCore::MeshGeomFacet(p1, p2, p3));
kernel.AddFacet(MeshCore::MeshGeomFacet(p3, p2, p4));
MeshCore::MeshFacetGrid grid(kernel, 10);
unsigned long countX {};
unsigned long countY {};
unsigned long countZ {};
grid.GetCtGrids(countX, countY, countZ);
EXPECT_EQ(countX, 1);
EXPECT_EQ(countY, 1);
EXPECT_EQ(countZ, 1);
}
TEST_F(MeshTest, TestGrid2OfPlanarMesh)
{
MeshCore::MeshKernel kernel;
Base::Vector3f p1 {0, 0, 0};
Base::Vector3f p2 {1, 0, 0};
Base::Vector3f p3 {0, 1, 0};
Base::Vector3f p4 {1, 1, 0};
kernel.AddFacet(MeshCore::MeshGeomFacet(p1, p2, p3));
kernel.AddFacet(MeshCore::MeshGeomFacet(p3, p2, p4));
MeshCore::MeshFacetGrid grid(kernel);
unsigned long countX {};
unsigned long countY {};
unsigned long countZ {};
grid.GetCtGrids(countX, countY, countZ);
EXPECT_EQ(countX, 1);
EXPECT_EQ(countY, 1);
EXPECT_EQ(countZ, 1);
}
TEST_F(MeshTest, TestGrid1OfAlmostPlanarMesh)
{
MeshCore::MeshKernel kernel;
Base::Vector3f p1 {0, 0, 0};
Base::Vector3f p2 {1, 0, 0};
Base::Vector3f p3 {0, 1, 0};
Base::Vector3f p4 {1, 1, 1.0e-18F};
kernel.AddFacet(MeshCore::MeshGeomFacet(p1, p2, p3));
kernel.AddFacet(MeshCore::MeshGeomFacet(p3, p2, p4));
MeshCore::MeshFacetGrid grid(kernel, 10);
unsigned long countX {};
unsigned long countY {};
unsigned long countZ {};
grid.GetCtGrids(countX, countY, countZ);
EXPECT_EQ(countX, 1);
EXPECT_EQ(countY, 1);
EXPECT_EQ(countZ, 1);
}
TEST_F(MeshTest, TestGrid2OfAlmostPlanarMesh)
{
MeshCore::MeshKernel kernel;
Base::Vector3f p1 {0, 0, 0};
Base::Vector3f p2 {1, 0, 0};
Base::Vector3f p3 {0, 1, 0};
Base::Vector3f p4 {1, 1, 1.0e-18F};
kernel.AddFacet(MeshCore::MeshGeomFacet(p1, p2, p3));
kernel.AddFacet(MeshCore::MeshGeomFacet(p3, p2, p4));
MeshCore::MeshFacetGrid grid(kernel);
unsigned long countX {};
unsigned long countY {};
unsigned long countZ {};
grid.GetCtGrids(countX, countY, countZ);
EXPECT_EQ(countX, 1);
EXPECT_EQ(countY, 1);
EXPECT_EQ(countZ, 1);
}
// NOLINTEND(cppcoreguidelines-*,readability-*)

Some files were not shown because too many files have changed in this diff Show More