Debian Codegraph @

godot/addons/gut/utils.gd

raw
1 # ##############################################################################
2 #(G)odot (U)nit (T)est class
3 #
4 # ##############################################################################
5 # The MIT License (MIT)
6 # =====================
7 #
8 # Copyright (c) 2020 Tom "Butch" Wesley
9 #
10 # Permission is hereby granted, free of charge, to any person obtaining a copy
11 # of this software and associated documentation files (the "Software"), to deal
12 # in the Software without restriction, including without limitation the rights
13 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14 # copies of the Software, and to permit persons to whom the Software is
15 # furnished to do so, subject to the following conditions:
16 #
17 # The above copyright notice and this permission notice shall be included in
18 # all copies or substantial portions of the Software.
19 #
20 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
26 # THE SOFTWARE.
27 #
28 # ##############################################################################
29 # Description
30 # -----------
31 # This class is a PSUEDO SINGLETON. You should not make instances of it but use
32 # the get_instance static method.
33 # ##############################################################################
34 extends Node
35
36 # ------------------------------------------------------------------------------
37 # The instance name as a function since you can't have static variables.
38 # ------------------------------------------------------------------------------
39 static func INSTANCE_NAME():
40 return '__GutUtilsInstName__'
41
42 # ------------------------------------------------------------------------------
43 # Gets the root node without having to be in the tree and pushing out an error
44 # if we don't have a main loop ready to go yet.
45 # ------------------------------------------------------------------------------
46 static func get_root_node():
47 var to_return = null
48 var main_loop = Engine.get_main_loop()
49 if(main_loop != null):
50 return main_loop.root
51 else:
52 push_error('No Main Loop Yet')
53 return null
54
55 # ------------------------------------------------------------------------------
56 # Get the ONE instance of utils
57 # ------------------------------------------------------------------------------
58 static func get_instance():
59 var the_root = get_root_node()
60 var inst = null
61 if(the_root.has_node(INSTANCE_NAME())):
62 inst = the_root.get_node(INSTANCE_NAME())
63 else:
64 inst = load('res://addons/gut/utils.gd').new()
65 inst.set_name(INSTANCE_NAME())
66 the_root.add_child(inst)
67 return inst
68
69 var Logger = load('res://addons/gut/logger.gd') # everything should use get_logger
70 var _lgr = null
71
72 var _test_mode = false
73
74 var AutoFree = load('res://addons/gut/autofree.gd')
75 var Comparator = load('res://addons/gut/comparator.gd')
76 var CompareResult = load('res://addons/gut/compare_result.gd')
77 var DiffTool = load('res://addons/gut/diff_tool.gd')
78 var Doubler = load('res://addons/gut/doubler.gd')
79 var Gut = load('res://addons/gut/gut.gd')
80 var HookScript = load('res://addons/gut/hook_script.gd')
81 var MethodMaker = load('res://addons/gut/method_maker.gd')
82 var OneToMany = load('res://addons/gut/one_to_many.gd')
83 var OrphanCounter = load('res://addons/gut/orphan_counter.gd')
84 var ParameterFactory = load('res://addons/gut/parameter_factory.gd')
85 var ParameterHandler = load('res://addons/gut/parameter_handler.gd')
86 var Printers = load('res://addons/gut/printers.gd')
87 var Spy = load('res://addons/gut/spy.gd')
88 var Strutils = load('res://addons/gut/strutils.gd')
89 var Stubber = load('res://addons/gut/stubber.gd')
90 var StubParams = load('res://addons/gut/stub_params.gd')
91 var Summary = load('res://addons/gut/summary.gd')
92 var Test = load('res://addons/gut/test.gd')
93 var TestCollector = load('res://addons/gut/test_collector.gd')
94 var ThingCounter = load('res://addons/gut/thing_counter.gd')
95
96 # Source of truth for the GUT version
97 var version = '7.1.0'
98 # The required Godot version as an array.
99 var req_godot = [3, 2, 0]
100 # Used for doing file manipulation stuff so as to not keep making File instances.
101 # could be a bit of overkill but who cares.
102 var _file_checker = File.new()
103
104 const GUT_METADATA = '__gut_metadata_'
105
106 enum DOUBLE_STRATEGY{
107 FULL,
108 PARTIAL
109 }
110
111 enum DIFF {
112 DEEP,
113 SHALLOW,
114 SIMPLE
115 }
116
117 # ------------------------------------------------------------------------------
118 # Blurb of text with GUT and Godot versions.
119 # ------------------------------------------------------------------------------
120 func get_version_text():
121 var v_info = Engine.get_version_info()
122 var gut_version_info = str('GUT version: ', version)
123 var godot_version_info = str('Godot version: ', v_info.major, '.', v_info.minor, '.', v_info.patch)
124 return godot_version_info + "\n" + gut_version_info
125
126
127 # ------------------------------------------------------------------------------
128 # Returns a nice string for erroring out when we have a bad Godot version.
129 # ------------------------------------------------------------------------------
130 func get_bad_version_text():
131 var ver = join_array(req_godot, '.')
132 var info = Engine.get_version_info()
133 var gd_version = str(info.major, '.', info.minor, '.', info.patch)
134 return 'GUT ' + version + ' requires Godot ' + ver + ' or greater. Godot version is ' + gd_version
135
136
137 # ------------------------------------------------------------------------------
138 # Checks the Godot version against req_godot array.
139 # ------------------------------------------------------------------------------
140 func is_version_ok(engine_info=Engine.get_version_info(),required=req_godot):
141 var is_ok = null
142 var engine_array = [engine_info.major, engine_info.minor, engine_info.patch]
143
144 var idx = 0
145 while(is_ok == null and idx < engine_array.size()):
146 if(int(engine_array[idx]) > int(required[idx])):
147 is_ok = true
148 elif(int(engine_array[idx]) < int(required[idx])):
149 is_ok = false
150
151 idx += 1
152
153 # still null means each index was the same.
154 return nvl(is_ok, true)
155
156
157 # ------------------------------------------------------------------------------
158 # Everything should get a logger through this.
159 #
160 # When running in test mode this will always return a new logger so that errors
161 # are not caused by getting bad warn/error/etc counts.
162 # ------------------------------------------------------------------------------
163 func get_logger():
164 if(_test_mode):
165 return Logger.new()
166 else:
167 if(_lgr == null):
168 _lgr = Logger.new()
169 return _lgr
170
171
172 # ------------------------------------------------------------------------------
173 # Returns an array created by splitting the string by the delimiter
174 # ------------------------------------------------------------------------------
175 func split_string(to_split, delim):
176 var to_return = []
177
178 var loc = to_split.find(delim)
179 while(loc != -1):
180 to_return.append(to_split.substr(0, loc))
181 to_split = to_split.substr(loc + 1, to_split.length() - loc)
182 loc = to_split.find(delim)
183 to_return.append(to_split)
184 return to_return
185
186
187 # ------------------------------------------------------------------------------
188 # Returns a string containing all the elements in the array separated by delim
189 # ------------------------------------------------------------------------------
190 func join_array(a, delim):
191 var to_return = ''
192 for i in range(a.size()):
193 to_return += str(a[i])
194 if(i != a.size() -1):
195 to_return += str(delim)
196 return to_return
197
198
199 # ------------------------------------------------------------------------------
200 # return if_null if value is null otherwise return value
201 # ------------------------------------------------------------------------------
202 func nvl(value, if_null):
203 if(value == null):
204 return if_null
205 else:
206 return value
207
208
209 # ------------------------------------------------------------------------------
210 # returns true if the object has been freed, false if not
211 #
212 # From what i've read, the weakref approach should work. It seems to work most
213 # of the time but sometimes it does not catch it. The str comparison seems to
214 # fill in the gaps. I've not seen any errors after adding that check.
215 # ------------------------------------------------------------------------------
216 func is_freed(obj):
217 var wr = weakref(obj)
218 return !(wr.get_ref() and str(obj) != '[Deleted Object]')
219
220
221 # ------------------------------------------------------------------------------
222 # Pretty self explanitory.
223 # ------------------------------------------------------------------------------
224 func is_not_freed(obj):
225 return !is_freed(obj)
226
227
228 # ------------------------------------------------------------------------------
229 # Checks if the passed in object is a GUT Double or Partial Double.
230 # ------------------------------------------------------------------------------
231 func is_double(obj):
232 var to_return = false
233 if(typeof(obj) == TYPE_OBJECT and is_instance_valid(obj)):
234 to_return = obj.has_method('__gut_instance_from_id')
235 return to_return
236
237
238 # ------------------------------------------------------------------------------
239 # Checks if the passed in is an instance of a class
240 # ------------------------------------------------------------------------------
241 func is_instance(obj):
242 return typeof(obj) == TYPE_OBJECT and !obj.has_method('new') and !obj.has_method('instance')
243
244
245 # ------------------------------------------------------------------------------
246 # Returns an array of values by calling get(property) on each element in source
247 # ------------------------------------------------------------------------------
248 func extract_property_from_array(source, property):
249 var to_return = []
250 for i in (source.size()):
251 to_return.append(source[i].get(property))
252 return to_return
253
254
255 # ------------------------------------------------------------------------------
256 # true if file exists, false if not.
257 # ------------------------------------------------------------------------------
258 func file_exists(path):
259 return _file_checker.file_exists(path)
260
261
262 # ------------------------------------------------------------------------------
263 # Write a file.
264 # ------------------------------------------------------------------------------
265 func write_file(path, content):
266 var f = File.new()
267 var result = f.open(path, f.WRITE)
268 if(result == OK):
269 f.store_string(content)
270 f.close()
271
272
273 # ------------------------------------------------------------------------------
274 # true if what is passed in is null or an empty string.
275 # ------------------------------------------------------------------------------
276 func is_null_or_empty(text):
277 return text == null or text == ''
278
279
280 # ------------------------------------------------------------------------------
281 # Get the name of a native class or null if the object passed in is not a
282 # native class.
283 # ------------------------------------------------------------------------------
284 func get_native_class_name(thing):
285 var to_return = null
286 if(is_native_class(thing)):
287 var newone = thing.new()
288 to_return = newone.get_class()
289 newone.free()
290 return to_return
291
292
293 # ------------------------------------------------------------------------------
294 # Checks an object to see if it is a GDScriptNativeClass
295 # ------------------------------------------------------------------------------
296 func is_native_class(thing):
297 var it_is = false
298 if(typeof(thing) == TYPE_OBJECT):
299 it_is = str(thing).begins_with("[GDScriptNativeClass:")
300 return it_is
301
302
303 # ------------------------------------------------------------------------------
304 # Returns the text of a file or an empty string if the file could not be opened.
305 # ------------------------------------------------------------------------------
306 func get_file_as_text(path):
307 var to_return = ''
308 var f = File.new()
309 var result = f.open(path, f.READ)
310 if(result == OK):
311 to_return = f.get_as_text()
312 f.close()
313 return to_return
314
315
316 # ------------------------------------------------------------------------------
317 # Loops through an array of things and calls a method or checks a property on
318 # each element until it finds the returned value. The item in the array is
319 # returned or null if it is not found.
320 # ------------------------------------------------------------------------------
321 func search_array(ar, prop_method, value):
322 var found = false
323 var idx = 0
324
325 while(idx < ar.size() and !found):
326 var item = ar[idx]
327 if(item.get(prop_method) != null):
328 if(item.get(prop_method) == value):
329 found = true
330 elif(item.has_method(prop_method)):
331 if(item.call(prop_method) == value):
332 found = true
333
334 if(!found):
335 idx += 1
336
337 if(found):
338 return ar[idx]
339 else:
340 return null
341
342
343 func are_datatypes_same(got, expected):
344 return !(typeof(got) != typeof(expected) and got != null and expected != null)