test_object.h 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608
  1. /**************************************************************************/
  2. /* test_object.h */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #ifndef TEST_OBJECT_H
  31. #define TEST_OBJECT_H
  32. #include "core/object/class_db.h"
  33. #include "core/object/object.h"
  34. #include "core/object/script_language.h"
  35. #include "tests/test_macros.h"
  36. #ifdef SANITIZERS_ENABLED
  37. #ifdef __has_feature
  38. #if __has_feature(address_sanitizer) || __has_feature(thread_sanitizer)
  39. #define ASAN_OR_TSAN_ENABLED
  40. #endif
  41. #elif defined(__SANITIZE_ADDRESS__) || defined(__SANITIZE_THREAD__)
  42. #define ASAN_OR_TSAN_ENABLED
  43. #endif
  44. #endif
  45. // Declared in global namespace because of GDCLASS macro warning (Windows):
  46. // "Unqualified friend declaration referring to type outside of the nearest enclosing namespace
  47. // is a Microsoft extension; add a nested name specifier".
  48. class _TestDerivedObject : public Object {
  49. GDCLASS(_TestDerivedObject, Object);
  50. int property_value;
  51. protected:
  52. static void _bind_methods() {
  53. ClassDB::bind_method(D_METHOD("set_property", "property"), &_TestDerivedObject::set_property);
  54. ClassDB::bind_method(D_METHOD("get_property"), &_TestDerivedObject::get_property);
  55. ADD_PROPERTY(PropertyInfo(Variant::INT, "property"), "set_property", "get_property");
  56. }
  57. public:
  58. void set_property(int value) { property_value = value; }
  59. int get_property() const { return property_value; }
  60. };
  61. namespace TestObject {
  62. class _MockScriptInstance : public ScriptInstance {
  63. StringName property_name = "NO_NAME";
  64. Variant property_value;
  65. public:
  66. bool set(const StringName &p_name, const Variant &p_value) override {
  67. property_name = p_name;
  68. property_value = p_value;
  69. return true;
  70. }
  71. bool get(const StringName &p_name, Variant &r_ret) const override {
  72. if (property_name == p_name) {
  73. r_ret = property_value;
  74. return true;
  75. }
  76. return false;
  77. }
  78. void get_property_list(List<PropertyInfo> *p_properties) const override {
  79. }
  80. Variant::Type get_property_type(const StringName &p_name, bool *r_is_valid) const override {
  81. return Variant::PACKED_FLOAT32_ARRAY;
  82. }
  83. virtual void validate_property(PropertyInfo &p_property) const override {
  84. }
  85. bool property_can_revert(const StringName &p_name) const override {
  86. return false;
  87. }
  88. bool property_get_revert(const StringName &p_name, Variant &r_ret) const override {
  89. return false;
  90. }
  91. void get_method_list(List<MethodInfo> *p_list) const override {
  92. }
  93. bool has_method(const StringName &p_method) const override {
  94. return false;
  95. }
  96. int get_method_argument_count(const StringName &p_method, bool *r_is_valid = nullptr) const override {
  97. if (r_is_valid) {
  98. *r_is_valid = false;
  99. }
  100. return 0;
  101. }
  102. Variant callp(const StringName &p_method, const Variant **p_args, int p_argcount, Callable::CallError &r_error) override {
  103. return Variant();
  104. }
  105. void notification(int p_notification, bool p_reversed = false) override {
  106. }
  107. Ref<Script> get_script() const override {
  108. return Ref<Script>();
  109. }
  110. const Variant get_rpc_config() const override {
  111. return Variant();
  112. }
  113. ScriptLanguage *get_language() override {
  114. return nullptr;
  115. }
  116. };
  117. TEST_CASE("[Object] Core getters") {
  118. Object object;
  119. CHECK_MESSAGE(
  120. object.is_class("Object"),
  121. "is_class() should return the expected value.");
  122. CHECK_MESSAGE(
  123. object.get_class() == "Object",
  124. "The returned class should match the expected value.");
  125. CHECK_MESSAGE(
  126. object.get_class_name() == "Object",
  127. "The returned class name should match the expected value.");
  128. CHECK_MESSAGE(
  129. object.get_class_static() == "Object",
  130. "The returned static class should match the expected value.");
  131. CHECK_MESSAGE(
  132. object.get_save_class() == "Object",
  133. "The returned save class should match the expected value.");
  134. List<String> inheritance_list;
  135. object.get_inheritance_list_static(&inheritance_list);
  136. CHECK_MESSAGE(
  137. inheritance_list.size() == 1,
  138. "The inheritance list should consist of Object only");
  139. CHECK_MESSAGE(
  140. inheritance_list.front()->get() == "Object",
  141. "The inheritance list should consist of Object only");
  142. }
  143. TEST_CASE("[Object] Metadata") {
  144. const String meta_path = "complex_metadata_path";
  145. Object object;
  146. object.set_meta(meta_path, Color(0, 1, 0));
  147. CHECK_MESSAGE(
  148. Color(object.get_meta(meta_path)).is_equal_approx(Color(0, 1, 0)),
  149. "The returned object metadata after setting should match the expected value.");
  150. List<StringName> meta_list;
  151. object.get_meta_list(&meta_list);
  152. CHECK_MESSAGE(
  153. meta_list.size() == 1,
  154. "The metadata list should only contain 1 item after adding one metadata item.");
  155. object.remove_meta(meta_path);
  156. // Also try removing nonexistent metadata (it should do nothing, without printing an error message).
  157. object.remove_meta("I don't exist");
  158. ERR_PRINT_OFF;
  159. CHECK_MESSAGE(
  160. object.get_meta(meta_path) == Variant(),
  161. "The returned object metadata after removing should match the expected value.");
  162. ERR_PRINT_ON;
  163. List<StringName> meta_list2;
  164. object.get_meta_list(&meta_list2);
  165. CHECK_MESSAGE(
  166. meta_list2.size() == 0,
  167. "The metadata list should contain 0 items after removing all metadata items.");
  168. Object other;
  169. object.set_meta("conflicting_meta", "string");
  170. object.set_meta("not_conflicting_meta", 123);
  171. other.set_meta("conflicting_meta", Color(0, 1, 0));
  172. other.set_meta("other_meta", "other");
  173. object.merge_meta_from(&other);
  174. CHECK_MESSAGE(
  175. Color(object.get_meta("conflicting_meta")).is_equal_approx(Color(0, 1, 0)),
  176. "String meta should be overwritten with Color after merging.");
  177. CHECK_MESSAGE(
  178. int(object.get_meta("not_conflicting_meta")) == 123,
  179. "Not conflicting meta on destination should be kept intact.");
  180. CHECK_MESSAGE(
  181. object.get_meta("other_meta", String()) == "other",
  182. "Not conflicting meta name on source should merged.");
  183. List<StringName> meta_list3;
  184. object.get_meta_list(&meta_list3);
  185. CHECK_MESSAGE(
  186. meta_list3.size() == 3,
  187. "The metadata list should contain 3 items after merging meta from two objects.");
  188. }
  189. TEST_CASE("[Object] Construction") {
  190. Object object;
  191. CHECK_MESSAGE(
  192. !object.is_ref_counted(),
  193. "Object is not a RefCounted.");
  194. Object *p_db = ObjectDB::get_instance(object.get_instance_id());
  195. CHECK_MESSAGE(
  196. p_db == &object,
  197. "The database pointer returned by the object id should reference same object.");
  198. }
  199. TEST_CASE("[Object] Script instance property setter") {
  200. Object object;
  201. _MockScriptInstance *script_instance = memnew(_MockScriptInstance);
  202. object.set_script_instance(script_instance);
  203. bool valid = false;
  204. object.set("some_name", 100, &valid);
  205. CHECK(valid);
  206. Variant actual_value;
  207. CHECK_MESSAGE(
  208. script_instance->get("some_name", actual_value),
  209. "The assigned script instance should successfully retrieve value by name.");
  210. CHECK_MESSAGE(
  211. actual_value == Variant(100),
  212. "The returned value should equal the one which was set by the object.");
  213. }
  214. TEST_CASE("[Object] Script instance property getter") {
  215. Object object;
  216. _MockScriptInstance *script_instance = memnew(_MockScriptInstance);
  217. script_instance->set("some_name", 100); // Make sure script instance has the property
  218. object.set_script_instance(script_instance);
  219. bool valid = false;
  220. const Variant &actual_value = object.get("some_name", &valid);
  221. CHECK(valid);
  222. CHECK_MESSAGE(
  223. actual_value == Variant(100),
  224. "The returned value should equal the one which was set by the script instance.");
  225. }
  226. TEST_CASE("[Object] Built-in property setter") {
  227. GDREGISTER_CLASS(_TestDerivedObject);
  228. _TestDerivedObject derived_object;
  229. bool valid = false;
  230. derived_object.set("property", 100, &valid);
  231. CHECK(valid);
  232. CHECK_MESSAGE(
  233. derived_object.get_property() == 100,
  234. "The property value should equal the one which was set with built-in setter.");
  235. }
  236. TEST_CASE("[Object] Built-in property getter") {
  237. GDREGISTER_CLASS(_TestDerivedObject);
  238. _TestDerivedObject derived_object;
  239. derived_object.set_property(100);
  240. bool valid = false;
  241. const Variant &actual_value = derived_object.get("property", &valid);
  242. CHECK(valid);
  243. CHECK_MESSAGE(
  244. actual_value == Variant(100),
  245. "The returned value should equal the one which was set with built-in setter.");
  246. }
  247. TEST_CASE("[Object] Script property setter") {
  248. Object object;
  249. Variant script;
  250. bool valid = false;
  251. object.set(CoreStringName(script), script, &valid);
  252. CHECK(valid);
  253. CHECK_MESSAGE(
  254. object.get_script() == script,
  255. "The object script should be equal to the assigned one.");
  256. }
  257. TEST_CASE("[Object] Script property getter") {
  258. Object object;
  259. Variant script;
  260. object.set_script(script);
  261. bool valid = false;
  262. const Variant &actual_value = object.get(CoreStringName(script), &valid);
  263. CHECK(valid);
  264. CHECK_MESSAGE(
  265. actual_value == script,
  266. "The returned value should be equal to the assigned script.");
  267. }
  268. TEST_CASE("[Object] Absent name setter") {
  269. Object object;
  270. bool valid = true;
  271. object.set("absent_name", 100, &valid);
  272. CHECK(!valid);
  273. }
  274. TEST_CASE("[Object] Absent name getter") {
  275. Object object;
  276. bool valid = true;
  277. const Variant &actual_value = object.get("absent_name", &valid);
  278. CHECK(!valid);
  279. CHECK_MESSAGE(
  280. actual_value == Variant(),
  281. "The returned value should equal nil variant.");
  282. }
  283. TEST_CASE("[Object] Signals") {
  284. Object object;
  285. CHECK_FALSE(object.has_signal("my_custom_signal"));
  286. List<MethodInfo> signals_before;
  287. object.get_signal_list(&signals_before);
  288. object.add_user_signal(MethodInfo("my_custom_signal"));
  289. CHECK(object.has_signal("my_custom_signal"));
  290. List<MethodInfo> signals_after;
  291. object.get_signal_list(&signals_after);
  292. // Should be one more signal.
  293. CHECK_EQ(signals_before.size() + 1, signals_after.size());
  294. SUBCASE("Adding the same user signal again should not have any effect") {
  295. CHECK(object.has_signal("my_custom_signal"));
  296. ERR_PRINT_OFF;
  297. object.add_user_signal(MethodInfo("my_custom_signal"));
  298. ERR_PRINT_ON;
  299. CHECK(object.has_signal("my_custom_signal"));
  300. List<MethodInfo> signals_after_existing_added;
  301. object.get_signal_list(&signals_after_existing_added);
  302. CHECK_EQ(signals_after.size(), signals_after_existing_added.size());
  303. }
  304. SUBCASE("Trying to add a preexisting signal should not have any effect") {
  305. CHECK(object.has_signal("script_changed"));
  306. ERR_PRINT_OFF;
  307. object.add_user_signal(MethodInfo("script_changed"));
  308. ERR_PRINT_ON;
  309. CHECK(object.has_signal("script_changed"));
  310. List<MethodInfo> signals_after_existing_added;
  311. object.get_signal_list(&signals_after_existing_added);
  312. CHECK_EQ(signals_after.size(), signals_after_existing_added.size());
  313. }
  314. SUBCASE("Adding an empty signal should not have any effect") {
  315. CHECK_FALSE(object.has_signal(""));
  316. ERR_PRINT_OFF;
  317. object.add_user_signal(MethodInfo(""));
  318. ERR_PRINT_ON;
  319. CHECK_FALSE(object.has_signal(""));
  320. List<MethodInfo> signals_after_empty_added;
  321. object.get_signal_list(&signals_after_empty_added);
  322. CHECK_EQ(signals_after.size(), signals_after_empty_added.size());
  323. }
  324. SUBCASE("Deleting an object with connected signals should disconnect them") {
  325. List<Object::Connection> signal_connections;
  326. {
  327. Object target;
  328. target.add_user_signal(MethodInfo("my_custom_signal"));
  329. ERR_PRINT_OFF;
  330. target.connect("nonexistent_signal1", callable_mp(&object, &Object::notify_property_list_changed));
  331. target.connect("my_custom_signal", callable_mp(&object, &Object::notify_property_list_changed));
  332. target.connect("nonexistent_signal2", callable_mp(&object, &Object::notify_property_list_changed));
  333. ERR_PRINT_ON;
  334. signal_connections.clear();
  335. object.get_all_signal_connections(&signal_connections);
  336. CHECK(signal_connections.size() == 0);
  337. signal_connections.clear();
  338. object.get_signals_connected_to_this(&signal_connections);
  339. CHECK(signal_connections.size() == 1);
  340. ERR_PRINT_OFF;
  341. object.connect("nonexistent_signal1", callable_mp(&target, &Object::notify_property_list_changed));
  342. object.connect("my_custom_signal", callable_mp(&target, &Object::notify_property_list_changed));
  343. object.connect("nonexistent_signal2", callable_mp(&target, &Object::notify_property_list_changed));
  344. ERR_PRINT_ON;
  345. signal_connections.clear();
  346. object.get_all_signal_connections(&signal_connections);
  347. CHECK(signal_connections.size() == 1);
  348. signal_connections.clear();
  349. object.get_signals_connected_to_this(&signal_connections);
  350. CHECK(signal_connections.size() == 1);
  351. }
  352. signal_connections.clear();
  353. object.get_all_signal_connections(&signal_connections);
  354. CHECK(signal_connections.size() == 0);
  355. signal_connections.clear();
  356. object.get_signals_connected_to_this(&signal_connections);
  357. CHECK(signal_connections.size() == 0);
  358. }
  359. SUBCASE("Emitting a non existing signal will return an error") {
  360. Error err = object.emit_signal("some_signal");
  361. CHECK(err == ERR_UNAVAILABLE);
  362. }
  363. SUBCASE("Emitting an existing signal should call the connected method") {
  364. Array empty_signal_args;
  365. empty_signal_args.push_back(Array());
  366. SIGNAL_WATCH(&object, "my_custom_signal");
  367. SIGNAL_CHECK_FALSE("my_custom_signal");
  368. Error err = object.emit_signal("my_custom_signal");
  369. CHECK(err == OK);
  370. SIGNAL_CHECK("my_custom_signal", empty_signal_args);
  371. SIGNAL_UNWATCH(&object, "my_custom_signal");
  372. }
  373. SUBCASE("Connecting and then disconnecting many signals should not leave anything behind") {
  374. List<Object::Connection> signal_connections;
  375. Object targets[100];
  376. for (int i = 0; i < 10; i++) {
  377. ERR_PRINT_OFF;
  378. for (Object &target : targets) {
  379. object.connect("my_custom_signal", callable_mp(&target, &Object::notify_property_list_changed));
  380. }
  381. ERR_PRINT_ON;
  382. signal_connections.clear();
  383. object.get_all_signal_connections(&signal_connections);
  384. CHECK(signal_connections.size() == 100);
  385. }
  386. for (Object &target : targets) {
  387. object.disconnect("my_custom_signal", callable_mp(&target, &Object::notify_property_list_changed));
  388. }
  389. signal_connections.clear();
  390. object.get_all_signal_connections(&signal_connections);
  391. CHECK(signal_connections.size() == 0);
  392. }
  393. }
  394. class NotificationObject1 : public Object {
  395. GDCLASS(NotificationObject1, Object);
  396. protected:
  397. void _notification(int p_what) {
  398. switch (p_what) {
  399. case 12345: {
  400. order_internal1 = order_global++;
  401. } break;
  402. }
  403. }
  404. public:
  405. static int order_global;
  406. int order_internal1 = -1;
  407. void reset_order() {
  408. order_internal1 = -1;
  409. order_global = 1;
  410. }
  411. };
  412. int NotificationObject1::order_global = 1;
  413. class NotificationObject2 : public NotificationObject1 {
  414. GDCLASS(NotificationObject2, NotificationObject1);
  415. protected:
  416. void _notification(int p_what) {
  417. switch (p_what) {
  418. case 12345: {
  419. order_internal2 = order_global++;
  420. } break;
  421. }
  422. }
  423. public:
  424. int order_internal2 = -1;
  425. void reset_order() {
  426. NotificationObject1::reset_order();
  427. order_internal2 = -1;
  428. }
  429. };
  430. TEST_CASE("[Object] Notification order") { // GH-52325
  431. NotificationObject2 *test_notification_object = memnew(NotificationObject2);
  432. SUBCASE("regular order") {
  433. test_notification_object->notification(12345, false);
  434. CHECK_EQ(test_notification_object->order_internal1, 1);
  435. CHECK_EQ(test_notification_object->order_internal2, 2);
  436. test_notification_object->reset_order();
  437. }
  438. SUBCASE("reverse order") {
  439. test_notification_object->notification(12345, true);
  440. CHECK_EQ(test_notification_object->order_internal1, 2);
  441. CHECK_EQ(test_notification_object->order_internal2, 1);
  442. test_notification_object->reset_order();
  443. }
  444. memdelete(test_notification_object);
  445. }
  446. TEST_CASE("[Object] Destruction at the end of the call chain is safe") {
  447. Object *object = memnew(Object);
  448. ObjectID obj_id = object->get_instance_id();
  449. class _SelfDestroyingScriptInstance : public _MockScriptInstance {
  450. Object *self = nullptr;
  451. // This has to be static because ~Object() also destroys the script instance.
  452. static void free_self(Object *p_self) {
  453. #if defined(ASAN_OR_TSAN_ENABLED)
  454. // Regular deletion is enough becausa asan/tsan will catch a potential heap-after-use.
  455. memdelete(p_self);
  456. #else
  457. // Without asan/tsan, try at least to force a crash by replacing the otherwise seemingly good data with garbage.
  458. // Operations such as dereferencing pointers or decreasing a refcount would fail.
  459. // Unfortunately, we may not poison the memory after the deletion, because the memory would no longer belong to us
  460. // and on doing so we may cause a more generalized crash on some platforms (allocator implementations).
  461. p_self->~Object();
  462. memset((void *)p_self, 0, sizeof(Object));
  463. Memory::free_static(p_self, false);
  464. #endif
  465. }
  466. public:
  467. Variant callp(const StringName &p_method, const Variant **p_args, int p_argcount, Callable::CallError &r_error) override {
  468. free_self(self);
  469. return Variant();
  470. }
  471. Variant call_const(const StringName &p_method, const Variant **p_args, int p_argcount, Callable::CallError &r_error) override {
  472. free_self(self);
  473. return Variant();
  474. }
  475. bool has_method(const StringName &p_method) const override {
  476. return p_method == "some_method";
  477. }
  478. public:
  479. _SelfDestroyingScriptInstance(Object *p_self) :
  480. self(p_self) {}
  481. };
  482. _SelfDestroyingScriptInstance *script_instance = memnew(_SelfDestroyingScriptInstance(object));
  483. object->set_script_instance(script_instance);
  484. SUBCASE("Within callp()") {
  485. SUBCASE("Through call()") {
  486. object->call("some_method");
  487. }
  488. SUBCASE("Through callv()") {
  489. object->callv("some_method", Array());
  490. }
  491. }
  492. SUBCASE("Within call_const()") {
  493. Callable::CallError call_error;
  494. object->call_const("some_method", nullptr, 0, call_error);
  495. }
  496. SUBCASE("Within signal handling (from emit_signalp(), through emit_signal())") {
  497. Object emitter;
  498. emitter.add_user_signal(MethodInfo("some_signal"));
  499. emitter.connect("some_signal", Callable(object, "some_method"));
  500. emitter.emit_signal("some_signal");
  501. }
  502. CHECK_MESSAGE(
  503. ObjectDB::get_instance(obj_id) == nullptr,
  504. "Object was tail-deleted without crashes.");
  505. }
  506. } // namespace TestObject
  507. #endif // TEST_OBJECT_H