extends TestCase ## Identifiers from the engine's rendering, audio, UI and scene-tree areas. const FORBIDDEN: Array[String] = [ "RenderingServer", "PhysicsServer3D", "AudioServer", "AudioStream", "DisplayServer", "Node2D", "Node3D", "MeshInstance3D", "Camera3D", "Control", "CanvasItem", "Viewport", "SceneTree", "get_tree", "Input.", ] const NONDETERMINISTIC: Array[String] = ["Time.", "OS.get_ticks"] ## Global random calls. A method call on a seeded stream (stream.randf()) is allowed. const GLOBAL_RANDOM: String = "(? void: _scan(FORBIDDEN) func test_simulation_has_no_unseeded_randomness() -> void: _scan(NONDETERMINISTIC) func test_simulation_makes_no_global_random_calls() -> void: for path: String in _scripts_under("res://src/sim"): for line: String in _code_lines(path): if _global_random().search(line) != null: fail("%s makes a global random call: %s" % [path, line.strip_edges()]) func test_only_sim_rng_creates_generators() -> void: for path: String in _scripts_under("res://src/sim"): if path == RNG_OWNER: continue for line: String in _code_lines(path): if line.contains("RandomNumberGenerator.new"): fail("%s creates its own generator: %s" % [path, line.strip_edges()]) func test_scanner_tells_global_calls_from_seeded_ones() -> void: var pattern: RegEx = _global_random() assert_not_null(pattern.search("var x: float = randf()"), "global call must match") assert_not_null(pattern.search("foo(randi_range(1, 2))"), "nested global call must match") assert_null(pattern.search("var x: float = stream.randf()"), "seeded call must not match") assert_null(pattern.search("my_randf(1)"), "other identifiers must not match") func _global_random() -> RegEx: var pattern: RegEx = RegEx.new() pattern.compile(GLOBAL_RANDOM) return pattern func _code_lines(path: String) -> Array[String]: var lines: Array[String] = [] for line: String in FileAccess.get_file_as_string(path).split("\n"): lines.append(line.get_slice("#", 0)) return lines func _scan(needles: Array[String]) -> void: var paths: Array[String] = _scripts_under("res://src/sim") assert_true(not paths.is_empty(), "expected scripts in src/sim") for path: String in paths: for needle: String in needles: # Comments may mention these; only code counts. for line: String in _code_lines(path): if line.contains(needle): fail("%s uses %s: %s" % [path, needle, line.strip_edges()]) func _scripts_under(dir_path: String) -> Array[String]: var found: Array[String] = [] for name: String in DirAccess.get_files_at(dir_path): if name.ends_with(".gd"): found.append(dir_path.path_join(name)) for name: String in DirAccess.get_directories_at(dir_path): found.append_array(_scripts_under(dir_path.path_join(name))) return found