initial commit, 4.5 stable
Some checks failed
🔗 GHA / 📊 Static checks (push) Has been cancelled
🔗 GHA / 🤖 Android (push) Has been cancelled
🔗 GHA / 🍏 iOS (push) Has been cancelled
🔗 GHA / 🐧 Linux (push) Has been cancelled
🔗 GHA / 🍎 macOS (push) Has been cancelled
🔗 GHA / 🏁 Windows (push) Has been cancelled
🔗 GHA / 🌐 Web (push) Has been cancelled

This commit is contained in:
2025-09-16 20:46:46 -04:00
commit 9d30169a8d
13378 changed files with 7050105 additions and 0 deletions

View File

@@ -0,0 +1,898 @@
/**************************************************************************/
/* test_class_db.h */
/**************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/**************************************************************************/
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
/* */
/* 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. */
/**************************************************************************/
#pragma once
#include "core/core_bind.h"
#include "core/core_constants.h"
#include "core/object/class_db.h"
#include "tests/test_macros.h"
namespace TestClassDB {
struct TypeReference {
StringName name;
bool is_enum = false;
};
struct ConstantData {
String name;
int64_t 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;
int position;
};
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_ref_counted = 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 PropertyData &E : properties) {
if (E.name == p_name) {
return &E;
}
}
return nullptr;
}
const MethodData *find_method_by_name(const StringName &p_name) const {
for (const MethodData &E : methods) {
if (E.name == p_name) {
return &E;
}
}
return nullptr;
}
};
struct NamesCache {
StringName variant_type = StringName("Variant");
StringName object_class = StringName("Object");
StringName ref_counted_class = StringName("RefCounted");
StringName string_type = StringName("String");
StringName string_name_type = StringName("StringName");
StringName node_path_type = StringName("NodePath");
StringName bool_type = StringName("bool");
StringName int_type = StringName("int");
StringName float_type = StringName("float");
StringName void_type = StringName("void");
StringName vararg_stub_type = StringName("@VarArg@");
StringName vector2_type = StringName("Vector2");
StringName rect2_type = StringName("Rect2");
StringName vector3_type = StringName("Vector3");
StringName vector4_type = StringName("Vector4");
// Object not included as it must be checked for all derived classes
static constexpr int nullable_types_count = 18;
StringName nullable_types[nullable_types_count] = {
string_type,
string_name_type,
node_path_type,
StringName(_STR(Array)),
StringName(_STR(Dictionary)),
StringName(_STR(Callable)),
StringName(_STR(Signal)),
StringName(_STR(PackedByteArray)),
StringName(_STR(PackedInt32Array)),
StringName(_STR(PackedInt64rray)),
StringName(_STR(PackedFloat32Array)),
StringName(_STR(PackedFloat64Array)),
StringName(_STR(PackedStringArray)),
StringName(_STR(PackedVector2Array)),
StringName(_STR(PackedVector3Array)),
StringName(_STR(PackedColorArray)),
StringName(_STR(PackedVector4Array)),
};
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 HashMap<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::ConstIterator elem = exposed_classes.find(p_name);
return elem ? &elem->value : nullptr;
}
const ExposedClass *find_exposed_class(const TypeReference &p_type_ref) const {
ExposedClasses::ConstIterator 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.has(p_type_ref.name)) {
return true;
}
if (p_type_ref.is_enum) {
if (enum_types.has(p_type_ref.name)) {
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::TRANSFORM3D:
case Variant::TRANSFORM2D:
case Variant::BASIS:
case Variant::QUATERNION:
case Variant::PLANE:
case Variant::AABB:
case Variant::COLOR:
case Variant::VECTOR2:
case Variant::RECT2:
case Variant::VECTOR3:
case Variant::VECTOR4:
case Variant::PROJECTION:
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::PACKED_VECTOR4_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());
case Variant::VECTOR4I:
return p_arg_type.name == p_context.names_cache.vector4_type ||
p_arg_type.name == Variant::get_type_name(p_val.get_type());
case Variant::VARIANT_MAX:
break;
}
if (r_err_msg) {
*r_err_msg = "Unexpected Variant type: " + itos(p_val.get_type());
}
return false;
}
bool arg_default_value_is_valid_data(const Variant &p_val, String *r_err_msg = nullptr) {
switch (p_val.get_type()) {
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::PACKED_VECTOR4_ARRAY:
case Variant::CALLABLE:
case Variant::SIGNAL:
case Variant::OBJECT:
if (p_val.is_zero()) {
return true;
}
if (r_err_msg) {
*r_err_msg = "Must be zero.";
}
break;
default:
return true;
}
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) {
TEST_FAIL(
"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), "'.");
if (p_class.api_type == ClassDB::API_CORE) {
TEST_COND(prop_class->api_type == ClassDB::API_EDITOR,
"Property '", p_class.name, ".", p_prop.name, "' has type '", prop_class->name,
"' from the editor API. Core API cannot have dependencies on the editor API.");
}
} else {
// Look for types that don't inherit Object
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.has(idx_arg.type.name),
"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.has(idx_arg.type.name),
"Invalid type '", idx_arg.type.name, "' for index argument of property setter: '", p_class.name, ".", String(p_prop.name), "'.");
}
}
}
}
void validate_argument(const Context &p_context, const ExposedClass &p_class, const String &p_owner_name, const String &p_owner_type, const ArgumentData &p_arg) {
#ifdef DEBUG_ENABLED
TEST_COND((p_arg.name.is_empty() || p_arg.name.begins_with("_unnamed_arg")),
vformat("Unnamed argument in position %d of %s '%s.%s'.", p_arg.position, p_owner_type, p_class.name, p_owner_name));
TEST_FAIL_COND((p_arg.name != "@varargs@" && !p_arg.name.is_valid_ascii_identifier()),
vformat("Invalid argument name '%s' of %s '%s.%s'.", p_arg.name, p_owner_type, p_class.name, p_owner_name));
#endif // DEBUG_ENABLED
const ExposedClass *arg_class = p_context.find_exposed_class(p_arg.type);
if (arg_class) {
TEST_COND(arg_class->is_singleton,
vformat("Argument type is a singleton: '%s' of %s '%s.%s'.", p_arg.name, p_owner_type, p_class.name, p_owner_name));
if (p_class.api_type == ClassDB::API_CORE) {
TEST_COND(arg_class->api_type == ClassDB::API_EDITOR,
vformat("Argument '%s' of %s '%s.%s' has type '%s' from the editor API. Core API cannot have dependencies on the editor API.",
p_arg.name, p_owner_type, p_class.name, p_owner_name, arg_class->name));
}
} else {
// Look for types that don't inherit Object.
TEST_FAIL_COND(!p_context.has_type(p_arg.type),
vformat("Argument type '%s' not found: '%s' of %s '%s.%s'.", p_arg.type.name, p_arg.name, p_owner_type, p_class.name, p_owner_name));
}
if (p_arg.has_defval) {
String type_error_msg;
bool arg_defval_assignable_to_type = arg_default_value_is_assignable_to_type(p_context, p_arg.defval, p_arg.type, &type_error_msg);
String err_msg = vformat("Invalid default value for parameter '%s' of %s '%s.%s'.", p_arg.name, p_owner_type, p_class.name, p_owner_name);
if (!type_error_msg.is_empty()) {
err_msg += " " + type_error_msg;
}
TEST_COND(!arg_defval_assignable_to_type, err_msg);
bool arg_defval_valid_data = arg_default_value_is_valid_data(p_arg.defval, &type_error_msg);
if (!type_error_msg.is_empty()) {
err_msg += " " + type_error_msg;
}
TEST_COND(!arg_defval_valid_data, err_msg);
}
}
void validate_method(const Context &p_context, const ExposedClass &p_class, const MethodData &p_method) {
if (p_method.return_type.name != StringName()) {
const ExposedClass *return_class = p_context.find_exposed_class(p_method.return_type);
if (return_class) {
if (p_class.api_type == ClassDB::API_CORE) {
TEST_COND(return_class->api_type == ClassDB::API_EDITOR,
"Method '", p_class.name, ".", p_method.name, "' has return type '", return_class->name,
"' from the editor API. Core API cannot have dependencies on the editor API.");
}
} else {
// Look for types that don't inherit Object
TEST_FAIL_COND(!p_context.has_type(p_method.return_type),
"Method return type '", p_method.return_type.name, "' not found: '", p_class.name, ".", p_method.name, "'.");
}
}
for (const ArgumentData &F : p_method.arguments) {
const ArgumentData &arg = F;
validate_argument(p_context, p_class, p_method.name, "method", arg);
}
}
void validate_signal(const Context &p_context, const ExposedClass &p_class, const SignalData &p_signal) {
for (const ArgumentData &F : p_signal.arguments) {
const ArgumentData &arg = F;
validate_argument(p_context, p_class, p_signal.name, "signal", arg);
}
}
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 PropertyData &F : p_exposed_class.properties) {
validate_property(p_context, p_exposed_class, F);
}
for (const MethodData &F : p_exposed_class.methods) {
validate_method(p_context, p_exposed_class, F);
}
for (const SignalData &F : p_exposed_class.signals_) {
validate_signal(p_context, p_exposed_class, F);
}
}
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)) {
INFO(vformat("Ignoring class '%s' because it's not exposed.", class_name));
class_list.pop_front();
continue;
}
if (!ClassDB::is_class_enabled(class_name)) {
INFO(vformat("Ignoring class '%s' because it's not enabled.", class_name));
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_ref_counted = ClassDB::is_parent_class(class_name, "RefCounted");
exposed_class.base = ClassDB::get_parent_class(class_name);
// Add properties
List<PropertyInfo> property_list;
ClassDB::get_property_list(class_name, &property_list, true);
HashMap<StringName, StringName> accessor_methods;
for (const PropertyInfo &property : property_list) {
if (property.usage & PROPERTY_USAGE_GROUP || property.usage & PROPERTY_USAGE_SUBGROUP || property.usage & PROPERTY_USAGE_CATEGORY || (property.type == Variant::NIL && property.usage & PROPERTY_USAGE_ARRAY)) {
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 (const MethodInfo &E : method_list) {
const MethodInfo &method_info = E;
if (method_info.name.is_empty()) {
continue;
}
MethodData method;
method.name = method_info.name;
TEST_FAIL_COND(!String(method.name).is_valid_ascii_identifier(),
"Method name is not a valid identifier: '", exposed_class.name, ".", method.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);
} else if (return_info.type == Variant::INT && return_info.usage & (PROPERTY_USAGE_CLASS_IS_ENUM | PROPERTY_USAGE_CLASS_IS_BITFIELD)) {
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.ref_counted_class);
TEST_COND(bad_reference_hint, "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 (int64_t i = 0; i < method_info.arguments.size(); ++i) {
const PropertyInfo &arg_info = method_info.arguments[i];
String orig_arg_name = arg_info.name;
ArgumentData arg;
arg.name = orig_arg_name;
arg.position = i;
if (arg_info.type == Variant::INT && arg_info.usage & (PROPERTY_USAGE_CLASS_IS_ENUM | PROPERTY_USAGE_CLASS_IS_BITFIELD)) {
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), "'.");
// Methods starting with an underscore are ignored unless they're virtual or used as a property setter or getter.
if (!method.is_virtual && String(method.name)[0] == '_') {
for (const PropertyData &F : exposed_class.properties) {
const PropertyData &prop = F;
if (prop.setter == method.name || prop.getter == method.name) {
exposed_class.methods.push_back(method);
break;
}
}
} else {
exposed_class.methods.push_back(method);
}
if (method.is_virtual) {
TEST_COND(String(method.name)[0] != '_', "Virtual method ", String(method.name), " does not start with underscore.");
}
}
// Add signals
const HashMap<StringName, MethodInfo> &signal_map = class_info->signal_map;
for (const KeyValue<StringName, MethodInfo> &K : signal_map) {
SignalData signal;
const MethodInfo &method_info = signal_map.get(K.key);
signal.name = method_info.name;
TEST_FAIL_COND(!String(signal.name).is_valid_ascii_identifier(),
"Signal name is not a valid identifier: '", exposed_class.name, ".", signal.name, "'.");
for (int64_t i = 0; i < method_info.arguments.size(); ++i) {
const PropertyInfo &arg_info = method_info.arguments[i];
String orig_arg_name = arg_info.name;
ArgumentData arg;
arg.name = orig_arg_name;
arg.position = i;
if (arg_info.type == Variant::INT && arg_info.usage & (PROPERTY_USAGE_CLASS_IS_ENUM | PROPERTY_USAGE_CLASS_IS_BITFIELD)) {
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);
String warn_msg = vformat(
"Signal name conflicts with %s: '%s.%s.",
method_conflict ? "method" : "property", class_name, signal.name);
TEST_FAIL_COND((method_conflict || exposed_class.find_method_by_name(signal.name)),
warn_msg);
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, ClassDB::ClassInfo::EnumInfo> &enum_map = class_info->enum_map;
for (const KeyValue<StringName, ClassDB::ClassInfo::EnumInfo> &K : enum_map) {
EnumData enum_;
enum_.name = K.key;
for (const StringName &E : K.value.constants) {
const StringName &constant_name = E;
TEST_FAIL_COND(String(constant_name).contains("::"),
"Enum constant contains '::', check bindings to remove the scope: '",
String(class_name), ".", String(enum_.name), ".", String(constant_name), "'.");
int64_t *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.key));
}
for (const String &E : constants) {
const String &constant_name = E;
TEST_FAIL_COND(constant_name.contains("::"),
"Constant contains '::', check bindings to remove the scope: '",
String(class_name), ".", constant_name, "'.");
int64_t *value = class_info->constant_map.getptr(StringName(E));
TEST_FAIL_COND(!value, "Missing 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 (const EnumData &E : r_context.global_enums) {
r_context.enum_types.push_back(E.name);
}
}
for (int i = 0; i < Variant::VARIANT_MAX; i++) {
if (i == Variant::OBJECT) {
continue;
}
const Variant::Type type = Variant::Type(i);
List<StringName> enum_names;
Variant::get_enums_for_type(type, &enum_names);
for (const StringName &enum_name : enum_names) {
r_context.enum_types.push_back(Variant::get_type_name(type) + "." + enum_name);
}
}
}
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] Validate exposed classes") {
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 (const KeyValue<StringName, ExposedClass> &E : context.exposed_classes) {
validate_class(context, E.value);
}
}
}
}
} // namespace TestClassDB

View File

@@ -0,0 +1,174 @@
/**************************************************************************/
/* test_method_bind.h */
/**************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/**************************************************************************/
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
/* */
/* 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. */
/**************************************************************************/
#pragma once
#include "core/object/class_db.h"
#include "tests/test_macros.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_METHOD_OBJECT_CAST,
TEST_MAX
};
class ObjectSubclass : public Object {
GDSOFTCLASS(ObjectSubclass, Object);
public:
int value = 1;
};
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
}
void test_method_object_cast(ObjectSubclass *p_object) {
test_valid[TEST_METHOD_OBJECT_CAST] = p_object->value == 1;
}
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));
ClassDB::bind_method(D_METHOD("test_method_object_cast", "object"), &MethodBindTester::test_method_object_cast);
}
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);
ObjectSubclass *obj = memnew(ObjectSubclass);
call("test_method_object_cast", obj);
memdelete(obj);
}
};
TEST_CASE("[MethodBind] check all method binds") {
MethodBindTester *mbt = memnew(MethodBindTester);
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]);
CHECK(mbt->test_valid[MethodBindTester::TEST_METHOD_OBJECT_CAST]);
memdelete(mbt);
}
} // namespace TestMethodBind

View File

@@ -0,0 +1,597 @@
/**************************************************************************/
/* test_object.h */
/**************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/**************************************************************************/
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
/* */
/* 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. */
/**************************************************************************/
#pragma once
#include "core/object/class_db.h"
#include "core/object/object.h"
#include "core/object/script_language.h"
#include "tests/test_macros.h"
#ifdef SANITIZERS_ENABLED
#ifdef __has_feature
#if __has_feature(address_sanitizer) || __has_feature(thread_sanitizer)
#define ASAN_OR_TSAN_ENABLED
#endif
#elif defined(__SANITIZE_ADDRESS__) || defined(__SANITIZE_THREAD__)
#define ASAN_OR_TSAN_ENABLED
#endif
#endif
// Declared in global namespace because of GDCLASS macro warning (Windows):
// "Unqualified friend declaration referring to type outside of the nearest enclosing namespace
// is a Microsoft extension; add a nested name specifier".
class _TestDerivedObject : public Object {
GDCLASS(_TestDerivedObject, Object);
int property_value;
protected:
static void _bind_methods() {
ClassDB::bind_method(D_METHOD("set_property", "property"), &_TestDerivedObject::set_property);
ClassDB::bind_method(D_METHOD("get_property"), &_TestDerivedObject::get_property);
ADD_PROPERTY(PropertyInfo(Variant::INT, "property"), "set_property", "get_property");
}
public:
void set_property(int value) { property_value = value; }
int get_property() const { return property_value; }
};
namespace TestObject {
class _MockScriptInstance : public ScriptInstance {
StringName property_name = "NO_NAME";
Variant property_value;
public:
bool set(const StringName &p_name, const Variant &p_value) override {
property_name = p_name;
property_value = p_value;
return true;
}
bool get(const StringName &p_name, Variant &r_ret) const override {
if (property_name == p_name) {
r_ret = property_value;
return true;
}
return false;
}
void get_property_list(List<PropertyInfo> *p_properties) const override {
}
Variant::Type get_property_type(const StringName &p_name, bool *r_is_valid) const override {
return Variant::PACKED_FLOAT32_ARRAY;
}
virtual void validate_property(PropertyInfo &p_property) const override {
}
bool property_can_revert(const StringName &p_name) const override {
return false;
}
bool property_get_revert(const StringName &p_name, Variant &r_ret) const override {
return false;
}
void get_method_list(List<MethodInfo> *p_list) const override {
}
bool has_method(const StringName &p_method) const override {
return false;
}
int get_method_argument_count(const StringName &p_method, bool *r_is_valid = nullptr) const override {
if (r_is_valid) {
*r_is_valid = false;
}
return 0;
}
Variant callp(const StringName &p_method, const Variant **p_args, int p_argcount, Callable::CallError &r_error) override {
return Variant();
}
void notification(int p_notification, bool p_reversed = false) override {
}
Ref<Script> get_script() const override {
return Ref<Script>();
}
const Variant get_rpc_config() const override {
return Variant();
}
ScriptLanguage *get_language() override {
return nullptr;
}
};
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 = "complex_metadata_path";
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<StringName> 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<StringName> 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.");
Object other;
object.set_meta("conflicting_meta", "string");
object.set_meta("not_conflicting_meta", 123);
other.set_meta("conflicting_meta", Color(0, 1, 0));
other.set_meta("other_meta", "other");
object.merge_meta_from(&other);
CHECK_MESSAGE(
Color(object.get_meta("conflicting_meta")).is_equal_approx(Color(0, 1, 0)),
"String meta should be overwritten with Color after merging.");
CHECK_MESSAGE(
int(object.get_meta("not_conflicting_meta")) == 123,
"Not conflicting meta on destination should be kept intact.");
CHECK_MESSAGE(
object.get_meta("other_meta", String()) == "other",
"Not conflicting meta name on source should merged.");
List<StringName> meta_list3;
object.get_meta_list(&meta_list3);
CHECK_MESSAGE(
meta_list3.size() == 3,
"The metadata list should contain 3 items after merging meta from two objects.");
}
TEST_CASE("[Object] Construction") {
Object object;
CHECK_MESSAGE(
!object.is_ref_counted(),
"Object is not a RefCounted.");
Object *p_db = ObjectDB::get_instance(object.get_instance_id());
CHECK_MESSAGE(
p_db == &object,
"The database pointer returned by the object id should reference same object.");
}
TEST_CASE("[Object] Script instance property setter") {
Object object;
_MockScriptInstance *script_instance = memnew(_MockScriptInstance);
object.set_script_instance(script_instance);
bool valid = false;
object.set("some_name", 100, &valid);
CHECK(valid);
Variant actual_value;
CHECK_MESSAGE(
script_instance->get("some_name", actual_value),
"The assigned script instance should successfully retrieve value by name.");
CHECK_MESSAGE(
actual_value == Variant(100),
"The returned value should equal the one which was set by the object.");
}
TEST_CASE("[Object] Script instance property getter") {
Object object;
_MockScriptInstance *script_instance = memnew(_MockScriptInstance);
script_instance->set("some_name", 100); // Make sure script instance has the property
object.set_script_instance(script_instance);
bool valid = false;
const Variant &actual_value = object.get("some_name", &valid);
CHECK(valid);
CHECK_MESSAGE(
actual_value == Variant(100),
"The returned value should equal the one which was set by the script instance.");
}
TEST_CASE("[Object] Built-in property setter") {
GDREGISTER_CLASS(_TestDerivedObject);
_TestDerivedObject derived_object;
bool valid = false;
derived_object.set("property", 100, &valid);
CHECK(valid);
CHECK_MESSAGE(
derived_object.get_property() == 100,
"The property value should equal the one which was set with built-in setter.");
}
TEST_CASE("[Object] Built-in property getter") {
GDREGISTER_CLASS(_TestDerivedObject);
_TestDerivedObject derived_object;
derived_object.set_property(100);
bool valid = false;
const Variant &actual_value = derived_object.get("property", &valid);
CHECK(valid);
CHECK_MESSAGE(
actual_value == Variant(100),
"The returned value should equal the one which was set with built-in setter.");
}
TEST_CASE("[Object] Script property setter") {
Object object;
Variant script;
bool valid = false;
object.set(CoreStringName(script), script, &valid);
CHECK(valid);
CHECK_MESSAGE(
object.get_script() == script,
"The object script should be equal to the assigned one.");
}
TEST_CASE("[Object] Script property getter") {
Object object;
Variant script;
object.set_script(script);
bool valid = false;
const Variant &actual_value = object.get(CoreStringName(script), &valid);
CHECK(valid);
CHECK_MESSAGE(
actual_value == script,
"The returned value should be equal to the assigned script.");
}
TEST_CASE("[Object] Absent name setter") {
Object object;
bool valid = true;
object.set("absent_name", 100, &valid);
CHECK(!valid);
}
TEST_CASE("[Object] Absent name getter") {
Object object;
bool valid = true;
const Variant &actual_value = object.get("absent_name", &valid);
CHECK(!valid);
CHECK_MESSAGE(
actual_value == Variant(),
"The returned value should equal nil variant.");
}
TEST_CASE("[Object] Signals") {
Object object;
CHECK_FALSE(object.has_signal("my_custom_signal"));
List<MethodInfo> signals_before;
object.get_signal_list(&signals_before);
object.add_user_signal(MethodInfo("my_custom_signal"));
CHECK(object.has_signal("my_custom_signal"));
List<MethodInfo> signals_after;
object.get_signal_list(&signals_after);
// Should be one more signal.
CHECK_EQ(signals_before.size() + 1, signals_after.size());
SUBCASE("Adding the same user signal again should not have any effect") {
CHECK(object.has_signal("my_custom_signal"));
ERR_PRINT_OFF;
object.add_user_signal(MethodInfo("my_custom_signal"));
ERR_PRINT_ON;
CHECK(object.has_signal("my_custom_signal"));
List<MethodInfo> signals_after_existing_added;
object.get_signal_list(&signals_after_existing_added);
CHECK_EQ(signals_after.size(), signals_after_existing_added.size());
}
SUBCASE("Trying to add a preexisting signal should not have any effect") {
CHECK(object.has_signal("script_changed"));
ERR_PRINT_OFF;
object.add_user_signal(MethodInfo("script_changed"));
ERR_PRINT_ON;
CHECK(object.has_signal("script_changed"));
List<MethodInfo> signals_after_existing_added;
object.get_signal_list(&signals_after_existing_added);
CHECK_EQ(signals_after.size(), signals_after_existing_added.size());
}
SUBCASE("Adding an empty signal should not have any effect") {
CHECK_FALSE(object.has_signal(""));
ERR_PRINT_OFF;
object.add_user_signal(MethodInfo(""));
ERR_PRINT_ON;
CHECK_FALSE(object.has_signal(""));
List<MethodInfo> signals_after_empty_added;
object.get_signal_list(&signals_after_empty_added);
CHECK_EQ(signals_after.size(), signals_after_empty_added.size());
}
SUBCASE("Deleting an object with connected signals should disconnect them") {
List<Object::Connection> signal_connections;
{
Object target;
target.add_user_signal(MethodInfo("my_custom_signal"));
ERR_PRINT_OFF;
target.connect("nonexistent_signal1", callable_mp(&object, &Object::notify_property_list_changed));
target.connect("my_custom_signal", callable_mp(&object, &Object::notify_property_list_changed));
target.connect("nonexistent_signal2", callable_mp(&object, &Object::notify_property_list_changed));
ERR_PRINT_ON;
signal_connections.clear();
object.get_all_signal_connections(&signal_connections);
CHECK(signal_connections.size() == 0);
signal_connections.clear();
object.get_signals_connected_to_this(&signal_connections);
CHECK(signal_connections.size() == 1);
ERR_PRINT_OFF;
object.connect("nonexistent_signal1", callable_mp(&target, &Object::notify_property_list_changed));
object.connect("my_custom_signal", callable_mp(&target, &Object::notify_property_list_changed));
object.connect("nonexistent_signal2", callable_mp(&target, &Object::notify_property_list_changed));
ERR_PRINT_ON;
signal_connections.clear();
object.get_all_signal_connections(&signal_connections);
CHECK(signal_connections.size() == 1);
signal_connections.clear();
object.get_signals_connected_to_this(&signal_connections);
CHECK(signal_connections.size() == 1);
}
signal_connections.clear();
object.get_all_signal_connections(&signal_connections);
CHECK(signal_connections.size() == 0);
signal_connections.clear();
object.get_signals_connected_to_this(&signal_connections);
CHECK(signal_connections.size() == 0);
}
SUBCASE("Emitting a non existing signal will return an error") {
Error err = object.emit_signal("some_signal");
CHECK(err == ERR_UNAVAILABLE);
}
SUBCASE("Emitting an existing signal should call the connected method") {
Array empty_signal_args = { {} };
SIGNAL_WATCH(&object, "my_custom_signal");
SIGNAL_CHECK_FALSE("my_custom_signal");
Error err = object.emit_signal("my_custom_signal");
CHECK(err == OK);
SIGNAL_CHECK("my_custom_signal", empty_signal_args);
SIGNAL_UNWATCH(&object, "my_custom_signal");
}
SUBCASE("Connecting and then disconnecting many signals should not leave anything behind") {
List<Object::Connection> signal_connections;
Object targets[100];
for (int i = 0; i < 10; i++) {
ERR_PRINT_OFF;
for (Object &target : targets) {
object.connect("my_custom_signal", callable_mp(&target, &Object::notify_property_list_changed));
}
ERR_PRINT_ON;
signal_connections.clear();
object.get_all_signal_connections(&signal_connections);
CHECK(signal_connections.size() == 100);
}
for (Object &target : targets) {
object.disconnect("my_custom_signal", callable_mp(&target, &Object::notify_property_list_changed));
}
signal_connections.clear();
object.get_all_signal_connections(&signal_connections);
CHECK(signal_connections.size() == 0);
}
}
class NotificationObjectSuperclass : public Object {
GDCLASS(NotificationObjectSuperclass, Object);
protected:
void _notification(int p_what) {
order_superclass = ++order_global;
}
public:
static inline int order_global = 0;
int order_superclass = -1;
};
class NotificationObjectSubclass : public NotificationObjectSuperclass {
GDCLASS(NotificationObjectSubclass, NotificationObjectSuperclass);
protected:
void _notification(int p_what) {
order_subclass = ++order_global;
}
public:
int order_subclass = -1;
};
class NotificationScriptInstance : public _MockScriptInstance {
void notification(int p_notification, bool p_reversed) override {
order_script = ++NotificationObjectSuperclass::order_global;
}
public:
int order_script = -1;
};
TEST_CASE("[Object] Notification order") { // GH-52325
NotificationObjectSubclass *object = memnew(NotificationObjectSubclass);
NotificationScriptInstance *script = memnew(NotificationScriptInstance);
object->set_script_instance(script);
SUBCASE("regular order") {
NotificationObjectSubclass::order_global = 0;
object->order_superclass = -1;
object->order_subclass = -1;
script->order_script = -1;
object->notification(12345, false);
CHECK_EQ(object->order_superclass, 1);
CHECK_EQ(object->order_subclass, 2);
// TODO If an extension is attached, it should come here.
CHECK_EQ(script->order_script, 3);
CHECK_EQ(NotificationObjectSubclass::order_global, 3);
}
SUBCASE("reverse order") {
NotificationObjectSubclass::order_global = 0;
object->order_superclass = -1;
object->order_subclass = -1;
script->order_script = -1;
object->notification(12345, true);
CHECK_EQ(script->order_script, 1);
// TODO If an extension is attached, it should come here.
CHECK_EQ(object->order_subclass, 2);
CHECK_EQ(object->order_superclass, 3);
CHECK_EQ(NotificationObjectSubclass::order_global, 3);
}
memdelete(object);
}
TEST_CASE("[Object] Destruction at the end of the call chain is safe") {
Object *object = memnew(Object);
ObjectID obj_id = object->get_instance_id();
class _SelfDestroyingScriptInstance : public _MockScriptInstance {
Object *self = nullptr;
// This has to be static because ~Object() also destroys the script instance.
static void free_self(Object *p_self) {
#if defined(ASAN_OR_TSAN_ENABLED)
// Regular deletion is enough becausa asan/tsan will catch a potential heap-after-use.
memdelete(p_self);
#else
// Without asan/tsan, try at least to force a crash by replacing the otherwise seemingly good data with garbage.
// Operations such as dereferencing pointers or decreasing a refcount would fail.
// Unfortunately, we may not poison the memory after the deletion, because the memory would no longer belong to us
// and on doing so we may cause a more generalized crash on some platforms (allocator implementations).
p_self->~Object();
memset((void *)p_self, 0, sizeof(Object));
Memory::free_static(p_self, false);
#endif
}
public:
Variant callp(const StringName &p_method, const Variant **p_args, int p_argcount, Callable::CallError &r_error) override {
free_self(self);
return Variant();
}
Variant call_const(const StringName &p_method, const Variant **p_args, int p_argcount, Callable::CallError &r_error) override {
free_self(self);
return Variant();
}
bool has_method(const StringName &p_method) const override {
return p_method == "some_method";
}
public:
_SelfDestroyingScriptInstance(Object *p_self) :
self(p_self) {}
};
_SelfDestroyingScriptInstance *script_instance = memnew(_SelfDestroyingScriptInstance(object));
object->set_script_instance(script_instance);
SUBCASE("Within callp()") {
SUBCASE("Through call()") {
object->call("some_method");
}
SUBCASE("Through callv()") {
object->callv("some_method", Array());
}
}
SUBCASE("Within call_const()") {
Callable::CallError call_error;
object->call_const("some_method", nullptr, 0, call_error);
}
SUBCASE("Within signal handling (from emit_signalp(), through emit_signal())") {
Object emitter;
emitter.add_user_signal(MethodInfo("some_signal"));
emitter.connect("some_signal", Callable(object, "some_method"));
emitter.emit_signal("some_signal");
}
CHECK_MESSAGE(
ObjectDB::get_instance(obj_id) == nullptr,
"Object was tail-deleted without crashes.");
}
} // namespace TestObject

View File

@@ -0,0 +1,199 @@
/**************************************************************************/
/* test_undo_redo.h */
/**************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/**************************************************************************/
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
/* */
/* 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. */
/**************************************************************************/
#pragma once
#include "core/object/undo_redo.h"
#include "tests/test_macros.h"
// Declared in global namespace because of GDCLASS macro warning (Windows):
// "Unqualified friend declaration referring to type outside of the nearest enclosing namespace
// is a Microsoft extension; add a nested name specifier".
class _TestUndoRedoObject : public Object {
GDCLASS(_TestUndoRedoObject, Object);
int property_value = 0;
protected:
static void _bind_methods() {
ClassDB::bind_method(D_METHOD("set_property", "property"), &_TestUndoRedoObject::set_property);
ClassDB::bind_method(D_METHOD("get_property"), &_TestUndoRedoObject::get_property);
ADD_PROPERTY(PropertyInfo(Variant::INT, "property"), "set_property", "get_property");
}
public:
void set_property(int value) { property_value = value; }
int get_property() const { return property_value; }
void add_to_property(int value) { property_value += value; }
void subtract_from_property(int value) { property_value -= value; }
};
namespace TestUndoRedo {
void set_property_action(UndoRedo *undo_redo, const String &name, _TestUndoRedoObject *test_object, int value, UndoRedo::MergeMode merge_mode = UndoRedo::MERGE_DISABLE) {
undo_redo->create_action(name, merge_mode);
undo_redo->add_do_property(test_object, "property", value);
undo_redo->add_undo_property(test_object, "property", test_object->get_property());
undo_redo->commit_action();
}
void increment_property_action(UndoRedo *undo_redo, const String &name, _TestUndoRedoObject *test_object, int value, UndoRedo::MergeMode merge_mode = UndoRedo::MERGE_DISABLE) {
undo_redo->create_action(name, merge_mode);
undo_redo->add_do_method(callable_mp(test_object, &_TestUndoRedoObject::add_to_property).bind(value));
undo_redo->add_undo_method(callable_mp(test_object, &_TestUndoRedoObject::subtract_from_property).bind(value));
undo_redo->commit_action();
}
TEST_CASE("[UndoRedo] Simple Property UndoRedo") {
GDREGISTER_CLASS(_TestUndoRedoObject);
UndoRedo *undo_redo = memnew(UndoRedo());
_TestUndoRedoObject *test_object = memnew(_TestUndoRedoObject());
CHECK(test_object->get_property() == 0);
CHECK(undo_redo->get_version() == 1);
CHECK(undo_redo->get_history_count() == 0);
set_property_action(undo_redo, "Set Property", test_object, 10);
CHECK(test_object->get_property() == 10);
CHECK(undo_redo->get_version() == 2);
CHECK(undo_redo->get_history_count() == 1);
undo_redo->undo();
CHECK(test_object->get_property() == 0);
CHECK(undo_redo->get_version() == 1);
CHECK(undo_redo->get_history_count() == 1);
undo_redo->redo();
CHECK(test_object->get_property() == 10);
CHECK(undo_redo->get_version() == 2);
CHECK(undo_redo->get_history_count() == 1);
set_property_action(undo_redo, "Set Property", test_object, 100);
CHECK(test_object->get_property() == 100);
CHECK(undo_redo->get_version() == 3);
CHECK(undo_redo->get_history_count() == 2);
set_property_action(undo_redo, "Set Property", test_object, 1000);
CHECK(test_object->get_property() == 1000);
CHECK(undo_redo->get_version() == 4);
CHECK(undo_redo->get_history_count() == 3);
undo_redo->undo();
CHECK(test_object->get_property() == 100);
CHECK(undo_redo->get_version() == 3);
CHECK(undo_redo->get_history_count() == 3);
memdelete(test_object);
memdelete(undo_redo);
}
TEST_CASE("[UndoRedo] Merge Property UndoRedo") {
GDREGISTER_CLASS(_TestUndoRedoObject);
UndoRedo *undo_redo = memnew(UndoRedo());
_TestUndoRedoObject *test_object = memnew(_TestUndoRedoObject());
CHECK(test_object->get_property() == 0);
CHECK(undo_redo->get_version() == 1);
CHECK(undo_redo->get_history_count() == 0);
set_property_action(undo_redo, "Merge Action 1", test_object, 10, UndoRedo::MERGE_ALL);
CHECK(test_object->get_property() == 10);
CHECK(undo_redo->get_version() == 2);
CHECK(undo_redo->get_history_count() == 1);
set_property_action(undo_redo, "Merge Action 1", test_object, 100, UndoRedo::MERGE_ALL);
CHECK(test_object->get_property() == 100);
CHECK(undo_redo->get_version() == 2);
CHECK(undo_redo->get_history_count() == 1);
set_property_action(undo_redo, "Merge Action 1", test_object, 1000, UndoRedo::MERGE_ALL);
CHECK(test_object->get_property() == 1000);
CHECK(undo_redo->get_version() == 2);
CHECK(undo_redo->get_history_count() == 1);
memdelete(test_object);
memdelete(undo_redo);
}
TEST_CASE("[UndoRedo] Merge Method UndoRedo") {
GDREGISTER_CLASS(_TestUndoRedoObject);
UndoRedo *undo_redo = memnew(UndoRedo());
_TestUndoRedoObject *test_object = memnew(_TestUndoRedoObject());
CHECK(test_object->get_property() == 0);
CHECK(undo_redo->get_version() == 1);
CHECK(undo_redo->get_history_count() == 0);
increment_property_action(undo_redo, "Merge Increment 1", test_object, 10, UndoRedo::MERGE_ALL);
CHECK(test_object->get_property() == 10);
CHECK(undo_redo->get_version() == 2);
CHECK(undo_redo->get_history_count() == 1);
increment_property_action(undo_redo, "Merge Increment 1", test_object, 10, UndoRedo::MERGE_ALL);
CHECK(test_object->get_property() == 20);
CHECK(undo_redo->get_version() == 2);
CHECK(undo_redo->get_history_count() == 1);
increment_property_action(undo_redo, "Merge Increment 1", test_object, 10, UndoRedo::MERGE_ALL);
CHECK(test_object->get_property() == 30);
CHECK(undo_redo->get_version() == 2);
CHECK(undo_redo->get_history_count() == 1);
undo_redo->undo();
CHECK(test_object->get_property() == 0);
CHECK(undo_redo->get_version() == 1);
CHECK(undo_redo->get_history_count() == 1);
undo_redo->redo();
CHECK(test_object->get_property() == 30);
CHECK(undo_redo->get_version() == 2);
CHECK(undo_redo->get_history_count() == 1);
memdelete(test_object);
memdelete(undo_redo);
}
} //namespace TestUndoRedo