ya.py 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. import os
  2. import sys
  3. import logging
  4. import json
  5. import six
  6. from .tools import to_str
  7. from .external import ExternalDataInfo
  8. TESTING_OUT_DIR_NAME = "testing_out_stuff" # XXX import from test.const
  9. yatest_logger = logging.getLogger("ya.test")
  10. class RunMode(object):
  11. Run = "run"
  12. List = "list"
  13. class TestMisconfigurationException(Exception):
  14. pass
  15. class Ya(object):
  16. """
  17. Adds integration with ya, helps in finding dependencies
  18. """
  19. def __init__(
  20. self,
  21. mode=None,
  22. source_root=None,
  23. build_root=None,
  24. dep_roots=None,
  25. output_dir=None,
  26. test_params=None,
  27. context=None,
  28. python_path=None,
  29. valgrind_path=None,
  30. gdb_path=None,
  31. data_root=None,
  32. env_file=None,
  33. ):
  34. context_file_path = os.environ.get("YA_TEST_CONTEXT_FILE", None)
  35. if context_file_path:
  36. with open(context_file_path, 'r') as afile:
  37. test_context = json.load(afile)
  38. context_runtime = test_context["runtime"]
  39. context_internal = test_context.get("internal", {})
  40. context_build = test_context.get("build", {})
  41. context_resources = test_context.get("resources", {})
  42. else:
  43. context_runtime = {}
  44. context_internal = {}
  45. context_build = {}
  46. context_resources = {}
  47. self._mode = mode
  48. self._build_root = to_str(context_runtime.get("build_root", "")) or build_root
  49. self._source_root = to_str(context_runtime.get("source_root", "")) or source_root or self._detect_source_root()
  50. self._output_dir = to_str(context_runtime.get("output_path", "")) or output_dir or self._detect_output_root()
  51. if not self._output_dir:
  52. raise Exception("Run ya make -t before running test binary")
  53. if not self._source_root:
  54. logging.warning("Source root was not set neither determined, use --source-root to set it explicitly")
  55. if not self._build_root:
  56. if self._source_root:
  57. self._build_root = self._source_root
  58. else:
  59. logging.warning("Build root was not set neither determined, use --build-root to set it explicitly")
  60. if data_root:
  61. self._data_root = data_root
  62. elif self._source_root:
  63. self._data_root = os.path.abspath(os.path.join(self._source_root, "..", "arcadia_tests_data"))
  64. self._dep_roots = dep_roots
  65. self._python_path = to_str(context_runtime.get("python_bin", "")) or python_path
  66. self._valgrind_path = valgrind_path
  67. self._gdb_path = to_str(context_runtime.get("gdb_bin", "")) or gdb_path
  68. self._test_params = {}
  69. self._context = {}
  70. self._test_item_node_id = None
  71. ram_drive_path = to_str(context_runtime.get("ram_drive_path", ""))
  72. if ram_drive_path:
  73. self._test_params["ram_drive_path"] = ram_drive_path
  74. if test_params:
  75. self._test_params.update(dict(x.split('=', 1) for x in test_params))
  76. self._test_params.update(context_runtime.get("test_params", {}))
  77. self._context["project_path"] = context_runtime.get("project_path")
  78. self._context["modulo"] = context_runtime.get("split_count", 1)
  79. self._context["modulo_index"] = context_runtime.get("split_index", 0)
  80. self._context["work_path"] = to_str(context_runtime.get("work_path"))
  81. self._context["test_tool_path"] = context_runtime.get("test_tool_path")
  82. self._context["test_output_ram_drive_path"] = to_str(context_runtime.get("test_output_ram_drive_path"))
  83. self._context["retry_index"] = context_runtime.get("retry_index")
  84. self._context["ya_global_resources"] = context_resources.get("global")
  85. self._context["sanitize"] = context_build.get("sanitizer")
  86. self._context["ya_trace_path"] = context_internal.get("trace_file")
  87. self._env_file = context_internal.get("env_file") or env_file
  88. if context:
  89. for k, v in context.items():
  90. if k not in self._context or v is not None:
  91. self._context[k] = v
  92. if self._env_file and os.path.exists(self._env_file):
  93. yatest_logger.debug("Reading variables from env_file at %s", self._env_file)
  94. var_list = []
  95. with open(self._env_file) as file:
  96. for ljson in file.readlines():
  97. variable = json.loads(ljson)
  98. for key, value in six.iteritems(variable):
  99. os.environ[key] = str(value)
  100. var_list.append(key)
  101. yatest_logger.debug("Variables loaded: %s", var_list)
  102. @property
  103. def source_root(self):
  104. return self._source_root
  105. @property
  106. def data_root(self):
  107. return self._data_root
  108. @property
  109. def build_root(self):
  110. return self._build_root
  111. @property
  112. def dep_roots(self):
  113. return self._dep_roots
  114. @property
  115. def output_dir(self):
  116. return self._output_dir
  117. @property
  118. def python_path(self):
  119. return self._python_path or sys.executable
  120. @property
  121. def valgrind_path(self):
  122. if not self._valgrind_path:
  123. raise ValueError("path to valgrind was not pass correctly, use --valgrind-path to fix it")
  124. return self._valgrind_path
  125. @property
  126. def gdb_path(self):
  127. return self._gdb_path
  128. @property
  129. def env_file(self):
  130. return self._env_file
  131. def get_binary(self, *path):
  132. assert self._build_root, "Build root was not set neither determined, use --build-root to set it explicitly"
  133. path = list(path)
  134. if os.name == "nt":
  135. if not path[-1].endswith(".exe"):
  136. path[-1] += ".exe"
  137. target_dirs = [self.build_root]
  138. # Search for binaries within PATH dirs to be able to get path to the binaries specified by basename for exectests
  139. if 'PATH' in os.environ:
  140. target_dirs += os.environ['PATH'].split(':')
  141. for target_dir in target_dirs:
  142. binary_path = os.path.join(target_dir, *path)
  143. if os.path.exists(binary_path):
  144. yatest_logger.debug("Binary was found by %s", binary_path)
  145. return binary_path
  146. error_message = "Cannot find binary '{binary}': make sure it was added in the DEPENDS section".format(binary=path)
  147. yatest_logger.debug(error_message)
  148. if self._mode == RunMode.Run:
  149. raise TestMisconfigurationException(error_message)
  150. def _build_root_rel(self, path):
  151. real_build_root = os.path.realpath(self.build_root)
  152. real_path = os.path.abspath(path)
  153. if path.startswith(real_build_root):
  154. return os.path.relpath(real_path, real_build_root)
  155. return path
  156. def file(self, path, diff_tool=None, local=False, diff_file_name=None, diff_tool_timeout=None):
  157. if diff_tool:
  158. if isinstance(diff_tool, tuple):
  159. diff_tool = list(diff_tool)
  160. # Normalize path to diff_tool - abs path in run_test node won't be accessible in canonize node
  161. if isinstance(diff_tool, list):
  162. diff_tool[0] = self._build_root_rel(diff_tool[0])
  163. else:
  164. diff_tool = self._build_root_rel(diff_tool)
  165. return ExternalDataInfo.serialize_file(path, diff_tool=diff_tool, local=local, diff_file_name=diff_file_name, diff_tool_timeout=diff_tool_timeout)
  166. def get_param(self, key, default=None):
  167. return self._test_params.get(key, default)
  168. def get_param_dict_copy(self):
  169. return dict(self._test_params)
  170. def get_context(self, key):
  171. return self._context.get(key)
  172. def _detect_source_root(self):
  173. root = None
  174. try:
  175. import library.python.find_root
  176. # try to determine source root from cwd
  177. cwd = os.getcwd()
  178. root = library.python.find_root.detect_root(cwd)
  179. if not root:
  180. # try to determine root pretending we are in the test work dir made from --keep-temps run
  181. env_subdir = os.path.join("environment", "arcadia")
  182. root = library.python.find_root.detect_root(cwd, detector=lambda p: os.path.exists(os.path.join(p, env_subdir)))
  183. except ImportError:
  184. logging.warning("Unable to import library.python.find_root")
  185. return root
  186. def _detect_output_root(self):
  187. # if run from kept test working dir
  188. if os.path.exists(TESTING_OUT_DIR_NAME):
  189. return TESTING_OUT_DIR_NAME
  190. # if run from source dir
  191. if sys.version_info.major == 3:
  192. test_results_dir = "py3test"
  193. else:
  194. test_results_dir = "pytest"
  195. test_results_output_path = os.path.join("test-results", test_results_dir, TESTING_OUT_DIR_NAME)
  196. if os.path.exists(test_results_output_path):
  197. return test_results_output_path
  198. if os.path.exists(os.path.dirname(test_results_output_path)):
  199. os.mkdir(test_results_output_path)
  200. return test_results_output_path
  201. return None
  202. def set_test_item_node_id(self, node_id):
  203. self._test_item_node_id = node_id
  204. def get_test_item_node_id(self):
  205. assert self._test_item_node_id
  206. return self._test_item_node_id
  207. def set_metric_value(self, name, val):
  208. from library.python.pytest.plugins.metrics import test_metrics
  209. node_id = self.get_test_item_node_id()
  210. if node_id not in test_metrics.metrics:
  211. test_metrics[node_id] = {}
  212. test_metrics[node_id][name] = val
  213. def get_metric_value(self, name, default=None):
  214. from library.python.pytest.plugins.metrics import test_metrics
  215. res = test_metrics.get(self.get_test_item_node_id(), {}).get(name)
  216. if res is None:
  217. return default
  218. return res