2
0

gdscript_test_runner.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588
  1. /*************************************************************************/
  2. /* gdscript_test_runner.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
  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. #include "gdscript_test_runner.h"
  31. #include "../gdscript.h"
  32. #include "../gdscript_analyzer.h"
  33. #include "../gdscript_compiler.h"
  34. #include "../gdscript_parser.h"
  35. #include "core/config/project_settings.h"
  36. #include "core/core_string_names.h"
  37. #include "core/io/dir_access.h"
  38. #include "core/io/file_access_pack.h"
  39. #include "core/os/os.h"
  40. #include "core/string/string_builder.h"
  41. #include "scene/resources/packed_scene.h"
  42. #include "tests/test_macros.h"
  43. namespace GDScriptTests {
  44. void init_autoloads() {
  45. OrderedHashMap<StringName, ProjectSettings::AutoloadInfo> autoloads = ProjectSettings::get_singleton()->get_autoload_list();
  46. // First pass, add the constants so they exist before any script is loaded.
  47. for (OrderedHashMap<StringName, ProjectSettings::AutoloadInfo>::Element E = autoloads.front(); E; E = E.next()) {
  48. const ProjectSettings::AutoloadInfo &info = E.get();
  49. if (info.is_singleton) {
  50. for (int i = 0; i < ScriptServer::get_language_count(); i++) {
  51. ScriptServer::get_language(i)->add_global_constant(info.name, Variant());
  52. }
  53. }
  54. }
  55. // Second pass, load into global constants.
  56. for (OrderedHashMap<StringName, ProjectSettings::AutoloadInfo>::Element E = autoloads.front(); E; E = E.next()) {
  57. const ProjectSettings::AutoloadInfo &info = E.get();
  58. if (!info.is_singleton) {
  59. // Skip non-singletons since we don't have a scene tree here anyway.
  60. continue;
  61. }
  62. RES res = ResourceLoader::load(info.path);
  63. ERR_CONTINUE_MSG(res.is_null(), "Can't autoload: " + info.path);
  64. Node *n = nullptr;
  65. if (res->is_class("PackedScene")) {
  66. Ref<PackedScene> ps = res;
  67. n = ps->instantiate();
  68. } else if (res->is_class("Script")) {
  69. Ref<Script> script_res = res;
  70. StringName ibt = script_res->get_instance_base_type();
  71. bool valid_type = ClassDB::is_parent_class(ibt, "Node");
  72. ERR_CONTINUE_MSG(!valid_type, "Script does not inherit a Node: " + info.path);
  73. Object *obj = ClassDB::instantiate(ibt);
  74. ERR_CONTINUE_MSG(obj == nullptr,
  75. "Cannot instance script for autoload, expected 'Node' inheritance, got: " +
  76. String(ibt));
  77. n = Object::cast_to<Node>(obj);
  78. n->set_script(script_res);
  79. }
  80. ERR_CONTINUE_MSG(!n, "Path in autoload not a node or script: " + info.path);
  81. n->set_name(info.name);
  82. for (int i = 0; i < ScriptServer::get_language_count(); i++) {
  83. ScriptServer::get_language(i)->add_global_constant(info.name, n);
  84. }
  85. }
  86. }
  87. void init_language(const String &p_base_path) {
  88. // Setup project settings since it's needed by the languages to get the global scripts.
  89. // This also sets up the base resource path.
  90. Error err = ProjectSettings::get_singleton()->setup(p_base_path, String(), true);
  91. if (err) {
  92. print_line("Could not load project settings.");
  93. // Keep going since some scripts still work without this.
  94. }
  95. // Initialize the language for the test routine.
  96. GDScriptLanguage::get_singleton()->init();
  97. init_autoloads();
  98. }
  99. void finish_language() {
  100. GDScriptLanguage::get_singleton()->finish();
  101. ScriptServer::global_classes_clear();
  102. }
  103. StringName GDScriptTestRunner::test_function_name;
  104. GDScriptTestRunner::GDScriptTestRunner(const String &p_source_dir, bool p_init_language) {
  105. test_function_name = StaticCString::create("test");
  106. do_init_languages = p_init_language;
  107. source_dir = p_source_dir;
  108. if (!source_dir.ends_with("/")) {
  109. source_dir += "/";
  110. }
  111. if (do_init_languages) {
  112. init_language(p_source_dir);
  113. }
  114. // Enable all warnings for GDScript, so we can test them.
  115. ProjectSettings::get_singleton()->set_setting("debug/gdscript/warnings/enable", true);
  116. for (int i = 0; i < (int)GDScriptWarning::WARNING_MAX; i++) {
  117. String warning = GDScriptWarning::get_name_from_code((GDScriptWarning::Code)i).to_lower();
  118. ProjectSettings::get_singleton()->set_setting("debug/gdscript/warnings/" + warning, true);
  119. }
  120. // Enable printing to show results
  121. _print_line_enabled = true;
  122. _print_error_enabled = true;
  123. }
  124. GDScriptTestRunner::~GDScriptTestRunner() {
  125. test_function_name = StringName();
  126. if (do_init_languages) {
  127. finish_language();
  128. }
  129. }
  130. int GDScriptTestRunner::run_tests() {
  131. if (!make_tests()) {
  132. FAIL("An error occurred while making the tests.");
  133. return -1;
  134. }
  135. if (!generate_class_index()) {
  136. FAIL("An error occurred while generating class index.");
  137. return -1;
  138. }
  139. int failed = 0;
  140. for (int i = 0; i < tests.size(); i++) {
  141. GDScriptTest test = tests[i];
  142. GDScriptTest::TestResult result = test.run_test();
  143. String expected = FileAccess::get_file_as_string(test.get_output_file());
  144. INFO(test.get_source_file());
  145. if (!result.passed) {
  146. INFO(expected);
  147. failed++;
  148. }
  149. CHECK_MESSAGE(result.passed, (result.passed ? String() : result.output));
  150. }
  151. return failed;
  152. }
  153. bool GDScriptTestRunner::generate_outputs() {
  154. is_generating = true;
  155. if (!make_tests()) {
  156. print_line("Failed to generate a test output.");
  157. return false;
  158. }
  159. if (!generate_class_index()) {
  160. return false;
  161. }
  162. for (int i = 0; i < tests.size(); i++) {
  163. OS::get_singleton()->print(".");
  164. GDScriptTest test = tests[i];
  165. bool result = test.generate_output();
  166. if (!result) {
  167. print_line("\nCould not generate output for " + test.get_source_file());
  168. return false;
  169. }
  170. }
  171. print_line("\nGenerated output files for " + itos(tests.size()) + " tests successfully.");
  172. return true;
  173. }
  174. bool GDScriptTestRunner::make_tests_for_dir(const String &p_dir) {
  175. Error err = OK;
  176. DirAccessRef dir(DirAccess::open(p_dir, &err));
  177. if (err != OK) {
  178. return false;
  179. }
  180. String current_dir = dir->get_current_dir();
  181. dir->list_dir_begin();
  182. String next = dir->get_next();
  183. while (!next.is_empty()) {
  184. if (dir->current_is_dir()) {
  185. if (next == "." || next == "..") {
  186. next = dir->get_next();
  187. continue;
  188. }
  189. if (!make_tests_for_dir(current_dir.plus_file(next))) {
  190. return false;
  191. }
  192. } else {
  193. if (next.get_extension().to_lower() == "gd") {
  194. String out_file = next.get_basename() + ".out";
  195. if (!is_generating && !dir->file_exists(out_file)) {
  196. ERR_FAIL_V_MSG(false, "Could not find output file for " + next);
  197. }
  198. GDScriptTest test(current_dir.plus_file(next), current_dir.plus_file(out_file), source_dir);
  199. tests.push_back(test);
  200. }
  201. }
  202. next = dir->get_next();
  203. }
  204. dir->list_dir_end();
  205. return true;
  206. }
  207. bool GDScriptTestRunner::make_tests() {
  208. Error err = OK;
  209. DirAccessRef dir(DirAccess::open(source_dir, &err));
  210. ERR_FAIL_COND_V_MSG(err != OK, false, "Could not open specified test directory.");
  211. source_dir = dir->get_current_dir() + "/"; // Make it absolute path.
  212. return make_tests_for_dir(dir->get_current_dir());
  213. }
  214. bool GDScriptTestRunner::generate_class_index() {
  215. StringName gdscript_name = GDScriptLanguage::get_singleton()->get_name();
  216. for (int i = 0; i < tests.size(); i++) {
  217. GDScriptTest test = tests[i];
  218. String base_type;
  219. String class_name = GDScriptLanguage::get_singleton()->get_global_class_name(test.get_source_file(), &base_type);
  220. if (class_name == String()) {
  221. continue;
  222. }
  223. ERR_FAIL_COND_V_MSG(ScriptServer::is_global_class(class_name), false,
  224. "Class name '" + class_name + "' from " + test.get_source_file() + " is already used in " + ScriptServer::get_global_class_path(class_name));
  225. ScriptServer::add_global_class(class_name, base_type, gdscript_name, test.get_source_file());
  226. }
  227. return true;
  228. }
  229. GDScriptTest::GDScriptTest(const String &p_source_path, const String &p_output_path, const String &p_base_dir) {
  230. source_file = p_source_path;
  231. output_file = p_output_path;
  232. base_dir = p_base_dir;
  233. _print_handler.printfunc = print_handler;
  234. _error_handler.errfunc = error_handler;
  235. }
  236. void GDScriptTestRunner::handle_cmdline() {
  237. List<String> cmdline_args = OS::get_singleton()->get_cmdline_args();
  238. // TODO: this could likely be ported to use test commands:
  239. // https://github.com/godotengine/godot/pull/41355
  240. // Currently requires to startup the whole engine, which is slow.
  241. String test_cmd = "--gdscript-test";
  242. String gen_cmd = "--gdscript-generate-tests";
  243. for (List<String>::Element *E = cmdline_args.front(); E; E = E->next()) {
  244. String &cmd = E->get();
  245. if (cmd == test_cmd || cmd == gen_cmd) {
  246. if (E->next() == nullptr) {
  247. ERR_PRINT("Needed a path for the test files.");
  248. exit(-1);
  249. }
  250. const String &path = E->next()->get();
  251. GDScriptTestRunner runner(path, false);
  252. int failed = 0;
  253. if (cmd == test_cmd) {
  254. failed = runner.run_tests();
  255. } else {
  256. bool completed = runner.generate_outputs();
  257. failed = completed ? 0 : -1;
  258. }
  259. exit(failed);
  260. }
  261. }
  262. }
  263. void GDScriptTest::enable_stdout() {
  264. // TODO: this could likely be handled by doctest or `tests/test_macros.h`.
  265. OS::get_singleton()->set_stdout_enabled(true);
  266. OS::get_singleton()->set_stderr_enabled(true);
  267. }
  268. void GDScriptTest::disable_stdout() {
  269. // TODO: this could likely be handled by doctest or `tests/test_macros.h`.
  270. OS::get_singleton()->set_stdout_enabled(false);
  271. OS::get_singleton()->set_stderr_enabled(false);
  272. }
  273. void GDScriptTest::print_handler(void *p_this, const String &p_message, bool p_error) {
  274. TestResult *result = (TestResult *)p_this;
  275. result->output += p_message + "\n";
  276. }
  277. void GDScriptTest::error_handler(void *p_this, const char *p_function, const char *p_file, int p_line, const char *p_error, const char *p_explanation, bool p_editor_notify, ErrorHandlerType p_type) {
  278. ErrorHandlerData *data = (ErrorHandlerData *)p_this;
  279. GDScriptTest *self = data->self;
  280. TestResult *result = data->result;
  281. result->status = GDTEST_RUNTIME_ERROR;
  282. StringBuilder builder;
  283. builder.append(">> ");
  284. switch (p_type) {
  285. case ERR_HANDLER_ERROR:
  286. builder.append("ERROR");
  287. break;
  288. case ERR_HANDLER_WARNING:
  289. builder.append("WARNING");
  290. break;
  291. case ERR_HANDLER_SCRIPT:
  292. builder.append("SCRIPT ERROR");
  293. break;
  294. case ERR_HANDLER_SHADER:
  295. builder.append("SHADER ERROR");
  296. break;
  297. default:
  298. builder.append("Unknown error type");
  299. break;
  300. }
  301. builder.append("\n>> on function: ");
  302. builder.append(p_function);
  303. builder.append("()\n>> ");
  304. builder.append(String(p_file).trim_prefix(self->base_dir));
  305. builder.append("\n>> ");
  306. builder.append(itos(p_line));
  307. builder.append("\n>> ");
  308. builder.append(p_error);
  309. if (strlen(p_explanation) > 0) {
  310. builder.append("\n>> ");
  311. builder.append(p_explanation);
  312. }
  313. builder.append("\n");
  314. result->output = builder.as_string();
  315. }
  316. bool GDScriptTest::check_output(const String &p_output) const {
  317. Error err = OK;
  318. String expected = FileAccess::get_file_as_string(output_file, &err);
  319. ERR_FAIL_COND_V_MSG(err != OK, false, "Error when opening the output file.");
  320. String got = p_output.strip_edges(); // TODO: may be hacky.
  321. got += "\n"; // Make sure to insert newline for CI static checks.
  322. return got == expected;
  323. }
  324. String GDScriptTest::get_text_for_status(GDScriptTest::TestStatus p_status) const {
  325. switch (p_status) {
  326. case GDTEST_OK:
  327. return "GDTEST_OK";
  328. case GDTEST_LOAD_ERROR:
  329. return "GDTEST_LOAD_ERROR";
  330. case GDTEST_PARSER_ERROR:
  331. return "GDTEST_PARSER_ERROR";
  332. case GDTEST_ANALYZER_ERROR:
  333. return "GDTEST_ANALYZER_ERROR";
  334. case GDTEST_COMPILER_ERROR:
  335. return "GDTEST_COMPILER_ERROR";
  336. case GDTEST_RUNTIME_ERROR:
  337. return "GDTEST_RUNTIME_ERROR";
  338. }
  339. return "";
  340. }
  341. GDScriptTest::TestResult GDScriptTest::execute_test_code(bool p_is_generating) {
  342. disable_stdout();
  343. TestResult result;
  344. result.status = GDTEST_OK;
  345. result.output = String();
  346. result.passed = false;
  347. Error err = OK;
  348. // Create script.
  349. Ref<GDScript> script;
  350. script.instantiate();
  351. script->set_path(source_file);
  352. script->set_script_path(source_file);
  353. err = script->load_source_code(source_file);
  354. if (err != OK) {
  355. enable_stdout();
  356. result.status = GDTEST_LOAD_ERROR;
  357. result.passed = false;
  358. ERR_FAIL_V_MSG(result, "\nCould not load source code for: '" + source_file + "'");
  359. }
  360. // Test parsing.
  361. GDScriptParser parser;
  362. err = parser.parse(script->get_source_code(), source_file, false);
  363. if (err != OK) {
  364. enable_stdout();
  365. result.status = GDTEST_PARSER_ERROR;
  366. result.output = get_text_for_status(result.status) + "\n";
  367. const List<GDScriptParser::ParserError> &errors = parser.get_errors();
  368. for (const GDScriptParser::ParserError &E : errors) {
  369. result.output += E.message + "\n"; // TODO: line, column?
  370. break; // Only the first error since the following might be cascading.
  371. }
  372. if (!p_is_generating) {
  373. result.passed = check_output(result.output);
  374. }
  375. return result;
  376. }
  377. // Test type-checking.
  378. GDScriptAnalyzer analyzer(&parser);
  379. err = analyzer.analyze();
  380. if (err != OK) {
  381. enable_stdout();
  382. result.status = GDTEST_ANALYZER_ERROR;
  383. result.output = get_text_for_status(result.status) + "\n";
  384. const List<GDScriptParser::ParserError> &errors = parser.get_errors();
  385. for (const GDScriptParser::ParserError &E : errors) {
  386. result.output += E.message + "\n"; // TODO: line, column?
  387. break; // Only the first error since the following might be cascading.
  388. }
  389. if (!p_is_generating) {
  390. result.passed = check_output(result.output);
  391. }
  392. return result;
  393. }
  394. StringBuilder warning_string;
  395. for (const GDScriptWarning &E : parser.get_warnings()) {
  396. const GDScriptWarning warning = E;
  397. warning_string.append(">> WARNING");
  398. warning_string.append("\n>> Line: ");
  399. warning_string.append(itos(warning.start_line));
  400. warning_string.append("\n>> ");
  401. warning_string.append(warning.get_name());
  402. warning_string.append("\n>> ");
  403. warning_string.append(warning.get_message());
  404. warning_string.append("\n");
  405. }
  406. result.output += warning_string.as_string();
  407. // Test compiling.
  408. GDScriptCompiler compiler;
  409. err = compiler.compile(&parser, script.ptr(), false);
  410. if (err != OK) {
  411. enable_stdout();
  412. result.status = GDTEST_COMPILER_ERROR;
  413. result.output = get_text_for_status(result.status) + "\n";
  414. result.output = compiler.get_error();
  415. if (!p_is_generating) {
  416. result.passed = check_output(result.output);
  417. }
  418. return result;
  419. }
  420. // Script files matching this pattern are allowed to not contain a test() function.
  421. if (source_file.match("*.notest.gd")) {
  422. enable_stdout();
  423. result.passed = check_output(result.output);
  424. return result;
  425. }
  426. // Test running.
  427. const Map<StringName, GDScriptFunction *>::Element *test_function_element = script->get_member_functions().find(GDScriptTestRunner::test_function_name);
  428. if (test_function_element == nullptr) {
  429. enable_stdout();
  430. result.status = GDTEST_LOAD_ERROR;
  431. result.output = "";
  432. result.passed = false;
  433. ERR_FAIL_V_MSG(result, "\nCould not find test function on: '" + source_file + "'");
  434. }
  435. script->reload();
  436. // Create object instance for test.
  437. Object *obj = ClassDB::instantiate(script->get_native()->get_name());
  438. Ref<RefCounted> obj_ref;
  439. if (obj->is_ref_counted()) {
  440. obj_ref = Ref<RefCounted>(Object::cast_to<RefCounted>(obj));
  441. }
  442. obj->set_script(script);
  443. GDScriptInstance *instance = static_cast<GDScriptInstance *>(obj->get_script_instance());
  444. // Setup output handlers.
  445. ErrorHandlerData error_data(&result, this);
  446. _print_handler.userdata = &result;
  447. _error_handler.userdata = &error_data;
  448. add_print_handler(&_print_handler);
  449. add_error_handler(&_error_handler);
  450. // Call test function.
  451. Callable::CallError call_err;
  452. instance->call(GDScriptTestRunner::test_function_name, nullptr, 0, call_err);
  453. // Tear down output handlers.
  454. remove_print_handler(&_print_handler);
  455. remove_error_handler(&_error_handler);
  456. // Check results.
  457. if (call_err.error != Callable::CallError::CALL_OK) {
  458. enable_stdout();
  459. result.status = GDTEST_LOAD_ERROR;
  460. result.passed = false;
  461. ERR_FAIL_V_MSG(result, "\nCould not call test function on: '" + source_file + "'");
  462. }
  463. result.output = get_text_for_status(result.status) + "\n" + result.output;
  464. if (!p_is_generating) {
  465. result.passed = check_output(result.output);
  466. }
  467. if (obj_ref.is_null()) {
  468. memdelete(obj);
  469. }
  470. enable_stdout();
  471. return result;
  472. }
  473. GDScriptTest::TestResult GDScriptTest::run_test() {
  474. return execute_test_code(false);
  475. }
  476. bool GDScriptTest::generate_output() {
  477. TestResult result = execute_test_code(true);
  478. if (result.status == GDTEST_LOAD_ERROR) {
  479. return false;
  480. }
  481. Error err = OK;
  482. FileAccessRef out_file = FileAccess::open(output_file, FileAccess::WRITE, &err);
  483. if (err != OK) {
  484. return false;
  485. }
  486. String output = result.output.strip_edges(); // TODO: may be hacky.
  487. output += "\n"; // Make sure to insert newline for CI static checks.
  488. out_file->store_string(output);
  489. out_file->close();
  490. return true;
  491. }
  492. } // namespace GDScriptTests