summaryrefslogtreecommitdiff
path: root/tests
diff options
context:
space:
mode:
Diffstat (limited to 'tests')
-rw-r--r--tests/SCsub5
-rw-r--r--tests/data/translations.csv3
-rw-r--r--tests/test_aabb.h381
-rw-r--r--tests/test_astar.cpp409
-rw-r--r--tests/test_astar.h332
-rw-r--r--tests/test_basis.cpp325
-rw-r--r--tests/test_basis.h251
-rw-r--r--tests/test_class_db.cpp882
-rw-r--r--tests/test_class_db.h797
-rw-r--r--tests/test_color.h207
-rw-r--r--tests/test_command_queue.h481
-rw-r--r--tests/test_config_file.h156
-rw-r--r--tests/test_crypto.h74
-rw-r--r--tests/test_curve.h221
-rw-r--r--tests/test_expression.h444
-rw-r--r--tests/test_file_access.h64
-rw-r--r--tests/test_gdscript.cpp187
-rw-r--r--tests/test_gradient.h151
-rw-r--r--tests/test_gui.cpp9
-rw-r--r--tests/test_json.h166
-rw-r--r--tests/test_list.h548
-rw-r--r--tests/test_lru.h100
-rw-r--r--tests/test_macros.cpp (renamed from tests/test_gdscript.h)28
-rw-r--r--tests/test_macros.h126
-rw-r--r--tests/test_main.cpp135
-rw-r--r--tests/test_main.h5
-rw-r--r--tests/test_math.cpp19
-rw-r--r--tests/test_method_bind.h164
-rw-r--r--tests/test_node_path.h172
-rw-r--r--tests/test_oa_hash_map.cpp3
-rw-r--r--tests/test_object.h92
-rw-r--r--tests/test_ordered_hash_map.cpp175
-rw-r--r--tests/test_ordered_hash_map.h101
-rw-r--r--tests/test_paged_array.h153
-rw-r--r--tests/test_pck_packer.h114
-rw-r--r--tests/test_physics_2d.cpp5
-rw-r--r--tests/test_physics_3d.cpp5
-rw-r--r--tests/test_random_number_generator.h275
-rw-r--r--tests/test_rect2.h467
-rw-r--r--tests/test_render.cpp5
-rw-r--r--tests/test_shader_lang.cpp5
-rw-r--r--tests/test_string.h586
-rw-r--r--tests/test_text_server.h249
-rw-r--r--tests/test_validate_testing.h153
-rw-r--r--tests/test_variant.h7
45 files changed, 7074 insertions, 2163 deletions
diff --git a/tests/SCsub b/tests/SCsub
index 84c9fc1ffe..7aab28531d 100644
--- a/tests/SCsub
+++ b/tests/SCsub
@@ -6,8 +6,9 @@ env.tests_sources = []
env_tests = env.Clone()
-# Enable test framework and inform it of configuration method.
-env_tests.Append(CPPDEFINES=["DOCTEST_CONFIG_IMPLEMENT"])
+# Include GDNative headers.
+if env["module_gdnative_enabled"]:
+ env_tests.Append(CPPPATH=["#modules/gdnative/include"])
# We must disable the THREAD_LOCAL entirely in doctest to prevent crashes on debugging
# Since we link with /MT thread_local is always expired when the header is used
diff --git a/tests/data/translations.csv b/tests/data/translations.csv
new file mode 100644
index 0000000000..4c9ad4996a
--- /dev/null
+++ b/tests/data/translations.csv
@@ -0,0 +1,3 @@
+keys,en,de
+GOOD_MORNING,"Good Morning","Guten Morgen"
+GOOD_EVENING,"Good Evening",""
diff --git a/tests/test_aabb.h b/tests/test_aabb.h
new file mode 100644
index 0000000000..404a73a95f
--- /dev/null
+++ b/tests/test_aabb.h
@@ -0,0 +1,381 @@
+/*************************************************************************/
+/* test_aabb.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+#ifndef TEST_AABB_H
+#define TEST_AABB_H
+
+#include "core/math/aabb.h"
+#include "core/string/print_string.h"
+#include "tests/test_macros.h"
+
+#include "thirdparty/doctest/doctest.h"
+
+namespace TestAABB {
+
+TEST_CASE("[AABB] Constructor methods") {
+ const AABB aabb = AABB(Vector3(-1.5, 2, -2.5), Vector3(4, 5, 6));
+ const AABB aabb_copy = AABB(aabb);
+
+ CHECK_MESSAGE(
+ aabb == aabb_copy,
+ "AABBs created with the same dimensions but by different methods should be equal.");
+}
+
+TEST_CASE("[AABB] String conversion") {
+ CHECK_MESSAGE(
+ String(AABB(Vector3(-1.5, 2, -2.5), Vector3(4, 5, 6))) == "-1.5, 2, -2.5 - 4, 5, 6",
+ "The string representation shouild match the expected value.");
+}
+
+TEST_CASE("[AABB] Basic getters") {
+ const AABB aabb = AABB(Vector3(-1.5, 2, -2.5), Vector3(4, 5, 6));
+ CHECK_MESSAGE(
+ aabb.get_position().is_equal_approx(Vector3(-1.5, 2, -2.5)),
+ "get_position() should return the expected value.");
+ CHECK_MESSAGE(
+ aabb.get_size().is_equal_approx(Vector3(4, 5, 6)),
+ "get_size() should return the expected value.");
+ CHECK_MESSAGE(
+ aabb.get_end().is_equal_approx(Vector3(2.5, 7, 3.5)),
+ "get_end() should return the expected value.");
+}
+
+TEST_CASE("[AABB] Basic setters") {
+ AABB aabb = AABB(Vector3(-1.5, 2, -2.5), Vector3(4, 5, 6));
+ aabb.set_end(Vector3(100, 0, 100));
+ CHECK_MESSAGE(
+ aabb.is_equal_approx(AABB(Vector3(-1.5, 2, -2.5), Vector3(101.5, -2, 102.5))),
+ "set_end() should result in the expected AABB.");
+
+ aabb = AABB(Vector3(-1.5, 2, -2.5), Vector3(4, 5, 6));
+ aabb.set_position(Vector3(-1000, -2000, -3000));
+ CHECK_MESSAGE(
+ aabb.is_equal_approx(AABB(Vector3(-1000, -2000, -3000), Vector3(4, 5, 6))),
+ "set_position() should result in the expected AABB.");
+
+ aabb = AABB(Vector3(-1.5, 2, -2.5), Vector3(4, 5, 6));
+ aabb.set_size(Vector3(0, 0, -50));
+ CHECK_MESSAGE(
+ aabb.is_equal_approx(AABB(Vector3(-1.5, 2, -2.5), Vector3(0, 0, -50))),
+ "set_size() should result in the expected AABB.");
+}
+
+TEST_CASE("[AABB] Area getters") {
+ AABB aabb = AABB(Vector3(-1.5, 2, -2.5), Vector3(4, 5, 6));
+ CHECK_MESSAGE(
+ Math::is_equal_approx(aabb.get_area(), 120),
+ "get_area() should return the expected value with positive size.");
+ CHECK_MESSAGE(
+ !aabb.has_no_area(),
+ "Non-empty volumetric AABB should have an area.");
+
+ aabb = AABB(Vector3(-1.5, 2, -2.5), Vector3(-4, 5, 6));
+ CHECK_MESSAGE(
+ Math::is_equal_approx(aabb.get_area(), -120),
+ "get_area() should return the expected value with negative size (1 component).");
+
+ aabb = AABB(Vector3(-1.5, 2, -2.5), Vector3(-4, -5, 6));
+ CHECK_MESSAGE(
+ Math::is_equal_approx(aabb.get_area(), 120),
+ "get_area() should return the expected value with negative size (2 components).");
+
+ aabb = AABB(Vector3(-1.5, 2, -2.5), Vector3(-4, -5, -6));
+ CHECK_MESSAGE(
+ Math::is_equal_approx(aabb.get_area(), -120),
+ "get_area() should return the expected value with negative size (3 components).");
+
+ aabb = AABB(Vector3(-1.5, 2, -2.5), Vector3(4, 0, 6));
+ CHECK_MESSAGE(
+ aabb.has_no_area(),
+ "Non-empty flat AABB should not have an area.");
+
+ CHECK_MESSAGE(
+ AABB().has_no_area(),
+ "Empty AABB should not have an area.");
+}
+
+TEST_CASE("[AABB] Surface getters") {
+ AABB aabb = AABB(Vector3(-1.5, 2, -2.5), Vector3(4, 5, 6));
+ CHECK_MESSAGE(
+ !aabb.has_no_surface(),
+ "Non-empty volumetric AABB should have an surface.");
+
+ aabb = AABB(Vector3(-1.5, 2, -2.5), Vector3(4, 0, 6));
+ CHECK_MESSAGE(
+ !aabb.has_no_surface(),
+ "Non-empty flat AABB should have a surface.");
+
+ CHECK_MESSAGE(
+ AABB().has_no_surface(),
+ "Empty AABB should not have an surface.");
+}
+
+TEST_CASE("[AABB] Intersection") {
+ const AABB aabb_big = AABB(Vector3(-1.5, 2, -2.5), Vector3(4, 5, 6));
+
+ AABB aabb_small = AABB(Vector3(-1.5, 2, -2.5), Vector3(1, 1, 1));
+ CHECK_MESSAGE(
+ aabb_big.intersects(aabb_small),
+ "intersects() with fully contained AABB (touching the edge) should return the expected result.");
+
+ aabb_small = AABB(Vector3(0.5, 1.5, -2), Vector3(1, 1, 1));
+ CHECK_MESSAGE(
+ aabb_big.intersects(aabb_small),
+ "intersects() with partially contained AABB (overflowing on Y axis) should return the expected result.");
+
+ aabb_small = AABB(Vector3(10, -10, -10), Vector3(1, 1, 1));
+ CHECK_MESSAGE(
+ !aabb_big.intersects(aabb_small),
+ "intersects() with non-contained AABB should return the expected result.");
+
+ aabb_small = AABB(Vector3(-1.5, 2, -2.5), Vector3(1, 1, 1));
+ CHECK_MESSAGE(
+ aabb_big.intersection(aabb_small).is_equal_approx(aabb_small),
+ "intersection() with fully contained AABB (touching the edge) should return the expected result.");
+
+ aabb_small = AABB(Vector3(0.5, 1.5, -2), Vector3(1, 1, 1));
+ CHECK_MESSAGE(
+ aabb_big.intersection(aabb_small).is_equal_approx(AABB(Vector3(0.5, 2, -2), Vector3(1, 0.5, 1))),
+ "intersection() with partially contained AABB (overflowing on Y axis) should return the expected result.");
+
+ aabb_small = AABB(Vector3(10, -10, -10), Vector3(1, 1, 1));
+ CHECK_MESSAGE(
+ aabb_big.intersection(aabb_small).is_equal_approx(AABB()),
+ "intersection() with non-contained AABB should return the expected result.");
+
+ CHECK_MESSAGE(
+ aabb_big.intersects_plane(Plane(Vector3(0, 1, 0), 4)),
+ "intersects_plane() should return the expected result.");
+ CHECK_MESSAGE(
+ aabb_big.intersects_plane(Plane(Vector3(0, -1, 0), -4)),
+ "intersects_plane() should return the expected result.");
+ CHECK_MESSAGE(
+ !aabb_big.intersects_plane(Plane(Vector3(0, 1, 0), 200)),
+ "intersects_plane() should return the expected result.");
+
+ CHECK_MESSAGE(
+ aabb_big.intersects_segment(Vector3(1, 3, 0), Vector3(0, 3, 0)),
+ "intersects_segment() should return the expected result.");
+ CHECK_MESSAGE(
+ aabb_big.intersects_segment(Vector3(0, 3, 0), Vector3(0, -300, 0)),
+ "intersects_segment() should return the expected result.");
+ CHECK_MESSAGE(
+ aabb_big.intersects_segment(Vector3(-50, 3, -50), Vector3(50, 3, 50)),
+ "intersects_segment() should return the expected result.");
+ CHECK_MESSAGE(
+ !aabb_big.intersects_segment(Vector3(-50, 25, -50), Vector3(50, 25, 50)),
+ "intersects_segment() should return the expected result.");
+ CHECK_MESSAGE(
+ aabb_big.intersects_segment(Vector3(0, 3, 0), Vector3(0, 3, 0)),
+ "intersects_segment() should return the expected result with segment of length 0.");
+ CHECK_MESSAGE(
+ !aabb_big.intersects_segment(Vector3(0, 300, 0), Vector3(0, 300, 0)),
+ "intersects_segment() should return the expected result with segment of length 0.");
+}
+
+TEST_CASE("[AABB] Merging") {
+ const AABB aabb_big = AABB(Vector3(-1.5, 2, -2.5), Vector3(4, 5, 6));
+
+ AABB aabb_small = AABB(Vector3(-1.5, 2, -2.5), Vector3(1, 1, 1));
+ CHECK_MESSAGE(
+ aabb_big.merge(aabb_small).is_equal_approx(aabb_big),
+ "merge() with fully contained AABB (touching the edge) should return the expected result.");
+
+ aabb_small = AABB(Vector3(0.5, 1.5, -2), Vector3(1, 1, 1));
+ CHECK_MESSAGE(
+ aabb_big.merge(aabb_small).is_equal_approx(AABB(Vector3(-1.5, 1.5, -2.5), Vector3(4, 5.5, 6))),
+ "merge() with partially contained AABB (overflowing on Y axis) should return the expected result.");
+
+ aabb_small = AABB(Vector3(10, -10, -10), Vector3(1, 1, 1));
+ CHECK_MESSAGE(
+ aabb_big.merge(aabb_small).is_equal_approx(AABB(Vector3(-1.5, -10, -10), Vector3(12.5, 17, 13.5))),
+ "merge() with non-contained AABB should return the expected result.");
+}
+
+TEST_CASE("[AABB] Encloses") {
+ const AABB aabb_big = AABB(Vector3(-1.5, 2, -2.5), Vector3(4, 5, 6));
+
+ AABB aabb_small = AABB(Vector3(-1.5, 2, -2.5), Vector3(1, 1, 1));
+ CHECK_MESSAGE(
+ aabb_big.encloses(aabb_small),
+ "encloses() with fully contained AABB (touching the edge) should return the expected result.");
+
+ aabb_small = AABB(Vector3(0.5, 1.5, -2), Vector3(1, 1, 1));
+ CHECK_MESSAGE(
+ !aabb_big.encloses(aabb_small),
+ "encloses() with partially contained AABB (overflowing on Y axis) should return the expected result.");
+
+ aabb_small = AABB(Vector3(10, -10, -10), Vector3(1, 1, 1));
+ CHECK_MESSAGE(
+ !aabb_big.encloses(aabb_small),
+ "encloses() with non-contained AABB should return the expected result.");
+}
+
+TEST_CASE("[AABB] Get endpoints") {
+ const AABB aabb = AABB(Vector3(-1.5, 2, -2.5), Vector3(4, 5, 6));
+ CHECK_MESSAGE(
+ aabb.get_endpoint(0).is_equal_approx(Vector3(-1.5, 2, -2.5)),
+ "The endpoint at index 0 should match the expected value.");
+ CHECK_MESSAGE(
+ aabb.get_endpoint(1).is_equal_approx(Vector3(-1.5, 2, 3.5)),
+ "The endpoint at index 1 should match the expected value.");
+ CHECK_MESSAGE(
+ aabb.get_endpoint(2).is_equal_approx(Vector3(-1.5, 7, -2.5)),
+ "The endpoint at index 2 should match the expected value.");
+ CHECK_MESSAGE(
+ aabb.get_endpoint(3).is_equal_approx(Vector3(-1.5, 7, 3.5)),
+ "The endpoint at index 3 should match the expected value.");
+ CHECK_MESSAGE(
+ aabb.get_endpoint(4).is_equal_approx(Vector3(2.5, 2, -2.5)),
+ "The endpoint at index 4 should match the expected value.");
+ CHECK_MESSAGE(
+ aabb.get_endpoint(5).is_equal_approx(Vector3(2.5, 2, 3.5)),
+ "The endpoint at index 5 should match the expected value.");
+ CHECK_MESSAGE(
+ aabb.get_endpoint(6).is_equal_approx(Vector3(2.5, 7, -2.5)),
+ "The endpoint at index 6 should match the expected value.");
+ CHECK_MESSAGE(
+ aabb.get_endpoint(7).is_equal_approx(Vector3(2.5, 7, 3.5)),
+ "The endpoint at index 7 should match the expected value.");
+
+ ERR_PRINT_OFF;
+ CHECK_MESSAGE(
+ aabb.get_endpoint(8).is_equal_approx(Vector3()),
+ "The endpoint at invalid index 8 should match the expected value.");
+ CHECK_MESSAGE(
+ aabb.get_endpoint(-1).is_equal_approx(Vector3()),
+ "The endpoint at invalid index -1 should match the expected value.");
+ ERR_PRINT_ON;
+}
+
+TEST_CASE("[AABB] Get longest/shortest axis") {
+ const AABB aabb = AABB(Vector3(-1.5, 2, -2.5), Vector3(4, 5, 6));
+ CHECK_MESSAGE(
+ aabb.get_longest_axis().is_equal_approx(Vector3(0, 0, 1)),
+ "get_longest_axis() should return the expected value.");
+ CHECK_MESSAGE(
+ aabb.get_longest_axis_index() == Vector3::AXIS_Z,
+ "get_longest_axis() should return the expected value.");
+ CHECK_MESSAGE(
+ Math::is_equal_approx(aabb.get_longest_axis_size(), 6),
+ "get_longest_axis() should return the expected value.");
+
+ CHECK_MESSAGE(
+ aabb.get_shortest_axis().is_equal_approx(Vector3(1, 0, 0)),
+ "get_shortest_axis() should return the expected value.");
+ CHECK_MESSAGE(
+ aabb.get_shortest_axis_index() == Vector3::AXIS_X,
+ "get_shortest_axis() should return the expected value.");
+ CHECK_MESSAGE(
+ Math::is_equal_approx(aabb.get_shortest_axis_size(), 4),
+ "get_shortest_axis() should return the expected value.");
+}
+
+#ifndef _MSC_VER
+#warning Support tests need to be re-done
+#endif
+
+/* Support function was actually broken. As it was fixed, the tests now fail. Tests need to be re-done.
+
+TEST_CASE("[AABB] Get support") {
+ const AABB aabb = AABB(Vector3(-1.5, 2, -2.5), Vector3(4, 5, 6));
+ CHECK_MESSAGE(
+ aabb.get_support(Vector3(1, 0, 0)).is_equal_approx(Vector3(-1.5, 7, 3.5)),
+ "get_support() should return the expected value.");
+ CHECK_MESSAGE(
+ aabb.get_support(Vector3(0.5, 1, 0)).is_equal_approx(Vector3(-1.5, 2, 3.5)),
+ "get_support() should return the expected value.");
+ CHECK_MESSAGE(
+ aabb.get_support(Vector3(0.5, 1, -400)).is_equal_approx(Vector3(-1.5, 2, 3.5)),
+ "get_support() should return the expected value.");
+ CHECK_MESSAGE(
+ aabb.get_support(Vector3(0, -1, 0)).is_equal_approx(Vector3(2.5, 7, 3.5)),
+ "get_support() should return the expected value.");
+ CHECK_MESSAGE(
+ aabb.get_support(Vector3(0, -0.1, 0)).is_equal_approx(Vector3(2.5, 7, 3.5)),
+ "get_support() should return the expected value.");
+ CHECK_MESSAGE(
+ aabb.get_support(Vector3()).is_equal_approx(Vector3(2.5, 7, 3.5)),
+ "get_support() should return the expected value with a null vector.");
+}
+*/
+TEST_CASE("[AABB] Grow") {
+ const AABB aabb = AABB(Vector3(-1.5, 2, -2.5), Vector3(4, 5, 6));
+ CHECK_MESSAGE(
+ aabb.grow(0.25).is_equal_approx(AABB(Vector3(-1.75, 1.75, -2.75), Vector3(4.5, 5.5, 6.5))),
+ "grow() with positive value should return the expected AABB.");
+ CHECK_MESSAGE(
+ aabb.grow(-0.25).is_equal_approx(AABB(Vector3(-1.25, 2.25, -2.25), Vector3(3.5, 4.5, 5.5))),
+ "grow() with negative value should return the expected AABB.");
+ CHECK_MESSAGE(
+ aabb.grow(-10).is_equal_approx(AABB(Vector3(8.5, 12, 7.5), Vector3(-16, -15, -14))),
+ "grow() with large negative value should return the expected AABB.");
+}
+
+TEST_CASE("[AABB] Has point") {
+ const AABB aabb = AABB(Vector3(-1.5, 2, -2.5), Vector3(4, 5, 6));
+ CHECK_MESSAGE(
+ aabb.has_point(Vector3(-1, 3, 0)),
+ "has_point() with contained point should return the expected value.");
+ CHECK_MESSAGE(
+ aabb.has_point(Vector3(2, 3, 0)),
+ "has_point() with contained point should return the expected value.");
+ CHECK_MESSAGE(
+ aabb.has_point(Vector3(-1.5, 3, 0)),
+ "has_point() with contained point on negative edge should return the expected value.");
+ CHECK_MESSAGE(
+ aabb.has_point(Vector3(2.5, 3, 0)),
+ "has_point() with contained point on positive edge should return the expected value.");
+ CHECK_MESSAGE(
+ !aabb.has_point(Vector3(-20, 0, 0)),
+ "has_point() with non-contained point should return the expected value.");
+}
+
+TEST_CASE("[AABB] Expanding") {
+ const AABB aabb = AABB(Vector3(-1.5, 2, -2.5), Vector3(4, 5, 6));
+ CHECK_MESSAGE(
+ aabb.expand(Vector3(-1, 3, 0)).is_equal_approx(aabb),
+ "expand() with contained point should return the expected AABB.");
+ CHECK_MESSAGE(
+ aabb.expand(Vector3(2, 3, 0)).is_equal_approx(aabb),
+ "expand() with contained point should return the expected AABB.");
+ CHECK_MESSAGE(
+ aabb.expand(Vector3(-1.5, 3, 0)).is_equal_approx(aabb),
+ "expand() with contained point on negative edge should return the expected AABB.");
+ CHECK_MESSAGE(
+ aabb.expand(Vector3(2.5, 3, 0)).is_equal_approx(aabb),
+ "expand() with contained point on positive edge should return the expected AABB.");
+ CHECK_MESSAGE(
+ aabb.expand(Vector3(-20, 0, 0)).is_equal_approx(AABB(Vector3(-20, 0, -2.5), Vector3(22.5, 7, 6))),
+ "expand() with non-contained point should return the expected AABB.");
+}
+} // namespace TestAABB
+
+#endif // TEST_AABB_H
diff --git a/tests/test_astar.cpp b/tests/test_astar.cpp
deleted file mode 100644
index cb5fcfe37b..0000000000
--- a/tests/test_astar.cpp
+++ /dev/null
@@ -1,409 +0,0 @@
-/*************************************************************************/
-/* test_astar.cpp */
-/*************************************************************************/
-/* This file is part of: */
-/* GODOT ENGINE */
-/* https://godotengine.org */
-/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
-/* */
-/* Permission is hereby granted, free of charge, to any person obtaining */
-/* a copy of this software and associated documentation files (the */
-/* "Software"), to deal in the Software without restriction, including */
-/* without limitation the rights to use, copy, modify, merge, publish, */
-/* distribute, sublicense, and/or sell copies of the Software, and to */
-/* permit persons to whom the Software is furnished to do so, subject to */
-/* the following conditions: */
-/* */
-/* The above copyright notice and this permission notice shall be */
-/* included in all copies or substantial portions of the Software. */
-/* */
-/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
-/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
-/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
-/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
-/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
-/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
-/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
-/*************************************************************************/
-
-#include "test_astar.h"
-
-#include "core/math/a_star.h"
-#include "core/math/math_funcs.h"
-#include "core/os/os.h"
-
-#include <math.h>
-#include <stdio.h>
-
-namespace TestAStar {
-
-class ABCX : public AStar {
-public:
- enum { A,
- B,
- C,
- X };
-
- ABCX() {
- add_point(A, Vector3(0, 0, 0));
- add_point(B, Vector3(1, 0, 0));
- add_point(C, Vector3(0, 1, 0));
- add_point(X, Vector3(0, 0, 1));
- connect_points(A, B);
- connect_points(A, C);
- connect_points(B, C);
- connect_points(X, A);
- }
-
- // Disable heuristic completely
- float _compute_cost(int p_from, int p_to) {
- if (p_from == A && p_to == C) {
- return 1000;
- }
- return 100;
- }
-};
-
-bool test_abc() {
- ABCX abcx;
- Vector<int> path = abcx.get_id_path(ABCX::A, ABCX::C);
- bool ok = path.size() == 3;
- int i = 0;
- ok = ok && path[i++] == ABCX::A;
- ok = ok && path[i++] == ABCX::B;
- ok = ok && path[i++] == ABCX::C;
- return ok;
-}
-
-bool test_abcx() {
- ABCX abcx;
- Vector<int> path = abcx.get_id_path(ABCX::X, ABCX::C);
- bool ok = path.size() == 4;
- int i = 0;
- ok = ok && path[i++] == ABCX::X;
- ok = ok && path[i++] == ABCX::A;
- ok = ok && path[i++] == ABCX::B;
- ok = ok && path[i++] == ABCX::C;
- return ok;
-}
-
-bool test_add_remove() {
- AStar a;
- bool ok = true;
-
- // Manual tests
- a.add_point(1, Vector3(0, 0, 0));
- a.add_point(2, Vector3(0, 1, 0));
- a.add_point(3, Vector3(1, 1, 0));
- a.add_point(4, Vector3(2, 0, 0));
- a.connect_points(1, 2, true);
- a.connect_points(1, 3, true);
- a.connect_points(1, 4, false);
-
- ok = ok && (a.are_points_connected(2, 1));
- ok = ok && (a.are_points_connected(4, 1));
- ok = ok && (a.are_points_connected(2, 1, false));
- ok = ok && (a.are_points_connected(4, 1, false) == false);
-
- a.disconnect_points(1, 2, true);
- ok = ok && (a.get_point_connections(1).size() == 2); // 3, 4
- ok = ok && (a.get_point_connections(2).size() == 0);
-
- a.disconnect_points(4, 1, false);
- ok = ok && (a.get_point_connections(1).size() == 2); // 3, 4
- ok = ok && (a.get_point_connections(4).size() == 0);
-
- a.disconnect_points(4, 1, true);
- ok = ok && (a.get_point_connections(1).size() == 1); // 3
- ok = ok && (a.get_point_connections(4).size() == 0);
-
- a.connect_points(2, 3, false);
- ok = ok && (a.get_point_connections(2).size() == 1); // 3
- ok = ok && (a.get_point_connections(3).size() == 1); // 1
-
- a.connect_points(2, 3, true);
- ok = ok && (a.get_point_connections(2).size() == 1); // 3
- ok = ok && (a.get_point_connections(3).size() == 2); // 1, 2
-
- a.disconnect_points(2, 3, false);
- ok = ok && (a.get_point_connections(2).size() == 0);
- ok = ok && (a.get_point_connections(3).size() == 2); // 1, 2
-
- a.connect_points(4, 3, true);
- ok = ok && (a.get_point_connections(3).size() == 3); // 1, 2, 4
- ok = ok && (a.get_point_connections(4).size() == 1); // 3
-
- a.disconnect_points(3, 4, false);
- ok = ok && (a.get_point_connections(3).size() == 2); // 1, 2
- ok = ok && (a.get_point_connections(4).size() == 1); // 3
-
- a.remove_point(3);
- ok = ok && (a.get_point_connections(1).size() == 0);
- ok = ok && (a.get_point_connections(2).size() == 0);
- ok = ok && (a.get_point_connections(4).size() == 0);
-
- a.add_point(0, Vector3(0, -1, 0));
- a.add_point(3, Vector3(2, 1, 0));
- // 0: (0, -1)
- // 1: (0, 0)
- // 2: (0, 1)
- // 3: (2, 1)
- // 4: (2, 0)
-
- // Tests for get_closest_position_in_segment
- a.connect_points(2, 3);
- ok = ok && (a.get_closest_position_in_segment(Vector3(0.5, 0.5, 0)) == Vector3(0.5, 1, 0));
-
- a.connect_points(3, 4);
- a.connect_points(0, 3);
- a.connect_points(1, 4);
- a.disconnect_points(1, 4, false);
- a.disconnect_points(4, 3, false);
- a.disconnect_points(3, 4, false);
- // Remaining edges: <2, 3>, <0, 3>, <1, 4> (directed)
- ok = ok && (a.get_closest_position_in_segment(Vector3(2, 0.5, 0)) == Vector3(1.75, 0.75, 0));
- ok = ok && (a.get_closest_position_in_segment(Vector3(-1, 0.2, 0)) == Vector3(0, 0, 0));
- ok = ok && (a.get_closest_position_in_segment(Vector3(3, 2, 0)) == Vector3(2, 1, 0));
-
- Math::seed(0);
-
- // Random tests for connectivity checks
- for (int i = 0; i < 20000; i++) {
- int u = Math::rand() % 5;
- int v = Math::rand() % 4;
- if (u == v) {
- v = 4;
- }
- if (Math::rand() % 2 == 1) {
- // Add a (possibly existing) directed edge and confirm connectivity
- a.connect_points(u, v, false);
- ok = ok && (a.are_points_connected(u, v, false));
- } else {
- // Remove a (possibly nonexistent) directed edge and confirm disconnectivity
- a.disconnect_points(u, v, false);
- ok = ok && (a.are_points_connected(u, v, false) == false);
- }
- }
-
- // Random tests for point removal
- for (int i = 0; i < 20000; i++) {
- a.clear();
- for (int j = 0; j < 5; j++) {
- a.add_point(j, Vector3(0, 0, 0));
- }
-
- // Add or remove random edges
- for (int j = 0; j < 10; j++) {
- int u = Math::rand() % 5;
- int v = Math::rand() % 4;
- if (u == v) {
- v = 4;
- }
- if (Math::rand() % 2 == 1) {
- a.connect_points(u, v, false);
- } else {
- a.disconnect_points(u, v, false);
- }
- }
-
- // Remove point 0
- a.remove_point(0);
- // White box: this will check all edges remaining in the segments set
- for (int j = 1; j < 5; j++) {
- ok = ok && (a.are_points_connected(0, j, true) == false);
- }
- }
-
- // It's been great work, cheers \(^ ^)/
- return ok;
-}
-
-bool test_solutions() {
- // Random stress tests with Floyd-Warshall
-
- const int N = 30;
- Math::seed(0);
-
- for (int test = 0; test < 1000; test++) {
- AStar a;
- Vector3 p[N];
- bool adj[N][N] = { { false } };
-
- // Assign initial coordinates
- for (int u = 0; u < N; u++) {
- p[u].x = Math::rand() % 100;
- p[u].y = Math::rand() % 100;
- p[u].z = Math::rand() % 100;
- a.add_point(u, p[u]);
- }
-
- // Generate a random sequence of operations
- for (int i = 0; i < 1000; i++) {
- // Pick two different vertices
- int u, v;
- u = Math::rand() % N;
- v = Math::rand() % (N - 1);
- if (u == v) {
- v = N - 1;
- }
-
- // Pick a random operation
- int op = Math::rand();
- switch (op % 9) {
- case 0:
- case 1:
- case 2:
- case 3:
- case 4:
- case 5:
- // Add edge (u, v); possibly bidirectional
- a.connect_points(u, v, op % 2);
- adj[u][v] = true;
- if (op % 2) {
- adj[v][u] = true;
- }
- break;
- case 6:
- case 7:
- // Remove edge (u, v); possibly bidirectional
- a.disconnect_points(u, v, op % 2);
- adj[u][v] = false;
- if (op % 2) {
- adj[v][u] = false;
- }
- break;
- case 8:
- // Remove point u and add it back; clears adjacent edges and changes coordinates
- a.remove_point(u);
- p[u].x = Math::rand() % 100;
- p[u].y = Math::rand() % 100;
- p[u].z = Math::rand() % 100;
- a.add_point(u, p[u]);
- for (v = 0; v < N; v++) {
- adj[u][v] = adj[v][u] = false;
- }
- break;
- }
- }
-
- // Floyd-Warshall
- float d[N][N];
- for (int u = 0; u < N; u++) {
- for (int v = 0; v < N; v++) {
- d[u][v] = (u == v || adj[u][v]) ? p[u].distance_to(p[v]) : INFINITY;
- }
- }
-
- for (int w = 0; w < N; w++) {
- for (int u = 0; u < N; u++) {
- for (int v = 0; v < N; v++) {
- if (d[u][v] > d[u][w] + d[w][v]) {
- d[u][v] = d[u][w] + d[w][v];
- }
- }
- }
- }
-
- // Display statistics
- int count = 0;
- for (int u = 0; u < N; u++) {
- for (int v = 0; v < N; v++) {
- if (adj[u][v]) {
- count++;
- }
- }
- }
- printf("Test #%4d: %3d edges, ", test + 1, count);
- count = 0;
- for (int u = 0; u < N; u++) {
- for (int v = 0; v < N; v++) {
- if (!Math::is_inf(d[u][v])) {
- count++;
- }
- }
- }
- printf("%3d/%d pairs of reachable points\n", count - N, N * (N - 1));
-
- // Check A*'s output
- bool match = true;
- for (int u = 0; u < N; u++) {
- for (int v = 0; v < N; v++) {
- if (u != v) {
- Vector<int> route = a.get_id_path(u, v);
- if (!Math::is_inf(d[u][v])) {
- // Reachable
- if (route.size() == 0) {
- printf("From %d to %d: A* did not find a path\n", u, v);
- match = false;
- goto exit;
- }
- float astar_dist = 0;
- for (int i = 1; i < route.size(); i++) {
- if (!adj[route[i - 1]][route[i]]) {
- printf("From %d to %d: edge (%d, %d) does not exist\n",
- u, v, route[i - 1], route[i]);
- match = false;
- goto exit;
- }
- astar_dist += p[route[i - 1]].distance_to(p[route[i]]);
- }
- if (!Math::is_equal_approx(astar_dist, d[u][v])) {
- printf("From %d to %d: Floyd-Warshall gives %.6f, A* gives %.6f\n",
- u, v, d[u][v], astar_dist);
- match = false;
- goto exit;
- }
- } else {
- // Unreachable
- if (route.size() > 0) {
- printf("From %d to %d: A* somehow found a nonexistent path\n", u, v);
- match = false;
- goto exit;
- }
- }
- }
- }
- }
-
- exit:
- if (!match) {
- return false;
- }
- }
- return true;
-}
-
-typedef bool (*TestFunc)();
-
-TestFunc test_funcs[] = {
- test_abc,
- test_abcx,
- test_add_remove,
- test_solutions,
- nullptr
-};
-
-MainLoop *test() {
- int count = 0;
- int passed = 0;
-
- while (true) {
- if (!test_funcs[count]) {
- break;
- }
- bool pass = test_funcs[count]();
- if (pass) {
- passed++;
- }
- OS::get_singleton()->print("\t%s\n", pass ? "PASS" : "FAILED");
-
- count++;
- }
- OS::get_singleton()->print("\n");
- OS::get_singleton()->print("Passed %i of %i tests\n", passed, count);
- return nullptr;
-}
-
-} // namespace TestAStar
diff --git a/tests/test_astar.h b/tests/test_astar.h
index 0992812c18..cd1bd84c15 100644
--- a/tests/test_astar.h
+++ b/tests/test_astar.h
@@ -31,11 +31,337 @@
#ifndef TEST_ASTAR_H
#define TEST_ASTAR_H
-#include "core/os/main_loop.h"
+#include "core/math/a_star.h"
+#include "core/math/math_funcs.h"
+#include "core/os/os.h"
+
+#include <math.h>
+#include <stdio.h>
+
+#include "tests/test_macros.h"
namespace TestAStar {
-MainLoop *test();
+class ABCX : public AStar {
+public:
+ enum {
+ A,
+ B,
+ C,
+ X,
+ };
+
+ ABCX() {
+ add_point(A, Vector3(0, 0, 0));
+ add_point(B, Vector3(1, 0, 0));
+ add_point(C, Vector3(0, 1, 0));
+ add_point(X, Vector3(0, 0, 1));
+ connect_points(A, B);
+ connect_points(A, C);
+ connect_points(B, C);
+ connect_points(X, A);
+ }
+
+ // Disable heuristic completely.
+ float _compute_cost(int p_from, int p_to) {
+ if (p_from == A && p_to == C) {
+ return 1000;
+ }
+ return 100;
+ }
+};
+
+TEST_CASE("[AStar] ABC path") {
+ ABCX abcx;
+ Vector<int> path = abcx.get_id_path(ABCX::A, ABCX::C);
+ REQUIRE(path.size() == 3);
+ CHECK(path[0] == ABCX::A);
+ CHECK(path[1] == ABCX::B);
+ CHECK(path[2] == ABCX::C);
+}
+
+TEST_CASE("[AStar] ABCX path") {
+ ABCX abcx;
+ Vector<int> path = abcx.get_id_path(ABCX::X, ABCX::C);
+ REQUIRE(path.size() == 4);
+ CHECK(path[0] == ABCX::X);
+ CHECK(path[1] == ABCX::A);
+ CHECK(path[2] == ABCX::B);
+ CHECK(path[3] == ABCX::C);
+}
+
+TEST_CASE("[AStar] Add/Remove") {
+ AStar a;
+
+ // Manual tests.
+ a.add_point(1, Vector3(0, 0, 0));
+ a.add_point(2, Vector3(0, 1, 0));
+ a.add_point(3, Vector3(1, 1, 0));
+ a.add_point(4, Vector3(2, 0, 0));
+ a.connect_points(1, 2, true);
+ a.connect_points(1, 3, true);
+ a.connect_points(1, 4, false);
+
+ CHECK(a.are_points_connected(2, 1));
+ CHECK(a.are_points_connected(4, 1));
+ CHECK(a.are_points_connected(2, 1, false));
+ CHECK_FALSE(a.are_points_connected(4, 1, false));
+
+ a.disconnect_points(1, 2, true);
+ CHECK(a.get_point_connections(1).size() == 2); // 3, 4
+ CHECK(a.get_point_connections(2).size() == 0);
+
+ a.disconnect_points(4, 1, false);
+ CHECK(a.get_point_connections(1).size() == 2); // 3, 4
+ CHECK(a.get_point_connections(4).size() == 0);
+
+ a.disconnect_points(4, 1, true);
+ CHECK(a.get_point_connections(1).size() == 1); // 3
+ CHECK(a.get_point_connections(4).size() == 0);
+
+ a.connect_points(2, 3, false);
+ CHECK(a.get_point_connections(2).size() == 1); // 3
+ CHECK(a.get_point_connections(3).size() == 1); // 1
+
+ a.connect_points(2, 3, true);
+ CHECK(a.get_point_connections(2).size() == 1); // 3
+ CHECK(a.get_point_connections(3).size() == 2); // 1, 2
+
+ a.disconnect_points(2, 3, false);
+ CHECK(a.get_point_connections(2).size() == 0);
+ CHECK(a.get_point_connections(3).size() == 2); // 1, 2
+
+ a.connect_points(4, 3, true);
+ CHECK(a.get_point_connections(3).size() == 3); // 1, 2, 4
+ CHECK(a.get_point_connections(4).size() == 1); // 3
+
+ a.disconnect_points(3, 4, false);
+ CHECK(a.get_point_connections(3).size() == 2); // 1, 2
+ CHECK(a.get_point_connections(4).size() == 1); // 3
+
+ a.remove_point(3);
+ CHECK(a.get_point_connections(1).size() == 0);
+ CHECK(a.get_point_connections(2).size() == 0);
+ CHECK(a.get_point_connections(4).size() == 0);
+
+ a.add_point(0, Vector3(0, -1, 0));
+ a.add_point(3, Vector3(2, 1, 0));
+ // 0: (0, -1)
+ // 1: (0, 0)
+ // 2: (0, 1)
+ // 3: (2, 1)
+ // 4: (2, 0)
+
+ // Tests for get_closest_position_in_segment.
+ a.connect_points(2, 3);
+ CHECK(a.get_closest_position_in_segment(Vector3(0.5, 0.5, 0)) == Vector3(0.5, 1, 0));
+
+ a.connect_points(3, 4);
+ a.connect_points(0, 3);
+ a.connect_points(1, 4);
+ a.disconnect_points(1, 4, false);
+ a.disconnect_points(4, 3, false);
+ a.disconnect_points(3, 4, false);
+ // Remaining edges: <2, 3>, <0, 3>, <1, 4> (directed).
+ CHECK(a.get_closest_position_in_segment(Vector3(2, 0.5, 0)) == Vector3(1.75, 0.75, 0));
+ CHECK(a.get_closest_position_in_segment(Vector3(-1, 0.2, 0)) == Vector3(0, 0, 0));
+ CHECK(a.get_closest_position_in_segment(Vector3(3, 2, 0)) == Vector3(2, 1, 0));
+
+ Math::seed(0);
+
+ // Random tests for connectivity checks
+ for (int i = 0; i < 20000; i++) {
+ int u = Math::rand() % 5;
+ int v = Math::rand() % 4;
+ if (u == v) {
+ v = 4;
+ }
+ if (Math::rand() % 2 == 1) {
+ // Add a (possibly existing) directed edge and confirm connectivity.
+ a.connect_points(u, v, false);
+ CHECK(a.are_points_connected(u, v, false));
+ } else {
+ // Remove a (possibly nonexistent) directed edge and confirm disconnectivity.
+ a.disconnect_points(u, v, false);
+ CHECK_FALSE(a.are_points_connected(u, v, false));
+ }
+ }
+
+ // Random tests for point removal.
+ for (int i = 0; i < 20000; i++) {
+ a.clear();
+ for (int j = 0; j < 5; j++) {
+ a.add_point(j, Vector3(0, 0, 0));
+ }
+
+ // Add or remove random edges.
+ for (int j = 0; j < 10; j++) {
+ int u = Math::rand() % 5;
+ int v = Math::rand() % 4;
+ if (u == v) {
+ v = 4;
+ }
+ if (Math::rand() % 2 == 1) {
+ a.connect_points(u, v, false);
+ } else {
+ a.disconnect_points(u, v, false);
+ }
+ }
+
+ // Remove point 0.
+ a.remove_point(0);
+ // White box: this will check all edges remaining in the segments set.
+ for (int j = 1; j < 5; j++) {
+ CHECK_FALSE(a.are_points_connected(0, j, true));
+ }
+ }
+ // It's been great work, cheers. \(^ ^)/
+}
+
+TEST_CASE("[Stress][AStar] Find paths") {
+ // Random stress tests with Floyd-Warshall.
+ const int N = 30;
+ Math::seed(0);
+
+ for (int test = 0; test < 1000; test++) {
+ AStar a;
+ Vector3 p[N];
+ bool adj[N][N] = { { false } };
+
+ // Assign initial coordinates.
+ for (int u = 0; u < N; u++) {
+ p[u].x = Math::rand() % 100;
+ p[u].y = Math::rand() % 100;
+ p[u].z = Math::rand() % 100;
+ a.add_point(u, p[u]);
+ }
+ // Generate a random sequence of operations.
+ for (int i = 0; i < 1000; i++) {
+ // Pick two different vertices.
+ int u, v;
+ u = Math::rand() % N;
+ v = Math::rand() % (N - 1);
+ if (u == v) {
+ v = N - 1;
+ }
+ // Pick a random operation.
+ int op = Math::rand();
+ switch (op % 9) {
+ case 0:
+ case 1:
+ case 2:
+ case 3:
+ case 4:
+ case 5:
+ // Add edge (u, v); possibly bidirectional.
+ a.connect_points(u, v, op % 2);
+ adj[u][v] = true;
+ if (op % 2) {
+ adj[v][u] = true;
+ }
+ break;
+ case 6:
+ case 7:
+ // Remove edge (u, v); possibly bidirectional.
+ a.disconnect_points(u, v, op % 2);
+ adj[u][v] = false;
+ if (op % 2) {
+ adj[v][u] = false;
+ }
+ break;
+ case 8:
+ // Remove point u and add it back; clears adjacent edges and changes coordinates.
+ a.remove_point(u);
+ p[u].x = Math::rand() % 100;
+ p[u].y = Math::rand() % 100;
+ p[u].z = Math::rand() % 100;
+ a.add_point(u, p[u]);
+ for (v = 0; v < N; v++) {
+ adj[u][v] = adj[v][u] = false;
+ }
+ break;
+ }
+ }
+ // Floyd-Warshall.
+ float d[N][N];
+ for (int u = 0; u < N; u++) {
+ for (int v = 0; v < N; v++) {
+ d[u][v] = (u == v || adj[u][v]) ? p[u].distance_to(p[v]) : INFINITY;
+ }
+ }
+ for (int w = 0; w < N; w++) {
+ for (int u = 0; u < N; u++) {
+ for (int v = 0; v < N; v++) {
+ if (d[u][v] > d[u][w] + d[w][v]) {
+ d[u][v] = d[u][w] + d[w][v];
+ }
+ }
+ }
+ }
+ // Display statistics.
+ int count = 0;
+ for (int u = 0; u < N; u++) {
+ for (int v = 0; v < N; v++) {
+ if (adj[u][v]) {
+ count++;
+ }
+ }
+ }
+ print_verbose(vformat("Test #%4d: %3d edges, ", test + 1, count));
+ count = 0;
+ for (int u = 0; u < N; u++) {
+ for (int v = 0; v < N; v++) {
+ if (!Math::is_inf(d[u][v])) {
+ count++;
+ }
+ }
+ }
+ print_verbose(vformat("%3d/%d pairs of reachable points\n", count - N, N * (N - 1)));
+
+ // Check A*'s output.
+ bool match = true;
+ for (int u = 0; u < N; u++) {
+ for (int v = 0; v < N; v++) {
+ if (u != v) {
+ Vector<int> route = a.get_id_path(u, v);
+ if (!Math::is_inf(d[u][v])) {
+ // Reachable.
+ if (route.size() == 0) {
+ print_verbose(vformat("From %d to %d: A* did not find a path\n", u, v));
+ match = false;
+ goto exit;
+ }
+ float astar_dist = 0;
+ for (int i = 1; i < route.size(); i++) {
+ if (!adj[route[i - 1]][route[i]]) {
+ print_verbose(vformat("From %d to %d: edge (%d, %d) does not exist\n",
+ u, v, route[i - 1], route[i]));
+ match = false;
+ goto exit;
+ }
+ astar_dist += p[route[i - 1]].distance_to(p[route[i]]);
+ }
+ if (!Math::is_equal_approx(astar_dist, d[u][v])) {
+ print_verbose(vformat("From %d to %d: Floyd-Warshall gives %.6f, A* gives %.6f\n",
+ u, v, d[u][v], astar_dist));
+ match = false;
+ goto exit;
+ }
+ } else {
+ // Unreachable.
+ if (route.size() > 0) {
+ print_verbose(vformat("From %d to %d: A* somehow found a nonexistent path\n", u, v));
+ match = false;
+ goto exit;
+ }
+ }
+ }
+ }
+ }
+ exit:
+ CHECK_MESSAGE(match, "Found all paths.");
+ }
}
+} // namespace TestAStar
-#endif
+#endif // TEST_ASTAR_H
diff --git a/tests/test_basis.cpp b/tests/test_basis.cpp
deleted file mode 100644
index 5904fc386a..0000000000
--- a/tests/test_basis.cpp
+++ /dev/null
@@ -1,325 +0,0 @@
-/*************************************************************************/
-/* test_basis.cpp */
-/*************************************************************************/
-/* This file is part of: */
-/* GODOT ENGINE */
-/* https://godotengine.org */
-/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
-/* */
-/* Permission is hereby granted, free of charge, to any person obtaining */
-/* a copy of this software and associated documentation files (the */
-/* "Software"), to deal in the Software without restriction, including */
-/* without limitation the rights to use, copy, modify, merge, publish, */
-/* distribute, sublicense, and/or sell copies of the Software, and to */
-/* permit persons to whom the Software is furnished to do so, subject to */
-/* the following conditions: */
-/* */
-/* The above copyright notice and this permission notice shall be */
-/* included in all copies or substantial portions of the Software. */
-/* */
-/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
-/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
-/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
-/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
-/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
-/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
-/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
-/*************************************************************************/
-
-#include "test_basis.h"
-
-#include "core/math/random_number_generator.h"
-#include "core/os/os.h"
-#include "core/ustring.h"
-
-namespace TestBasis {
-
-enum RotOrder {
- EulerXYZ,
- EulerXZY,
- EulerYZX,
- EulerYXZ,
- EulerZXY,
- EulerZYX
-};
-
-Vector3 deg2rad(const Vector3 &p_rotation) {
- return p_rotation / 180.0 * Math_PI;
-}
-
-Vector3 rad2deg(const Vector3 &p_rotation) {
- return p_rotation / Math_PI * 180.0;
-}
-
-Basis EulerToBasis(RotOrder mode, const Vector3 &p_rotation) {
- Basis ret;
- switch (mode) {
- case EulerXYZ:
- ret.set_euler_xyz(p_rotation);
- break;
-
- case EulerXZY:
- ret.set_euler_xzy(p_rotation);
- break;
-
- case EulerYZX:
- ret.set_euler_yzx(p_rotation);
- break;
-
- case EulerYXZ:
- ret.set_euler_yxz(p_rotation);
- break;
-
- case EulerZXY:
- ret.set_euler_zxy(p_rotation);
- break;
-
- case EulerZYX:
- ret.set_euler_zyx(p_rotation);
- break;
-
- default:
- // If you land here, Please integrate all rotation orders.
- CRASH_NOW_MSG("This is not unreachable.");
- }
-
- return ret;
-}
-
-Vector3 BasisToEuler(RotOrder mode, const Basis &p_rotation) {
- switch (mode) {
- case EulerXYZ:
- return p_rotation.get_euler_xyz();
-
- case EulerXZY:
- return p_rotation.get_euler_xzy();
-
- case EulerYZX:
- return p_rotation.get_euler_yzx();
-
- case EulerYXZ:
- return p_rotation.get_euler_yxz();
-
- case EulerZXY:
- return p_rotation.get_euler_zxy();
-
- case EulerZYX:
- return p_rotation.get_euler_zyx();
-
- default:
- // If you land here, Please integrate all rotation orders.
- CRASH_NOW_MSG("This is not unreachable.");
- return Vector3();
- }
-}
-
-String get_rot_order_name(RotOrder ro) {
- switch (ro) {
- case EulerXYZ:
- return "XYZ";
- case EulerXZY:
- return "XZY";
- case EulerYZX:
- return "YZX";
- case EulerYXZ:
- return "YXZ";
- case EulerZXY:
- return "ZXY";
- case EulerZYX:
- return "ZYX";
- default:
- return "[Not supported]";
- }
-}
-
-bool test_rotation(Vector3 deg_original_euler, RotOrder rot_order) {
- // This test:
- // 1. Converts the rotation vector from deg to rad.
- // 2. Converts euler to basis.
- // 3. Converts the above basis back into euler.
- // 4. Converts the above euler into basis again.
- // 5. Compares the basis obtained in step 2 with the basis of step 4
- //
- // The conversion "basis to euler", done in the step 3, may be different from
- // the original euler, even if the final rotation are the same.
- // This happens because there are more ways to represents the same rotation,
- // both valid, using eulers.
- // For this reason is necessary to convert that euler back to basis and finally
- // compares it.
- //
- // In this way we can assert that both functions: basis to euler / euler to basis
- // are correct.
-
- bool pass = true;
-
- // Euler to rotation
- const Vector3 original_euler = deg2rad(deg_original_euler);
- const Basis to_rotation = EulerToBasis(rot_order, original_euler);
-
- // Euler from rotation
- const Vector3 euler_from_rotation = BasisToEuler(rot_order, to_rotation);
- const Basis rotation_from_computed_euler = EulerToBasis(rot_order, euler_from_rotation);
-
- Basis res = to_rotation.inverse() * rotation_from_computed_euler;
-
- if ((res.get_axis(0) - Vector3(1.0, 0.0, 0.0)).length() > 0.1) {
- OS::get_singleton()->print("Fail due to X %ls\n", String(res.get_axis(0)).c_str());
- pass = false;
- }
- if ((res.get_axis(1) - Vector3(0.0, 1.0, 0.0)).length() > 0.1) {
- OS::get_singleton()->print("Fail due to Y %ls\n", String(res.get_axis(1)).c_str());
- pass = false;
- }
- if ((res.get_axis(2) - Vector3(0.0, 0.0, 1.0)).length() > 0.1) {
- OS::get_singleton()->print("Fail due to Z %ls\n", String(res.get_axis(2)).c_str());
- pass = false;
- }
-
- if (pass) {
- // Double check `to_rotation` decomposing with XYZ rotation order.
- const Vector3 euler_xyz_from_rotation = to_rotation.get_euler_xyz();
- Basis rotation_from_xyz_computed_euler;
- rotation_from_xyz_computed_euler.set_euler_xyz(euler_xyz_from_rotation);
-
- res = to_rotation.inverse() * rotation_from_xyz_computed_euler;
-
- if ((res.get_axis(0) - Vector3(1.0, 0.0, 0.0)).length() > 0.1) {
- OS::get_singleton()->print("Double check with XYZ rot order failed, due to X %ls\n", String(res.get_axis(0)).c_str());
- pass = false;
- }
- if ((res.get_axis(1) - Vector3(0.0, 1.0, 0.0)).length() > 0.1) {
- OS::get_singleton()->print("Double check with XYZ rot order failed, due to Y %ls\n", String(res.get_axis(1)).c_str());
- pass = false;
- }
- if ((res.get_axis(2) - Vector3(0.0, 0.0, 1.0)).length() > 0.1) {
- OS::get_singleton()->print("Double check with XYZ rot order failed, due to Z %ls\n", String(res.get_axis(2)).c_str());
- pass = false;
- }
- }
-
- if (pass == false) {
- // Print phase only if not pass.
- OS *os = OS::get_singleton();
- os->print("Rotation order: %ls\n.", get_rot_order_name(rot_order).c_str());
- os->print("Original Rotation: %ls\n", String(deg_original_euler).c_str());
- os->print("Quaternion to rotation order: %ls\n", String(rad2deg(euler_from_rotation)).c_str());
- }
-
- return pass;
-}
-
-void test_euler_conversion() {
- Vector<RotOrder> rotorder_to_test;
- rotorder_to_test.push_back(EulerXYZ);
- rotorder_to_test.push_back(EulerXZY);
- rotorder_to_test.push_back(EulerYZX);
- rotorder_to_test.push_back(EulerYXZ);
- rotorder_to_test.push_back(EulerZXY);
- rotorder_to_test.push_back(EulerZYX);
-
- Vector<Vector3> vectors_to_test;
-
- // Test the special cases.
- vectors_to_test.push_back(Vector3(0.0, 0.0, 0.0));
- vectors_to_test.push_back(Vector3(0.5, 0.5, 0.5));
- vectors_to_test.push_back(Vector3(-0.5, -0.5, -0.5));
- vectors_to_test.push_back(Vector3(40.0, 40.0, 40.0));
- vectors_to_test.push_back(Vector3(-40.0, -40.0, -40.0));
- vectors_to_test.push_back(Vector3(0.0, 0.0, -90.0));
- vectors_to_test.push_back(Vector3(0.0, -90.0, 0.0));
- vectors_to_test.push_back(Vector3(-90.0, 0.0, 0.0));
- vectors_to_test.push_back(Vector3(0.0, 0.0, 90.0));
- vectors_to_test.push_back(Vector3(0.0, 90.0, 0.0));
- vectors_to_test.push_back(Vector3(90.0, 0.0, 0.0));
- vectors_to_test.push_back(Vector3(0.0, 0.0, -30.0));
- vectors_to_test.push_back(Vector3(0.0, -30.0, 0.0));
- vectors_to_test.push_back(Vector3(-30.0, 0.0, 0.0));
- vectors_to_test.push_back(Vector3(0.0, 0.0, 30.0));
- vectors_to_test.push_back(Vector3(0.0, 30.0, 0.0));
- vectors_to_test.push_back(Vector3(30.0, 0.0, 0.0));
- vectors_to_test.push_back(Vector3(0.5, 50.0, 20.0));
- vectors_to_test.push_back(Vector3(-0.5, -50.0, -20.0));
- vectors_to_test.push_back(Vector3(0.5, 0.0, 90.0));
- vectors_to_test.push_back(Vector3(0.5, 0.0, -90.0));
- vectors_to_test.push_back(Vector3(360.0, 360.0, 360.0));
- vectors_to_test.push_back(Vector3(-360.0, -360.0, -360.0));
- vectors_to_test.push_back(Vector3(-90.0, 60.0, -90.0));
- vectors_to_test.push_back(Vector3(90.0, 60.0, -90.0));
- vectors_to_test.push_back(Vector3(90.0, -60.0, -90.0));
- vectors_to_test.push_back(Vector3(-90.0, -60.0, -90.0));
- vectors_to_test.push_back(Vector3(-90.0, 60.0, 90.0));
- vectors_to_test.push_back(Vector3(90.0, 60.0, 90.0));
- vectors_to_test.push_back(Vector3(90.0, -60.0, 90.0));
- vectors_to_test.push_back(Vector3(-90.0, -60.0, 90.0));
- vectors_to_test.push_back(Vector3(60.0, 90.0, -40.0));
- vectors_to_test.push_back(Vector3(60.0, -90.0, -40.0));
- vectors_to_test.push_back(Vector3(-60.0, -90.0, -40.0));
- vectors_to_test.push_back(Vector3(-60.0, 90.0, 40.0));
- vectors_to_test.push_back(Vector3(60.0, 90.0, 40.0));
- vectors_to_test.push_back(Vector3(60.0, -90.0, 40.0));
- vectors_to_test.push_back(Vector3(-60.0, -90.0, 40.0));
- vectors_to_test.push_back(Vector3(-90.0, 90.0, -90.0));
- vectors_to_test.push_back(Vector3(90.0, 90.0, -90.0));
- vectors_to_test.push_back(Vector3(90.0, -90.0, -90.0));
- vectors_to_test.push_back(Vector3(-90.0, -90.0, -90.0));
- vectors_to_test.push_back(Vector3(-90.0, 90.0, 90.0));
- vectors_to_test.push_back(Vector3(90.0, 90.0, 90.0));
- vectors_to_test.push_back(Vector3(90.0, -90.0, 90.0));
- vectors_to_test.push_back(Vector3(20.0, 150.0, 30.0));
- vectors_to_test.push_back(Vector3(20.0, -150.0, 30.0));
- vectors_to_test.push_back(Vector3(-120.0, -150.0, 30.0));
- vectors_to_test.push_back(Vector3(-120.0, -150.0, -130.0));
- vectors_to_test.push_back(Vector3(120.0, -150.0, -130.0));
- vectors_to_test.push_back(Vector3(120.0, 150.0, -130.0));
- vectors_to_test.push_back(Vector3(120.0, 150.0, 130.0));
-
- // Add 1000 random vectors with weirds numbers.
- RandomNumberGenerator rng;
- for (int _ = 0; _ < 1000; _ += 1) {
- vectors_to_test.push_back(Vector3(
- rng.randf_range(-1800, 1800),
- rng.randf_range(-1800, 1800),
- rng.randf_range(-1800, 1800)));
- }
-
- bool success = true;
- for (int h = 0; h < rotorder_to_test.size(); h += 1) {
- int passed = 0;
- int failed = 0;
- for (int i = 0; i < vectors_to_test.size(); i += 1) {
- if (test_rotation(vectors_to_test[i], rotorder_to_test[h])) {
- //OS::get_singleton()->print("Success. \n\n");
- passed += 1;
- } else {
- OS::get_singleton()->print("FAILED FAILED FAILED. \n\n");
- OS::get_singleton()->print("------------>\n");
- OS::get_singleton()->print("------------>\n");
- failed += 1;
- success = false;
- }
- }
-
- if (failed == 0) {
- OS::get_singleton()->print("%i passed tests for rotation order: %ls.\n", passed, get_rot_order_name(rotorder_to_test[h]).c_str());
- } else {
- OS::get_singleton()->print("%i FAILED tests for rotation order: %ls.\n", failed, get_rot_order_name(rotorder_to_test[h]).c_str());
- }
- }
-
- if (success) {
- OS::get_singleton()->print("Euler conversion checks passed.\n");
- } else {
- OS::get_singleton()->print("Euler conversion checks FAILED.\n");
- }
-}
-
-MainLoop *test() {
- OS::get_singleton()->print("Start euler conversion checks.\n");
- test_euler_conversion();
-
- return NULL;
-}
-
-} // namespace TestBasis
diff --git a/tests/test_basis.h b/tests/test_basis.h
index 63297bd3b8..00a00b4a5b 100644
--- a/tests/test_basis.h
+++ b/tests/test_basis.h
@@ -31,10 +31,257 @@
#ifndef TEST_BASIS_H
#define TEST_BASIS_H
-#include "core/os/main_loop.h"
+#include "core/math/random_number_generator.h"
+#include "core/os/os.h"
+#include "core/string/ustring.h"
+
+#include "tests/test_macros.h"
namespace TestBasis {
-MainLoop *test();
+
+enum RotOrder {
+ EulerXYZ,
+ EulerXZY,
+ EulerYZX,
+ EulerYXZ,
+ EulerZXY,
+ EulerZYX
+};
+
+Vector3 deg2rad(const Vector3 &p_rotation) {
+ return p_rotation / 180.0 * Math_PI;
+}
+
+Vector3 rad2deg(const Vector3 &p_rotation) {
+ return p_rotation / Math_PI * 180.0;
+}
+
+Basis EulerToBasis(RotOrder mode, const Vector3 &p_rotation) {
+ Basis ret;
+ switch (mode) {
+ case EulerXYZ:
+ ret.set_euler_xyz(p_rotation);
+ break;
+
+ case EulerXZY:
+ ret.set_euler_xzy(p_rotation);
+ break;
+
+ case EulerYZX:
+ ret.set_euler_yzx(p_rotation);
+ break;
+
+ case EulerYXZ:
+ ret.set_euler_yxz(p_rotation);
+ break;
+
+ case EulerZXY:
+ ret.set_euler_zxy(p_rotation);
+ break;
+
+ case EulerZYX:
+ ret.set_euler_zyx(p_rotation);
+ break;
+
+ default:
+ // If you land here, Please integrate all rotation orders.
+ FAIL("This is not unreachable.");
+ }
+
+ return ret;
+}
+
+Vector3 BasisToEuler(RotOrder mode, const Basis &p_rotation) {
+ switch (mode) {
+ case EulerXYZ:
+ return p_rotation.get_euler_xyz();
+
+ case EulerXZY:
+ return p_rotation.get_euler_xzy();
+
+ case EulerYZX:
+ return p_rotation.get_euler_yzx();
+
+ case EulerYXZ:
+ return p_rotation.get_euler_yxz();
+
+ case EulerZXY:
+ return p_rotation.get_euler_zxy();
+
+ case EulerZYX:
+ return p_rotation.get_euler_zyx();
+
+ default:
+ // If you land here, Please integrate all rotation orders.
+ FAIL("This is not unreachable.");
+ return Vector3();
+ }
+}
+
+String get_rot_order_name(RotOrder ro) {
+ switch (ro) {
+ case EulerXYZ:
+ return "XYZ";
+ case EulerXZY:
+ return "XZY";
+ case EulerYZX:
+ return "YZX";
+ case EulerYXZ:
+ return "YXZ";
+ case EulerZXY:
+ return "ZXY";
+ case EulerZYX:
+ return "ZYX";
+ default:
+ return "[Not supported]";
+ }
+}
+
+void test_rotation(Vector3 deg_original_euler, RotOrder rot_order) {
+ // This test:
+ // 1. Converts the rotation vector from deg to rad.
+ // 2. Converts euler to basis.
+ // 3. Converts the above basis back into euler.
+ // 4. Converts the above euler into basis again.
+ // 5. Compares the basis obtained in step 2 with the basis of step 4
+ //
+ // The conversion "basis to euler", done in the step 3, may be different from
+ // the original euler, even if the final rotation are the same.
+ // This happens because there are more ways to represents the same rotation,
+ // both valid, using eulers.
+ // For this reason is necessary to convert that euler back to basis and finally
+ // compares it.
+ //
+ // In this way we can assert that both functions: basis to euler / euler to basis
+ // are correct.
+
+ // Euler to rotation
+ const Vector3 original_euler = deg2rad(deg_original_euler);
+ const Basis to_rotation = EulerToBasis(rot_order, original_euler);
+
+ // Euler from rotation
+ const Vector3 euler_from_rotation = BasisToEuler(rot_order, to_rotation);
+ const Basis rotation_from_computed_euler = EulerToBasis(rot_order, euler_from_rotation);
+
+ Basis res = to_rotation.inverse() * rotation_from_computed_euler;
+
+ CHECK_MESSAGE((res.get_axis(0) - Vector3(1.0, 0.0, 0.0)).length() <= 0.1, vformat("Fail due to X %s\n", String(res.get_axis(0))).utf8().ptr());
+ CHECK_MESSAGE((res.get_axis(1) - Vector3(0.0, 1.0, 0.0)).length() <= 0.1, vformat("Fail due to Y %s\n", String(res.get_axis(1))).utf8().ptr());
+ CHECK_MESSAGE((res.get_axis(2) - Vector3(0.0, 0.0, 1.0)).length() <= 0.1, vformat("Fail due to Z %s\n", String(res.get_axis(2))).utf8().ptr());
+
+ // Double check `to_rotation` decomposing with XYZ rotation order.
+ const Vector3 euler_xyz_from_rotation = to_rotation.get_euler_xyz();
+ Basis rotation_from_xyz_computed_euler;
+ rotation_from_xyz_computed_euler.set_euler_xyz(euler_xyz_from_rotation);
+
+ res = to_rotation.inverse() * rotation_from_xyz_computed_euler;
+
+ CHECK_MESSAGE((res.get_axis(0) - Vector3(1.0, 0.0, 0.0)).length() <= 0.1, vformat("Double check with XYZ rot order failed, due to X %s\n", String(res.get_axis(0))).utf8().ptr());
+ CHECK_MESSAGE((res.get_axis(1) - Vector3(0.0, 1.0, 0.0)).length() <= 0.1, vformat("Double check with XYZ rot order failed, due to Y %s\n", String(res.get_axis(1))).utf8().ptr());
+ CHECK_MESSAGE((res.get_axis(2) - Vector3(0.0, 0.0, 1.0)).length() <= 0.1, vformat("Double check with XYZ rot order failed, due to Z %s\n", String(res.get_axis(2))).utf8().ptr());
+
+ INFO(vformat("Rotation order: %s\n.", get_rot_order_name(rot_order)).utf8().ptr());
+ INFO(vformat("Original Rotation: %s\n", String(deg_original_euler)).utf8().ptr());
+ INFO(vformat("Quaternion to rotation order: %s\n", String(rad2deg(euler_from_rotation))).utf8().ptr());
+}
+
+TEST_CASE("[Basis] Euler conversions") {
+ Vector<RotOrder> rotorder_to_test;
+ rotorder_to_test.push_back(EulerXYZ);
+ rotorder_to_test.push_back(EulerXZY);
+ rotorder_to_test.push_back(EulerYZX);
+ rotorder_to_test.push_back(EulerYXZ);
+ rotorder_to_test.push_back(EulerZXY);
+ rotorder_to_test.push_back(EulerZYX);
+
+ Vector<Vector3> vectors_to_test;
+
+ // Test the special cases.
+ vectors_to_test.push_back(Vector3(0.0, 0.0, 0.0));
+ vectors_to_test.push_back(Vector3(0.5, 0.5, 0.5));
+ vectors_to_test.push_back(Vector3(-0.5, -0.5, -0.5));
+ vectors_to_test.push_back(Vector3(40.0, 40.0, 40.0));
+ vectors_to_test.push_back(Vector3(-40.0, -40.0, -40.0));
+ vectors_to_test.push_back(Vector3(0.0, 0.0, -90.0));
+ vectors_to_test.push_back(Vector3(0.0, -90.0, 0.0));
+ vectors_to_test.push_back(Vector3(-90.0, 0.0, 0.0));
+ vectors_to_test.push_back(Vector3(0.0, 0.0, 90.0));
+ vectors_to_test.push_back(Vector3(0.0, 90.0, 0.0));
+ vectors_to_test.push_back(Vector3(90.0, 0.0, 0.0));
+ vectors_to_test.push_back(Vector3(0.0, 0.0, -30.0));
+ vectors_to_test.push_back(Vector3(0.0, -30.0, 0.0));
+ vectors_to_test.push_back(Vector3(-30.0, 0.0, 0.0));
+ vectors_to_test.push_back(Vector3(0.0, 0.0, 30.0));
+ vectors_to_test.push_back(Vector3(0.0, 30.0, 0.0));
+ vectors_to_test.push_back(Vector3(30.0, 0.0, 0.0));
+ vectors_to_test.push_back(Vector3(0.5, 50.0, 20.0));
+ vectors_to_test.push_back(Vector3(-0.5, -50.0, -20.0));
+ vectors_to_test.push_back(Vector3(0.5, 0.0, 90.0));
+ vectors_to_test.push_back(Vector3(0.5, 0.0, -90.0));
+ vectors_to_test.push_back(Vector3(360.0, 360.0, 360.0));
+ vectors_to_test.push_back(Vector3(-360.0, -360.0, -360.0));
+ vectors_to_test.push_back(Vector3(-90.0, 60.0, -90.0));
+ vectors_to_test.push_back(Vector3(90.0, 60.0, -90.0));
+ vectors_to_test.push_back(Vector3(90.0, -60.0, -90.0));
+ vectors_to_test.push_back(Vector3(-90.0, -60.0, -90.0));
+ vectors_to_test.push_back(Vector3(-90.0, 60.0, 90.0));
+ vectors_to_test.push_back(Vector3(90.0, 60.0, 90.0));
+ vectors_to_test.push_back(Vector3(90.0, -60.0, 90.0));
+ vectors_to_test.push_back(Vector3(-90.0, -60.0, 90.0));
+ vectors_to_test.push_back(Vector3(60.0, 90.0, -40.0));
+ vectors_to_test.push_back(Vector3(60.0, -90.0, -40.0));
+ vectors_to_test.push_back(Vector3(-60.0, -90.0, -40.0));
+ vectors_to_test.push_back(Vector3(-60.0, 90.0, 40.0));
+ vectors_to_test.push_back(Vector3(60.0, 90.0, 40.0));
+ vectors_to_test.push_back(Vector3(60.0, -90.0, 40.0));
+ vectors_to_test.push_back(Vector3(-60.0, -90.0, 40.0));
+ vectors_to_test.push_back(Vector3(-90.0, 90.0, -90.0));
+ vectors_to_test.push_back(Vector3(90.0, 90.0, -90.0));
+ vectors_to_test.push_back(Vector3(90.0, -90.0, -90.0));
+ vectors_to_test.push_back(Vector3(-90.0, -90.0, -90.0));
+ vectors_to_test.push_back(Vector3(-90.0, 90.0, 90.0));
+ vectors_to_test.push_back(Vector3(90.0, 90.0, 90.0));
+ vectors_to_test.push_back(Vector3(90.0, -90.0, 90.0));
+ vectors_to_test.push_back(Vector3(20.0, 150.0, 30.0));
+ vectors_to_test.push_back(Vector3(20.0, -150.0, 30.0));
+ vectors_to_test.push_back(Vector3(-120.0, -150.0, 30.0));
+ vectors_to_test.push_back(Vector3(-120.0, -150.0, -130.0));
+ vectors_to_test.push_back(Vector3(120.0, -150.0, -130.0));
+ vectors_to_test.push_back(Vector3(120.0, 150.0, -130.0));
+ vectors_to_test.push_back(Vector3(120.0, 150.0, 130.0));
+
+ for (int h = 0; h < rotorder_to_test.size(); h += 1) {
+ for (int i = 0; i < vectors_to_test.size(); i += 1) {
+ test_rotation(vectors_to_test[i], rotorder_to_test[h]);
+ }
+ }
+}
+
+TEST_CASE("[Stress][Basis] Euler conversions") {
+ Vector<RotOrder> rotorder_to_test;
+ rotorder_to_test.push_back(EulerXYZ);
+ rotorder_to_test.push_back(EulerXZY);
+ rotorder_to_test.push_back(EulerYZX);
+ rotorder_to_test.push_back(EulerYXZ);
+ rotorder_to_test.push_back(EulerZXY);
+ rotorder_to_test.push_back(EulerZYX);
+
+ Vector<Vector3> vectors_to_test;
+ // Add 1000 random vectors with weirds numbers.
+ RandomNumberGenerator rng;
+ for (int _ = 0; _ < 1000; _ += 1) {
+ vectors_to_test.push_back(Vector3(
+ rng.randf_range(-1800, 1800),
+ rng.randf_range(-1800, 1800),
+ rng.randf_range(-1800, 1800)));
+ }
+
+ for (int h = 0; h < rotorder_to_test.size(); h += 1) {
+ for (int i = 0; i < vectors_to_test.size(); i += 1) {
+ test_rotation(vectors_to_test[i], rotorder_to_test[h]);
+ }
+ }
}
+} // namespace TestBasis
#endif
diff --git a/tests/test_class_db.cpp b/tests/test_class_db.cpp
deleted file mode 100644
index 3171091402..0000000000
--- a/tests/test_class_db.cpp
+++ /dev/null
@@ -1,882 +0,0 @@
-/*************************************************************************/
-/* test_class_db.cpp */
-/*************************************************************************/
-/* This file is part of: */
-/* GODOT ENGINE */
-/* https://godotengine.org */
-/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
-/* */
-/* Permission is hereby granted, free of charge, to any person obtaining */
-/* a copy of this software and associated documentation files (the */
-/* "Software"), to deal in the Software without restriction, including */
-/* without limitation the rights to use, copy, modify, merge, publish, */
-/* distribute, sublicense, and/or sell copies of the Software, and to */
-/* permit persons to whom the Software is furnished to do so, subject to */
-/* the following conditions: */
-/* */
-/* The above copyright notice and this permission notice shall be */
-/* included in all copies or substantial portions of the Software. */
-/* */
-/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
-/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
-/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
-/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
-/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
-/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
-/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
-/*************************************************************************/
-
-#include "test_class_db.h"
-
-#include "core/global_constants.h"
-#include "core/ordered_hash_map.h"
-#include "core/os/os.h"
-#include "core/string_name.h"
-#include "core/ustring.h"
-#include "core/variant.h"
-
-namespace TestClassDB {
-
-enum class [[nodiscard]] TestResult{
- FAILED,
- PASS
-};
-
-#define TEST_FAIL_COND(m_cond, m_msg) \
- if (unlikely(m_cond)) { \
- ERR_PRINT(m_msg); \
- return TestResult::FAILED; \
- } else \
- ((void)0)
-
-#define TEST_COND(m_cond, m_msg) \
- if (unlikely(m_cond)) { \
- ERR_PRINT(m_msg); \
- __test_result__ = TestResult::FAILED; \
- } else \
- ((void)0)
-
-#define TEST_FAIL_CHECK(m_test_expr) \
- if (unlikely((m_test_expr) == TestResult::FAILED)) { \
- return TestResult::FAILED; \
- } else \
- ((void)0)
-
-#define TEST_CHECK(m_test_expr) \
- if (unlikely((m_test_expr) == TestResult::FAILED)) { \
- __test_result__ = TestResult::FAILED; \
- } else \
- ((void)0)
-
-#define TEST_START() \
- TestResult __test_result__ = TestResult::PASS; \
- ((void)0)
-
-#define TEST_END() return __test_result__;
-
-struct TypeReference {
- StringName name;
- bool is_enum = false;
-};
-
-struct ConstantData {
- String name;
- int value = 0;
-};
-
-struct EnumData {
- StringName name;
- List<ConstantData> constants;
-
- _FORCE_INLINE_ bool operator==(const EnumData &p_enum) const {
- return p_enum.name == name;
- }
-};
-
-struct PropertyData {
- StringName name;
- int index = 0;
-
- StringName getter;
- StringName setter;
-};
-
-struct ArgumentData {
- TypeReference type;
- String name;
- bool has_defval = false;
- Variant defval;
-};
-
-struct MethodData {
- StringName name;
- TypeReference return_type;
- List<ArgumentData> arguments;
- bool is_virtual = false;
- bool is_vararg = false;
-};
-
-struct SignalData {
- StringName name;
- List<ArgumentData> arguments;
-};
-
-struct ExposedClass {
- StringName name;
- StringName base;
-
- bool is_singleton = false;
- bool is_instantiable = false;
- bool is_reference = false;
-
- ClassDB::APIType api_type;
-
- List<ConstantData> constants;
- List<EnumData> enums;
- List<PropertyData> properties;
- List<MethodData> methods;
- List<SignalData> signals_;
-
- const PropertyData *find_property_by_name(const StringName &p_name) const {
- for (const List<PropertyData>::Element *E = properties.front(); E; E = E->next()) {
- if (E->get().name == p_name) {
- return &E->get();
- }
- }
-
- return nullptr;
- }
-
- const MethodData *find_method_by_name(const StringName &p_name) const {
- for (const List<MethodData>::Element *E = methods.front(); E; E = E->next()) {
- if (E->get().name == p_name) {
- return &E->get();
- }
- }
-
- return nullptr;
- }
-};
-
-struct NamesCache {
- StringName variant_type = StaticCString::create("Variant");
- StringName object_class = StaticCString::create("Object");
- StringName reference_class = StaticCString::create("Reference");
- StringName string_type = StaticCString::create("String");
- StringName string_name_type = StaticCString::create("StringName");
- StringName node_path_type = StaticCString::create("NodePath");
- StringName bool_type = StaticCString::create("bool");
- StringName int_type = StaticCString::create("int");
- StringName float_type = StaticCString::create("float");
- StringName void_type = StaticCString::create("void");
- StringName vararg_stub_type = StaticCString::create("@VarArg@");
- StringName vector2_type = StaticCString::create("Vector2");
- StringName rect2_type = StaticCString::create("Rect2");
- StringName vector3_type = StaticCString::create("Vector3");
-
- // Object not included as it must be checked for all derived classes
- static constexpr int nullable_types_count = 17;
- StringName nullable_types[nullable_types_count] = {
- string_type,
- string_name_type,
- node_path_type,
-
- StaticCString::create(_STR(Array)),
- StaticCString::create(_STR(Dictionary)),
- StaticCString::create(_STR(Callable)),
- StaticCString::create(_STR(Signal)),
-
- StaticCString::create(_STR(PackedByteArray)),
- StaticCString::create(_STR(PackedInt32Array)),
- StaticCString::create(_STR(PackedInt64rray)),
- StaticCString::create(_STR(PackedFloat32Array)),
- StaticCString::create(_STR(PackedFloat64Array)),
- StaticCString::create(_STR(PackedStringArray)),
- StaticCString::create(_STR(PackedVector2Array)),
- StaticCString::create(_STR(PackedVector3Array)),
- StaticCString::create(_STR(PackedColorArray)),
- };
-
- bool is_nullable_type(const StringName &p_type) const {
- for (int i = 0; i < nullable_types_count; i++) {
- if (p_type == nullable_types[i]) {
- return true;
- }
- }
-
- return false;
- }
-};
-
-typedef OrderedHashMap<StringName, ExposedClass> ExposedClasses;
-
-struct Context {
- Vector<StringName> enum_types;
- Vector<StringName> builtin_types;
- ExposedClasses exposed_classes;
- List<EnumData> global_enums;
- NamesCache names_cache;
-
- const ExposedClass *find_exposed_class(const StringName &p_name) const {
- ExposedClasses::ConstElement elem = exposed_classes.find(p_name);
- return elem ? &elem.value() : nullptr;
- }
-
- const ExposedClass *find_exposed_class(const TypeReference &p_type_ref) const {
- ExposedClasses::ConstElement elem = exposed_classes.find(p_type_ref.name);
- return elem ? &elem.value() : nullptr;
- }
-
- bool has_type(const TypeReference &p_type_ref) const {
- if (builtin_types.find(p_type_ref.name) >= 0) {
- return true;
- }
-
- if (p_type_ref.is_enum) {
- if (enum_types.find(p_type_ref.name) >= 0) {
- return true;
- }
-
- // Enum not found. Most likely because none of its constants were bound, so it's empty. That's fine. Use int instead.
- return builtin_types.find(names_cache.int_type);
- }
-
- return false;
- }
-};
-
-bool arg_default_value_is_assignable_to_type(const Context &p_context, const Variant &p_val, const TypeReference &p_arg_type) {
- if (p_arg_type.name == p_context.names_cache.variant_type) {
- // Variant can take anything
- return true;
- }
-
- switch (p_val.get_type()) {
- case Variant::NIL:
- return p_context.find_exposed_class(p_arg_type) ||
- p_context.names_cache.is_nullable_type(p_arg_type.name);
- case Variant::BOOL:
- return p_arg_type.name == p_context.names_cache.bool_type;
- case Variant::INT:
- return p_arg_type.name == p_context.names_cache.int_type ||
- p_arg_type.name == p_context.names_cache.float_type ||
- p_arg_type.is_enum;
- case Variant::FLOAT:
- return p_arg_type.name == p_context.names_cache.float_type;
- case Variant::STRING:
- case Variant::STRING_NAME:
- return p_arg_type.name == p_context.names_cache.string_type ||
- p_arg_type.name == p_context.names_cache.string_name_type ||
- p_arg_type.name == p_context.names_cache.node_path_type;
- case Variant::NODE_PATH:
- return p_arg_type.name == p_context.names_cache.node_path_type;
- case Variant::TRANSFORM:
- case Variant::TRANSFORM2D:
- case Variant::BASIS:
- case Variant::QUAT:
- case Variant::PLANE:
- case Variant::AABB:
- case Variant::COLOR:
- case Variant::VECTOR2:
- case Variant::RECT2:
- case Variant::VECTOR3:
- case Variant::_RID:
- case Variant::ARRAY:
- case Variant::DICTIONARY:
- case Variant::PACKED_BYTE_ARRAY:
- case Variant::PACKED_INT32_ARRAY:
- case Variant::PACKED_INT64_ARRAY:
- case Variant::PACKED_FLOAT32_ARRAY:
- case Variant::PACKED_FLOAT64_ARRAY:
- case Variant::PACKED_STRING_ARRAY:
- case Variant::PACKED_VECTOR2_ARRAY:
- case Variant::PACKED_VECTOR3_ARRAY:
- case Variant::PACKED_COLOR_ARRAY:
- case Variant::CALLABLE:
- case Variant::SIGNAL:
- return p_arg_type.name == Variant::get_type_name(p_val.get_type());
- case Variant::OBJECT:
- return p_context.find_exposed_class(p_arg_type);
- case Variant::VECTOR2I:
- return p_arg_type.name == p_context.names_cache.vector2_type ||
- p_arg_type.name == Variant::get_type_name(p_val.get_type());
- case Variant::RECT2I:
- return p_arg_type.name == p_context.names_cache.rect2_type ||
- p_arg_type.name == Variant::get_type_name(p_val.get_type());
- case Variant::VECTOR3I:
- return p_arg_type.name == p_context.names_cache.vector3_type ||
- p_arg_type.name == Variant::get_type_name(p_val.get_type());
- default:
- ERR_PRINT("Unexpected Variant type: " + itos(p_val.get_type()));
- break;
- }
-
- return false;
-}
-
-TestResult validate_property(const Context &p_context, const ExposedClass &p_class, const PropertyData &p_prop) {
- TEST_START();
-
- const MethodData *setter = p_class.find_method_by_name(p_prop.setter);
-
- // Search it in base classes too
- const ExposedClass *top = &p_class;
- while (!setter && top->base != StringName()) {
- top = p_context.find_exposed_class(top->base);
- TEST_FAIL_COND(!top, "Class not found '" + top->base + "'. Inherited by '" + top->name + "'.");
- setter = top->find_method_by_name(p_prop.setter);
- }
-
- const MethodData *getter = p_class.find_method_by_name(p_prop.getter);
-
- // Search it in base classes too
- top = &p_class;
- while (!getter && top->base != StringName()) {
- top = p_context.find_exposed_class(top->base);
- TEST_FAIL_COND(!top, "Class not found '" + top->base + "'. Inherited by '" + top->name + "'.");
- getter = top->find_method_by_name(p_prop.getter);
- }
-
- TEST_FAIL_COND(!setter && !getter,
- "Couldn't find neither the setter nor the getter for property: '" + p_class.name + "." + String(p_prop.name) + "'.");
-
- if (setter) {
- int setter_argc = p_prop.index != -1 ? 2 : 1;
- TEST_FAIL_COND(setter->arguments.size() != setter_argc,
- "Invalid property setter argument count: '" + p_class.name + "." + String(p_prop.name) + "'.");
- }
-
- if (getter) {
- int getter_argc = p_prop.index != -1 ? 1 : 0;
- TEST_FAIL_COND(getter->arguments.size() != getter_argc,
- "Invalid property setter argument count: '" + p_class.name + "." + String(p_prop.name) + "'.");
- }
-
- if (getter && setter) {
- const ArgumentData &setter_first_arg = setter->arguments.back()->get();
- if (getter->return_type.name != setter_first_arg.type.name) {
- // Special case for Node::set_name
- bool whitelisted = getter->return_type.name == p_context.names_cache.string_name_type &&
- setter_first_arg.type.name == p_context.names_cache.string_type;
-
- TEST_FAIL_COND(!whitelisted,
- "Return type from getter doesn't match first argument of setter, for property: '" + p_class.name + "." + String(p_prop.name) + "'.");
- }
- }
-
- const TypeReference &prop_type_ref = getter ? getter->return_type : setter->arguments.back()->get().type;
-
- const ExposedClass *prop_class = p_context.find_exposed_class(prop_type_ref);
- if (prop_class) {
- TEST_COND(prop_class->is_singleton,
- "Property type is a singleton: '" + p_class.name + "." + String(p_prop.name) + "'.");
- } else {
- TEST_FAIL_COND(!p_context.has_type(prop_type_ref),
- "Property type '" + prop_type_ref.name + "' not found: '" + p_class.name + "." + String(p_prop.name) + "'.");
- }
-
- if (getter) {
- if (p_prop.index != -1) {
- const ArgumentData &idx_arg = getter->arguments.front()->get();
- if (idx_arg.type.name != p_context.names_cache.int_type) {
- // If not an int, it can be an enum
- TEST_COND(p_context.enum_types.find(idx_arg.type.name) < 0,
- "Invalid type '" + idx_arg.type.name + "' for index argument of property getter: '" + p_class.name + "." + String(p_prop.name) + "'.");
- }
- }
- }
-
- if (setter) {
- if (p_prop.index != -1) {
- const ArgumentData &idx_arg = setter->arguments.front()->get();
- if (idx_arg.type.name != p_context.names_cache.int_type) {
- // Assume the index parameter is an enum
- // If not an int, it can be an enum
- TEST_COND(p_context.enum_types.find(idx_arg.type.name) < 0,
- "Invalid type '" + idx_arg.type.name + "' for index argument of property setter: '" + p_class.name + "." + String(p_prop.name) + "'.");
- }
- }
- }
-
- TEST_END();
-}
-
-TestResult validate_method(const Context &p_context, const ExposedClass &p_class, const MethodData &p_method) {
- TEST_START();
-
- const ExposedClass *return_class = p_context.find_exposed_class(p_method.return_type);
- if (return_class) {
- TEST_COND(return_class->is_singleton,
- "Method return type is a singleton: '" + p_class.name + "." + p_method.name + "'.");
- }
-
- for (const List<ArgumentData>::Element *F = p_method.arguments.front(); F; F = F->next()) {
- const ArgumentData &arg = F->get();
-
- const ExposedClass *arg_class = p_context.find_exposed_class(arg.type);
- if (arg_class) {
- TEST_COND(arg_class->is_singleton,
- "Argument type is a singleton: '" + arg.name + "' of method '" + p_class.name + "." + p_method.name + "'.");
- } else {
- TEST_FAIL_COND(!p_context.has_type(arg.type),
- "Argument type '" + arg.type.name + "' not found: '" + arg.name + "' of method" + p_class.name + "." + p_method.name + "'.");
- }
-
- if (arg.has_defval) {
- TEST_COND(!arg_default_value_is_assignable_to_type(p_context, arg.defval, arg.type),
- "Invalid default value for parameter '" + arg.name + "' of method '" + p_class.name + "." + p_method.name + "'.");
- }
- }
-
- TEST_END();
-}
-
-TestResult validate_signal(const Context &p_context, const ExposedClass &p_class, const SignalData &p_signal) {
- TEST_START();
-
- for (const List<ArgumentData>::Element *F = p_signal.arguments.front(); F; F = F->next()) {
- const ArgumentData &arg = F->get();
-
- const ExposedClass *arg_class = p_context.find_exposed_class(arg.type);
- if (arg_class) {
- TEST_COND(arg_class->is_singleton,
- "Argument class is a singleton: '" + arg.name + "' of signal" + p_class.name + "." + p_signal.name + "'.");
- } else {
- TEST_FAIL_COND(!p_context.has_type(arg.type),
- "Argument type '" + arg.type.name + "' not found: '" + arg.name + "' of signal" + p_class.name + "." + p_signal.name + "'.");
- }
- }
-
- TEST_END();
-}
-
-TestResult validate_class(const Context &p_context, const ExposedClass &p_exposed_class) {
- TEST_START();
-
- bool is_derived_type = p_exposed_class.base != StringName();
-
- if (!is_derived_type) {
- // Asserts about the base Object class
- TEST_FAIL_COND(p_exposed_class.name != p_context.names_cache.object_class,
- "Class '" + p_exposed_class.name + "' has no base class.");
- TEST_FAIL_COND(!p_exposed_class.is_instantiable,
- "Object class is not instantiable.");
- TEST_FAIL_COND(p_exposed_class.api_type != ClassDB::API_CORE,
- "Object class is API is not API_CORE.");
- TEST_FAIL_COND(p_exposed_class.is_singleton,
- "Object class is registered as a singleton.");
- }
-
- TEST_FAIL_COND(p_exposed_class.is_singleton && p_exposed_class.base != p_context.names_cache.object_class,
- "Singleton base class '" + String(p_exposed_class.base) + "' is not Object, for class '" + p_exposed_class.name + "'.");
-
- TEST_FAIL_COND(is_derived_type && !p_context.exposed_classes.has(p_exposed_class.base),
- "Base type '" + p_exposed_class.base.operator String() + "' does not exist, for class '" + p_exposed_class.name + "'.");
-
- for (const List<PropertyData>::Element *F = p_exposed_class.properties.front(); F; F = F->next()) {
- TEST_CHECK(validate_property(p_context, p_exposed_class, F->get()));
- }
-
- for (const List<MethodData>::Element *F = p_exposed_class.methods.front(); F; F = F->next()) {
- TEST_CHECK(validate_method(p_context, p_exposed_class, F->get()));
- }
-
- for (const List<SignalData>::Element *F = p_exposed_class.signals_.front(); F; F = F->next()) {
- TEST_CHECK(validate_signal(p_context, p_exposed_class, F->get()));
- }
-
- TEST_END();
-}
-
-TestResult add_exposed_classes(Context &r_context) {
- TEST_START();
-
- List<StringName> class_list;
- ClassDB::get_class_list(&class_list);
- class_list.sort_custom<StringName::AlphCompare>();
-
- while (class_list.size()) {
- StringName class_name = class_list.front()->get();
-
- ClassDB::APIType api_type = ClassDB::get_api_type(class_name);
-
- if (api_type == ClassDB::API_NONE) {
- class_list.pop_front();
- continue;
- }
-
- if (!ClassDB::is_class_exposed(class_name)) {
- OS::get_singleton()->print("Ignoring class '%s' because it's not exposed\n", String(class_name).utf8().get_data());
- class_list.pop_front();
- continue;
- }
-
- if (!ClassDB::is_class_enabled(class_name)) {
- OS::get_singleton()->print("Ignoring class '%s' because it's not enabled\n", String(class_name).utf8().get_data());
- class_list.pop_front();
- continue;
- }
-
- ClassDB::ClassInfo *class_info = ClassDB::classes.getptr(class_name);
-
- ExposedClass exposed_class;
- exposed_class.name = class_name;
- exposed_class.api_type = api_type;
- exposed_class.is_singleton = Engine::get_singleton()->has_singleton(class_name);
- exposed_class.is_instantiable = class_info->creation_func && !exposed_class.is_singleton;
- exposed_class.is_reference = ClassDB::is_parent_class(class_name, "Reference");
- exposed_class.base = ClassDB::get_parent_class(class_name);
-
- // Add properties
-
- List<PropertyInfo> property_list;
- ClassDB::get_property_list(class_name, &property_list, true);
-
- Map<StringName, StringName> accessor_methods;
-
- for (const List<PropertyInfo>::Element *E = property_list.front(); E; E = E->next()) {
- const PropertyInfo &property = E->get();
-
- if (property.usage & PROPERTY_USAGE_GROUP || property.usage & PROPERTY_USAGE_SUBGROUP || property.usage & PROPERTY_USAGE_CATEGORY) {
- continue;
- }
-
- PropertyData prop;
- prop.name = property.name;
- prop.setter = ClassDB::get_property_setter(class_name, prop.name);
- prop.getter = ClassDB::get_property_getter(class_name, prop.name);
-
- if (prop.setter != StringName()) {
- accessor_methods[prop.setter] = prop.name;
- }
- if (prop.getter != StringName()) {
- accessor_methods[prop.getter] = prop.name;
- }
-
- bool valid = false;
- prop.index = ClassDB::get_property_index(class_name, prop.name, &valid);
- TEST_FAIL_COND(!valid, "Invalid property: '" + exposed_class.name + "." + String(prop.name) + "'.");
-
- exposed_class.properties.push_back(prop);
- }
-
- // Add methods
-
- List<MethodInfo> virtual_method_list;
- ClassDB::get_virtual_methods(class_name, &virtual_method_list, true);
-
- List<MethodInfo> method_list;
- ClassDB::get_method_list(class_name, &method_list, true);
- method_list.sort();
-
- for (List<MethodInfo>::Element *E = method_list.front(); E; E = E->next()) {
- const MethodInfo &method_info = E->get();
-
- int argc = method_info.arguments.size();
-
- if (method_info.name.empty()) {
- continue;
- }
-
- MethodData method;
- method.name = method_info.name;
-
- if (method_info.flags & METHOD_FLAG_VIRTUAL) {
- method.is_virtual = true;
- }
-
- PropertyInfo return_info = method_info.return_val;
-
- MethodBind *m = method.is_virtual ? nullptr : ClassDB::get_method(class_name, method_info.name);
-
- method.is_vararg = m && m->is_vararg();
-
- if (!m && !method.is_virtual) {
- TEST_FAIL_COND(!virtual_method_list.find(method_info),
- "Missing MethodBind for non-virtual method: '" + exposed_class.name + "." + method.name + "'.");
-
- // A virtual method without the virtual flag. This is a special case.
-
- // The method Object.free is registered as a virtual method, but without the virtual flag.
- // This is because this method is not supposed to be overridden, but called.
- // We assume the return type is void.
- method.return_type.name = r_context.names_cache.void_type;
-
- // Actually, more methods like this may be added in the future, which could return
- // something different. Let's put this check to notify us if that ever happens.
- if (exposed_class.name != r_context.names_cache.object_class || String(method.name) != "free") {
- WARN_PRINT("Notification: New unexpected virtual non-overridable method found."
- " We only expected Object.free, but found '" +
- exposed_class.name + "." + method.name + "'.");
- }
- } else if (return_info.type == Variant::INT && return_info.usage & PROPERTY_USAGE_CLASS_IS_ENUM) {
- method.return_type.name = return_info.class_name;
- method.return_type.is_enum = true;
- } else if (return_info.class_name != StringName()) {
- method.return_type.name = return_info.class_name;
-
- bool bad_reference_hint = !method.is_virtual && return_info.hint != PROPERTY_HINT_RESOURCE_TYPE &&
- ClassDB::is_parent_class(return_info.class_name, r_context.names_cache.reference_class);
- TEST_COND(bad_reference_hint, String() + "Return type is reference but hint is not '" _STR(PROPERTY_HINT_RESOURCE_TYPE) "'." +
- " Are you returning a reference type by pointer? Method: '" +
- exposed_class.name + "." + method.name + "'.");
- } else if (return_info.hint == PROPERTY_HINT_RESOURCE_TYPE) {
- method.return_type.name = return_info.hint_string;
- } else if (return_info.type == Variant::NIL && return_info.usage & PROPERTY_USAGE_NIL_IS_VARIANT) {
- method.return_type.name = r_context.names_cache.variant_type;
- } else if (return_info.type == Variant::NIL) {
- method.return_type.name = r_context.names_cache.void_type;
- } else {
- // NOTE: We don't care about the size and sign of int and float in these tests
- method.return_type.name = Variant::get_type_name(return_info.type);
- }
-
- for (int i = 0; i < argc; i++) {
- PropertyInfo arg_info = method_info.arguments[i];
-
- String orig_arg_name = arg_info.name;
-
- ArgumentData arg;
- arg.name = orig_arg_name;
-
- if (arg_info.type == Variant::INT && arg_info.usage & PROPERTY_USAGE_CLASS_IS_ENUM) {
- arg.type.name = arg_info.class_name;
- arg.type.is_enum = true;
- } else if (arg_info.class_name != StringName()) {
- arg.type.name = arg_info.class_name;
- } else if (arg_info.hint == PROPERTY_HINT_RESOURCE_TYPE) {
- arg.type.name = arg_info.hint_string;
- } else if (arg_info.type == Variant::NIL) {
- arg.type.name = r_context.names_cache.variant_type;
- } else {
- // NOTE: We don't care about the size and sign of int and float in these tests
- arg.type.name = Variant::get_type_name(arg_info.type);
- }
-
- if (m && m->has_default_argument(i)) {
- arg.has_defval = true;
- arg.defval = m->get_default_argument(i);
- }
-
- method.arguments.push_back(arg);
- }
-
- if (method.is_vararg) {
- ArgumentData vararg;
- vararg.type.name = r_context.names_cache.vararg_stub_type;
- vararg.name = "@varargs@";
- method.arguments.push_back(vararg);
- }
-
- TEST_COND(exposed_class.find_property_by_name(method.name),
- "Method name conflicts with property: '" + String(class_name) + "." + String(method.name) + "'.");
-
- // Classes starting with an underscore are ignored unless they're used as a property setter or getter
- if (!method.is_virtual && String(method.name)[0] == '_') {
- for (const List<PropertyData>::Element *F = exposed_class.properties.front(); F; F = F->next()) {
- const PropertyData &prop = F->get();
-
- if (prop.setter == method.name || prop.getter == method.name) {
- exposed_class.methods.push_back(method);
- break;
- }
- }
- } else {
- exposed_class.methods.push_back(method);
- }
- }
-
- // Add signals
-
- const HashMap<StringName, MethodInfo> &signal_map = class_info->signal_map;
- const StringName *k = nullptr;
-
- while ((k = signal_map.next(k))) {
- SignalData signal;
-
- const MethodInfo &method_info = signal_map.get(*k);
-
- signal.name = method_info.name;
-
- int argc = method_info.arguments.size();
-
- for (int i = 0; i < argc; i++) {
- PropertyInfo arg_info = method_info.arguments[i];
-
- String orig_arg_name = arg_info.name;
-
- ArgumentData arg;
- arg.name = orig_arg_name;
-
- if (arg_info.type == Variant::INT && arg_info.usage & PROPERTY_USAGE_CLASS_IS_ENUM) {
- arg.type.name = arg_info.class_name;
- arg.type.is_enum = true;
- } else if (arg_info.class_name != StringName()) {
- arg.type.name = arg_info.class_name;
- } else if (arg_info.hint == PROPERTY_HINT_RESOURCE_TYPE) {
- arg.type.name = arg_info.hint_string;
- } else if (arg_info.type == Variant::NIL) {
- arg.type.name = r_context.names_cache.variant_type;
- } else {
- // NOTE: We don't care about the size and sign of int and float in these tests
- arg.type.name = Variant::get_type_name(arg_info.type);
- }
-
- signal.arguments.push_back(arg);
- }
-
- bool method_conflict = exposed_class.find_property_by_name(signal.name);
-
- if (method_conflict || exposed_class.find_method_by_name(signal.name)) {
- // TODO:
- // ClassDB allows signal names that conflict with method or property names.
- // However registering a signal with a conflicting name is still considered wrong.
- // Unfortunately there are some existing cases that are yet to be fixed.
- // Until those are fixed we will print a warning instead of failing the test.
- WARN_PRINT("Signal name conflicts with " + String(method_conflict ? "method" : "property") +
- ": '" + String(class_name) + "." + String(signal.name) + "'.");
- }
-
- exposed_class.signals_.push_back(signal);
- }
-
- // Add enums and constants
-
- List<String> constants;
- ClassDB::get_integer_constant_list(class_name, &constants, true);
-
- const HashMap<StringName, List<StringName>> &enum_map = class_info->enum_map;
- k = nullptr;
-
- while ((k = enum_map.next(k))) {
- EnumData enum_;
- enum_.name = *k;
-
- const List<StringName> &enum_constants = enum_map.get(*k);
- for (const List<StringName>::Element *E = enum_constants.front(); E; E = E->next()) {
- const StringName &constant_name = E->get();
- int *value = class_info->constant_map.getptr(constant_name);
- TEST_FAIL_COND(!value, "Missing enum constant value: '" +
- String(class_name) + "." + String(enum_.name) + "." + String(constant_name) + "'.");
- constants.erase(constant_name);
-
- ConstantData constant;
- constant.name = constant_name;
- constant.value = *value;
-
- enum_.constants.push_back(constant);
- }
-
- exposed_class.enums.push_back(enum_);
-
- r_context.enum_types.push_back(String(class_name) + "." + String(*k));
- }
-
- for (const List<String>::Element *E = constants.front(); E; E = E->next()) {
- const String &constant_name = E->get();
- int *value = class_info->constant_map.getptr(StringName(E->get()));
- TEST_FAIL_COND(!value, "Missing enum constant value: '" + String(class_name) + "." + String(constant_name) + "'.");
-
- ConstantData constant;
- constant.name = constant_name;
- constant.value = *value;
-
- exposed_class.constants.push_back(constant);
- }
-
- r_context.exposed_classes.insert(class_name, exposed_class);
- class_list.pop_front();
- }
-
- TEST_END();
-}
-
-void add_builtin_types(Context &r_context) {
- // NOTE: We don't care about the size and sign of int and float in these tests
- for (int i = 0; i < Variant::VARIANT_MAX; i++) {
- r_context.builtin_types.push_back(Variant::get_type_name(Variant::Type(i)));
- }
-
- r_context.builtin_types.push_back(_STR(Variant));
- r_context.builtin_types.push_back(r_context.names_cache.vararg_stub_type);
- r_context.builtin_types.push_back("void");
-}
-
-void add_global_enums(Context &r_context) {
- int global_constants_count = GlobalConstants::get_global_constant_count();
-
- if (global_constants_count > 0) {
- for (int i = 0; i < global_constants_count; i++) {
- StringName enum_name = GlobalConstants::get_global_constant_enum(i);
-
- if (enum_name != StringName()) {
- ConstantData constant;
- constant.name = GlobalConstants::get_global_constant_name(i);
- constant.value = GlobalConstants::get_global_constant_value(i);
-
- EnumData enum_;
- enum_.name = enum_name;
- List<EnumData>::Element *enum_match = r_context.global_enums.find(enum_);
- if (enum_match) {
- enum_match->get().constants.push_back(constant);
- } else {
- enum_.constants.push_back(constant);
- r_context.global_enums.push_back(enum_);
- }
- }
- }
-
- for (List<EnumData>::Element *E = r_context.global_enums.front(); E; E = E->next()) {
- r_context.enum_types.push_back(E->get().name);
- }
- }
-
- // HARDCODED
- List<StringName> hardcoded_enums;
- hardcoded_enums.push_back("Vector2.Axis");
- hardcoded_enums.push_back("Vector2i.Axis");
- hardcoded_enums.push_back("Vector3.Axis");
- hardcoded_enums.push_back("Vector3i.Axis");
- for (List<StringName>::Element *E = hardcoded_enums.front(); E; E = E->next()) {
- // These enums are not generated and must be written manually (e.g.: Vector3.Axis)
- // Here, we assume core types do not begin with underscore
- r_context.enum_types.push_back(E->get());
- }
-}
-
-TestResult run_class_db_tests() {
- TEST_START();
-
- Context context;
-
- TEST_FAIL_CHECK(add_exposed_classes(context));
- add_builtin_types(context);
- add_global_enums(context);
-
- const ExposedClass *object_class = context.find_exposed_class(context.names_cache.object_class);
- TEST_FAIL_COND(!object_class, "Object class not found.");
- TEST_FAIL_COND(object_class->base != StringName(),
- "Object class derives from another class: '" + object_class->base + "'.");
-
- for (ExposedClasses::Element E = context.exposed_classes.front(); E; E = E.next()) {
- TEST_CHECK(validate_class(context, E.value()));
- }
-
- TEST_END();
-}
-
-MainLoop *test() {
- TestResult pass = run_class_db_tests();
-
- OS::get_singleton()->print("ClassDB tests: %s\n", pass == TestResult::PASS ? "PASS" : "FAILED");
-
- if (pass == TestResult::FAILED) {
- OS::get_singleton()->set_exit_code(pass == TestResult::PASS ? 0 : 1);
- }
-
- return nullptr;
-}
-
-} // namespace TestClassDB
diff --git a/tests/test_class_db.h b/tests/test_class_db.h
index 1a31cfb01b..9a30891c16 100644
--- a/tests/test_class_db.h
+++ b/tests/test_class_db.h
@@ -31,12 +31,805 @@
#ifndef GODOT_TEST_CLASS_DB_H
#define GODOT_TEST_CLASS_DB_H
-#include "core/os/main_loop.h"
+#include "core/register_core_types.h"
+
+#include "core/core_constants.h"
+#include "core/os/os.h"
+#include "core/string/string_name.h"
+#include "core/string/ustring.h"
+#include "core/templates/ordered_hash_map.h"
+#include "core/variant/variant.h"
+
+#include "tests/test_macros.h"
+
+#define TEST_COND DOCTEST_CHECK_FALSE_MESSAGE
+#define TEST_FAIL DOCTEST_FAIL
+#define TEST_FAIL_COND DOCTEST_REQUIRE_FALSE_MESSAGE
+#define TEST_FAIL_COND_WARN DOCTEST_WARN_FALSE_MESSAGE
namespace TestClassDB {
-MainLoop *test();
+struct TypeReference {
+ StringName name;
+ bool is_enum = false;
+};
+
+struct ConstantData {
+ String name;
+ int value = 0;
+};
+
+struct EnumData {
+ StringName name;
+ List<ConstantData> constants;
+
+ _FORCE_INLINE_ bool operator==(const EnumData &p_enum) const {
+ return p_enum.name == name;
+ }
+};
+
+struct PropertyData {
+ StringName name;
+ int index = 0;
+
+ StringName getter;
+ StringName setter;
+};
+
+struct ArgumentData {
+ TypeReference type;
+ String name;
+ bool has_defval = false;
+ Variant defval;
+};
+
+struct MethodData {
+ StringName name;
+ TypeReference return_type;
+ List<ArgumentData> arguments;
+ bool is_virtual = false;
+ bool is_vararg = false;
+};
+
+struct SignalData {
+ StringName name;
+ List<ArgumentData> arguments;
+};
+
+struct ExposedClass {
+ StringName name;
+ StringName base;
+
+ bool is_singleton = false;
+ bool is_instantiable = false;
+ bool is_reference = false;
+
+ ClassDB::APIType api_type;
+
+ List<ConstantData> constants;
+ List<EnumData> enums;
+ List<PropertyData> properties;
+ List<MethodData> methods;
+ List<SignalData> signals_;
+
+ const PropertyData *find_property_by_name(const StringName &p_name) const {
+ for (const List<PropertyData>::Element *E = properties.front(); E; E = E->next()) {
+ if (E->get().name == p_name) {
+ return &E->get();
+ }
+ }
+
+ return nullptr;
+ }
+
+ const MethodData *find_method_by_name(const StringName &p_name) const {
+ for (const List<MethodData>::Element *E = methods.front(); E; E = E->next()) {
+ if (E->get().name == p_name) {
+ return &E->get();
+ }
+ }
+
+ return nullptr;
+ }
+};
+
+struct NamesCache {
+ StringName variant_type = StaticCString::create("Variant");
+ StringName object_class = StaticCString::create("Object");
+ StringName reference_class = StaticCString::create("Reference");
+ StringName string_type = StaticCString::create("String");
+ StringName string_name_type = StaticCString::create("StringName");
+ StringName node_path_type = StaticCString::create("NodePath");
+ StringName bool_type = StaticCString::create("bool");
+ StringName int_type = StaticCString::create("int");
+ StringName float_type = StaticCString::create("float");
+ StringName void_type = StaticCString::create("void");
+ StringName vararg_stub_type = StaticCString::create("@VarArg@");
+ StringName vector2_type = StaticCString::create("Vector2");
+ StringName rect2_type = StaticCString::create("Rect2");
+ StringName vector3_type = StaticCString::create("Vector3");
+
+ // Object not included as it must be checked for all derived classes
+ static constexpr int nullable_types_count = 17;
+ StringName nullable_types[nullable_types_count] = {
+ string_type,
+ string_name_type,
+ node_path_type,
+
+ StaticCString::create(_STR(Array)),
+ StaticCString::create(_STR(Dictionary)),
+ StaticCString::create(_STR(Callable)),
+ StaticCString::create(_STR(Signal)),
+
+ StaticCString::create(_STR(PackedByteArray)),
+ StaticCString::create(_STR(PackedInt32Array)),
+ StaticCString::create(_STR(PackedInt64rray)),
+ StaticCString::create(_STR(PackedFloat32Array)),
+ StaticCString::create(_STR(PackedFloat64Array)),
+ StaticCString::create(_STR(PackedStringArray)),
+ StaticCString::create(_STR(PackedVector2Array)),
+ StaticCString::create(_STR(PackedVector3Array)),
+ StaticCString::create(_STR(PackedColorArray)),
+ };
+
+ bool is_nullable_type(const StringName &p_type) const {
+ for (int i = 0; i < nullable_types_count; i++) {
+ if (p_type == nullable_types[i]) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+};
+
+typedef OrderedHashMap<StringName, ExposedClass> ExposedClasses;
+
+struct Context {
+ Vector<StringName> enum_types;
+ Vector<StringName> builtin_types;
+ ExposedClasses exposed_classes;
+ List<EnumData> global_enums;
+ NamesCache names_cache;
+
+ const ExposedClass *find_exposed_class(const StringName &p_name) const {
+ ExposedClasses::ConstElement elem = exposed_classes.find(p_name);
+ return elem ? &elem.value() : nullptr;
+ }
+
+ const ExposedClass *find_exposed_class(const TypeReference &p_type_ref) const {
+ ExposedClasses::ConstElement elem = exposed_classes.find(p_type_ref.name);
+ return elem ? &elem.value() : nullptr;
+ }
+
+ bool has_type(const TypeReference &p_type_ref) const {
+ if (builtin_types.find(p_type_ref.name) >= 0) {
+ return true;
+ }
+
+ if (p_type_ref.is_enum) {
+ if (enum_types.find(p_type_ref.name) >= 0) {
+ return true;
+ }
+
+ // Enum not found. Most likely because none of its constants were bound, so it's empty. That's fine. Use int instead.
+ return builtin_types.find(names_cache.int_type);
+ }
+
+ return false;
+ }
+};
+
+bool arg_default_value_is_assignable_to_type(const Context &p_context, const Variant &p_val, const TypeReference &p_arg_type, String *r_err_msg = nullptr) {
+ if (p_arg_type.name == p_context.names_cache.variant_type) {
+ // Variant can take anything
+ return true;
+ }
+
+ switch (p_val.get_type()) {
+ case Variant::NIL:
+ return p_context.find_exposed_class(p_arg_type) ||
+ p_context.names_cache.is_nullable_type(p_arg_type.name);
+ case Variant::BOOL:
+ return p_arg_type.name == p_context.names_cache.bool_type;
+ case Variant::INT:
+ return p_arg_type.name == p_context.names_cache.int_type ||
+ p_arg_type.name == p_context.names_cache.float_type ||
+ p_arg_type.is_enum;
+ case Variant::FLOAT:
+ return p_arg_type.name == p_context.names_cache.float_type;
+ case Variant::STRING:
+ case Variant::STRING_NAME:
+ return p_arg_type.name == p_context.names_cache.string_type ||
+ p_arg_type.name == p_context.names_cache.string_name_type ||
+ p_arg_type.name == p_context.names_cache.node_path_type;
+ case Variant::NODE_PATH:
+ return p_arg_type.name == p_context.names_cache.node_path_type;
+ case Variant::TRANSFORM:
+ case Variant::TRANSFORM2D:
+ case Variant::BASIS:
+ case Variant::QUAT:
+ case Variant::PLANE:
+ case Variant::AABB:
+ case Variant::COLOR:
+ case Variant::VECTOR2:
+ case Variant::RECT2:
+ case Variant::VECTOR3:
+ case Variant::RID:
+ case Variant::ARRAY:
+ case Variant::DICTIONARY:
+ case Variant::PACKED_BYTE_ARRAY:
+ case Variant::PACKED_INT32_ARRAY:
+ case Variant::PACKED_INT64_ARRAY:
+ case Variant::PACKED_FLOAT32_ARRAY:
+ case Variant::PACKED_FLOAT64_ARRAY:
+ case Variant::PACKED_STRING_ARRAY:
+ case Variant::PACKED_VECTOR2_ARRAY:
+ case Variant::PACKED_VECTOR3_ARRAY:
+ case Variant::PACKED_COLOR_ARRAY:
+ case Variant::CALLABLE:
+ case Variant::SIGNAL:
+ return p_arg_type.name == Variant::get_type_name(p_val.get_type());
+ case Variant::OBJECT:
+ return p_context.find_exposed_class(p_arg_type);
+ case Variant::VECTOR2I:
+ return p_arg_type.name == p_context.names_cache.vector2_type ||
+ p_arg_type.name == Variant::get_type_name(p_val.get_type());
+ case Variant::RECT2I:
+ return p_arg_type.name == p_context.names_cache.rect2_type ||
+ p_arg_type.name == Variant::get_type_name(p_val.get_type());
+ case Variant::VECTOR3I:
+ return p_arg_type.name == p_context.names_cache.vector3_type ||
+ p_arg_type.name == Variant::get_type_name(p_val.get_type());
+ default:
+ if (r_err_msg) {
+ *r_err_msg = "Unexpected Variant type: " + itos(p_val.get_type());
+ }
+ break;
+ }
+
+ return false;
+}
+
+void validate_property(const Context &p_context, const ExposedClass &p_class, const PropertyData &p_prop) {
+ const MethodData *setter = p_class.find_method_by_name(p_prop.setter);
+
+ // Search it in base classes too
+ const ExposedClass *top = &p_class;
+ while (!setter && top->base != StringName()) {
+ top = p_context.find_exposed_class(top->base);
+ TEST_FAIL_COND(!top, "Class not found '" + top->base + "'. Inherited by '" + top->name + "'.");
+ setter = top->find_method_by_name(p_prop.setter);
+ }
+
+ const MethodData *getter = p_class.find_method_by_name(p_prop.getter);
+
+ // Search it in base classes too
+ top = &p_class;
+ while (!getter && top->base != StringName()) {
+ top = p_context.find_exposed_class(top->base);
+ TEST_FAIL_COND(!top, "Class not found '" + top->base + "'. Inherited by '" + top->name + "'.");
+ getter = top->find_method_by_name(p_prop.getter);
+ }
+
+ TEST_FAIL_COND((!setter && !getter),
+ "Couldn't find neither the setter nor the getter for property: '" + p_class.name + "." + String(p_prop.name) + "'.");
+
+ if (setter) {
+ int setter_argc = p_prop.index != -1 ? 2 : 1;
+ TEST_FAIL_COND(setter->arguments.size() != setter_argc,
+ "Invalid property setter argument count: '" + p_class.name + "." + String(p_prop.name) + "'.");
+ }
+
+ if (getter) {
+ int getter_argc = p_prop.index != -1 ? 1 : 0;
+ TEST_FAIL_COND(getter->arguments.size() != getter_argc,
+ "Invalid property setter argument count: '" + p_class.name + "." + String(p_prop.name) + "'.");
+ }
+
+ if (getter && setter) {
+ const ArgumentData &setter_first_arg = setter->arguments.back()->get();
+ if (getter->return_type.name != setter_first_arg.type.name) {
+ // Special case for Node::set_name
+ bool whitelisted = getter->return_type.name == p_context.names_cache.string_name_type &&
+ setter_first_arg.type.name == p_context.names_cache.string_type;
+
+ TEST_FAIL_COND(!whitelisted,
+ "Return type from getter doesn't match first argument of setter, for property: '" + p_class.name + "." + String(p_prop.name) + "'.");
+ }
+ }
+
+ const TypeReference &prop_type_ref = getter ? getter->return_type : setter->arguments.back()->get().type;
+
+ const ExposedClass *prop_class = p_context.find_exposed_class(prop_type_ref);
+ if (prop_class) {
+ TEST_COND(prop_class->is_singleton,
+ "Property type is a singleton: '" + p_class.name + "." + String(p_prop.name) + "'.");
+ } else {
+ TEST_FAIL_COND(!p_context.has_type(prop_type_ref),
+ "Property type '" + prop_type_ref.name + "' not found: '" + p_class.name + "." + String(p_prop.name) + "'.");
+ }
+
+ if (getter) {
+ if (p_prop.index != -1) {
+ const ArgumentData &idx_arg = getter->arguments.front()->get();
+ if (idx_arg.type.name != p_context.names_cache.int_type) {
+ // If not an int, it can be an enum
+ TEST_COND(p_context.enum_types.find(idx_arg.type.name) < 0,
+ "Invalid type '" + idx_arg.type.name + "' for index argument of property getter: '" + p_class.name + "." + String(p_prop.name) + "'.");
+ }
+ }
+ }
+
+ if (setter) {
+ if (p_prop.index != -1) {
+ const ArgumentData &idx_arg = setter->arguments.front()->get();
+ if (idx_arg.type.name != p_context.names_cache.int_type) {
+ // Assume the index parameter is an enum
+ // If not an int, it can be an enum
+ TEST_COND(p_context.enum_types.find(idx_arg.type.name) < 0,
+ "Invalid type '" + idx_arg.type.name + "' for index argument of property setter: '" + p_class.name + "." + String(p_prop.name) + "'.");
+ }
+ }
+ }
+}
+
+void validate_method(const Context &p_context, const ExposedClass &p_class, const MethodData &p_method) {
+ const ExposedClass *return_class = p_context.find_exposed_class(p_method.return_type);
+ if (return_class) {
+ TEST_COND(return_class->is_singleton,
+ "Method return type is a singleton: '" + p_class.name + "." + p_method.name + "'.");
+ }
+
+ for (const List<ArgumentData>::Element *F = p_method.arguments.front(); F; F = F->next()) {
+ const ArgumentData &arg = F->get();
+
+ const ExposedClass *arg_class = p_context.find_exposed_class(arg.type);
+ if (arg_class) {
+ TEST_COND(arg_class->is_singleton,
+ "Argument type is a singleton: '" + arg.name + "' of method '" + p_class.name + "." + p_method.name + "'.");
+ } else {
+ TEST_FAIL_COND(!p_context.has_type(arg.type),
+ "Argument type '" + arg.type.name + "' not found: '" + arg.name + "' of method" + p_class.name + "." + p_method.name + "'.");
+ }
+
+ if (arg.has_defval) {
+ String type_error_msg;
+ bool arg_defval_assignable_to_type = arg_default_value_is_assignable_to_type(p_context, arg.defval, arg.type, &type_error_msg);
+ String err_msg = vformat("Invalid default value for parameter '%s' of method '%s.%s'.", arg.name, p_class.name, p_method.name);
+ if (!type_error_msg.empty()) {
+ err_msg += " " + type_error_msg;
+ }
+ TEST_COND(!arg_defval_assignable_to_type, err_msg.utf8().get_data());
+ }
+ }
+}
+
+void validate_signal(const Context &p_context, const ExposedClass &p_class, const SignalData &p_signal) {
+ for (const List<ArgumentData>::Element *F = p_signal.arguments.front(); F; F = F->next()) {
+ const ArgumentData &arg = F->get();
+
+ const ExposedClass *arg_class = p_context.find_exposed_class(arg.type);
+ if (arg_class) {
+ TEST_COND(arg_class->is_singleton,
+ "Argument class is a singleton: '" + arg.name + "' of signal" + p_class.name + "." + p_signal.name + "'.");
+ } else {
+ TEST_FAIL_COND(!p_context.has_type(arg.type),
+ "Argument type '" + arg.type.name + "' not found: '" + arg.name + "' of signal" + p_class.name + "." + p_signal.name + "'.");
+ }
+ }
+}
+
+void validate_class(const Context &p_context, const ExposedClass &p_exposed_class) {
+ bool is_derived_type = p_exposed_class.base != StringName();
+
+ if (!is_derived_type) {
+ // Asserts about the base Object class
+ TEST_FAIL_COND(p_exposed_class.name != p_context.names_cache.object_class,
+ "Class '" + p_exposed_class.name + "' has no base class.");
+ TEST_FAIL_COND(!p_exposed_class.is_instantiable,
+ "Object class is not instantiable.");
+ TEST_FAIL_COND(p_exposed_class.api_type != ClassDB::API_CORE,
+ "Object class is API is not API_CORE.");
+ TEST_FAIL_COND(p_exposed_class.is_singleton,
+ "Object class is registered as a singleton.");
+ }
+
+ TEST_FAIL_COND((p_exposed_class.is_singleton && p_exposed_class.base != p_context.names_cache.object_class),
+ "Singleton base class '" + String(p_exposed_class.base) + "' is not Object, for class '" + p_exposed_class.name + "'.");
+
+ TEST_FAIL_COND((is_derived_type && !p_context.exposed_classes.has(p_exposed_class.base)),
+ "Base type '" + p_exposed_class.base.operator String() + "' does not exist, for class '" + p_exposed_class.name + "'.");
+
+ for (const List<PropertyData>::Element *F = p_exposed_class.properties.front(); F; F = F->next()) {
+ validate_property(p_context, p_exposed_class, F->get());
+ }
+
+ for (const List<MethodData>::Element *F = p_exposed_class.methods.front(); F; F = F->next()) {
+ validate_method(p_context, p_exposed_class, F->get());
+ }
+
+ for (const List<SignalData>::Element *F = p_exposed_class.signals_.front(); F; F = F->next()) {
+ validate_signal(p_context, p_exposed_class, F->get());
+ }
+}
+
+void add_exposed_classes(Context &r_context) {
+ List<StringName> class_list;
+ ClassDB::get_class_list(&class_list);
+ class_list.sort_custom<StringName::AlphCompare>();
+
+ while (class_list.size()) {
+ StringName class_name = class_list.front()->get();
+
+ ClassDB::APIType api_type = ClassDB::get_api_type(class_name);
+
+ if (api_type == ClassDB::API_NONE) {
+ class_list.pop_front();
+ continue;
+ }
+
+ if (!ClassDB::is_class_exposed(class_name)) {
+ MESSAGE(vformat("Ignoring class '%s' because it's not exposed.", class_name).utf8().get_data());
+ class_list.pop_front();
+ continue;
+ }
+
+ if (!ClassDB::is_class_enabled(class_name)) {
+ MESSAGE(vformat("Ignoring class '%s' because it's not enabled.", class_name).utf8().get_data());
+ class_list.pop_front();
+ continue;
+ }
+
+ ClassDB::ClassInfo *class_info = ClassDB::classes.getptr(class_name);
+
+ ExposedClass exposed_class;
+ exposed_class.name = class_name;
+ exposed_class.api_type = api_type;
+ exposed_class.is_singleton = Engine::get_singleton()->has_singleton(class_name);
+ exposed_class.is_instantiable = class_info->creation_func && !exposed_class.is_singleton;
+ exposed_class.is_reference = ClassDB::is_parent_class(class_name, "Reference");
+ exposed_class.base = ClassDB::get_parent_class(class_name);
+
+ // Add properties
+
+ List<PropertyInfo> property_list;
+ ClassDB::get_property_list(class_name, &property_list, true);
+
+ Map<StringName, StringName> accessor_methods;
+
+ for (const List<PropertyInfo>::Element *E = property_list.front(); E; E = E->next()) {
+ const PropertyInfo &property = E->get();
+
+ if (property.usage & PROPERTY_USAGE_GROUP || property.usage & PROPERTY_USAGE_SUBGROUP || property.usage & PROPERTY_USAGE_CATEGORY) {
+ continue;
+ }
+
+ PropertyData prop;
+ prop.name = property.name;
+ prop.setter = ClassDB::get_property_setter(class_name, prop.name);
+ prop.getter = ClassDB::get_property_getter(class_name, prop.name);
+
+ if (prop.setter != StringName()) {
+ accessor_methods[prop.setter] = prop.name;
+ }
+ if (prop.getter != StringName()) {
+ accessor_methods[prop.getter] = prop.name;
+ }
+
+ bool valid = false;
+ prop.index = ClassDB::get_property_index(class_name, prop.name, &valid);
+ TEST_FAIL_COND(!valid, "Invalid property: '" + exposed_class.name + "." + String(prop.name) + "'.");
+
+ exposed_class.properties.push_back(prop);
+ }
+
+ // Add methods
+
+ List<MethodInfo> virtual_method_list;
+ ClassDB::get_virtual_methods(class_name, &virtual_method_list, true);
+
+ List<MethodInfo> method_list;
+ ClassDB::get_method_list(class_name, &method_list, true);
+ method_list.sort();
+
+ for (List<MethodInfo>::Element *E = method_list.front(); E; E = E->next()) {
+ const MethodInfo &method_info = E->get();
+
+ int argc = method_info.arguments.size();
+
+ if (method_info.name.empty()) {
+ continue;
+ }
+
+ MethodData method;
+ method.name = method_info.name;
+
+ if (method_info.flags & METHOD_FLAG_VIRTUAL) {
+ method.is_virtual = true;
+ }
+
+ PropertyInfo return_info = method_info.return_val;
+
+ MethodBind *m = method.is_virtual ? nullptr : ClassDB::get_method(class_name, method_info.name);
+
+ method.is_vararg = m && m->is_vararg();
+
+ if (!m && !method.is_virtual) {
+ TEST_FAIL_COND(!virtual_method_list.find(method_info),
+ "Missing MethodBind for non-virtual method: '" + exposed_class.name + "." + method.name + "'.");
+
+ // A virtual method without the virtual flag. This is a special case.
+
+ // The method Object.free is registered as a virtual method, but without the virtual flag.
+ // This is because this method is not supposed to be overridden, but called.
+ // We assume the return type is void.
+ method.return_type.name = r_context.names_cache.void_type;
+
+ // Actually, more methods like this may be added in the future, which could return
+ // something different. Let's put this check to notify us if that ever happens.
+ String warn_msg = vformat(
+ "Notification: New unexpected virtual non-overridable method found. "
+ "We only expected Object.free, but found '%s.%s'.",
+ exposed_class.name, method.name);
+ TEST_FAIL_COND_WARN(
+ (exposed_class.name != r_context.names_cache.object_class || String(method.name) != "free"),
+ warn_msg.utf8().get_data());
+
+ } else if (return_info.type == Variant::INT && return_info.usage & PROPERTY_USAGE_CLASS_IS_ENUM) {
+ method.return_type.name = return_info.class_name;
+ method.return_type.is_enum = true;
+ } else if (return_info.class_name != StringName()) {
+ method.return_type.name = return_info.class_name;
+
+ bool bad_reference_hint = !method.is_virtual && return_info.hint != PROPERTY_HINT_RESOURCE_TYPE &&
+ ClassDB::is_parent_class(return_info.class_name, r_context.names_cache.reference_class);
+ TEST_COND(bad_reference_hint, String() + "Return type is reference but hint is not '" _STR(PROPERTY_HINT_RESOURCE_TYPE) "'." +
+ " Are you returning a reference type by pointer? Method: '" +
+ exposed_class.name + "." + method.name + "'.");
+ } else if (return_info.hint == PROPERTY_HINT_RESOURCE_TYPE) {
+ method.return_type.name = return_info.hint_string;
+ } else if (return_info.type == Variant::NIL && return_info.usage & PROPERTY_USAGE_NIL_IS_VARIANT) {
+ method.return_type.name = r_context.names_cache.variant_type;
+ } else if (return_info.type == Variant::NIL) {
+ method.return_type.name = r_context.names_cache.void_type;
+ } else {
+ // NOTE: We don't care about the size and sign of int and float in these tests
+ method.return_type.name = Variant::get_type_name(return_info.type);
+ }
+
+ for (int i = 0; i < argc; i++) {
+ PropertyInfo arg_info = method_info.arguments[i];
+
+ String orig_arg_name = arg_info.name;
+
+ ArgumentData arg;
+ arg.name = orig_arg_name;
+
+ if (arg_info.type == Variant::INT && arg_info.usage & PROPERTY_USAGE_CLASS_IS_ENUM) {
+ arg.type.name = arg_info.class_name;
+ arg.type.is_enum = true;
+ } else if (arg_info.class_name != StringName()) {
+ arg.type.name = arg_info.class_name;
+ } else if (arg_info.hint == PROPERTY_HINT_RESOURCE_TYPE) {
+ arg.type.name = arg_info.hint_string;
+ } else if (arg_info.type == Variant::NIL) {
+ arg.type.name = r_context.names_cache.variant_type;
+ } else {
+ // NOTE: We don't care about the size and sign of int and float in these tests
+ arg.type.name = Variant::get_type_name(arg_info.type);
+ }
+
+ if (m && m->has_default_argument(i)) {
+ arg.has_defval = true;
+ arg.defval = m->get_default_argument(i);
+ }
+
+ method.arguments.push_back(arg);
+ }
+
+ if (method.is_vararg) {
+ ArgumentData vararg;
+ vararg.type.name = r_context.names_cache.vararg_stub_type;
+ vararg.name = "@varargs@";
+ method.arguments.push_back(vararg);
+ }
+
+ TEST_COND(exposed_class.find_property_by_name(method.name),
+ "Method name conflicts with property: '" + String(class_name) + "." + String(method.name) + "'.");
+
+ // Classes starting with an underscore are ignored unless they're used as a property setter or getter
+ if (!method.is_virtual && String(method.name)[0] == '_') {
+ for (const List<PropertyData>::Element *F = exposed_class.properties.front(); F; F = F->next()) {
+ const PropertyData &prop = F->get();
+
+ if (prop.setter == method.name || prop.getter == method.name) {
+ exposed_class.methods.push_back(method);
+ break;
+ }
+ }
+ } else {
+ exposed_class.methods.push_back(method);
+ }
+ }
+
+ // Add signals
+
+ const HashMap<StringName, MethodInfo> &signal_map = class_info->signal_map;
+ const StringName *k = nullptr;
+
+ while ((k = signal_map.next(k))) {
+ SignalData signal;
+
+ const MethodInfo &method_info = signal_map.get(*k);
+
+ signal.name = method_info.name;
+
+ int argc = method_info.arguments.size();
+
+ for (int i = 0; i < argc; i++) {
+ PropertyInfo arg_info = method_info.arguments[i];
+
+ String orig_arg_name = arg_info.name;
+
+ ArgumentData arg;
+ arg.name = orig_arg_name;
+
+ if (arg_info.type == Variant::INT && arg_info.usage & PROPERTY_USAGE_CLASS_IS_ENUM) {
+ arg.type.name = arg_info.class_name;
+ arg.type.is_enum = true;
+ } else if (arg_info.class_name != StringName()) {
+ arg.type.name = arg_info.class_name;
+ } else if (arg_info.hint == PROPERTY_HINT_RESOURCE_TYPE) {
+ arg.type.name = arg_info.hint_string;
+ } else if (arg_info.type == Variant::NIL) {
+ arg.type.name = r_context.names_cache.variant_type;
+ } else {
+ // NOTE: We don't care about the size and sign of int and float in these tests
+ arg.type.name = Variant::get_type_name(arg_info.type);
+ }
+
+ signal.arguments.push_back(arg);
+ }
+
+ bool method_conflict = exposed_class.find_property_by_name(signal.name);
+
+ // TODO:
+ // ClassDB allows signal names that conflict with method or property names.
+ // However registering a signal with a conflicting name is still considered wrong.
+ // Unfortunately there are some existing cases that are yet to be fixed.
+ // Until those are fixed we will print a warning instead of failing the test.
+ String warn_msg = vformat(
+ "Signal name conflicts with %s: '%s.%s.",
+ method_conflict ? "method" : "property", class_name, signal.name);
+ TEST_FAIL_COND_WARN((method_conflict || exposed_class.find_method_by_name(signal.name)),
+ warn_msg.utf8().get_data());
+
+ exposed_class.signals_.push_back(signal);
+ }
+
+ // Add enums and constants
+
+ List<String> constants;
+ ClassDB::get_integer_constant_list(class_name, &constants, true);
+
+ const HashMap<StringName, List<StringName>> &enum_map = class_info->enum_map;
+ k = nullptr;
+
+ while ((k = enum_map.next(k))) {
+ EnumData enum_;
+ enum_.name = *k;
+
+ const List<StringName> &enum_constants = enum_map.get(*k);
+ for (const List<StringName>::Element *E = enum_constants.front(); E; E = E->next()) {
+ const StringName &constant_name = E->get();
+ int *value = class_info->constant_map.getptr(constant_name);
+ TEST_FAIL_COND(!value, "Missing enum constant value: '" +
+ String(class_name) + "." + String(enum_.name) + "." + String(constant_name) + "'.");
+ constants.erase(constant_name);
+
+ ConstantData constant;
+ constant.name = constant_name;
+ constant.value = *value;
+
+ enum_.constants.push_back(constant);
+ }
+
+ exposed_class.enums.push_back(enum_);
+
+ r_context.enum_types.push_back(String(class_name) + "." + String(*k));
+ }
+
+ for (const List<String>::Element *E = constants.front(); E; E = E->next()) {
+ const String &constant_name = E->get();
+ int *value = class_info->constant_map.getptr(StringName(E->get()));
+ TEST_FAIL_COND(!value, "Missing enum constant value: '" + String(class_name) + "." + String(constant_name) + "'.");
+
+ ConstantData constant;
+ constant.name = constant_name;
+ constant.value = *value;
+
+ exposed_class.constants.push_back(constant);
+ }
+
+ r_context.exposed_classes.insert(class_name, exposed_class);
+ class_list.pop_front();
+ }
+}
+
+void add_builtin_types(Context &r_context) {
+ // NOTE: We don't care about the size and sign of int and float in these tests
+ for (int i = 0; i < Variant::VARIANT_MAX; i++) {
+ r_context.builtin_types.push_back(Variant::get_type_name(Variant::Type(i)));
+ }
+
+ r_context.builtin_types.push_back(_STR(Variant));
+ r_context.builtin_types.push_back(r_context.names_cache.vararg_stub_type);
+ r_context.builtin_types.push_back("void");
+}
+
+void add_global_enums(Context &r_context) {
+ int global_constants_count = CoreConstants::get_global_constant_count();
+
+ if (global_constants_count > 0) {
+ for (int i = 0; i < global_constants_count; i++) {
+ StringName enum_name = CoreConstants::get_global_constant_enum(i);
+
+ if (enum_name != StringName()) {
+ ConstantData constant;
+ constant.name = CoreConstants::get_global_constant_name(i);
+ constant.value = CoreConstants::get_global_constant_value(i);
+
+ EnumData enum_;
+ enum_.name = enum_name;
+ List<EnumData>::Element *enum_match = r_context.global_enums.find(enum_);
+ if (enum_match) {
+ enum_match->get().constants.push_back(constant);
+ } else {
+ enum_.constants.push_back(constant);
+ r_context.global_enums.push_back(enum_);
+ }
+ }
+ }
+
+ for (List<EnumData>::Element *E = r_context.global_enums.front(); E; E = E->next()) {
+ r_context.enum_types.push_back(E->get().name);
+ }
+ }
+
+ // HARDCODED
+ List<StringName> hardcoded_enums;
+ hardcoded_enums.push_back("Vector2.Axis");
+ hardcoded_enums.push_back("Vector2i.Axis");
+ hardcoded_enums.push_back("Vector3.Axis");
+ hardcoded_enums.push_back("Vector3i.Axis");
+ for (List<StringName>::Element *E = hardcoded_enums.front(); E; E = E->next()) {
+ // These enums are not generated and must be written manually (e.g.: Vector3.Axis)
+ // Here, we assume core types do not begin with underscore
+ r_context.enum_types.push_back(E->get());
+ }
+}
+
+TEST_SUITE("[ClassDB]") {
+ TEST_CASE("[ClassDB] Add exposed classes, builtin types, and global enums") {
+ Context context;
+
+ add_exposed_classes(context);
+ add_builtin_types(context);
+ add_global_enums(context);
+
+ SUBCASE("[ClassDB] Find exposed class") {
+ const ExposedClass *object_class = context.find_exposed_class(context.names_cache.object_class);
+ TEST_FAIL_COND(!object_class, "Object class not found.");
+ TEST_FAIL_COND(object_class->base != StringName(),
+ "Object class derives from another class: '" + object_class->base + "'.");
+ for (ExposedClasses::Element E = context.exposed_classes.front(); E; E = E.next()) {
+ validate_class(context, E.value());
+ }
+ }
+ }
}
+} // namespace TestClassDB
#endif //GODOT_TEST_CLASS_DB_H
diff --git a/tests/test_color.h b/tests/test_color.h
new file mode 100644
index 0000000000..c2bb63b7d0
--- /dev/null
+++ b/tests/test_color.h
@@ -0,0 +1,207 @@
+/*************************************************************************/
+/* test_color.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+#ifndef TEST_COLOR_H
+#define TEST_COLOR_H
+
+#include "core/math/color.h"
+
+#include "thirdparty/doctest/doctest.h"
+
+namespace TestColor {
+
+TEST_CASE("[Color] Constructor methods") {
+ const Color blue_rgba = Color(0.25098, 0.376471, 1, 0.501961);
+ const Color blue_html = Color::html("#4060ff80");
+ const Color blue_hex = Color::hex(0x4060ff80);
+ const Color blue_hex64 = Color::hex64(0x4040'6060'ffff'8080);
+
+ CHECK_MESSAGE(
+ blue_rgba.is_equal_approx(blue_html),
+ "Creation with HTML notation should result in components approximately equal to the default constructor.");
+ CHECK_MESSAGE(
+ blue_rgba.is_equal_approx(blue_hex),
+ "Creation with a 32-bit hexadecimal number should result in components approximately equal to the default constructor.");
+ CHECK_MESSAGE(
+ blue_rgba.is_equal_approx(blue_hex64),
+ "Creation with a 64-bit hexadecimal number should result in components approximately equal to the default constructor.");
+
+ ERR_PRINT_OFF;
+ const Color html_invalid = Color::html("invalid");
+ ERR_PRINT_ON;
+
+ CHECK_MESSAGE(
+ html_invalid.is_equal_approx(Color()),
+ "Creation with invalid HTML notation should result in a Color with the default values.");
+
+ const Color green_rgba = Color(0, 1, 0, 0.25);
+ const Color green_hsva = Color(0, 0, 0).from_hsv(120 / 360.0, 1, 1, 0.25);
+
+ CHECK_MESSAGE(
+ green_rgba.is_equal_approx(green_hsva),
+ "Creation with HSV notation should result in components approximately equal to the default constructor.");
+}
+
+TEST_CASE("[Color] Operators") {
+ const Color blue = Color(0.2, 0.2, 1);
+ const Color dark_red = Color(0.3, 0.1, 0.1);
+
+ // Color components may be negative. Also, the alpha component may be greater than 1.0.
+ CHECK_MESSAGE(
+ (blue + dark_red).is_equal_approx(Color(0.5, 0.3, 1.1, 2)),
+ "Color addition should behave as expected.");
+ CHECK_MESSAGE(
+ (blue - dark_red).is_equal_approx(Color(-0.1, 0.1, 0.9, 0)),
+ "Color subtraction should behave as expected.");
+ CHECK_MESSAGE(
+ (blue * 2).is_equal_approx(Color(0.4, 0.4, 2, 2)),
+ "Color multiplication with a scalar should behave as expected.");
+ CHECK_MESSAGE(
+ (blue / 2).is_equal_approx(Color(0.1, 0.1, 0.5, 0.5)),
+ "Color division with a scalar should behave as expected.");
+ CHECK_MESSAGE(
+ (blue * dark_red).is_equal_approx(Color(0.06, 0.02, 0.1)),
+ "Color multiplication with another Color should behave as expected.");
+ CHECK_MESSAGE(
+ (blue / dark_red).is_equal_approx(Color(0.666667, 2, 10)),
+ "Color division with another Color should behave as expected.");
+ CHECK_MESSAGE(
+ (-blue).is_equal_approx(Color(0.8, 0.8, 0, 0)),
+ "Color negation should behave as expected (affecting the alpha channel, unlike `invert()`).");
+}
+
+TEST_CASE("[Color] Reading methods") {
+ const Color dark_blue = Color(0, 0, 0.5, 0.4);
+
+ CHECK_MESSAGE(
+ Math::is_equal_approx(dark_blue.get_h(), 240 / 360.0),
+ "The returned HSV hue should match the expected value.");
+ CHECK_MESSAGE(
+ Math::is_equal_approx(dark_blue.get_s(), 1),
+ "The returned HSV saturation should match the expected value.");
+ CHECK_MESSAGE(
+ Math::is_equal_approx(dark_blue.get_v(), 0.5),
+ "The returned HSV value should match the expected value.");
+}
+
+TEST_CASE("[Color] Conversion methods") {
+ const Color cyan = Color(0, 1, 1);
+ const Color cyan_transparent = Color(0, 1, 1, 0);
+
+ CHECK_MESSAGE(
+ cyan.to_html() == "00ffffff",
+ "The returned RGB HTML color code should match the expected value.");
+ CHECK_MESSAGE(
+ cyan_transparent.to_html() == "00ffff00",
+ "The returned RGBA HTML color code should match the expected value.");
+ CHECK_MESSAGE(
+ cyan.to_argb32() == 0xff00ffff,
+ "The returned 32-bit RGB number should match the expected value.");
+ CHECK_MESSAGE(
+ cyan.to_abgr32() == 0xffffff00,
+ "The returned 32-bit BGR number should match the expected value.");
+ CHECK_MESSAGE(
+ cyan.to_rgba32() == 0x00ffffff,
+ "The returned 32-bit BGR number should match the expected value.");
+ CHECK_MESSAGE(
+ cyan.to_argb64() == 0xffff'0000'ffff'ffff,
+ "The returned 64-bit RGB number should match the expected value.");
+ CHECK_MESSAGE(
+ cyan.to_abgr64() == 0xffff'ffff'ffff'0000,
+ "The returned 64-bit BGR number should match the expected value.");
+ CHECK_MESSAGE(
+ cyan.to_rgba64() == 0x0000'ffff'ffff'ffff,
+ "The returned 64-bit BGR number should match the expected value.");
+ CHECK_MESSAGE(
+ String(cyan) == "0, 1, 1, 1",
+ "The string representation should match the expected value.");
+}
+
+TEST_CASE("[Color] Named colors") {
+ CHECK_MESSAGE(
+ Color::named("red").is_equal_approx(Color(1, 0, 0)),
+ "The named color \"red\" should match the expected value.");
+
+ // Named colors have their names automatically normalized.
+ CHECK_MESSAGE(
+ Color::named("white_smoke").is_equal_approx(Color(0.96, 0.96, 0.96)),
+ "The named color \"white_smoke\" should match the expected value.");
+ CHECK_MESSAGE(
+ Color::named("Slate Blue").is_equal_approx(Color(0.42, 0.35, 0.80)),
+ "The named color \"Slate Blue\" should match the expected value.");
+
+ ERR_PRINT_OFF;
+ CHECK_MESSAGE(
+ Color::named("doesn't exist").is_equal_approx(Color()),
+ "The invalid named color \"doesn't exist\" should result in a Color with the default values.");
+ ERR_PRINT_ON;
+}
+
+TEST_CASE("[Color] Validation methods") {
+ CHECK_MESSAGE(
+ Color::html_is_valid("#4080ff"),
+ "Valid HTML color (with leading #) should be considered valid.");
+ CHECK_MESSAGE(
+ Color::html_is_valid("4080ff"),
+ "Valid HTML color (without leading #) should be considered valid.");
+ CHECK_MESSAGE(
+ !Color::html_is_valid("12345"),
+ "Invalid HTML color should be considered invalid.");
+ CHECK_MESSAGE(
+ !Color::html_is_valid("#fuf"),
+ "Invalid HTML color should be considered invalid.");
+}
+
+TEST_CASE("[Color] Manipulation methods") {
+ const Color blue = Color(0, 0, 1, 0.4);
+
+ CHECK_MESSAGE(
+ blue.inverted().is_equal_approx(Color(1, 1, 0, 0.4)),
+ "Inverted color should have its red, green and blue components inverted.");
+
+ const Color purple = Color(0.5, 0.2, 0.5, 0.25);
+
+ CHECK_MESSAGE(
+ purple.lightened(0.2).is_equal_approx(Color(0.6, 0.36, 0.6, 0.25)),
+ "Color should be lightened by the expected amount.");
+ CHECK_MESSAGE(
+ purple.darkened(0.2).is_equal_approx(Color(0.4, 0.16, 0.4, 0.25)),
+ "Color should be darkened by the expected amount.");
+
+ const Color red = Color(1, 0, 0, 0.2);
+ const Color yellow = Color(1, 1, 0, 0.8);
+
+ CHECK_MESSAGE(
+ red.lerp(yellow, 0.5).is_equal_approx(Color(1, 0.5, 0, 0.5)),
+ "Red interpolated with yellow should be orange (with interpolated alpha).");
+}
+} // namespace TestColor
+
+#endif // TEST_COLOR_H
diff --git a/tests/test_command_queue.h b/tests/test_command_queue.h
new file mode 100644
index 0000000000..ce42d94475
--- /dev/null
+++ b/tests/test_command_queue.h
@@ -0,0 +1,481 @@
+/*************************************************************************/
+/* test_command_queue.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+#ifndef TEST_COMMAND_QUEUE_H
+#define TEST_COMMAND_QUEUE_H
+
+#include "test_command_queue.h"
+
+#include "core/config/project_settings.h"
+#include "core/os/mutex.h"
+#include "core/os/os.h"
+#include "core/os/semaphore.h"
+#include "core/os/thread.h"
+#include "core/templates/command_queue_mt.h"
+
+#if !defined(NO_THREADS)
+
+namespace TestCommandQueue {
+
+class ThreadWork {
+ Semaphore thread_sem;
+ Semaphore main_sem;
+ Mutex mut;
+ int threading_errors = 0;
+ enum State {
+ MAIN_START,
+ MAIN_DONE,
+ THREAD_START,
+ THREAD_DONE,
+ } state;
+
+public:
+ ThreadWork() {
+ mut.lock();
+ state = MAIN_START;
+ }
+ ~ThreadWork() {
+ CHECK_MESSAGE(threading_errors == 0, "threads did not lock/unlock correctly");
+ }
+ void thread_wait_for_work() {
+ thread_sem.wait();
+ mut.lock();
+ if (state != MAIN_DONE) {
+ threading_errors++;
+ }
+ state = THREAD_START;
+ }
+ void thread_done_work() {
+ if (state != THREAD_START) {
+ threading_errors++;
+ }
+ state = THREAD_DONE;
+ mut.unlock();
+ main_sem.post();
+ }
+
+ void main_wait_for_done() {
+ main_sem.wait();
+ mut.lock();
+ if (state != THREAD_DONE) {
+ threading_errors++;
+ }
+ state = MAIN_START;
+ }
+ void main_start_work() {
+ if (state != MAIN_START) {
+ threading_errors++;
+ }
+ state = MAIN_DONE;
+ mut.unlock();
+ thread_sem.post();
+ }
+};
+
+class SharedThreadState {
+public:
+ ThreadWork reader_threadwork;
+ ThreadWork writer_threadwork;
+
+ CommandQueueMT command_queue = CommandQueueMT(true);
+
+ enum TestMsgType {
+ TEST_MSG_FUNC1_TRANSFORM,
+ TEST_MSG_FUNC2_TRANSFORM_FLOAT,
+ TEST_MSG_FUNC3_TRANSFORMx6,
+ TEST_MSGSYNC_FUNC1_TRANSFORM,
+ TEST_MSGSYNC_FUNC2_TRANSFORM_FLOAT,
+ TEST_MSGRET_FUNC1_TRANSFORM,
+ TEST_MSGRET_FUNC2_TRANSFORM_FLOAT,
+ TEST_MSG_MAX
+ };
+
+ Vector<TestMsgType> message_types_to_write;
+ bool during_writing = false;
+ int message_count_to_read = 0;
+ bool exit_threads = false;
+
+ Thread *reader_thread = nullptr;
+ Thread *writer_thread = nullptr;
+
+ int func1_count = 0;
+
+ void func1(Transform t) {
+ func1_count++;
+ }
+ void func2(Transform t, float f) {
+ func1_count++;
+ }
+ void func3(Transform t1, Transform t2, Transform t3, Transform t4, Transform t5, Transform t6) {
+ func1_count++;
+ }
+ Transform func1r(Transform t) {
+ func1_count++;
+ return t;
+ }
+ Transform func2r(Transform t, float f) {
+ func1_count++;
+ return t;
+ }
+
+ void add_msg_to_write(TestMsgType type) {
+ message_types_to_write.push_back(type);
+ }
+
+ void reader_thread_loop() {
+ reader_threadwork.thread_wait_for_work();
+ while (!exit_threads) {
+ if (message_count_to_read < 0) {
+ command_queue.flush_all();
+ }
+ for (int i = 0; i < message_count_to_read; i++) {
+ command_queue.wait_and_flush_one();
+ }
+ message_count_to_read = 0;
+
+ reader_threadwork.thread_done_work();
+ reader_threadwork.thread_wait_for_work();
+ }
+ command_queue.flush_all();
+ reader_threadwork.thread_done_work();
+ }
+ static void static_reader_thread_loop(void *stsvoid) {
+ SharedThreadState *sts = static_cast<SharedThreadState *>(stsvoid);
+ sts->reader_thread_loop();
+ }
+
+ void writer_thread_loop() {
+ during_writing = false;
+ writer_threadwork.thread_wait_for_work();
+ while (!exit_threads) {
+ Transform tr;
+ Transform otr;
+ float f = 1;
+ during_writing = true;
+ for (int i = 0; i < message_types_to_write.size(); i++) {
+ TestMsgType msg_type = message_types_to_write[i];
+ switch (msg_type) {
+ case TEST_MSG_FUNC1_TRANSFORM:
+ command_queue.push(this, &SharedThreadState::func1, tr);
+ break;
+ case TEST_MSG_FUNC2_TRANSFORM_FLOAT:
+ command_queue.push(this, &SharedThreadState::func2, tr, f);
+ break;
+ case TEST_MSG_FUNC3_TRANSFORMx6:
+ command_queue.push(this, &SharedThreadState::func3, tr, tr, tr, tr, tr, tr);
+ break;
+ case TEST_MSGSYNC_FUNC1_TRANSFORM:
+ command_queue.push_and_sync(this, &SharedThreadState::func1, tr);
+ break;
+ case TEST_MSGSYNC_FUNC2_TRANSFORM_FLOAT:
+ command_queue.push_and_sync(this, &SharedThreadState::func2, tr, f);
+ break;
+ case TEST_MSGRET_FUNC1_TRANSFORM:
+ command_queue.push_and_ret(this, &SharedThreadState::func1r, tr, &otr);
+ break;
+ case TEST_MSGRET_FUNC2_TRANSFORM_FLOAT:
+ command_queue.push_and_ret(this, &SharedThreadState::func2r, tr, f, &otr);
+ break;
+ default:
+ break;
+ }
+ }
+ message_types_to_write.clear();
+ during_writing = false;
+
+ writer_threadwork.thread_done_work();
+ writer_threadwork.thread_wait_for_work();
+ }
+ writer_threadwork.thread_done_work();
+ }
+ static void static_writer_thread_loop(void *stsvoid) {
+ SharedThreadState *sts = static_cast<SharedThreadState *>(stsvoid);
+ sts->writer_thread_loop();
+ }
+
+ void init_threads() {
+ reader_thread = Thread::create(&SharedThreadState::static_reader_thread_loop, this);
+ writer_thread = Thread::create(&SharedThreadState::static_writer_thread_loop, this);
+ }
+ void destroy_threads() {
+ exit_threads = true;
+ reader_threadwork.main_start_work();
+ writer_threadwork.main_start_work();
+
+ Thread::wait_to_finish(reader_thread);
+ memdelete(reader_thread);
+ reader_thread = nullptr;
+ Thread::wait_to_finish(writer_thread);
+ memdelete(writer_thread);
+ writer_thread = nullptr;
+ }
+};
+
+TEST_CASE("[CommandQueue] Test Queue Basics") {
+ const char *COMMAND_QUEUE_SETTING = "memory/limits/command_queue/multithreading_queue_size_kb";
+ ProjectSettings::get_singleton()->set_setting(COMMAND_QUEUE_SETTING, 1);
+ SharedThreadState sts;
+ sts.init_threads();
+
+ sts.add_msg_to_write(SharedThreadState::TEST_MSG_FUNC1_TRANSFORM);
+ sts.writer_threadwork.main_start_work();
+ sts.writer_threadwork.main_wait_for_done();
+ CHECK_MESSAGE(sts.func1_count == 0,
+ "Control: no messages read before reader has run.");
+
+ sts.message_count_to_read = 1;
+ sts.reader_threadwork.main_start_work();
+ sts.reader_threadwork.main_wait_for_done();
+ CHECK_MESSAGE(sts.func1_count == 1,
+ "Reader should have read one message");
+
+ sts.message_count_to_read = -1;
+ sts.reader_threadwork.main_start_work();
+ sts.reader_threadwork.main_wait_for_done();
+ CHECK_MESSAGE(sts.func1_count == 1,
+ "Reader should have read no additional messages from flush_all");
+
+ sts.add_msg_to_write(SharedThreadState::TEST_MSG_FUNC1_TRANSFORM);
+ sts.writer_threadwork.main_start_work();
+ sts.writer_threadwork.main_wait_for_done();
+
+ sts.message_count_to_read = -1;
+ sts.reader_threadwork.main_start_work();
+ sts.reader_threadwork.main_wait_for_done();
+ CHECK_MESSAGE(sts.func1_count == 2,
+ "Reader should have read one additional message from flush_all");
+
+ sts.destroy_threads();
+
+ CHECK_MESSAGE(sts.func1_count == 2,
+ "Reader should have read no additional messages after join");
+ ProjectSettings::get_singleton()->set_setting(COMMAND_QUEUE_SETTING,
+ ProjectSettings::get_singleton()->property_get_revert(COMMAND_QUEUE_SETTING));
+}
+
+TEST_CASE("[CommandQueue] Test Waiting at Queue Full") {
+ const char *COMMAND_QUEUE_SETTING = "memory/limits/command_queue/multithreading_queue_size_kb";
+ ProjectSettings::get_singleton()->set_setting(COMMAND_QUEUE_SETTING, 1);
+ SharedThreadState sts;
+ sts.init_threads();
+
+ int msgs_to_add = 24; // a queue of size 1kB fundamentally cannot fit 24 matrices.
+ for (int i = 0; i < msgs_to_add; i++) {
+ sts.add_msg_to_write(SharedThreadState::TEST_MSG_FUNC1_TRANSFORM);
+ }
+ sts.writer_threadwork.main_start_work();
+ // If we call main_wait_for_done, we will deadlock. So instead...
+ sts.message_count_to_read = 1;
+ sts.reader_threadwork.main_start_work();
+ sts.reader_threadwork.main_wait_for_done();
+ CHECK_MESSAGE(sts.func1_count == 1,
+ "Reader should have read one message");
+ CHECK_MESSAGE(sts.during_writing,
+ "Writer thread should still be blocked on writing.");
+ sts.message_count_to_read = msgs_to_add - 3;
+ sts.reader_threadwork.main_start_work();
+ sts.reader_threadwork.main_wait_for_done();
+ CHECK_MESSAGE(sts.func1_count >= msgs_to_add - 3,
+ "Reader should have read most messages");
+ sts.writer_threadwork.main_wait_for_done();
+ CHECK_MESSAGE(sts.during_writing == false,
+ "Writer thread should no longer be blocked on writing.");
+ sts.message_count_to_read = 2;
+ sts.reader_threadwork.main_start_work();
+ sts.reader_threadwork.main_wait_for_done();
+ sts.message_count_to_read = -1;
+ sts.reader_threadwork.main_start_work();
+ sts.reader_threadwork.main_wait_for_done();
+ CHECK_MESSAGE(sts.func1_count == msgs_to_add,
+ "Reader should have read all messages");
+
+ sts.destroy_threads();
+
+ CHECK_MESSAGE(sts.func1_count == msgs_to_add,
+ "Reader should have read no additional messages after join");
+ ProjectSettings::get_singleton()->set_setting(COMMAND_QUEUE_SETTING,
+ ProjectSettings::get_singleton()->property_get_revert(COMMAND_QUEUE_SETTING));
+}
+
+TEST_CASE("[CommandQueue] Test Queue Wrapping to same spot.") {
+ const char *COMMAND_QUEUE_SETTING = "memory/limits/command_queue/multithreading_queue_size_kb";
+ ProjectSettings::get_singleton()->set_setting(COMMAND_QUEUE_SETTING, 1);
+ SharedThreadState sts;
+ sts.init_threads();
+
+ sts.add_msg_to_write(SharedThreadState::TEST_MSG_FUNC3_TRANSFORMx6);
+ sts.add_msg_to_write(SharedThreadState::TEST_MSG_FUNC3_TRANSFORMx6);
+ sts.add_msg_to_write(SharedThreadState::TEST_MSG_FUNC1_TRANSFORM);
+ sts.writer_threadwork.main_start_work();
+ sts.writer_threadwork.main_wait_for_done();
+
+ sts.message_count_to_read = -1;
+ sts.reader_threadwork.main_start_work();
+ sts.reader_threadwork.main_wait_for_done();
+ CHECK_MESSAGE(sts.func1_count == 3,
+ "Reader should have read at least three messages");
+
+ sts.add_msg_to_write(SharedThreadState::TEST_MSG_FUNC3_TRANSFORMx6);
+ sts.writer_threadwork.main_start_work();
+ sts.writer_threadwork.main_wait_for_done();
+ sts.add_msg_to_write(SharedThreadState::TEST_MSG_FUNC1_TRANSFORM);
+ sts.add_msg_to_write(SharedThreadState::TEST_MSG_FUNC3_TRANSFORMx6);
+ sts.writer_threadwork.main_start_work();
+ OS::get_singleton()->delay_usec(1000);
+
+ sts.message_count_to_read = -1;
+ sts.reader_threadwork.main_start_work();
+ OS::get_singleton()->delay_usec(1000);
+
+ sts.writer_threadwork.main_wait_for_done();
+ sts.reader_threadwork.main_wait_for_done();
+ CHECK_MESSAGE(sts.func1_count >= 3,
+ "Reader should have read at least three messages");
+
+ sts.message_count_to_read = 6 - sts.func1_count;
+ sts.reader_threadwork.main_start_work();
+
+ // The following will fail immediately.
+ // The reason it hangs indefinitely in engine, is all subsequent calls to
+ // CommandQueue.wait_and_flush_one will also fail.
+ sts.reader_threadwork.main_wait_for_done();
+
+ // Because looping around uses an extra message, easiest to consume all.
+ sts.message_count_to_read = -1;
+ sts.reader_threadwork.main_start_work();
+ sts.reader_threadwork.main_wait_for_done();
+ CHECK_MESSAGE(sts.func1_count == 6,
+ "Reader should have read both message sets");
+
+ sts.destroy_threads();
+
+ CHECK_MESSAGE(sts.func1_count == 6,
+ "Reader should have read no additional messages after join");
+ ProjectSettings::get_singleton()->set_setting(COMMAND_QUEUE_SETTING,
+ ProjectSettings::get_singleton()->property_get_revert(COMMAND_QUEUE_SETTING));
+}
+
+TEST_CASE("[CommandQueue] Test Queue Lapping") {
+ const char *COMMAND_QUEUE_SETTING = "memory/limits/command_queue/multithreading_queue_size_kb";
+ ProjectSettings::get_singleton()->set_setting(COMMAND_QUEUE_SETTING, 1);
+ SharedThreadState sts;
+ sts.init_threads();
+
+ sts.add_msg_to_write(SharedThreadState::TEST_MSG_FUNC1_TRANSFORM);
+ sts.add_msg_to_write(SharedThreadState::TEST_MSG_FUNC3_TRANSFORMx6);
+ sts.add_msg_to_write(SharedThreadState::TEST_MSG_FUNC3_TRANSFORMx6);
+ sts.writer_threadwork.main_start_work();
+ sts.writer_threadwork.main_wait_for_done();
+
+ // We need to read an extra message so that it triggers the dealloc logic once.
+ // Otherwise, the queue will be considered full.
+ sts.message_count_to_read = 3;
+ sts.reader_threadwork.main_start_work();
+ sts.reader_threadwork.main_wait_for_done();
+ CHECK_MESSAGE(sts.func1_count == 3,
+ "Reader should have read first set of messages");
+
+ sts.add_msg_to_write(SharedThreadState::TEST_MSG_FUNC3_TRANSFORMx6);
+ sts.add_msg_to_write(SharedThreadState::TEST_MSG_FUNC3_TRANSFORMx6);
+ sts.writer_threadwork.main_start_work();
+ // Don't wait for these, because the queue isn't big enough.
+ sts.writer_threadwork.main_wait_for_done();
+
+ sts.add_msg_to_write(SharedThreadState::TEST_MSG_FUNC2_TRANSFORM_FLOAT);
+ sts.writer_threadwork.main_start_work();
+ OS::get_singleton()->delay_usec(1000);
+
+ sts.message_count_to_read = 3;
+ sts.reader_threadwork.main_start_work();
+ sts.reader_threadwork.main_wait_for_done();
+
+ sts.writer_threadwork.main_wait_for_done();
+
+ sts.message_count_to_read = -1;
+ sts.reader_threadwork.main_start_work();
+ sts.reader_threadwork.main_wait_for_done();
+
+ CHECK_MESSAGE(sts.func1_count == 6,
+ "Reader should have read rest of the messages after lapping writers.");
+
+ sts.destroy_threads();
+
+ CHECK_MESSAGE(sts.func1_count == 6,
+ "Reader should have read no additional messages after join");
+ ProjectSettings::get_singleton()->set_setting(COMMAND_QUEUE_SETTING,
+ ProjectSettings::get_singleton()->property_get_revert(COMMAND_QUEUE_SETTING));
+}
+
+TEST_CASE("[Stress][CommandQueue] Stress test command queue") {
+ const char *COMMAND_QUEUE_SETTING = "memory/limits/command_queue/multithreading_queue_size_kb";
+ ProjectSettings::get_singleton()->set_setting(COMMAND_QUEUE_SETTING, 1);
+ SharedThreadState sts;
+ sts.init_threads();
+
+ RandomNumberGenerator rng;
+
+ rng.set_seed(1837267);
+
+ int msgs_to_add = 2048;
+
+ for (int i = 0; i < msgs_to_add; i++) {
+ // randi_range is inclusive, so allow any enum value except MAX.
+ sts.add_msg_to_write((SharedThreadState::TestMsgType)rng.randi_range(0, SharedThreadState::TEST_MSG_MAX - 1));
+ }
+ sts.writer_threadwork.main_start_work();
+
+ int max_loop_iters = msgs_to_add * 2;
+ int loop_iters = 0;
+ while (sts.func1_count < msgs_to_add && loop_iters < max_loop_iters) {
+ int remaining = (msgs_to_add - sts.func1_count);
+ sts.message_count_to_read = rng.randi_range(1, remaining < 128 ? remaining : 128);
+ if (loop_iters % 3 == 0) {
+ sts.message_count_to_read = -1;
+ }
+ sts.reader_threadwork.main_start_work();
+ sts.reader_threadwork.main_wait_for_done();
+ loop_iters++;
+ }
+ CHECK_MESSAGE(loop_iters < max_loop_iters,
+ "Reader needed too many iterations to read messages!");
+ sts.writer_threadwork.main_wait_for_done();
+
+ sts.destroy_threads();
+
+ CHECK_MESSAGE(sts.func1_count == msgs_to_add,
+ "Reader should have read no additional messages after join");
+ ProjectSettings::get_singleton()->set_setting(COMMAND_QUEUE_SETTING,
+ ProjectSettings::get_singleton()->property_get_revert(COMMAND_QUEUE_SETTING));
+}
+} // namespace TestCommandQueue
+
+#endif // !defined(NO_THREADS)
+
+#endif // TEST_COMMAND_QUEUE_H
diff --git a/tests/test_config_file.h b/tests/test_config_file.h
new file mode 100644
index 0000000000..f910ca4b1f
--- /dev/null
+++ b/tests/test_config_file.h
@@ -0,0 +1,156 @@
+/*************************************************************************/
+/* test_config_file.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+#ifndef TEST_CONFIG_FILE_H
+#define TEST_CONFIG_FILE_H
+
+#include "core/io/config_file.h"
+
+#include "tests/test_macros.h"
+
+namespace TestConfigFile {
+
+TEST_CASE("[ConfigFile] Parsing well-formatted files") {
+ ConfigFile config_file;
+ // Formatting is intentionally hand-edited to see how human-friendly the parser is.
+ const Error error = config_file.parse(R"(
+[player]
+
+name = "Unnamed Player"
+tagline="Waiting
+for
+Godot"
+
+color =Color( 0, 0.5,1, 1) ; Inline comment
+position= Vector2(
+ 3,
+ 4
+)
+
+[graphics]
+
+antialiasing = true
+
+; Testing comments and case-sensitivity...
+antiAliasing = false
+)");
+
+ CHECK_MESSAGE(error == OK, "The configuration file should parse successfully.");
+ CHECK_MESSAGE(
+ String(config_file.get_value("player", "name")) == "Unnamed Player",
+ "Reading `player/name` should return the expected value.");
+ CHECK_MESSAGE(
+ String(config_file.get_value("player", "tagline")) == "Waiting\nfor\nGodot",
+ "Reading `player/tagline` should return the expected value.");
+ CHECK_MESSAGE(
+ Color(config_file.get_value("player", "color")).is_equal_approx(Color(0, 0.5, 1)),
+ "Reading `player/color` should return the expected value.");
+ CHECK_MESSAGE(
+ Vector2(config_file.get_value("player", "position")).is_equal_approx(Vector2(3, 4)),
+ "Reading `player/position` should return the expected value.");
+ CHECK_MESSAGE(
+ bool(config_file.get_value("graphics", "antialiasing")),
+ "Reading `graphics/antialiasing` should return `true`.");
+ CHECK_MESSAGE(
+ bool(config_file.get_value("graphics", "antiAliasing")) == false,
+ "Reading `graphics/antiAliasing` should return `false`.");
+
+ // An empty ConfigFile is valid.
+ const Error error_empty = config_file.parse("");
+ CHECK_MESSAGE(error_empty == OK,
+ "An empty configuration file should parse successfully.");
+}
+
+TEST_CASE("[ConfigFile] Parsing malformatted file") {
+ ConfigFile config_file;
+ ERR_PRINT_OFF;
+ const Error error = config_file.parse(R"(
+[player]
+
+name = "Unnamed Player"" ; Extraneous closing quote.
+tagline = "Waiting\nfor\nGodot"
+
+color = Color(0, 0.5, 1) ; Missing 4th parameter.
+position = Vector2(
+ 3,,
+ 4
+) ; Extraneous comma.
+
+[graphics]
+
+antialiasing = true
+antialiasing = false ; Duplicate key.
+)");
+ ERR_PRINT_ON;
+
+ CHECK_MESSAGE(error == ERR_PARSE_ERROR,
+ "The configuration file shouldn't parse successfully.");
+}
+
+TEST_CASE("[ConfigFile] Saving file") {
+ ConfigFile config_file;
+ config_file.set_value("player", "name", "Unnamed Player");
+ config_file.set_value("player", "tagline", "Waiting\nfor\nGodot");
+ config_file.set_value("player", "color", Color(0, 0.5, 1));
+ config_file.set_value("player", "position", Vector2(3, 4));
+ config_file.set_value("graphics", "antialiasing", true);
+ config_file.set_value("graphics", "antiAliasing", false);
+
+#ifdef WINDOWS_ENABLED
+ const String config_path = OS::get_singleton()->get_environment("TEMP").plus_file("config.ini");
+#else
+ const String config_path = "/tmp/config.ini";
+#endif
+
+ config_file.save(config_path);
+
+ // Expected contents of the saved ConfigFile.
+ const String contents = R"([player]
+
+name="Unnamed Player"
+tagline="Waiting
+for
+Godot"
+color=Color( 0, 0.5, 1, 1 )
+position=Vector2( 3, 4 )
+
+[graphics]
+
+antialiasing=true
+antiAliasing=false
+)";
+
+ FileAccessRef file = FileAccess::open(config_path, FileAccess::READ);
+ CHECK_MESSAGE(file->get_as_utf8_string() == contents,
+ "The saved configuration file should match the expected format.");
+}
+} // namespace TestConfigFile
+
+#endif // TEST_CONFIG_FILE_H
diff --git a/tests/test_crypto.h b/tests/test_crypto.h
new file mode 100644
index 0000000000..9e219ceec9
--- /dev/null
+++ b/tests/test_crypto.h
@@ -0,0 +1,74 @@
+/*************************************************************************/
+/* test_crypto.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+#ifndef TEST_CRYPTO_H
+#define TEST_CRYPTO_H
+
+#include "core/crypto/crypto.h"
+#include "tests/test_macros.h"
+#include <stdio.h>
+
+namespace TestCrypto {
+
+class _MockCrypto : public Crypto {
+ virtual PackedByteArray generate_random_bytes(int p_bytes) { return PackedByteArray(); }
+ virtual Ref<CryptoKey> generate_rsa(int p_bytes) { return nullptr; }
+ virtual Ref<X509Certificate> generate_self_signed_certificate(Ref<CryptoKey> p_key, String p_issuer_name, String p_not_before, String p_not_after) { return nullptr; }
+
+ virtual Vector<uint8_t> sign(HashingContext::HashType p_hash_type, Vector<uint8_t> p_hash, Ref<CryptoKey> p_key) { return Vector<uint8_t>(); }
+ virtual bool verify(HashingContext::HashType p_hash_type, Vector<uint8_t> p_hash, Vector<uint8_t> p_signature, Ref<CryptoKey> p_key) { return false; }
+ virtual Vector<uint8_t> encrypt(Ref<CryptoKey> p_key, Vector<uint8_t> p_plaintext) { return Vector<uint8_t>(); }
+ virtual Vector<uint8_t> decrypt(Ref<CryptoKey> p_key, Vector<uint8_t> p_ciphertext) { return Vector<uint8_t>(); }
+ virtual PackedByteArray hmac_digest(HashingContext::HashType p_hash_type, PackedByteArray p_key, PackedByteArray p_msg) { return PackedByteArray(); }
+};
+
+PackedByteArray raw_to_pba(const uint8_t *arr, size_t len) {
+ PackedByteArray pba;
+ pba.resize(len);
+ for (size_t i = 0; i < len; i++) {
+ pba.set(i, arr[i]);
+ }
+ return pba;
+}
+
+TEST_CASE("[Crypto] PackedByteArray constant time compare") {
+ const uint8_t hm1[] = { 144, 140, 176, 38, 88, 113, 101, 45, 71, 105, 10, 91, 248, 16, 117, 244, 189, 30, 238, 29, 219, 134, 82, 130, 212, 114, 161, 166, 188, 169, 200, 106 };
+ const uint8_t hm2[] = { 80, 30, 144, 228, 108, 38, 188, 125, 150, 64, 165, 127, 221, 118, 144, 232, 45, 100, 15, 248, 193, 244, 245, 34, 116, 147, 132, 200, 110, 27, 38, 75 };
+ PackedByteArray p1 = raw_to_pba(hm1, sizeof(hm1) / sizeof(hm1[0]));
+ PackedByteArray p2 = raw_to_pba(hm2, sizeof(hm2) / sizeof(hm2[0]));
+ _MockCrypto crypto;
+ bool equal = crypto.constant_time_compare(p1, p1);
+ CHECK(equal);
+ equal = crypto.constant_time_compare(p1, p2);
+ CHECK(!equal);
+}
+} // namespace TestCrypto
+
+#endif // TEST_CRYPTO_H
diff --git a/tests/test_curve.h b/tests/test_curve.h
new file mode 100644
index 0000000000..b123ef6325
--- /dev/null
+++ b/tests/test_curve.h
@@ -0,0 +1,221 @@
+/*************************************************************************/
+/* test_curve.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+#ifndef TEST_CURVE_H
+#define TEST_CURVE_H
+
+#include "scene/resources/curve.h"
+
+#include "thirdparty/doctest/doctest.h"
+
+namespace TestCurve {
+
+TEST_CASE("[Curve] Default curve") {
+ const Ref<Curve> curve = memnew(Curve);
+
+ CHECK_MESSAGE(
+ curve->get_point_count() == 0,
+ "Default curve should contain the expected number of points.");
+ CHECK_MESSAGE(
+ Math::is_zero_approx(curve->interpolate(0)),
+ "Default curve should return the expected value at offset 0.0.");
+ CHECK_MESSAGE(
+ Math::is_zero_approx(curve->interpolate(0.5)),
+ "Default curve should return the expected value at offset 0.5.");
+ CHECK_MESSAGE(
+ Math::is_zero_approx(curve->interpolate(1)),
+ "Default curve should return the expected value at offset 1.0.");
+}
+
+TEST_CASE("[Curve] Custom curve with free tangents") {
+ Ref<Curve> curve = memnew(Curve);
+ // "Sawtooth" curve with an open ending towards the 1.0 offset.
+ curve->add_point(Vector2(0, 0));
+ curve->add_point(Vector2(0.25, 1));
+ curve->add_point(Vector2(0.5, 0));
+ curve->add_point(Vector2(0.75, 1));
+
+ CHECK_MESSAGE(
+ Math::is_zero_approx(curve->get_point_left_tangent(0)),
+ "get_point_left_tangent() should return the expected value for point index 0.");
+ CHECK_MESSAGE(
+ Math::is_zero_approx(curve->get_point_right_tangent(0)),
+ "get_point_right_tangent() should return the expected value for point index 0.");
+ CHECK_MESSAGE(
+ curve->get_point_left_mode(0) == Curve::TangentMode::TANGENT_FREE,
+ "get_point_left_mode() should return the expected value for point index 0.");
+ CHECK_MESSAGE(
+ curve->get_point_right_mode(0) == Curve::TangentMode::TANGENT_FREE,
+ "get_point_right_mode() should return the expected value for point index 0.");
+
+ CHECK_MESSAGE(
+ curve->get_point_count() == 4,
+ "Custom free curve should contain the expected number of points.");
+
+ CHECK_MESSAGE(
+ Math::is_equal_approx(curve->interpolate(-0.1), 0),
+ "Custom free curve should return the expected value at offset 0.1.");
+ CHECK_MESSAGE(
+ Math::is_equal_approx(curve->interpolate(0.1), 0.352),
+ "Custom free curve should return the expected value at offset 0.1.");
+ CHECK_MESSAGE(
+ Math::is_equal_approx(curve->interpolate(0.4), 0.352),
+ "Custom free curve should return the expected value at offset 0.1.");
+ CHECK_MESSAGE(
+ Math::is_equal_approx(curve->interpolate(0.7), 0.896),
+ "Custom free curve should return the expected value at offset 0.1.");
+ CHECK_MESSAGE(
+ Math::is_equal_approx(curve->interpolate(1), 1),
+ "Custom free curve should return the expected value at offset 0.1.");
+ CHECK_MESSAGE(
+ Math::is_equal_approx(curve->interpolate(2), 1),
+ "Custom free curve should return the expected value at offset 0.1.");
+
+ CHECK_MESSAGE(
+ Math::is_equal_approx(curve->interpolate_baked(-0.1), 0),
+ "Custom free curve should return the expected baked value at offset 0.1.");
+ CHECK_MESSAGE(
+ Math::is_equal_approx(curve->interpolate_baked(0.1), 0.352),
+ "Custom free curve should return the expected baked value at offset 0.1.");
+ CHECK_MESSAGE(
+ Math::is_equal_approx(curve->interpolate_baked(0.4), 0.352),
+ "Custom free curve should return the expected baked value at offset 0.1.");
+ CHECK_MESSAGE(
+ Math::is_equal_approx(curve->interpolate_baked(0.7), 0.896),
+ "Custom free curve should return the expected baked value at offset 0.1.");
+ CHECK_MESSAGE(
+ Math::is_equal_approx(curve->interpolate_baked(1), 1),
+ "Custom free curve should return the expected baked value at offset 0.1.");
+ CHECK_MESSAGE(
+ Math::is_equal_approx(curve->interpolate_baked(2), 1),
+ "Custom free curve should return the expected baked value at offset 0.1.");
+
+ curve->remove_point(1);
+ CHECK_MESSAGE(
+ Math::is_equal_approx(curve->interpolate(0.1), 0),
+ "Custom free curve should return the expected value at offset 0.1 after removing point at index 1.");
+ CHECK_MESSAGE(
+ Math::is_equal_approx(curve->interpolate_baked(0.1), 0),
+ "Custom free curve should return the expected baked value at offset 0.1 after removing point at index 1.");
+
+ curve->clear_points();
+ CHECK_MESSAGE(
+ Math::is_equal_approx(curve->interpolate(0.6), 0),
+ "Custom free curve should return the expected value at offset 0.6 after clearing all points.");
+ CHECK_MESSAGE(
+ Math::is_equal_approx(curve->interpolate_baked(0.6), 0),
+ "Custom free curve should return the expected baked value at offset 0.6 after clearing all points.");
+}
+
+TEST_CASE("[Curve] Custom curve with linear tangents") {
+ Ref<Curve> curve = memnew(Curve);
+ // "Sawtooth" curve with an open ending towards the 1.0 offset.
+ curve->add_point(Vector2(0, 0), 0, 0, Curve::TangentMode::TANGENT_LINEAR, Curve::TangentMode::TANGENT_LINEAR);
+ curve->add_point(Vector2(0.25, 1), 0, 0, Curve::TangentMode::TANGENT_LINEAR, Curve::TangentMode::TANGENT_LINEAR);
+ curve->add_point(Vector2(0.5, 0), 0, 0, Curve::TangentMode::TANGENT_LINEAR, Curve::TangentMode::TANGENT_LINEAR);
+ curve->add_point(Vector2(0.75, 1), 0, 0, Curve::TangentMode::TANGENT_LINEAR, Curve::TangentMode::TANGENT_LINEAR);
+
+ CHECK_MESSAGE(
+ Math::is_equal_approx(curve->get_point_left_tangent(3), 4),
+ "get_point_left_tangent() should return the expected value for point index 3.");
+ CHECK_MESSAGE(
+ Math::is_zero_approx(curve->get_point_right_tangent(3)),
+ "get_point_right_tangent() should return the expected value for point index 3.");
+ CHECK_MESSAGE(
+ curve->get_point_left_mode(3) == Curve::TangentMode::TANGENT_LINEAR,
+ "get_point_left_mode() should return the expected value for point index 3.");
+ CHECK_MESSAGE(
+ curve->get_point_right_mode(3) == Curve::TangentMode::TANGENT_LINEAR,
+ "get_point_right_mode() should return the expected value for point index 3.");
+
+ ERR_PRINT_OFF;
+ CHECK_MESSAGE(
+ Math::is_zero_approx(curve->get_point_right_tangent(300)),
+ "get_point_right_tangent() should return the expected value for invalid point index 300.");
+ CHECK_MESSAGE(
+ curve->get_point_left_mode(-12345) == Curve::TangentMode::TANGENT_FREE,
+ "get_point_left_mode() should return the expected value for invalid point index -12345.");
+ ERR_PRINT_ON;
+
+ CHECK_MESSAGE(
+ curve->get_point_count() == 4,
+ "Custom linear curve should contain the expected number of points.");
+
+ CHECK_MESSAGE(
+ Math::is_equal_approx(curve->interpolate(-0.1), 0),
+ "Custom linear curve should return the expected value at offset -0.1.");
+ CHECK_MESSAGE(
+ Math::is_equal_approx(curve->interpolate(0.1), 0.4),
+ "Custom linear curve should return the expected value at offset 0.1.");
+ CHECK_MESSAGE(
+ Math::is_equal_approx(curve->interpolate(0.4), 0.4),
+ "Custom linear curve should return the expected value at offset 0.4.");
+ CHECK_MESSAGE(
+ Math::is_equal_approx(curve->interpolate(0.7), 0.8),
+ "Custom linear curve should return the expected value at offset 0.7.");
+ CHECK_MESSAGE(
+ Math::is_equal_approx(curve->interpolate(1), 1),
+ "Custom linear curve should return the expected value at offset 1.0.");
+ CHECK_MESSAGE(
+ Math::is_equal_approx(curve->interpolate(2), 1),
+ "Custom linear curve should return the expected value at offset 2.0.");
+
+ CHECK_MESSAGE(
+ Math::is_equal_approx(curve->interpolate_baked(-0.1), 0),
+ "Custom linear curve should return the expected baked value at offset -0.1.");
+ CHECK_MESSAGE(
+ Math::is_equal_approx(curve->interpolate_baked(0.1), 0.4),
+ "Custom linear curve should return the expected baked value at offset 0.1.");
+ CHECK_MESSAGE(
+ Math::is_equal_approx(curve->interpolate_baked(0.4), 0.4),
+ "Custom linear curve should return the expected baked value at offset 0.4.");
+ CHECK_MESSAGE(
+ Math::is_equal_approx(curve->interpolate_baked(0.7), 0.8),
+ "Custom linear curve should return the expected baked value at offset 0.7.");
+ CHECK_MESSAGE(
+ Math::is_equal_approx(curve->interpolate_baked(1), 1),
+ "Custom linear curve should return the expected baked value at offset 1.0.");
+ CHECK_MESSAGE(
+ Math::is_equal_approx(curve->interpolate_baked(2), 1),
+ "Custom linear curve should return the expected baked value at offset 2.0.");
+
+ ERR_PRINT_OFF;
+ curve->remove_point(10);
+ ERR_PRINT_ON;
+ CHECK_MESSAGE(
+ Math::is_equal_approx(curve->interpolate(0.7), 0.8),
+ "Custom free curve should return the expected value at offset 0.7 after removing point at invalid index 10.");
+ CHECK_MESSAGE(
+ Math::is_equal_approx(curve->interpolate_baked(0.7), 0.8),
+ "Custom free curve should return the expected baked value at offset 0.7 after removing point at invalid index 10.");
+}
+} // namespace TestCurve
+
+#endif // TEST_CURVE_H
diff --git a/tests/test_expression.h b/tests/test_expression.h
new file mode 100644
index 0000000000..0d970ba87a
--- /dev/null
+++ b/tests/test_expression.h
@@ -0,0 +1,444 @@
+/*************************************************************************/
+/* test_expression.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+#ifndef TEST_EXPRESSION_H
+#define TEST_EXPRESSION_H
+
+#include "core/math/expression.h"
+
+#include "tests/test_macros.h"
+
+namespace TestExpression {
+
+TEST_CASE("[Expression] Integer arithmetic") {
+ Expression expression;
+
+ CHECK_MESSAGE(
+ expression.parse("-123456") == OK,
+ "Integer identity should parse successfully.");
+ CHECK_MESSAGE(
+ int(expression.execute()) == -123456,
+ "Integer identity should return the expected result.");
+
+ CHECK_MESSAGE(
+ expression.parse("2 + 3") == OK,
+ "Integer addition should parse successfully.");
+ CHECK_MESSAGE(
+ int(expression.execute()) == 5,
+ "Integer addition should return the expected result.");
+
+ CHECK_MESSAGE(
+ expression.parse("999999999999 + 999999999999") == OK,
+ "Large integer addition should parse successfully.");
+ CHECK_MESSAGE(
+ int64_t(expression.execute()) == 1'999'999'999'998,
+ "Large integer addition should return the expected result.");
+
+ CHECK_MESSAGE(
+ expression.parse("25 / 10") == OK,
+ "Integer / integer division should parse successfully.");
+ CHECK_MESSAGE(
+ int(expression.execute()) == 2,
+ "Integer / integer division should return the expected result.");
+
+ CHECK_MESSAGE(
+ expression.parse("2 * (6 + 14) / 2 - 5") == OK,
+ "Integer multiplication-addition-subtraction-division should parse successfully.");
+ CHECK_MESSAGE(
+ int(expression.execute()) == 15,
+ "Integer multiplication-addition-subtraction-division should return the expected result.");
+}
+
+TEST_CASE("[Expression] Floating-point arithmetic") {
+ Expression expression;
+
+ CHECK_MESSAGE(
+ expression.parse("-123.456") == OK,
+ "Float identity should parse successfully.");
+ CHECK_MESSAGE(
+ Math::is_equal_approx(float(expression.execute()), -123.456),
+ "Float identity should return the expected result.");
+
+ CHECK_MESSAGE(
+ expression.parse("2.0 + 3.0") == OK,
+ "Float addition should parse successfully.");
+ CHECK_MESSAGE(
+ Math::is_equal_approx(float(expression.execute()), 5),
+ "Float addition should return the expected result.");
+
+ CHECK_MESSAGE(
+ expression.parse("3.0 / 10") == OK,
+ "Float / integer division should parse successfully.");
+ CHECK_MESSAGE(
+ Math::is_equal_approx(float(expression.execute()), 0.3),
+ "Float / integer division should return the expected result.");
+
+ CHECK_MESSAGE(
+ expression.parse("3 / 10.0") == OK,
+ "Basic integer / float division should parse successfully.");
+ CHECK_MESSAGE(
+ Math::is_equal_approx(float(expression.execute()), 0.3),
+ "Basic integer / float division should return the expected result.");
+
+ CHECK_MESSAGE(
+ expression.parse("3.0 / 10.0") == OK,
+ "Float / float division should parse successfully.");
+ CHECK_MESSAGE(
+ Math::is_equal_approx(float(expression.execute()), 0.3),
+ "Float / float division should return the expected result.");
+
+ CHECK_MESSAGE(
+ expression.parse("2.5 * (6.0 + 14.25) / 2.0 - 5.12345") == OK,
+ "Float multiplication-addition-subtraction-division should parse successfully.");
+ CHECK_MESSAGE(
+ Math::is_equal_approx(float(expression.execute()), 20.18905),
+ "Float multiplication-addition-subtraction-division should return the expected result.");
+}
+
+TEST_CASE("[Expression] Scientific notation") {
+ Expression expression;
+
+ CHECK_MESSAGE(
+ expression.parse("2.e5") == OK,
+ "The expression should parse successfully.");
+ CHECK_MESSAGE(
+ Math::is_equal_approx(float(expression.execute()), 200'000),
+ "The expression should return the expected result.");
+
+ // The middle "e" is ignored here.
+ CHECK_MESSAGE(
+ expression.parse("2e5") == OK,
+ "The expression should parse successfully.");
+ CHECK_MESSAGE(
+ Math::is_equal_approx(float(expression.execute()), 25),
+ "The expression should return the expected result.");
+
+ CHECK_MESSAGE(
+ expression.parse("2e.5") == OK,
+ "The expression should parse successfully.");
+ CHECK_MESSAGE(
+ Math::is_equal_approx(float(expression.execute()), 2),
+ "The expression should return the expected result.");
+}
+
+TEST_CASE("[Expression] Underscored numeric literals") {
+ Expression expression;
+
+ CHECK_MESSAGE(
+ expression.parse("1_000_000") == OK,
+ "The expression should parse successfully.");
+ CHECK_MESSAGE(
+ expression.parse("1_000.000") == OK,
+ "The expression should parse successfully.");
+ CHECK_MESSAGE(
+ expression.parse("0xff_99_00") == OK,
+ "The expression should parse successfully.");
+}
+
+TEST_CASE("[Expression] Built-in functions") {
+ Expression expression;
+
+ CHECK_MESSAGE(
+ expression.parse("sqrt(pow(3, 2) + pow(4, 2))") == OK,
+ "The expression should parse successfully.");
+ CHECK_MESSAGE(
+ int(expression.execute()) == 5,
+ "`sqrt(pow(3, 2) + pow(4, 2))` should return the expected result.");
+
+ CHECK_MESSAGE(
+ expression.parse("stepify(sin(0.5), 0.01)") == OK,
+ "The expression should parse successfully.");
+ CHECK_MESSAGE(
+ Math::is_equal_approx(float(expression.execute()), 0.48),
+ "`stepify(sin(0.5), 0.01)` should return the expected result.");
+
+ CHECK_MESSAGE(
+ expression.parse("pow(2.0, -2500)") == OK,
+ "The expression should parse successfully.");
+ CHECK_MESSAGE(
+ Math::is_zero_approx(float(expression.execute())),
+ "`pow(2.0, -2500)` should return the expected result (asymptotically zero).");
+}
+
+TEST_CASE("[Expression] Boolean expressions") {
+ Expression expression;
+
+ CHECK_MESSAGE(
+ expression.parse("24 >= 12") == OK,
+ "The boolean expression should parse successfully.");
+ CHECK_MESSAGE(
+ bool(expression.execute()),
+ "The boolean expression should evaluate to `true`.");
+
+ CHECK_MESSAGE(
+ expression.parse("1.0 < 1.25 && 1.25 < 2.0") == OK,
+ "The boolean expression should parse successfully.");
+ CHECK_MESSAGE(
+ bool(expression.execute()),
+ "The boolean expression should evaluate to `true`.");
+
+ CHECK_MESSAGE(
+ expression.parse("!2") == OK,
+ "The boolean expression should parse successfully.");
+ CHECK_MESSAGE(
+ !bool(expression.execute()),
+ "The boolean expression should evaluate to `false`.");
+
+ CHECK_MESSAGE(
+ expression.parse("!!2") == OK,
+ "The boolean expression should parse successfully.");
+ CHECK_MESSAGE(
+ bool(expression.execute()),
+ "The boolean expression should evaluate to `true`.");
+
+ CHECK_MESSAGE(
+ expression.parse("!0") == OK,
+ "The boolean expression should parse successfully.");
+ CHECK_MESSAGE(
+ bool(expression.execute()),
+ "The boolean expression should evaluate to `true`.");
+
+ CHECK_MESSAGE(
+ expression.parse("!!0") == OK,
+ "The boolean expression should parse successfully.");
+ CHECK_MESSAGE(
+ !bool(expression.execute()),
+ "The boolean expression should evaluate to `false`.");
+
+ CHECK_MESSAGE(
+ expression.parse("2 && 5") == OK,
+ "The boolean expression should parse successfully.");
+ CHECK_MESSAGE(
+ bool(expression.execute()),
+ "The boolean expression should evaluate to `true`.");
+
+ CHECK_MESSAGE(
+ expression.parse("0 || 0") == OK,
+ "The boolean expression should parse successfully.");
+ CHECK_MESSAGE(
+ !bool(expression.execute()),
+ "The boolean expression should evaluate to `false`.");
+
+ CHECK_MESSAGE(
+ expression.parse("(2 <= 4) && (2 > 5)") == OK,
+ "The boolean expression should parse successfully.");
+ CHECK_MESSAGE(
+ !bool(expression.execute()),
+ "The boolean expression should evaluate to `false`.");
+}
+
+TEST_CASE("[Expression] Expressions with variables") {
+ Expression expression;
+
+ PackedStringArray parameter_names;
+ parameter_names.push_back("foo");
+ parameter_names.push_back("bar");
+ CHECK_MESSAGE(
+ expression.parse("foo + bar + 50", parameter_names) == OK,
+ "The expression should parse successfully.");
+ Array values;
+ values.push_back(60);
+ values.push_back(20);
+ CHECK_MESSAGE(
+ int(expression.execute(values)) == 130,
+ "The expression should return the expected value.");
+
+ PackedStringArray parameter_names_invalid;
+ parameter_names_invalid.push_back("foo");
+ parameter_names_invalid.push_back("baz"); // Invalid parameter name.
+ CHECK_MESSAGE(
+ expression.parse("foo + bar + 50", parameter_names_invalid) == OK,
+ "The expression should parse successfully.");
+ Array values_invalid;
+ values_invalid.push_back(60);
+ values_invalid.push_back(20);
+ // Invalid parameters will parse successfully but print an error message when executing.
+ ERR_PRINT_OFF;
+ CHECK_MESSAGE(
+ int(expression.execute(values_invalid)) == 0,
+ "The expression should return the expected value.");
+ ERR_PRINT_ON;
+
+ // Mismatched argument count (more values than parameters).
+ PackedStringArray parameter_names_mismatch;
+ parameter_names_mismatch.push_back("foo");
+ parameter_names_mismatch.push_back("bar");
+ CHECK_MESSAGE(
+ expression.parse("foo + bar + 50", parameter_names_mismatch) == OK,
+ "The expression should parse successfully.");
+ Array values_mismatch;
+ values_mismatch.push_back(60);
+ values_mismatch.push_back(20);
+ values_mismatch.push_back(110);
+ CHECK_MESSAGE(
+ int(expression.execute(values_mismatch)) == 130,
+ "The expression should return the expected value.");
+
+ // Mismatched argument count (more parameters than values).
+ PackedStringArray parameter_names_mismatch2;
+ parameter_names_mismatch2.push_back("foo");
+ parameter_names_mismatch2.push_back("bar");
+ parameter_names_mismatch2.push_back("baz");
+ CHECK_MESSAGE(
+ expression.parse("foo + bar + baz + 50", parameter_names_mismatch2) == OK,
+ "The expression should parse successfully.");
+ Array values_mismatch2;
+ values_mismatch2.push_back(60);
+ values_mismatch2.push_back(20);
+ // Having more parameters than values will parse successfully but print an
+ // error message when executing.
+ ERR_PRINT_OFF;
+ CHECK_MESSAGE(
+ int(expression.execute(values_mismatch2)) == 0,
+ "The expression should return the expected value.");
+ ERR_PRINT_ON;
+}
+
+TEST_CASE("[Expression] Invalid expressions") {
+ Expression expression;
+
+ CHECK_MESSAGE(
+ expression.parse("\\") == ERR_INVALID_PARAMETER,
+ "The expression shouldn't parse successfully.");
+
+ CHECK_MESSAGE(
+ expression.parse("0++") == ERR_INVALID_PARAMETER,
+ "The expression shouldn't parse successfully.");
+
+ CHECK_MESSAGE(
+ expression.parse("()") == ERR_INVALID_PARAMETER,
+ "The expression shouldn't parse successfully.");
+
+ CHECK_MESSAGE(
+ expression.parse("()()") == ERR_INVALID_PARAMETER,
+ "The expression shouldn't parse successfully.");
+
+ CHECK_MESSAGE(
+ expression.parse("() - ()") == ERR_INVALID_PARAMETER,
+ "The expression shouldn't parse successfully.");
+
+ CHECK_MESSAGE(
+ expression.parse("() * 12345") == ERR_INVALID_PARAMETER,
+ "The expression shouldn't parse successfully.");
+
+ CHECK_MESSAGE(
+ expression.parse("() * 12345") == ERR_INVALID_PARAMETER,
+ "The expression shouldn't parse successfully.");
+
+ CHECK_MESSAGE(
+ expression.parse("123'456") == ERR_INVALID_PARAMETER,
+ "The expression shouldn't parse successfully.");
+
+ CHECK_MESSAGE(
+ expression.parse("123\"456") == ERR_INVALID_PARAMETER,
+ "The expression shouldn't parse successfully.");
+}
+
+TEST_CASE("[Expression] Unusual expressions") {
+ Expression expression;
+
+ // Redundant parentheses don't cause a parse error as long as they're matched.
+ CHECK_MESSAGE(
+ expression.parse("(((((((((((((((666)))))))))))))))") == OK,
+ "The expression should parse successfully.");
+
+ // Using invalid identifiers doesn't cause a parse error.
+ ERR_PRINT_OFF;
+ CHECK_MESSAGE(
+ expression.parse("hello + hello") == OK,
+ "The expression should parse successfully.");
+ CHECK_MESSAGE(
+ int(expression.execute()) == 0,
+ "The expression should return the expected result.");
+ ERR_PRINT_ON;
+
+ ERR_PRINT_OFF;
+ CHECK_MESSAGE(
+ expression.parse("$1.00 + ???5") == OK,
+ "The expression should parse successfully.");
+ CHECK_MESSAGE(
+ int(expression.execute()) == 0,
+ "The expression should return the expected result.");
+ ERR_PRINT_ON;
+
+ // Commas can't be used as a decimal parameter.
+ CHECK_MESSAGE(
+ expression.parse("123,456") == OK,
+ "The expression should parse successfully.");
+ CHECK_MESSAGE(
+ int(expression.execute()) == 123,
+ "The expression should return the expected result.");
+
+ // Spaces can't be used as a separator for large numbers.
+ CHECK_MESSAGE(
+ expression.parse("123 456") == OK,
+ "The expression should parse successfully.");
+ CHECK_MESSAGE(
+ int(expression.execute()) == 123,
+ "The expression should return the expected result.");
+
+ // Division by zero is accepted, even though it prints an error message normally.
+ CHECK_MESSAGE(
+ expression.parse("-25.4 / 0") == OK,
+ "The expression should parse successfully.");
+ ERR_PRINT_OFF;
+ CHECK_MESSAGE(
+ Math::is_inf(float(expression.execute())),
+ "`-25.4 / 0` should return inf.");
+ ERR_PRINT_ON;
+
+ CHECK_MESSAGE(
+ expression.parse("0 / 0") == OK,
+ "The expression should parse successfully.");
+ ERR_PRINT_OFF;
+ CHECK_MESSAGE(
+ int(expression.execute()) == 0,
+ "`0 / 0` should return 0.");
+ ERR_PRINT_ON;
+
+ // The tests below currently crash the engine.
+ //
+ //CHECK_MESSAGE(
+ // expression.parse("(-9223372036854775807 - 1) % -1") == OK,
+ // "The expression should parse successfully.");
+ //CHECK_MESSAGE(
+ // int64_t(expression.execute()) == 0,
+ // "`(-9223372036854775807 - 1) % -1` should return the expected result.");
+ //
+ //CHECK_MESSAGE(
+ // expression.parse("(-9223372036854775807 - 1) / -1") == OK,
+ // "The expression should parse successfully.");
+ //CHECK_MESSAGE(
+ // int64_t(expression.execute()) == 0,
+ // "`(-9223372036854775807 - 1) / -1` should return the expected result.");
+}
+} // namespace TestExpression
+
+#endif // TEST_EXPRESSION_H
diff --git a/tests/test_file_access.h b/tests/test_file_access.h
new file mode 100644
index 0000000000..0d5c9d79ce
--- /dev/null
+++ b/tests/test_file_access.h
@@ -0,0 +1,64 @@
+/*************************************************************************/
+/* test_file_access.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+#ifndef TEST_FILE_ACCESS_H
+#define TEST_FILE_ACCESS_H
+
+#include "core/os/file_access.h"
+
+namespace TestFileAccess {
+
+TEST_CASE("[FileAccess] CSV read") {
+ FileAccess *f = FileAccess::open("tests/data/translations.csv", FileAccess::READ);
+
+ Vector<String> header = f->get_csv_line(); // Default delimiter: ","
+ REQUIRE(header.size() == 3);
+
+ Vector<String> row1 = f->get_csv_line(",");
+ REQUIRE(row1.size() == 3);
+ CHECK(row1[0] == "GOOD_MORNING");
+ CHECK(row1[1] == "Good Morning");
+ CHECK(row1[2] == "Guten Morgen");
+
+ Vector<String> row2 = f->get_csv_line();
+ REQUIRE(row2.size() == 3);
+ CHECK(row2[0] == "GOOD_EVENING");
+ CHECK(row2[1] == "Good Evening");
+ CHECK(row2[2] == ""); // Use case: not yet translated!
+
+ // https://github.com/godotengine/godot/issues/44269
+ CHECK_MESSAGE(row2[2] != "\"", "Should not parse empty string as a single double quote.");
+
+ f->close();
+ memdelete(f);
+}
+} // namespace TestFileAccess
+
+#endif // TEST_FILE_ACCESS_H
diff --git a/tests/test_gdscript.cpp b/tests/test_gdscript.cpp
deleted file mode 100644
index a50311972f..0000000000
--- a/tests/test_gdscript.cpp
+++ /dev/null
@@ -1,187 +0,0 @@
-/*************************************************************************/
-/* test_gdscript.cpp */
-/*************************************************************************/
-/* This file is part of: */
-/* GODOT ENGINE */
-/* https://godotengine.org */
-/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
-/* */
-/* Permission is hereby granted, free of charge, to any person obtaining */
-/* a copy of this software and associated documentation files (the */
-/* "Software"), to deal in the Software without restriction, including */
-/* without limitation the rights to use, copy, modify, merge, publish, */
-/* distribute, sublicense, and/or sell copies of the Software, and to */
-/* permit persons to whom the Software is furnished to do so, subject to */
-/* the following conditions: */
-/* */
-/* The above copyright notice and this permission notice shall be */
-/* included in all copies or substantial portions of the Software. */
-/* */
-/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
-/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
-/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
-/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
-/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
-/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
-/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
-/*************************************************************************/
-
-#include "test_gdscript.h"
-
-#include "core/os/file_access.h"
-#include "core/os/main_loop.h"
-#include "core/os/os.h"
-#include "core/string_builder.h"
-
-#include "modules/modules_enabled.gen.h"
-#ifdef MODULE_GDSCRIPT_ENABLED
-
-#include "modules/gdscript/gdscript_parser.h"
-#include "modules/gdscript/gdscript_tokenizer.h"
-
-#ifdef TOOLS_ENABLED
-#include "editor/editor_settings.h"
-#endif
-
-namespace TestGDScript {
-
-static void test_tokenizer(const String &p_code, const Vector<String> &p_lines) {
- GDScriptTokenizer tokenizer;
- tokenizer.set_source_code(p_code);
-
- int tab_size = 4;
-#ifdef TOOLS_ENABLED
- if (EditorSettings::get_singleton()) {
- tab_size = EditorSettings::get_singleton()->get_setting("text_editor/indent/size");
- }
-#endif // TOOLS_ENABLED
- String tab = String(" ").repeat(tab_size);
-
- GDScriptTokenizer::Token current = tokenizer.scan();
- while (current.type != GDScriptTokenizer::Token::TK_EOF) {
- StringBuilder token;
- token += " --> "; // Padding for line number.
-
- for (int l = current.start_line; l <= current.end_line; l++) {
- print_line(vformat("%04d %s", l, p_lines[l - 1]).replace("\t", tab));
- }
-
- {
- // Print carets to point at the token.
- StringBuilder pointer;
- pointer += " "; // Padding for line number.
- int rightmost_column = current.rightmost_column;
- if (current.end_line > current.start_line) {
- rightmost_column--; // Don't point to the newline as a column.
- }
- for (int col = 1; col < rightmost_column; col++) {
- if (col < current.leftmost_column) {
- pointer += " ";
- } else {
- pointer += "^";
- }
- }
- print_line(pointer.as_string());
- }
-
- token += current.get_name();
-
- if (current.type == GDScriptTokenizer::Token::ERROR || current.type == GDScriptTokenizer::Token::LITERAL || current.type == GDScriptTokenizer::Token::IDENTIFIER || current.type == GDScriptTokenizer::Token::ANNOTATION) {
- token += "(";
- token += Variant::get_type_name(current.literal.get_type());
- token += ") ";
- token += current.literal;
- }
-
- print_line(token.as_string());
-
- print_line("-------------------------------------------------------");
-
- current = tokenizer.scan();
- }
-
- print_line(current.get_name()); // Should be EOF
-}
-
-static void test_parser(const String &p_code, const String &p_script_path, const Vector<String> &p_lines) {
- GDScriptParser parser;
- Error err = parser.parse(p_code, p_script_path, false);
-
- if (err != OK) {
- const List<GDScriptParser::ParserError> &errors = parser.get_errors();
- for (const List<GDScriptParser::ParserError>::Element *E = errors.front(); E != nullptr; E = E->next()) {
- const GDScriptParser::ParserError &error = E->get();
- print_line(vformat("%02d:%02d: %s", error.line, error.column, error.message));
- }
- }
-
- GDScriptParser::TreePrinter printer;
-
- printer.print_tree(parser);
-}
-
-MainLoop *test(TestType p_type) {
- List<String> cmdlargs = OS::get_singleton()->get_cmdline_args();
-
- if (cmdlargs.empty()) {
- return nullptr;
- }
-
- String test = cmdlargs.back()->get();
- if (!test.ends_with(".gd")) {
- print_line("This test expects a path to a GDScript file as its last parameter. Got: " + test);
- return nullptr;
- }
-
- FileAccessRef fa = FileAccess::open(test, FileAccess::READ);
- ERR_FAIL_COND_V_MSG(!fa, nullptr, "Could not open file: " + test);
-
- Vector<uint8_t> buf;
- int flen = fa->get_len();
- buf.resize(fa->get_len() + 1);
- fa->get_buffer(buf.ptrw(), flen);
- buf.write[flen] = 0;
-
- String code;
- code.parse_utf8((const char *)&buf[0]);
-
- Vector<String> lines;
- int last = 0;
- for (int i = 0; i <= code.length(); i++) {
- if (code[i] == '\n' || code[i] == 0) {
- lines.push_back(code.substr(last, i - last));
- last = i + 1;
- }
- }
-
- switch (p_type) {
- case TEST_TOKENIZER:
- test_tokenizer(code, lines);
- break;
- case TEST_PARSER:
- test_parser(code, test, lines);
- break;
- case TEST_COMPILER:
- case TEST_BYTECODE:
- print_line("Not implemented.");
- }
-
- return nullptr;
-}
-
-} // namespace TestGDScript
-
-#else
-
-namespace TestGDScript {
-
-MainLoop *test(TestType p_type) {
- ERR_PRINT("The GDScript module is disabled, therefore GDScript tests cannot be used.");
- return nullptr;
-}
-
-} // namespace TestGDScript
-
-#endif
diff --git a/tests/test_gradient.h b/tests/test_gradient.h
new file mode 100644
index 0000000000..0c018c33e5
--- /dev/null
+++ b/tests/test_gradient.h
@@ -0,0 +1,151 @@
+/*************************************************************************/
+/* test_gradient.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+#ifndef TEST_GRADIENT_H
+#define TEST_GRADIENT_H
+
+#include "core/math/color.h"
+#include "core/object/class_db.h"
+#include "scene/resources/gradient.h"
+
+#include "thirdparty/doctest/doctest.h"
+
+namespace TestGradient {
+
+TEST_CASE("[Gradient] Default gradient") {
+ // Black-white gradient.
+ Ref<Gradient> gradient = memnew(Gradient);
+
+ CHECK_MESSAGE(
+ gradient->get_points_count() == 2,
+ "Default gradient should contain the expected number of points.");
+
+ CHECK_MESSAGE(
+ gradient->get_color_at_offset(0.0).is_equal_approx(Color(0, 0, 0)),
+ "Default gradient should return the expected interpolated value at offset 0.0.");
+ CHECK_MESSAGE(
+ gradient->get_color_at_offset(0.4).is_equal_approx(Color(0.4, 0.4, 0.4)),
+ "Default gradient should return the expected interpolated value at offset 0.4.");
+ CHECK_MESSAGE(
+ gradient->get_color_at_offset(0.8).is_equal_approx(Color(0.8, 0.8, 0.8)),
+ "Default gradient should return the expected interpolated value at offset 0.8.");
+ CHECK_MESSAGE(
+ gradient->get_color_at_offset(1.0).is_equal_approx(Color(1, 1, 1)),
+ "Default gradient should return the expected interpolated value at offset 1.0.");
+
+ // Out of bounds checks.
+ CHECK_MESSAGE(
+ gradient->get_color_at_offset(-1.0).is_equal_approx(Color(0, 0, 0)),
+ "Default gradient should return the expected interpolated value at offset -1.0.");
+ CHECK_MESSAGE(
+ gradient->get_color_at_offset(1234.0).is_equal_approx(Color(1, 1, 1)),
+ "Default gradient should return the expected interpolated value at offset 1234.0.");
+}
+
+TEST_CASE("[Gradient] Custom gradient (points specified in order)") {
+ // Red-yellow-green gradient (with overbright green).
+ Ref<Gradient> gradient = memnew(Gradient);
+ Vector<Gradient::Point> points;
+ points.push_back({ 0.0, Color(1, 0, 0) });
+ points.push_back({ 0.5, Color(1, 1, 0) });
+ points.push_back({ 1.0, Color(0, 2, 0) });
+ gradient->set_points(points);
+
+ CHECK_MESSAGE(
+ gradient->get_points_count() == 3,
+ "Custom gradient should contain the expected number of points.");
+
+ CHECK_MESSAGE(
+ gradient->get_color_at_offset(0.0).is_equal_approx(Color(1, 0, 0)),
+ "Custom gradient should return the expected interpolated value at offset 0.0.");
+ CHECK_MESSAGE(
+ gradient->get_color_at_offset(0.25).is_equal_approx(Color(1, 0.5, 0)),
+ "Custom gradient should return the expected interpolated value at offset 0.25.");
+ CHECK_MESSAGE(
+ gradient->get_color_at_offset(0.5).is_equal_approx(Color(1, 1, 0)),
+ "Custom gradient should return the expected interpolated value at offset 0.5.");
+ CHECK_MESSAGE(
+ gradient->get_color_at_offset(0.75).is_equal_approx(Color(0.5, 1.5, 0)),
+ "Custom gradient should return the expected interpolated value at offset 0.75.");
+ CHECK_MESSAGE(
+ gradient->get_color_at_offset(1.0).is_equal_approx(Color(0, 2, 0)),
+ "Custom gradient should return the expected interpolated value at offset 1.0.");
+
+ gradient->remove_point(1);
+ CHECK_MESSAGE(
+ gradient->get_points_count() == 2,
+ "Custom gradient should contain the expected number of points after removing one point.");
+ CHECK_MESSAGE(
+ gradient->get_color_at_offset(0.5).is_equal_approx(Color(0.5, 1, 0)),
+ "Custom gradient should return the expected interpolated value at offset 0.5 after removing point at index 1.");
+}
+
+TEST_CASE("[Gradient] Custom gradient (points specified out-of-order)") {
+ // HSL rainbow with points specified out of order.
+ // These should be sorted automatically when adding points.
+ Ref<Gradient> gradient = memnew(Gradient);
+ Vector<Gradient::Point> points;
+ points.push_back({ 0.2, Color(1, 0, 0) });
+ points.push_back({ 0.0, Color(1, 1, 0) });
+ points.push_back({ 0.8, Color(0, 1, 0) });
+ points.push_back({ 0.4, Color(0, 1, 1) });
+ points.push_back({ 1.0, Color(0, 0, 1) });
+ points.push_back({ 0.6, Color(1, 0, 1) });
+ gradient->set_points(points);
+
+ CHECK_MESSAGE(
+ gradient->get_points_count() == 6,
+ "Custom out-of-order gradient should contain the expected number of points.");
+
+ CHECK_MESSAGE(
+ gradient->get_color_at_offset(0.0).is_equal_approx(Color(1, 1, 0)),
+ "Custom out-of-order gradient should return the expected interpolated value at offset 0.0.");
+ CHECK_MESSAGE(
+ gradient->get_color_at_offset(0.3).is_equal_approx(Color(0.5, 0.5, 0.5)),
+ "Custom out-of-order gradient should return the expected interpolated value at offset 0.3.");
+ CHECK_MESSAGE(
+ gradient->get_color_at_offset(0.6).is_equal_approx(Color(1, 0, 1)),
+ "Custom out-of-order gradient should return the expected interpolated value at offset 0.6.");
+ CHECK_MESSAGE(
+ gradient->get_color_at_offset(1.0).is_equal_approx(Color(0, 0, 1)),
+ "Custom out-of-order gradient should return the expected interpolated value at offset 1.0.");
+
+ gradient->remove_point(0);
+ CHECK_MESSAGE(
+ gradient->get_points_count() == 5,
+ "Custom out-of-order gradient should contain the expected number of points after removing one point.");
+ // The color will be clamped to the nearest point (which is at offset 0.2).
+ CHECK_MESSAGE(
+ gradient->get_color_at_offset(0.1).is_equal_approx(Color(1, 0, 0)),
+ "Custom out-of-order gradient should return the expected interpolated value at offset 0.1 after removing point at index 0.");
+}
+} // namespace TestGradient
+
+#endif // TEST_GRADIENT_H
diff --git a/tests/test_gui.cpp b/tests/test_gui.cpp
index d46a13d2c0..a4559687c8 100644
--- a/tests/test_gui.cpp
+++ b/tests/test_gui.cpp
@@ -34,7 +34,7 @@
#include "core/io/image_loader.h"
#include "core/os/os.h"
-#include "core/print_string.h"
+#include "core/string/print_string.h"
#include "scene/2d/sprite_2d.h"
#include "scene/gui/button.h"
#include "scene/gui/control.h"
@@ -67,8 +67,8 @@ public:
SceneTree::init();
Panel *frame = memnew(Panel);
- frame->set_anchor(MARGIN_RIGHT, Control::ANCHOR_END);
- frame->set_anchor(MARGIN_BOTTOM, Control::ANCHOR_END);
+ frame->set_anchor(SIDE_RIGHT, Control::ANCHOR_END);
+ frame->set_anchor(SIDE_BOTTOM, Control::ANCHOR_END);
frame->set_end(Point2(0, 0));
Ref<Theme> t = memnew(Theme);
@@ -199,7 +199,7 @@ public:
richtext->set_position(Point2(600, 210));
richtext->set_size(Point2(180, 250));
- richtext->set_anchor_and_margin(MARGIN_RIGHT, Control::ANCHOR_END, -20);
+ richtext->set_anchor_and_offset(SIDE_RIGHT, Control::ANCHOR_END, -20);
frame->add_child(richtext);
@@ -265,7 +265,6 @@ public:
MainLoop *test() {
return memnew(TestMainLoop);
}
-
} // namespace TestGUI
#endif
diff --git a/tests/test_json.h b/tests/test_json.h
new file mode 100644
index 0000000000..fe29e89e06
--- /dev/null
+++ b/tests/test_json.h
@@ -0,0 +1,166 @@
+/*************************************************************************/
+/* test_json.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+#ifndef TEST_JSON_H
+#define TEST_JSON_H
+
+#include "core/io/json.h"
+
+#include "thirdparty/doctest/doctest.h"
+
+namespace TestJSON {
+
+// NOTE: The current JSON parser accepts many non-conformant strings such as
+// single-quoted strings, duplicate commas and trailing commas.
+// This is intentionally not tested as users shouldn't rely on this behavior.
+
+TEST_CASE("[JSON] Parsing single data types") {
+ // Parsing a single data type as JSON is valid per the JSON specification.
+
+ JSON json;
+ Variant result;
+ String err_str;
+ int err_line;
+
+ json.parse("null", result, err_str, err_line);
+ CHECK_MESSAGE(
+ err_line == 0,
+ "Parsing `null` as JSON should parse successfully.");
+ CHECK_MESSAGE(
+ result == Variant(),
+ "Parsing a double quoted string as JSON should return the expected value.");
+
+ json.parse("true", result, err_str, err_line);
+ CHECK_MESSAGE(
+ err_line == 0,
+ "Parsing boolean `true` as JSON should parse successfully.");
+ CHECK_MESSAGE(
+ result,
+ "Parsing boolean `true` as JSON should return the expected value.");
+
+ json.parse("false", result, err_str, err_line);
+ CHECK_MESSAGE(
+ err_line == 0,
+ "Parsing boolean `false` as JSON should parse successfully.");
+ CHECK_MESSAGE(
+ !result,
+ "Parsing boolean `false` as JSON should return the expected value.");
+
+ // JSON only has a floating-point number type, no integer type.
+ // This is why we use `is_equal_approx()` for the comparison.
+ json.parse("123456", result, err_str, err_line);
+ CHECK_MESSAGE(
+ err_line == 0,
+ "Parsing an integer number as JSON should parse successfully.");
+ CHECK_MESSAGE(
+ Math::is_equal_approx(result, 123'456),
+ "Parsing an integer number as JSON should return the expected value.");
+
+ json.parse("0.123456", result, err_str, err_line);
+ CHECK_MESSAGE(
+ err_line == 0,
+ "Parsing a floating-point number as JSON should parse successfully.");
+ CHECK_MESSAGE(
+ Math::is_equal_approx(result, 0.123456),
+ "Parsing a floating-point number as JSON should return the expected value.");
+
+ json.parse("\"hello\"", result, err_str, err_line);
+ CHECK_MESSAGE(
+ err_line == 0,
+ "Parsing a double quoted string as JSON should parse successfully.");
+ CHECK_MESSAGE(
+ result == "hello",
+ "Parsing a double quoted string as JSON should return the expected value.");
+}
+
+TEST_CASE("[JSON] Parsing arrays") {
+ JSON json;
+ Variant result;
+ String err_str;
+ int err_line;
+
+ // JSON parsing fails if it's split over several lines (even if leading indentation is removed).
+ json.parse(
+ R"(["Hello", "world.", "This is",["a","json","array.",[]], "Empty arrays ahoy:", [[["Gotcha!"]]]])",
+ result, err_str, err_line);
+
+ const Array array = result;
+ CHECK_MESSAGE(
+ err_line == 0,
+ "Parsing a JSON array should parse successfully.");
+ CHECK_MESSAGE(
+ array[0] == "Hello",
+ "The parsed JSON should contain the expected values.");
+ const Array sub_array = array[3];
+ CHECK_MESSAGE(
+ sub_array.size() == 4,
+ "The parsed JSON should contain the expected values.");
+ CHECK_MESSAGE(
+ sub_array[1] == "json",
+ "The parsed JSON should contain the expected values.");
+ CHECK_MESSAGE(
+ sub_array[3].hash() == Array().hash(),
+ "The parsed JSON should contain the expected values.");
+ const Array deep_array = Array(Array(array[5])[0])[0];
+ CHECK_MESSAGE(
+ deep_array[0] == "Gotcha!",
+ "The parsed JSON should contain the expected values.");
+}
+
+TEST_CASE("[JSON] Parsing objects (dictionaries)") {
+ JSON json;
+ Variant result;
+ String err_str;
+ int err_line;
+
+ json.parse(
+ R"({"name": "Godot Engine", "is_free": true, "bugs": null, "apples": {"red": 500, "green": 0, "blue": -20}, "empty_object": {}})",
+ result, err_str, err_line);
+
+ const Dictionary dictionary = result;
+ CHECK_MESSAGE(
+ dictionary["name"] == "Godot Engine",
+ "The parsed JSON should contain the expected values.");
+ CHECK_MESSAGE(
+ dictionary["is_free"],
+ "The parsed JSON should contain the expected values.");
+ CHECK_MESSAGE(
+ dictionary["bugs"] == Variant(),
+ "The parsed JSON should contain the expected values.");
+ CHECK_MESSAGE(
+ Math::is_equal_approx(Dictionary(dictionary["apples"])["blue"], -20),
+ "The parsed JSON should contain the expected values.");
+ CHECK_MESSAGE(
+ dictionary["empty_object"].hash() == Dictionary().hash(),
+ "The parsed JSON should contain the expected values.");
+}
+} // namespace TestJSON
+
+#endif // TEST_JSON_H
diff --git a/tests/test_list.h b/tests/test_list.h
new file mode 100644
index 0000000000..8d29bd907f
--- /dev/null
+++ b/tests/test_list.h
@@ -0,0 +1,548 @@
+/*************************************************************************/
+/* test_list.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+#ifndef TEST_LIST_H
+#define TEST_LIST_H
+
+#include "core/templates/list.h"
+
+#include "tests/test_macros.h"
+
+namespace TestList {
+
+static void populate_integers(List<int> &p_list, List<int>::Element *r_elements[], int num_elements) {
+ p_list.clear();
+ for (int i = 0; i < num_elements; ++i) {
+ List<int>::Element *n = p_list.push_back(i);
+ r_elements[i] = n;
+ }
+}
+
+TEST_CASE("[List] Push/pop back") {
+ List<String> list;
+
+ List<String>::Element *n;
+ n = list.push_back("A");
+ CHECK(n->get() == "A");
+ n = list.push_back("B");
+ CHECK(n->get() == "B");
+ n = list.push_back("C");
+ CHECK(n->get() == "C");
+
+ CHECK(list.size() == 3);
+ CHECK(!list.empty());
+
+ String v;
+ v = list.back()->get();
+ list.pop_back();
+ CHECK(v == "C");
+ v = list.back()->get();
+ list.pop_back();
+ CHECK(v == "B");
+ v = list.back()->get();
+ list.pop_back();
+ CHECK(v == "A");
+
+ CHECK(list.size() == 0);
+ CHECK(list.empty());
+
+ CHECK(list.back() == nullptr);
+ CHECK(list.front() == nullptr);
+}
+
+TEST_CASE("[List] Push/pop front") {
+ List<String> list;
+
+ List<String>::Element *n;
+ n = list.push_front("A");
+ CHECK(n->get() == "A");
+ n = list.push_front("B");
+ CHECK(n->get() == "B");
+ n = list.push_front("C");
+ CHECK(n->get() == "C");
+
+ CHECK(list.size() == 3);
+ CHECK(!list.empty());
+
+ String v;
+ v = list.front()->get();
+ list.pop_front();
+ CHECK(v == "C");
+ v = list.front()->get();
+ list.pop_front();
+ CHECK(v == "B");
+ v = list.front()->get();
+ list.pop_front();
+ CHECK(v == "A");
+
+ CHECK(list.size() == 0);
+ CHECK(list.empty());
+
+ CHECK(list.back() == nullptr);
+ CHECK(list.front() == nullptr);
+}
+
+TEST_CASE("[List] Set and get") {
+ List<String> list;
+ list.push_back("A");
+
+ List<String>::Element *n = list.front();
+ CHECK(n->get() == "A");
+
+ n->set("X");
+ CHECK(n->get() == "X");
+}
+
+TEST_CASE("[List] Insert before") {
+ List<String> list;
+ List<String>::Element *a = list.push_back("A");
+ List<String>::Element *b = list.push_back("B");
+ List<String>::Element *c = list.push_back("C");
+
+ list.insert_before(b, "I");
+
+ CHECK(a->next()->get() == "I");
+ CHECK(c->prev()->prev()->get() == "I");
+ CHECK(list.front()->next()->get() == "I");
+ CHECK(list.back()->prev()->prev()->get() == "I");
+}
+
+TEST_CASE("[List] Insert after") {
+ List<String> list;
+ List<String>::Element *a = list.push_back("A");
+ List<String>::Element *b = list.push_back("B");
+ List<String>::Element *c = list.push_back("C");
+
+ list.insert_after(b, "I");
+
+ CHECK(a->next()->next()->get() == "I");
+ CHECK(c->prev()->get() == "I");
+ CHECK(list.front()->next()->next()->get() == "I");
+ CHECK(list.back()->prev()->get() == "I");
+}
+
+TEST_CASE("[List] Insert before null") {
+ List<String> list;
+ List<String>::Element *a = list.push_back("A");
+ List<String>::Element *b = list.push_back("B");
+ List<String>::Element *c = list.push_back("C");
+
+ list.insert_before(nullptr, "I");
+
+ CHECK(a->next()->get() == "B");
+ CHECK(b->get() == "B");
+ CHECK(c->prev()->prev()->get() == "A");
+ CHECK(list.front()->next()->get() == "B");
+ CHECK(list.back()->prev()->prev()->get() == "B");
+ CHECK(list.back()->get() == "I");
+}
+
+TEST_CASE("[List] Insert after null") {
+ List<String> list;
+ List<String>::Element *a = list.push_back("A");
+ List<String>::Element *b = list.push_back("B");
+ List<String>::Element *c = list.push_back("C");
+
+ list.insert_after(nullptr, "I");
+
+ CHECK(a->next()->get() == "B");
+ CHECK(b->get() == "B");
+ CHECK(c->prev()->prev()->get() == "A");
+ CHECK(list.front()->next()->get() == "B");
+ CHECK(list.back()->prev()->prev()->get() == "B");
+ CHECK(list.back()->get() == "I");
+}
+
+TEST_CASE("[List] Find") {
+ List<int> list;
+ List<int>::Element *n[10];
+ // Indices match values.
+ populate_integers(list, n, 10);
+
+ for (int i = 0; i < 10; ++i) {
+ CHECK(n[i]->get() == list.find(i)->get());
+ }
+}
+
+TEST_CASE("[List] Erase (by value)") {
+ List<int> list;
+ List<int>::Element *n[4];
+ // Indices match values.
+ populate_integers(list, n, 4);
+
+ CHECK(list.front()->next()->next()->get() == 2);
+ bool erased = list.erase(2); // 0, 1, 3.
+ CHECK(erased);
+ CHECK(list.size() == 3);
+
+ // The pointer n[2] points to the freed memory which is not reset to zero,
+ // so the below assertion may pass, but this relies on undefined behavior.
+ // CHECK(n[2]->get() == 2);
+
+ CHECK(list.front()->get() == 0);
+ CHECK(list.front()->next()->next()->get() == 3);
+ CHECK(list.back()->get() == 3);
+ CHECK(list.back()->prev()->get() == 1);
+
+ CHECK(n[1]->next()->get() == 3);
+ CHECK(n[3]->prev()->get() == 1);
+
+ erased = list.erase(9000); // Doesn't exist.
+ CHECK(!erased);
+}
+
+TEST_CASE("[List] Erase (by element)") {
+ List<int> list;
+ List<int>::Element *n[4];
+ // Indices match values.
+ populate_integers(list, n, 4);
+
+ bool erased = list.erase(n[2]);
+ CHECK(erased);
+ CHECK(list.size() == 3);
+ CHECK(n[1]->next()->get() == 3);
+ CHECK(n[3]->prev()->get() == 1);
+}
+
+TEST_CASE("[List] Element erase") {
+ List<int> list;
+ List<int>::Element *n[4];
+ // Indices match values.
+ populate_integers(list, n, 4);
+
+ n[2]->erase();
+
+ CHECK(list.size() == 3);
+ CHECK(n[1]->next()->get() == 3);
+ CHECK(n[3]->prev()->get() == 1);
+}
+
+TEST_CASE("[List] Clear") {
+ List<int> list;
+ List<int>::Element *n[100];
+ populate_integers(list, n, 100);
+
+ list.clear();
+
+ CHECK(list.size() == 0);
+ CHECK(list.empty());
+}
+
+TEST_CASE("[List] Invert") {
+ List<int> list;
+ List<int>::Element *n[4];
+ populate_integers(list, n, 4);
+
+ list.invert();
+
+ CHECK(list.front()->get() == 3);
+ CHECK(list.front()->next()->get() == 2);
+ CHECK(list.back()->prev()->get() == 1);
+ CHECK(list.back()->get() == 0);
+}
+
+TEST_CASE("[List] Move to front") {
+ List<int> list;
+ List<int>::Element *n[4];
+ populate_integers(list, n, 4);
+
+ list.move_to_front(n[3]);
+
+ CHECK(list.front()->get() == 3);
+ CHECK(list.back()->get() == 2);
+}
+
+TEST_CASE("[List] Move to back") {
+ List<int> list;
+ List<int>::Element *n[4];
+ populate_integers(list, n, 4);
+
+ list.move_to_back(n[0]);
+
+ CHECK(list.back()->get() == 0);
+ CHECK(list.front()->get() == 1);
+}
+
+TEST_CASE("[List] Move before") {
+ List<int> list;
+ List<int>::Element *n[4];
+ populate_integers(list, n, 4);
+
+ list.move_before(n[3], n[1]);
+
+ CHECK(list.front()->next()->get() == n[3]->get());
+}
+
+TEST_CASE("[List] Sort") {
+ List<String> list;
+ list.push_back("D");
+ list.push_back("B");
+ list.push_back("A");
+ list.push_back("C");
+
+ list.sort();
+
+ CHECK(list.front()->get() == "A");
+ CHECK(list.front()->next()->get() == "B");
+ CHECK(list.back()->prev()->get() == "C");
+ CHECK(list.back()->get() == "D");
+}
+
+TEST_CASE("[List] Swap adjacent front and back") {
+ List<int> list;
+ List<int>::Element *n[2];
+ populate_integers(list, n, 2);
+
+ list.swap(list.front(), list.back());
+
+ CHECK(list.front()->prev() == nullptr);
+ CHECK(list.front() != list.front()->next());
+
+ CHECK(list.front() == n[1]);
+ CHECK(list.back() == n[0]);
+
+ CHECK(list.back()->next() == nullptr);
+ CHECK(list.back() != list.back()->prev());
+}
+
+TEST_CASE("[List] Swap first adjacent pair") {
+ List<int> list;
+ List<int>::Element *n[4];
+ populate_integers(list, n, 4);
+
+ list.swap(n[0], n[1]);
+
+ CHECK(list.front()->prev() == nullptr);
+ CHECK(list.front() != list.front()->next());
+
+ CHECK(list.front() == n[1]);
+ CHECK(list.front()->next() == n[0]);
+ CHECK(list.back()->prev() == n[2]);
+ CHECK(list.back() == n[3]);
+
+ CHECK(list.back()->next() == nullptr);
+ CHECK(list.back() != list.back()->prev());
+}
+
+TEST_CASE("[List] Swap middle adjacent pair") {
+ List<int> list;
+ List<int>::Element *n[4];
+ populate_integers(list, n, 4);
+
+ list.swap(n[1], n[2]);
+
+ CHECK(list.front()->prev() == nullptr);
+
+ CHECK(list.front() == n[0]);
+ CHECK(list.front()->next() == n[2]);
+ CHECK(list.back()->prev() == n[1]);
+ CHECK(list.back() == n[3]);
+
+ CHECK(list.back()->next() == nullptr);
+}
+
+TEST_CASE("[List] Swap last adjacent pair") {
+ List<int> list;
+ List<int>::Element *n[4];
+ populate_integers(list, n, 4);
+
+ list.swap(n[2], n[3]);
+
+ CHECK(list.front()->prev() == nullptr);
+
+ CHECK(list.front() == n[0]);
+ CHECK(list.front()->next() == n[1]);
+ CHECK(list.back()->prev() == n[3]);
+ CHECK(list.back() == n[2]);
+
+ CHECK(list.back()->next() == nullptr);
+}
+
+TEST_CASE("[List] Swap first cross pair") {
+ List<int> list;
+ List<int>::Element *n[4];
+ populate_integers(list, n, 4);
+
+ list.swap(n[0], n[2]);
+
+ CHECK(list.front()->prev() == nullptr);
+
+ CHECK(list.front() == n[2]);
+ CHECK(list.front()->next() == n[1]);
+ CHECK(list.back()->prev() == n[0]);
+ CHECK(list.back() == n[3]);
+
+ CHECK(list.back()->next() == nullptr);
+}
+
+TEST_CASE("[List] Swap last cross pair") {
+ List<int> list;
+ List<int>::Element *n[4];
+ populate_integers(list, n, 4);
+
+ list.swap(n[1], n[3]);
+
+ CHECK(list.front()->prev() == nullptr);
+
+ CHECK(list.front() == n[0]);
+ CHECK(list.front()->next() == n[3]);
+ CHECK(list.back()->prev() == n[2]);
+ CHECK(list.back() == n[1]);
+
+ CHECK(list.back()->next() == nullptr);
+}
+
+TEST_CASE("[List] Swap edges") {
+ List<int> list;
+ List<int>::Element *n[4];
+ populate_integers(list, n, 4);
+
+ list.swap(n[1], n[3]);
+
+ CHECK(list.front()->prev() == nullptr);
+
+ CHECK(list.front() == n[0]);
+ CHECK(list.front()->next() == n[3]);
+ CHECK(list.back()->prev() == n[2]);
+ CHECK(list.back() == n[1]);
+
+ CHECK(list.back()->next() == nullptr);
+}
+
+TEST_CASE("[List] Swap middle (values check)") {
+ List<String> list;
+ List<String>::Element *n_str1 = list.push_back("Still");
+ List<String>::Element *n_str2 = list.push_back("waiting");
+ List<String>::Element *n_str3 = list.push_back("for");
+ List<String>::Element *n_str4 = list.push_back("Godot.");
+
+ CHECK(n_str1->get() == "Still");
+ CHECK(n_str4->get() == "Godot.");
+
+ CHECK(list.front()->get() == "Still");
+ CHECK(list.front()->next()->get() == "waiting");
+ CHECK(list.back()->prev()->get() == "for");
+ CHECK(list.back()->get() == "Godot.");
+
+ list.swap(n_str2, n_str3);
+
+ CHECK(list.front()->next()->get() == "for");
+ CHECK(list.back()->prev()->get() == "waiting");
+}
+
+TEST_CASE("[List] Swap front and back (values check)") {
+ List<Variant> list;
+ Variant str = "Godot";
+ List<Variant>::Element *n_str = list.push_back(str);
+ Variant color = Color(0, 0, 1);
+ List<Variant>::Element *n_color = list.push_back(color);
+
+ CHECK(list.front()->get() == "Godot");
+ CHECK(list.back()->get() == Color(0, 0, 1));
+
+ list.swap(n_str, n_color);
+
+ CHECK(list.front()->get() == Color(0, 0, 1));
+ CHECK(list.back()->get() == "Godot");
+}
+
+TEST_CASE("[List] Swap adjacent back and front (reverse order of elements)") {
+ List<int> list;
+ List<int>::Element *n[2];
+ populate_integers(list, n, 2);
+
+ list.swap(n[1], n[0]);
+
+ List<int>::Element *it = list.front();
+ while (it) {
+ List<int>::Element *prev_it = it;
+ it = it->next();
+ if (it == prev_it) {
+ FAIL_CHECK("Infinite loop detected.");
+ break;
+ }
+ }
+}
+
+static void swap_random(List<int> &p_list, List<int>::Element *r_elements[], size_t p_size, size_t p_iterations) {
+ Math::seed(0);
+
+ for (size_t test_i = 0; test_i < p_iterations; ++test_i) {
+ // A and B elements have corresponding indices as values.
+ const int a_idx = static_cast<int>(Math::rand() % p_size);
+ const int b_idx = static_cast<int>(Math::rand() % p_size);
+ List<int>::Element *a = p_list.find(a_idx); // via find.
+ List<int>::Element *b = r_elements[b_idx]; // via pointer.
+
+ int va = a->get();
+ int vb = b->get();
+
+ p_list.swap(a, b);
+
+ CHECK(va == a->get());
+ CHECK(vb == b->get());
+
+ size_t element_count = 0;
+
+ // Fully traversable after swap?
+ List<int>::Element *it = p_list.front();
+ while (it) {
+ element_count += 1;
+ List<int>::Element *prev_it = it;
+ it = it->next();
+ if (it == prev_it) {
+ FAIL_CHECK("Infinite loop detected.");
+ break;
+ }
+ }
+ // We should not lose anything in the process.
+ if (element_count != p_size) {
+ FAIL_CHECK("Element count mismatch.");
+ break;
+ }
+ }
+}
+
+TEST_CASE("[Stress][List] Swap random 100 elements, 500 iterations.") {
+ List<int> list;
+ List<int>::Element *n[100];
+ populate_integers(list, n, 100);
+ swap_random(list, n, 100, 500);
+}
+
+TEST_CASE("[Stress][List] Swap random 10 elements, 1000 iterations.") {
+ List<int> list;
+ List<int>::Element *n[10];
+ populate_integers(list, n, 10);
+ swap_random(list, n, 10, 1000);
+}
+} // namespace TestList
+
+#endif // TEST_LIST_H
diff --git a/tests/test_lru.h b/tests/test_lru.h
new file mode 100644
index 0000000000..260841f4c4
--- /dev/null
+++ b/tests/test_lru.h
@@ -0,0 +1,100 @@
+/*************************************************************************/
+/* test_lru.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+#ifndef TEST_LRU_H
+#define TEST_LRU_H
+
+#include "core/templates/lru.h"
+#include "core/templates/vector.h"
+
+#include "tests/test_macros.h"
+
+namespace TestLRU {
+
+TEST_CASE("[LRU] Store and read") {
+ LRUCache<int, int> lru;
+
+ lru.set_capacity(3);
+ lru.insert(1, 1);
+ lru.insert(50, 2);
+ lru.insert(100, 5);
+
+ CHECK(lru.has(1));
+ CHECK(lru.has(50));
+ CHECK(lru.has(100));
+ CHECK(!lru.has(200));
+
+ CHECK(lru.get(1) == 1);
+ CHECK(lru.get(50) == 2);
+ CHECK(lru.get(100) == 5);
+
+ CHECK(lru.getptr(1) != nullptr);
+ CHECK(lru.getptr(1000) == nullptr);
+
+ lru.insert(600, 600); // Erase <50>
+ CHECK(lru.has(600));
+ CHECK(!lru.has(50));
+}
+
+TEST_CASE("[LRU] Resize and clear") {
+ LRUCache<int, int> lru;
+
+ lru.set_capacity(3);
+ lru.insert(1, 1);
+ lru.insert(2, 2);
+ lru.insert(3, 3);
+
+ CHECK(lru.get_capacity() == 3);
+
+ lru.set_capacity(5);
+ CHECK(lru.get_capacity() == 5);
+
+ CHECK(lru.has(1));
+ CHECK(lru.has(2));
+ CHECK(lru.has(3));
+ CHECK(!lru.has(4));
+
+ lru.set_capacity(2);
+ CHECK(lru.get_capacity() == 2);
+
+ CHECK(!lru.has(1));
+ CHECK(lru.has(2));
+ CHECK(lru.has(3));
+ CHECK(!lru.has(4));
+
+ lru.clear();
+ CHECK(!lru.has(1));
+ CHECK(!lru.has(2));
+ CHECK(!lru.has(3));
+ CHECK(!lru.has(4));
+}
+} // namespace TestLRU
+
+#endif // TEST_LRU_H
diff --git a/tests/test_gdscript.h b/tests/test_macros.cpp
index 6595da1430..2317223b23 100644
--- a/tests/test_gdscript.h
+++ b/tests/test_macros.cpp
@@ -1,5 +1,5 @@
/*************************************************************************/
-/* test_gdscript.h */
+/* test_macros.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
@@ -28,21 +28,15 @@
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
-#ifndef TEST_GDSCRIPT_H
-#define TEST_GDSCRIPT_H
+#define DOCTEST_CONFIG_IMPLEMENT
+#include "test_macros.h"
-#include "core/os/main_loop.h"
+Map<String, TestFunc> *test_commands = nullptr;
-namespace TestGDScript {
-
-enum TestType {
- TEST_TOKENIZER,
- TEST_PARSER,
- TEST_COMPILER,
- TEST_BYTECODE,
-};
-
-MainLoop *test(TestType p_type);
-} // namespace TestGDScript
-
-#endif // TEST_GDSCRIPT_H
+int register_test_command(String p_command, TestFunc p_function) {
+ if (!test_commands) {
+ test_commands = new Map<String, TestFunc>;
+ }
+ test_commands->insert(p_command, p_function);
+ return 0;
+}
diff --git a/tests/test_macros.h b/tests/test_macros.h
new file mode 100644
index 0000000000..ae6af93825
--- /dev/null
+++ b/tests/test_macros.h
@@ -0,0 +1,126 @@
+/*************************************************************************/
+/* test_macros.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+#ifndef TEST_MACROS_H
+#define TEST_MACROS_H
+
+#include "core/templates/map.h"
+#include "core/variant/variant.h"
+
+// See documentation for doctest at:
+// https://github.com/onqtam/doctest/blob/master/doc/markdown/readme.md#reference
+#include "thirdparty/doctest/doctest.h"
+
+// The test is skipped with this, run pending tests with `--test --no-skip`.
+#define TEST_CASE_PENDING(name) TEST_CASE(name *doctest::skip())
+
+// The test case is marked as failed, but does not fail the entire test run.
+#define TEST_CASE_MAY_FAIL(name) TEST_CASE(name *doctest::may_fail())
+
+// Temporarily disable error prints to test failure paths.
+// This allows to avoid polluting the test summary with error messages.
+// The `_print_error_enabled` boolean is defined in `core/print_string.cpp` and
+// works at global scope. It's used by various loggers in `should_log()` method,
+// which are used by error macros which call into `OS::print_error`, effectively
+// disabling any error messages to be printed from the engine side (not tests).
+#define ERR_PRINT_OFF _print_error_enabled = false;
+#define ERR_PRINT_ON _print_error_enabled = true;
+
+// Stringify all `Variant` compatible types for doctest output by default.
+// https://github.com/onqtam/doctest/blob/master/doc/markdown/stringification.md
+
+#define DOCTEST_STRINGIFY_VARIANT(m_type) \
+ template <> \
+ struct doctest::StringMaker<m_type> { \
+ static doctest::String convert(const m_type &p_val) { \
+ const Variant val = p_val; \
+ return val.get_construct_string().utf8().get_data(); \
+ } \
+ };
+
+#define DOCTEST_STRINGIFY_VARIANT_POINTER(m_type) \
+ template <> \
+ struct doctest::StringMaker<m_type> { \
+ static doctest::String convert(const m_type *p_val) { \
+ const Variant val = p_val; \
+ return val.get_construct_string().utf8().get_data(); \
+ } \
+ };
+
+DOCTEST_STRINGIFY_VARIANT(Variant);
+DOCTEST_STRINGIFY_VARIANT(::String); // Disambiguate from `doctest::String`.
+
+DOCTEST_STRINGIFY_VARIANT(Vector2);
+DOCTEST_STRINGIFY_VARIANT(Vector2i);
+DOCTEST_STRINGIFY_VARIANT(Rect2);
+DOCTEST_STRINGIFY_VARIANT(Rect2i);
+DOCTEST_STRINGIFY_VARIANT(Vector3);
+DOCTEST_STRINGIFY_VARIANT(Vector3i);
+DOCTEST_STRINGIFY_VARIANT(Transform2D);
+DOCTEST_STRINGIFY_VARIANT(Plane);
+DOCTEST_STRINGIFY_VARIANT(Quat);
+DOCTEST_STRINGIFY_VARIANT(AABB);
+DOCTEST_STRINGIFY_VARIANT(Basis);
+DOCTEST_STRINGIFY_VARIANT(Transform);
+
+DOCTEST_STRINGIFY_VARIANT(::Color); // Disambiguate from `doctest::Color`.
+DOCTEST_STRINGIFY_VARIANT(StringName);
+DOCTEST_STRINGIFY_VARIANT(NodePath);
+DOCTEST_STRINGIFY_VARIANT(RID);
+DOCTEST_STRINGIFY_VARIANT_POINTER(Object);
+DOCTEST_STRINGIFY_VARIANT(Callable);
+DOCTEST_STRINGIFY_VARIANT(Signal);
+DOCTEST_STRINGIFY_VARIANT(Dictionary);
+DOCTEST_STRINGIFY_VARIANT(Array);
+
+DOCTEST_STRINGIFY_VARIANT(PackedByteArray);
+DOCTEST_STRINGIFY_VARIANT(PackedInt32Array);
+DOCTEST_STRINGIFY_VARIANT(PackedInt64Array);
+DOCTEST_STRINGIFY_VARIANT(PackedFloat32Array);
+DOCTEST_STRINGIFY_VARIANT(PackedFloat64Array);
+DOCTEST_STRINGIFY_VARIANT(PackedStringArray);
+DOCTEST_STRINGIFY_VARIANT(PackedVector2Array);
+DOCTEST_STRINGIFY_VARIANT(PackedVector3Array);
+DOCTEST_STRINGIFY_VARIANT(PackedColorArray);
+
+// Register test commands to be launched from the command-line.
+// For instance: REGISTER_TEST_COMMAND("gdscript-parser" &test_parser_func).
+// Example usage: `godot --test gdscript-parser`.
+
+typedef void (*TestFunc)();
+extern Map<String, TestFunc> *test_commands;
+int register_test_command(String p_command, TestFunc p_function);
+
+#define REGISTER_TEST_COMMAND(m_command, m_function) \
+ DOCTEST_GLOBAL_NO_WARNINGS(DOCTEST_ANONYMOUS(_DOCTEST_ANON_VAR_)) = \
+ register_test_command(m_command, m_function); \
+ DOCTEST_GLOBAL_NO_WARNINGS_END()
+
+#endif // TEST_MACROS_H
diff --git a/tests/test_main.cpp b/tests/test_main.cpp
index 84d2fe1f6c..5d961854cb 100644
--- a/tests/test_main.cpp
+++ b/tests/test_main.cpp
@@ -30,101 +30,102 @@
#include "test_main.h"
-#include "core/list.h"
-
-#ifdef DEBUG_ENABLED
+#include "core/templates/list.h"
+#include "test_aabb.h"
#include "test_astar.h"
#include "test_basis.h"
#include "test_class_db.h"
-#include "test_gdscript.h"
+#include "test_color.h"
+#include "test_command_queue.h"
+#include "test_config_file.h"
+#include "test_crypto.h"
+#include "test_curve.h"
+#include "test_expression.h"
+#include "test_file_access.h"
+#include "test_gradient.h"
#include "test_gui.h"
+#include "test_json.h"
+#include "test_list.h"
+#include "test_lru.h"
#include "test_math.h"
+#include "test_method_bind.h"
+#include "test_node_path.h"
#include "test_oa_hash_map.h"
+#include "test_object.h"
#include "test_ordered_hash_map.h"
+#include "test_paged_array.h"
+#include "test_pck_packer.h"
#include "test_physics_2d.h"
#include "test_physics_3d.h"
+#include "test_random_number_generator.h"
+#include "test_rect2.h"
#include "test_render.h"
#include "test_shader_lang.h"
#include "test_string.h"
+#include "test_text_server.h"
#include "test_validate_testing.h"
#include "test_variant.h"
#include "modules/modules_tests.gen.h"
-#include "thirdparty/doctest/doctest.h"
+#include "tests/test_macros.h"
-const char **tests_get_names() {
- static const char *test_names[] = {
- "*",
- "all",
- "math",
- "basis",
- "physics_2d",
- "physics_3d",
- "render",
- "oa_hash_map",
- "class_db",
- "gui",
- "shaderlang",
- "gd_tokenizer",
- "gd_parser",
- "gd_compiler",
- "gd_bytecode",
- "ordered_hash_map",
- "astar",
- nullptr
- };
+int test_main(int argc, char *argv[]) {
+ bool run_tests = true;
- return test_names;
-}
+ // Convert arguments to Godot's command-line.
+ List<String> args;
-int test_main(int argc, char *argv[]) {
- // doctest runner for when legacy unit tests are no found
+ for (int i = 0; i < argc; i++) {
+ args.push_back(String::utf8(argv[i]));
+ }
+ OS::get_singleton()->set_cmdline("", args);
+
+ // Run custom test tools.
+ if (test_commands) {
+ for (Map<String, TestFunc>::Element *E = test_commands->front(); E; E = E->next()) {
+ if (args.find(E->key())) {
+ const TestFunc &test_func = E->get();
+ test_func();
+ run_tests = false;
+ break;
+ }
+ }
+ if (!run_tests) {
+ delete test_commands;
+ return 0;
+ }
+ }
+ // Doctest runner.
doctest::Context test_context;
- List<String> valid_arguments;
+ List<String> test_args;
- // clean arguments of --test from the args
- int argument_count = 0;
+ // Clean arguments of "--test" from the args.
for (int x = 0; x < argc; x++) {
- if (strncmp(argv[x], "--test", 6) != 0) {
- valid_arguments.push_back(String(argv[x]));
- argument_count++;
+ String arg = String(argv[x]);
+ if (arg != "--test") {
+ test_args.push_back(arg);
}
}
-
- // convert godot command line arguments back to standard arguments.
- char **args = new char *[valid_arguments.size()];
- for (int x = 0; x < valid_arguments.size(); x++) {
- // operation to convert godot string to non wchar string
- const char *str = valid_arguments[x].utf8().ptr();
- // allocate the string copy
- args[x] = new char[strlen(str) + 1];
- // copy this into memory
- std::memcpy(args[x], str, strlen(str) + 1);
+ // Convert Godot command line arguments back to standard arguments.
+ char **doctest_args = new char *[test_args.size()];
+ for (int x = 0; x < test_args.size(); x++) {
+ // Operation to convert Godot string to non wchar string.
+ CharString cs = test_args[x].utf8();
+ const char *str = cs.get_data();
+ // Allocate the string copy.
+ doctest_args[x] = new char[strlen(str) + 1];
+ // Copy this into memory.
+ memcpy(doctest_args[x], str, strlen(str) + 1);
}
- test_context.applyCommandLine(valid_arguments.size(), args);
+ test_context.applyCommandLine(test_args.size(), doctest_args);
- test_context.setOption("order-by", "name");
- test_context.setOption("abort-after", 5);
- test_context.setOption("no-breaks", true);
- delete[] args;
- return test_context.run();
-}
-
-#else
-
-const char **tests_get_names() {
- static const char *test_names[] = {
- nullptr
- };
-
- return test_names;
-}
+ for (int x = 0; x < test_args.size(); x++) {
+ delete[] doctest_args[x];
+ }
+ delete[] doctest_args;
-int test_main(int argc, char *argv[]) {
- return 0;
+ return test_context.run();
}
-
-#endif
diff --git a/tests/test_main.h b/tests/test_main.h
index 8273b74eac..983bfde402 100644
--- a/tests/test_main.h
+++ b/tests/test_main.h
@@ -31,11 +31,6 @@
#ifndef TEST_MAIN_H
#define TEST_MAIN_H
-#include "core/list.h"
-#include "core/os/main_loop.h"
-#include "core/ustring.h"
-
-const char **tests_get_names();
int test_main(int argc, char *argv[]);
#endif // TEST_MAIN_H
diff --git a/tests/test_math.cpp b/tests/test_math.cpp
index 84a85be2f6..a7f99e5401 100644
--- a/tests/test_math.cpp
+++ b/tests/test_math.cpp
@@ -36,14 +36,14 @@
#include "core/math/geometry_2d.h"
#include "core/math/math_funcs.h"
#include "core/math/transform.h"
-#include "core/method_ptrcall.h"
#include "core/os/file_access.h"
#include "core/os/keyboard.h"
#include "core/os/os.h"
-#include "core/print_string.h"
-#include "core/ustring.h"
-#include "core/variant.h"
-#include "core/vmap.h"
+#include "core/string/print_string.h"
+#include "core/string/ustring.h"
+#include "core/templates/vmap.h"
+#include "core/variant/method_ptrcall.h"
+#include "core/variant/variant.h"
#include "scene/main/node.h"
#include "scene/resources/texture.h"
#include "servers/rendering/shader_language.h"
@@ -162,7 +162,7 @@ class GetClassAndNamespace {
} break;
case '\'':
case '"': {
- CharType begin_str = code[idx];
+ char32_t begin_str = code[idx];
idx++;
String tk_string = String();
while (true) {
@@ -176,13 +176,13 @@ class GetClassAndNamespace {
} else if (code[idx] == '\\') {
//escaped characters...
idx++;
- CharType next = code[idx];
+ char32_t next = code[idx];
if (next == 0) {
error_str = "Unterminated String";
error = true;
return TK_ERROR;
}
- CharType res = 0;
+ char32_t res = 0;
switch (next) {
case 'b':
@@ -241,7 +241,7 @@ class GetClassAndNamespace {
if (code[idx] == '-' || (code[idx] >= '0' && code[idx] <= '9')) {
//a number
- const CharType *rptr;
+ const char32_t *rptr;
double number = String::to_float(&code[idx], &rptr);
idx += (rptr - &code[idx]);
value = number;
@@ -699,5 +699,4 @@ MainLoop *test() {
return nullptr;
}
-
} // namespace TestMath
diff --git a/tests/test_method_bind.h b/tests/test_method_bind.h
new file mode 100644
index 0000000000..62d8bd132c
--- /dev/null
+++ b/tests/test_method_bind.h
@@ -0,0 +1,164 @@
+/*************************************************************************/
+/* test_method_bind.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+#ifndef TEST_METHOD_BIND_H
+#define TEST_METHOD_BIND_H
+
+#include "core/object/class_db.h"
+
+#include "tests/test_macros.h"
+
+#include <inttypes.h>
+#include <stdio.h>
+#include <wchar.h>
+
+namespace TestMethodBind {
+
+class MethodBindTester : public Object {
+ GDCLASS(MethodBindTester, Object);
+
+public:
+ enum Test {
+ TEST_METHOD,
+ TEST_METHOD_ARGS,
+ TEST_METHODC,
+ TEST_METHODC_ARGS,
+ TEST_METHODR,
+ TEST_METHODR_ARGS,
+ TEST_METHODRC,
+ TEST_METHODRC_ARGS,
+ TEST_METHOD_DEFARGS,
+ TEST_MAX
+ };
+
+ int test_num = 0;
+
+ bool test_valid[TEST_MAX];
+
+ void test_method() {
+ test_valid[TEST_METHOD] = true;
+ }
+
+ void test_method_args(int p_arg) {
+ test_valid[TEST_METHOD_ARGS] = p_arg == test_num;
+ }
+
+ void test_methodc() {
+ test_valid[TEST_METHODC] = true;
+ }
+
+ void test_methodc_args(int p_arg) {
+ test_valid[TEST_METHODC_ARGS] = p_arg == test_num;
+ }
+
+ int test_methodr() {
+ test_valid[TEST_METHODR] = true; //temporary
+ return test_num;
+ }
+
+ int test_methodr_args(int p_arg) {
+ test_valid[TEST_METHODR_ARGS] = true; //temporary
+ return p_arg;
+ }
+
+ int test_methodrc() {
+ test_valid[TEST_METHODRC] = true; //temporary
+ return test_num;
+ }
+
+ int test_methodrc_args(int p_arg) {
+ test_valid[TEST_METHODRC_ARGS] = true; //temporary
+ return p_arg;
+ }
+
+ void test_method_default_args(int p_arg1, int p_arg2, int p_arg3, int p_arg4, int p_arg5) {
+ test_valid[TEST_METHOD_DEFARGS] = p_arg1 == 1 && p_arg2 == 2 && p_arg3 == 3 && p_arg4 == 4 && p_arg5 == 5; //temporary
+ }
+
+ static void _bind_methods() {
+ ClassDB::bind_method(D_METHOD("test_method"), &MethodBindTester::test_method);
+ ClassDB::bind_method(D_METHOD("test_method_args"), &MethodBindTester::test_method_args);
+ ClassDB::bind_method(D_METHOD("test_methodc"), &MethodBindTester::test_methodc);
+ ClassDB::bind_method(D_METHOD("test_methodc_args"), &MethodBindTester::test_methodc_args);
+ ClassDB::bind_method(D_METHOD("test_methodr"), &MethodBindTester::test_methodr);
+ ClassDB::bind_method(D_METHOD("test_methodr_args"), &MethodBindTester::test_methodr_args);
+ ClassDB::bind_method(D_METHOD("test_methodrc"), &MethodBindTester::test_methodrc);
+ ClassDB::bind_method(D_METHOD("test_methodrc_args"), &MethodBindTester::test_methodrc_args);
+ ClassDB::bind_method(D_METHOD("test_method_default_args"), &MethodBindTester::test_method_default_args, DEFVAL(9) /* wrong on purpose */, DEFVAL(4), DEFVAL(5));
+ }
+
+ virtual void run_tests() {
+ for (int i = 0; i < TEST_MAX; i++) {
+ test_valid[i] = false;
+ }
+ //regular
+ test_num = Math::rand();
+ call("test_method");
+ test_num = Math::rand();
+ call("test_method_args", test_num);
+ test_num = Math::rand();
+ call("test_methodc");
+ test_num = Math::rand();
+ call("test_methodc_args", test_num);
+ //return
+ test_num = Math::rand();
+ test_valid[TEST_METHODR] = int(call("test_methodr")) == test_num && test_valid[TEST_METHODR];
+ test_num = Math::rand();
+ test_valid[TEST_METHODR_ARGS] = int(call("test_methodr_args", test_num)) == test_num && test_valid[TEST_METHODR_ARGS];
+ test_num = Math::rand();
+ test_valid[TEST_METHODRC] = int(call("test_methodrc")) == test_num && test_valid[TEST_METHODRC];
+ test_num = Math::rand();
+ test_valid[TEST_METHODRC_ARGS] = int(call("test_methodrc_args", test_num)) == test_num && test_valid[TEST_METHODRC_ARGS];
+
+ call("test_method_default_args", 1, 2, 3, 4);
+ }
+};
+
+TEST_CASE("[MethodBind] check all method binds") {
+ MethodBindTester *mbt = memnew(MethodBindTester);
+
+ print_line("testing method bind");
+ mbt->run_tests();
+
+ CHECK(mbt->test_valid[MethodBindTester::TEST_METHOD]);
+ CHECK(mbt->test_valid[MethodBindTester::TEST_METHOD_ARGS]);
+ CHECK(mbt->test_valid[MethodBindTester::TEST_METHODC]);
+ CHECK(mbt->test_valid[MethodBindTester::TEST_METHODC_ARGS]);
+ CHECK(mbt->test_valid[MethodBindTester::TEST_METHODR]);
+ CHECK(mbt->test_valid[MethodBindTester::TEST_METHODR_ARGS]);
+ CHECK(mbt->test_valid[MethodBindTester::TEST_METHODRC]);
+ CHECK(mbt->test_valid[MethodBindTester::TEST_METHODRC_ARGS]);
+ CHECK(mbt->test_valid[MethodBindTester::TEST_METHOD_DEFARGS]);
+
+ memdelete(mbt);
+}
+} // namespace TestMethodBind
+
+#endif // TEST_METHOD_BIND_H
diff --git a/tests/test_node_path.h b/tests/test_node_path.h
new file mode 100644
index 0000000000..e9e06186f5
--- /dev/null
+++ b/tests/test_node_path.h
@@ -0,0 +1,172 @@
+/*************************************************************************/
+/* test_node_path.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+#ifndef TEST_NODE_PATH_H
+#define TEST_NODE_PATH_H
+
+#include "core/string/node_path.h"
+
+#include "thirdparty/doctest/doctest.h"
+
+namespace TestNodePath {
+
+TEST_CASE("[NodePath] Relative path") {
+ const NodePath node_path_relative = NodePath("Path2D/PathFollow2D/Sprite2D:position:x");
+
+ CHECK_MESSAGE(
+ node_path_relative.get_as_property_path() == NodePath(":Path2D/PathFollow2D/Sprite2D:position:x"),
+ "The returned property path should match the expected value.");
+ CHECK_MESSAGE(
+ node_path_relative.get_concatenated_subnames() == "position:x",
+ "The returned concatenated subnames should match the expected value.");
+
+ CHECK_MESSAGE(
+ node_path_relative.get_name(0) == "Path2D",
+ "The returned name at index 0 should match the expected value.");
+ CHECK_MESSAGE(
+ node_path_relative.get_name(1) == "PathFollow2D",
+ "The returned name at index 1 should match the expected value.");
+ CHECK_MESSAGE(
+ node_path_relative.get_name(2) == "Sprite2D",
+ "The returned name at index 2 should match the expected value.");
+ ERR_PRINT_OFF;
+ CHECK_MESSAGE(
+ node_path_relative.get_name(3) == "",
+ "The returned name at invalid index 3 should match the expected value.");
+ CHECK_MESSAGE(
+ node_path_relative.get_name(-1) == "",
+ "The returned name at invalid index -1 should match the expected value.");
+ ERR_PRINT_ON;
+
+ CHECK_MESSAGE(
+ node_path_relative.get_name_count() == 3,
+ "The returned number of names should match the expected value.");
+
+ CHECK_MESSAGE(
+ node_path_relative.get_subname(0) == "position",
+ "The returned subname at index 0 should match the expected value.");
+ CHECK_MESSAGE(
+ node_path_relative.get_subname(1) == "x",
+ "The returned subname at index 1 should match the expected value.");
+ ERR_PRINT_OFF;
+ CHECK_MESSAGE(
+ node_path_relative.get_subname(2) == "",
+ "The returned subname at invalid index 2 should match the expected value.");
+ CHECK_MESSAGE(
+ node_path_relative.get_subname(-1) == "",
+ "The returned subname at invalid index -1 should match the expected value.");
+ ERR_PRINT_ON;
+
+ CHECK_MESSAGE(
+ node_path_relative.get_subname_count() == 2,
+ "The returned number of subnames should match the expected value.");
+
+ CHECK_MESSAGE(
+ !node_path_relative.is_absolute(),
+ "The node path should be considered relative.");
+
+ CHECK_MESSAGE(
+ !node_path_relative.is_empty(),
+ "The node path shouldn't be considered empty.");
+}
+
+TEST_CASE("[NodePath] Absolute path") {
+ const NodePath node_path_aboslute = NodePath("/root/Sprite2D");
+
+ CHECK_MESSAGE(
+ node_path_aboslute.get_as_property_path() == NodePath(":root/Sprite2D"),
+ "The returned property path should match the expected value.");
+ CHECK_MESSAGE(
+ node_path_aboslute.get_concatenated_subnames() == "",
+ "The returned concatenated subnames should match the expected value.");
+
+ CHECK_MESSAGE(
+ node_path_aboslute.get_name(0) == "root",
+ "The returned name at index 0 should match the expected value.");
+ CHECK_MESSAGE(
+ node_path_aboslute.get_name(1) == "Sprite2D",
+ "The returned name at index 1 should match the expected value.");
+ ERR_PRINT_OFF;
+ CHECK_MESSAGE(
+ node_path_aboslute.get_name(2) == "",
+ "The returned name at invalid index 2 should match the expected value.");
+ CHECK_MESSAGE(
+ node_path_aboslute.get_name(-1) == "",
+ "The returned name at invalid index -1 should match the expected value.");
+ ERR_PRINT_ON;
+
+ CHECK_MESSAGE(
+ node_path_aboslute.get_name_count() == 2,
+ "The returned number of names should match the expected value.");
+
+ CHECK_MESSAGE(
+ node_path_aboslute.get_subname_count() == 0,
+ "The returned number of subnames should match the expected value.");
+
+ CHECK_MESSAGE(
+ node_path_aboslute.is_absolute(),
+ "The node path should be considered absolute.");
+
+ CHECK_MESSAGE(
+ !node_path_aboslute.is_empty(),
+ "The node path shouldn't be considered empty.");
+}
+
+TEST_CASE("[NodePath] Empty path") {
+ const NodePath node_path_empty = NodePath();
+
+ CHECK_MESSAGE(
+ node_path_empty.get_as_property_path() == NodePath(),
+ "The returned property path should match the expected value.");
+ ERR_PRINT_OFF;
+ CHECK_MESSAGE(
+ node_path_empty.get_concatenated_subnames() == "",
+ "The returned concatenated subnames should match the expected value.");
+ ERR_PRINT_ON;
+
+ CHECK_MESSAGE(
+ node_path_empty.get_name_count() == 0,
+ "The returned number of names should match the expected value.");
+
+ CHECK_MESSAGE(
+ node_path_empty.get_subname_count() == 0,
+ "The returned number of subnames should match the expected value.");
+
+ CHECK_MESSAGE(
+ !node_path_empty.is_absolute(),
+ "The node path shouldn't be considered absolute.");
+
+ CHECK_MESSAGE(
+ node_path_empty.is_empty(),
+ "The node path should be considered empty.");
+}
+} // namespace TestNodePath
+
+#endif // TEST_NODE_PATH_H
diff --git a/tests/test_oa_hash_map.cpp b/tests/test_oa_hash_map.cpp
index 9182f66b61..b0bb01bc71 100644
--- a/tests/test_oa_hash_map.cpp
+++ b/tests/test_oa_hash_map.cpp
@@ -30,8 +30,8 @@
#include "test_oa_hash_map.h"
-#include "core/oa_hash_map.h"
#include "core/os/os.h"
+#include "core/templates/oa_hash_map.h"
namespace TestOAHashMap {
@@ -295,5 +295,4 @@ MainLoop *test() {
return nullptr;
}
-
} // namespace TestOAHashMap
diff --git a/tests/test_object.h b/tests/test_object.h
new file mode 100644
index 0000000000..6fef2576e7
--- /dev/null
+++ b/tests/test_object.h
@@ -0,0 +1,92 @@
+/*************************************************************************/
+/* test_object.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+#ifndef TEST_OBJECT_H
+#define TEST_OBJECT_H
+
+#include "core/object/object.h"
+
+#include "thirdparty/doctest/doctest.h"
+
+namespace TestObject {
+
+TEST_CASE("[Object] Core getters") {
+ Object object;
+
+ CHECK_MESSAGE(
+ object.is_class("Object"),
+ "is_class() should return the expected value.");
+ CHECK_MESSAGE(
+ object.get_class() == "Object",
+ "The returned class should match the expected value.");
+ CHECK_MESSAGE(
+ object.get_class_name() == "Object",
+ "The returned class name should match the expected value.");
+ CHECK_MESSAGE(
+ object.get_class_static() == "Object",
+ "The returned static class should match the expected value.");
+ CHECK_MESSAGE(
+ object.get_save_class() == "Object",
+ "The returned save class should match the expected value.");
+}
+
+TEST_CASE("[Object] Metadata") {
+ const String meta_path = "hello/world complex métadata\n\n\t\tpath";
+ Object object;
+
+ object.set_meta(meta_path, Color(0, 1, 0));
+ CHECK_MESSAGE(
+ Color(object.get_meta(meta_path)).is_equal_approx(Color(0, 1, 0)),
+ "The returned object metadata after setting should match the expected value.");
+
+ List<String> meta_list;
+ object.get_meta_list(&meta_list);
+ CHECK_MESSAGE(
+ meta_list.size() == 1,
+ "The metadata list should only contain 1 item after adding one metadata item.");
+
+ object.remove_meta(meta_path);
+ // Also try removing nonexistent metadata (it should do nothing, without printing an error message).
+ object.remove_meta("I don't exist");
+ ERR_PRINT_OFF;
+ CHECK_MESSAGE(
+ object.get_meta(meta_path) == Variant(),
+ "The returned object metadata after removing should match the expected value.");
+ ERR_PRINT_ON;
+
+ List<String> meta_list2;
+ object.get_meta_list(&meta_list2);
+ CHECK_MESSAGE(
+ meta_list2.size() == 0,
+ "The metadata list should contain 0 items after removing all metadata items.");
+}
+} // namespace TestObject
+
+#endif // TEST_OBJECT_H
diff --git a/tests/test_ordered_hash_map.cpp b/tests/test_ordered_hash_map.cpp
deleted file mode 100644
index d18a3784be..0000000000
--- a/tests/test_ordered_hash_map.cpp
+++ /dev/null
@@ -1,175 +0,0 @@
-/*************************************************************************/
-/* test_ordered_hash_map.cpp */
-/*************************************************************************/
-/* This file is part of: */
-/* GODOT ENGINE */
-/* https://godotengine.org */
-/*************************************************************************/
-/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
-/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
-/* */
-/* Permission is hereby granted, free of charge, to any person obtaining */
-/* a copy of this software and associated documentation files (the */
-/* "Software"), to deal in the Software without restriction, including */
-/* without limitation the rights to use, copy, modify, merge, publish, */
-/* distribute, sublicense, and/or sell copies of the Software, and to */
-/* permit persons to whom the Software is furnished to do so, subject to */
-/* the following conditions: */
-/* */
-/* The above copyright notice and this permission notice shall be */
-/* included in all copies or substantial portions of the Software. */
-/* */
-/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
-/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
-/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
-/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
-/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
-/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
-/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
-/*************************************************************************/
-
-#include "test_ordered_hash_map.h"
-
-#include "core/ordered_hash_map.h"
-#include "core/os/os.h"
-#include "core/pair.h"
-#include "core/vector.h"
-
-namespace TestOrderedHashMap {
-
-bool test_insert() {
- OrderedHashMap<int, int> map;
- OrderedHashMap<int, int>::Element e = map.insert(42, 84);
-
- return e && e.key() == 42 && e.get() == 84 && e.value() == 84 && map[42] == 84 && map.has(42) && map.find(42);
-}
-
-bool test_insert_overwrite() {
- OrderedHashMap<int, int> map;
- map.insert(42, 84);
- map.insert(42, 1234);
-
- return map[42] == 1234;
-}
-
-bool test_erase_via_element() {
- OrderedHashMap<int, int> map;
- OrderedHashMap<int, int>::Element e = map.insert(42, 84);
-
- map.erase(e);
- return !e && !map.has(42) && !map.find(42);
-}
-
-bool test_erase_via_key() {
- OrderedHashMap<int, int> map;
- map.insert(42, 84);
- map.erase(42);
- return !map.has(42) && !map.find(42);
-}
-
-bool test_size() {
- OrderedHashMap<int, int> map;
- map.insert(42, 84);
- map.insert(123, 84);
- map.insert(123, 84);
- map.insert(0, 84);
- map.insert(123485, 84);
-
- return map.size() == 4;
-}
-
-bool test_iteration() {
- OrderedHashMap<int, int> map;
- map.insert(42, 84);
- map.insert(123, 12385);
- map.insert(0, 12934);
- map.insert(123485, 1238888);
- map.insert(123, 111111);
-
- Vector<Pair<int, int>> expected;
- expected.push_back(Pair<int, int>(42, 84));
- expected.push_back(Pair<int, int>(123, 111111));
- expected.push_back(Pair<int, int>(0, 12934));
- expected.push_back(Pair<int, int>(123485, 1238888));
-
- int idx = 0;
- for (OrderedHashMap<int, int>::Element E = map.front(); E; E = E.next()) {
- if (expected[idx] != Pair<int, int>(E.key(), E.value())) {
- return false;
- }
- ++idx;
- }
- return true;
-}
-
-bool test_const_iteration(const OrderedHashMap<int, int> &map) {
- Vector<Pair<int, int>> expected;
- expected.push_back(Pair<int, int>(42, 84));
- expected.push_back(Pair<int, int>(123, 111111));
- expected.push_back(Pair<int, int>(0, 12934));
- expected.push_back(Pair<int, int>(123485, 1238888));
-
- int idx = 0;
- for (OrderedHashMap<int, int>::ConstElement E = map.front(); E; E = E.next()) {
- if (expected[idx] != Pair<int, int>(E.key(), E.value())) {
- return false;
- }
- ++idx;
- }
- return true;
-}
-
-bool test_const_iteration() {
- OrderedHashMap<int, int> map;
- map.insert(42, 84);
- map.insert(123, 12385);
- map.insert(0, 12934);
- map.insert(123485, 1238888);
- map.insert(123, 111111);
-
- return test_const_iteration(map);
-}
-
-typedef bool (*TestFunc)();
-
-TestFunc test_funcs[] = {
-
- test_insert,
- test_insert_overwrite,
- test_erase_via_element,
- test_erase_via_key,
- test_size,
- test_iteration,
- test_const_iteration,
- nullptr
-
-};
-
-MainLoop *test() {
- int count = 0;
- int passed = 0;
-
- while (true) {
- if (!test_funcs[count]) {
- break;
- }
- bool pass = test_funcs[count]();
- if (pass) {
- passed++;
- }
- OS::get_singleton()->print("\t%s\n", pass ? "PASS" : "FAILED");
-
- count++;
- }
-
- OS::get_singleton()->print("\n\n\n");
- OS::get_singleton()->print("*************\n");
- OS::get_singleton()->print("***TOTALS!***\n");
- OS::get_singleton()->print("*************\n");
-
- OS::get_singleton()->print("Passed %i of %i tests\n", passed, count);
-
- return nullptr;
-}
-
-} // namespace TestOrderedHashMap
diff --git a/tests/test_ordered_hash_map.h b/tests/test_ordered_hash_map.h
index f251da0ba2..ef26d2531b 100644
--- a/tests/test_ordered_hash_map.h
+++ b/tests/test_ordered_hash_map.h
@@ -31,11 +31,108 @@
#ifndef TEST_ORDERED_HASH_MAP_H
#define TEST_ORDERED_HASH_MAP_H
-#include "core/os/main_loop.h"
+#include "core/os/os.h"
+#include "core/templates/ordered_hash_map.h"
+#include "core/templates/pair.h"
+#include "core/templates/vector.h"
+
+#include "tests/test_macros.h"
namespace TestOrderedHashMap {
-MainLoop *test();
+TEST_CASE("[OrderedHashMap] Insert element") {
+ OrderedHashMap<int, int> map;
+ OrderedHashMap<int, int>::Element e = map.insert(42, 84);
+
+ CHECK(e);
+ CHECK(e.key() == 42);
+ CHECK(e.get() == 84);
+ CHECK(e.value() == 84);
+ CHECK(map[42] == 84);
+ CHECK(map.has(42));
+ CHECK(map.find(42));
+}
+
+TEST_CASE("[OrderedHashMap] Overwrite element") {
+ OrderedHashMap<int, int> map;
+ map.insert(42, 84);
+ map.insert(42, 1234);
+
+ CHECK(map[42] == 1234);
+}
+
+TEST_CASE("[OrderedHashMap] Erase via element") {
+ OrderedHashMap<int, int> map;
+ OrderedHashMap<int, int>::Element e = map.insert(42, 84);
+
+ map.erase(e);
+ CHECK(!e);
+ CHECK(!map.has(42));
+ CHECK(!map.find(42));
+}
+
+TEST_CASE("[OrderedHashMap] Erase via key") {
+ OrderedHashMap<int, int> map;
+ map.insert(42, 84);
+ map.erase(42);
+ CHECK(!map.has(42));
+ CHECK(!map.find(42));
+}
+
+TEST_CASE("[OrderedHashMap] Size") {
+ OrderedHashMap<int, int> map;
+ map.insert(42, 84);
+ map.insert(123, 84);
+ map.insert(123, 84);
+ map.insert(0, 84);
+ map.insert(123485, 84);
+
+ CHECK(map.size() == 4);
+}
+
+TEST_CASE("[OrderedHashMap] Iteration") {
+ OrderedHashMap<int, int> map;
+ map.insert(42, 84);
+ map.insert(123, 12385);
+ map.insert(0, 12934);
+ map.insert(123485, 1238888);
+ map.insert(123, 111111);
+
+ Vector<Pair<int, int>> expected;
+ expected.push_back(Pair<int, int>(42, 84));
+ expected.push_back(Pair<int, int>(123, 111111));
+ expected.push_back(Pair<int, int>(0, 12934));
+ expected.push_back(Pair<int, int>(123485, 1238888));
+
+ int idx = 0;
+ for (OrderedHashMap<int, int>::Element E = map.front(); E; E = E.next()) {
+ CHECK(expected[idx] == Pair<int, int>(E.key(), E.value()));
+ ++idx;
+ }
+}
+
+TEST_CASE("[OrderedHashMap] Const iteration") {
+ OrderedHashMap<int, int> map;
+ map.insert(42, 84);
+ map.insert(123, 12385);
+ map.insert(0, 12934);
+ map.insert(123485, 1238888);
+ map.insert(123, 111111);
+
+ const OrderedHashMap<int, int> const_map = map;
+
+ Vector<Pair<int, int>> expected;
+ expected.push_back(Pair<int, int>(42, 84));
+ expected.push_back(Pair<int, int>(123, 111111));
+ expected.push_back(Pair<int, int>(0, 12934));
+ expected.push_back(Pair<int, int>(123485, 1238888));
+
+ int idx = 0;
+ for (OrderedHashMap<int, int>::ConstElement E = const_map.front(); E; E = E.next()) {
+ CHECK(expected[idx] == Pair<int, int>(E.key(), E.value()));
+ ++idx;
+ }
}
+} // namespace TestOrderedHashMap
#endif // TEST_ORDERED_HASH_MAP_H
diff --git a/tests/test_paged_array.h b/tests/test_paged_array.h
new file mode 100644
index 0000000000..6b61160229
--- /dev/null
+++ b/tests/test_paged_array.h
@@ -0,0 +1,153 @@
+/*************************************************************************/
+/* test_paged_array.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+#ifndef TEST_PAGED_ARRAY_H
+#define TEST_PAGED_ARRAY_H
+
+#include "core/templates/paged_array.h"
+
+#include "thirdparty/doctest/doctest.h"
+
+namespace TestPagedArray {
+
+// PagedArray
+
+TEST_CASE("[PagedArray] Simple fill and refill") {
+ PagedArrayPool<uint32_t> pool;
+ PagedArray<uint32_t> array;
+ array.set_page_pool(&pool);
+
+ for (uint32_t i = 0; i < 123456; i++) {
+ array.push_back(i);
+ }
+ CHECK_MESSAGE(
+ array.size() == 123456,
+ "PagedArray should have 123456 elements.");
+
+ bool all_match = true;
+ for (uint32_t i = 0; i < 123456; i++) {
+ if (array[i] != i) {
+ all_match = false;
+ break;
+ }
+ }
+
+ CHECK_MESSAGE(
+ all_match,
+ "PagedArray elements should match from 0 to 123455.");
+
+ array.clear();
+
+ CHECK_MESSAGE(
+ array.size() == 0,
+ "PagedArray elements should be 0 after clear.");
+
+ for (uint32_t i = 0; i < 999; i++) {
+ array.push_back(i);
+ }
+ CHECK_MESSAGE(
+ array.size() == 999,
+ "PagedArray should have 999 elements.");
+
+ all_match = true;
+ for (uint32_t i = 0; i < 999; i++) {
+ if (array[i] != i) {
+ all_match = false;
+ }
+ }
+
+ CHECK_MESSAGE(
+ all_match,
+ "PagedArray elements should match from 0 to 998.");
+
+ array.reset(); //reset so pagepool can be reset
+ pool.reset();
+}
+
+TEST_CASE("[PagedArray] Shared pool fill, including merging") {
+ PagedArrayPool<uint32_t> pool;
+ PagedArray<uint32_t> array1;
+ PagedArray<uint32_t> array2;
+ array1.set_page_pool(&pool);
+ array2.set_page_pool(&pool);
+
+ for (uint32_t i = 0; i < 123456; i++) {
+ array1.push_back(i);
+ }
+ CHECK_MESSAGE(
+ array1.size() == 123456,
+ "PagedArray #1 should have 123456 elements.");
+
+ bool all_match = true;
+ for (uint32_t i = 0; i < 123456; i++) {
+ if (array1[i] != i) {
+ all_match = false;
+ }
+ }
+
+ CHECK_MESSAGE(
+ all_match,
+ "PagedArray #1 elements should match from 0 to 123455.");
+
+ for (uint32_t i = 0; i < 999; i++) {
+ array2.push_back(i);
+ }
+ CHECK_MESSAGE(
+ array2.size() == 999,
+ "PagedArray #2 should have 999 elements.");
+
+ all_match = true;
+ for (uint32_t i = 0; i < 999; i++) {
+ if (array2[i] != i) {
+ all_match = false;
+ }
+ }
+
+ CHECK_MESSAGE(
+ all_match,
+ "PagedArray #2 elements should match from 0 to 998.");
+
+ array1.merge_unordered(array2);
+
+ CHECK_MESSAGE(
+ array1.size() == 123456 + 999,
+ "PagedArray #1 should now be 123456 + 999 elements.");
+
+ CHECK_MESSAGE(
+ array2.size() == 0,
+ "PagedArray #2 should now be 0 elements.");
+
+ array1.reset(); //reset so pagepool can be reset
+ array2.reset(); //reset so pagepool can be reset
+ pool.reset();
+}
+} // namespace TestPagedArray
+
+#endif // TEST_PAGED_ARRAY_H
diff --git a/tests/test_pck_packer.h b/tests/test_pck_packer.h
new file mode 100644
index 0000000000..e086d65105
--- /dev/null
+++ b/tests/test_pck_packer.h
@@ -0,0 +1,114 @@
+/*************************************************************************/
+/* test_pck_packer.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+#ifndef TEST_PCK_PACKER_H
+#define TEST_PCK_PACKER_H
+
+#include "core/io/file_access_pack.h"
+#include "core/io/pck_packer.h"
+#include "core/os/os.h"
+
+#include "thirdparty/doctest/doctest.h"
+
+namespace TestPCKPacker {
+
+// Dummy 64-character encryption key (since it's required).
+constexpr const char *ENCRYPTION_KEY = "0000000000000000000000000000000000000000000000000000000000000000";
+
+TEST_CASE("[PCKPacker] Pack an empty PCK file") {
+ PCKPacker pck_packer;
+ const String output_pck_path = OS::get_singleton()->get_cache_path().plus_file("output_empty.pck");
+ CHECK_MESSAGE(
+ pck_packer.pck_start(
+ output_pck_path,
+ 32,
+ ENCRYPTION_KEY) == OK,
+ "Starting a PCK file should return an OK error code.");
+
+ CHECK_MESSAGE(
+ pck_packer.flush() == OK,
+ "Flushing the PCK should return an OK error code.");
+
+ Error err;
+ FileAccessRef f = FileAccess::open(output_pck_path, FileAccess::READ, &err);
+ CHECK_MESSAGE(
+ err == OK,
+ "The generated empty PCK file should be opened successfully.");
+ CHECK_MESSAGE(
+ f->get_len() >= 100,
+ "The generated empty PCK file shouldn't be too small (it should have the PCK header).");
+ CHECK_MESSAGE(
+ f->get_len() <= 500,
+ "The generated empty PCK file shouldn't be too large.");
+}
+
+TEST_CASE("[PCKPacker] Pack a PCK file with some files and directories") {
+ PCKPacker pck_packer;
+ const String output_pck_path = OS::get_singleton()->get_cache_path().plus_file("output_with_files.pck");
+ CHECK_MESSAGE(
+ pck_packer.pck_start(
+ output_pck_path,
+ 32,
+ ENCRYPTION_KEY) == OK,
+ "Starting a PCK file should return an OK error code.");
+
+ const String base_dir = OS::get_singleton()->get_executable_path().get_base_dir();
+
+ CHECK_MESSAGE(
+ pck_packer.add_file("version.py", base_dir.plus_file("../version.py"), "version.py") == OK,
+ "Adding a file to the PCK should return an OK error code.");
+ CHECK_MESSAGE(
+ pck_packer.add_file("some/directories with spaces/to/create/icon.png", base_dir.plus_file("../icon.png")) == OK,
+ "Adding a file to a new subdirectory in the PCK should return an OK error code.");
+ CHECK_MESSAGE(
+ pck_packer.add_file("some/directories with spaces/to/create/icon.svg", base_dir.plus_file("../icon.svg")) == OK,
+ "Adding a file to an existing subdirectory in the PCK should return an OK error code.");
+ CHECK_MESSAGE(
+ pck_packer.add_file("some/directories with spaces/to/create/icon.png", base_dir.plus_file("../logo.png")) == OK,
+ "Overriding a non-flushed file to an existing subdirectory in the PCK should return an OK error code.");
+ CHECK_MESSAGE(
+ pck_packer.flush() == OK,
+ "Flushing the PCK should return an OK error code.");
+
+ Error err;
+ FileAccessRef f = FileAccess::open(output_pck_path, FileAccess::READ, &err);
+ CHECK_MESSAGE(
+ err == OK,
+ "The generated non-empty PCK file should be opened successfully.");
+ CHECK_MESSAGE(
+ f->get_len() >= 25000,
+ "The generated non-empty PCK file should be large enough to actually hold the contents specified above.");
+ CHECK_MESSAGE(
+ f->get_len() <= 35000,
+ "The generated non-empty PCK file shouldn't be too large.");
+}
+} // namespace TestPCKPacker
+
+#endif // TEST_PCK_PACKER_H
diff --git a/tests/test_physics_2d.cpp b/tests/test_physics_2d.cpp
index c82ae920bc..d40df52f1b 100644
--- a/tests/test_physics_2d.cpp
+++ b/tests/test_physics_2d.cpp
@@ -30,10 +30,10 @@
#include "test_physics_2d.h"
-#include "core/map.h"
#include "core/os/main_loop.h"
#include "core/os/os.h"
-#include "core/print_string.h"
+#include "core/string/print_string.h"
+#include "core/templates/map.h"
#include "scene/resources/texture.h"
#include "servers/display_server.h"
#include "servers/physics_server_2d.h"
@@ -403,5 +403,4 @@ namespace TestPhysics2D {
MainLoop *test() {
return memnew(TestPhysics2DMainLoop);
}
-
} // namespace TestPhysics2D
diff --git a/tests/test_physics_3d.cpp b/tests/test_physics_3d.cpp
index 72de2041e4..5f84b2eb50 100644
--- a/tests/test_physics_3d.cpp
+++ b/tests/test_physics_3d.cpp
@@ -30,12 +30,12 @@
#include "test_physics_3d.h"
-#include "core/map.h"
#include "core/math/math_funcs.h"
#include "core/math/quick_hull.h"
#include "core/os/main_loop.h"
#include "core/os/os.h"
-#include "core/print_string.h"
+#include "core/string/print_string.h"
+#include "core/templates/map.h"
#include "servers/display_server.h"
#include "servers/physics_server_3d.h"
#include "servers/rendering_server.h"
@@ -409,5 +409,4 @@ namespace TestPhysics3D {
MainLoop *test() {
return memnew(TestPhysics3DMainLoop);
}
-
} // namespace TestPhysics3D
diff --git a/tests/test_random_number_generator.h b/tests/test_random_number_generator.h
new file mode 100644
index 0000000000..999e6d4862
--- /dev/null
+++ b/tests/test_random_number_generator.h
@@ -0,0 +1,275 @@
+/*************************************************************************/
+/* test_random_number_generator.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+#ifndef TEST_RANDOM_NUMBER_GENERATOR_H
+#define TEST_RANDOM_NUMBER_GENERATOR_H
+
+#include "core/math/random_number_generator.h"
+#include "tests/test_macros.h"
+
+namespace TestRandomNumberGenerator {
+
+TEST_CASE("[RandomNumberGenerator] Float") {
+ Ref<RandomNumberGenerator> rng = memnew(RandomNumberGenerator);
+ rng->set_seed(0);
+
+ INFO("Should give float between 0.0 and 1.0.");
+ for (int i = 0; i < 1000; i++) {
+ real_t n = rng->randf();
+ CHECK(n >= 0.0);
+ CHECK(n <= 1.0);
+ }
+}
+
+TEST_CASE("[RandomNumberGenerator] Integer range via modulo") {
+ Ref<RandomNumberGenerator> rng = memnew(RandomNumberGenerator);
+ rng->set_seed(0);
+
+ INFO("Should give integer between 0 and 100.");
+ for (int i = 0; i < 1000; i++) {
+ uint32_t n = rng->randi() % 100;
+ CHECK(n >= 0);
+ CHECK(n <= 100);
+ }
+}
+
+TEST_CASE_MAY_FAIL("[RandomNumberGenerator] Integer 32 bit") {
+ Ref<RandomNumberGenerator> rng = memnew(RandomNumberGenerator);
+ rng->set_seed(0); // Change the seed if this fails.
+
+ bool higher = false;
+ int i;
+ for (i = 0; i < 1000; i++) {
+ uint32_t n = rng->randi();
+ if (n > 0x0fff'ffff) {
+ higher = true;
+ break;
+ }
+ }
+ INFO("Current seed: " << rng->get_seed());
+ INFO("Current iteration: " << i);
+ CHECK_MESSAGE(higher, "Given current seed, this should give an integer higher than 0x0fff'ffff at least once.");
+}
+
+TEST_CASE("[RandomNumberGenerator] Float and integer range") {
+ Ref<RandomNumberGenerator> rng = memnew(RandomNumberGenerator);
+ rng->set_seed(0);
+ uint64_t initial_state = rng->get_state();
+ uint32_t initial_seed = rng->get_seed();
+
+ INFO("Should give float between -100.0 and 100.0, base test.");
+ for (int i = 0; i < 1000; i++) {
+ real_t n0 = rng->randf_range(-100.0, 100.0);
+ CHECK(n0 >= -100);
+ CHECK(n0 <= 100);
+ }
+
+ rng->randomize();
+ INFO("Should give float between -75.0 and 75.0.");
+ INFO("Shouldn't be affected by randomize.");
+ for (int i = 0; i < 1000; i++) {
+ real_t n1 = rng->randf_range(-75.0, 75.0);
+ CHECK(n1 >= -75);
+ CHECK(n1 <= 75);
+ }
+
+ rng->set_state(initial_state);
+ INFO("Should give integer between -50 and 50.");
+ INFO("Shouldn't be affected by set_state.");
+ for (int i = 0; i < 1000; i++) {
+ real_t n2 = rng->randi_range(-50, 50);
+ CHECK(n2 >= -50);
+ CHECK(n2 <= 50);
+ }
+
+ rng->set_seed(initial_seed);
+ INFO("Should give integer between -25 and 25.");
+ INFO("Shouldn't be affected by set_seed.");
+ for (int i = 0; i < 1000; i++) {
+ int32_t n3 = rng->randi_range(-25, 25);
+ CHECK(n3 >= -25);
+ CHECK(n3 <= 25);
+ }
+
+ rng->randf();
+ rng->randf();
+
+ INFO("Should give float between -10.0 and 10.0.");
+ INFO("Shouldn't be affected after generating new numbers.");
+ for (int i = 0; i < 1000; i++) {
+ real_t n4 = rng->randf_range(-10.0, 10.0);
+ CHECK(n4 >= -10);
+ CHECK(n4 <= 10);
+ }
+
+ rng->randi();
+ rng->randi();
+
+ INFO("Should give integer between -5 and 5.");
+ INFO("Shouldn't be affected after generating new numbers.");
+ for (int i = 0; i < 1000; i++) {
+ real_t n5 = rng->randf_range(-5, 5);
+ CHECK(n5 >= -5);
+ CHECK(n5 <= 5);
+ }
+}
+
+TEST_CASE_MAY_FAIL("[RandomNumberGenerator] Normal distribution") {
+ Ref<RandomNumberGenerator> rng = memnew(RandomNumberGenerator);
+ rng->set_seed(1); // Change the seed if this fails.
+ INFO("Should give a number between -5 to 5 (5 std deviations away; above 99.7% chance it will be in this range).");
+ INFO("Standard randfn function call.");
+ for (int i = 0; i < 100; i++) {
+ real_t n = rng->randfn();
+ CHECK(n >= -5);
+ CHECK(n <= 5);
+ }
+
+ INFO("Should give number between -5 to 5 after multiple randi/randf calls.");
+ INFO("5 std deviations away; above 99.7% chance it will be in this range.");
+ rng->randf();
+ rng->randi();
+ for (int i = 0; i < 100; i++) {
+ real_t n = rng->randfn();
+ CHECK(n >= -5);
+ CHECK(n <= 5);
+ }
+
+ INFO("Checks if user defined mean and deviation work properly.");
+ INFO("5 std deviations away; above 99.7% chance it will be in this range.");
+ for (int i = 0; i < 100; i++) {
+ real_t n = rng->randfn(5, 10);
+ CHECK(n >= -45);
+ CHECK(n <= 55);
+ }
+
+ INFO("Checks if randfn works with changed seeds.");
+ INFO("5 std deviations away; above 99.7% chance it will be in this range.");
+ rng->randomize();
+ for (int i = 0; i < 100; i++) {
+ real_t n = rng->randfn(3, 3);
+ CHECK(n >= -12);
+ CHECK(n <= 18);
+ }
+}
+
+TEST_CASE("[RandomNumberGenerator] Zero for first number immediately after seeding") {
+ Ref<RandomNumberGenerator> rng = memnew(RandomNumberGenerator);
+ rng->set_seed(0);
+ uint32_t n1 = rng->randi();
+ uint32_t n2 = rng->randi();
+ INFO("Initial random values: " << n1 << " " << n2);
+ CHECK(n1 != 0);
+
+ rng->set_seed(1);
+ uint32_t n3 = rng->randi();
+ uint32_t n4 = rng->randi();
+ INFO("Values after changing the seed: " << n3 << " " << n4);
+ CHECK(n3 != 0);
+}
+
+TEST_CASE("[RandomNumberGenerator] Restore state") {
+ Ref<RandomNumberGenerator> rng = memnew(RandomNumberGenerator);
+ rng->randomize();
+ uint64_t last_seed = rng->get_seed();
+ INFO("Current seed: " << last_seed);
+
+ rng->randi();
+ rng->randi();
+
+ CHECK_MESSAGE(rng->get_seed() == last_seed,
+ "The seed should remain the same after generating some numbers");
+
+ uint64_t saved_state = rng->get_state();
+ INFO("Current state: " << saved_state);
+
+ real_t f1_before = rng->randf();
+ real_t f2_before = rng->randf();
+ INFO("This seed produces: " << f1_before << " " << f2_before);
+
+ // Restore now.
+ rng->set_state(saved_state);
+
+ real_t f1_after = rng->randf();
+ real_t f2_after = rng->randf();
+ INFO("Resetting the state produces: " << f1_after << " " << f2_after);
+
+ String msg = "Should restore the sequence of numbers after resetting the state";
+ CHECK_MESSAGE(f1_before == f1_after, msg);
+ CHECK_MESSAGE(f2_before == f2_after, msg);
+}
+
+TEST_CASE("[RandomNumberGenerator] Restore from seed") {
+ Ref<RandomNumberGenerator> rng = memnew(RandomNumberGenerator);
+ rng->set_seed(0);
+ INFO("Current seed: " << rng->get_seed());
+ uint32_t s0_1_before = rng->randi();
+ uint32_t s0_2_before = rng->randi();
+ INFO("This seed produces: " << s0_1_before << " " << s0_2_before);
+
+ rng->set_seed(9000);
+ INFO("Current seed: " << rng->get_seed());
+ uint32_t s9000_1 = rng->randi();
+ uint32_t s9000_2 = rng->randi();
+ INFO("This seed produces: " << s9000_1 << " " << s9000_2);
+
+ rng->set_seed(0);
+ INFO("Current seed: " << rng->get_seed());
+ uint32_t s0_1_after = rng->randi();
+ uint32_t s0_2_after = rng->randi();
+ INFO("This seed produces: " << s0_1_after << " " << s0_2_after);
+
+ String msg = "Should restore the sequence of numbers after resetting the seed";
+ CHECK_MESSAGE(s0_1_before == s0_1_after, msg);
+ CHECK_MESSAGE(s0_2_before == s0_2_after, msg);
+}
+
+TEST_CASE_MAY_FAIL("[RandomNumberGenerator] randi_range bias check") {
+ int zeros = 0;
+ int ones = 0;
+ Ref<RandomNumberGenerator> rng = memnew(RandomNumberGenerator);
+ for (int i = 0; i < 10000; i++) {
+ int val = rng->randi_range(0, 1);
+ val == 0 ? zeros++ : ones++;
+ }
+ CHECK_MESSAGE(abs(zeros * 1.0 / ones - 1.0) < 0.1, "The ratio of zeros to ones should be nearly 1");
+
+ int vals[10] = { 0 };
+ for (int i = 0; i < 1000000; i++) {
+ vals[rng->randi_range(0, 9)]++;
+ }
+
+ for (int i = 0; i < 10; i++) {
+ CHECK_MESSAGE(abs(vals[i] / 1000000.0 - 0.1) < 0.01, "Each element should appear roughly 10% of the time");
+ }
+}
+} // namespace TestRandomNumberGenerator
+
+#endif // TEST_RANDOM_NUMBER_GENERATOR_H
diff --git a/tests/test_rect2.h b/tests/test_rect2.h
new file mode 100644
index 0000000000..b6edc9ce81
--- /dev/null
+++ b/tests/test_rect2.h
@@ -0,0 +1,467 @@
+/*************************************************************************/
+/* test_rect2.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+#ifndef TEST_RECT2_H
+#define TEST_RECT2_H
+
+#include "core/math/rect2.h"
+
+#include "thirdparty/doctest/doctest.h"
+
+namespace TestRect2 {
+// We also test Rect2i here, for consistency with the source code where Rect2
+// and Rect2i are defined in the same file.
+
+// Rect2
+
+TEST_CASE("[Rect2] Constructor methods") {
+ const Rect2 rect = Rect2(0, 100, 1280, 720);
+ const Rect2 rect_vector = Rect2(Vector2(0, 100), Vector2(1280, 720));
+ const Rect2 rect_copy_rect = Rect2(rect);
+ const Rect2 rect_copy_recti = Rect2(Rect2i(0, 100, 1280, 720));
+
+ CHECK_MESSAGE(
+ rect == rect_vector,
+ "Rect2s created with the same dimensions but by different methods should be equal.");
+ CHECK_MESSAGE(
+ rect == rect_copy_rect,
+ "Rect2s created with the same dimensions but by different methods should be equal.");
+ CHECK_MESSAGE(
+ rect == rect_copy_recti,
+ "Rect2s created with the same dimensions but by different methods should be equal.");
+}
+
+TEST_CASE("[Rect2] String conversion") {
+ // Note: This also depends on the Vector2 string representation.
+ CHECK_MESSAGE(
+ String(Rect2(0, 100, 1280, 720)) == "0, 100, 1280, 720",
+ "The string representation should match the expected value.");
+}
+
+TEST_CASE("[Rect2] Basic getters") {
+ const Rect2 rect = Rect2(0, 100, 1280, 720);
+ CHECK_MESSAGE(
+ rect.get_position().is_equal_approx(Vector2(0, 100)),
+ "get_position() should return the expected value.");
+ CHECK_MESSAGE(
+ rect.get_size().is_equal_approx(Vector2(1280, 720)),
+ "get_size() should return the expected value.");
+ CHECK_MESSAGE(
+ rect.get_end().is_equal_approx(Vector2(1280, 820)),
+ "get_end() should return the expected value.");
+}
+
+TEST_CASE("[Rect2] Basic setters") {
+ Rect2 rect = Rect2(0, 100, 1280, 720);
+ rect.set_end(Vector2(4000, 4000));
+ CHECK_MESSAGE(
+ rect.is_equal_approx(Rect2(0, 100, 4000, 3900)),
+ "set_end() should result in the expected Rect2.");
+
+ rect = Rect2(0, 100, 1280, 720);
+ rect.set_position(Vector2(4000, 4000));
+ CHECK_MESSAGE(
+ rect.is_equal_approx(Rect2(4000, 4000, 1280, 720)),
+ "set_position() should result in the expected Rect2.");
+
+ rect = Rect2(0, 100, 1280, 720);
+ rect.set_size(Vector2(4000, 4000));
+ CHECK_MESSAGE(
+ rect.is_equal_approx(Rect2(0, 100, 4000, 4000)),
+ "set_size() should result in the expected Rect2.");
+}
+
+TEST_CASE("[Rect2] Area getters") {
+ CHECK_MESSAGE(
+ Math::is_equal_approx(Rect2(0, 100, 1280, 720).get_area(), 921'600),
+ "get_area() should return the expected value.");
+ CHECK_MESSAGE(
+ Math::is_equal_approx(Rect2(0, 100, -1280, -720).get_area(), 921'600),
+ "get_area() should return the expected value.");
+ CHECK_MESSAGE(
+ Math::is_equal_approx(Rect2(0, 100, 1280, -720).get_area(), -921'600),
+ "get_area() should return the expected value.");
+ CHECK_MESSAGE(
+ Math::is_equal_approx(Rect2(0, 100, -1280, 720).get_area(), -921'600),
+ "get_area() should return the expected value.");
+ CHECK_MESSAGE(
+ Math::is_zero_approx(Rect2(0, 100, 0, 720).get_area()),
+ "get_area() should return the expected value.");
+
+ CHECK_MESSAGE(
+ !Rect2(0, 100, 1280, 720).has_no_area(),
+ "has_no_area() should return the expected value on Rect2 with an area.");
+ CHECK_MESSAGE(
+ Rect2(0, 100, 0, 500).has_no_area(),
+ "has_no_area() should return the expected value on Rect2 with no area.");
+ CHECK_MESSAGE(
+ Rect2(0, 100, 500, 0).has_no_area(),
+ "has_no_area() should return the expected value on Rect2 with no area.");
+ CHECK_MESSAGE(
+ Rect2(0, 100, 0, 0).has_no_area(),
+ "has_no_area() should return the expected value on Rect2 with no area.");
+}
+
+TEST_CASE("[Rect2] Absolute coordinates") {
+ CHECK_MESSAGE(
+ Rect2(0, 100, 1280, 720).abs().is_equal_approx(Rect2(0, 100, 1280, 720)),
+ "abs() should return the expected Rect2.");
+ CHECK_MESSAGE(
+ Rect2(0, -100, 1280, 720).abs().is_equal_approx(Rect2(0, -100, 1280, 720)),
+ "abs() should return the expected Rect2.");
+ CHECK_MESSAGE(
+ Rect2(0, -100, -1280, -720).abs().is_equal_approx(Rect2(-1280, -820, 1280, 720)),
+ "abs() should return the expected Rect2.");
+ CHECK_MESSAGE(
+ Rect2(0, 100, -1280, 720).abs().is_equal_approx(Rect2(-1280, 100, 1280, 720)),
+ "abs() should return the expected Rect2.");
+}
+
+TEST_CASE("[Rect2] Intersecton") {
+ CHECK_MESSAGE(
+ Rect2(0, 100, 1280, 720).intersection(Rect2(0, 300, 100, 100)).is_equal_approx(Rect2(0, 300, 100, 100)),
+ "intersection() with fully enclosed Rect2 should return the expected result.");
+ // The resulting Rect2 is 100 pixels high because the first Rect2 is vertically offset by 100 pixels.
+ CHECK_MESSAGE(
+ Rect2(0, 100, 1280, 720).intersection(Rect2(1200, 700, 100, 100)).is_equal_approx(Rect2(1200, 700, 80, 100)),
+ "intersection() with partially enclosed Rect2 should return the expected result.");
+ CHECK_MESSAGE(
+ Rect2(0, 100, 1280, 720).intersection(Rect2(-4000, -4000, 100, 100)).is_equal_approx(Rect2()),
+ "intersection() with non-enclosed Rect2 should return the expected result.");
+}
+
+TEST_CASE("[Rect2] Enclosing") {
+ CHECK_MESSAGE(
+ Rect2(0, 100, 1280, 720).encloses(Rect2(0, 300, 100, 100)),
+ "encloses() with fully contained Rect2 should return the expected result.");
+ CHECK_MESSAGE(
+ !Rect2(0, 100, 1280, 720).encloses(Rect2(1200, 700, 100, 100)),
+ "encloses() with partially contained Rect2 should return the expected result.");
+ CHECK_MESSAGE(
+ !Rect2(0, 100, 1280, 720).encloses(Rect2(-4000, -4000, 100, 100)),
+ "encloses() with non-contained Rect2 should return the expected result.");
+}
+
+TEST_CASE("[Rect2] Expanding") {
+ CHECK_MESSAGE(
+ Rect2(0, 100, 1280, 720).expand(Vector2(500, 600)).is_equal_approx(Rect2(0, 100, 1280, 720)),
+ "expand() with contained Vector2 should return the expected result.");
+ CHECK_MESSAGE(
+ Rect2(0, 100, 1280, 720).expand(Vector2(0, 0)).is_equal_approx(Rect2(0, 0, 1280, 820)),
+ "expand() with non-contained Vector2 should return the expected result.");
+}
+
+TEST_CASE("[Rect2] Growing") {
+ CHECK_MESSAGE(
+ Rect2(0, 100, 1280, 720).grow(100).is_equal_approx(Rect2(-100, 0, 1480, 920)),
+ "grow() with positive value should return the expected Rect2.");
+ CHECK_MESSAGE(
+ Rect2(0, 100, 1280, 720).grow(-100).is_equal_approx(Rect2(100, 200, 1080, 520)),
+ "grow() with negative value should return the expected Rect2.");
+ CHECK_MESSAGE(
+ Rect2(0, 100, 1280, 720).grow(-4000).is_equal_approx(Rect2(4000, 4100, -6720, -7280)),
+ "grow() with large negative value should return the expected Rect2.");
+
+ CHECK_MESSAGE(
+ Rect2(0, 100, 1280, 720).grow_individual(100, 200, 300, 400).is_equal_approx(Rect2(-100, -100, 1680, 1320)),
+ "grow_individual() with positive values should return the expected Rect2.");
+ CHECK_MESSAGE(
+ Rect2(0, 100, 1280, 720).grow_individual(-100, 200, 300, -400).is_equal_approx(Rect2(100, -100, 1480, 520)),
+ "grow_individual() with positive and negative values should return the expected Rect2.");
+
+ CHECK_MESSAGE(
+ Rect2(0, 100, 1280, 720).grow_margin(SIDE_TOP, 500).is_equal_approx(Rect2(0, -400, 1280, 1220)),
+ "grow_margin() with positive value should return the expected Rect2.");
+ CHECK_MESSAGE(
+ Rect2(0, 100, 1280, 720).grow_margin(SIDE_TOP, -500).is_equal_approx(Rect2(0, 600, 1280, 220)),
+ "grow_margin() with negative value should return the expected Rect2.");
+}
+
+TEST_CASE("[Rect2] Has point") {
+ CHECK_MESSAGE(
+ Rect2(0, 100, 1280, 720).has_point(Vector2(500, 600)),
+ "has_point() with contained Vector2 should return the expected result.");
+ CHECK_MESSAGE(
+ !Rect2(0, 100, 1280, 720).has_point(Vector2(0, 0)),
+ "has_point() with non-contained Vector2 should return the expected result.");
+
+ CHECK_MESSAGE(
+ Rect2(0, 100, 1280, 720).has_point(Vector2(0, 110)),
+ "has_point() with positive Vector2 on left edge should return the expected result.");
+ CHECK_MESSAGE(
+ !Rect2(0, 100, 1280, 720).has_point(Vector2(1280, 110)),
+ "has_point() with positive Vector2 on right edge should return the expected result.");
+
+ CHECK_MESSAGE(
+ Rect2(-4000, 100, 1280, 720).has_point(Vector2(-4000, 110)),
+ "has_point() with negative Vector2 on left edge should return the expected result.");
+ CHECK_MESSAGE(
+ !Rect2(-4000, 100, 1280, 720).has_point(Vector2(-2720, 110)),
+ "has_point() with negative Vector2 on right edge should return the expected result.");
+}
+
+TEST_CASE("[Rect2] Intersection") {
+ CHECK_MESSAGE(
+ Rect2(0, 100, 1280, 720).intersects(Rect2(0, 300, 100, 100)),
+ "intersects() with fully enclosed Rect2 should return the expected result.");
+ CHECK_MESSAGE(
+ Rect2(0, 100, 1280, 720).intersects(Rect2(1200, 700, 100, 100)),
+ "intersects() with partially enclosed Rect2 should return the expected result.");
+ CHECK_MESSAGE(
+ !Rect2(0, 100, 1280, 720).intersects(Rect2(-4000, -4000, 100, 100)),
+ "intersects() with non-enclosed Rect2 should return the expected result.");
+}
+
+TEST_CASE("[Rect2] Merging") {
+ CHECK_MESSAGE(
+ Rect2(0, 100, 1280, 720).merge(Rect2(0, 300, 100, 100)).is_equal_approx(Rect2(0, 100, 1280, 720)),
+ "merge() with fully enclosed Rect2 should return the expected result.");
+ CHECK_MESSAGE(
+ Rect2(0, 100, 1280, 720).merge(Rect2(1200, 700, 100, 100)).is_equal_approx(Rect2(0, 100, 1300, 720)),
+ "merge() with partially enclosed Rect2 should return the expected result.");
+ CHECK_MESSAGE(
+ Rect2(0, 100, 1280, 720).merge(Rect2(-4000, -4000, 100, 100)).is_equal_approx(Rect2(-4000, -4000, 5280, 4820)),
+ "merge() with non-enclosed Rect2 should return the expected result.");
+}
+
+// Rect2i
+
+TEST_CASE("[Rect2i] Constructor methods") {
+ Rect2i recti = Rect2i(0, 100, 1280, 720);
+ Rect2i recti_vector = Rect2i(Vector2i(0, 100), Vector2i(1280, 720));
+ Rect2i recti_copy_recti = Rect2i(recti);
+ Rect2i recti_copy_rect = Rect2i(Rect2(0, 100, 1280, 720));
+
+ CHECK_MESSAGE(
+ recti == recti_vector,
+ "Rect2is created with the same dimensions but by different methods should be equal.");
+ CHECK_MESSAGE(
+ recti == recti_copy_recti,
+ "Rect2is created with the same dimensions but by different methods should be equal.");
+ CHECK_MESSAGE(
+ recti == recti_copy_rect,
+ "Rect2is created with the same dimensions but by different methods should be equal.");
+}
+
+TEST_CASE("[Rect2i] String conversion") {
+ // Note: This also depends on the Vector2 string representation.
+ CHECK_MESSAGE(
+ String(Rect2i(0, 100, 1280, 720)) == "0, 100, 1280, 720",
+ "The string representation should match the expected value.");
+}
+
+TEST_CASE("[Rect2i] Basic getters") {
+ const Rect2i rect = Rect2i(0, 100, 1280, 720);
+ CHECK_MESSAGE(
+ rect.get_position() == Vector2i(0, 100),
+ "get_position() should return the expected value.");
+ CHECK_MESSAGE(
+ rect.get_size() == Vector2i(1280, 720),
+ "get_size() should return the expected value.");
+ CHECK_MESSAGE(
+ rect.get_end() == Vector2i(1280, 820),
+ "get_end() should return the expected value.");
+}
+
+TEST_CASE("[Rect2i] Basic setters") {
+ Rect2i rect = Rect2i(0, 100, 1280, 720);
+ rect.set_end(Vector2i(4000, 4000));
+ CHECK_MESSAGE(
+ rect == Rect2i(0, 100, 4000, 3900),
+ "set_end() should result in the expected Rect2i.");
+
+ rect = Rect2i(0, 100, 1280, 720);
+ rect.set_position(Vector2i(4000, 4000));
+ CHECK_MESSAGE(
+ rect == Rect2i(4000, 4000, 1280, 720),
+ "set_position() should result in the expected Rect2i.");
+
+ rect = Rect2i(0, 100, 1280, 720);
+ rect.set_size(Vector2i(4000, 4000));
+ CHECK_MESSAGE(
+ rect == Rect2i(0, 100, 4000, 4000),
+ "set_size() should result in the expected Rect2i.");
+}
+
+TEST_CASE("[Rect2i] Area getters") {
+ CHECK_MESSAGE(
+ Math::is_equal_approx(Rect2i(0, 100, 1280, 720).get_area(), 921'600),
+ "get_area() should return the expected value.");
+ CHECK_MESSAGE(
+ Math::is_equal_approx(Rect2i(0, 100, -1280, -720).get_area(), 921'600),
+ "get_area() should return the expected value.");
+ CHECK_MESSAGE(
+ Math::is_equal_approx(Rect2i(0, 100, 1280, -720).get_area(), -921'600),
+ "get_area() should return the expected value.");
+ CHECK_MESSAGE(
+ Math::is_equal_approx(Rect2i(0, 100, -1280, 720).get_area(), -921'600),
+ "get_area() should return the expected value.");
+ CHECK_MESSAGE(
+ Math::is_zero_approx(Rect2i(0, 100, 0, 720).get_area()),
+ "get_area() should return the expected value.");
+
+ CHECK_MESSAGE(
+ !Rect2i(0, 100, 1280, 720).has_no_area(),
+ "has_no_area() should return the expected value on Rect2i with an area.");
+ CHECK_MESSAGE(
+ Rect2i(0, 100, 0, 500).has_no_area(),
+ "has_no_area() should return the expected value on Rect2i with no area.");
+ CHECK_MESSAGE(
+ Rect2i(0, 100, 500, 0).has_no_area(),
+ "has_no_area() should return the expected value on Rect2i with no area.");
+ CHECK_MESSAGE(
+ Rect2i(0, 100, 0, 0).has_no_area(),
+ "has_no_area() should return the expected value on Rect2i with no area.");
+}
+
+TEST_CASE("[Rect2i] Absolute coordinates") {
+ CHECK_MESSAGE(
+ Rect2i(0, 100, 1280, 720).abs() == Rect2i(0, 100, 1280, 720),
+ "abs() should return the expected Rect2i.");
+ CHECK_MESSAGE(
+ Rect2i(0, -100, 1280, 720).abs() == Rect2i(0, -100, 1280, 720),
+ "abs() should return the expected Rect2i.");
+ CHECK_MESSAGE(
+ Rect2i(0, -100, -1280, -720).abs() == Rect2i(-1280, -820, 1280, 720),
+ "abs() should return the expected Rect2i.");
+ CHECK_MESSAGE(
+ Rect2i(0, 100, -1280, 720).abs() == Rect2i(-1280, 100, 1280, 720),
+ "abs() should return the expected Rect2i.");
+}
+
+TEST_CASE("[Rect2i] Intersection") {
+ CHECK_MESSAGE(
+ Rect2i(0, 100, 1280, 720).intersection(Rect2i(0, 300, 100, 100)) == Rect2i(0, 300, 100, 100),
+ "intersection() with fully enclosed Rect2i should return the expected result.");
+ // The resulting Rect2i is 100 pixels high because the first Rect2i is vertically offset by 100 pixels.
+ CHECK_MESSAGE(
+ Rect2i(0, 100, 1280, 720).intersection(Rect2i(1200, 700, 100, 100)) == Rect2i(1200, 700, 80, 100),
+ "intersection() with partially enclosed Rect2i should return the expected result.");
+ CHECK_MESSAGE(
+ Rect2i(0, 100, 1280, 720).intersection(Rect2i(-4000, -4000, 100, 100)) == Rect2i(),
+ "intersection() with non-enclosed Rect2i should return the expected result.");
+}
+
+TEST_CASE("[Rect2i] Enclosing") {
+ CHECK_MESSAGE(
+ Rect2i(0, 100, 1280, 720).encloses(Rect2i(0, 300, 100, 100)),
+ "encloses() with fully contained Rect2i should return the expected result.");
+ CHECK_MESSAGE(
+ !Rect2i(0, 100, 1280, 720).encloses(Rect2i(1200, 700, 100, 100)),
+ "encloses() with partially contained Rect2i should return the expected result.");
+ CHECK_MESSAGE(
+ !Rect2i(0, 100, 1280, 720).encloses(Rect2i(-4000, -4000, 100, 100)),
+ "encloses() with non-contained Rect2i should return the expected result.");
+}
+
+TEST_CASE("[Rect2i] Expanding") {
+ CHECK_MESSAGE(
+ Rect2i(0, 100, 1280, 720).expand(Vector2i(500, 600)) == Rect2i(0, 100, 1280, 720),
+ "expand() with contained Vector2i should return the expected result.");
+ CHECK_MESSAGE(
+ Rect2i(0, 100, 1280, 720).expand(Vector2i(0, 0)) == Rect2i(0, 0, 1280, 820),
+ "expand() with non-contained Vector2i should return the expected result.");
+}
+
+TEST_CASE("[Rect2i] Growing") {
+ CHECK_MESSAGE(
+ Rect2i(0, 100, 1280, 720).grow(100) == Rect2i(-100, 0, 1480, 920),
+ "grow() with positive value should return the expected Rect2i.");
+ CHECK_MESSAGE(
+ Rect2i(0, 100, 1280, 720).grow(-100) == Rect2i(100, 200, 1080, 520),
+ "grow() with negative value should return the expected Rect2i.");
+ CHECK_MESSAGE(
+ Rect2i(0, 100, 1280, 720).grow(-4000) == Rect2i(4000, 4100, -6720, -7280),
+ "grow() with large negative value should return the expected Rect2i.");
+
+ CHECK_MESSAGE(
+ Rect2i(0, 100, 1280, 720).grow_individual(100, 200, 300, 400) == Rect2i(-100, -100, 1680, 1320),
+ "grow_individual() with positive values should return the expected Rect2i.");
+ CHECK_MESSAGE(
+ Rect2i(0, 100, 1280, 720).grow_individual(-100, 200, 300, -400) == Rect2i(100, -100, 1480, 520),
+ "grow_individual() with positive and negative values should return the expected Rect2i.");
+
+ CHECK_MESSAGE(
+ Rect2i(0, 100, 1280, 720).grow_margin(SIDE_TOP, 500) == Rect2i(0, -400, 1280, 1220),
+ "grow_margin() with positive value should return the expected Rect2i.");
+ CHECK_MESSAGE(
+ Rect2i(0, 100, 1280, 720).grow_margin(SIDE_TOP, -500) == Rect2i(0, 600, 1280, 220),
+ "grow_margin() with negative value should return the expected Rect2i.");
+}
+
+TEST_CASE("[Rect2i] Has point") {
+ CHECK_MESSAGE(
+ Rect2i(0, 100, 1280, 720).has_point(Vector2i(500, 600)),
+ "has_point() with contained Vector2i should return the expected result.");
+ CHECK_MESSAGE(
+ !Rect2i(0, 100, 1280, 720).has_point(Vector2i(0, 0)),
+ "has_point() with non-contained Vector2i should return the expected result.");
+
+ CHECK_MESSAGE(
+ Rect2i(0, 100, 1280, 720).has_point(Vector2(0, 110)),
+ "has_point() with positive Vector2 on left edge should return the expected result.");
+ CHECK_MESSAGE(
+ !Rect2i(0, 100, 1280, 720).has_point(Vector2(1280, 110)),
+ "has_point() with positive Vector2 on right edge should return the expected result.");
+
+ CHECK_MESSAGE(
+ Rect2i(-4000, 100, 1280, 720).has_point(Vector2(-4000, 110)),
+ "has_point() with negative Vector2 on left edge should return the expected result.");
+ CHECK_MESSAGE(
+ !Rect2i(-4000, 100, 1280, 720).has_point(Vector2(-2720, 110)),
+ "has_point() with negative Vector2 on right edge should return the expected result.");
+}
+
+TEST_CASE("[Rect2i] Intersection") {
+ CHECK_MESSAGE(
+ Rect2i(0, 100, 1280, 720).intersects(Rect2i(0, 300, 100, 100)),
+ "intersects() with fully enclosed Rect2i should return the expected result.");
+ CHECK_MESSAGE(
+ Rect2i(0, 100, 1280, 720).intersects(Rect2i(1200, 700, 100, 100)),
+ "intersects() with partially enclosed Rect2i should return the expected result.");
+ CHECK_MESSAGE(
+ !Rect2i(0, 100, 1280, 720).intersects(Rect2i(-4000, -4000, 100, 100)),
+ "intersects() with non-enclosed Rect2i should return the expected result.");
+}
+
+TEST_CASE("[Rect2i] Merging") {
+ CHECK_MESSAGE(
+ Rect2i(0, 100, 1280, 720).merge(Rect2i(0, 300, 100, 100)) == Rect2i(0, 100, 1280, 720),
+ "merge() with fully enclosed Rect2i should return the expected result.");
+ CHECK_MESSAGE(
+ Rect2i(0, 100, 1280, 720).merge(Rect2i(1200, 700, 100, 100)) == Rect2i(0, 100, 1300, 720),
+ "merge() with partially enclosed Rect2i should return the expected result.");
+ CHECK_MESSAGE(
+ Rect2i(0, 100, 1280, 720).merge(Rect2i(-4000, -4000, 100, 100)) == Rect2i(-4000, -4000, 5280, 4820),
+ "merge() with non-enclosed Rect2i should return the expected result.");
+}
+} // namespace TestRect2
+
+#endif // TEST_RECT2_H
diff --git a/tests/test_render.cpp b/tests/test_render.cpp
index d936dd72e7..d14251bc6a 100644
--- a/tests/test_render.cpp
+++ b/tests/test_render.cpp
@@ -35,7 +35,7 @@
#include "core/os/keyboard.h"
#include "core/os/main_loop.h"
#include "core/os/os.h"
-#include "core/print_string.h"
+#include "core/string/print_string.h"
#include "servers/display_server.h"
#include "servers/rendering_server.h"
@@ -98,7 +98,6 @@ public:
}
}*/
/*for(int i=0;i<100;i++) {
-
vts.push_back( Vector3(Math::randf()*2-1.0,Math::randf()*2-1.0,Math::randf()*2-1.0).normalized()*2);
}*/
/*
@@ -216,7 +215,6 @@ public:
vs->instance_set_transform(E->get().instance, pre * E->get().base);
/*
if( !E->next() ) {
-
vs->free( E->get().instance );
instances.erase(E );
}*/
@@ -236,5 +234,4 @@ public:
MainLoop *test() {
return memnew(TestMainLoop);
}
-
} // namespace TestRender
diff --git a/tests/test_shader_lang.cpp b/tests/test_shader_lang.cpp
index 34ee3e3210..e79c83b001 100644
--- a/tests/test_shader_lang.cpp
+++ b/tests/test_shader_lang.cpp
@@ -34,7 +34,7 @@
#include "core/os/main_loop.h"
#include "core/os/os.h"
-#include "core/print_string.h"
+#include "core/string/print_string.h"
#include "scene/gui/control.h"
#include "scene/gui/text_edit.h"
#include "servers/rendering/shader_language.h"
@@ -325,7 +325,7 @@ MainLoop *test() {
String code;
while (true) {
- CharType c = fa->get_8();
+ char32_t c = fa->get_8();
if (fa->eof_reached()) {
break;
}
@@ -357,5 +357,4 @@ MainLoop *test() {
return nullptr;
}
-
} // namespace TestShaderLang
diff --git a/tests/test_string.h b/tests/test_string.h
index 310be31f4b..3c5d4a2f01 100644
--- a/tests/test_string.h
+++ b/tests/test_string.h
@@ -38,46 +38,165 @@
#include "core/io/ip_address.h"
#include "core/os/main_loop.h"
#include "core/os/os.h"
-#include "core/ustring.h"
+#include "core/string/ustring.h"
-#ifdef MODULE_REGEX_ENABLED
-#include "modules/regex/regex.h"
-#endif
-
-#include "thirdparty/doctest/doctest.h"
+#include "tests/test_macros.h"
namespace TestString {
-TEST_CASE("[String] Assign from cstr") {
+int u32scmp(const char32_t *l, const char32_t *r) {
+ for (; *l == *r && *l && *r; l++, r++)
+ ;
+ return *l - *r;
+}
+
+TEST_CASE("[String] Assign Latin-1 char string") {
String s = "Hello";
- CHECK(wcscmp(s.c_str(), L"Hello") == 0);
+ CHECK(u32scmp(s.get_data(), U"Hello") == 0);
}
-TEST_CASE("[String] Assign from string (operator=)") {
+TEST_CASE("[String] Assign from Latin-1 char string (operator=)") {
String s = "Dolly";
const String &t = s;
- CHECK(wcscmp(t.c_str(), L"Dolly") == 0);
+ CHECK(u32scmp(t.get_data(), U"Dolly") == 0);
}
-TEST_CASE("[String] Assign from c-string (copycon)") {
+TEST_CASE("[String] Assign from Latin-1 char string (copycon)") {
String s("Sheep");
- const String &t(s);
- CHECK(wcscmp(t.c_str(), L"Sheep") == 0);
+ const String &t1(s);
+ CHECK(u32scmp(t1.get_data(), U"Sheep") == 0);
+
+ String t2 = String("Sheep", 3);
+ CHECK(u32scmp(t2.get_data(), U"She") == 0);
}
-TEST_CASE("[String] Assign from c-widechar (operator=)") {
- String s(L"Give me");
- CHECK(wcscmp(s.c_str(), L"Give me") == 0);
+TEST_CASE("[String] Assign from wchar_t string (operator=)") {
+ String s = L"Give me";
+ CHECK(u32scmp(s.get_data(), U"Give me") == 0);
}
-TEST_CASE("[String] Assign from c-widechar (copycon)") {
+TEST_CASE("[String] Assign from wchar_t string (copycon)") {
String s(L"Wool");
- CHECK(wcscmp(s.c_str(), L"Wool") == 0);
+ CHECK(u32scmp(s.get_data(), U"Wool") == 0);
+}
+
+TEST_CASE("[String] Assign from char32_t string (operator=)") {
+ String s = U"Give me";
+ CHECK(u32scmp(s.get_data(), U"Give me") == 0);
+}
+
+TEST_CASE("[String] Assign from char32_t string (copycon)") {
+ String s(U"Wool");
+ CHECK(u32scmp(s.get_data(), U"Wool") == 0);
+}
+
+TEST_CASE("[String] UTF8") {
+ /* how can i embed UTF in here? */
+ static const char32_t u32str[] = { 0x0045, 0x0020, 0x304A, 0x360F, 0x3088, 0x3046, 0x1F3A4, 0 };
+ static const uint8_t u8str[] = { 0x45, 0x20, 0xE3, 0x81, 0x8A, 0xE3, 0x98, 0x8F, 0xE3, 0x82, 0x88, 0xE3, 0x81, 0x86, 0xF0, 0x9F, 0x8E, 0xA4, 0 };
+ String s = u32str;
+ bool err = s.parse_utf8(s.utf8().get_data());
+ CHECK(!err);
+ CHECK(s == u32str);
+
+ err = s.parse_utf8((const char *)u8str);
+ CHECK(!err);
+ CHECK(s == u32str);
+
+ CharString cs = (const char *)u8str;
+ CHECK(String::utf8(cs) == s);
+}
+
+TEST_CASE("[String] UTF16") {
+ /* how can i embed UTF in here? */
+ static const char32_t u32str[] = { 0x0045, 0x0020, 0x304A, 0x360F, 0x3088, 0x3046, 0x1F3A4, 0 };
+ static const char16_t u16str[] = { 0x0045, 0x0020, 0x304A, 0x360F, 0x3088, 0x3046, 0xD83C, 0xDFA4, 0 };
+ String s = u32str;
+ bool err = s.parse_utf16(s.utf16().get_data());
+ CHECK(!err);
+ CHECK(s == u32str);
+
+ err = s.parse_utf16(u16str);
+ CHECK(!err);
+ CHECK(s == u32str);
+
+ Char16String cs = u16str;
+ CHECK(String::utf16(cs) == s);
+}
+
+TEST_CASE("[String] UTF8 with BOM") {
+ /* how can i embed UTF in here? */
+ static const char32_t u32str[] = { 0x0045, 0x0020, 0x304A, 0x360F, 0x3088, 0x3046, 0x1F3A4, 0 };
+ static const uint8_t u8str[] = { 0xEF, 0xBB, 0xBF, 0x45, 0x20, 0xE3, 0x81, 0x8A, 0xE3, 0x98, 0x8F, 0xE3, 0x82, 0x88, 0xE3, 0x81, 0x86, 0xF0, 0x9F, 0x8E, 0xA4, 0 };
+ String s;
+ bool err = s.parse_utf8((const char *)u8str);
+ CHECK(!err);
+ CHECK(s == u32str);
+
+ CharString cs = (const char *)u8str;
+ CHECK(String::utf8(cs) == s);
+}
+
+TEST_CASE("[String] UTF16 with BOM") {
+ /* how can i embed UTF in here? */
+ static const char32_t u32str[] = { 0x0020, 0x0045, 0x304A, 0x360F, 0x3088, 0x3046, 0x1F3A4, 0 };
+ static const char16_t u16str[] = { 0xFEFF, 0x0020, 0x0045, 0x304A, 0x360F, 0x3088, 0x3046, 0xD83C, 0xDFA4, 0 };
+ static const char16_t u16str_swap[] = { 0xFFFE, 0x2000, 0x4500, 0x4A30, 0x0F36, 0x8830, 0x4630, 0x3CD8, 0xA4DF, 0 };
+ String s;
+ bool err = s.parse_utf16(u16str);
+ CHECK(!err);
+ CHECK(s == u32str);
+
+ err = s.parse_utf16(u16str_swap);
+ CHECK(!err);
+ CHECK(s == u32str);
+
+ Char16String cs = u16str;
+ CHECK(String::utf16(cs) == s);
+
+ cs = u16str_swap;
+ CHECK(String::utf16(cs) == s);
+}
+
+TEST_CASE("[String] Invalid UTF8") {
+ ERR_PRINT_OFF
+ static const uint8_t u8str[] = { 0x45, 0xE3, 0x81, 0x8A, 0x8F, 0xE3, 0xE3, 0x98, 0x8F, 0xE3, 0x82, 0x88, 0xE3, 0x81, 0x86, 0xF0, 0x9F, 0x8E, 0xA4, 0 };
+ String s;
+ bool err = s.parse_utf8((const char *)u8str);
+ CHECK(err);
+ CHECK(s == String());
+
+ CharString cs = (const char *)u8str;
+ CHECK(String::utf8(cs) == String());
+ ERR_PRINT_ON
+}
+
+TEST_CASE("[String] Invalid UTF16") {
+ ERR_PRINT_OFF
+ static const char16_t u16str[] = { 0x0045, 0x304A, 0x3088, 0x3046, 0xDFA4, 0 };
+ String s;
+ bool err = s.parse_utf16(u16str);
+ CHECK(err);
+ CHECK(s == String());
+
+ Char16String cs = u16str;
+ CHECK(String::utf16(cs) == String());
+ ERR_PRINT_ON
+}
+
+TEST_CASE("[String] ASCII") {
+ String s = U"Primero Leche";
+ String t = s.ascii(false).get_data();
+ CHECK(s == t);
+
+ t = s.ascii(true).get_data();
+ CHECK(s == t);
}
TEST_CASE("[String] Comparisons (equal)") {
String s = "Test Compare";
CHECK(s == "Test Compare");
+ CHECK(s == U"Test Compare");
CHECK(s == L"Test Compare");
CHECK(s == String("Test Compare"));
}
@@ -85,6 +204,7 @@ TEST_CASE("[String] Comparisons (equal)") {
TEST_CASE("[String] Comparisons (not equal)") {
String s = "Test Compare";
CHECK(s != "Peanut");
+ CHECK(s != U"Coconut");
CHECK(s != L"Coconut");
CHECK(s != String("Butter"));
}
@@ -92,6 +212,7 @@ TEST_CASE("[String] Comparisons (not equal)") {
TEST_CASE("[String] Comparisons (operator <)") {
String s = "Bees";
CHECK(s < "Elephant");
+ CHECK(!(s < U"Amber"));
CHECK(!(s < L"Amber"));
CHECK(!(s < String("Beatrix")));
}
@@ -103,7 +224,7 @@ TEST_CASE("[String] Concatenation") {
s += ' ';
s += 'a';
s += String(" ");
- s = s + L"Nice";
+ s = s + U"Nice";
s = s + " ";
s = s + String("Day");
@@ -130,34 +251,49 @@ TEST_CASE("[String] Testing for empty string") {
CHECK(String("").empty());
}
+TEST_CASE("[String] Test chr") {
+ CHECK(String::chr('H') == "H");
+ CHECK(String::chr(0x3012)[0] == 0x3012);
+ ERR_PRINT_OFF
+ CHECK(String::chr(0xd812)[0] == 0xfffd); // Unpaired UTF-16 surrogate
+ CHECK(String::chr(0x20d812)[0] == 0xfffd); // Outside UTF-32 range
+ ERR_PRINT_ON
+}
+
TEST_CASE("[String] Operator []") {
String a = "Kugar Sane";
a[0] = 'S';
a[6] = 'C';
CHECK(a == "Sugar Cane");
CHECK(a[1] == 'u');
+ CHECK(a.ord_at(1) == 'u');
}
TEST_CASE("[String] Case function test") {
String a = "MoMoNgA";
CHECK(a.to_upper() == "MOMONGA");
+ CHECK(a.to_lower() == "momonga");
+}
+
+TEST_CASE("[String] Case compare function test") {
+ String a = "MoMoNgA";
+
+ CHECK(a.casecmp_to("momonga") != 0);
CHECK(a.nocasecmp_to("momonga") == 0);
}
-TEST_CASE("[String] UTF8") {
- /* how can i embed UTF in here? */
- static const CharType ustr[] = { 0x304A, 0x360F, 0x3088, 0x3046, 0 };
- //static const wchar_t ustr[] = { 'P', 0xCE, 'p',0xD3, 0 };
- String s = ustr;
- s.parse_utf8(s.utf8().get_data());
- CHECK(s == ustr);
+TEST_CASE("[String] Natural compare function test") {
+ String a = "img2.png";
+
+ CHECK(a.nocasecmp_to("img10.png") > 0);
+ CHECK(a.naturalnocasecmp_to("img10.png") < 0);
}
-TEST_CASE("[String] ASCII") {
- String s = L"Primero Leche";
- String t = s.ascii().get_data();
- CHECK(s == t);
+TEST_CASE("[String] hex_encode_buffer") {
+ static const uint8_t u8str[] = { 0x45, 0xE3, 0x81, 0x8A, 0x8F, 0xE3 };
+ String s = String::hex_encode_buffer(u8str, 6);
+ CHECK(s == U"45e3818a8fe3");
}
TEST_CASE("[String] Substr") {
@@ -165,24 +301,45 @@ TEST_CASE("[String] Substr") {
CHECK(s.substr(3, 4) == "ler ");
}
-TEST_CASE("[string] Find") {
- String s = "Pretty Woman";
- s.find("Revenge of the Monster Truck");
-
+TEST_CASE("[String] Find") {
+ String s = "Pretty Woman Woman";
CHECK(s.find("tty") == 3);
+ CHECK(s.find("Wo", 9) == 13);
CHECK(s.find("Revenge of the Monster Truck") == -1);
+ CHECK(s.rfind("man") == 15);
}
-TEST_CASE("[String] find no case") {
- String s = "Pretty Whale";
+TEST_CASE("[String] Find no case") {
+ String s = "Pretty Whale Whale";
CHECK(s.findn("WHA") == 7);
+ CHECK(s.findn("WHA", 9) == 13);
CHECK(s.findn("Revenge of the Monster SawFish") == -1);
+ CHECK(s.rfindn("WHA") == 13);
+}
+
+TEST_CASE("[String] Find MK") {
+ Vector<String> keys;
+ keys.push_back("sty");
+ keys.push_back("tty");
+ keys.push_back("man");
+
+ String s = "Pretty Woman";
+ int key = 0;
+
+ CHECK(s.findmk(keys, 0, &key) == 3);
+ CHECK(key == 1);
+
+ CHECK(s.findmk(keys, 5, &key) == 9);
+ CHECK(key == 2);
}
TEST_CASE("[String] Find and replace") {
String s = "Happy Birthday, Anna!";
s = s.replace("Birthday", "Halloween");
CHECK(s == "Happy Halloween, Anna!");
+
+ s = s.replace_first("H", "W");
+ CHECK(s == "Wappy Halloween, Anna!");
}
TEST_CASE("[String] Insertion") {
@@ -193,6 +350,12 @@ TEST_CASE("[String] Insertion") {
TEST_CASE("[String] Number to string") {
CHECK(String::num(3.141593) == "3.141593");
+ CHECK(String::num(3.141593, 3) == "3.142");
+ CHECK(String::num_real(3.141593) == "3.141593");
+ CHECK(String::num_scientific(30000000) == "3e+07");
+ CHECK(String::num_int64(3141593) == "3141593");
+ CHECK(String::num_int64(0xA141593, 16) == "a141593");
+ CHECK(String::num_int64(0xA141593, 16, true) == "A141593");
}
TEST_CASE("[String] String to integer") {
@@ -204,6 +367,18 @@ TEST_CASE("[String] String to integer") {
}
}
+TEST_CASE("[String] Hex to integer") {
+ static const char *nums[4] = { "0xFFAE", "22", "0", "AADDAD" };
+ static const int64_t num[4] = { 0xFFAE, 0x22, 0, 0xAADDAD };
+ static const bool wo_prefix[4] = { false, true, true, true };
+ static const bool w_prefix[4] = { true, false, true, false };
+
+ for (int i = 0; i < 4; i++) {
+ CHECK((String(nums[i]).hex_to_int(true) == num[i]) == w_prefix[i]);
+ CHECK((String(nums[i]).hex_to_int(false) == num[i]) == wo_prefix[i]);
+ }
+}
+
TEST_CASE("[String] String to float") {
static const char *nums[4] = { "-12348298412.2", "0.05", "2.0002", " -0.0001" };
static const double num[4] = { -12348298412.2, 0.05, 2.0002, -0.0001 };
@@ -213,6 +388,11 @@ TEST_CASE("[String] String to float") {
}
}
+TEST_CASE("[String] CamelCase to underscore") {
+ CHECK(String("TestTestStringGD").camelcase_to_underscore(false) == String("Test_Test_String_GD"));
+ CHECK(String("TestTestStringGD").camelcase_to_underscore(true) == String("test_test_string_gd"));
+}
+
TEST_CASE("[String] Slicing") {
String s = "Mars,Jupiter,Saturn,Uranus";
@@ -222,24 +402,78 @@ TEST_CASE("[String] Slicing") {
}
}
+TEST_CASE("[String] Splitting") {
+ String s = "Mars,Jupiter,Saturn,Uranus";
+ Vector<String> l;
+
+ const char *slices_l[3] = { "Mars", "Jupiter", "Saturn,Uranus" };
+ const char *slices_r[3] = { "Mars,Jupiter", "Saturn", "Uranus" };
+
+ l = s.split(",", true, 2);
+ CHECK(l.size() == 3);
+ for (int i = 0; i < l.size(); i++) {
+ CHECK(l[i] == slices_l[i]);
+ }
+
+ l = s.rsplit(",", true, 2);
+ CHECK(l.size() == 3);
+ for (int i = 0; i < l.size(); i++) {
+ CHECK(l[i] == slices_r[i]);
+ }
+
+ s = "Mars Jupiter Saturn Uranus";
+ const char *slices_s[4] = { "Mars", "Jupiter", "Saturn", "Uranus" };
+ l = s.split_spaces();
+ for (int i = 0; i < l.size(); i++) {
+ CHECK(l[i] == slices_s[i]);
+ }
+
+ s = "1.2;2.3 4.5";
+ const double slices_d[3] = { 1.2, 2.3, 4.5 };
+
+ Vector<float> f;
+ f = s.split_floats(";");
+ CHECK(f.size() == 2);
+ for (int i = 0; i < f.size(); i++) {
+ CHECK(ABS(f[i] - slices_d[i]) <= 0.00001);
+ }
+
+ Vector<String> keys;
+ keys.push_back(";");
+ keys.push_back(" ");
+
+ f = s.split_floats_mk(keys);
+ CHECK(f.size() == 3);
+ for (int i = 0; i < f.size(); i++) {
+ CHECK(ABS(f[i] - slices_d[i]) <= 0.00001);
+ }
+
+ s = "1;2 4";
+ const int slices_i[3] = { 1, 2, 4 };
+
+ Vector<int> ii;
+ ii = s.split_ints(";");
+ CHECK(ii.size() == 2);
+ for (int i = 0; i < ii.size(); i++) {
+ CHECK(ii[i] == slices_i[i]);
+ }
+
+ ii = s.split_ints_mk(keys);
+ CHECK(ii.size() == 3);
+ for (int i = 0; i < ii.size(); i++) {
+ CHECK(ii[i] == slices_i[i]);
+ }
+}
+
TEST_CASE("[String] Erasing") {
String s = "Josephine is such a cute girl!";
s.erase(s.find("cute "), String("cute ").length());
CHECK(s == "Josephine is such a girl!");
}
-#ifdef MODULE_REGEX_ENABLED
-TEST_CASE("[String] Regex substitution") {
- String s = "Double all the vowels.";
- RegEx re("(?<vowel>[aeiou])");
- s = re.sub(s, "$0$vowel", true);
- CHECK(s == "Doouublee aall thee vooweels.");
-}
-#endif
-
struct test_27_data {
char const *data;
- char const *begin;
+ char const *part;
bool expected;
};
@@ -253,9 +487,9 @@ TEST_CASE("[String] Begins with") {
bool state = true;
for (size_t i = 0; state && i < count; ++i) {
String s = tc[i].data;
- state = s.begins_with(tc[i].begin) == tc[i].expected;
+ state = s.begins_with(tc[i].part) == tc[i].expected;
if (state) {
- String sb = tc[i].begin;
+ String sb = tc[i].part;
state = s.begins_with(sb) == tc[i].expected;
}
CHECK(state);
@@ -266,6 +500,42 @@ TEST_CASE("[String] Begins with") {
CHECK(state);
}
+TEST_CASE("[String] Ends with") {
+ test_27_data tc[] = {
+ { "res://foobar", "foobar", true },
+ { "res", "res://", false },
+ { "abc", "abc", true }
+ };
+ size_t count = sizeof(tc) / sizeof(tc[0]);
+ bool state = true;
+ for (size_t i = 0; state && i < count; ++i) {
+ String s = tc[i].data;
+ state = s.ends_with(tc[i].part) == tc[i].expected;
+ if (state) {
+ String sb = tc[i].part;
+ state = s.ends_with(sb) == tc[i].expected;
+ }
+ CHECK(state);
+ if (!state) {
+ break;
+ }
+ };
+ CHECK(state);
+}
+
+TEST_CASE("[String] format") {
+ const String value_format = "red=\"$red\" green=\"$green\" blue=\"$blue\" alpha=\"$alpha\"";
+
+ Dictionary value_dictionary;
+ value_dictionary["red"] = 10;
+ value_dictionary["green"] = 20;
+ value_dictionary["blue"] = "bla";
+ value_dictionary["alpha"] = 0.4;
+ String value = value_format.format(value_dictionary, "$_");
+
+ CHECK(value == "red=\"10\" green=\"20\" blue=\"bla\" alpha=\"0.4\"");
+}
+
TEST_CASE("[String] sprintf") {
String format, output;
Array args;
@@ -560,6 +830,38 @@ TEST_CASE("[String] sprintf") {
CHECK(output == "%c requires number or single-character string");
}
+TEST_CASE("[String] is_numeric") {
+ CHECK(String("12").is_numeric());
+ CHECK(String("1.2").is_numeric());
+ CHECK(!String("AF").is_numeric());
+ CHECK(String("-12").is_numeric());
+ CHECK(String("-1.2").is_numeric());
+}
+
+TEST_CASE("[String] pad") {
+ String s = String("test");
+ CHECK(s.lpad(10, "x") == U"xxxxxxtest");
+ CHECK(s.rpad(10, "x") == U"testxxxxxx");
+
+ s = String("10.10");
+ CHECK(s.pad_decimals(4) == U"10.1000");
+ CHECK(s.pad_zeros(4) == U"0010.10");
+}
+
+TEST_CASE("[String] is_subsequence_of") {
+ String a = "is subsequence of";
+ CHECK(String("sub").is_subsequence_of(a));
+ CHECK(!String("Sub").is_subsequence_of(a));
+ CHECK(String("Sub").is_subsequence_ofi(a));
+}
+
+TEST_CASE("[String] match") {
+ CHECK(String("img1.png").match("*.png"));
+ CHECK(!String("img1.jpeg").match("*.png"));
+ CHECK(!String("img1.Png").match("*.png"));
+ CHECK(String("img1.Png").matchn("*.png"));
+}
+
TEST_CASE("[String] IPVX address to string") {
IP_Address ip0("2001:0db8:85a3:0000:0000:8a2e:0370:7334");
IP_Address ip(0x0123, 0x4567, 0x89ab, 0xcdef, true);
@@ -792,6 +1094,194 @@ TEST_CASE("[String] Count and countn functionality") {
COUNT_TEST(String("testTest-TeStatest").countn("tEsT", 4, 16) == 2);
CHECK(state);
+
+#undef COUNT_TEST
+}
+
+TEST_CASE("[String] Bigrams") {
+ String s = "abcd";
+ Vector<String> bigr = s.bigrams();
+
+ CHECK(bigr.size() == 3);
+ CHECK(bigr[0] == "ab");
+ CHECK(bigr[1] == "bc");
+ CHECK(bigr[2] == "cd");
+}
+
+TEST_CASE("[String] c-escape/unescape") {
+ String s = "\\1\a2\b\f3\n45\r6\t7\v8\'9\?0\"";
+ CHECK(s.c_escape().c_unescape() == s);
+}
+
+TEST_CASE("[String] dedent") {
+ String s = " aaa\n bbb";
+ String t = "aaa\nbbb";
+ CHECK(s.dedent() == t);
+}
+
+TEST_CASE("[String] Path functions") {
+ static const char *path[4] = { "C:\\Godot\\project\\test.tscn", "/Godot/project/test.xscn", "../Godot/project/test.scn", "Godot\\test.doc" };
+ static const char *base_dir[4] = { "C:\\Godot\\project", "/Godot/project", "../Godot/project", "Godot" };
+ static const char *base_name[4] = { "C:\\Godot\\project\\test", "/Godot/project/test", "../Godot/project/test", "Godot\\test" };
+ static const char *ext[4] = { "tscn", "xscn", "scn", "doc" };
+ static const char *file[4] = { "test.tscn", "test.xscn", "test.scn", "test.doc" };
+ static const bool abs[4] = { true, true, false, false };
+
+ for (int i = 0; i < 4; i++) {
+ CHECK(String(path[i]).get_base_dir() == base_dir[i]);
+ CHECK(String(path[i]).get_basename() == base_name[i]);
+ CHECK(String(path[i]).get_extension() == ext[i]);
+ CHECK(String(path[i]).get_file() == file[i]);
+ CHECK(String(path[i]).is_abs_path() == abs[i]);
+ CHECK(String(path[i]).is_rel_path() != abs[i]);
+ CHECK(String(path[i]).simplify_path().get_base_dir().plus_file(file[i]) == String(path[i]).simplify_path());
+ }
+
+ static const char *file_name[3] = { "test.tscn", "test://.xscn", "?tes*t.scn" };
+ static const bool valid[3] = { true, false, false };
+ for (int i = 0; i < 3; i++) {
+ CHECK(String(file_name[i]).is_valid_filename() == valid[i]);
+ }
+}
+
+TEST_CASE("[String] hash") {
+ String a = "Test";
+ String b = "Test";
+ String c = "West";
+ CHECK(a.hash() == b.hash());
+ CHECK(a.hash() != c.hash());
+
+ CHECK(a.hash64() == b.hash64());
+ CHECK(a.hash64() != c.hash64());
+}
+
+TEST_CASE("[String] http_escape/unescape") {
+ String s = "Godot Engine:'docs'";
+ String t = "Godot%20Engine%3A%27docs%27";
+
+ CHECK(s.http_escape() == t);
+ CHECK(t.http_unescape() == s);
+}
+
+TEST_CASE("[String] percent_encode/decode") { // Note: is it redundant? Seems to be same as http_escape/unescape but in lower case.
+ String s = "Godot Engine:'docs'";
+ String t = "Godot%20Engine%3a%27docs%27";
+
+ CHECK(s.percent_encode() == t);
+ CHECK(t.percent_decode() == s);
+}
+
+TEST_CASE("[String] xml_escape/unescape") {
+ String s = "\"Test\" <test@test&'test'>";
+ CHECK(s.xml_escape(true).xml_unescape() == s);
+ CHECK(s.xml_escape(false).xml_unescape() == s);
+}
+
+TEST_CASE("[String] Strip escapes") {
+ String s = "\t\tTest Test\r\n Test";
+ CHECK(s.strip_escapes() == "Test Test Test");
+}
+
+TEST_CASE("[String] Similarity") {
+ String a = "Test";
+ String b = "West";
+ String c = "Toad";
+ CHECK(a.similarity(b) > a.similarity(c));
+}
+
+TEST_CASE("[String] Strip edges") {
+ String s = "\t Test Test ";
+ CHECK(s.strip_edges(true, false) == "Test Test ");
+ CHECK(s.strip_edges(false, true) == "\t Test Test");
+ CHECK(s.strip_edges(true, true) == "Test Test");
+}
+
+TEST_CASE("[String] Trim") {
+ String s = "aaaTestbbb";
+ CHECK(s.trim_prefix("aaa") == "Testbbb");
+ CHECK(s.trim_suffix("bbb") == "aaaTest");
+ CHECK(s.trim_suffix("Test") == s);
+}
+
+TEST_CASE("[String] Right/Left") {
+ String s = "aaaTestbbb";
+ // ^
+ CHECK(s.right(6) == "tbbb");
+ CHECK(s.left(6) == "aaaTes");
+}
+
+TEST_CASE("[String] Repeat") {
+ String s = "abababab";
+ String x = "ab";
+ String t = x.repeat(4);
+ CHECK(t == s);
+}
+
+TEST_CASE("[String] SHA1/SHA256/MD5") {
+ String s = "Godot";
+ String sha1 = "a1e91f39b9fce6a9998b14bdbe2aa2b39dc2d201";
+ static uint8_t sha1_buf[20] = {
+ 0xA1, 0xE9, 0x1F, 0x39, 0xB9, 0xFC, 0xE6, 0xA9, 0x99, 0x8B, 0x14, 0xBD, 0xBE, 0x2A, 0xA2, 0xB3,
+ 0x9D, 0xC2, 0xD2, 0x01
+ };
+ String sha256 = "2a02b2443f7985d89d09001086ae3dcfa6eb0f55c6ef170715d42328e16e6cb8";
+ static uint8_t sha256_buf[32] = {
+ 0x2A, 0x02, 0xB2, 0x44, 0x3F, 0x79, 0x85, 0xD8, 0x9D, 0x09, 0x00, 0x10, 0x86, 0xAE, 0x3D, 0xCF,
+ 0xA6, 0xEB, 0x0F, 0x55, 0xC6, 0xEF, 0x17, 0x07, 0x15, 0xD4, 0x23, 0x28, 0xE1, 0x6E, 0x6C, 0xB8
+ };
+ String md5 = "4a336d087aeb0390da10ee2ea7cb87f8";
+ static uint8_t md5_buf[16] = {
+ 0x4A, 0x33, 0x6D, 0x08, 0x7A, 0xEB, 0x03, 0x90, 0xDA, 0x10, 0xEE, 0x2E, 0xA7, 0xCB, 0x87, 0xF8
+ };
+
+ PackedByteArray buf = s.sha1_buffer();
+ CHECK(memcmp(sha1_buf, buf.ptr(), 20) == 0);
+ CHECK(s.sha1_text() == sha1);
+
+ buf = s.sha256_buffer();
+ CHECK(memcmp(sha256_buf, buf.ptr(), 32) == 0);
+ CHECK(s.sha256_text() == sha256);
+
+ buf = s.md5_buffer();
+ CHECK(memcmp(md5_buf, buf.ptr(), 16) == 0);
+ CHECK(s.md5_text() == md5);
+}
+
+TEST_CASE("[String] Join") {
+ String s = ", ";
+ Vector<String> parts;
+ parts.push_back("One");
+ parts.push_back("B");
+ parts.push_back("C");
+ String t = s.join(parts);
+ CHECK(t == "One, B, C");
+}
+
+TEST_CASE("[String] Is_*") {
+ static const char *data[12] = { "-30", "100", "10.1", "10,1", "1e2", "1e-2", "1e2e3", "0xAB", "AB", "Test1", "1Test", "Test*1" };
+ static bool isnum[12] = { true, true, true, false, false, false, false, false, false, false, false, false };
+ static bool isint[12] = { true, true, false, false, false, false, false, false, false, false, false, false };
+ static bool ishex[12] = { true, true, false, false, true, false, true, false, true, false, false, false };
+ static bool ishex_p[12] = { false, false, false, false, false, false, false, true, false, false, false, false };
+ static bool isflt[12] = { true, true, true, false, true, true, false, false, false, false, false, false };
+ static bool isid[12] = { false, false, false, false, false, false, false, false, true, true, false, false };
+ for (int i = 0; i < 12; i++) {
+ String s = String(data[i]);
+ CHECK(s.is_numeric() == isnum[i]);
+ CHECK(s.is_valid_integer() == isint[i]);
+ CHECK(s.is_valid_hex_number(false) == ishex[i]);
+ CHECK(s.is_valid_hex_number(true) == ishex_p[i]);
+ CHECK(s.is_valid_float() == isflt[i]);
+ CHECK(s.is_valid_identifier() == isid[i]);
+ }
+}
+
+TEST_CASE("[String] humanize_size") {
+ CHECK(String::humanize_size(1000) == "1000 B");
+ CHECK(String::humanize_size(1025) == "1.00 KiB");
+ CHECK(String::humanize_size(1025300) == "1001.2 KiB");
+ CHECK(String::humanize_size(100523550) == "95.86 MiB");
+ CHECK(String::humanize_size(5345555000) == "4.97 GiB");
}
} // namespace TestString
diff --git a/tests/test_text_server.h b/tests/test_text_server.h
new file mode 100644
index 0000000000..a1a97f3211
--- /dev/null
+++ b/tests/test_text_server.h
@@ -0,0 +1,249 @@
+/*************************************************************************/
+/* test_text_server.h */
+/*************************************************************************/
+/* This file is part of: */
+/* GODOT ENGINE */
+/* https://godotengine.org */
+/*************************************************************************/
+/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
+/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
+/* */
+/* Permission is hereby granted, free of charge, to any person obtaining */
+/* a copy of this software and associated documentation files (the */
+/* "Software"), to deal in the Software without restriction, including */
+/* without limitation the rights to use, copy, modify, merge, publish, */
+/* distribute, sublicense, and/or sell copies of the Software, and to */
+/* permit persons to whom the Software is furnished to do so, subject to */
+/* the following conditions: */
+/* */
+/* The above copyright notice and this permission notice shall be */
+/* included in all copies or substantial portions of the Software. */
+/* */
+/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
+/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
+/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
+/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
+/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
+/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
+/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
+/*************************************************************************/
+
+#ifndef TEST_TEXT_SERVER_H
+#define TEST_TEXT_SERVER_H
+
+#include "editor/builtin_fonts.gen.h"
+#include "servers/text_server.h"
+#include "tests/test_macros.h"
+
+namespace TestTextServer {
+
+TEST_SUITE("[[TextServer]") {
+ TEST_CASE("[TextServer] Init, font loading and shaping") {
+ TextServerManager *tsman = memnew(TextServerManager);
+ Error err = OK;
+
+ SUBCASE("[TextServer] Init") {
+ for (int i = 0; i < TextServerManager::get_interface_count(); i++) {
+ TextServer *ts = TextServerManager::initialize(i, err);
+ TEST_FAIL_COND((err != OK || ts == nullptr), "Text server " + TextServerManager::get_interface_name(i) + " init failed.");
+ }
+ }
+
+ SUBCASE("[TextServer] Loading fonts") {
+ for (int i = 0; i < TextServerManager::get_interface_count(); i++) {
+ TextServer *ts = TextServerManager::initialize(i, err);
+
+ RID font = ts->create_font_memory(_font_NotoSansUI_Regular, _font_NotoSansUI_Regular_size, "ttf");
+ TEST_FAIL_COND(font == RID(), "Loading font failed.");
+ ts->free(font);
+ }
+ }
+
+ SUBCASE("[TextServer] Text layout: Font fallback") {
+ for (int i = 0; i < TextServerManager::get_interface_count(); i++) {
+ TextServer *ts = TextServerManager::initialize(i, err);
+
+ Vector<RID> font;
+ font.push_back(ts->create_font_memory(_font_NotoSansUI_Regular, _font_NotoSansUI_Regular_size, "ttf"));
+ font.push_back(ts->create_font_memory(_font_NotoSansThaiUI_Regular, _font_NotoSansThaiUI_Regular_size, "ttf"));
+
+ String test = U"คนอ้วน khon uan ראה";
+ // 6^ 17^
+
+ RID ctx = ts->create_shaped_text();
+ TEST_FAIL_COND(ctx == RID(), "Creating text buffer failed.");
+ bool ok = ts->shaped_text_add_string(ctx, test, font, 16);
+ TEST_FAIL_COND(!ok, "Adding text to the buffer failed.");
+
+ Vector<TextServer::Glyph> glyphs = ts->shaped_text_get_glyphs(ctx);
+ TEST_FAIL_COND(glyphs.size() == 0, "Shaping failed");
+ for (int j = 0; j < glyphs.size(); j++) {
+ if (glyphs[j].start < 6) {
+ TEST_FAIL_COND(glyphs[j].font_rid != font[1], "Incorrect font selected.");
+ }
+ if ((glyphs[j].start > 6) && (glyphs[j].start < 16)) {
+ TEST_FAIL_COND(glyphs[j].font_rid != font[0], "Incorrect font selected.");
+ }
+ if (glyphs[j].start > 16) {
+ TEST_FAIL_COND(glyphs[j].font_rid != RID(), "Incorrect font selected.");
+ TEST_FAIL_COND(glyphs[j].index != test[glyphs[j].start], "Incorrect glyph index.");
+ }
+ TEST_FAIL_COND((glyphs[j].start < 0 || glyphs[j].end > test.length()), "Incorrect glyph range.");
+ TEST_FAIL_COND(glyphs[j].font_size != 16, "Incorrect glyph font size.");
+ }
+
+ ts->free(ctx);
+
+ for (int j = 0; j < font.size(); j++) {
+ ts->free(font[j]);
+ }
+ font.clear();
+ }
+ }
+
+ SUBCASE("[TextServer] Text layout: BiDi") {
+ for (int i = 0; i < TextServerManager::get_interface_count(); i++) {
+ TextServer *ts = TextServerManager::initialize(i, err);
+
+ if (!ts->has_feature(TextServer::FEATURE_BIDI_LAYOUT)) {
+ continue;
+ }
+
+ Vector<RID> font;
+ font.push_back(ts->create_font_memory(_font_NotoSansUI_Regular, _font_NotoSansUI_Regular_size, "ttf"));
+ font.push_back(ts->create_font_memory(_font_NotoNaskhArabicUI_Regular, _font_NotoNaskhArabicUI_Regular_size, "ttf"));
+
+ String test = U"Arabic (اَلْعَرَبِيَّةُ, al-ʿarabiyyah)";
+ // 7^ 26^
+
+ RID ctx = ts->create_shaped_text();
+ TEST_FAIL_COND(ctx == RID(), "Creating text buffer failed.");
+ bool ok = ts->shaped_text_add_string(ctx, test, font, 16);
+ TEST_FAIL_COND(!ok, "Adding text to the buffer failed.");
+
+ Vector<TextServer::Glyph> glyphs = ts->shaped_text_get_glyphs(ctx);
+ TEST_FAIL_COND(glyphs.size() == 0, "Shaping failed");
+ for (int j = 0; j < glyphs.size(); j++) {
+ if (glyphs[j].count > 0) {
+ if (glyphs[j].start < 7) {
+ TEST_FAIL_COND(((glyphs[j].flags & TextServer::GRAPHEME_IS_RTL) == TextServer::GRAPHEME_IS_RTL), "Incorrect direction.");
+ }
+ if ((glyphs[j].start > 8) && (glyphs[j].start < 23)) {
+ TEST_FAIL_COND(((glyphs[j].flags & TextServer::GRAPHEME_IS_RTL) != TextServer::GRAPHEME_IS_RTL), "Incorrect direction.");
+ }
+ if (glyphs[j].start > 26) {
+ TEST_FAIL_COND(((glyphs[j].flags & TextServer::GRAPHEME_IS_RTL) == TextServer::GRAPHEME_IS_RTL), "Incorrect direction.");
+ }
+ }
+ }
+
+ ts->free(ctx);
+
+ for (int j = 0; j < font.size(); j++) {
+ ts->free(font[j]);
+ }
+ font.clear();
+ }
+ }
+
+ SUBCASE("[TextServer] Text layout: Line breaking") {
+ for (int i = 0; i < TextServerManager::get_interface_count(); i++) {
+ TextServer *ts = TextServerManager::initialize(i, err);
+
+ String test_1 = U"test test test";
+ // 5^ 10^
+
+ Vector<RID> font;
+ font.push_back(ts->create_font_memory(_font_NotoSansUI_Regular, _font_NotoSansUI_Regular_size, "ttf"));
+ font.push_back(ts->create_font_memory(_font_NotoSansThaiUI_Regular, _font_NotoSansThaiUI_Regular_size, "ttf"));
+
+ RID ctx = ts->create_shaped_text();
+ TEST_FAIL_COND(ctx == RID(), "Creating text buffer failed.");
+ bool ok = ts->shaped_text_add_string(ctx, test_1, font, 16);
+ TEST_FAIL_COND(!ok, "Adding text to the buffer failed.");
+
+ Vector<Vector2i> brks = ts->shaped_text_get_line_breaks(ctx, 1);
+ TEST_FAIL_COND(brks.size() != 3, "Invalid line breaks number.");
+ if (brks.size() == 3) {
+ TEST_FAIL_COND(brks[0] != Vector2i(0, 5), "Invalid line break position.");
+ TEST_FAIL_COND(brks[1] != Vector2i(5, 10), "Invalid line break position.");
+ TEST_FAIL_COND(brks[2] != Vector2i(10, 14), "Invalid line break position.");
+ }
+
+ ts->free(ctx);
+
+ for (int j = 0; j < font.size(); j++) {
+ ts->free(font[j]);
+ }
+ font.clear();
+ }
+ }
+
+ SUBCASE("[TextServer] Text layout: Justification") {
+ for (int i = 0; i < TextServerManager::get_interface_count(); i++) {
+ TextServer *ts = TextServerManager::initialize(i, err);
+
+ Vector<RID> font;
+ font.push_back(ts->create_font_memory(_font_NotoSansUI_Regular, _font_NotoSansUI_Regular_size, "ttf"));
+ font.push_back(ts->create_font_memory(_font_NotoNaskhArabicUI_Regular, _font_NotoNaskhArabicUI_Regular_size, "ttf"));
+
+ String test_1 = U"الحمد";
+ String test_2 = U"الحمد test";
+ String test_3 = U"test test";
+ // 7^ 26^
+
+ RID ctx;
+ bool ok;
+ float width_old, width;
+ if (ts->has_feature(TextServer::FEATURE_KASHIDA_JUSTIFICATION)) {
+ ctx = ts->create_shaped_text();
+ TEST_FAIL_COND(ctx == RID(), "Creating text buffer failed.");
+ ok = ts->shaped_text_add_string(ctx, test_1, font, 16);
+ TEST_FAIL_COND(!ok, "Adding text to the buffer failed.");
+
+ width_old = ts->shaped_text_get_width(ctx);
+ width = ts->shaped_text_fit_to_width(ctx, 100, TextServer::JUSTIFICATION_WORD_BOUND);
+ TEST_FAIL_COND((width != width_old), "Invalid fill width.");
+ width = ts->shaped_text_fit_to_width(ctx, 100, TextServer::JUSTIFICATION_WORD_BOUND | TextServer::JUSTIFICATION_KASHIDA);
+ TEST_FAIL_COND((width <= width_old || width > 100), "Invalid fill width.");
+
+ ts->free(ctx);
+
+ ctx = ts->create_shaped_text();
+ TEST_FAIL_COND(ctx == RID(), "Creating text buffer failed.");
+ ok = ts->shaped_text_add_string(ctx, test_2, font, 16);
+ TEST_FAIL_COND(!ok, "Adding text to the buffer failed.");
+
+ width_old = ts->shaped_text_get_width(ctx);
+ width = ts->shaped_text_fit_to_width(ctx, 100, TextServer::JUSTIFICATION_WORD_BOUND);
+ TEST_FAIL_COND((width <= width_old || width > 100), "Invalid fill width.");
+ width = ts->shaped_text_fit_to_width(ctx, 100, TextServer::JUSTIFICATION_WORD_BOUND | TextServer::JUSTIFICATION_KASHIDA);
+ TEST_FAIL_COND((width <= width_old || width > 100), "Invalid fill width.");
+
+ ts->free(ctx);
+ }
+
+ ctx = ts->create_shaped_text();
+ TEST_FAIL_COND(ctx == RID(), "Creating text buffer failed.");
+ ok = ts->shaped_text_add_string(ctx, test_3, font, 16);
+ TEST_FAIL_COND(!ok, "Adding text to the buffer failed.");
+
+ width_old = ts->shaped_text_get_width(ctx);
+ width = ts->shaped_text_fit_to_width(ctx, 100, TextServer::JUSTIFICATION_WORD_BOUND);
+ TEST_FAIL_COND((width <= width_old || width > 100), "Invalid fill width.");
+
+ ts->free(ctx);
+
+ for (int j = 0; j < font.size(); j++) {
+ ts->free(font[j]);
+ }
+ font.clear();
+ }
+ }
+
+ memdelete(tsman);
+ }
+}
+}; // namespace TestTextServer
+
+#endif // TEST_TEXT_SERVER_H
diff --git a/tests/test_validate_testing.h b/tests/test_validate_testing.h
index 5be7d45185..b4ea6eb576 100644
--- a/tests/test_validate_testing.h
+++ b/tests/test_validate_testing.h
@@ -33,10 +33,157 @@
#include "core/os/os.h"
-#include "thirdparty/doctest/doctest.h"
+#include "tests/test_macros.h"
-TEST_CASE("Validate Test will always pass") {
- CHECK(true);
+TEST_SUITE("Validate tests") {
+ TEST_CASE("Always pass") {
+ CHECK(true);
+ }
+ TEST_CASE_PENDING("Pending tests are skipped") {
+ if (!doctest::getContextOptions()->no_skip) { // Normal run.
+ FAIL("This should be skipped if `--no-skip` is NOT set (missing `doctest::skip()` decorator?)");
+ } else {
+ CHECK_MESSAGE(true, "Pending test is run with `--no-skip`");
+ }
+ }
+ TEST_CASE("Muting Godot error messages") {
+ ERR_PRINT_OFF;
+ CHECK_MESSAGE(!_print_error_enabled, "Error printing should be disabled.");
+ ERR_PRINT("Still waiting for Godot!"); // This should never get printed!
+ ERR_PRINT_ON;
+ CHECK_MESSAGE(_print_error_enabled, "Error printing should be re-enabled.");
+ }
+ TEST_CASE("Stringify Variant types") {
+ Variant var;
+ INFO(var);
+
+ String string("Godot is finally here!");
+ INFO(string);
+
+ Vector2 vec2(0.5, 1.0);
+ INFO(vec2);
+
+ Vector2i vec2i(1, 2);
+ INFO(vec2i);
+
+ Rect2 rect2(0.5, 0.5, 100.5, 100.5);
+ INFO(rect2);
+
+ Rect2i rect2i(0, 0, 100, 100);
+ INFO(rect2i);
+
+ Vector3 vec3(0.5, 1.0, 2.0);
+ INFO(vec3);
+
+ Vector3i vec3i(1, 2, 3);
+ INFO(vec3i);
+
+ Transform2D trans2d(0.5, Vector2(100, 100));
+ INFO(trans2d);
+
+ Plane plane(Vector3(1, 1, 1), 1.0);
+ INFO(plane);
+
+ Quat quat(Vector3(0.5, 1.0, 2.0));
+ INFO(quat);
+
+ AABB aabb(Vector3(), Vector3(100, 100, 100));
+ INFO(aabb);
+
+ Basis basis(quat);
+ INFO(basis);
+
+ Transform trans(basis);
+ INFO(trans);
+
+ Color color(1, 0.5, 0.2, 0.3);
+ INFO(color);
+
+ StringName string_name("has_method");
+ INFO(string_name);
+
+ NodePath node_path("godot/sprite");
+ INFO(node_path);
+
+ INFO(RID());
+
+ Object *obj = memnew(Object);
+ INFO(obj);
+
+ Callable callable(obj, "has_method");
+ INFO(callable);
+
+ Signal signal(obj, "script_changed");
+ INFO(signal);
+
+ memdelete(obj);
+
+ Dictionary dict;
+ dict["string"] = string;
+ dict["color"] = color;
+ INFO(dict);
+
+ Array arr;
+ arr.push_back(string);
+ arr.push_back(color);
+ INFO(arr);
+
+ PackedByteArray byte_arr;
+ byte_arr.push_back(0);
+ byte_arr.push_back(1);
+ byte_arr.push_back(2);
+ INFO(byte_arr);
+
+ PackedInt32Array int32_arr;
+ int32_arr.push_back(0);
+ int32_arr.push_back(1);
+ int32_arr.push_back(2);
+ INFO(int32_arr);
+
+ PackedInt64Array int64_arr;
+ int64_arr.push_back(0);
+ int64_arr.push_back(1);
+ int64_arr.push_back(2);
+ INFO(int64_arr);
+
+ PackedFloat32Array float32_arr;
+ float32_arr.push_back(0.5);
+ float32_arr.push_back(1.5);
+ float32_arr.push_back(2.5);
+ INFO(float32_arr);
+
+ PackedFloat64Array float64_arr;
+ float64_arr.push_back(0.5);
+ float64_arr.push_back(1.5);
+ float64_arr.push_back(2.5);
+ INFO(float64_arr);
+
+ PackedStringArray str_arr = string.split(" ");
+ INFO(str_arr);
+
+ PackedVector2Array vec2_arr;
+ vec2_arr.push_back(Vector2(0, 0));
+ vec2_arr.push_back(Vector2(1, 1));
+ vec2_arr.push_back(Vector2(2, 2));
+ INFO(vec2_arr);
+
+ PackedVector3Array vec3_arr;
+ vec3_arr.push_back(Vector3(0, 0, 0));
+ vec3_arr.push_back(Vector3(1, 1, 1));
+ vec3_arr.push_back(Vector3(2, 2, 2));
+ INFO(vec3_arr);
+
+ PackedColorArray color_arr;
+ color_arr.push_back(Color(0, 0, 0));
+ color_arr.push_back(Color(1, 1, 1));
+ color_arr.push_back(Color(2, 2, 2));
+ INFO(color_arr);
+
+ INFO("doctest insertion operator << "
+ << var << " " << vec2 << " " << rect2 << " " << color);
+
+ CHECK(true); // So all above prints.
+ }
}
#endif // TEST_VALIDATE_TESTING_H
diff --git a/tests/test_variant.h b/tests/test_variant.h
index 06dcfde664..b575f6744d 100644
--- a/tests/test_variant.h
+++ b/tests/test_variant.h
@@ -31,10 +31,10 @@
#ifndef TEST_VARIANT_H
#define TEST_VARIANT_H
-#include "core/variant.h"
-#include "core/variant_parser.h"
+#include "core/variant/variant.h"
+#include "core/variant/variant_parser.h"
-#include "thirdparty/doctest/doctest.h"
+#include "tests/test_macros.h"
namespace TestVariant {
@@ -105,7 +105,6 @@ TEST_CASE("[Variant] Writer and parser float") {
CHECK_MESSAGE(b64_float_parsed == 340282001837565597733306976381245063168.0, "Should not overflow.");
}
-
} // namespace TestVariant
#endif // TEST_VARIANT_H