create_test.py 6.3 KB

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