Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
godotengine
GitHub Repository: godotengine/godot
Path: blob/master/tests/create_test.py
9887 views
1
#!/usr/bin/env python3
2
3
import argparse
4
import os
5
import re
6
import sys
7
from subprocess import call
8
9
10
def main():
11
# Change to the directory where the script is located,
12
# so that the script can be run from any location.
13
os.chdir(os.path.dirname(os.path.realpath(__file__)))
14
15
parser = argparse.ArgumentParser(description="Creates a new unit test file.")
16
parser.add_argument(
17
"name",
18
type=str,
19
help="Specifies the class or component name to be tested, in PascalCase (e.g., MeshInstance3D). The name will be prefixed with 'test_' for the header file and 'Test' for the namespace.",
20
)
21
parser.add_argument(
22
"path",
23
type=str,
24
nargs="?",
25
help="The path to the unit test file relative to the tests folder (e.g. core). This should correspond to the relative path of the class or component being tested. (default: .)",
26
default=".",
27
)
28
parser.add_argument(
29
"-i",
30
"--invasive",
31
action="store_true",
32
help="if set, the script will automatically insert the include directive in test_main.cpp. Use with caution!",
33
)
34
args = parser.parse_args()
35
36
snake_case_regex = re.compile(r"(?<!^)(?=[A-Z, 0-9])")
37
# Replace 2D, 3D, and 4D with 2d, 3d, and 4d, respectively. This avoids undesired splits like node_3_d.
38
prefiltered_name = re.sub(r"([234])D", lambda match: match.group(1).lower() + "d", args.name)
39
name_snake_case = snake_case_regex.sub("_", prefiltered_name).lower()
40
file_path = os.path.normpath(os.path.join(args.path, f"test_{name_snake_case}.h"))
41
42
# Ensure the directory exists.
43
os.makedirs(os.path.dirname(file_path), exist_ok=True)
44
45
print(file_path)
46
if os.path.isfile(file_path):
47
print(f'ERROR: The file "{file_path}" already exists.')
48
sys.exit(1)
49
with open(file_path, "w", encoding="utf-8", newline="\n") as file:
50
file.write(
51
"""/**************************************************************************/
52
/* test_{name_snake_case}.h {padding} */
53
/**************************************************************************/
54
/* This file is part of: */
55
/* GODOT ENGINE */
56
/* https://godotengine.org */
57
/**************************************************************************/
58
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
59
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
60
/* */
61
/* Permission is hereby granted, free of charge, to any person obtaining */
62
/* a copy of this software and associated documentation files (the */
63
/* "Software"), to deal in the Software without restriction, including */
64
/* without limitation the rights to use, copy, modify, merge, publish, */
65
/* distribute, sublicense, and/or sell copies of the Software, and to */
66
/* permit persons to whom the Software is furnished to do so, subject to */
67
/* the following conditions: */
68
/* */
69
/* The above copyright notice and this permission notice shall be */
70
/* included in all copies or substantial portions of the Software. */
71
/* */
72
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
73
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
74
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
75
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
76
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
77
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
78
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
79
/**************************************************************************/
80
81
#pragma once
82
83
#include "tests/test_macros.h"
84
85
namespace Test{name_pascal_case} {{
86
87
TEST_CASE("[{name_pascal_case}] Example test case") {{
88
// TODO: Remove this comment and write your test code here.
89
}}
90
91
}} // namespace Test{name_pascal_case}
92
""".format(
93
name_snake_case=name_snake_case,
94
# Capitalize the first letter but keep capitalization for the rest of the string.
95
# This is done in case the user passes a camelCase string instead of PascalCase.
96
name_pascal_case=args.name[0].upper() + args.name[1:],
97
# The padding length depends on the test name length.
98
padding=" " * (61 - len(name_snake_case)),
99
)
100
)
101
102
# Print an absolute path so it can be Ctrl + clicked in some IDEs and terminal emulators.
103
print("Test header file created:")
104
print(os.path.abspath(file_path))
105
106
if args.invasive:
107
print("Trying to insert include directive in test_main.cpp...")
108
with open("test_main.cpp", "r", encoding="utf-8") as file:
109
contents = file.read()
110
match = re.search(r'#include "tests.*\n', contents)
111
112
if match:
113
new_string = contents[: match.start()] + f'#include "tests/{file_path}"\n' + contents[match.start() :]
114
115
with open("test_main.cpp", "w", encoding="utf-8", newline="\n") as file:
116
file.write(new_string)
117
print("Done.")
118
# Use clang format to sort include directives afster insertion.
119
clang_format_args = ["clang-format", "test_main.cpp", "-i"]
120
retcode = call(clang_format_args)
121
if retcode != 0:
122
print(
123
"Include directives in test_main.cpp could not be sorted automatically using clang-format. Please sort them manually."
124
)
125
else:
126
print("Could not find a valid position in test_main.cpp to insert the include directive.")
127
128
else:
129
print("\nRemember to #include the new test header in this file (following alphabetical order):")
130
print(os.path.abspath("test_main.cpp"))
131
print("Insert the following line in the appropriate place:")
132
print(f'#include "tests/{file_path}"')
133
134
135
if __name__ == "__main__":
136
main()
137
138