gdscript_test_runner.cpp 23 KB

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