diff options
Diffstat (limited to 'tests')
-rw-r--r-- | tests/SCsub | 5 | ||||
-rw-r--r-- | tests/test_color.h | 8 | ||||
-rw-r--r-- | tests/test_expression.h | 445 | ||||
-rw-r--r-- | tests/test_gdscript.cpp | 187 | ||||
-rw-r--r-- | tests/test_gradient.h | 152 | ||||
-rw-r--r-- | tests/test_list.h | 279 | ||||
-rw-r--r-- | tests/test_macros.cpp (renamed from tests/test_gdscript.h) | 28 | ||||
-rw-r--r-- | tests/test_macros.h | 16 | ||||
-rw-r--r-- | tests/test_main.cpp | 56 | ||||
-rw-r--r-- | tests/test_math.cpp | 8 | ||||
-rw-r--r-- | tests/test_shader_lang.cpp | 2 | ||||
-rw-r--r-- | tests/test_string.h | 570 |
12 files changed, 1492 insertions, 264 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/test_color.h b/tests/test_color.h index 3633f2746d..dfdc29ec7d 100644 --- a/tests/test_color.h +++ b/tests/test_color.h @@ -39,9 +39,7 @@ namespace TestColor { TEST_CASE("[Color] Constructor methods") { const Color blue_rgba = Color(0.25098, 0.376471, 1, 0.501961); - // HTML currently uses ARGB notation, which is contrary to the CSS standard. - // This may be changed to RGBA in 4.0. - const Color blue_html = Color::html("#804060ff"); + const Color blue_html = Color::html("#4060ff80"); const Color blue_hex = Color::hex(0x4060ff80); const Color blue_hex64 = Color::hex64(0x4040'6060'ffff'8080); @@ -118,10 +116,10 @@ TEST_CASE("[Color] Conversion methods") { const Color cyan_transparent = Color(0, 1, 1, 0); CHECK_MESSAGE( - cyan.to_html() == "ff00ffff", + cyan.to_html() == "00ffffff", "The returned RGB HTML color code should match the expected value."); CHECK_MESSAGE( - cyan_transparent.to_html() == "0000ffff", + cyan_transparent.to_html() == "00ffff00", "The returned RGBA HTML color code should match the expected value."); CHECK_MESSAGE( cyan.to_argb32() == 0xff00ffff, diff --git a/tests/test_expression.h b/tests/test_expression.h new file mode 100644 index 0000000000..a3d4877d52 --- /dev/null +++ b/tests/test_expression.h @@ -0,0 +1,445 @@ +/*************************************************************************/ +/* 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_zero_approx(float(expression.execute())), + "`-25.4 / 0` should return 0."); + 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_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..88fe06b3ec --- /dev/null +++ b/tests/test_gradient.h @@ -0,0 +1,152 @@ +/*************************************************************************/ +/* 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/class_db.h" +#include "core/color.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_list.h b/tests/test_list.h new file mode 100644 index 0000000000..7412fbc3c8 --- /dev/null +++ b/tests/test_list.h @@ -0,0 +1,279 @@ +/*************************************************************************/ +/* 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/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] 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_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 index 45ba8581dd..3486c68bb7 100644 --- a/tests/test_macros.h +++ b/tests/test_macros.h @@ -31,6 +31,9 @@ #ifndef TEST_MACROS_H #define TEST_MACROS_H +#include "core/map.h" +#include "core/variant.h" + // See documentation for doctest at: // https://github.com/onqtam/doctest/blob/master/doc/markdown/readme.md#reference #include "thirdparty/doctest/doctest.h" @@ -104,4 +107,17 @@ 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 137882841c..f0dec22738 100644 --- a/tests/test_main.cpp +++ b/tests/test_main.cpp @@ -36,8 +36,10 @@ #include "test_basis.h" #include "test_class_db.h" #include "test_color.h" -#include "test_gdscript.h" +#include "test_expression.h" +#include "test_gradient.h" #include "test_gui.h" +#include "test_list.h" #include "test_math.h" #include "test_oa_hash_map.h" #include "test_ordered_hash_map.h" @@ -54,40 +56,64 @@ #include "tests/test_macros.h" int test_main(int argc, char *argv[]) { + bool run_tests = true; + + // Convert arguments to Godot's command-line. + List<String> args; + + 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; 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++) { + 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 = valid_arguments[x].utf8(); + CharString cs = test_args[x].utf8(); const char *str = cs.get_data(); // Allocate the string copy. - args[x] = new char[strlen(str) + 1]; + doctest_args[x] = new char[strlen(str) + 1]; // Copy this into memory. - std::memcpy(args[x], str, strlen(str) + 1); + 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); - for (int x = 0; x < valid_arguments.size(); x++) { - delete[] args[x]; + for (int x = 0; x < test_args.size(); x++) { + delete[] doctest_args[x]; } - delete[] args; + delete[] doctest_args; return test_context.run(); } diff --git a/tests/test_math.cpp b/tests/test_math.cpp index 84a85be2f6..862535b57e 100644 --- a/tests/test_math.cpp +++ b/tests/test_math.cpp @@ -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; diff --git a/tests/test_shader_lang.cpp b/tests/test_shader_lang.cpp index 34ee3e3210..d363ee22b5 100644 --- a/tests/test_shader_lang.cpp +++ b/tests/test_shader_lang.cpp @@ -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; } diff --git a/tests/test_string.h b/tests/test_string.h index 22019a64c6..b041cb2f49 100644 --- a/tests/test_string.h +++ b/tests/test_string.h @@ -48,36 +48,159 @@ 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 +208,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 +216,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 +228,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 +255,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 +305,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 +354,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 +371,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 +392,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,6 +406,69 @@ 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()); @@ -239,7 +486,7 @@ TEST_CASE("[String] Regex substitution") { struct test_27_data { char const *data; - char const *begin; + char const *part; bool expected; }; @@ -253,9 +500,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 +513,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 +843,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,7 +1107,196 @@ 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 #endif // TEST_STRING_H |