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

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