frida 16.2.0 → 16.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (386) hide show
  1. package/BSDmakefile +6 -0
  2. package/Makefile +16 -0
  3. package/README.md +14 -11
  4. package/configure +18 -0
  5. package/configure.bat +22 -0
  6. package/dist/native.js +0 -8
  7. package/lib/application.ts +98 -0
  8. package/lib/authentication.ts +3 -0
  9. package/lib/build.py +50 -0
  10. package/lib/bus.ts +30 -0
  11. package/lib/cancellable.ts +33 -0
  12. package/lib/child.ts +15 -0
  13. package/lib/crash.ts +11 -0
  14. package/lib/device.ts +329 -0
  15. package/lib/device_manager.ts +69 -0
  16. package/lib/endpoint_parameters.ts +56 -0
  17. package/lib/icon.ts +15 -0
  18. package/lib/index.ts +311 -0
  19. package/lib/iostream.ts +78 -0
  20. package/lib/meson.build +53 -0
  21. package/lib/native.ts +9 -0
  22. package/lib/portal_membership.ts +10 -0
  23. package/lib/portal_service.ts +105 -0
  24. package/lib/process.ts +57 -0
  25. package/lib/relay.ts +44 -0
  26. package/lib/script.ts +352 -0
  27. package/lib/session.ts +113 -0
  28. package/lib/signals.ts +45 -0
  29. package/lib/socket_address.ts +35 -0
  30. package/lib/spawn.ts +4 -0
  31. package/lib/system_parameters.ts +78 -0
  32. package/make.bat +23 -0
  33. package/meson.build +160 -0
  34. package/meson.options +11 -0
  35. package/package.json +27 -6
  36. package/releng/deps.py +1133 -0
  37. package/releng/deps.toml +391 -0
  38. package/releng/devkit-assets/frida-core-example-unix.c +188 -0
  39. package/releng/devkit-assets/frida-core-example-windows.c +197 -0
  40. package/releng/devkit-assets/frida-core-example.sln +28 -0
  41. package/releng/devkit-assets/frida-core-example.vcxproj +157 -0
  42. package/releng/devkit-assets/frida-core-example.vcxproj.filters +27 -0
  43. package/releng/devkit-assets/frida-gum-example-unix.c +122 -0
  44. package/releng/devkit-assets/frida-gum-example-windows.c +132 -0
  45. package/releng/devkit-assets/frida-gum-example.sln +28 -0
  46. package/releng/devkit-assets/frida-gum-example.vcxproj +157 -0
  47. package/releng/devkit-assets/frida-gum-example.vcxproj.filters +27 -0
  48. package/releng/devkit-assets/frida-gumjs-example-unix.c +84 -0
  49. package/releng/devkit-assets/frida-gumjs-example-windows.c +91 -0
  50. package/releng/devkit-assets/frida-gumjs-example.sln +28 -0
  51. package/releng/devkit-assets/frida-gumjs-example.vcxproj +157 -0
  52. package/releng/devkit-assets/frida-gumjs-example.vcxproj.filters +27 -0
  53. package/releng/devkit.py +535 -0
  54. package/releng/env.py +420 -0
  55. package/releng/env_android.py +150 -0
  56. package/releng/env_apple.py +176 -0
  57. package/releng/env_generic.py +373 -0
  58. package/releng/frida_version.py +69 -0
  59. package/releng/machine_file.py +44 -0
  60. package/releng/machine_spec.py +290 -0
  61. package/releng/meson/meson.py +27 -0
  62. package/releng/meson/mesonbuild/__init__.py +0 -0
  63. package/releng/meson/mesonbuild/_pathlib.py +63 -0
  64. package/releng/meson/mesonbuild/_typing.py +69 -0
  65. package/releng/meson/mesonbuild/arglist.py +321 -0
  66. package/releng/meson/mesonbuild/ast/__init__.py +23 -0
  67. package/releng/meson/mesonbuild/ast/interpreter.py +441 -0
  68. package/releng/meson/mesonbuild/ast/introspection.py +374 -0
  69. package/releng/meson/mesonbuild/ast/postprocess.py +109 -0
  70. package/releng/meson/mesonbuild/ast/printer.py +620 -0
  71. package/releng/meson/mesonbuild/ast/visitor.py +161 -0
  72. package/releng/meson/mesonbuild/backend/__init__.py +0 -0
  73. package/releng/meson/mesonbuild/backend/backends.py +2047 -0
  74. package/releng/meson/mesonbuild/backend/ninjabackend.py +3808 -0
  75. package/releng/meson/mesonbuild/backend/nonebackend.py +26 -0
  76. package/releng/meson/mesonbuild/backend/vs2010backend.py +2078 -0
  77. package/releng/meson/mesonbuild/backend/vs2012backend.py +35 -0
  78. package/releng/meson/mesonbuild/backend/vs2013backend.py +34 -0
  79. package/releng/meson/mesonbuild/backend/vs2015backend.py +35 -0
  80. package/releng/meson/mesonbuild/backend/vs2017backend.py +59 -0
  81. package/releng/meson/mesonbuild/backend/vs2019backend.py +54 -0
  82. package/releng/meson/mesonbuild/backend/vs2022backend.py +54 -0
  83. package/releng/meson/mesonbuild/backend/xcodebackend.py +1781 -0
  84. package/releng/meson/mesonbuild/build.py +3249 -0
  85. package/releng/meson/mesonbuild/cargo/__init__.py +5 -0
  86. package/releng/meson/mesonbuild/cargo/builder.py +238 -0
  87. package/releng/meson/mesonbuild/cargo/cfg.py +274 -0
  88. package/releng/meson/mesonbuild/cargo/interpreter.py +733 -0
  89. package/releng/meson/mesonbuild/cargo/manifest.py +227 -0
  90. package/releng/meson/mesonbuild/cargo/version.py +95 -0
  91. package/releng/meson/mesonbuild/cmake/__init__.py +28 -0
  92. package/releng/meson/mesonbuild/cmake/common.py +331 -0
  93. package/releng/meson/mesonbuild/cmake/data/__init__.py +0 -0
  94. package/releng/meson/mesonbuild/cmake/data/preload.cmake +82 -0
  95. package/releng/meson/mesonbuild/cmake/executor.py +241 -0
  96. package/releng/meson/mesonbuild/cmake/fileapi.py +324 -0
  97. package/releng/meson/mesonbuild/cmake/generator.py +186 -0
  98. package/releng/meson/mesonbuild/cmake/interpreter.py +1267 -0
  99. package/releng/meson/mesonbuild/cmake/toolchain.py +248 -0
  100. package/releng/meson/mesonbuild/cmake/traceparser.py +814 -0
  101. package/releng/meson/mesonbuild/cmake/tracetargets.py +161 -0
  102. package/releng/meson/mesonbuild/compilers/__init__.py +86 -0
  103. package/releng/meson/mesonbuild/compilers/asm.py +307 -0
  104. package/releng/meson/mesonbuild/compilers/c.py +788 -0
  105. package/releng/meson/mesonbuild/compilers/c_function_attributes.py +143 -0
  106. package/releng/meson/mesonbuild/compilers/compilers.py +1388 -0
  107. package/releng/meson/mesonbuild/compilers/cpp.py +1035 -0
  108. package/releng/meson/mesonbuild/compilers/cs.py +136 -0
  109. package/releng/meson/mesonbuild/compilers/cuda.py +806 -0
  110. package/releng/meson/mesonbuild/compilers/cython.py +91 -0
  111. package/releng/meson/mesonbuild/compilers/d.py +861 -0
  112. package/releng/meson/mesonbuild/compilers/detect.py +1396 -0
  113. package/releng/meson/mesonbuild/compilers/fortran.py +523 -0
  114. package/releng/meson/mesonbuild/compilers/java.py +113 -0
  115. package/releng/meson/mesonbuild/compilers/mixins/__init__.py +0 -0
  116. package/releng/meson/mesonbuild/compilers/mixins/arm.py +167 -0
  117. package/releng/meson/mesonbuild/compilers/mixins/ccrx.py +113 -0
  118. package/releng/meson/mesonbuild/compilers/mixins/clang.py +170 -0
  119. package/releng/meson/mesonbuild/compilers/mixins/clike.py +1330 -0
  120. package/releng/meson/mesonbuild/compilers/mixins/compcert.py +117 -0
  121. package/releng/meson/mesonbuild/compilers/mixins/elbrus.py +93 -0
  122. package/releng/meson/mesonbuild/compilers/mixins/emscripten.py +89 -0
  123. package/releng/meson/mesonbuild/compilers/mixins/gnu.py +629 -0
  124. package/releng/meson/mesonbuild/compilers/mixins/intel.py +167 -0
  125. package/releng/meson/mesonbuild/compilers/mixins/islinker.py +120 -0
  126. package/releng/meson/mesonbuild/compilers/mixins/metrowerks.py +279 -0
  127. package/releng/meson/mesonbuild/compilers/mixins/pgi.py +88 -0
  128. package/releng/meson/mesonbuild/compilers/mixins/ti.py +130 -0
  129. package/releng/meson/mesonbuild/compilers/mixins/visualstudio.py +458 -0
  130. package/releng/meson/mesonbuild/compilers/mixins/xc16.py +111 -0
  131. package/releng/meson/mesonbuild/compilers/objc.py +120 -0
  132. package/releng/meson/mesonbuild/compilers/objcpp.py +102 -0
  133. package/releng/meson/mesonbuild/compilers/rust.py +230 -0
  134. package/releng/meson/mesonbuild/compilers/swift.py +131 -0
  135. package/releng/meson/mesonbuild/compilers/vala.py +121 -0
  136. package/releng/meson/mesonbuild/coredata.py +1532 -0
  137. package/releng/meson/mesonbuild/dependencies/__init__.py +252 -0
  138. package/releng/meson/mesonbuild/dependencies/base.py +663 -0
  139. package/releng/meson/mesonbuild/dependencies/boost.py +1083 -0
  140. package/releng/meson/mesonbuild/dependencies/cmake.py +656 -0
  141. package/releng/meson/mesonbuild/dependencies/coarrays.py +80 -0
  142. package/releng/meson/mesonbuild/dependencies/configtool.py +163 -0
  143. package/releng/meson/mesonbuild/dependencies/cuda.py +295 -0
  144. package/releng/meson/mesonbuild/dependencies/data/CMakeLists.txt +102 -0
  145. package/releng/meson/mesonbuild/dependencies/data/CMakeListsLLVM.txt +204 -0
  146. package/releng/meson/mesonbuild/dependencies/data/CMakePathInfo.txt +31 -0
  147. package/releng/meson/mesonbuild/dependencies/data/__init__.py +0 -0
  148. package/releng/meson/mesonbuild/dependencies/detect.py +225 -0
  149. package/releng/meson/mesonbuild/dependencies/dev.py +707 -0
  150. package/releng/meson/mesonbuild/dependencies/dub.py +424 -0
  151. package/releng/meson/mesonbuild/dependencies/factory.py +146 -0
  152. package/releng/meson/mesonbuild/dependencies/framework.py +111 -0
  153. package/releng/meson/mesonbuild/dependencies/hdf5.py +168 -0
  154. package/releng/meson/mesonbuild/dependencies/misc.py +618 -0
  155. package/releng/meson/mesonbuild/dependencies/mpi.py +231 -0
  156. package/releng/meson/mesonbuild/dependencies/pkgconfig.py +570 -0
  157. package/releng/meson/mesonbuild/dependencies/platform.py +52 -0
  158. package/releng/meson/mesonbuild/dependencies/python.py +431 -0
  159. package/releng/meson/mesonbuild/dependencies/qt.py +484 -0
  160. package/releng/meson/mesonbuild/dependencies/scalapack.py +142 -0
  161. package/releng/meson/mesonbuild/dependencies/ui.py +281 -0
  162. package/releng/meson/mesonbuild/depfile.py +82 -0
  163. package/releng/meson/mesonbuild/envconfig.py +480 -0
  164. package/releng/meson/mesonbuild/environment.py +987 -0
  165. package/releng/meson/mesonbuild/interpreter/__init__.py +47 -0
  166. package/releng/meson/mesonbuild/interpreter/compiler.py +900 -0
  167. package/releng/meson/mesonbuild/interpreter/dependencyfallbacks.py +386 -0
  168. package/releng/meson/mesonbuild/interpreter/interpreter.py +3595 -0
  169. package/releng/meson/mesonbuild/interpreter/interpreterobjects.py +1096 -0
  170. package/releng/meson/mesonbuild/interpreter/kwargs.py +479 -0
  171. package/releng/meson/mesonbuild/interpreter/mesonmain.py +487 -0
  172. package/releng/meson/mesonbuild/interpreter/primitives/__init__.py +29 -0
  173. package/releng/meson/mesonbuild/interpreter/primitives/array.py +108 -0
  174. package/releng/meson/mesonbuild/interpreter/primitives/boolean.py +52 -0
  175. package/releng/meson/mesonbuild/interpreter/primitives/dict.py +88 -0
  176. package/releng/meson/mesonbuild/interpreter/primitives/integer.py +86 -0
  177. package/releng/meson/mesonbuild/interpreter/primitives/range.py +38 -0
  178. package/releng/meson/mesonbuild/interpreter/primitives/string.py +247 -0
  179. package/releng/meson/mesonbuild/interpreter/type_checking.py +853 -0
  180. package/releng/meson/mesonbuild/interpreterbase/__init__.py +126 -0
  181. package/releng/meson/mesonbuild/interpreterbase/_unholder.py +25 -0
  182. package/releng/meson/mesonbuild/interpreterbase/baseobjects.py +174 -0
  183. package/releng/meson/mesonbuild/interpreterbase/decorators.py +806 -0
  184. package/releng/meson/mesonbuild/interpreterbase/disabler.py +35 -0
  185. package/releng/meson/mesonbuild/interpreterbase/exceptions.py +22 -0
  186. package/releng/meson/mesonbuild/interpreterbase/helpers.py +67 -0
  187. package/releng/meson/mesonbuild/interpreterbase/interpreterbase.py +665 -0
  188. package/releng/meson/mesonbuild/interpreterbase/operator.py +32 -0
  189. package/releng/meson/mesonbuild/linkers/__init__.py +20 -0
  190. package/releng/meson/mesonbuild/linkers/base.py +39 -0
  191. package/releng/meson/mesonbuild/linkers/detect.py +229 -0
  192. package/releng/meson/mesonbuild/linkers/linkers.py +1614 -0
  193. package/releng/meson/mesonbuild/mcompile.py +380 -0
  194. package/releng/meson/mesonbuild/mconf.py +368 -0
  195. package/releng/meson/mesonbuild/mdevenv.py +234 -0
  196. package/releng/meson/mesonbuild/mdist.py +376 -0
  197. package/releng/meson/mesonbuild/mesondata.py +38 -0
  198. package/releng/meson/mesonbuild/mesonlib.py +23 -0
  199. package/releng/meson/mesonbuild/mesonmain.py +289 -0
  200. package/releng/meson/mesonbuild/minit.py +204 -0
  201. package/releng/meson/mesonbuild/minstall.py +864 -0
  202. package/releng/meson/mesonbuild/mintro.py +667 -0
  203. package/releng/meson/mesonbuild/mlog.py +542 -0
  204. package/releng/meson/mesonbuild/modules/__init__.py +270 -0
  205. package/releng/meson/mesonbuild/modules/cmake.py +442 -0
  206. package/releng/meson/mesonbuild/modules/cuda.py +377 -0
  207. package/releng/meson/mesonbuild/modules/dlang.py +117 -0
  208. package/releng/meson/mesonbuild/modules/external_project.py +306 -0
  209. package/releng/meson/mesonbuild/modules/fs.py +323 -0
  210. package/releng/meson/mesonbuild/modules/gnome.py +2215 -0
  211. package/releng/meson/mesonbuild/modules/hotdoc.py +487 -0
  212. package/releng/meson/mesonbuild/modules/i18n.py +405 -0
  213. package/releng/meson/mesonbuild/modules/icestorm.py +123 -0
  214. package/releng/meson/mesonbuild/modules/java.py +112 -0
  215. package/releng/meson/mesonbuild/modules/keyval.py +65 -0
  216. package/releng/meson/mesonbuild/modules/modtest.py +33 -0
  217. package/releng/meson/mesonbuild/modules/pkgconfig.py +744 -0
  218. package/releng/meson/mesonbuild/modules/python.py +556 -0
  219. package/releng/meson/mesonbuild/modules/python3.py +85 -0
  220. package/releng/meson/mesonbuild/modules/qt.py +621 -0
  221. package/releng/meson/mesonbuild/modules/qt4.py +23 -0
  222. package/releng/meson/mesonbuild/modules/qt5.py +23 -0
  223. package/releng/meson/mesonbuild/modules/qt6.py +22 -0
  224. package/releng/meson/mesonbuild/modules/rust.py +355 -0
  225. package/releng/meson/mesonbuild/modules/simd.py +114 -0
  226. package/releng/meson/mesonbuild/modules/sourceset.py +291 -0
  227. package/releng/meson/mesonbuild/modules/wayland.py +151 -0
  228. package/releng/meson/mesonbuild/modules/windows.py +207 -0
  229. package/releng/meson/mesonbuild/mparser.py +1114 -0
  230. package/releng/meson/mesonbuild/msetup.py +365 -0
  231. package/releng/meson/mesonbuild/msubprojects.py +764 -0
  232. package/releng/meson/mesonbuild/mtest.py +2201 -0
  233. package/releng/meson/mesonbuild/munstable_coredata.py +107 -0
  234. package/releng/meson/mesonbuild/optinterpreter.py +276 -0
  235. package/releng/meson/mesonbuild/programs.py +367 -0
  236. package/releng/meson/mesonbuild/rewriter.py +1075 -0
  237. package/releng/meson/mesonbuild/scripts/__init__.py +10 -0
  238. package/releng/meson/mesonbuild/scripts/clangformat.py +55 -0
  239. package/releng/meson/mesonbuild/scripts/clangtidy.py +30 -0
  240. package/releng/meson/mesonbuild/scripts/cleantrees.py +35 -0
  241. package/releng/meson/mesonbuild/scripts/cmake_run_ctgt.py +103 -0
  242. package/releng/meson/mesonbuild/scripts/cmd_or_ps.ps1 +17 -0
  243. package/releng/meson/mesonbuild/scripts/copy.py +19 -0
  244. package/releng/meson/mesonbuild/scripts/coverage.py +214 -0
  245. package/releng/meson/mesonbuild/scripts/delwithsuffix.py +27 -0
  246. package/releng/meson/mesonbuild/scripts/depfixer.py +495 -0
  247. package/releng/meson/mesonbuild/scripts/depscan.py +198 -0
  248. package/releng/meson/mesonbuild/scripts/dirchanger.py +20 -0
  249. package/releng/meson/mesonbuild/scripts/env2mfile.py +402 -0
  250. package/releng/meson/mesonbuild/scripts/externalproject.py +106 -0
  251. package/releng/meson/mesonbuild/scripts/gettext.py +86 -0
  252. package/releng/meson/mesonbuild/scripts/gtkdochelper.py +286 -0
  253. package/releng/meson/mesonbuild/scripts/hotdochelper.py +40 -0
  254. package/releng/meson/mesonbuild/scripts/itstool.py +77 -0
  255. package/releng/meson/mesonbuild/scripts/meson_exe.py +115 -0
  256. package/releng/meson/mesonbuild/scripts/msgfmthelper.py +29 -0
  257. package/releng/meson/mesonbuild/scripts/pycompile.py +54 -0
  258. package/releng/meson/mesonbuild/scripts/python_info.py +121 -0
  259. package/releng/meson/mesonbuild/scripts/regen_checker.py +55 -0
  260. package/releng/meson/mesonbuild/scripts/run_tool.py +58 -0
  261. package/releng/meson/mesonbuild/scripts/scanbuild.py +57 -0
  262. package/releng/meson/mesonbuild/scripts/symbolextractor.py +322 -0
  263. package/releng/meson/mesonbuild/scripts/tags.py +44 -0
  264. package/releng/meson/mesonbuild/scripts/test_loaded_modules.py +14 -0
  265. package/releng/meson/mesonbuild/scripts/uninstall.py +41 -0
  266. package/releng/meson/mesonbuild/scripts/vcstagger.py +35 -0
  267. package/releng/meson/mesonbuild/scripts/yasm.py +24 -0
  268. package/releng/meson/mesonbuild/templates/__init__.py +0 -0
  269. package/releng/meson/mesonbuild/templates/cpptemplates.py +143 -0
  270. package/releng/meson/mesonbuild/templates/cstemplates.py +90 -0
  271. package/releng/meson/mesonbuild/templates/ctemplates.py +126 -0
  272. package/releng/meson/mesonbuild/templates/cudatemplates.py +143 -0
  273. package/releng/meson/mesonbuild/templates/dlangtemplates.py +109 -0
  274. package/releng/meson/mesonbuild/templates/fortrantemplates.py +101 -0
  275. package/releng/meson/mesonbuild/templates/javatemplates.py +94 -0
  276. package/releng/meson/mesonbuild/templates/mesontemplates.py +70 -0
  277. package/releng/meson/mesonbuild/templates/objcpptemplates.py +126 -0
  278. package/releng/meson/mesonbuild/templates/objctemplates.py +126 -0
  279. package/releng/meson/mesonbuild/templates/rusttemplates.py +79 -0
  280. package/releng/meson/mesonbuild/templates/samplefactory.py +41 -0
  281. package/releng/meson/mesonbuild/templates/sampleimpl.py +160 -0
  282. package/releng/meson/mesonbuild/templates/valatemplates.py +82 -0
  283. package/releng/meson/mesonbuild/utils/__init__.py +0 -0
  284. package/releng/meson/mesonbuild/utils/core.py +166 -0
  285. package/releng/meson/mesonbuild/utils/platform.py +27 -0
  286. package/releng/meson/mesonbuild/utils/posix.py +32 -0
  287. package/releng/meson/mesonbuild/utils/universal.py +2445 -0
  288. package/releng/meson/mesonbuild/utils/vsenv.py +126 -0
  289. package/releng/meson/mesonbuild/utils/win32.py +29 -0
  290. package/releng/meson/mesonbuild/wrap/__init__.py +59 -0
  291. package/releng/meson/mesonbuild/wrap/wrap.py +846 -0
  292. package/releng/meson/mesonbuild/wrap/wraptool.py +198 -0
  293. package/releng/meson-scripts/BSDmakefile +6 -0
  294. package/releng/meson-scripts/Makefile +16 -0
  295. package/releng/meson-scripts/configure +18 -0
  296. package/releng/meson-scripts/configure.bat +22 -0
  297. package/releng/meson-scripts/make.bat +23 -0
  298. package/releng/meson_configure.py +506 -0
  299. package/releng/meson_make.py +131 -0
  300. package/releng/mkdevkit.py +107 -0
  301. package/releng/mkfatmacho.py +54 -0
  302. package/releng/post-process-oabi.py +97 -0
  303. package/releng/progress.py +14 -0
  304. package/releng/sync-from-upstream.py +185 -0
  305. package/releng/tomlkit/tomlkit/__init__.py +59 -0
  306. package/releng/tomlkit/tomlkit/_compat.py +22 -0
  307. package/releng/tomlkit/tomlkit/_types.py +83 -0
  308. package/releng/tomlkit/tomlkit/_utils.py +158 -0
  309. package/releng/tomlkit/tomlkit/api.py +308 -0
  310. package/releng/tomlkit/tomlkit/container.py +875 -0
  311. package/releng/tomlkit/tomlkit/exceptions.py +227 -0
  312. package/releng/tomlkit/tomlkit/items.py +1967 -0
  313. package/releng/tomlkit/tomlkit/parser.py +1141 -0
  314. package/releng/tomlkit/tomlkit/py.typed +0 -0
  315. package/releng/tomlkit/tomlkit/source.py +180 -0
  316. package/releng/tomlkit/tomlkit/toml_char.py +52 -0
  317. package/releng/tomlkit/tomlkit/toml_document.py +7 -0
  318. package/releng/tomlkit/tomlkit/toml_file.py +58 -0
  319. package/releng/winenv.py +140 -0
  320. package/scripts/adjust-version.py +19 -0
  321. package/scripts/detect-version.py +40 -0
  322. package/scripts/fetch-abi-bits.py +343 -0
  323. package/scripts/install.js +23 -0
  324. package/scripts/package.py +15 -0
  325. package/src/addon.cc +76 -0
  326. package/src/application.cc +148 -0
  327. package/src/application.h +31 -0
  328. package/src/authentication.cc +174 -0
  329. package/src/authentication.h +24 -0
  330. package/src/bus.cc +167 -0
  331. package/src/bus.h +33 -0
  332. package/src/cancellable.cc +117 -0
  333. package/src/cancellable.h +31 -0
  334. package/src/child.cc +150 -0
  335. package/src/child.h +32 -0
  336. package/src/crash.cc +122 -0
  337. package/src/crash.h +30 -0
  338. package/src/device.cc +1302 -0
  339. package/src/device.h +55 -0
  340. package/src/device_manager.cc +362 -0
  341. package/src/device_manager.h +35 -0
  342. package/src/endpoint_parameters.cc +171 -0
  343. package/src/endpoint_parameters.h +28 -0
  344. package/src/glib_context.cc +62 -0
  345. package/src/glib_context.h +29 -0
  346. package/src/glib_object.cc +25 -0
  347. package/src/glib_object.h +37 -0
  348. package/src/iostream.cc +247 -0
  349. package/src/iostream.h +30 -0
  350. package/src/meson.build +26 -0
  351. package/src/operation.h +94 -0
  352. package/src/portal_membership.cc +100 -0
  353. package/src/portal_membership.h +26 -0
  354. package/src/portal_service.cc +401 -0
  355. package/src/portal_service.h +40 -0
  356. package/src/process.cc +135 -0
  357. package/src/process.h +30 -0
  358. package/src/relay.cc +139 -0
  359. package/src/relay.h +31 -0
  360. package/src/runtime.cc +443 -0
  361. package/src/runtime.h +64 -0
  362. package/src/script.cc +301 -0
  363. package/src/script.h +36 -0
  364. package/src/session.cc +860 -0
  365. package/src/session.h +42 -0
  366. package/src/signals.cc +334 -0
  367. package/src/signals.h +47 -0
  368. package/src/spawn.cc +95 -0
  369. package/src/spawn.h +27 -0
  370. package/src/usage_monitor.h +117 -0
  371. package/src/uv_context.cc +118 -0
  372. package/src/uv_context.h +40 -0
  373. package/src/win_delay_load_hook.cc +63 -0
  374. package/subprojects/frida-core.wrap +8 -0
  375. package/subprojects/nan.wrap +9 -0
  376. package/subprojects/packagefiles/nan.patch +13 -0
  377. package/test/data/index.ts +13 -0
  378. package/test/data/unixvictim-linux-x86 +0 -0
  379. package/test/data/unixvictim-linux-x86_64 +0 -0
  380. package/test/data/unixvictim-macos +0 -0
  381. package/test/device.ts +27 -0
  382. package/test/device_manager.ts +16 -0
  383. package/test/labrat.ts +32 -0
  384. package/test/script.ts +176 -0
  385. package/test/session.ts +73 -0
  386. package/tsconfig.json +18 -0
@@ -0,0 +1,2201 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # Copyright 2016-2017 The Meson development team
3
+
4
+ # A tool to run tests in many different ways.
5
+ from __future__ import annotations
6
+
7
+ from pathlib import Path
8
+ from collections import deque
9
+ from contextlib import suppress
10
+ from copy import deepcopy
11
+ from fnmatch import fnmatch
12
+ import argparse
13
+ import asyncio
14
+ import datetime
15
+ import enum
16
+ import json
17
+ import multiprocessing
18
+ import os
19
+ import pickle
20
+ import platform
21
+ import random
22
+ import re
23
+ import signal
24
+ import subprocess
25
+ import shlex
26
+ import sys
27
+ import textwrap
28
+ import time
29
+ import typing as T
30
+ import unicodedata
31
+ import xml.etree.ElementTree as et
32
+
33
+ from . import build
34
+ from . import environment
35
+ from . import mlog
36
+ from .coredata import MesonVersionMismatchException, major_versions_differ
37
+ from .coredata import version as coredata_version
38
+ from .mesonlib import (MesonException, OptionKey, OrderedSet, RealPathAction,
39
+ get_wine_shortpath, join_args, split_args, setup_vsenv)
40
+ from .mintro import get_infodir, load_info_file
41
+ from .programs import ExternalProgram
42
+ from .backend.backends import TestProtocol, TestSerialisation
43
+
44
+ if T.TYPE_CHECKING:
45
+ TYPE_TAPResult = T.Union['TAPParser.Test',
46
+ 'TAPParser.Error',
47
+ 'TAPParser.Version',
48
+ 'TAPParser.Plan',
49
+ 'TAPParser.UnknownLine',
50
+ 'TAPParser.Bailout']
51
+
52
+
53
+ # GNU autotools interprets a return code of 77 from tests it executes to
54
+ # mean that the test should be skipped.
55
+ GNU_SKIP_RETURNCODE = 77
56
+
57
+ # GNU autotools interprets a return code of 99 from tests it executes to
58
+ # mean that the test failed even before testing what it is supposed to test.
59
+ GNU_ERROR_RETURNCODE = 99
60
+
61
+ # Exit if 3 Ctrl-C's are received within one second
62
+ MAX_CTRLC = 3
63
+
64
+ # Define unencodable xml characters' regex for replacing them with their
65
+ # printable representation
66
+ UNENCODABLE_XML_UNICHRS: T.List[T.Tuple[int, int]] = [
67
+ (0x00, 0x08), (0x0B, 0x0C), (0x0E, 0x1F), (0x7F, 0x84),
68
+ (0x86, 0x9F), (0xFDD0, 0xFDEF), (0xFFFE, 0xFFFF)]
69
+ # Not narrow build
70
+ if sys.maxunicode >= 0x10000:
71
+ UNENCODABLE_XML_UNICHRS.extend([
72
+ (0x1FFFE, 0x1FFFF), (0x2FFFE, 0x2FFFF),
73
+ (0x3FFFE, 0x3FFFF), (0x4FFFE, 0x4FFFF),
74
+ (0x5FFFE, 0x5FFFF), (0x6FFFE, 0x6FFFF),
75
+ (0x7FFFE, 0x7FFFF), (0x8FFFE, 0x8FFFF),
76
+ (0x9FFFE, 0x9FFFF), (0xAFFFE, 0xAFFFF),
77
+ (0xBFFFE, 0xBFFFF), (0xCFFFE, 0xCFFFF),
78
+ (0xDFFFE, 0xDFFFF), (0xEFFFE, 0xEFFFF),
79
+ (0xFFFFE, 0xFFFFF), (0x10FFFE, 0x10FFFF)])
80
+ UNENCODABLE_XML_CHR_RANGES = [fr'{chr(low)}-{chr(high)}' for (low, high) in UNENCODABLE_XML_UNICHRS]
81
+ UNENCODABLE_XML_CHRS_RE = re.compile('([' + ''.join(UNENCODABLE_XML_CHR_RANGES) + '])')
82
+
83
+
84
+ def is_windows() -> bool:
85
+ platname = platform.system().lower()
86
+ return platname == 'windows'
87
+
88
+ def is_cygwin() -> bool:
89
+ return sys.platform == 'cygwin'
90
+
91
+ UNIWIDTH_MAPPING = {'F': 2, 'H': 1, 'W': 2, 'Na': 1, 'N': 1, 'A': 1}
92
+ def uniwidth(s: str) -> int:
93
+ result = 0
94
+ for c in s:
95
+ w = unicodedata.east_asian_width(c)
96
+ result += UNIWIDTH_MAPPING[w]
97
+ return result
98
+
99
+ def determine_worker_count() -> int:
100
+ varname = 'MESON_TESTTHREADS'
101
+ if varname in os.environ:
102
+ try:
103
+ num_workers = int(os.environ[varname])
104
+ except ValueError:
105
+ print(f'Invalid value in {varname}, using 1 thread.')
106
+ num_workers = 1
107
+ else:
108
+ try:
109
+ # Fails in some weird environments such as Debian
110
+ # reproducible build.
111
+ num_workers = multiprocessing.cpu_count()
112
+ except Exception:
113
+ num_workers = 1
114
+ return num_workers
115
+
116
+ # Note: when adding arguments, please also add them to the completion
117
+ # scripts in $MESONSRC/data/shell-completions/
118
+ def add_arguments(parser: argparse.ArgumentParser) -> None:
119
+ parser.add_argument('--maxfail', default=0, type=int,
120
+ help='Number of failing tests before aborting the '
121
+ 'test run. (default: 0, to disable aborting on failure)')
122
+ parser.add_argument('--repeat', default=1, dest='repeat', type=int,
123
+ help='Number of times to run the tests.')
124
+ parser.add_argument('--no-rebuild', default=False, action='store_true',
125
+ help='Do not rebuild before running tests.')
126
+ parser.add_argument('--gdb', default=False, dest='gdb', action='store_true',
127
+ help='Run test under gdb.')
128
+ parser.add_argument('--gdb-path', default='gdb', dest='gdb_path',
129
+ help='Path to the gdb binary (default: gdb).')
130
+ parser.add_argument('--list', default=False, dest='list', action='store_true',
131
+ help='List available tests.')
132
+ parser.add_argument('--wrapper', default=None, dest='wrapper', type=split_args,
133
+ help='wrapper to run tests with (e.g. Valgrind)')
134
+ parser.add_argument('-C', dest='wd', action=RealPathAction,
135
+ help='directory to cd into before running')
136
+ parser.add_argument('--suite', default=[], dest='include_suites', action='append', metavar='SUITE',
137
+ help='Only run tests belonging to the given suite.')
138
+ parser.add_argument('--no-suite', default=[], dest='exclude_suites', action='append', metavar='SUITE',
139
+ help='Do not run tests belonging to the given suite.')
140
+ parser.add_argument('--no-stdsplit', default=True, dest='split', action='store_false',
141
+ help='Do not split stderr and stdout in test logs.')
142
+ parser.add_argument('--print-errorlogs', default=False, action='store_true',
143
+ help="Whether to print failing tests' logs.")
144
+ parser.add_argument('--benchmark', default=False, action='store_true',
145
+ help="Run benchmarks instead of tests.")
146
+ parser.add_argument('--logbase', default='testlog',
147
+ help="Base name for log file.")
148
+ parser.add_argument('-j', '--num-processes', default=determine_worker_count(), type=int,
149
+ help='How many parallel processes to use.')
150
+ parser.add_argument('-v', '--verbose', default=False, action='store_true',
151
+ help='Do not redirect stdout and stderr')
152
+ parser.add_argument('-q', '--quiet', default=False, action='store_true',
153
+ help='Produce less output to the terminal.')
154
+ parser.add_argument('-t', '--timeout-multiplier', type=float, default=None,
155
+ help='Define a multiplier for test timeout, for example '
156
+ ' when running tests in particular conditions they might take'
157
+ ' more time to execute. (<= 0 to disable timeout)')
158
+ parser.add_argument('--setup', default=None, dest='setup',
159
+ help='Which test setup to use.')
160
+ parser.add_argument('--test-args', default=[], type=split_args,
161
+ help='Arguments to pass to the specified test(s) or all tests')
162
+ parser.add_argument('args', nargs='*',
163
+ help='Optional list of test names to run. "testname" to run all tests with that name, '
164
+ '"subprojname:testname" to specifically run "testname" from "subprojname", '
165
+ '"subprojname:" to run all tests defined by "subprojname".')
166
+
167
+
168
+ def print_safe(s: str) -> None:
169
+ end = '' if s[-1] == '\n' else '\n'
170
+ try:
171
+ print(s, end=end)
172
+ except UnicodeEncodeError:
173
+ s = s.encode('ascii', errors='backslashreplace').decode('ascii')
174
+ print(s, end=end)
175
+
176
+ def join_lines(a: str, b: str) -> str:
177
+ if not a:
178
+ return b
179
+ if not b:
180
+ return a
181
+ return a + '\n' + b
182
+
183
+ def dashes(s: str, dash: str, cols: int) -> str:
184
+ if not s:
185
+ return dash * cols
186
+ s = ' ' + s + ' '
187
+ width = uniwidth(s)
188
+ first = (cols - width) // 2
189
+ s = dash * first + s
190
+ return s + dash * (cols - first - width)
191
+
192
+ def returncode_to_status(retcode: int) -> str:
193
+ # Note: We can't use `os.WIFSIGNALED(result.returncode)` and the related
194
+ # functions here because the status returned by subprocess is munged. It
195
+ # returns a negative value if the process was killed by a signal rather than
196
+ # the raw status returned by `wait()`. Also, If a shell sits between Meson
197
+ # the actual unit test that shell is likely to convert a termination due
198
+ # to a signal into an exit status of 128 plus the signal number.
199
+ if retcode < 0:
200
+ signum = -retcode
201
+ try:
202
+ signame = signal.Signals(signum).name
203
+ except ValueError:
204
+ signame = 'SIGinvalid'
205
+ return f'killed by signal {signum} {signame}'
206
+
207
+ if retcode <= 128:
208
+ return f'exit status {retcode}'
209
+
210
+ signum = retcode - 128
211
+ try:
212
+ signame = signal.Signals(signum).name
213
+ except ValueError:
214
+ signame = 'SIGinvalid'
215
+ return f'(exit status {retcode} or signal {signum} {signame})'
216
+
217
+ # TODO for Windows
218
+ sh_quote: T.Callable[[str], str] = lambda x: x
219
+ if not is_windows():
220
+ sh_quote = shlex.quote
221
+
222
+ def env_tuple_to_str(env: T.Iterable[T.Tuple[str, str]]) -> str:
223
+ return ''.join(["{}={} ".format(k, sh_quote(v)) for k, v in env])
224
+
225
+
226
+ class TestException(MesonException):
227
+ pass
228
+
229
+
230
+ @enum.unique
231
+ class ConsoleUser(enum.Enum):
232
+
233
+ # the logger can use the console
234
+ LOGGER = 0
235
+
236
+ # the console is used by gdb
237
+ GDB = 1
238
+
239
+ # the console is used to write stdout/stderr
240
+ STDOUT = 2
241
+
242
+
243
+ @enum.unique
244
+ class TestResult(enum.Enum):
245
+
246
+ PENDING = 'PENDING'
247
+ RUNNING = 'RUNNING'
248
+ OK = 'OK'
249
+ TIMEOUT = 'TIMEOUT'
250
+ INTERRUPT = 'INTERRUPT'
251
+ SKIP = 'SKIP'
252
+ FAIL = 'FAIL'
253
+ EXPECTEDFAIL = 'EXPECTEDFAIL'
254
+ UNEXPECTEDPASS = 'UNEXPECTEDPASS'
255
+ ERROR = 'ERROR'
256
+
257
+ @staticmethod
258
+ def maxlen() -> int:
259
+ return 14 # len(UNEXPECTEDPASS)
260
+
261
+ def is_ok(self) -> bool:
262
+ return self in {TestResult.OK, TestResult.EXPECTEDFAIL}
263
+
264
+ def is_bad(self) -> bool:
265
+ return self in {TestResult.FAIL, TestResult.TIMEOUT, TestResult.INTERRUPT,
266
+ TestResult.UNEXPECTEDPASS, TestResult.ERROR}
267
+
268
+ def is_finished(self) -> bool:
269
+ return self not in {TestResult.PENDING, TestResult.RUNNING}
270
+
271
+ def was_killed(self) -> bool:
272
+ return self in (TestResult.TIMEOUT, TestResult.INTERRUPT)
273
+
274
+ def colorize(self, s: str) -> mlog.AnsiDecorator:
275
+ if self.is_bad():
276
+ decorator = mlog.red
277
+ elif self in (TestResult.SKIP, TestResult.EXPECTEDFAIL):
278
+ decorator = mlog.yellow
279
+ elif self.is_finished():
280
+ decorator = mlog.green
281
+ else:
282
+ decorator = mlog.blue
283
+ return decorator(s)
284
+
285
+ def get_text(self, colorize: bool) -> str:
286
+ result_str = '{res:{reslen}}'.format(res=self.value, reslen=self.maxlen())
287
+ return self.colorize(result_str).get_text(colorize)
288
+
289
+ def get_command_marker(self) -> str:
290
+ return str(self.colorize('>>> '))
291
+
292
+
293
+ class TAPParser:
294
+ class Plan(T.NamedTuple):
295
+ num_tests: int
296
+ late: bool
297
+ skipped: bool
298
+ explanation: T.Optional[str]
299
+
300
+ class Bailout(T.NamedTuple):
301
+ message: str
302
+
303
+ class Test(T.NamedTuple):
304
+ number: int
305
+ name: str
306
+ result: TestResult
307
+ explanation: T.Optional[str]
308
+
309
+ def __str__(self) -> str:
310
+ return f'{self.number} {self.name}'.strip()
311
+
312
+ class Error(T.NamedTuple):
313
+ message: str
314
+
315
+ class UnknownLine(T.NamedTuple):
316
+ message: str
317
+ lineno: int
318
+
319
+ class Version(T.NamedTuple):
320
+ version: int
321
+
322
+ _MAIN = 1
323
+ _AFTER_TEST = 2
324
+ _YAML = 3
325
+
326
+ _RE_BAILOUT = re.compile(r'Bail out!\s*(.*)')
327
+ _RE_DIRECTIVE = re.compile(r'(?:\s*\#\s*([Ss][Kk][Ii][Pp]\S*|[Tt][Oo][Dd][Oo])\b\s*(.*))?')
328
+ _RE_PLAN = re.compile(r'1\.\.([0-9]+)' + _RE_DIRECTIVE.pattern)
329
+ _RE_TEST = re.compile(r'((?:not )?ok)\s*(?:([0-9]+)\s*)?([^#]*)' + _RE_DIRECTIVE.pattern)
330
+ _RE_VERSION = re.compile(r'TAP version ([0-9]+)')
331
+ _RE_YAML_START = re.compile(r'(\s+)---.*')
332
+ _RE_YAML_END = re.compile(r'\s+\.\.\.\s*')
333
+
334
+ found_late_test = False
335
+ bailed_out = False
336
+ plan: T.Optional[Plan] = None
337
+ lineno = 0
338
+ num_tests = 0
339
+ yaml_lineno: T.Optional[int] = None
340
+ yaml_indent = ''
341
+ state = _MAIN
342
+ version = 12
343
+
344
+ def parse_test(self, ok: bool, num: int, name: str, directive: T.Optional[str], explanation: T.Optional[str]) -> \
345
+ T.Generator[T.Union['TAPParser.Test', 'TAPParser.Error'], None, None]:
346
+ name = name.strip()
347
+ explanation = explanation.strip() if explanation else None
348
+ if directive is not None:
349
+ directive = directive.upper()
350
+ if directive.startswith('SKIP'):
351
+ if ok:
352
+ yield self.Test(num, name, TestResult.SKIP, explanation)
353
+ return
354
+ elif directive == 'TODO':
355
+ yield self.Test(num, name, TestResult.UNEXPECTEDPASS if ok else TestResult.EXPECTEDFAIL, explanation)
356
+ return
357
+ else:
358
+ yield self.Error(f'invalid directive "{directive}"')
359
+
360
+ yield self.Test(num, name, TestResult.OK if ok else TestResult.FAIL, explanation)
361
+
362
+ async def parse_async(self, lines: T.AsyncIterator[str]) -> T.AsyncIterator[TYPE_TAPResult]:
363
+ async for line in lines:
364
+ for event in self.parse_line(line):
365
+ yield event
366
+ for event in self.parse_line(None):
367
+ yield event
368
+
369
+ def parse(self, io: T.Iterator[str]) -> T.Iterator[TYPE_TAPResult]:
370
+ for line in io:
371
+ yield from self.parse_line(line)
372
+ yield from self.parse_line(None)
373
+
374
+ def parse_line(self, line: T.Optional[str]) -> T.Iterator[TYPE_TAPResult]:
375
+ if line is not None:
376
+ self.lineno += 1
377
+ line = line.rstrip()
378
+
379
+ # YAML blocks are only accepted after a test
380
+ if self.state == self._AFTER_TEST:
381
+ if self.version >= 13:
382
+ m = self._RE_YAML_START.match(line)
383
+ if m:
384
+ self.state = self._YAML
385
+ self.yaml_lineno = self.lineno
386
+ self.yaml_indent = m.group(1)
387
+ return
388
+ self.state = self._MAIN
389
+
390
+ elif self.state == self._YAML:
391
+ if self._RE_YAML_END.match(line):
392
+ self.state = self._MAIN
393
+ return
394
+ if line.startswith(self.yaml_indent):
395
+ return
396
+ yield self.Error(f'YAML block not terminated (started on line {self.yaml_lineno})')
397
+ self.state = self._MAIN
398
+
399
+ assert self.state == self._MAIN
400
+ if not line or line.startswith('#'):
401
+ return
402
+
403
+ m = self._RE_TEST.match(line)
404
+ if m:
405
+ if self.plan and self.plan.late and not self.found_late_test:
406
+ yield self.Error('unexpected test after late plan')
407
+ self.found_late_test = True
408
+ self.num_tests += 1
409
+ num = self.num_tests if m.group(2) is None else int(m.group(2))
410
+ if num != self.num_tests:
411
+ yield self.Error('out of order test numbers')
412
+ yield from self.parse_test(m.group(1) == 'ok', num,
413
+ m.group(3), m.group(4), m.group(5))
414
+ self.state = self._AFTER_TEST
415
+ return
416
+
417
+ m = self._RE_PLAN.match(line)
418
+ if m:
419
+ if self.plan:
420
+ yield self.Error('more than one plan found')
421
+ else:
422
+ num_tests = int(m.group(1))
423
+ skipped = num_tests == 0
424
+ if m.group(2):
425
+ if m.group(2).upper().startswith('SKIP'):
426
+ if num_tests > 0:
427
+ yield self.Error('invalid SKIP directive for plan')
428
+ skipped = True
429
+ else:
430
+ yield self.Error('invalid directive for plan')
431
+ self.plan = self.Plan(num_tests=num_tests, late=(self.num_tests > 0),
432
+ skipped=skipped, explanation=m.group(3))
433
+ yield self.plan
434
+ return
435
+
436
+ m = self._RE_BAILOUT.match(line)
437
+ if m:
438
+ yield self.Bailout(m.group(1))
439
+ self.bailed_out = True
440
+ return
441
+
442
+ m = self._RE_VERSION.match(line)
443
+ if m:
444
+ # The TAP version is only accepted as the first line
445
+ if self.lineno != 1:
446
+ yield self.Error('version number must be on the first line')
447
+ return
448
+ self.version = int(m.group(1))
449
+ if self.version < 13:
450
+ yield self.Error('version number should be at least 13')
451
+ else:
452
+ yield self.Version(version=self.version)
453
+ return
454
+
455
+ # unknown syntax
456
+ yield self.UnknownLine(line, self.lineno)
457
+ else:
458
+ # end of file
459
+ if self.state == self._YAML:
460
+ yield self.Error(f'YAML block not terminated (started on line {self.yaml_lineno})')
461
+
462
+ if not self.bailed_out and self.plan and self.num_tests != self.plan.num_tests:
463
+ if self.num_tests < self.plan.num_tests:
464
+ yield self.Error(f'Too few tests run (expected {self.plan.num_tests}, got {self.num_tests})')
465
+ else:
466
+ yield self.Error(f'Too many tests run (expected {self.plan.num_tests}, got {self.num_tests})')
467
+
468
+ class TestLogger:
469
+ def flush(self) -> None:
470
+ pass
471
+
472
+ def start(self, harness: 'TestHarness') -> None:
473
+ pass
474
+
475
+ def start_test(self, harness: 'TestHarness', test: 'TestRun') -> None:
476
+ pass
477
+
478
+ def log_subtest(self, harness: 'TestHarness', test: 'TestRun', s: str, res: TestResult) -> None:
479
+ pass
480
+
481
+ def log(self, harness: 'TestHarness', result: 'TestRun') -> None:
482
+ pass
483
+
484
+ async def finish(self, harness: 'TestHarness') -> None:
485
+ pass
486
+
487
+ def close(self) -> None:
488
+ pass
489
+
490
+
491
+ class TestFileLogger(TestLogger):
492
+ def __init__(self, filename: str, errors: str = 'replace') -> None:
493
+ self.filename = filename
494
+ self.file = open(filename, 'w', encoding='utf-8', errors=errors)
495
+
496
+ def close(self) -> None:
497
+ if self.file:
498
+ self.file.close()
499
+ self.file = None
500
+
501
+
502
+ class ConsoleLogger(TestLogger):
503
+ ASCII_SPINNER = ['..', ':.', '.:']
504
+ SPINNER = ["\U0001f311", "\U0001f312", "\U0001f313", "\U0001f314",
505
+ "\U0001f315", "\U0001f316", "\U0001f317", "\U0001f318"]
506
+
507
+ SCISSORS = "\u2700 "
508
+ HLINE = "\u2015"
509
+ RTRI = "\u25B6 "
510
+
511
+ def __init__(self) -> None:
512
+ self.running_tests: OrderedSet['TestRun'] = OrderedSet()
513
+ self.progress_test: T.Optional['TestRun'] = None
514
+ self.progress_task: T.Optional[asyncio.Future] = None
515
+ self.max_left_width = 0
516
+ self.stop = False
517
+ # TODO: before 3.10 this cannot be created immediately, because
518
+ # it will create a new event loop
519
+ self.update: asyncio.Event
520
+ self.should_erase_line = ''
521
+ self.test_count = 0
522
+ self.started_tests = 0
523
+ self.spinner_index = 0
524
+ try:
525
+ self.cols, _ = os.get_terminal_size(1)
526
+ self.is_tty = True
527
+ except OSError:
528
+ self.cols = 80
529
+ self.is_tty = False
530
+
531
+ self.output_start = dashes(self.SCISSORS, self.HLINE, self.cols - 2)
532
+ self.output_end = dashes('', self.HLINE, self.cols - 2)
533
+ self.sub = self.RTRI
534
+ self.spinner = self.SPINNER
535
+ try:
536
+ self.output_start.encode(sys.stdout.encoding or 'ascii')
537
+ except UnicodeEncodeError:
538
+ self.output_start = dashes('8<', '-', self.cols - 2)
539
+ self.output_end = dashes('', '-', self.cols - 2)
540
+ self.sub = '| '
541
+ self.spinner = self.ASCII_SPINNER
542
+
543
+ def flush(self) -> None:
544
+ if self.should_erase_line:
545
+ print(self.should_erase_line, end='')
546
+ self.should_erase_line = ''
547
+
548
+ def print_progress(self, line: str) -> None:
549
+ print(self.should_erase_line, line, sep='', end='\r')
550
+ self.should_erase_line = '\x1b[K'
551
+
552
+ def request_update(self) -> None:
553
+ self.update.set()
554
+
555
+ def emit_progress(self, harness: 'TestHarness') -> None:
556
+ if self.progress_test is None:
557
+ self.flush()
558
+ return
559
+
560
+ if len(self.running_tests) == 1:
561
+ count = f'{self.started_tests}/{self.test_count}'
562
+ else:
563
+ count = '{}-{}/{}'.format(self.started_tests - len(self.running_tests) + 1,
564
+ self.started_tests, self.test_count)
565
+
566
+ left = '[{}] {} '.format(count, self.spinner[self.spinner_index])
567
+ self.spinner_index = (self.spinner_index + 1) % len(self.spinner)
568
+
569
+ right = '{spaces} {dur:{durlen}}'.format(
570
+ spaces=' ' * TestResult.maxlen(),
571
+ dur=int(time.time() - self.progress_test.starttime),
572
+ durlen=harness.duration_max_len)
573
+ if self.progress_test.timeout:
574
+ right += '/{timeout:{durlen}}'.format(
575
+ timeout=self.progress_test.timeout,
576
+ durlen=harness.duration_max_len)
577
+ right += 's'
578
+ details = self.progress_test.get_details()
579
+ if details:
580
+ right += ' ' + details
581
+
582
+ line = harness.format(self.progress_test, colorize=True,
583
+ max_left_width=self.max_left_width,
584
+ left=left, right=right)
585
+ self.print_progress(line)
586
+
587
+ def start(self, harness: 'TestHarness') -> None:
588
+ async def report_progress() -> None:
589
+ loop = asyncio.get_running_loop()
590
+ next_update = 0.0
591
+ self.request_update()
592
+ while not self.stop:
593
+ await self.update.wait()
594
+ self.update.clear()
595
+ # We may get here simply because the progress line has been
596
+ # overwritten, so do not always switch. Only do so every
597
+ # second, or if the printed test has finished
598
+ if loop.time() >= next_update:
599
+ self.progress_test = None
600
+ next_update = loop.time() + 1
601
+ loop.call_at(next_update, self.request_update)
602
+
603
+ if (self.progress_test and
604
+ self.progress_test.res is not TestResult.RUNNING):
605
+ self.progress_test = None
606
+
607
+ if not self.progress_test:
608
+ if not self.running_tests:
609
+ continue
610
+ # Pick a test in round robin order
611
+ self.progress_test = self.running_tests.pop(last=False)
612
+ self.running_tests.add(self.progress_test)
613
+
614
+ self.emit_progress(harness)
615
+ self.flush()
616
+
617
+ self.update = asyncio.Event()
618
+ self.test_count = harness.test_count
619
+ self.cols = max(self.cols, harness.max_left_width + 30)
620
+
621
+ if self.is_tty and not harness.need_console:
622
+ # Account for "[aa-bb/cc] OO " in the progress report
623
+ self.max_left_width = 3 * len(str(self.test_count)) + 8
624
+ self.progress_task = asyncio.ensure_future(report_progress())
625
+
626
+ def start_test(self, harness: 'TestHarness', test: 'TestRun') -> None:
627
+ if test.verbose and test.cmdline:
628
+ self.flush()
629
+ print(harness.format(test, mlog.colorize_console(),
630
+ max_left_width=self.max_left_width,
631
+ right=test.res.get_text(mlog.colorize_console())))
632
+ print(test.res.get_command_marker() + test.cmdline)
633
+ if test.direct_stdout:
634
+ print(self.output_start, flush=True)
635
+ elif not test.needs_parsing:
636
+ print(flush=True)
637
+
638
+ self.started_tests += 1
639
+ self.running_tests.add(test)
640
+ self.running_tests.move_to_end(test, last=False)
641
+ self.request_update()
642
+
643
+ def shorten_log(self, harness: 'TestHarness', result: 'TestRun') -> str:
644
+ if not result.verbose and not harness.options.print_errorlogs:
645
+ return ''
646
+
647
+ log = result.get_log(mlog.colorize_console(),
648
+ stderr_only=result.needs_parsing)
649
+ if result.verbose:
650
+ return log
651
+
652
+ lines = log.splitlines()
653
+ if len(lines) < 100:
654
+ return log
655
+ else:
656
+ return str(mlog.bold('Listing only the last 100 lines from a long log.\n')) + '\n'.join(lines[-100:])
657
+
658
+ def print_log(self, harness: 'TestHarness', result: 'TestRun') -> None:
659
+ if not result.verbose:
660
+ cmdline = result.cmdline
661
+ if not cmdline:
662
+ print(result.res.get_command_marker() + result.stdo)
663
+ return
664
+ print(result.res.get_command_marker() + cmdline)
665
+
666
+ log = self.shorten_log(harness, result)
667
+ if log:
668
+ print(self.output_start)
669
+ print_safe(log)
670
+ print(self.output_end)
671
+
672
+ def log_subtest(self, harness: 'TestHarness', test: 'TestRun', s: str, result: TestResult) -> None:
673
+ if test.verbose or (harness.options.print_errorlogs and result.is_bad()):
674
+ self.flush()
675
+ print(harness.format(test, mlog.colorize_console(), max_left_width=self.max_left_width,
676
+ prefix=self.sub,
677
+ middle=s,
678
+ right=result.get_text(mlog.colorize_console())), flush=True)
679
+
680
+ self.request_update()
681
+
682
+ def log(self, harness: 'TestHarness', result: 'TestRun') -> None:
683
+ self.running_tests.remove(result)
684
+ if result.res is TestResult.TIMEOUT and (result.verbose or
685
+ harness.options.print_errorlogs):
686
+ self.flush()
687
+ print(f'{result.name} time out (After {result.timeout} seconds)')
688
+
689
+ if not harness.options.quiet or not result.res.is_ok():
690
+ self.flush()
691
+ if result.cmdline and result.direct_stdout:
692
+ print(self.output_end)
693
+ print(harness.format(result, mlog.colorize_console(), max_left_width=self.max_left_width))
694
+ else:
695
+ print(harness.format(result, mlog.colorize_console(), max_left_width=self.max_left_width),
696
+ flush=True)
697
+ if result.verbose or result.res.is_bad():
698
+ self.print_log(harness, result)
699
+ if result.warnings:
700
+ print(flush=True)
701
+ for w in result.warnings:
702
+ print(w, flush=True)
703
+ print(flush=True)
704
+ if result.verbose or result.res.is_bad():
705
+ print(flush=True)
706
+
707
+ self.request_update()
708
+
709
+ async def finish(self, harness: 'TestHarness') -> None:
710
+ self.stop = True
711
+ self.request_update()
712
+ if self.progress_task:
713
+ await self.progress_task
714
+
715
+ if harness.collected_failures and \
716
+ (harness.options.print_errorlogs or harness.options.verbose):
717
+ print("\nSummary of Failures:\n")
718
+ for i, result in enumerate(harness.collected_failures, 1):
719
+ print(harness.format(result, mlog.colorize_console()))
720
+
721
+ print(harness.summary())
722
+
723
+
724
+ class TextLogfileBuilder(TestFileLogger):
725
+ def start(self, harness: 'TestHarness') -> None:
726
+ self.file.write(f'Log of Meson test suite run on {datetime.datetime.now().isoformat()}\n\n')
727
+ inherit_env = env_tuple_to_str(os.environ.items())
728
+ self.file.write(f'Inherited environment: {inherit_env}\n\n')
729
+
730
+ def log(self, harness: 'TestHarness', result: 'TestRun') -> None:
731
+ title = f'{result.num}/{harness.test_count}'
732
+ self.file.write(dashes(title, '=', 78) + '\n')
733
+ self.file.write('test: ' + result.name + '\n')
734
+ starttime_str = time.strftime("%H:%M:%S", time.gmtime(result.starttime))
735
+ self.file.write('start time: ' + starttime_str + '\n')
736
+ self.file.write('duration: ' + '%.2fs' % result.duration + '\n')
737
+ self.file.write('result: ' + result.get_exit_status() + '\n')
738
+ if result.cmdline:
739
+ self.file.write('command: ' + result.cmdline + '\n')
740
+ if result.stdo:
741
+ name = 'stdout' if harness.options.split else 'output'
742
+ self.file.write(dashes(name, '-', 78) + '\n')
743
+ self.file.write(result.stdo)
744
+ if result.stde:
745
+ self.file.write(dashes('stderr', '-', 78) + '\n')
746
+ self.file.write(result.stde)
747
+ self.file.write(dashes('', '=', 78) + '\n\n')
748
+
749
+ async def finish(self, harness: 'TestHarness') -> None:
750
+ if harness.collected_failures:
751
+ self.file.write("\nSummary of Failures:\n\n")
752
+ for i, result in enumerate(harness.collected_failures, 1):
753
+ self.file.write(harness.format(result, False) + '\n')
754
+ self.file.write(harness.summary())
755
+
756
+ print(f'Full log written to {self.filename}')
757
+
758
+
759
+ class JsonLogfileBuilder(TestFileLogger):
760
+ def log(self, harness: 'TestHarness', result: 'TestRun') -> None:
761
+ jresult: T.Dict[str, T.Any] = {
762
+ 'name': result.name,
763
+ 'stdout': result.stdo,
764
+ 'result': result.res.value,
765
+ 'starttime': result.starttime,
766
+ 'duration': result.duration,
767
+ 'returncode': result.returncode,
768
+ 'env': result.env,
769
+ 'command': result.cmd,
770
+ }
771
+ if result.stde:
772
+ jresult['stderr'] = result.stde
773
+ self.file.write(json.dumps(jresult) + '\n')
774
+
775
+
776
+ class JunitBuilder(TestLogger):
777
+
778
+ """Builder for Junit test results.
779
+
780
+ Junit is impossible to stream out, it requires attributes counting the
781
+ total number of tests, failures, skips, and errors in the root element
782
+ and in each test suite. As such, we use a builder class to track each
783
+ test case, and calculate all metadata before writing it out.
784
+
785
+ For tests with multiple results (like from a TAP test), we record the
786
+ test as a suite with the project_name.test_name. This allows us to track
787
+ each result separately. For tests with only one result (such as exit-code
788
+ tests) we record each one into a suite with the name project_name. The use
789
+ of the project_name allows us to sort subproject tests separately from
790
+ the root project.
791
+ """
792
+
793
+ def __init__(self, filename: str) -> None:
794
+ self.filename = filename
795
+ self.root = et.Element(
796
+ 'testsuites', tests='0', errors='0', failures='0')
797
+ self.suites: T.Dict[str, et.Element] = {}
798
+
799
+ def log(self, harness: 'TestHarness', test: 'TestRun') -> None:
800
+ """Log a single test case."""
801
+ if test.junit is not None:
802
+ for suite in test.junit.findall('.//testsuite'):
803
+ # Assume that we don't need to merge anything here...
804
+ suite.attrib['name'] = '{}.{}.{}'.format(test.project, test.name, suite.attrib['name'])
805
+
806
+ # GTest can inject invalid attributes
807
+ for case in suite.findall('.//testcase[@result]'):
808
+ del case.attrib['result']
809
+ for case in suite.findall('.//testcase[@timestamp]'):
810
+ del case.attrib['timestamp']
811
+ for case in suite.findall('.//testcase[@file]'):
812
+ del case.attrib['file']
813
+ for case in suite.findall('.//testcase[@line]'):
814
+ del case.attrib['line']
815
+ self.root.append(suite)
816
+ return
817
+
818
+ # In this case we have a test binary with multiple results.
819
+ # We want to record this so that each result is recorded
820
+ # separately
821
+ if test.results:
822
+ suitename = f'{test.project}.{test.name}'
823
+ assert suitename not in self.suites or harness.options.repeat > 1, 'duplicate suite'
824
+
825
+ suite = self.suites[suitename] = et.Element(
826
+ 'testsuite',
827
+ name=suitename,
828
+ tests=str(len(test.results)),
829
+ errors=str(sum(1 for r in test.results if r.result in
830
+ {TestResult.INTERRUPT, TestResult.ERROR})),
831
+ failures=str(sum(1 for r in test.results if r.result in
832
+ {TestResult.FAIL, TestResult.UNEXPECTEDPASS, TestResult.TIMEOUT})),
833
+ skipped=str(sum(1 for r in test.results if r.result is TestResult.SKIP)),
834
+ time=str(test.duration),
835
+ )
836
+
837
+ for subtest in test.results:
838
+ # Both name and classname are required. Use the suite name as
839
+ # the class name, so that e.g. GitLab groups testcases correctly.
840
+ testcase = et.SubElement(suite, 'testcase', name=str(subtest), classname=suitename)
841
+ if subtest.result is TestResult.SKIP:
842
+ et.SubElement(testcase, 'skipped')
843
+ elif subtest.result is TestResult.ERROR:
844
+ et.SubElement(testcase, 'error')
845
+ elif subtest.result is TestResult.FAIL:
846
+ et.SubElement(testcase, 'failure')
847
+ elif subtest.result is TestResult.UNEXPECTEDPASS:
848
+ fail = et.SubElement(testcase, 'failure')
849
+ fail.text = 'Test unexpected passed.'
850
+ elif subtest.result is TestResult.INTERRUPT:
851
+ fail = et.SubElement(testcase, 'error')
852
+ fail.text = 'Test was interrupted by user.'
853
+ elif subtest.result is TestResult.TIMEOUT:
854
+ fail = et.SubElement(testcase, 'error')
855
+ fail.text = 'Test did not finish before configured timeout.'
856
+ if subtest.explanation:
857
+ et.SubElement(testcase, 'system-out').text = subtest.explanation
858
+ if test.stdo:
859
+ out = et.SubElement(suite, 'system-out')
860
+ out.text = replace_unencodable_xml_chars(test.stdo.rstrip())
861
+ if test.stde:
862
+ err = et.SubElement(suite, 'system-err')
863
+ err.text = replace_unencodable_xml_chars(test.stde.rstrip())
864
+ else:
865
+ if test.project not in self.suites:
866
+ suite = self.suites[test.project] = et.Element(
867
+ 'testsuite', name=test.project, tests='1', errors='0',
868
+ failures='0', skipped='0', time=str(test.duration))
869
+ else:
870
+ suite = self.suites[test.project]
871
+ suite.attrib['tests'] = str(int(suite.attrib['tests']) + 1)
872
+
873
+ testcase = et.SubElement(suite, 'testcase', name=test.name,
874
+ classname=test.project, time=str(test.duration))
875
+ if test.res is TestResult.SKIP:
876
+ et.SubElement(testcase, 'skipped')
877
+ suite.attrib['skipped'] = str(int(suite.attrib['skipped']) + 1)
878
+ elif test.res is TestResult.ERROR:
879
+ et.SubElement(testcase, 'error')
880
+ suite.attrib['errors'] = str(int(suite.attrib['errors']) + 1)
881
+ elif test.res is TestResult.FAIL:
882
+ et.SubElement(testcase, 'failure')
883
+ suite.attrib['failures'] = str(int(suite.attrib['failures']) + 1)
884
+ if test.stdo:
885
+ out = et.SubElement(testcase, 'system-out')
886
+ out.text = replace_unencodable_xml_chars(test.stdo.rstrip())
887
+ if test.stde:
888
+ err = et.SubElement(testcase, 'system-err')
889
+ err.text = replace_unencodable_xml_chars(test.stde.rstrip())
890
+
891
+ async def finish(self, harness: 'TestHarness') -> None:
892
+ """Calculate total test counts and write out the xml result."""
893
+ for suite in self.suites.values():
894
+ self.root.append(suite)
895
+ # Skipped is really not allowed in the "testsuits" element
896
+ for attr in ['tests', 'errors', 'failures']:
897
+ self.root.attrib[attr] = str(int(self.root.attrib[attr]) + int(suite.attrib[attr]))
898
+
899
+ tree = et.ElementTree(self.root)
900
+ with open(self.filename, 'wb') as f:
901
+ tree.write(f, encoding='utf-8', xml_declaration=True)
902
+
903
+
904
+ class TestRun:
905
+ TEST_NUM = 0
906
+ PROTOCOL_TO_CLASS: T.Dict[TestProtocol, T.Type['TestRun']] = {}
907
+
908
+ def __new__(cls, test: TestSerialisation, *args: T.Any, **kwargs: T.Any) -> T.Any:
909
+ return super().__new__(TestRun.PROTOCOL_TO_CLASS[test.protocol])
910
+
911
+ def __init__(self, test: TestSerialisation, test_env: T.Dict[str, str],
912
+ name: str, timeout: T.Optional[int], is_parallel: bool, verbose: bool):
913
+ self.res = TestResult.PENDING
914
+ self.test = test
915
+ self._num: T.Optional[int] = None
916
+ self.name = name
917
+ self.timeout = timeout
918
+ self.results: T.List[TAPParser.Test] = []
919
+ self.returncode: T.Optional[int] = None
920
+ self.starttime: T.Optional[float] = None
921
+ self.duration: T.Optional[float] = None
922
+ self.stdo = ''
923
+ self.stde = ''
924
+ self.additional_error = ''
925
+ self.cmd: T.Optional[T.List[str]] = None
926
+ self.env = test_env
927
+ self.should_fail = test.should_fail
928
+ self.project = test.project_name
929
+ self.junit: T.Optional[et.ElementTree] = None
930
+ self.is_parallel = is_parallel
931
+ self.verbose = verbose
932
+ self.warnings: T.List[str] = []
933
+
934
+ def start(self, cmd: T.List[str]) -> None:
935
+ self.res = TestResult.RUNNING
936
+ self.starttime = time.time()
937
+ self.cmd = cmd
938
+
939
+ @property
940
+ def num(self) -> int:
941
+ if self._num is None:
942
+ TestRun.TEST_NUM += 1
943
+ self._num = TestRun.TEST_NUM
944
+ return self._num
945
+
946
+ @property
947
+ def direct_stdout(self) -> bool:
948
+ return self.verbose and not self.is_parallel and not self.needs_parsing
949
+
950
+ def get_results(self) -> str:
951
+ if self.results:
952
+ # running or succeeded
953
+ passed = sum(x.result.is_ok() for x in self.results)
954
+ ran = sum(x.result is not TestResult.SKIP for x in self.results)
955
+ if passed == ran:
956
+ return f'{passed} subtests passed'
957
+ else:
958
+ return f'{passed}/{ran} subtests passed'
959
+ return ''
960
+
961
+ def get_exit_status(self) -> str:
962
+ return returncode_to_status(self.returncode)
963
+
964
+ def get_details(self) -> str:
965
+ if self.res is TestResult.PENDING:
966
+ return ''
967
+ if self.returncode:
968
+ return self.get_exit_status()
969
+ return self.get_results()
970
+
971
+ def _complete(self) -> None:
972
+ if self.res == TestResult.RUNNING:
973
+ self.res = TestResult.OK
974
+ assert isinstance(self.res, TestResult)
975
+ if self.should_fail and self.res in (TestResult.OK, TestResult.FAIL):
976
+ self.res = TestResult.UNEXPECTEDPASS if self.res is TestResult.OK else TestResult.EXPECTEDFAIL
977
+ if self.stdo and not self.stdo.endswith('\n'):
978
+ self.stdo += '\n'
979
+ if self.stde and not self.stde.endswith('\n'):
980
+ self.stde += '\n'
981
+ self.duration = time.time() - self.starttime
982
+
983
+ @property
984
+ def cmdline(self) -> T.Optional[str]:
985
+ if not self.cmd:
986
+ return None
987
+ test_only_env = set(self.env.items()) - set(os.environ.items())
988
+ return env_tuple_to_str(test_only_env) + \
989
+ ' '.join(sh_quote(x) for x in self.cmd)
990
+
991
+ def complete_skip(self) -> None:
992
+ self.starttime = time.time()
993
+ self.returncode = GNU_SKIP_RETURNCODE
994
+ self.res = TestResult.SKIP
995
+ self._complete()
996
+
997
+ def complete(self) -> None:
998
+ self._complete()
999
+
1000
+ def get_log(self, colorize: bool = False, stderr_only: bool = False) -> str:
1001
+ stdo = '' if stderr_only else self.stdo
1002
+ if self.stde or self.additional_error:
1003
+ res = ''
1004
+ if stdo:
1005
+ res += mlog.cyan('stdout:').get_text(colorize) + '\n'
1006
+ res += stdo
1007
+ if res[-1:] != '\n':
1008
+ res += '\n'
1009
+ res += mlog.cyan('stderr:').get_text(colorize) + '\n'
1010
+ res += join_lines(self.stde, self.additional_error)
1011
+ else:
1012
+ res = stdo
1013
+ if res and res[-1:] != '\n':
1014
+ res += '\n'
1015
+ return res
1016
+
1017
+ @property
1018
+ def needs_parsing(self) -> bool:
1019
+ return False
1020
+
1021
+ async def parse(self, harness: 'TestHarness', lines: T.AsyncIterator[str]) -> None:
1022
+ async for l in lines:
1023
+ pass
1024
+
1025
+
1026
+ class TestRunExitCode(TestRun):
1027
+
1028
+ def complete(self) -> None:
1029
+ if self.res != TestResult.RUNNING:
1030
+ pass
1031
+ elif self.returncode == GNU_SKIP_RETURNCODE:
1032
+ self.res = TestResult.SKIP
1033
+ elif self.returncode == GNU_ERROR_RETURNCODE:
1034
+ self.res = TestResult.ERROR
1035
+ else:
1036
+ self.res = TestResult.FAIL if bool(self.returncode) else TestResult.OK
1037
+ super().complete()
1038
+
1039
+ TestRun.PROTOCOL_TO_CLASS[TestProtocol.EXITCODE] = TestRunExitCode
1040
+
1041
+
1042
+ class TestRunGTest(TestRunExitCode):
1043
+ def complete(self) -> None:
1044
+ filename = f'{self.test.name}.xml'
1045
+ if self.test.workdir:
1046
+ filename = os.path.join(self.test.workdir, filename)
1047
+
1048
+ try:
1049
+ with open(filename, 'r', encoding='utf8', errors='replace') as f:
1050
+ self.junit = et.parse(f)
1051
+ except FileNotFoundError:
1052
+ # This can happen if the test fails to run or complete for some
1053
+ # reason, like the rpath for libgtest isn't properly set. ExitCode
1054
+ # will handle the failure, don't generate a stacktrace.
1055
+ pass
1056
+ except et.ParseError as e:
1057
+ # ExitCode will handle the failure, don't generate a stacktrace.
1058
+ mlog.error(f'Unable to parse {filename}: {e!s}')
1059
+
1060
+ super().complete()
1061
+
1062
+ TestRun.PROTOCOL_TO_CLASS[TestProtocol.GTEST] = TestRunGTest
1063
+
1064
+
1065
+ class TestRunTAP(TestRun):
1066
+ @property
1067
+ def needs_parsing(self) -> bool:
1068
+ return True
1069
+
1070
+ def complete(self) -> None:
1071
+ if self.returncode != 0 and not self.res.was_killed():
1072
+ self.res = TestResult.ERROR
1073
+ self.stde = self.stde or ''
1074
+ self.stde += f'\n(test program exited with status code {self.returncode})'
1075
+ super().complete()
1076
+
1077
+ async def parse(self, harness: 'TestHarness', lines: T.AsyncIterator[str]) -> None:
1078
+ res = None
1079
+ warnings: T.List[TAPParser.UnknownLine] = []
1080
+ version = 12
1081
+
1082
+ async for i in TAPParser().parse_async(lines):
1083
+ if isinstance(i, TAPParser.Version):
1084
+ version = i.version
1085
+ elif isinstance(i, TAPParser.Bailout):
1086
+ res = TestResult.ERROR
1087
+ harness.log_subtest(self, i.message, res)
1088
+ elif isinstance(i, TAPParser.Test):
1089
+ self.results.append(i)
1090
+ if i.result.is_bad():
1091
+ res = TestResult.FAIL
1092
+ harness.log_subtest(self, i.name or f'subtest {i.number}', i.result)
1093
+ elif isinstance(i, TAPParser.UnknownLine):
1094
+ warnings.append(i)
1095
+ elif isinstance(i, TAPParser.Error):
1096
+ self.additional_error += 'TAP parsing error: ' + i.message
1097
+ res = TestResult.ERROR
1098
+
1099
+ if warnings:
1100
+ unknown = str(mlog.yellow('UNKNOWN'))
1101
+ width = len(str(max(i.lineno for i in warnings)))
1102
+ for w in warnings:
1103
+ self.warnings.append(f'stdout: {w.lineno:{width}}: {unknown}: {w.message}')
1104
+ if version > 13:
1105
+ self.warnings.append('Unknown TAP output lines have been ignored. Please open a feature request to\n'
1106
+ 'implement them, or prefix them with a # if they are not TAP syntax.')
1107
+ else:
1108
+ self.warnings.append(str(mlog.red('ERROR')) + ': Unknown TAP output lines for a supported TAP version.\n'
1109
+ 'This is probably a bug in the test; if they are not TAP syntax, prefix them with a #')
1110
+ if all(t.result is TestResult.SKIP for t in self.results):
1111
+ # This includes the case where self.results is empty
1112
+ res = TestResult.SKIP
1113
+
1114
+ if res and self.res == TestResult.RUNNING:
1115
+ self.res = res
1116
+
1117
+ TestRun.PROTOCOL_TO_CLASS[TestProtocol.TAP] = TestRunTAP
1118
+
1119
+
1120
+ class TestRunRust(TestRun):
1121
+ @property
1122
+ def needs_parsing(self) -> bool:
1123
+ return True
1124
+
1125
+ async def parse(self, harness: 'TestHarness', lines: T.AsyncIterator[str]) -> None:
1126
+ def parse_res(n: int, name: str, result: str) -> TAPParser.Test:
1127
+ if result == 'ok':
1128
+ return TAPParser.Test(n, name, TestResult.OK, None)
1129
+ elif result == 'ignored':
1130
+ return TAPParser.Test(n, name, TestResult.SKIP, None)
1131
+ elif result == 'FAILED':
1132
+ return TAPParser.Test(n, name, TestResult.FAIL, None)
1133
+ return TAPParser.Test(n, name, TestResult.ERROR,
1134
+ f'Unsupported output from rust test: {result}')
1135
+
1136
+ n = 1
1137
+ async for line in lines:
1138
+ if line.startswith('test ') and not line.startswith('test result'):
1139
+ _, name, _, result = line.rstrip().split(' ')
1140
+ name = name.replace('::', '.')
1141
+ t = parse_res(n, name, result)
1142
+ self.results.append(t)
1143
+ harness.log_subtest(self, name, t.result)
1144
+ n += 1
1145
+
1146
+ res = None
1147
+
1148
+ if all(t.result is TestResult.SKIP for t in self.results):
1149
+ # This includes the case where self.results is empty
1150
+ res = TestResult.SKIP
1151
+ elif any(t.result is TestResult.ERROR for t in self.results):
1152
+ res = TestResult.ERROR
1153
+ elif any(t.result is TestResult.FAIL for t in self.results):
1154
+ res = TestResult.FAIL
1155
+
1156
+ if res and self.res == TestResult.RUNNING:
1157
+ self.res = res
1158
+
1159
+ TestRun.PROTOCOL_TO_CLASS[TestProtocol.RUST] = TestRunRust
1160
+
1161
+ # Check unencodable characters in xml output and replace them with
1162
+ # their printable representation
1163
+ def replace_unencodable_xml_chars(original_str: str) -> str:
1164
+ # [1:-1] is needed for removing `'` characters from both start and end
1165
+ # of the string
1166
+ replacement_lambda = lambda illegal_chr: repr(illegal_chr.group())[1:-1]
1167
+ return UNENCODABLE_XML_CHRS_RE.sub(replacement_lambda, original_str)
1168
+
1169
+ def decode(stream: T.Union[None, bytes]) -> str:
1170
+ if stream is None:
1171
+ return ''
1172
+ try:
1173
+ return stream.decode('utf-8')
1174
+ except UnicodeDecodeError:
1175
+ return stream.decode('iso-8859-1', errors='ignore')
1176
+
1177
+ async def read_decode(reader: asyncio.StreamReader,
1178
+ queue: T.Optional['asyncio.Queue[T.Optional[str]]'],
1179
+ console_mode: ConsoleUser) -> str:
1180
+ stdo_lines = []
1181
+ try:
1182
+ while not reader.at_eof():
1183
+ # Prefer splitting by line, as that produces nicer output
1184
+ try:
1185
+ line_bytes = await reader.readuntil(b'\n')
1186
+ except asyncio.IncompleteReadError as e:
1187
+ line_bytes = e.partial
1188
+ except asyncio.LimitOverrunError as e:
1189
+ line_bytes = await reader.readexactly(e.consumed)
1190
+ if line_bytes:
1191
+ line = decode(line_bytes)
1192
+ stdo_lines.append(line)
1193
+ if console_mode is ConsoleUser.STDOUT:
1194
+ print(line, end='', flush=True)
1195
+ if queue:
1196
+ await queue.put(line)
1197
+ return ''.join(stdo_lines)
1198
+ except asyncio.CancelledError:
1199
+ return ''.join(stdo_lines)
1200
+ finally:
1201
+ if queue:
1202
+ await queue.put(None)
1203
+
1204
+ def run_with_mono(fname: str) -> bool:
1205
+ return fname.endswith('.exe') and not (is_windows() or is_cygwin())
1206
+
1207
+ def check_testdata(objs: T.List[TestSerialisation]) -> T.List[TestSerialisation]:
1208
+ if not isinstance(objs, list):
1209
+ raise MesonVersionMismatchException('<unknown>', coredata_version)
1210
+ for obj in objs:
1211
+ if not isinstance(obj, TestSerialisation):
1212
+ raise MesonVersionMismatchException('<unknown>', coredata_version)
1213
+ if not hasattr(obj, 'version'):
1214
+ raise MesonVersionMismatchException('<unknown>', coredata_version)
1215
+ if major_versions_differ(obj.version, coredata_version):
1216
+ raise MesonVersionMismatchException(obj.version, coredata_version)
1217
+ return objs
1218
+
1219
+ # Custom waiting primitives for asyncio
1220
+
1221
+ async def queue_iter(q: 'asyncio.Queue[T.Optional[str]]') -> T.AsyncIterator[str]:
1222
+ while True:
1223
+ item = await q.get()
1224
+ q.task_done()
1225
+ if item is None:
1226
+ break
1227
+ yield item
1228
+
1229
+ async def complete(future: asyncio.Future) -> None:
1230
+ """Wait for completion of the given future, ignoring cancellation."""
1231
+ try:
1232
+ await future
1233
+ except asyncio.CancelledError:
1234
+ pass
1235
+
1236
+ async def complete_all(futures: T.Iterable[asyncio.Future],
1237
+ timeout: T.Optional[T.Union[int, float]] = None) -> None:
1238
+ """Wait for completion of all the given futures, ignoring cancellation.
1239
+ If timeout is not None, raise an asyncio.TimeoutError after the given
1240
+ time has passed. asyncio.TimeoutError is only raised if some futures
1241
+ have not completed and none have raised exceptions, even if timeout
1242
+ is zero."""
1243
+
1244
+ def check_futures(futures: T.Iterable[asyncio.Future]) -> None:
1245
+ # Raise exceptions if needed
1246
+ left = False
1247
+ for f in futures:
1248
+ if not f.done():
1249
+ left = True
1250
+ elif not f.cancelled():
1251
+ f.result()
1252
+ if left:
1253
+ raise asyncio.TimeoutError
1254
+
1255
+ # Python is silly and does not have a variant of asyncio.wait with an
1256
+ # absolute time as deadline.
1257
+ loop = asyncio.get_running_loop()
1258
+ deadline = None if timeout is None else loop.time() + timeout
1259
+ while futures and (timeout is None or timeout > 0):
1260
+ done, futures = await asyncio.wait(futures, timeout=timeout,
1261
+ return_when=asyncio.FIRST_EXCEPTION)
1262
+ check_futures(done)
1263
+ if deadline:
1264
+ timeout = deadline - loop.time()
1265
+
1266
+ check_futures(futures)
1267
+
1268
+
1269
+ class TestSubprocess:
1270
+ def __init__(self, p: asyncio.subprocess.Process,
1271
+ stdout: T.Optional[int], stderr: T.Optional[int],
1272
+ postwait_fn: T.Callable[[], None] = None):
1273
+ self._process = p
1274
+ self.stdout = stdout
1275
+ self.stderr = stderr
1276
+ self.stdo_task: T.Optional[asyncio.Task[None]] = None
1277
+ self.stde_task: T.Optional[asyncio.Task[None]] = None
1278
+ self.postwait_fn = postwait_fn
1279
+ self.all_futures: T.List[asyncio.Future] = []
1280
+ self.queue: T.Optional[asyncio.Queue[T.Optional[str]]] = None
1281
+
1282
+ def stdout_lines(self) -> T.AsyncIterator[str]:
1283
+ self.queue = asyncio.Queue()
1284
+ return queue_iter(self.queue)
1285
+
1286
+ def communicate(self,
1287
+ test: 'TestRun',
1288
+ console_mode: ConsoleUser) -> T.Tuple[T.Optional[T.Awaitable[str]],
1289
+ T.Optional[T.Awaitable[str]]]:
1290
+ async def collect_stdo(test: 'TestRun',
1291
+ reader: asyncio.StreamReader,
1292
+ console_mode: ConsoleUser) -> None:
1293
+ test.stdo = await read_decode(reader, self.queue, console_mode)
1294
+
1295
+ async def collect_stde(test: 'TestRun',
1296
+ reader: asyncio.StreamReader,
1297
+ console_mode: ConsoleUser) -> None:
1298
+ test.stde = await read_decode(reader, None, console_mode)
1299
+
1300
+ # asyncio.ensure_future ensures that printing can
1301
+ # run in the background, even before it is awaited
1302
+ if self.stdo_task is None and self.stdout is not None:
1303
+ decode_coro = collect_stdo(test, self._process.stdout, console_mode)
1304
+ self.stdo_task = asyncio.ensure_future(decode_coro)
1305
+ self.all_futures.append(self.stdo_task)
1306
+ if self.stderr is not None and self.stderr != asyncio.subprocess.STDOUT:
1307
+ decode_coro = collect_stde(test, self._process.stderr, console_mode)
1308
+ self.stde_task = asyncio.ensure_future(decode_coro)
1309
+ self.all_futures.append(self.stde_task)
1310
+
1311
+ return self.stdo_task, self.stde_task
1312
+
1313
+ async def _kill(self) -> T.Optional[str]:
1314
+ # Python does not provide multiplatform support for
1315
+ # killing a process and all its children so we need
1316
+ # to roll our own.
1317
+ p = self._process
1318
+ try:
1319
+ if is_windows():
1320
+ subprocess.run(['taskkill', '/F', '/T', '/PID', str(p.pid)])
1321
+ else:
1322
+ # Send a termination signal to the process group that setsid()
1323
+ # created - giving it a chance to perform any cleanup.
1324
+ os.killpg(p.pid, signal.SIGTERM)
1325
+
1326
+ # Make sure the termination signal actually kills the process
1327
+ # group, otherwise retry with a SIGKILL.
1328
+ with suppress(asyncio.TimeoutError):
1329
+ await asyncio.wait_for(p.wait(), timeout=0.5)
1330
+ if p.returncode is not None:
1331
+ return None
1332
+
1333
+ os.killpg(p.pid, signal.SIGKILL)
1334
+
1335
+ with suppress(asyncio.TimeoutError):
1336
+ await asyncio.wait_for(p.wait(), timeout=1)
1337
+ if p.returncode is not None:
1338
+ return None
1339
+
1340
+ # An earlier kill attempt has not worked for whatever reason.
1341
+ # Try to kill it one last time with a direct call.
1342
+ # If the process has spawned children, they will remain around.
1343
+ p.kill()
1344
+ with suppress(asyncio.TimeoutError):
1345
+ await asyncio.wait_for(p.wait(), timeout=1)
1346
+ if p.returncode is not None:
1347
+ return None
1348
+ return 'Test process could not be killed.'
1349
+ except ProcessLookupError:
1350
+ # Sometimes (e.g. with Wine) this happens. There's nothing
1351
+ # we can do, probably the process already died so just wait
1352
+ # for the event loop to pick that up.
1353
+ await p.wait()
1354
+ return None
1355
+ finally:
1356
+ if self.stdo_task:
1357
+ self.stdo_task.cancel()
1358
+ if self.stde_task:
1359
+ self.stde_task.cancel()
1360
+
1361
+ async def wait(self, test: 'TestRun') -> None:
1362
+ p = self._process
1363
+
1364
+ self.all_futures.append(asyncio.ensure_future(p.wait()))
1365
+ try:
1366
+ await complete_all(self.all_futures, timeout=test.timeout)
1367
+ except asyncio.TimeoutError:
1368
+ test.additional_error += await self._kill() or ''
1369
+ test.res = TestResult.TIMEOUT
1370
+ except asyncio.CancelledError:
1371
+ # The main loop must have seen Ctrl-C.
1372
+ test.additional_error += await self._kill() or ''
1373
+ test.res = TestResult.INTERRUPT
1374
+ finally:
1375
+ if self.postwait_fn:
1376
+ self.postwait_fn()
1377
+
1378
+ test.returncode = p.returncode or 0
1379
+
1380
+ class SingleTestRunner:
1381
+
1382
+ def __init__(self, test: TestSerialisation, env: T.Dict[str, str], name: str,
1383
+ options: argparse.Namespace):
1384
+ self.test = test
1385
+ self.options = options
1386
+ self.cmd = self._get_cmd()
1387
+
1388
+ if self.cmd and self.test.extra_paths:
1389
+ env['PATH'] = os.pathsep.join(self.test.extra_paths + ['']) + env['PATH']
1390
+ winecmd = []
1391
+ for c in self.cmd:
1392
+ winecmd.append(c)
1393
+ if os.path.basename(c).startswith('wine'):
1394
+ env['WINEPATH'] = get_wine_shortpath(
1395
+ winecmd,
1396
+ ['Z:' + p for p in self.test.extra_paths] + env.get('WINEPATH', '').split(';'),
1397
+ self.test.workdir
1398
+ )
1399
+ break
1400
+
1401
+ # If MALLOC_PERTURB_ is not set, or if it is set to an empty value,
1402
+ # (i.e., the test or the environment don't explicitly set it), set
1403
+ # it ourselves. We do this unconditionally for regular tests
1404
+ # because it is extremely useful to have.
1405
+ # Setting MALLOC_PERTURB_="0" will completely disable this feature.
1406
+ if ('MALLOC_PERTURB_' not in env or not env['MALLOC_PERTURB_']) and not options.benchmark:
1407
+ env['MALLOC_PERTURB_'] = str(random.randint(1, 255))
1408
+
1409
+ # Sanitizers do not default to aborting on error. This is counter to
1410
+ # expectations when using -Db_sanitize and has led to confusion in the wild
1411
+ # in CI. Set our own values of {ASAN,UBSAN}_OPTIONS to rectify this, but
1412
+ # only if the user has not defined them.
1413
+ if ('ASAN_OPTIONS' not in env or not env['ASAN_OPTIONS']):
1414
+ env['ASAN_OPTIONS'] = 'halt_on_error=1:abort_on_error=1:print_summary=1'
1415
+ if ('UBSAN_OPTIONS' not in env or not env['UBSAN_OPTIONS']):
1416
+ env['UBSAN_OPTIONS'] = 'halt_on_error=1:abort_on_error=1:print_summary=1:print_stacktrace=1'
1417
+ if ('MSAN_OPTIONS' not in env or not env['MSAN_OPTIONS']):
1418
+ env['UBSAN_OPTIONS'] = 'halt_on_error=1:abort_on_error=1:print_summary=1:print_stacktrace=1'
1419
+
1420
+ if self.options.gdb or self.test.timeout is None or self.test.timeout <= 0:
1421
+ timeout = None
1422
+ elif self.options.timeout_multiplier is None:
1423
+ timeout = self.test.timeout
1424
+ elif self.options.timeout_multiplier <= 0:
1425
+ timeout = None
1426
+ else:
1427
+ timeout = self.test.timeout * self.options.timeout_multiplier
1428
+
1429
+ is_parallel = test.is_parallel and self.options.num_processes > 1 and not self.options.gdb
1430
+ verbose = (test.verbose or self.options.verbose) and not self.options.quiet
1431
+ self.runobj = TestRun(test, env, name, timeout, is_parallel, verbose)
1432
+
1433
+ if self.options.gdb:
1434
+ self.console_mode = ConsoleUser.GDB
1435
+ elif self.runobj.direct_stdout:
1436
+ self.console_mode = ConsoleUser.STDOUT
1437
+ else:
1438
+ self.console_mode = ConsoleUser.LOGGER
1439
+
1440
+ def _get_test_cmd(self) -> T.Optional[T.List[str]]:
1441
+ testentry = self.test.fname[0]
1442
+ if self.options.no_rebuild and self.test.cmd_is_built and not os.path.isfile(testentry):
1443
+ raise TestException(f'The test program {testentry!r} does not exist. Cannot run tests before building them.')
1444
+ if testentry.endswith('.jar'):
1445
+ return ['java', '-jar'] + self.test.fname
1446
+ elif not self.test.is_cross_built and run_with_mono(testentry):
1447
+ return ['mono'] + self.test.fname
1448
+ elif self.test.cmd_is_exe and self.test.is_cross_built and self.test.needs_exe_wrapper:
1449
+ if self.test.exe_wrapper is None:
1450
+ # Can not run test on cross compiled executable
1451
+ # because there is no execute wrapper.
1452
+ return None
1453
+ elif self.test.cmd_is_exe:
1454
+ # If the command is not built (ie, its a python script),
1455
+ # then we don't check for the exe-wrapper
1456
+ if not self.test.exe_wrapper.found():
1457
+ msg = ('The exe_wrapper defined in the cross file {!r} was not '
1458
+ 'found. Please check the command and/or add it to PATH.')
1459
+ raise TestException(msg.format(self.test.exe_wrapper.name))
1460
+ return self.test.exe_wrapper.get_command() + self.test.fname
1461
+ elif self.test.cmd_is_built and not self.test.cmd_is_exe and is_windows():
1462
+ test_cmd = ExternalProgram._shebang_to_cmd(self.test.fname[0])
1463
+ if test_cmd is not None:
1464
+ test_cmd += self.test.fname[1:]
1465
+ return test_cmd
1466
+ return self.test.fname
1467
+
1468
+ def _get_cmd(self) -> T.Optional[T.List[str]]:
1469
+ test_cmd = self._get_test_cmd()
1470
+ if not test_cmd:
1471
+ return None
1472
+ return TestHarness.get_wrapper(self.options) + test_cmd
1473
+
1474
+ @property
1475
+ def is_parallel(self) -> bool:
1476
+ return self.runobj.is_parallel
1477
+
1478
+ @property
1479
+ def visible_name(self) -> str:
1480
+ return self.runobj.name
1481
+
1482
+ @property
1483
+ def timeout(self) -> T.Optional[int]:
1484
+ return self.runobj.timeout
1485
+
1486
+ async def run(self, harness: 'TestHarness') -> TestRun:
1487
+ if self.cmd is None:
1488
+ self.stdo = 'Not run because cannot execute cross compiled binaries.'
1489
+ harness.log_start_test(self.runobj)
1490
+ self.runobj.complete_skip()
1491
+ else:
1492
+ cmd = self.cmd + self.test.cmd_args + self.options.test_args
1493
+ self.runobj.start(cmd)
1494
+ harness.log_start_test(self.runobj)
1495
+ await self._run_cmd(harness, cmd)
1496
+ return self.runobj
1497
+
1498
+ async def _run_subprocess(self, args: T.List[str], *,
1499
+ stdout: T.Optional[int], stderr: T.Optional[int],
1500
+ env: T.Dict[str, str], cwd: T.Optional[str]) -> TestSubprocess:
1501
+ # Let gdb handle ^C instead of us
1502
+ if self.options.gdb:
1503
+ previous_sigint_handler = signal.getsignal(signal.SIGINT)
1504
+ # Make the meson executable ignore SIGINT while gdb is running.
1505
+ signal.signal(signal.SIGINT, signal.SIG_IGN)
1506
+
1507
+ def preexec_fn() -> None:
1508
+ if self.options.gdb:
1509
+ # Restore the SIGINT handler for the child process to
1510
+ # ensure it can handle it.
1511
+ signal.signal(signal.SIGINT, signal.SIG_DFL)
1512
+ else:
1513
+ # We don't want setsid() in gdb because gdb needs the
1514
+ # terminal in order to handle ^C and not show tcsetpgrp()
1515
+ # errors avoid not being able to use the terminal.
1516
+ os.setsid()
1517
+
1518
+ def postwait_fn() -> None:
1519
+ if self.options.gdb:
1520
+ # Let us accept ^C again
1521
+ signal.signal(signal.SIGINT, previous_sigint_handler)
1522
+
1523
+ p = await asyncio.create_subprocess_exec(*args,
1524
+ stdout=stdout,
1525
+ stderr=stderr,
1526
+ env=env,
1527
+ cwd=cwd,
1528
+ preexec_fn=preexec_fn if not is_windows() else None)
1529
+ return TestSubprocess(p, stdout=stdout, stderr=stderr,
1530
+ postwait_fn=postwait_fn if not is_windows() else None)
1531
+
1532
+ async def _run_cmd(self, harness: 'TestHarness', cmd: T.List[str]) -> None:
1533
+ if self.console_mode is ConsoleUser.GDB:
1534
+ stdout = None
1535
+ stderr = None
1536
+ else:
1537
+ stdout = asyncio.subprocess.PIPE
1538
+ stderr = asyncio.subprocess.STDOUT \
1539
+ if not self.options.split and not self.runobj.needs_parsing \
1540
+ else asyncio.subprocess.PIPE
1541
+
1542
+ extra_cmd: T.List[str] = []
1543
+ if self.test.protocol is TestProtocol.GTEST:
1544
+ gtestname = self.test.name
1545
+ if self.test.workdir:
1546
+ gtestname = os.path.join(self.test.workdir, self.test.name)
1547
+ extra_cmd.append(f'--gtest_output=xml:{gtestname}.xml')
1548
+
1549
+ p = await self._run_subprocess(cmd + extra_cmd,
1550
+ stdout=stdout,
1551
+ stderr=stderr,
1552
+ env=self.runobj.env,
1553
+ cwd=self.test.workdir)
1554
+
1555
+ if self.runobj.needs_parsing:
1556
+ parse_coro = self.runobj.parse(harness, p.stdout_lines())
1557
+ parse_task = asyncio.ensure_future(parse_coro)
1558
+ else:
1559
+ parse_task = None
1560
+
1561
+ stdo_task, stde_task = p.communicate(self.runobj, self.console_mode)
1562
+ await p.wait(self.runobj)
1563
+
1564
+ if parse_task:
1565
+ await parse_task
1566
+ if stdo_task:
1567
+ await stdo_task
1568
+ if stde_task:
1569
+ await stde_task
1570
+
1571
+ self.runobj.complete()
1572
+
1573
+
1574
+ class TestHarness:
1575
+ def __init__(self, options: argparse.Namespace):
1576
+ self.options = options
1577
+ self.collected_failures: T.List[TestRun] = []
1578
+ self.fail_count = 0
1579
+ self.expectedfail_count = 0
1580
+ self.unexpectedpass_count = 0
1581
+ self.success_count = 0
1582
+ self.skip_count = 0
1583
+ self.timeout_count = 0
1584
+ self.test_count = 0
1585
+ self.name_max_len = 0
1586
+ self.is_run = False
1587
+ self.loggers: T.List[TestLogger] = []
1588
+ self.console_logger = ConsoleLogger()
1589
+ self.loggers.append(self.console_logger)
1590
+ self.need_console = False
1591
+ self.ninja: T.List[str] = None
1592
+
1593
+ self.logfile_base: T.Optional[str] = None
1594
+ if self.options.logbase and not self.options.gdb:
1595
+ namebase = None
1596
+ self.logfile_base = os.path.join(self.options.wd, 'meson-logs', self.options.logbase)
1597
+
1598
+ if self.options.wrapper:
1599
+ namebase = os.path.basename(self.get_wrapper(self.options)[0])
1600
+ elif self.options.setup:
1601
+ namebase = self.options.setup.replace(":", "_")
1602
+
1603
+ if namebase:
1604
+ self.logfile_base += '-' + namebase.replace(' ', '_')
1605
+
1606
+ self.prepare_build()
1607
+ self.load_metadata()
1608
+
1609
+ ss = set()
1610
+ for t in self.tests:
1611
+ for s in t.suite:
1612
+ ss.add(s)
1613
+ self.suites = list(ss)
1614
+
1615
+ def get_console_logger(self) -> 'ConsoleLogger':
1616
+ assert self.console_logger
1617
+ return self.console_logger
1618
+
1619
+ def prepare_build(self) -> None:
1620
+ if self.options.no_rebuild:
1621
+ return
1622
+
1623
+ self.ninja = environment.detect_ninja()
1624
+ if not self.ninja:
1625
+ print("Can't find ninja, can't rebuild test.")
1626
+ # If ninja can't be found return exit code 127, indicating command
1627
+ # not found for shell, which seems appropriate here. This works
1628
+ # nicely for `git bisect run`, telling it to abort - no point in
1629
+ # continuing if there's no ninja.
1630
+ sys.exit(127)
1631
+
1632
+ def load_metadata(self) -> None:
1633
+ startdir = os.getcwd()
1634
+ try:
1635
+ os.chdir(self.options.wd)
1636
+
1637
+ # Before loading build / test data, make sure that the build
1638
+ # configuration does not need to be regenerated. This needs to
1639
+ # happen before rebuild_deps(), because we need the correct list of
1640
+ # tests and their dependencies to compute
1641
+ if not self.options.no_rebuild:
1642
+ teststdo = subprocess.run(self.ninja + ['-n', 'build.ninja'], capture_output=True).stdout
1643
+ if b'ninja: no work to do.' not in teststdo and b'samu: nothing to do' not in teststdo:
1644
+ stdo = sys.stderr if self.options.list else sys.stdout
1645
+ ret = subprocess.run(self.ninja + ['build.ninja'], stdout=stdo.fileno())
1646
+ if ret.returncode != 0:
1647
+ raise TestException(f'Could not configure {self.options.wd!r}')
1648
+
1649
+ self.build_data = build.load(os.getcwd())
1650
+ if not self.options.setup:
1651
+ self.options.setup = self.build_data.test_setup_default_name
1652
+ if self.options.benchmark:
1653
+ self.tests = self.load_tests('meson_benchmark_setup.dat')
1654
+ else:
1655
+ self.tests = self.load_tests('meson_test_setup.dat')
1656
+ finally:
1657
+ os.chdir(startdir)
1658
+
1659
+ def load_tests(self, file_name: str) -> T.List[TestSerialisation]:
1660
+ datafile = Path('meson-private') / file_name
1661
+ if not datafile.is_file():
1662
+ raise TestException(f'Directory {self.options.wd!r} does not seem to be a Meson build directory.')
1663
+ with datafile.open('rb') as f:
1664
+ objs = check_testdata(pickle.load(f))
1665
+ return objs
1666
+
1667
+ def __enter__(self) -> 'TestHarness':
1668
+ return self
1669
+
1670
+ def __exit__(self, exc_type: T.Any, exc_value: T.Any, traceback: T.Any) -> None:
1671
+ self.close_logfiles()
1672
+
1673
+ def close_logfiles(self) -> None:
1674
+ for l in self.loggers:
1675
+ l.close()
1676
+ self.console_logger = None
1677
+
1678
+ def get_test_setup(self, test: T.Optional[TestSerialisation]) -> build.TestSetup:
1679
+ if ':' in self.options.setup:
1680
+ if self.options.setup not in self.build_data.test_setups:
1681
+ sys.exit(f"Unknown test setup '{self.options.setup}'.")
1682
+ return self.build_data.test_setups[self.options.setup]
1683
+ else:
1684
+ full_name = test.project_name + ":" + self.options.setup
1685
+ if full_name not in self.build_data.test_setups:
1686
+ sys.exit(f"Test setup '{self.options.setup}' not found from project '{test.project_name}'.")
1687
+ return self.build_data.test_setups[full_name]
1688
+
1689
+ def merge_setup_options(self, options: argparse.Namespace, test: TestSerialisation) -> T.Dict[str, str]:
1690
+ current = self.get_test_setup(test)
1691
+ if not options.gdb:
1692
+ options.gdb = current.gdb
1693
+ if options.gdb:
1694
+ options.verbose = True
1695
+ if options.timeout_multiplier is None:
1696
+ options.timeout_multiplier = current.timeout_multiplier
1697
+ # if options.env is None:
1698
+ # options.env = current.env # FIXME, should probably merge options here.
1699
+ if options.wrapper is None:
1700
+ options.wrapper = current.exe_wrapper
1701
+ elif current.exe_wrapper:
1702
+ sys.exit('Conflict: both test setup and command line specify an exe wrapper.')
1703
+ return current.env.get_env(os.environ.copy())
1704
+
1705
+ def get_test_runner(self, test: TestSerialisation) -> SingleTestRunner:
1706
+ name = self.get_pretty_suite(test)
1707
+ options = deepcopy(self.options)
1708
+ if self.options.setup:
1709
+ env = self.merge_setup_options(options, test)
1710
+ else:
1711
+ env = os.environ.copy()
1712
+ test_env = test.env.get_env(env)
1713
+ env.update(test_env)
1714
+ if (test.is_cross_built and test.needs_exe_wrapper and
1715
+ test.exe_wrapper and test.exe_wrapper.found()):
1716
+ env['MESON_EXE_WRAPPER'] = join_args(test.exe_wrapper.get_command())
1717
+ return SingleTestRunner(test, env, name, options)
1718
+
1719
+ def process_test_result(self, result: TestRun) -> None:
1720
+ if result.res is TestResult.TIMEOUT:
1721
+ self.timeout_count += 1
1722
+ elif result.res is TestResult.SKIP:
1723
+ self.skip_count += 1
1724
+ elif result.res is TestResult.OK:
1725
+ self.success_count += 1
1726
+ elif result.res in {TestResult.FAIL, TestResult.ERROR, TestResult.INTERRUPT}:
1727
+ self.fail_count += 1
1728
+ elif result.res is TestResult.EXPECTEDFAIL:
1729
+ self.expectedfail_count += 1
1730
+ elif result.res is TestResult.UNEXPECTEDPASS:
1731
+ self.unexpectedpass_count += 1
1732
+ else:
1733
+ sys.exit(f'Unknown test result encountered: {result.res}')
1734
+
1735
+ if result.res.is_bad():
1736
+ self.collected_failures.append(result)
1737
+ for l in self.loggers:
1738
+ l.log(self, result)
1739
+
1740
+ @property
1741
+ def numlen(self) -> int:
1742
+ return len(str(self.test_count))
1743
+
1744
+ @property
1745
+ def max_left_width(self) -> int:
1746
+ return 2 * self.numlen + 2
1747
+
1748
+ def get_test_num_prefix(self, num: int) -> str:
1749
+ return '{num:{numlen}}/{testcount} '.format(numlen=self.numlen,
1750
+ num=num,
1751
+ testcount=self.test_count)
1752
+
1753
+ def format(self, result: TestRun, colorize: bool,
1754
+ max_left_width: int = 0,
1755
+ prefix: str = '',
1756
+ left: T.Optional[str] = None,
1757
+ middle: T.Optional[str] = None,
1758
+ right: T.Optional[str] = None) -> str:
1759
+ if left is None:
1760
+ left = self.get_test_num_prefix(result.num)
1761
+
1762
+ # A non-default max_left_width lets the logger print more stuff before the
1763
+ # name, while ensuring that the rightmost columns remain aligned.
1764
+ max_left_width = max(max_left_width, self.max_left_width)
1765
+
1766
+ if middle is None:
1767
+ middle = result.name
1768
+ extra_mid_width = max_left_width + self.name_max_len + 1 - uniwidth(middle) - uniwidth(left) - uniwidth(prefix)
1769
+ middle += ' ' * max(1, extra_mid_width)
1770
+
1771
+ if right is None:
1772
+ right = '{res} {dur:{durlen}.2f}s'.format(
1773
+ res=result.res.get_text(colorize),
1774
+ dur=result.duration,
1775
+ durlen=self.duration_max_len + 3)
1776
+ details = result.get_details()
1777
+ if details:
1778
+ right += ' ' + details
1779
+ return prefix + left + middle + right
1780
+
1781
+ def summary(self) -> str:
1782
+ return textwrap.dedent('''
1783
+ Ok: {:<4}
1784
+ Expected Fail: {:<4}
1785
+ Fail: {:<4}
1786
+ Unexpected Pass: {:<4}
1787
+ Skipped: {:<4}
1788
+ Timeout: {:<4}
1789
+ ''').format(self.success_count, self.expectedfail_count, self.fail_count,
1790
+ self.unexpectedpass_count, self.skip_count, self.timeout_count)
1791
+
1792
+ def total_failure_count(self) -> int:
1793
+ return self.fail_count + self.unexpectedpass_count + self.timeout_count
1794
+
1795
+ def doit(self) -> int:
1796
+ if self.is_run:
1797
+ raise RuntimeError('Test harness object can only be used once.')
1798
+ self.is_run = True
1799
+ tests = self.get_tests()
1800
+ if not tests:
1801
+ return 0
1802
+ if not self.options.no_rebuild and not rebuild_deps(self.ninja, self.options.wd, tests):
1803
+ # We return 125 here in case the build failed.
1804
+ # The reason is that exit code 125 tells `git bisect run` that the current
1805
+ # commit should be skipped. Thus users can directly use `meson test` to
1806
+ # bisect without needing to handle the does-not-build case separately in a
1807
+ # wrapper script.
1808
+ sys.exit(125)
1809
+
1810
+ self.name_max_len = max(uniwidth(self.get_pretty_suite(test)) for test in tests)
1811
+ self.options.num_processes = min(self.options.num_processes,
1812
+ len(tests) * self.options.repeat)
1813
+ startdir = os.getcwd()
1814
+ try:
1815
+ os.chdir(self.options.wd)
1816
+ runners: T.List[SingleTestRunner] = []
1817
+ for i in range(self.options.repeat):
1818
+ runners.extend(self.get_test_runner(test) for test in tests)
1819
+ if i == 0:
1820
+ self.duration_max_len = max(len(str(int(runner.timeout or 99)))
1821
+ for runner in runners)
1822
+ # Disable the progress report if it gets in the way
1823
+ self.need_console = any(runner.console_mode is not ConsoleUser.LOGGER
1824
+ for runner in runners)
1825
+
1826
+ self.test_count = len(runners)
1827
+ self.run_tests(runners)
1828
+ finally:
1829
+ os.chdir(startdir)
1830
+ return self.total_failure_count()
1831
+
1832
+ @staticmethod
1833
+ def split_suite_string(suite: str) -> T.Tuple[str, str]:
1834
+ if ':' in suite:
1835
+ split = suite.split(':', 1)
1836
+ assert len(split) == 2
1837
+ return split[0], split[1]
1838
+ else:
1839
+ return suite, ""
1840
+
1841
+ @staticmethod
1842
+ def test_in_suites(test: TestSerialisation, suites: T.List[str]) -> bool:
1843
+ for suite in suites:
1844
+ (prj_match, st_match) = TestHarness.split_suite_string(suite)
1845
+ for prjst in test.suite:
1846
+ (prj, st) = TestHarness.split_suite_string(prjst)
1847
+
1848
+ # the SUITE can be passed as
1849
+ # suite_name
1850
+ # or
1851
+ # project_name:suite_name
1852
+ # so we need to select only the test belonging to project_name
1853
+
1854
+ # this if handle the first case (i.e., SUITE == suite_name)
1855
+
1856
+ # in this way we can run tests belonging to different
1857
+ # (sub)projects which share the same suite_name
1858
+ if not st_match and st == prj_match:
1859
+ return True
1860
+
1861
+ # these two conditions are needed to handle the second option
1862
+ # i.e., SUITE == project_name:suite_name
1863
+
1864
+ # in this way we select the only the tests of
1865
+ # project_name with suite_name
1866
+ if prj_match and prj != prj_match:
1867
+ continue
1868
+ if st_match and st != st_match:
1869
+ continue
1870
+ return True
1871
+ return False
1872
+
1873
+ def test_suitable(self, test: TestSerialisation) -> bool:
1874
+ if TestHarness.test_in_suites(test, self.options.exclude_suites):
1875
+ return False
1876
+
1877
+ if self.options.include_suites:
1878
+ # Both force inclusion (overriding add_test_setup) and exclude
1879
+ # everything else
1880
+ return TestHarness.test_in_suites(test, self.options.include_suites)
1881
+
1882
+ if self.options.setup:
1883
+ setup = self.get_test_setup(test)
1884
+ if TestHarness.test_in_suites(test, setup.exclude_suites):
1885
+ return False
1886
+
1887
+ return True
1888
+
1889
+ def tests_from_args(self, tests: T.List[TestSerialisation]) -> T.Generator[TestSerialisation, None, None]:
1890
+ '''
1891
+ Allow specifying test names like "meson test foo1 foo2", where test('foo1', ...)
1892
+
1893
+ Also support specifying the subproject to run tests from like
1894
+ "meson test subproj:" (all tests inside subproj) or "meson test subproj:foo1"
1895
+ to run foo1 inside subproj. Coincidentally also "meson test :foo1" to
1896
+ run all tests with that name across all subprojects, which is
1897
+ identical to "meson test foo1"
1898
+ '''
1899
+ patterns: T.Dict[T.Tuple[str, str], bool] = {}
1900
+ for arg in self.options.args:
1901
+ # Replace empty components by wildcards:
1902
+ # '' -> '*:*'
1903
+ # 'name' -> '*:name'
1904
+ # ':name' -> '*:name'
1905
+ # 'proj:' -> 'proj:*'
1906
+ if ':' in arg:
1907
+ subproj, name = arg.split(':', maxsplit=1)
1908
+ if name == '':
1909
+ name = '*'
1910
+ if subproj == '': # in case arg was ':'
1911
+ subproj = '*'
1912
+ else:
1913
+ subproj, name = '*', arg
1914
+ patterns[(subproj, name)] = False
1915
+
1916
+ for t in tests:
1917
+ # For each test, find the first matching pattern
1918
+ # and mark it as used. yield the matching tests.
1919
+ for subproj, name in list(patterns):
1920
+ if fnmatch(t.project_name, subproj) and fnmatch(t.name, name):
1921
+ patterns[(subproj, name)] = True
1922
+ yield t
1923
+ break
1924
+
1925
+ for (subproj, name), was_used in patterns.items():
1926
+ if not was_used:
1927
+ # For each unused pattern...
1928
+ arg = f'{subproj}:{name}'
1929
+ for t in tests:
1930
+ # ... if it matches a test, then it wasn't used because another
1931
+ # pattern matched the same test before.
1932
+ # Report it as a warning.
1933
+ if fnmatch(t.project_name, subproj) and fnmatch(t.name, name):
1934
+ mlog.warning(f'{arg} test name is redundant and was not used')
1935
+ break
1936
+ else:
1937
+ # If the pattern doesn't match any test,
1938
+ # report it as an error. We don't want the `test` command to
1939
+ # succeed on an invalid pattern.
1940
+ raise MesonException(f'{arg} test name does not match any test')
1941
+
1942
+ def get_tests(self, errorfile: T.Optional[T.IO] = None) -> T.List[TestSerialisation]:
1943
+ if not self.tests:
1944
+ print('No tests defined.', file=errorfile)
1945
+ return []
1946
+
1947
+ tests = [t for t in self.tests if self.test_suitable(t)]
1948
+ if self.options.args:
1949
+ tests = list(self.tests_from_args(tests))
1950
+
1951
+ if not tests:
1952
+ print('No suitable tests defined.', file=errorfile)
1953
+ return []
1954
+
1955
+ return tests
1956
+
1957
+ def flush_logfiles(self) -> None:
1958
+ for l in self.loggers:
1959
+ l.flush()
1960
+
1961
+ def open_logfiles(self) -> None:
1962
+ if not self.logfile_base:
1963
+ return
1964
+
1965
+ self.loggers.append(JunitBuilder(self.logfile_base + '.junit.xml'))
1966
+ self.loggers.append(JsonLogfileBuilder(self.logfile_base + '.json'))
1967
+ self.loggers.append(TextLogfileBuilder(self.logfile_base + '.txt', errors='surrogateescape'))
1968
+
1969
+ @staticmethod
1970
+ def get_wrapper(options: argparse.Namespace) -> T.List[str]:
1971
+ wrap: T.List[str] = []
1972
+ if options.gdb:
1973
+ wrap = [options.gdb_path, '--quiet']
1974
+ if options.repeat > 1:
1975
+ wrap += ['-ex', 'run', '-ex', 'quit']
1976
+ # Signal the end of arguments to gdb
1977
+ wrap += ['--args']
1978
+ if options.wrapper:
1979
+ wrap += options.wrapper
1980
+ return wrap
1981
+
1982
+ def get_pretty_suite(self, test: TestSerialisation) -> str:
1983
+ if len(self.suites) > 1 and test.suite:
1984
+ rv = TestHarness.split_suite_string(test.suite[0])[0]
1985
+ s = "+".join(TestHarness.split_suite_string(s)[1] for s in test.suite)
1986
+ if s:
1987
+ rv += ":"
1988
+ return rv + s + " / " + test.name
1989
+ else:
1990
+ return test.name
1991
+
1992
+ def run_tests(self, runners: T.List[SingleTestRunner]) -> None:
1993
+ try:
1994
+ self.open_logfiles()
1995
+
1996
+ # TODO: this is the default for python 3.8
1997
+ if sys.platform == 'win32':
1998
+ asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy())
1999
+
2000
+ asyncio.run(self._run_tests(runners))
2001
+ finally:
2002
+ self.close_logfiles()
2003
+
2004
+ def log_subtest(self, test: TestRun, s: str, res: TestResult) -> None:
2005
+ for l in self.loggers:
2006
+ l.log_subtest(self, test, s, res)
2007
+
2008
+ def log_start_test(self, test: TestRun) -> None:
2009
+ for l in self.loggers:
2010
+ l.start_test(self, test)
2011
+
2012
+ async def _run_tests(self, runners: T.List[SingleTestRunner]) -> None:
2013
+ semaphore = asyncio.Semaphore(self.options.num_processes)
2014
+ futures: T.Deque[asyncio.Future] = deque()
2015
+ running_tests: T.Dict[asyncio.Future, str] = {}
2016
+ interrupted = False
2017
+ ctrlc_times: T.Deque[float] = deque(maxlen=MAX_CTRLC)
2018
+ loop = asyncio.get_running_loop()
2019
+
2020
+ async def run_test(test: SingleTestRunner) -> None:
2021
+ async with semaphore:
2022
+ if interrupted or (self.options.repeat > 1 and self.fail_count):
2023
+ return
2024
+ res = await test.run(self)
2025
+ self.process_test_result(res)
2026
+ maxfail = self.options.maxfail
2027
+ if maxfail and self.fail_count >= maxfail and res.res.is_bad():
2028
+ cancel_all_tests()
2029
+
2030
+ def test_done(f: asyncio.Future) -> None:
2031
+ if not f.cancelled():
2032
+ f.result()
2033
+ futures.remove(f)
2034
+ try:
2035
+ del running_tests[f]
2036
+ except KeyError:
2037
+ pass
2038
+
2039
+ def cancel_one_test(warn: bool) -> None:
2040
+ future = futures.popleft()
2041
+ futures.append(future)
2042
+ if warn:
2043
+ self.flush_logfiles()
2044
+ mlog.warning('CTRL-C detected, interrupting {}'.format(running_tests[future]))
2045
+ del running_tests[future]
2046
+ future.cancel()
2047
+
2048
+ def cancel_all_tests() -> None:
2049
+ nonlocal interrupted
2050
+ interrupted = True
2051
+ while running_tests:
2052
+ cancel_one_test(False)
2053
+
2054
+ def sigterm_handler() -> None:
2055
+ if interrupted:
2056
+ return
2057
+ self.flush_logfiles()
2058
+ mlog.warning('Received SIGTERM, exiting')
2059
+ cancel_all_tests()
2060
+
2061
+ def sigint_handler() -> None:
2062
+ # We always pick the longest-running future that has not been cancelled
2063
+ # If all the tests have been CTRL-C'ed, just stop
2064
+ nonlocal interrupted
2065
+ if interrupted:
2066
+ return
2067
+ ctrlc_times.append(loop.time())
2068
+ if len(ctrlc_times) == MAX_CTRLC and ctrlc_times[-1] - ctrlc_times[0] < 1:
2069
+ self.flush_logfiles()
2070
+ mlog.warning('CTRL-C detected, exiting')
2071
+ cancel_all_tests()
2072
+ elif running_tests:
2073
+ cancel_one_test(True)
2074
+ else:
2075
+ self.flush_logfiles()
2076
+ mlog.warning('CTRL-C detected, exiting')
2077
+ interrupted = True
2078
+
2079
+ for l in self.loggers:
2080
+ l.start(self)
2081
+
2082
+ if sys.platform != 'win32':
2083
+ if os.getpgid(0) == os.getpid():
2084
+ loop.add_signal_handler(signal.SIGINT, sigint_handler)
2085
+ else:
2086
+ loop.add_signal_handler(signal.SIGINT, sigterm_handler)
2087
+ loop.add_signal_handler(signal.SIGTERM, sigterm_handler)
2088
+ try:
2089
+ for runner in runners:
2090
+ if not runner.is_parallel:
2091
+ await complete_all(futures)
2092
+ future = asyncio.ensure_future(run_test(runner))
2093
+ futures.append(future)
2094
+ running_tests[future] = runner.visible_name
2095
+ future.add_done_callback(test_done)
2096
+ if not runner.is_parallel:
2097
+ await complete(future)
2098
+ if self.options.repeat > 1 and self.fail_count:
2099
+ break
2100
+
2101
+ await complete_all(futures)
2102
+ finally:
2103
+ if sys.platform != 'win32':
2104
+ loop.remove_signal_handler(signal.SIGINT)
2105
+ loop.remove_signal_handler(signal.SIGTERM)
2106
+ for l in self.loggers:
2107
+ await l.finish(self)
2108
+
2109
+ def list_tests(th: TestHarness) -> bool:
2110
+ tests = th.get_tests(errorfile=sys.stderr)
2111
+ for t in tests:
2112
+ print(th.get_pretty_suite(t))
2113
+ return not tests
2114
+
2115
+ def rebuild_deps(ninja: T.List[str], wd: str, tests: T.List[TestSerialisation]) -> bool:
2116
+ def convert_path_to_target(path: str) -> str:
2117
+ path = os.path.relpath(path, wd)
2118
+ if os.sep != '/':
2119
+ path = path.replace(os.sep, '/')
2120
+ return path
2121
+
2122
+ assert len(ninja) > 0
2123
+
2124
+ depends: T.Set[str] = set()
2125
+ targets: T.Set[str] = set()
2126
+ intro_targets: T.Dict[str, T.List[str]] = {}
2127
+ for target in load_info_file(get_infodir(wd), kind='targets'):
2128
+ intro_targets[target['id']] = [
2129
+ convert_path_to_target(f)
2130
+ for f in target['filename']]
2131
+ for t in tests:
2132
+ for d in t.depends:
2133
+ if d in depends:
2134
+ continue
2135
+ depends.update(d)
2136
+ targets.update(intro_targets[d])
2137
+
2138
+ ret = subprocess.run(ninja + ['-C', wd] + sorted(targets)).returncode
2139
+ if ret != 0:
2140
+ print(f'Could not rebuild {wd}')
2141
+ return False
2142
+
2143
+ return True
2144
+
2145
+ def run(options: argparse.Namespace) -> int:
2146
+ if options.benchmark:
2147
+ options.num_processes = 1
2148
+
2149
+ if options.verbose and options.quiet:
2150
+ print('Can not be both quiet and verbose at the same time.')
2151
+ return 1
2152
+
2153
+ check_bin = None
2154
+ if options.gdb:
2155
+ options.verbose = True
2156
+ if options.wrapper:
2157
+ print('Must not specify both a wrapper and gdb at the same time.')
2158
+ return 1
2159
+ check_bin = 'gdb'
2160
+
2161
+ if options.wrapper:
2162
+ check_bin = options.wrapper[0]
2163
+
2164
+ if check_bin is not None:
2165
+ exe = ExternalProgram(check_bin, silent=True)
2166
+ if not exe.found():
2167
+ print(f'Could not find requested program: {check_bin!r}')
2168
+ return 1
2169
+
2170
+ b = build.load(options.wd)
2171
+ need_vsenv = T.cast('bool', b.environment.coredata.get_option(OptionKey('vsenv')))
2172
+ setup_vsenv(need_vsenv)
2173
+
2174
+ if not options.no_rebuild:
2175
+ backend = b.environment.coredata.get_option(OptionKey('backend'))
2176
+ if backend == 'none':
2177
+ # nothing to build...
2178
+ options.no_rebuild = True
2179
+ elif backend != 'ninja':
2180
+ print('Only ninja backend is supported to rebuild tests before running them.')
2181
+ # Disable, no point in trying to build anything later
2182
+ options.no_rebuild = True
2183
+
2184
+ with TestHarness(options) as th:
2185
+ try:
2186
+ if options.list:
2187
+ return list_tests(th)
2188
+ return th.doit()
2189
+ except TestException as e:
2190
+ print('Meson test encountered an error:\n')
2191
+ if os.environ.get('MESON_FORCE_BACKTRACE'):
2192
+ raise e
2193
+ else:
2194
+ print(e)
2195
+ return 1
2196
+
2197
+ def run_with_args(args: T.List[str]) -> int:
2198
+ parser = argparse.ArgumentParser(prog='meson test')
2199
+ add_arguments(parser)
2200
+ options = parser.parse_args(args)
2201
+ return run(options)