-
Notifications
You must be signed in to change notification settings - Fork 110
/
Copy pathgut.gd
1464 lines (1224 loc) · 54.3 KB
/
gut.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
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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# ##############################################################################
#(G)odot (U)nit (T)est class
#
# ##############################################################################
# The MIT License (MIT)
# =====================
#
# Copyright (c) 2020 Tom "Butch" Wesley
#
# 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.
#
# ##############################################################################
# View readme for usage details.
# ##############################################################################
extends Control
# -- Settings --
var _select_script = ''
var _tests_like = ''
var _inner_class_name = ''
var _should_maximize = false setget set_should_maximize, get_should_maximize
var _log_level = 1 setget set_log_level, get_log_level
var _disable_strict_datatype_checks = false setget disable_strict_datatype_checks, is_strict_datatype_checks_disabled
var _test_prefix = 'test_'
var _file_prefix = 'test_'
var _file_extension = '.gd'
var _inner_class_prefix = 'Test'
var _temp_directory = 'user://gut_temp_directory'
var _export_path = '' setget set_export_path, get_export_path
var _include_subdirectories = false setget set_include_subdirectories, get_include_subdirectories
var _double_strategy = 1 setget set_double_strategy, get_double_strategy
var _pre_run_script = '' setget set_pre_run_script, get_pre_run_script
var _post_run_script = '' setget set_post_run_script, get_post_run_script
var _color_output = false setget set_color_output, get_color_output
# -- End Settings --
# ###########################
# Other Vars
# ###########################
const LOG_LEVEL_FAIL_ONLY = 0
const LOG_LEVEL_TEST_AND_FAILURES = 1
const LOG_LEVEL_ALL_ASSERTS = 2
const WAITING_MESSAGE = '/# waiting #/'
const PAUSE_MESSAGE = '/# Pausing. Press continue button...#/'
var _utils = load('res://addons/gut/utils.gd').get_instance()
var _lgr = _utils.get_logger()
var _strutils = _utils.Strutils.new()
# Used to prevent multiple messages for deprecated setup/teardown messages
var _deprecated_tracker = _utils.ThingCounter.new()
# The instance that is created from _pre_run_script. Accessible from
# get_pre_run_script_instance.
var _pre_run_script_instance = null
var _post_run_script_instance = null # This is not used except in tests.
var _script_name = null
var _test_collector = _utils.TestCollector.new()
# The instanced scripts. This is populated as the scripts are run.
var _test_script_objects = []
var _waiting = false
var _done = false
var _is_running = false
var _current_test = null
var _log_text = ""
var _pause_before_teardown = false
# when true _pause_before_teardown will be ignored. useful
# when batch processing and you don't want to watch.
var _ignore_pause_before_teardown = false
var _wait_timer = Timer.new()
var _yield_between = {
should = false,
timer = Timer.new(),
after_x_tests = 5,
tests_since_last_yield = 0
}
var _was_yield_method_called = false
# used when yielding to gut instead of some other
# signal. Start with set_yield_time()
var _yield_timer = Timer.new()
var _unit_test_name = ''
var _new_summary = null
var _yielding_to = {
obj = null,
signal_name = ''
}
var _stubber = _utils.Stubber.new()
var _doubler = _utils.Doubler.new()
var _spy = _utils.Spy.new()
var _gui = null
var _orphan_counter = _utils.OrphanCounter.new()
var _autofree = _utils.AutoFree.new()
# This is populated by test.gd each time a paramterized test is encountered
# for the first time.
var _parameter_handler = null
# Used to cancel importing scripts if an error has occurred in the setup. This
# prevents tests from being run if they were exported and ensures that the
# error displayed is seen since importing generates a lot of text.
var _cancel_import = false
const SIGNAL_TESTS_FINISHED = 'tests_finished'
const SIGNAL_STOP_YIELD_BEFORE_TEARDOWN = 'stop_yield_before_teardown'
const SIGNAL_PRAMETERIZED_YIELD_DONE = 'parameterized_yield_done'
# ------------------------------------------------------------------------------
# ------------------------------------------------------------------------------
func _init():
# When running tests for GUT itself, _utils has been setup to always return
# a new logger so this does not set the gut instance on the base logger
# when creating test instances of GUT.
_lgr.set_gut(self)
add_user_signal(SIGNAL_TESTS_FINISHED)
add_user_signal(SIGNAL_STOP_YIELD_BEFORE_TEARDOWN)
add_user_signal('timeout')
add_user_signal('done_waiting')
add_user_signal(SIGNAL_PRAMETERIZED_YIELD_DONE)
_doubler.set_output_dir(_temp_directory)
_doubler.set_stubber(_stubber)
_doubler.set_spy(_spy)
_doubler.set_gut(self)
# TODO remove these, universal logger should fix this.
_doubler.set_logger(_lgr)
_spy.set_logger(_lgr)
_stubber.set_logger(_lgr)
_test_collector.set_logger(_lgr)
_gui = load('res://addons/gut/GutScene.tscn').instance()
# ------------------------------------------------------------------------------
# Initialize controls
# ------------------------------------------------------------------------------
func _ready():
if(!_utils.is_version_ok()):
_print_versions()
push_error(_utils.get_bad_version_text())
print('Error: ', _utils.get_bad_version_text())
get_tree().quit()
return
_lgr.info(str('using [', OS.get_user_data_dir(), '] for temporary output.'))
set_process_input(true)
add_child(_wait_timer)
_wait_timer.set_wait_time(1)
_wait_timer.set_one_shot(true)
add_child(_yield_between.timer)
_wait_timer.set_one_shot(true)
add_child(_yield_timer)
_yield_timer.set_one_shot(true)
_yield_timer.connect('timeout', self, '_yielding_callback')
_setup_gui()
if(_select_script != null):
select_script(_select_script)
if(_tests_like != null):
set_unit_test_name(_tests_like)
if(_should_maximize):
# GUI checks for is_in_tree will not pass yet.
call_deferred('maximize')
# hide the panel that IS gut so that only the GUI is seen
self.self_modulate = Color(1,1,1,0)
show()
_print_versions()
# ------------------------------------------------------------------------------
# Runs right before free is called. Can't override `free`.
# ------------------------------------------------------------------------------
func _notification(what):
if(what == NOTIFICATION_PREDELETE):
for test_script in _test_script_objects:
if(is_instance_valid(test_script)):
test_script.free()
_test_script_objects = []
if(is_instance_valid(_gui)):
_gui.free()
func _print_versions(send_all = true):
var info = _utils.get_version_text()
if(send_all):
p(info)
else:
var printer = _lgr.get_printer('gui')
printer.send(info + "\n")
# ##############################################################################
#
# GUI Events and setup
#
# ##############################################################################
func _setup_gui():
# This is how we get the size of the control to translate to the gui when
# the scene is run. This is also another reason why the min_rect_size
# must match between both gut and the gui.
_gui.rect_size = self.rect_size
add_child(_gui)
_gui.set_anchor(MARGIN_RIGHT, ANCHOR_END)
_gui.set_anchor(MARGIN_BOTTOM, ANCHOR_END)
_gui.connect('run_single_script', self, '_on_run_one')
_gui.connect('run_script', self, '_on_new_gui_run_script')
_gui.connect('end_pause', self, '_on_new_gui_end_pause')
_gui.connect('ignore_pause', self, '_on_new_gui_ignore_pause')
_gui.connect('log_level_changed', self, '_on_log_level_changed')
var _foo = connect('tests_finished', _gui, 'end_run')
func _add_scripts_to_gui():
var scripts = []
for i in range(_test_collector.scripts.size()):
var s = _test_collector.scripts[i]
var txt = ''
if(s.has_inner_class()):
txt = str(' - ', s.inner_class_name, ' (', s.tests.size(), ')')
else:
txt = str(s.get_full_name(), ' (', s.tests.size(), ')')
scripts.append(txt)
_gui.set_scripts(scripts)
func _on_run_one(index):
clear_text()
var indexes = [index]
if(!_test_collector.scripts[index].has_inner_class()):
indexes = _get_indexes_matching_path(_test_collector.scripts[index].path)
_test_the_scripts(indexes)
func _on_new_gui_run_script(index):
var indexes = []
clear_text()
for i in range(index, _test_collector.scripts.size()):
indexes.append(i)
_test_the_scripts(indexes)
func _on_new_gui_end_pause():
_pause_before_teardown = false
emit_signal(SIGNAL_STOP_YIELD_BEFORE_TEARDOWN)
func _on_new_gui_ignore_pause(should):
_ignore_pause_before_teardown = should
func _on_log_level_changed(value):
set_log_level(value)
#####################
#
# Events
#
#####################
# ------------------------------------------------------------------------------
# Timeout for the built in timer. emits the timeout signal. Start timer
# with set_yield_time()
# ------------------------------------------------------------------------------
func _yielding_callback(from_obj=false):
_lgr.end_yield()
if(_yielding_to.obj):
_yielding_to.obj.call_deferred(
"disconnect",
_yielding_to.signal_name, self,
'_yielding_callback')
_yielding_to.obj = null
_yielding_to.signal_name = ''
if(from_obj):
# we must yiled for a little longer after the signal is emitted so that
# the signal can propagate to other objects. This was discovered trying
# to assert that obj/signal_name was emitted. Without this extra delay
# the yield returns and processing finishes before the rest of the
# objects can get the signal. This works b/c the timer will timeout
# and come back into this method but from_obj will be false.
_yield_timer.set_wait_time(.1)
_yield_timer.start()
else:
emit_signal('timeout')
# ------------------------------------------------------------------------------
# completed signal for GDScriptFucntionState returned from a test script that
# has yielded
# ------------------------------------------------------------------------------
func _on_test_script_yield_completed():
_waiting = false
#####################
#
# Private
#
#####################
func _log_test_children_warning(test_script):
if(!_lgr.is_type_enabled(_lgr.types.orphan)):
return
var kids = test_script.get_children()
if(kids.size() > 0):
var msg = ''
if(_log_level == 2):
msg = "Test script still has children when all tests finisehd.\n"
for i in range(kids.size()):
msg += str(" ", _strutils.type2str(kids[i]), "\n")
msg += "You can use autofree, autoqfree, add_child_autofree, or add_child_autoqfree to automatically free objects."
else:
msg = str("Test script has ", kids.size(), " unfreed children. Increase log level for more details.")
_lgr.warn(msg)
# ------------------------------------------------------------------------------
# Convert the _summary dictionary into text
# ------------------------------------------------------------------------------
func _print_summary():
_lgr.log("\n\n*** Run Summary ***", _lgr.fmts.yellow)
_new_summary.log_summary_text(_lgr)
var logger_text = ''
if(_lgr.get_errors().size() > 0):
logger_text += str("\n* ", _lgr.get_errors().size(), ' Errors.')
if(_lgr.get_warnings().size() > 0):
logger_text += str("\n* ", _lgr.get_warnings().size(), ' Warnings.')
if(_lgr.get_deprecated().size() > 0):
logger_text += str("\n* ", _lgr.get_deprecated().size(), ' Deprecated calls.')
if(logger_text != ''):
logger_text = "\nWarnings/Errors:" + logger_text + "\n\n"
_lgr.log(logger_text)
if(_new_summary.get_totals().tests > 0):
var fmt = _lgr.fmts.green
var msg = str(_new_summary.get_totals().passing) + ' passed ' + str(_new_summary.get_totals().failing) + ' failed. ' + \
str("Tests finished in ", _gui.elapsed_time_as_str())
if(_new_summary.get_totals().failing > 0):
fmt = _lgr.fmts.red
elif(_new_summary.get_totals().pending > 0):
fmt = _lgr.fmts.yellow
_lgr.log(msg, fmt)
else:
_lgr.log('No tests ran', _lgr.fmts.red)
func _validate_hook_script(path):
var result = {
valid = true,
instance = null
}
# empty path is valid but will have a null instance
if(path == ''):
return result
var f = File.new()
if(f.file_exists(path)):
var inst = load(path).new()
if(inst and inst is _utils.HookScript):
result.instance = inst
result.valid = true
else:
result.valid = false
_lgr.error('The hook script [' + path + '] does not extend res://addons/gut/hook_script.gd')
else:
result.valid = false
_lgr.error('The hook script [' + path + '] does not exist.')
return result
# ------------------------------------------------------------------------------
# Runs a hook script. Script must exist, and must extend
# res://addons/gut/hook_script.gd
# ------------------------------------------------------------------------------
func _run_hook_script(inst):
if(inst != null):
inst.gut = self
inst.run()
return inst
# ------------------------------------------------------------------------------
# Initialize variables for each run of a single test script.
# ------------------------------------------------------------------------------
func _init_run():
var valid = true
_test_collector.set_test_class_prefix(_inner_class_prefix)
_test_script_objects = []
_new_summary = _utils.Summary.new()
_log_text = ""
_current_test = null
_is_running = true
_yield_between.tests_since_last_yield = 0
var pre_hook_result = _validate_hook_script(_pre_run_script)
_pre_run_script_instance = pre_hook_result.instance
var post_hook_result = _validate_hook_script(_post_run_script)
_post_run_script_instance = post_hook_result.instance
valid = pre_hook_result.valid and post_hook_result.valid
return valid
# ------------------------------------------------------------------------------
# Print out run information and close out the run.
# ------------------------------------------------------------------------------
func _end_run():
_gui.end_run()
_print_summary()
p("\n")
# Do not count any of the _test_script_objects since these will be released
# when GUT is released.
_orphan_counter._counters.total += _test_script_objects.size()
if(_orphan_counter.get_counter('total') > 0 and _lgr.is_type_enabled('orphan')):
_orphan_counter.print_orphans('total', _lgr)
p("Note: This count does not include GUT objects that will be freed upon exit.")
p(" It also does not include any orphans created by global scripts")
p(" loaded before tests were ran.")
p(str("Total orphans = ", _orphan_counter.orphan_count()))
if(!_utils.is_null_or_empty(_select_script)):
p('Ran Scripts matching "' + _select_script + '"')
if(!_utils.is_null_or_empty(_unit_test_name)):
p('Ran Tests matching "' + _unit_test_name + '"')
if(!_utils.is_null_or_empty(_inner_class_name)):
p('Ran Inner Classes matching "' + _inner_class_name + '"')
# For some reason the text edit control isn't scrolling to the bottom after
# the summary is printed. As a workaround, yield for a short time and
# then move the cursor. I found this workaround through trial and error.
_yield_between.timer.set_wait_time(0.1)
_yield_between.timer.start()
yield(_yield_between.timer, 'timeout')
_gui.scroll_to_bottom()
_is_running = false
update()
_run_hook_script(_post_run_script_instance)
emit_signal(SIGNAL_TESTS_FINISHED)
_gui.set_title("Finished.")
# ------------------------------------------------------------------------------
# Checks the passed in thing to see if it is a "function state" object that gets
# returned when a function yields.
# ------------------------------------------------------------------------------
func _is_function_state(script_result):
return script_result != null and \
typeof(script_result) == TYPE_OBJECT and \
script_result is GDScriptFunctionState
# ------------------------------------------------------------------------------
# Print out the heading for a new script
# ------------------------------------------------------------------------------
func _print_script_heading(script):
if(_does_class_name_match(_inner_class_name, script.inner_class_name)):
var fmt = _lgr.fmts.underline
var divider = '-----------------------------------------'
var text = ''
if(script.inner_class_name == null):
text = script.path
else:
text = script.path + '.' + script.inner_class_name
_lgr.log("\n\n" + text, fmt)
if(!_utils.is_null_or_empty(_inner_class_name) and _does_class_name_match(_inner_class_name, script.inner_class_name)):
_lgr.log(str(' [',script.inner_class_name, '] matches [', _inner_class_name, ']'), fmt)
if(!_utils.is_null_or_empty(_unit_test_name)):
_lgr.log(' Only running tests like: "' + _unit_test_name + '"', fmt)
# ------------------------------------------------------------------------------
# Just gets more logic out of _test_the_scripts. Decides if we should yield after
# this test based on flags and counters.
# ------------------------------------------------------------------------------
func _should_yield_now():
var should = _yield_between.should and \
_yield_between.tests_since_last_yield == _yield_between.after_x_tests
if(should):
_yield_between.tests_since_last_yield = 0
else:
_yield_between.tests_since_last_yield += 1
return should
# ------------------------------------------------------------------------------
# Yes if the class name is null or the script's class name includes class_name
# ------------------------------------------------------------------------------
func _does_class_name_match(the_class_name, script_class_name):
return (the_class_name == null or the_class_name == '') or (script_class_name != null and script_class_name.findn(the_class_name) != -1)
# ------------------------------------------------------------------------------
# ------------------------------------------------------------------------------
func _setup_script(test_script):
test_script.gut = self
test_script.set_logger(_lgr)
add_child(test_script)
_test_script_objects.append(test_script)
# ------------------------------------------------------------------------------
# ------------------------------------------------------------------------------
func _do_yield_between(time):
_yield_between.timer.set_wait_time(time)
_yield_between.timer.start()
return _yield_between.timer
# ------------------------------------------------------------------------------
# ------------------------------------------------------------------------------
func _wait_for_done(result):
var iter_counter = 0
var print_after = 3
# sets waiting to false.
result.connect('completed', self, '_on_test_script_yield_completed')
if(!_was_yield_method_called):
_lgr.log('-- Yield detected, waiting --', _lgr.fmts.yellow)
_was_yield_method_called = false
_waiting = true
_wait_timer.set_wait_time(0.4)
var dots = ''
while(_waiting):
iter_counter += 1
_lgr.yield_text('waiting' + dots)
_wait_timer.start()
yield(_wait_timer, 'timeout')
dots += '.'
if(dots.length() > 5):
dots = ''
_lgr.end_yield()
emit_signal('done_waiting')
# ------------------------------------------------------------------------------
# returns self so it can be integrated into the yield call.
# ------------------------------------------------------------------------------
func _wait_for_continue_button():
p(PAUSE_MESSAGE, 0)
_waiting = true
return self
# ------------------------------------------------------------------------------
# ------------------------------------------------------------------------------
func _call_deprecated_script_method(script, method, alt):
if(script.has_method(method)):
var txt = str(script, '-', method)
if(!_deprecated_tracker.has(txt)):
# Removing the deprecated line. I think it's still too early to
# start bothering people with this. Left everything here though
# because I don't want to remember how I did this last time.
#_lgr.deprecated(str('The method ', method, ' has been deprecated, use ', alt, ' instead.'))
_deprecated_tracker.add(txt)
script.call(method)
# ------------------------------------------------------------------------------
# ------------------------------------------------------------------------------
func _get_indexes_matching_script_name(name):
var indexes = [] # empty runs all
for i in range(_test_collector.scripts.size()):
if(_test_collector.scripts[i].get_filename().find(name) != -1):
indexes.append(i)
return indexes
# ------------------------------------------------------------------------------
# ------------------------------------------------------------------------------
func _get_indexes_matching_path(path):
var indexes = []
for i in range(_test_collector.scripts.size()):
if(_test_collector.scripts[i].path == path):
indexes.append(i)
return indexes
# ------------------------------------------------------------------------------
# Execute all calls of a parameterized test.
# ------------------------------------------------------------------------------
func _parameterized_call(test_script):
var script_result = test_script.call(_current_test.name)
if(_is_function_state(script_result)):
_wait_for_done(script_result)
yield(self, 'done_waiting')
if(_parameter_handler == null):
_lgr.error(str('Parameterized test ', _current_test.name, ' did not call use_parameters for the default value of the parameter.'))
_fail(str('Parameterized test ', _current_test.name, ' did not call use_parameters for the default value of the parameter.'))
else:
while(!_parameter_handler.is_done()):
script_result = test_script.call(_current_test.name)
if(_is_function_state(script_result)):
_wait_for_done(script_result)
yield(self, 'done_waiting')
script_result = null
_parameter_handler = null
emit_signal(SIGNAL_PRAMETERIZED_YIELD_DONE)
# ------------------------------------------------------------------------------
# Run all tests in a script. This is the core logic for running tests.
#
# Note, this has to stay as a giant monstrosity of a method because of the
# yields.
# ------------------------------------------------------------------------------
func _test_the_scripts(indexes=[]):
_orphan_counter.add_counter('total')
_print_versions(false)
var is_valid = _init_run()
if(!is_valid):
_lgr.error('Something went wrong and the run was aborted.')
return
_run_hook_script(_pre_run_script_instance)
if(_pre_run_script_instance!= null and _pre_run_script_instance.should_abort()):
_lgr.error('pre-run abort')
emit_signal(SIGNAL_TESTS_FINISHED)
return
_gui.run_mode()
var indexes_to_run = []
if(indexes.size()==0):
for i in range(_test_collector.scripts.size()):
indexes_to_run.append(i)
else:
indexes_to_run = indexes
_gui.set_progress_script_max(indexes_to_run.size()) # New way
_gui.set_progress_script_value(0)
if(_doubler.get_strategy() == _utils.DOUBLE_STRATEGY.FULL):
_lgr.info("Using Double Strategy FULL as default strategy. Keep an eye out for weirdness, this is still experimental.")
# loop through scripts
for test_indexes in range(indexes_to_run.size()):
var the_script = _test_collector.scripts[indexes_to_run[test_indexes]]
_orphan_counter.add_counter('script')
if(the_script.tests.size() > 0):
_gui.set_title(the_script.get_full_name())
_lgr.set_indent_level(0)
_print_script_heading(the_script)
_new_summary.add_script(the_script.get_full_name())
var test_script = the_script.get_new()
var script_result = null
_setup_script(test_script)
_doubler.set_strategy(_double_strategy)
# yield between test scripts so things paint
if(_yield_between.should):
yield(_do_yield_between(0.01), 'timeout')
# !!!
# Hack so there isn't another indent to this monster of a method. if
# inner class is set and we do not have a match then empty the tests
# for the current test.
# !!!
if(!_does_class_name_match(_inner_class_name, the_script.inner_class_name)):
the_script.tests = []
else:
# call both pre-all-tests methods until prerun_setup is removed
_call_deprecated_script_method(test_script, 'prerun_setup', 'before_all')
test_script.before_all()
_gui.set_progress_test_max(the_script.tests.size()) # New way
# Each test in the script
for i in range(the_script.tests.size()):
_stubber.clear()
_spy.clear()
_doubler.clear_output_directory()
_current_test = the_script.tests[i]
if((_unit_test_name != '' and _current_test.name.find(_unit_test_name) > -1) or
(_unit_test_name == '')):
_lgr.log_test_name()
_lgr.set_indent_level(1)
_orphan_counter.add_counter('test')
# yield so things paint
if(_should_yield_now()):
yield(_do_yield_between(0.001), 'timeout')
_call_deprecated_script_method(test_script, 'setup', 'before_each')
test_script.before_each()
# When the script yields it will return a GDScriptFunctionState object
if(_current_test.arg_count > 1):
_lgr.error(str('Parameterized test ', _current_test.name, ' has too many parameters: ', _current_test.arg_count, '.'))
elif(_current_test.arg_count == 1):
script_result = _parameterized_call(test_script)
if(_is_function_state(script_result)):
yield(self, SIGNAL_PRAMETERIZED_YIELD_DONE)
script_result = null
else:
script_result = test_script.call(_current_test.name)
_new_summary.add_test(_current_test.name)
if(_is_function_state(script_result)):
_wait_for_done(script_result)
yield(script_result, 'completed')
_lgr.end_yield()
#if the test called pause_before_teardown then yield until
#the continue button is pressed.
if(_pause_before_teardown and !_ignore_pause_before_teardown):
_gui.pause()
yield(_wait_for_continue_button(), SIGNAL_STOP_YIELD_BEFORE_TEARDOWN)
test_script.clear_signal_watcher()
# call each post-each-test method until teardown is removed.
_call_deprecated_script_method(test_script, 'teardown', 'after_each')
test_script.after_each()
# Free up everything in the _autofree. Yield for a bit if we
# have anything with a queue_free so that they have time to
# free and are not found by the orphan counter.
var aqf_count = _autofree.get_queue_free_count()
_autofree.free_all()
if(aqf_count > 0):
yield(_do_yield_between(0.01), 'timeout')
# ------
if(_log_level > 0):
_orphan_counter.print_orphans('test', _lgr)
_current_test.has_printed_name = false
_gui.set_progress_test_value(i + 1)
_doubler.get_ignored_methods().clear()
_current_test = null
_lgr.dec_indent()
_orphan_counter.print_orphans('script', _lgr)
# call both post-all-tests methods until postrun_teardown is removed.
if(_does_class_name_match(_inner_class_name, the_script.inner_class_name)):
_call_deprecated_script_method(test_script, 'postrun_teardown', 'after_all')
test_script.after_all()
_log_test_children_warning(test_script)
# This might end up being very resource intensive if the scripts
# don't clean up after themselves. Might have to consolidate output
# into some other structure and kill the script objects with
# test_script.free() instead of remove child.
remove_child(test_script)
# END TESTS IN SCRIPT LOOP
_lgr.set_indent_level(0)
if(test_script.get_assert_count() > 0):
var script_sum = str(test_script.get_pass_count(), '/', test_script.get_assert_count(), ' passed.')
_lgr.log(script_sum, _lgr.fmts.bold)
_gui.set_progress_script_value(test_indexes + 1) # new way
# END TEST SCRIPT LOOP
_lgr.set_indent_level(0)
_end_run()
# ------------------------------------------------------------------------------
# ------------------------------------------------------------------------------
func _pass(text=''):
_gui.add_passing() # increments counters
if(_current_test):
_new_summary.add_pass(_current_test.name, text)
# ------------------------------------------------------------------------------
# ------------------------------------------------------------------------------
func _fail(text=''):
_gui.add_failing() # increments counters
if(_current_test != null):
var line_text = ' at line ' + str(_extractLineNumber( _current_test))
p(line_text, LOG_LEVEL_FAIL_ONLY)
# format for summary
line_text = "\n " + line_text
var call_count_text = ''
if(_parameter_handler != null):
call_count_text = str('(call #', _parameter_handler.get_call_count(), ') ')
_new_summary.add_fail(_current_test.name, call_count_text + text + line_text)
_current_test.passed = false
# ------------------------------------------------------------------------------
# Extracts the line number from curren stacktrace by matching the test case name
# ------------------------------------------------------------------------------
func _extractLineNumber(current_test):
var line_number = current_test.line_number
# if stack trace available than extraxt the test case line number
var stackTrace = get_stack()
if(stackTrace!=null):
for index in stackTrace.size():
var line = stackTrace[index]
var function = line.get("function")
if function == current_test.name:
line_number = line.get("line")
return line_number
# ------------------------------------------------------------------------------
# ------------------------------------------------------------------------------
func _pending(text=''):
if(_current_test):
_new_summary.add_pending(_current_test.name, text)
# ------------------------------------------------------------------------------
# Gets all the files in a directory and all subdirectories if get_include_subdirectories
# is true. The files returned are all sorted by name.
# ------------------------------------------------------------------------------
func _get_files(path, prefix, suffix):
var files = []
var directories = []
var d = Directory.new()
d.open(path)
# true parameter tells list_dir_begin not to include "." and ".." directories.
d.list_dir_begin(true)
# Traversing a directory is kinda odd. You have to start the process of listing
# the contents of a directory with list_dir_begin then use get_next until it
# returns an empty string. Then I guess you should end it.
var fs_item = d.get_next()
var full_path = ''
while(fs_item != ''):
full_path = path.plus_file(fs_item)
#file_exists returns fasle for directories
if(d.file_exists(full_path)):
if(fs_item.begins_with(prefix) and fs_item.ends_with(suffix)):
files.append(full_path)
elif(get_include_subdirectories() and d.dir_exists(full_path)):
directories.append(full_path)
fs_item = d.get_next()
d.list_dir_end()
for dir in range(directories.size()):
var dir_files = _get_files(directories[dir], prefix, suffix)
for i in range(dir_files.size()):
files.append(dir_files[i])
files.sort()
return files
#########################
#
# public
#
#########################
# ------------------------------------------------------------------------------
# Conditionally prints the text to the console/results variable based on the
# current log level and what level is passed in. Whenever currently in a test,
# the text will be indented under the test. It can be further indented if
# desired.
#
# The first time output is generated when in a test, the test name will be
# printed.
#
# NOT_USED_ANYMORE was indent level. This was deprecated in 7.0.0.
# ------------------------------------------------------------------------------
func p(text, level=0, NOT_USED_ANYMORE=-123):
if(NOT_USED_ANYMORE != -123):
_lgr.deprecated('gut.p no longer supports the optional 3rd parameter for indent_level parameter.')
var str_text = str(text)
if(level <= _utils.nvl(_log_level, 0)):
_lgr.log(str_text)
################
#
# RUN TESTS/ADD SCRIPTS
#
################
func get_minimum_size():
return Vector2(810, 380)
# ------------------------------------------------------------------------------
# Runs all the scripts that were added using add_script
# ------------------------------------------------------------------------------
func test_scripts(run_rest=false):
clear_text()
if(_script_name != null and _script_name != ''):
var indexes = _get_indexes_matching_script_name(_script_name)
if(indexes == []):
_lgr.error('Could not find script matching ' + _script_name)
else:
_test_the_scripts(indexes)
else:
_test_the_scripts([])
# alias
func run_tests(run_rest=false):
test_scripts(run_rest)
# ------------------------------------------------------------------------------
# Runs a single script passed in.
# ------------------------------------------------------------------------------
func test_script(script):
_test_collector.set_test_class_prefix(_inner_class_prefix)
_test_collector.clear()
_test_collector.add_script(script)
_test_the_scripts()
# ------------------------------------------------------------------------------
# Adds a script to be run when test_scripts called.
# ------------------------------------------------------------------------------
func add_script(script):
if(!Engine.is_editor_hint()):
_test_collector.set_test_class_prefix(_inner_class_prefix)
_test_collector.add_script(script)
_add_scripts_to_gui()
# ------------------------------------------------------------------------------
# Add all scripts in the specified directory that start with the prefix and end
# with the suffix. Does not look in sub directories. Can be called multiple
# times.
# ------------------------------------------------------------------------------
func add_directory(path, prefix=_file_prefix, suffix=_file_extension):
# check for '' b/c the calls to addin the exported directories 1-6 will pass
# '' if the field has not been populated. This will cause res:// to be
# processed which will include all files if include_subdirectories is true.
if(path == '' or path == null):
return
var d = Directory.new()
if(!d.dir_exists(path)):
_lgr.error(str('The path [', path, '] does not exist.'))
OS.exit_code = 1
else:
var files = _get_files(path, prefix, suffix)
for i in range(files.size()):
add_script(files[i])
# ------------------------------------------------------------------------------
# This will try to find a script in the list of scripts to test that contains
# the specified script name. It does not have to be a full match. It will
# select the first matching occurrence so that this script will run when run_tests
# is called. Works the same as the select_this_one option of add_script.
#
# returns whether it found a match or not
# ------------------------------------------------------------------------------
func select_script(script_name):
_script_name = script_name
# ------------------------------------------------------------------------------
# ------------------------------------------------------------------------------
func export_tests(path=_export_path):
if(path == null):
_lgr.error('You must pass a path or set the export_path before calling export_tests')
else:
var result = _test_collector.export_tests(path)
if(result):
p(_test_collector.to_s())
p("Exported to " + path)
# ------------------------------------------------------------------------------
# ------------------------------------------------------------------------------