gdscript_test_runner.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721
  1. /**************************************************************************/
  2. /* gdscript_test_runner.cpp */
  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. #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 "../gdscript_tokenizer_buffer.h"
  36. #include "core/config/project_settings.h"
  37. #include "core/core_globals.h"
  38. #include "core/core_string_names.h"
  39. #include "core/io/dir_access.h"
  40. #include "core/io/file_access_pack.h"
  41. #include "core/os/os.h"
  42. #include "core/string/string_builder.h"
  43. #include "scene/resources/packed_scene.h"
  44. #include "tests/test_macros.h"
  45. namespace GDScriptTests {
  46. void init_autoloads() {
  47. HashMap<StringName, ProjectSettings::AutoloadInfo> autoloads = ProjectSettings::get_singleton()->get_autoload_list();
  48. // First pass, add the constants so they exist before any script is loaded.
  49. for (const KeyValue<StringName, ProjectSettings::AutoloadInfo> &E : ProjectSettings::get_singleton()->get_autoload_list()) {
  50. const ProjectSettings::AutoloadInfo &info = E.value;
  51. if (info.is_singleton) {
  52. for (int i = 0; i < ScriptServer::get_language_count(); i++) {
  53. ScriptServer::get_language(i)->add_global_constant(info.name, Variant());
  54. }
  55. }
  56. }
  57. // Second pass, load into global constants.
  58. for (const KeyValue<StringName, ProjectSettings::AutoloadInfo> &E : ProjectSettings::get_singleton()->get_autoload_list()) {
  59. const ProjectSettings::AutoloadInfo &info = E.value;
  60. if (!info.is_singleton) {
  61. // Skip non-singletons since we don't have a scene tree here anyway.
  62. continue;
  63. }
  64. Node *n = nullptr;
  65. if (ResourceLoader::get_resource_type(info.path) == "PackedScene") {
  66. // Cache the scene reference before loading it (for cyclic references)
  67. Ref<PackedScene> scn;
  68. scn.instantiate();
  69. scn->set_path(info.path);
  70. scn->reload_from_file();
  71. ERR_CONTINUE_MSG(!scn.is_valid(), vformat("Failed to instantiate an autoload, can't load from path: %s.", info.path));
  72. if (scn.is_valid()) {
  73. n = scn->instantiate();
  74. }
  75. } else {
  76. Ref<Resource> res = ResourceLoader::load(info.path);
  77. ERR_CONTINUE_MSG(res.is_null(), vformat("Failed to instantiate an autoload, can't load from path: %s.", info.path));
  78. Ref<Script> scr = res;
  79. if (scr.is_valid()) {
  80. StringName ibt = scr->get_instance_base_type();
  81. bool valid_type = ClassDB::is_parent_class(ibt, "Node");
  82. ERR_CONTINUE_MSG(!valid_type, vformat("Failed to instantiate an autoload, script '%s' does not inherit from 'Node'.", info.path));
  83. Object *obj = ClassDB::instantiate(ibt);
  84. ERR_CONTINUE_MSG(!obj, vformat("Failed to instantiate an autoload, cannot instantiate '%s'.", ibt));
  85. n = Object::cast_to<Node>(obj);
  86. n->set_script(scr);
  87. }
  88. }
  89. ERR_CONTINUE_MSG(!n, vformat("Failed to instantiate an autoload, path is not pointing to a scene or a script: %s.", info.path));
  90. n->set_name(info.name);
  91. for (int i = 0; i < ScriptServer::get_language_count(); i++) {
  92. ScriptServer::get_language(i)->add_global_constant(info.name, n);
  93. }
  94. }
  95. }
  96. void init_language(const String &p_base_path) {
  97. // Setup project settings since it's needed by the languages to get the global scripts.
  98. // This also sets up the base resource path.
  99. Error err = ProjectSettings::get_singleton()->setup(p_base_path, String(), true);
  100. if (err) {
  101. print_line("Could not load project settings.");
  102. // Keep going since some scripts still work without this.
  103. }
  104. // Initialize the language for the test routine.
  105. GDScriptLanguage::get_singleton()->init();
  106. init_autoloads();
  107. }
  108. void finish_language() {
  109. GDScriptLanguage::get_singleton()->finish();
  110. ScriptServer::global_classes_clear();
  111. }
  112. StringName GDScriptTestRunner::test_function_name;
  113. GDScriptTestRunner::GDScriptTestRunner(const String &p_source_dir, bool p_init_language, bool p_print_filenames, bool p_use_binary_tokens) {
  114. test_function_name = StaticCString::create("test");
  115. do_init_languages = p_init_language;
  116. print_filenames = p_print_filenames;
  117. binary_tokens = p_use_binary_tokens;
  118. source_dir = p_source_dir;
  119. if (!source_dir.ends_with("/")) {
  120. source_dir += "/";
  121. }
  122. if (do_init_languages) {
  123. init_language(p_source_dir);
  124. }
  125. #ifdef DEBUG_ENABLED
  126. // Set all warning levels to "Warn" in order to test them properly, even the ones that default to error.
  127. ProjectSettings::get_singleton()->set_setting("debug/gdscript/warnings/enable", true);
  128. for (int i = 0; i < (int)GDScriptWarning::WARNING_MAX; i++) {
  129. if (i == GDScriptWarning::UNTYPED_DECLARATION || i == GDScriptWarning::INFERRED_DECLARATION) {
  130. // TODO: Add ability for test scripts to specify which warnings to enable/disable for testing.
  131. continue;
  132. }
  133. String warning_setting = GDScriptWarning::get_settings_path_from_code((GDScriptWarning::Code)i);
  134. ProjectSettings::get_singleton()->set_setting(warning_setting, (int)GDScriptWarning::WARN);
  135. }
  136. #endif
  137. // Enable printing to show results
  138. CoreGlobals::print_line_enabled = true;
  139. CoreGlobals::print_error_enabled = true;
  140. }
  141. GDScriptTestRunner::~GDScriptTestRunner() {
  142. test_function_name = StringName();
  143. if (do_init_languages) {
  144. finish_language();
  145. }
  146. }
  147. #ifndef DEBUG_ENABLED
  148. static String strip_warnings(const String &p_expected) {
  149. // On release builds we don't have warnings. Here we remove them from the output before comparison
  150. // so it doesn't fail just because of difference in warnings.
  151. String expected_no_warnings;
  152. for (String line : p_expected.split("\n")) {
  153. if (line.begins_with(">> ")) {
  154. continue;
  155. }
  156. expected_no_warnings += line + "\n";
  157. }
  158. return expected_no_warnings.strip_edges() + "\n";
  159. }
  160. #endif
  161. int GDScriptTestRunner::run_tests() {
  162. if (!make_tests()) {
  163. FAIL("An error occurred while making the tests.");
  164. return -1;
  165. }
  166. if (!generate_class_index()) {
  167. FAIL("An error occurred while generating class index.");
  168. return -1;
  169. }
  170. int failed = 0;
  171. for (int i = 0; i < tests.size(); i++) {
  172. GDScriptTest test = tests[i];
  173. if (print_filenames) {
  174. print_line(test.get_source_relative_filepath());
  175. }
  176. GDScriptTest::TestResult result = test.run_test();
  177. String expected = FileAccess::get_file_as_string(test.get_output_file());
  178. #ifndef DEBUG_ENABLED
  179. expected = strip_warnings(expected);
  180. #endif
  181. INFO(test.get_source_file());
  182. if (!result.passed) {
  183. INFO(expected);
  184. failed++;
  185. }
  186. CHECK_MESSAGE(result.passed, (result.passed ? String() : result.output));
  187. }
  188. return failed;
  189. }
  190. bool GDScriptTestRunner::generate_outputs() {
  191. is_generating = true;
  192. if (!make_tests()) {
  193. print_line("Failed to generate a test output.");
  194. return false;
  195. }
  196. if (!generate_class_index()) {
  197. return false;
  198. }
  199. for (int i = 0; i < tests.size(); i++) {
  200. GDScriptTest test = tests[i];
  201. if (print_filenames) {
  202. print_line(test.get_source_relative_filepath());
  203. } else {
  204. OS::get_singleton()->print(".");
  205. }
  206. bool result = test.generate_output();
  207. if (!result) {
  208. print_line("\nCould not generate output for " + test.get_source_file());
  209. return false;
  210. }
  211. }
  212. print_line("\nGenerated output files for " + itos(tests.size()) + " tests successfully.");
  213. return true;
  214. }
  215. bool GDScriptTestRunner::make_tests_for_dir(const String &p_dir) {
  216. Error err = OK;
  217. Ref<DirAccess> dir(DirAccess::open(p_dir, &err));
  218. if (err != OK) {
  219. return false;
  220. }
  221. String current_dir = dir->get_current_dir();
  222. dir->list_dir_begin();
  223. String next = dir->get_next();
  224. while (!next.is_empty()) {
  225. if (dir->current_is_dir()) {
  226. if (next == "." || next == ".." || next == "completion" || next == "lsp") {
  227. next = dir->get_next();
  228. continue;
  229. }
  230. if (!make_tests_for_dir(current_dir.path_join(next))) {
  231. return false;
  232. }
  233. } else {
  234. if (next.ends_with(".notest.gd")) {
  235. next = dir->get_next();
  236. continue;
  237. } else if (binary_tokens && next.ends_with(".textonly.gd")) {
  238. next = dir->get_next();
  239. continue;
  240. } else if (next.get_extension().to_lower() == "gd") {
  241. #ifndef DEBUG_ENABLED
  242. // On release builds, skip tests marked as debug only.
  243. Error open_err = OK;
  244. Ref<FileAccess> script_file(FileAccess::open(current_dir.path_join(next), FileAccess::READ, &open_err));
  245. if (open_err != OK) {
  246. ERR_PRINT(vformat(R"(Couldn't open test file "%s".)", next));
  247. next = dir->get_next();
  248. continue;
  249. } else {
  250. if (script_file->get_line() == "#debug-only") {
  251. next = dir->get_next();
  252. continue;
  253. }
  254. }
  255. #endif
  256. String out_file = next.get_basename() + ".out";
  257. if (!is_generating && !dir->file_exists(out_file)) {
  258. ERR_FAIL_V_MSG(false, "Could not find output file for " + next);
  259. }
  260. GDScriptTest test(current_dir.path_join(next), current_dir.path_join(out_file), source_dir);
  261. if (binary_tokens) {
  262. test.set_tokenizer_mode(GDScriptTest::TOKENIZER_BUFFER);
  263. }
  264. tests.push_back(test);
  265. }
  266. }
  267. next = dir->get_next();
  268. }
  269. dir->list_dir_end();
  270. return true;
  271. }
  272. bool GDScriptTestRunner::make_tests() {
  273. Error err = OK;
  274. Ref<DirAccess> dir(DirAccess::open(source_dir, &err));
  275. ERR_FAIL_COND_V_MSG(err != OK, false, "Could not open specified test directory.");
  276. source_dir = dir->get_current_dir() + "/"; // Make it absolute path.
  277. return make_tests_for_dir(dir->get_current_dir());
  278. }
  279. static bool generate_class_index_recursive(const String &p_dir) {
  280. Error err = OK;
  281. Ref<DirAccess> dir(DirAccess::open(p_dir, &err));
  282. if (err != OK) {
  283. return false;
  284. }
  285. String current_dir = dir->get_current_dir();
  286. dir->list_dir_begin();
  287. String next = dir->get_next();
  288. StringName gdscript_name = GDScriptLanguage::get_singleton()->get_name();
  289. while (!next.is_empty()) {
  290. if (dir->current_is_dir()) {
  291. if (next == "." || next == ".." || next == "completion" || next == "lsp") {
  292. next = dir->get_next();
  293. continue;
  294. }
  295. if (!generate_class_index_recursive(current_dir.path_join(next))) {
  296. return false;
  297. }
  298. } else {
  299. if (!next.ends_with(".gd")) {
  300. next = dir->get_next();
  301. continue;
  302. }
  303. String base_type;
  304. String source_file = current_dir.path_join(next);
  305. String class_name = GDScriptLanguage::get_singleton()->get_global_class_name(source_file, &base_type);
  306. if (class_name.is_empty()) {
  307. next = dir->get_next();
  308. continue;
  309. }
  310. ERR_FAIL_COND_V_MSG(ScriptServer::is_global_class(class_name), false,
  311. "Class name '" + class_name + "' from " + source_file + " is already used in " + ScriptServer::get_global_class_path(class_name));
  312. ScriptServer::add_global_class(class_name, base_type, gdscript_name, source_file);
  313. }
  314. next = dir->get_next();
  315. }
  316. dir->list_dir_end();
  317. return true;
  318. }
  319. bool GDScriptTestRunner::generate_class_index() {
  320. Error err = OK;
  321. Ref<DirAccess> dir(DirAccess::open(source_dir, &err));
  322. ERR_FAIL_COND_V_MSG(err != OK, false, "Could not open specified test directory.");
  323. source_dir = dir->get_current_dir() + "/"; // Make it absolute path.
  324. return generate_class_index_recursive(dir->get_current_dir());
  325. }
  326. GDScriptTest::GDScriptTest(const String &p_source_path, const String &p_output_path, const String &p_base_dir) {
  327. source_file = p_source_path;
  328. output_file = p_output_path;
  329. base_dir = p_base_dir;
  330. _print_handler.printfunc = print_handler;
  331. _error_handler.errfunc = error_handler;
  332. }
  333. void GDScriptTestRunner::handle_cmdline() {
  334. List<String> cmdline_args = OS::get_singleton()->get_cmdline_args();
  335. for (List<String>::Element *E = cmdline_args.front(); E; E = E->next()) {
  336. String &cmd = E->get();
  337. if (cmd == "--gdscript-generate-tests") {
  338. String path;
  339. if (E->next()) {
  340. path = E->next()->get();
  341. } else {
  342. path = "modules/gdscript/tests/scripts";
  343. }
  344. GDScriptTestRunner runner(path, false, cmdline_args.find("--print-filenames") != nullptr);
  345. bool completed = runner.generate_outputs();
  346. int failed = completed ? 0 : -1;
  347. exit(failed);
  348. }
  349. }
  350. }
  351. void GDScriptTest::enable_stdout() {
  352. // TODO: this could likely be handled by doctest or `tests/test_macros.h`.
  353. OS::get_singleton()->set_stdout_enabled(true);
  354. OS::get_singleton()->set_stderr_enabled(true);
  355. }
  356. void GDScriptTest::disable_stdout() {
  357. // TODO: this could likely be handled by doctest or `tests/test_macros.h`.
  358. OS::get_singleton()->set_stdout_enabled(false);
  359. OS::get_singleton()->set_stderr_enabled(false);
  360. }
  361. void GDScriptTest::print_handler(void *p_this, const String &p_message, bool p_error, bool p_rich) {
  362. TestResult *result = (TestResult *)p_this;
  363. result->output += p_message + "\n";
  364. }
  365. 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) {
  366. ErrorHandlerData *data = (ErrorHandlerData *)p_this;
  367. GDScriptTest *self = data->self;
  368. TestResult *result = data->result;
  369. result->status = GDTEST_RUNTIME_ERROR;
  370. StringBuilder builder;
  371. builder.append(">> ");
  372. // Only include the function, file and line for script errors, otherwise the
  373. // test outputs changes based on the platform/compiler.
  374. bool include_source_info = false;
  375. switch (p_type) {
  376. case ERR_HANDLER_ERROR:
  377. builder.append("ERROR");
  378. break;
  379. case ERR_HANDLER_WARNING:
  380. builder.append("WARNING");
  381. break;
  382. case ERR_HANDLER_SCRIPT:
  383. builder.append("SCRIPT ERROR");
  384. include_source_info = true;
  385. break;
  386. case ERR_HANDLER_SHADER:
  387. builder.append("SHADER ERROR");
  388. break;
  389. default:
  390. builder.append("Unknown error type");
  391. break;
  392. }
  393. if (include_source_info) {
  394. builder.append("\n>> on function: ");
  395. builder.append(String::utf8(p_function));
  396. builder.append("()\n>> ");
  397. builder.append(String::utf8(p_file).trim_prefix(self->base_dir).replace("\\", "/"));
  398. builder.append("\n>> ");
  399. builder.append(itos(p_line));
  400. }
  401. builder.append("\n>> ");
  402. builder.append(String::utf8(p_error));
  403. if (strlen(p_explanation) > 0) {
  404. builder.append("\n>> ");
  405. builder.append(String::utf8(p_explanation));
  406. }
  407. builder.append("\n");
  408. result->output = builder.as_string();
  409. }
  410. bool GDScriptTest::check_output(const String &p_output) const {
  411. Error err = OK;
  412. String expected = FileAccess::get_file_as_string(output_file, &err);
  413. ERR_FAIL_COND_V_MSG(err != OK, false, "Error when opening the output file.");
  414. String got = p_output.strip_edges(); // TODO: may be hacky.
  415. got += "\n"; // Make sure to insert newline for CI static checks.
  416. #ifndef DEBUG_ENABLED
  417. expected = strip_warnings(expected);
  418. #endif
  419. return got == expected;
  420. }
  421. String GDScriptTest::get_text_for_status(GDScriptTest::TestStatus p_status) const {
  422. switch (p_status) {
  423. case GDTEST_OK:
  424. return "GDTEST_OK";
  425. case GDTEST_LOAD_ERROR:
  426. return "GDTEST_LOAD_ERROR";
  427. case GDTEST_PARSER_ERROR:
  428. return "GDTEST_PARSER_ERROR";
  429. case GDTEST_ANALYZER_ERROR:
  430. return "GDTEST_ANALYZER_ERROR";
  431. case GDTEST_COMPILER_ERROR:
  432. return "GDTEST_COMPILER_ERROR";
  433. case GDTEST_RUNTIME_ERROR:
  434. return "GDTEST_RUNTIME_ERROR";
  435. }
  436. return "";
  437. }
  438. GDScriptTest::TestResult GDScriptTest::execute_test_code(bool p_is_generating) {
  439. disable_stdout();
  440. TestResult result;
  441. result.status = GDTEST_OK;
  442. result.output = String();
  443. result.passed = false;
  444. Error err = OK;
  445. // Create script.
  446. Ref<GDScript> script;
  447. script.instantiate();
  448. script->set_path(source_file);
  449. if (tokenizer_mode == TOKENIZER_TEXT) {
  450. err = script->load_source_code(source_file);
  451. } else {
  452. String code = FileAccess::get_file_as_string(source_file, &err);
  453. if (!err) {
  454. Vector<uint8_t> buffer = GDScriptTokenizerBuffer::parse_code_string(code);
  455. script->set_binary_tokens_source(buffer);
  456. }
  457. }
  458. if (err != OK) {
  459. enable_stdout();
  460. result.status = GDTEST_LOAD_ERROR;
  461. result.passed = false;
  462. ERR_FAIL_V_MSG(result, "\nCould not load source code for: '" + source_file + "'");
  463. }
  464. // Test parsing.
  465. GDScriptParser parser;
  466. if (tokenizer_mode == TOKENIZER_TEXT) {
  467. err = parser.parse(script->get_source_code(), source_file, false);
  468. } else {
  469. err = parser.parse_binary(script->get_binary_tokens_source(), source_file);
  470. }
  471. if (err != OK) {
  472. enable_stdout();
  473. result.status = GDTEST_PARSER_ERROR;
  474. result.output = get_text_for_status(result.status) + "\n";
  475. const List<GDScriptParser::ParserError> &errors = parser.get_errors();
  476. if (!errors.is_empty()) {
  477. // Only the first error since the following might be cascading.
  478. result.output += errors[0].message + "\n"; // TODO: line, column?
  479. }
  480. if (!p_is_generating) {
  481. result.passed = check_output(result.output);
  482. }
  483. return result;
  484. }
  485. // Test type-checking.
  486. GDScriptAnalyzer analyzer(&parser);
  487. err = analyzer.analyze();
  488. if (err != OK) {
  489. enable_stdout();
  490. result.status = GDTEST_ANALYZER_ERROR;
  491. result.output = get_text_for_status(result.status) + "\n";
  492. const List<GDScriptParser::ParserError> &errors = parser.get_errors();
  493. if (!errors.is_empty()) {
  494. // Only the first error since the following might be cascading.
  495. result.output += errors[0].message + "\n"; // TODO: line, column?
  496. }
  497. if (!p_is_generating) {
  498. result.passed = check_output(result.output);
  499. }
  500. return result;
  501. }
  502. #ifdef DEBUG_ENABLED
  503. StringBuilder warning_string;
  504. for (const GDScriptWarning &E : parser.get_warnings()) {
  505. const GDScriptWarning warning = E;
  506. warning_string.append(">> WARNING");
  507. warning_string.append("\n>> Line: ");
  508. warning_string.append(itos(warning.start_line));
  509. warning_string.append("\n>> ");
  510. warning_string.append(warning.get_name());
  511. warning_string.append("\n>> ");
  512. warning_string.append(warning.get_message());
  513. warning_string.append("\n");
  514. }
  515. result.output += warning_string.as_string();
  516. #endif
  517. // Test compiling.
  518. GDScriptCompiler compiler;
  519. err = compiler.compile(&parser, script.ptr(), false);
  520. if (err != OK) {
  521. enable_stdout();
  522. result.status = GDTEST_COMPILER_ERROR;
  523. result.output = get_text_for_status(result.status) + "\n";
  524. result.output = compiler.get_error();
  525. if (!p_is_generating) {
  526. result.passed = check_output(result.output);
  527. }
  528. return result;
  529. }
  530. // Script files matching this pattern are allowed to not contain a test() function.
  531. if (source_file.match("*.notest.gd")) {
  532. enable_stdout();
  533. result.passed = check_output(result.output);
  534. return result;
  535. }
  536. // Test running.
  537. const HashMap<StringName, GDScriptFunction *>::ConstIterator test_function_element = script->get_member_functions().find(GDScriptTestRunner::test_function_name);
  538. if (!test_function_element) {
  539. enable_stdout();
  540. result.status = GDTEST_LOAD_ERROR;
  541. result.output = "";
  542. result.passed = false;
  543. ERR_FAIL_V_MSG(result, "\nCould not find test function on: '" + source_file + "'");
  544. }
  545. // Setup output handlers.
  546. ErrorHandlerData error_data(&result, this);
  547. _print_handler.userdata = &result;
  548. _error_handler.userdata = &error_data;
  549. add_print_handler(&_print_handler);
  550. add_error_handler(&_error_handler);
  551. err = script->reload();
  552. if (err) {
  553. enable_stdout();
  554. result.status = GDTEST_LOAD_ERROR;
  555. result.output = "";
  556. result.passed = false;
  557. ERR_FAIL_V_MSG(result, "\nCould not reload script: '" + source_file + "'");
  558. }
  559. // Create object instance for test.
  560. Object *obj = ClassDB::instantiate(script->get_native()->get_name());
  561. Ref<RefCounted> obj_ref;
  562. if (obj->is_ref_counted()) {
  563. obj_ref = Ref<RefCounted>(Object::cast_to<RefCounted>(obj));
  564. }
  565. obj->set_script(script);
  566. GDScriptInstance *instance = static_cast<GDScriptInstance *>(obj->get_script_instance());
  567. // Call test function.
  568. Callable::CallError call_err;
  569. instance->callp(GDScriptTestRunner::test_function_name, nullptr, 0, call_err);
  570. // Tear down output handlers.
  571. remove_print_handler(&_print_handler);
  572. remove_error_handler(&_error_handler);
  573. // Check results.
  574. if (call_err.error != Callable::CallError::CALL_OK) {
  575. enable_stdout();
  576. result.status = GDTEST_LOAD_ERROR;
  577. result.passed = false;
  578. ERR_FAIL_V_MSG(result, "\nCould not call test function on: '" + source_file + "'");
  579. }
  580. result.output = get_text_for_status(result.status) + "\n" + result.output;
  581. if (!p_is_generating) {
  582. result.passed = check_output(result.output);
  583. }
  584. if (obj_ref.is_null()) {
  585. memdelete(obj);
  586. }
  587. enable_stdout();
  588. GDScriptCache::remove_script(script->get_path());
  589. return result;
  590. }
  591. GDScriptTest::TestResult GDScriptTest::run_test() {
  592. return execute_test_code(false);
  593. }
  594. bool GDScriptTest::generate_output() {
  595. TestResult result = execute_test_code(true);
  596. if (result.status == GDTEST_LOAD_ERROR) {
  597. return false;
  598. }
  599. Error err = OK;
  600. Ref<FileAccess> out_file = FileAccess::open(output_file, FileAccess::WRITE, &err);
  601. if (err != OK) {
  602. return false;
  603. }
  604. String output = result.output.strip_edges(); // TODO: may be hacky.
  605. output += "\n"; // Make sure to insert newline for CI static checks.
  606. out_file->store_string(output);
  607. return true;
  608. }
  609. } // namespace GDScriptTests