forked from GDQuest/learn-gdscript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPracticeTester.gd
86 lines (61 loc) · 2.14 KB
/
PracticeTester.gd
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
# Tests the code entered by a student in a given practice using a series of
# functions.
#
# To add a test, write a new method with a name starting with `test_`. The
# method should take no argument and return a String: an optional error message.
#
# If the returned string is empty, the test passed. If the string is not empty,
# the test failed.
#
# You can probe the tested scene and script slice using the `_scene` and
# `_slice` properties below.
class_name PracticeTester
extends Reference
# Reference to the tested scene. Use it to test the state of nodes in the scene.
var _scene_root_viewport: Node
# Reference to the edited script slice. Use it to look at the user's code.
var _slice: SliceProperties
var _test_methods := _find_test_method_names()
# We're not using _init() because it doesn't work unless you define it and call the parent's constructor in child classes. It would add boilerplate to every PracticeTester script.
func setup(scene_root: Node, slice: SliceProperties) -> void:
_slice = slice
_scene_root_viewport = scene_root
func get_test_names() -> Array:
return _test_methods.values()
func run_tests() -> TestResult:
var result := TestResult.new()
_prepare()
for method in _test_methods:
var test_name = _test_methods[method]
var error_message: String = call(method)
if error_message != "":
result.errors[test_name] = error_message
else:
# We pass the test name to display it in the interface.
result.passed_tests.push_back(_test_methods[method])
_clean_up()
return result
func _find_test_method_names() -> Dictionary:
var output := {}
var methods := []
for method in get_method_list():
if method.name.begins_with("test_"):
methods.append(method.name)
methods.sort()
for method in methods:
output[method] = method.trim_prefix("test_").capitalize()
return output
# Virtual method.
# Called before running tests.
func _prepare() -> void:
pass
# Virtual method.
# Called after running tests.
func _clean_up() -> void:
pass
class TestResult:
# List of tests passed successfully in the test suite.
var passed_tests := []
var errors := {}
func is_success() -> bool:
return errors.empty()