summaryrefslogtreecommitdiff
path: root/tests/test_macros.h
blob: b04c2117b7e1d4f3aaaa5c1dae9fcc562c2213d2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
/*************************************************************************/
/*  test_macros.h                                                        */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                      https://godotengine.org                          */
/*************************************************************************/
/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur.                 */
/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md).   */
/*                                                                       */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the       */
/* "Software"), to deal in the Software without restriction, including   */
/* without limitation the rights to use, copy, modify, merge, publish,   */
/* distribute, sublicense, and/or sell copies of the Software, and to    */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions:                                             */
/*                                                                       */
/* The above copyright notice and this permission notice shall be        */
/* included in all copies or substantial portions of the Software.       */
/*                                                                       */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
/*************************************************************************/

#ifndef TEST_MACROS_H
#define TEST_MACROS_H

#include "core/input/input_map.h"
#include "core/object/message_queue.h"
#include "core/variant/variant.h"

// See documentation for doctest at:
// https://github.com/onqtam/doctest/blob/master/doc/markdown/readme.md#reference
#include "thirdparty/doctest/doctest.h"

// The test is skipped with this, run pending tests with `--test --no-skip`.
#define TEST_CASE_PENDING(name) TEST_CASE(name *doctest::skip())

// The test case is marked as failed, but does not fail the entire test run.
#define TEST_CASE_MAY_FAIL(name) TEST_CASE(name *doctest::may_fail())

// Provide aliases to conform with Godot naming conventions (see error macros).
#define TEST_COND(cond, ...) DOCTEST_CHECK_FALSE_MESSAGE(cond, __VA_ARGS__)
#define TEST_FAIL(cond, ...) DOCTEST_FAIL(cond, __VA_ARGS__)
#define TEST_FAIL_COND(cond, ...) DOCTEST_REQUIRE_FALSE_MESSAGE(cond, __VA_ARGS__)
#define TEST_FAIL_COND_WARN(cond, ...) DOCTEST_WARN_FALSE_MESSAGE(cond, __VA_ARGS__)

// Temporarily disable error prints to test failure paths.
// This allows to avoid polluting the test summary with error messages.
// The `_print_error_enabled` boolean is defined in `core/print_string.cpp` and
// works at global scope. It's used by various loggers in `should_log()` method,
// which are used by error macros which call into `OS::print_error`, effectively
// disabling any error messages to be printed from the engine side (not tests).
#define ERR_PRINT_OFF _print_error_enabled = false;
#define ERR_PRINT_ON _print_error_enabled = true;

// Stringify all `Variant` compatible types for doctest output by default.
// https://github.com/onqtam/doctest/blob/master/doc/markdown/stringification.md

#define DOCTEST_STRINGIFY_VARIANT(m_type)                        \
	template <>                                                  \
	struct doctest::StringMaker<m_type> {                        \
		static doctest::String convert(const m_type &p_val) {    \
			const Variant val = p_val;                           \
			return val.get_construct_string().utf8().get_data(); \
		}                                                        \
	};

#define DOCTEST_STRINGIFY_VARIANT_POINTER(m_type)                \
	template <>                                                  \
	struct doctest::StringMaker<m_type> {                        \
		static doctest::String convert(const m_type *p_val) {    \
			const Variant val = p_val;                           \
			return val.get_construct_string().utf8().get_data(); \
		}                                                        \
	};

DOCTEST_STRINGIFY_VARIANT(Variant);
DOCTEST_STRINGIFY_VARIANT(::String); // Disambiguate from `doctest::String`.

DOCTEST_STRINGIFY_VARIANT(Vector2);
DOCTEST_STRINGIFY_VARIANT(Vector2i);
DOCTEST_STRINGIFY_VARIANT(Rect2);
DOCTEST_STRINGIFY_VARIANT(Rect2i);
DOCTEST_STRINGIFY_VARIANT(Vector3);
DOCTEST_STRINGIFY_VARIANT(Vector3i);
DOCTEST_STRINGIFY_VARIANT(Transform2D);
DOCTEST_STRINGIFY_VARIANT(Plane);
DOCTEST_STRINGIFY_VARIANT(Quaternion);
DOCTEST_STRINGIFY_VARIANT(AABB);
DOCTEST_STRINGIFY_VARIANT(Basis);
DOCTEST_STRINGIFY_VARIANT(Transform3D);

DOCTEST_STRINGIFY_VARIANT(::Color); // Disambiguate from `doctest::Color`.
DOCTEST_STRINGIFY_VARIANT(StringName);
DOCTEST_STRINGIFY_VARIANT(NodePath);
DOCTEST_STRINGIFY_VARIANT(RID);
DOCTEST_STRINGIFY_VARIANT_POINTER(Object);
DOCTEST_STRINGIFY_VARIANT(Callable);
DOCTEST_STRINGIFY_VARIANT(Signal);
DOCTEST_STRINGIFY_VARIANT(Dictionary);
DOCTEST_STRINGIFY_VARIANT(Array);

DOCTEST_STRINGIFY_VARIANT(PackedByteArray);
DOCTEST_STRINGIFY_VARIANT(PackedInt32Array);
DOCTEST_STRINGIFY_VARIANT(PackedInt64Array);
DOCTEST_STRINGIFY_VARIANT(PackedFloat32Array);
DOCTEST_STRINGIFY_VARIANT(PackedFloat64Array);
DOCTEST_STRINGIFY_VARIANT(PackedStringArray);
DOCTEST_STRINGIFY_VARIANT(PackedVector2Array);
DOCTEST_STRINGIFY_VARIANT(PackedVector3Array);
DOCTEST_STRINGIFY_VARIANT(PackedColorArray);

// Register test commands to be launched from the command-line.
// For instance: REGISTER_TEST_COMMAND("gdscript-parser" &test_parser_func).
// Example usage: `godot --test gdscript-parser`.

typedef void (*TestFunc)();
extern Map<String, TestFunc> *test_commands;
int register_test_command(String p_command, TestFunc p_function);

#define REGISTER_TEST_COMMAND(m_command, m_function)                    \
	DOCTEST_GLOBAL_NO_WARNINGS(DOCTEST_ANONYMOUS(_DOCTEST_ANON_VAR_)) = \
			register_test_command(m_command, m_function);               \
	DOCTEST_GLOBAL_NO_WARNINGS_END()

// Utility macros to send an event actions to a given object
// Requires Message Queue and InputMap to be setup.
// SEND_GUI_ACTION    - takes an object and a input map key. e.g SEND_GUI_ACTION(code_edit, "ui_text_newline").
// SEND_GUI_KEY_EVENT - takes an object and a keycode set.   e.g SEND_GUI_KEY_EVENT(code_edit, Key::A | KeyModifierMask::CMD).
// SEND_GUI_MOUSE_EVENT - takes an object, position, mouse button and mouse mask e.g SEND_GUI_MOUSE_EVENT(code_edit, Vector2(50, 50), MOUSE_BUTTON_NONE, MOUSE_BUTTON_NONE);
// SEND_GUI_DOUBLE_CLICK - takes an object and a postion. e.g SEND_GUI_DOUBLE_CLICK(code_edit, Vector2(50, 50));

#define SEND_GUI_ACTION(m_object, m_action)                                                           \
	{                                                                                                 \
		const List<Ref<InputEvent>> *events = InputMap::get_singleton()->action_get_events(m_action); \
		const List<Ref<InputEvent>>::Element *first_event = events->front();                          \
		Ref<InputEventKey> event = first_event->get();                                                \
		event->set_pressed(true);                                                                     \
		m_object->gui_input(event);                                                                   \
		MessageQueue::get_singleton()->flush();                                                       \
	}

#define SEND_GUI_KEY_EVENT(m_object, m_input)                                \
	{                                                                        \
		Ref<InputEventKey> event = InputEventKey::create_reference(m_input); \
		event->set_pressed(true);                                            \
		m_object->gui_input(event);                                          \
		MessageQueue::get_singleton()->flush();                              \
	}

#define _CREATE_GUI_MOUSE_EVENT(m_object, m_local_pos, m_input, m_mask) \
	Ref<InputEventMouseButton> event;                                   \
	event.instantiate();                                                \
	event->set_position(m_local_pos);                                   \
	event->set_button_index(m_input);                                   \
	event->set_button_mask(m_mask);                                     \
	event->set_pressed(true);

#define SEND_GUI_MOUSE_EVENT(m_object, m_local_pos, m_input, m_mask)     \
	{                                                                    \
		_CREATE_GUI_MOUSE_EVENT(m_object, m_local_pos, m_input, m_mask); \
		m_object->get_viewport()->push_input(event);                     \
		MessageQueue::get_singleton()->flush();                          \
	}

#define SEND_GUI_DOUBLE_CLICK(m_object, m_local_pos)                                          \
	{                                                                                         \
		_CREATE_GUI_MOUSE_EVENT(m_object, m_local_pos, MouseButton::LEFT, MouseButton::LEFT); \
		event->set_double_click(true);                                                        \
		m_object->get_viewport()->push_input(event);                                          \
		MessageQueue::get_singleton()->flush();                                               \
	}

// Utility class / macros for testing signals
//
// Use SIGNAL_WATCH(*object, "signal_name") to start watching
// Makes sure to call SIGNAL_UNWATCH(*object, "signal_name") to stop watching in cleanup, this is not done automatically.
//
// The SignalWatcher will capture all signals and their args sent between checks.
//
// Use SIGNAL_CHECK("signal_name"), Vector<Vector<Variant>>), to check the arguments of all fired signals.
// The outer vector is each fired signal, the inner vector the list of arguments for that signal. Order does matter.
//
// Use SIGNAL_CHECK_FALSE("signal_name") to check if a signal was not fired.
//
// Use SIGNAL_DISCARD("signal_name") to discard records all of the given signal, use only in placed you don't need to check.
//
// All signals are automaticaly discared between test/sub test cases.

class SignalWatcher : public Object {
private:
	inline static SignalWatcher *singleton;

	/* Equal to: Map<String, Vector<Vector<Variant>>> */
	Map<String, Array> _signals;
	void _add_signal_entry(const Array &p_args, const String &p_name) {
		if (!_signals.has(p_name)) {
			_signals[p_name] = Array();
		}
		_signals[p_name].push_back(p_args);
	}

	void _signal_callback_zero(const String &p_name) {
		Array args;
		_add_signal_entry(args, p_name);
	}

	void _signal_callback_one(Variant p_arg1, const String &p_name) {
		Array args;
		args.push_back(p_arg1);
		_add_signal_entry(args, p_name);
	}

	void _signal_callback_two(Variant p_arg1, Variant p_arg2, const String &p_name) {
		Array args;
		args.push_back(p_arg1);
		args.push_back(p_arg2);
		_add_signal_entry(args, p_name);
	}

	void _signal_callback_three(Variant p_arg1, Variant p_arg2, Variant p_arg3, const String &p_name) {
		Array args;
		args.push_back(p_arg1);
		args.push_back(p_arg2);
		args.push_back(p_arg3);
		_add_signal_entry(args, p_name);
	}

public:
	static SignalWatcher *get_singleton() { return singleton; }

	void watch_signal(Object *p_object, const String &p_signal) {
		Vector<Variant> args;
		args.push_back(p_signal);
		MethodInfo method_info;
		ClassDB::get_signal(p_object->get_class(), p_signal, &method_info);
		switch (method_info.arguments.size()) {
			case 0: {
				p_object->connect(p_signal, callable_mp(this, &SignalWatcher::_signal_callback_zero), args);
			} break;
			case 1: {
				p_object->connect(p_signal, callable_mp(this, &SignalWatcher::_signal_callback_one), args);
			} break;
			case 2: {
				p_object->connect(p_signal, callable_mp(this, &SignalWatcher::_signal_callback_two), args);
			} break;
			case 3: {
				p_object->connect(p_signal, callable_mp(this, &SignalWatcher::_signal_callback_three), args);
			} break;
			default: {
				MESSAGE("Signal ", p_signal, " arg count not supported.");
			} break;
		}
	}

	void unwatch_signal(Object *p_object, const String &p_signal) {
		MethodInfo method_info;
		ClassDB::get_signal(p_object->get_class(), p_signal, &method_info);
		switch (method_info.arguments.size()) {
			case 0: {
				p_object->disconnect(p_signal, callable_mp(this, &SignalWatcher::_signal_callback_zero));
			} break;
			case 1: {
				p_object->disconnect(p_signal, callable_mp(this, &SignalWatcher::_signal_callback_one));
			} break;
			case 2: {
				p_object->disconnect(p_signal, callable_mp(this, &SignalWatcher::_signal_callback_two));
			} break;
			case 3: {
				p_object->disconnect(p_signal, callable_mp(this, &SignalWatcher::_signal_callback_three));
			} break;
			default: {
				MESSAGE("Signal ", p_signal, " arg count not supported.");
			} break;
		}
	}

	bool check(const String &p_name, const Array &p_args) {
		if (!_signals.has(p_name)) {
			MESSAGE("Signal ", p_name, " not emitted");
			return false;
		}

		if (p_args.size() != _signals[p_name].size()) {
			MESSAGE("Signal has " << _signals[p_name] << " expected " << p_args);
			discard_signal(p_name);
			return false;
		}

		bool match = true;
		for (int i = 0; i < p_args.size(); i++) {
			if (((Array)p_args[i]).size() != ((Array)_signals[p_name][i]).size()) {
				MESSAGE("Signal has " << _signals[p_name][i] << " expected " << p_args[i]);
				match = false;
				continue;
			}

			for (int j = 0; j < ((Array)p_args[i]).size(); j++) {
				if (((Array)p_args[i])[j] != ((Array)_signals[p_name][i])[j]) {
					MESSAGE("Signal has " << _signals[p_name][i] << " expected " << p_args[i]);
					match = false;
					break;
				}
			}
		}

		discard_signal(p_name);
		return match;
	}

	bool check_false(const String &p_name) {
		bool has = _signals.has(p_name);
		discard_signal(p_name);
		return !has;
	}

	void discard_signal(const String &p_name) {
		if (_signals.has(p_name)) {
			_signals.erase(p_name);
		}
	}

	void _clear_signals() {
		_signals.clear();
	}

	SignalWatcher() {
		singleton = this;
	}

	~SignalWatcher() {
		singleton = nullptr;
	}
};

#define SIGNAL_WATCH(m_object, m_signal) SignalWatcher::get_singleton()->watch_signal(m_object, m_signal);
#define SIGNAL_UNWATCH(m_object, m_signal) SignalWatcher::get_singleton()->unwatch_signal(m_object, m_signal);

#define SIGNAL_CHECK(m_signal, m_args) CHECK(SignalWatcher::get_singleton()->check(m_signal, m_args));
#define SIGNAL_CHECK_FALSE(m_signal) CHECK(SignalWatcher::get_singleton()->check_false(m_signal));
#define SIGNAL_DISCARD(m_signal) SignalWatcher::get_singleton()->discard_signal(m_signal);

#endif // TEST_MACROS_H