ytest.py 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118
  1. import os
  2. import re
  3. import sys
  4. import json
  5. import copy
  6. import base64
  7. import shlex
  8. import _common
  9. import lib._metric_resolvers as mr
  10. import _test_const as consts
  11. import _requirements as reqs
  12. import StringIO
  13. import subprocess
  14. import collections
  15. import ymake
  16. MDS_URI_PREFIX = 'https://storage.yandex-team.ru/get-devtools/'
  17. MDS_SCHEME = 'mds'
  18. CANON_DATA_DIR_NAME = 'canondata'
  19. CANON_OUTPUT_STORAGE = 'canondata_storage'
  20. CANON_RESULT_FILE_NAME = 'result.json'
  21. CANON_MDS_RESOURCE_REGEX = re.compile(re.escape(MDS_URI_PREFIX) + r'(.*?)($|#)')
  22. CANON_SB_VAULT_REGEX = re.compile(r"\w+=(value|file):[-\w]+:\w+")
  23. CANON_SBR_RESOURCE_REGEX = re.compile(r'(sbr:/?/?(\d+))')
  24. VALID_NETWORK_REQUIREMENTS = ("full", "restricted")
  25. VALID_DNS_REQUIREMENTS = ("default", "local", "dns64")
  26. BLOCK_SEPARATOR = '============================================================='
  27. SPLIT_FACTOR_MAX_VALUE = 1000
  28. SPLIT_FACTOR_TEST_FILES_MAX_VALUE = 4250
  29. PARTITION_MODS = ('SEQUENTIAL', 'MODULO')
  30. DEFAULT_TIDY_CONFIG = "build/config/tests/clang_tidy/config.yaml"
  31. DEFAULT_TIDY_CONFIG_MAP_PATH = "build/yandex_specific/config/clang_tidy/tidy_default_map.json"
  32. PROJECT_TIDY_CONFIG_MAP_PATH = "build/yandex_specific/config/clang_tidy/tidy_project_map.json"
  33. tidy_config_map = None
  34. def ontest_data(unit, *args):
  35. ymake.report_configure_error("TEST_DATA is removed in favour of DATA")
  36. def save_in_file(filepath, data):
  37. if filepath:
  38. with open(filepath, 'a') as file_handler:
  39. if os.stat(filepath).st_size == 0:
  40. print >>file_handler, BLOCK_SEPARATOR
  41. print >> file_handler, data
  42. def prepare_recipes(data):
  43. data = data.replace('"USE_RECIPE_DELIM"', "\n")
  44. data = data.replace("$TEST_RECIPES_VALUE", "")
  45. return base64.b64encode(data or "")
  46. def prepare_env(data):
  47. data = data.replace("$TEST_ENV_VALUE", "")
  48. return serialize_list(shlex.split(data))
  49. def is_yt_spec_contain_pool_info(filename): # XXX switch to yson in ymake + perf test for configure
  50. pool_re = re.compile(r"""['"]*pool['"]*\s*?=""")
  51. cypress_root_re = re.compile(r"""['"]*cypress_root['"]*\s*=""")
  52. with open(filename, 'r') as afile:
  53. yt_spec = afile.read()
  54. return pool_re.search(yt_spec) and cypress_root_re.search(yt_spec)
  55. def validate_sb_vault(name, value):
  56. if not CANON_SB_VAULT_REGEX.match(value):
  57. return "sb_vault value '{}' should follow pattern <ENV_NAME>=:<value|file>:<owner>:<vault key>".format(value)
  58. def validate_numerical_requirement(name, value):
  59. if mr.resolve_value(value) is None:
  60. return "Cannot convert [[imp]]{}[[rst]] to the proper [[imp]]{}[[rst]] requirement value".format(value, name)
  61. def validate_choice_requirement(name, val, valid):
  62. if val not in valid:
  63. return "Unknown [[imp]]{}[[rst]] requirement: [[imp]]{}[[rst]], choose from [[imp]]{}[[rst]]".format(name, val, ", ".join(valid))
  64. def validate_force_sandbox_requirement(name, value, test_size, is_force_sandbox, in_autocheck, is_fuzzing, is_kvm, is_ytexec_run, check_func):
  65. if is_force_sandbox or not in_autocheck or is_fuzzing or is_ytexec_run:
  66. if value == 'all':
  67. return
  68. return validate_numerical_requirement(name, value)
  69. error_msg = validate_numerical_requirement(name, value)
  70. if error_msg:
  71. return error_msg
  72. return check_func(mr.resolve_value(value), test_size, is_kvm)
  73. # TODO: Remove is_kvm param when there will be guarantees on RAM
  74. def validate_requirement(req_name, value, test_size, is_force_sandbox, in_autocheck, is_fuzzing, is_kvm, is_ytexec_run):
  75. req_checks = {
  76. 'container': validate_numerical_requirement,
  77. 'cpu': lambda n, v: validate_force_sandbox_requirement(n, v, test_size, is_force_sandbox, in_autocheck, is_fuzzing, is_kvm, is_ytexec_run, reqs.check_cpu),
  78. 'disk_usage': validate_numerical_requirement,
  79. 'dns': lambda n, v: validate_choice_requirement(n, v, VALID_DNS_REQUIREMENTS),
  80. 'kvm': None,
  81. 'network': lambda n, v: validate_choice_requirement(n, v, VALID_NETWORK_REQUIREMENTS),
  82. 'ram': lambda n, v: validate_force_sandbox_requirement(n, v, test_size, is_force_sandbox, in_autocheck, is_fuzzing, is_kvm, is_ytexec_run, reqs.check_ram),
  83. 'ram_disk': lambda n, v: validate_force_sandbox_requirement(n, v, test_size, is_force_sandbox, in_autocheck, is_fuzzing, is_kvm, is_ytexec_run, reqs.check_ram_disk),
  84. 'sb': None,
  85. 'sb_vault': validate_sb_vault,
  86. }
  87. if req_name not in req_checks:
  88. return "Unknown requirement: [[imp]]{}[[rst]], choose from [[imp]]{}[[rst]]".format(req_name, ", ".join(sorted(req_checks)))
  89. if req_name in ('container', 'disk') and not is_force_sandbox:
  90. return "Only [[imp]]LARGE[[rst]] tests without [[imp]]ya:force_distbuild[[rst]] tag can have [[imp]]{}[[rst]] requirement".format(req_name)
  91. check_func = req_checks[req_name]
  92. if check_func:
  93. return check_func(req_name, value)
  94. def validate_test(unit, kw):
  95. def get_list(key):
  96. return deserialize_list(kw.get(key, ""))
  97. valid_kw = copy.deepcopy(kw)
  98. errors = []
  99. warnings = []
  100. if valid_kw.get('SCRIPT-REL-PATH') == 'boost.test':
  101. project_path = valid_kw.get('BUILD-FOLDER-PATH', "")
  102. if not project_path.startswith(("contrib", "mail", "maps", "tools/idl", "metrika", "devtools", "mds", "yandex_io", "smart_devices")):
  103. errors.append("BOOSTTEST is not allowed here")
  104. elif valid_kw.get('SCRIPT-REL-PATH') == 'gtest':
  105. project_path = valid_kw.get('BUILD-FOLDER-PATH', "")
  106. if not project_path.startswith(("contrib", "devtools", "mail", "mds", "taxi")):
  107. errors.append("GTEST_UGLY is not allowed here, use GTEST instead")
  108. size_timeout = collections.OrderedDict(sorted(consts.TestSize.DefaultTimeouts.items(), key=lambda t: t[1]))
  109. size = valid_kw.get('SIZE', consts.TestSize.Small).lower()
  110. # TODO: use set instead list
  111. tags = get_list("TAG")
  112. requirements_orig = get_list("REQUIREMENTS")
  113. in_autocheck = "ya:not_autocheck" not in tags and 'ya:manual' not in tags
  114. is_fat = 'ya:fat' in tags
  115. is_force_sandbox = 'ya:force_distbuild' not in tags and is_fat
  116. is_ytexec_run = 'ya:yt' in tags
  117. is_fuzzing = valid_kw.get("FUZZING", False)
  118. is_kvm = 'kvm' in requirements_orig
  119. requirements = {}
  120. list_requirements = ('sb_vault')
  121. for req in requirements_orig:
  122. if req in ('kvm', ):
  123. requirements[req] = str(True)
  124. continue
  125. if ":" in req:
  126. req_name, req_value = req.split(":", 1)
  127. if req_name in list_requirements:
  128. requirements[req_name] = ",".join(filter(None, [requirements.get(req_name), req_value]))
  129. else:
  130. if req_name in requirements:
  131. if req_value in ["0"]:
  132. warnings.append("Requirement [[imp]]{}[[rst]] is dropped [[imp]]{}[[rst]] -> [[imp]]{}[[rst]]".format(req_name, requirements[req_name], req_value))
  133. del requirements[req_name]
  134. elif requirements[req_name] != req_value:
  135. warnings.append("Requirement [[imp]]{}[[rst]] is redefined [[imp]]{}[[rst]] -> [[imp]]{}[[rst]]".format(req_name, requirements[req_name], req_value))
  136. requirements[req_name] = req_value
  137. else:
  138. requirements[req_name] = req_value
  139. else:
  140. errors.append("Invalid requirement syntax [[imp]]{}[[rst]]: expect <requirement>:<value>".format(req))
  141. if not errors:
  142. for req_name, req_value in requirements.items():
  143. error_msg = validate_requirement(req_name, req_value, size, is_force_sandbox, in_autocheck, is_fuzzing, is_kvm, is_ytexec_run)
  144. if error_msg:
  145. errors += [error_msg]
  146. invalid_requirements_for_distbuild = [requirement for requirement in requirements.keys() if requirement not in ('ram', 'ram_disk', 'cpu', 'network')]
  147. sb_tags = [tag for tag in tags if tag.startswith('sb:')]
  148. if is_fat:
  149. if size != consts.TestSize.Large:
  150. errors.append("Only LARGE test may have ya:fat tag")
  151. if in_autocheck and not is_force_sandbox:
  152. if invalid_requirements_for_distbuild:
  153. errors.append("'{}' REQUIREMENTS options can be used only for FAT tests without ya:force_distbuild tag. Remove TAG(ya:force_distbuild) or an option.".format(invalid_requirements_for_distbuild))
  154. if sb_tags:
  155. errors.append("You can set sandbox tags '{}' only for FAT tests without ya:force_distbuild. Remove TAG(ya:force_sandbox) or sandbox tags.".format(sb_tags))
  156. if 'ya:sandbox_coverage' in tags:
  157. errors.append("You can set 'ya:sandbox_coverage' tag only for FAT tests without ya:force_distbuild.")
  158. if is_ytexec_run:
  159. errors.append("Running LARGE tests over YT (ya:yt) on Distbuild (ya:force_distbuild) is forbidden. Consider removing TAG(ya:force_distbuild).")
  160. else:
  161. if is_force_sandbox:
  162. errors.append('ya:force_sandbox can be used with LARGE tests only')
  163. if 'ya:nofuse' in tags:
  164. errors.append('ya:nofuse can be used with LARGE tests only')
  165. if 'ya:privileged' in tags:
  166. errors.append("ya:privileged can be used with LARGE tests only")
  167. if in_autocheck and size == consts.TestSize.Large:
  168. errors.append("LARGE test must have ya:fat tag")
  169. if 'ya:privileged' in tags and 'container' not in requirements:
  170. errors.append("Only tests with 'container' requirement can have 'ya:privileged' tag")
  171. if size not in size_timeout:
  172. errors.append("Unknown test size: [[imp]]{}[[rst]], choose from [[imp]]{}[[rst]]".format(size.upper(), ", ".join([sz.upper() for sz in size_timeout.keys()])))
  173. else:
  174. try:
  175. timeout = int(valid_kw.get('TEST-TIMEOUT', size_timeout[size]) or size_timeout[size])
  176. script_rel_path = valid_kw.get('SCRIPT-REL-PATH')
  177. if timeout < 0:
  178. raise Exception("Timeout must be > 0")
  179. if size_timeout[size] < timeout and in_autocheck and script_rel_path != 'java.style':
  180. suggested_size = None
  181. for s, t in size_timeout.items():
  182. if timeout <= t:
  183. suggested_size = s
  184. break
  185. if suggested_size:
  186. suggested_size = ", suggested size: [[imp]]{}[[rst]]".format(suggested_size.upper())
  187. else:
  188. suggested_size = ""
  189. errors.append("Max allowed timeout for test size [[imp]]{}[[rst]] is [[imp]]{} sec[[rst]]{}".format(size.upper(), size_timeout[size], suggested_size))
  190. except Exception as e:
  191. errors.append("Error when parsing test timeout: [[bad]]{}[[rst]]".format(e))
  192. requirements_list = []
  193. for req_name, req_value in requirements.iteritems():
  194. requirements_list.append(req_name + ":" + req_value)
  195. valid_kw['REQUIREMENTS'] = serialize_list(requirements_list)
  196. if valid_kw.get("FUZZ-OPTS"):
  197. for option in get_list("FUZZ-OPTS"):
  198. if not option.startswith("-"):
  199. errors.append("Unrecognized fuzzer option '[[imp]]{}[[rst]]'. All fuzzer options should start with '-'".format(option))
  200. break
  201. eqpos = option.find("=")
  202. if eqpos == -1 or len(option) == eqpos + 1:
  203. errors.append("Unrecognized fuzzer option '[[imp]]{}[[rst]]'. All fuzzer options should obtain value specified after '='".format(option))
  204. break
  205. if option[eqpos - 1] == " " or option[eqpos + 1] == " ":
  206. errors.append("Spaces are not allowed: '[[imp]]{}[[rst]]'".format(option))
  207. break
  208. if option[:eqpos] in ("-runs", "-dict", "-jobs", "-workers", "-artifact_prefix", "-print_final_stats"):
  209. errors.append("You can't use '[[imp]]{}[[rst]]' - it will be automatically calculated or configured during run".format(option))
  210. break
  211. if valid_kw.get("YT-SPEC"):
  212. if not is_ytexec_run:
  213. errors.append("You can use YT_SPEC macro only tests marked with ya:yt tag")
  214. else:
  215. for filename in get_list("YT-SPEC"):
  216. filename = unit.resolve('$S/' + filename)
  217. if not os.path.exists(filename):
  218. errors.append("File '{}' specified in the YT_SPEC macro doesn't exist".format(filename))
  219. continue
  220. if is_yt_spec_contain_pool_info(filename) and "ya:external" not in tags:
  221. tags.append("ya:external")
  222. tags.append("ya:yt_research_pool")
  223. if valid_kw.get("USE_ARCADIA_PYTHON") == "yes" and valid_kw.get("SCRIPT-REL-PATH") == "py.test":
  224. errors.append("PYTEST_SCRIPT is deprecated")
  225. partition = valid_kw.get('TEST_PARTITION', 'SEQUENTIAL')
  226. if partition not in PARTITION_MODS:
  227. raise ValueError('partition mode should be one of {}, detected: {}'.format(PARTITION_MODS, partition))
  228. if valid_kw.get('SPLIT-FACTOR'):
  229. if valid_kw.get('FORK-MODE') == 'none':
  230. errors.append('SPLIT_FACTOR must be use with FORK_TESTS() or FORK_SUBTESTS() macro')
  231. value = 1
  232. try:
  233. value = int(valid_kw.get('SPLIT-FACTOR'))
  234. if value <= 0:
  235. raise ValueError("must be > 0")
  236. if value > SPLIT_FACTOR_MAX_VALUE:
  237. raise ValueError("the maximum allowed value is {}".format(SPLIT_FACTOR_MAX_VALUE))
  238. except ValueError as e:
  239. errors.append('Incorrect SPLIT_FACTOR value: {}'.format(e))
  240. if valid_kw.get('FORK-TEST-FILES') and size != consts.TestSize.Large:
  241. nfiles = count_entries(valid_kw.get('TEST-FILES'))
  242. if nfiles * value > SPLIT_FACTOR_TEST_FILES_MAX_VALUE:
  243. errors.append('Too much chunks generated:{} (limit: {}). Remove FORK_TEST_FILES() macro or reduce SPLIT_FACTOR({}).'.format(
  244. nfiles * value, SPLIT_FACTOR_TEST_FILES_MAX_VALUE, value))
  245. unit_path = get_norm_unit_path(unit)
  246. if not is_fat and "ya:noretries" in tags and not is_ytexec_run \
  247. and not unit_path.startswith("devtools/dummy_arcadia/test/noretries"):
  248. errors.append("Only LARGE tests can have 'ya:noretries' tag")
  249. if errors:
  250. return None, warnings, errors
  251. return valid_kw, warnings, errors
  252. def get_norm_unit_path(unit, extra=None):
  253. path = _common.strip_roots(unit.path())
  254. if extra:
  255. return '{}/{}'.format(path, extra)
  256. return path
  257. def dump_test(unit, kw):
  258. valid_kw, warnings, errors = validate_test(unit, kw)
  259. for w in warnings:
  260. unit.message(['warn', w])
  261. for e in errors:
  262. ymake.report_configure_error(e)
  263. if valid_kw is None:
  264. return None
  265. string_handler = StringIO.StringIO()
  266. for k, v in valid_kw.iteritems():
  267. print >>string_handler, k + ': ' + v
  268. print >>string_handler, BLOCK_SEPARATOR
  269. data = string_handler.getvalue()
  270. string_handler.close()
  271. return data
  272. def serialize_list(lst):
  273. lst = filter(None, lst)
  274. return '\"' + ';'.join(lst) + '\"' if lst else ''
  275. def deserialize_list(val):
  276. return filter(None, val.replace('"', "").split(";"))
  277. def count_entries(x):
  278. # see (de)serialize_list
  279. assert x is None or isinstance(x, str), type(x)
  280. if not x:
  281. return 0
  282. return x.count(";") + 1
  283. def get_values_list(unit, key):
  284. res = map(str.strip, (unit.get(key) or '').replace('$' + key, '').strip().split())
  285. return [r for r in res if r and r not in ['""', "''"]]
  286. def get_norm_paths(unit, key):
  287. # return paths without trailing (back)slash
  288. return [x.rstrip('\\/') for x in get_values_list(unit, key)]
  289. def get_unit_list_variable(unit, name):
  290. items = unit.get(name)
  291. if items:
  292. items = items.split(' ')
  293. assert items[0] == "${}".format(name), (items, name)
  294. return items[1:]
  295. return []
  296. def implies(a, b):
  297. return bool((not a) or b)
  298. def match_coverage_extractor_requirements(unit):
  299. # we shouldn't add test if
  300. return all([
  301. # tests are not requested
  302. unit.get("TESTS_REQUESTED") == "yes",
  303. # build doesn't imply clang coverage, which supports segment extraction from the binaries
  304. unit.get("CLANG_COVERAGE") == "yes",
  305. # contrib wasn't requested
  306. implies(get_norm_unit_path(unit).startswith("contrib/"), unit.get("ENABLE_CONTRIB_COVERAGE") == "yes"),
  307. ])
  308. def get_tidy_config_map(unit, map_path):
  309. config_map_path = unit.resolve(os.path.join("$S", map_path))
  310. config_map = {}
  311. try:
  312. with open(config_map_path, 'r') as afile:
  313. config_map = json.load(afile)
  314. except ValueError:
  315. ymake.report_configure_error("{} is invalid json".format(map_path))
  316. except Exception as e:
  317. ymake.report_configure_error(str(e))
  318. return config_map
  319. def get_default_tidy_config(unit):
  320. unit_path = get_norm_unit_path(unit)
  321. tidy_default_config_map = get_tidy_config_map(unit, DEFAULT_TIDY_CONFIG_MAP_PATH)
  322. for project_prefix, config_path in tidy_default_config_map.items():
  323. if unit_path.startswith(project_prefix):
  324. return config_path
  325. return DEFAULT_TIDY_CONFIG
  326. def get_project_tidy_config(unit):
  327. tidy_map = get_tidy_config_map(unit, PROJECT_TIDY_CONFIG_MAP_PATH)
  328. unit_path = get_norm_unit_path(unit)
  329. for project_prefix, config_path in tidy_map.items():
  330. if unit_path.startswith(project_prefix):
  331. return config_path
  332. else:
  333. return get_default_tidy_config(unit)
  334. def onadd_ytest(unit, *args):
  335. keywords = {"DEPENDS": -1, "DATA": -1, "TIMEOUT": 1, "FORK_MODE": 1, "SPLIT_FACTOR": 1,
  336. "FORK_SUBTESTS": 0, "FORK_TESTS": 0}
  337. flat_args, spec_args = _common.sort_by_keywords(keywords, args)
  338. test_data = sorted(_common.filter_out_by_keyword(spec_args.get('DATA', []) + get_norm_paths(unit, 'TEST_DATA_VALUE'), 'AUTOUPDATED'))
  339. if flat_args[1] == "fuzz.test":
  340. unit.ondata("arcadia/fuzzing/{}/corpus.json".format(get_norm_unit_path(unit)))
  341. elif flat_args[1] == "go.test":
  342. data, _ = get_canonical_test_resources(unit)
  343. test_data += data
  344. elif flat_args[1] == "coverage.extractor" and not match_coverage_extractor_requirements(unit):
  345. # XXX
  346. # Current ymake implementation doesn't allow to call macro inside the 'when' body
  347. # that's why we add ADD_YTEST(coverage.extractor) to every PROGRAM entry and check requirements later
  348. return
  349. elif flat_args[1] == "clang_tidy" and unit.get("TIDY") != "yes":
  350. # Graph is not prepared
  351. return
  352. elif flat_args[1] == "no.test":
  353. return
  354. test_size = ''.join(spec_args.get('SIZE', [])) or unit.get('TEST_SIZE_NAME') or ''
  355. test_tags = serialize_list(_get_test_tags(unit, spec_args))
  356. test_timeout = ''.join(spec_args.get('TIMEOUT', [])) or unit.get('TEST_TIMEOUT') or ''
  357. test_requirements = spec_args.get('REQUIREMENTS', []) + get_values_list(unit, 'TEST_REQUIREMENTS_VALUE')
  358. if flat_args[1] != "clang_tidy" and unit.get("TIDY") == "yes":
  359. # graph changed for clang_tidy tests
  360. if flat_args[1] in ("unittest.py", "gunittest", "g_benchmark"):
  361. flat_args[1] = "clang_tidy"
  362. test_size = 'SMALL'
  363. test_tags = ''
  364. test_timeout = "60"
  365. test_requirements = []
  366. unit.set(["TEST_YT_SPEC_VALUE", ""])
  367. else:
  368. return
  369. if flat_args[1] == "clang_tidy" and unit.get("TIDY") == "yes":
  370. if unit.get("TIDY_CONFIG"):
  371. default_config_path = unit.get("TIDY_CONFIG")
  372. project_config_path = unit.get("TIDY_CONFIG")
  373. else:
  374. default_config_path = get_default_tidy_config(unit)
  375. project_config_path = get_project_tidy_config(unit)
  376. unit.set(["DEFAULT_TIDY_CONFIG", default_config_path])
  377. unit.set(["PROJECT_TIDY_CONFIG", project_config_path])
  378. fork_mode = []
  379. if 'FORK_SUBTESTS' in spec_args:
  380. fork_mode.append('subtests')
  381. if 'FORK_TESTS' in spec_args:
  382. fork_mode.append('tests')
  383. fork_mode = fork_mode or spec_args.get('FORK_MODE', []) or unit.get('TEST_FORK_MODE').split()
  384. fork_mode = ' '.join(fork_mode) if fork_mode else ''
  385. unit_path = get_norm_unit_path(unit)
  386. test_record = {
  387. 'TEST-NAME': flat_args[0],
  388. 'SCRIPT-REL-PATH': flat_args[1],
  389. 'TESTED-PROJECT-NAME': unit.name(),
  390. 'TESTED-PROJECT-FILENAME': unit.filename(),
  391. 'SOURCE-FOLDER-PATH': unit_path,
  392. # TODO get rid of BUILD-FOLDER-PATH
  393. 'BUILD-FOLDER-PATH': unit_path,
  394. 'BINARY-PATH': "{}/{}".format(unit_path, unit.filename()),
  395. 'GLOBAL-LIBRARY-PATH': unit.global_filename(),
  396. 'CUSTOM-DEPENDENCIES': ' '.join(spec_args.get('DEPENDS', []) + get_values_list(unit, 'TEST_DEPENDS_VALUE')),
  397. 'TEST-RECIPES': prepare_recipes(unit.get("TEST_RECIPES_VALUE")),
  398. 'TEST-ENV': prepare_env(unit.get("TEST_ENV_VALUE")),
  399. # 'TEST-PRESERVE-ENV': 'da',
  400. 'TEST-DATA': serialize_list(test_data),
  401. 'TEST-TIMEOUT': test_timeout,
  402. 'FORK-MODE': fork_mode,
  403. 'SPLIT-FACTOR': ''.join(spec_args.get('SPLIT_FACTOR', [])) or unit.get('TEST_SPLIT_FACTOR') or '',
  404. 'SIZE': test_size,
  405. 'TAG': test_tags,
  406. 'REQUIREMENTS': serialize_list(test_requirements),
  407. 'TEST-CWD': unit.get('TEST_CWD_VALUE') or '',
  408. 'FUZZ-DICTS': serialize_list(spec_args.get('FUZZ_DICTS', []) + get_unit_list_variable(unit, 'FUZZ_DICTS_VALUE')),
  409. 'FUZZ-OPTS': serialize_list(spec_args.get('FUZZ_OPTS', []) + get_unit_list_variable(unit, 'FUZZ_OPTS_VALUE')),
  410. 'YT-SPEC': serialize_list(spec_args.get('YT_SPEC', []) + get_unit_list_variable(unit, 'TEST_YT_SPEC_VALUE')),
  411. 'BLOB': unit.get('TEST_BLOB_DATA') or '',
  412. 'SKIP_TEST': unit.get('SKIP_TEST_VALUE') or '',
  413. 'TEST_IOS_DEVICE_TYPE': unit.get('TEST_IOS_DEVICE_TYPE_VALUE') or '',
  414. 'TEST_IOS_RUNTIME_TYPE': unit.get('TEST_IOS_RUNTIME_TYPE_VALUE') or '',
  415. 'ANDROID_APK_TEST_ACTIVITY': unit.get('ANDROID_APK_TEST_ACTIVITY_VALUE') or '',
  416. 'TEST_PARTITION': unit.get("TEST_PARTITION") or 'SEQUENTIAL',
  417. 'GO_BENCH_TIMEOUT': unit.get('GO_BENCH_TIMEOUT') or '',
  418. }
  419. if flat_args[1] == "go.bench":
  420. if "ya:run_go_benchmark" not in test_record["TAG"]:
  421. return
  422. else:
  423. test_record["TEST-NAME"] += "_bench"
  424. if flat_args[1] == 'fuzz.test' and unit.get('FUZZING') == 'yes':
  425. test_record['FUZZING'] = '1'
  426. # use all cores if fuzzing requested
  427. test_record['REQUIREMENTS'] = serialize_list(filter(None, deserialize_list(test_record['REQUIREMENTS']) + ["cpu:all", "ram:all"]))
  428. data = dump_test(unit, test_record)
  429. if data:
  430. unit.set_property(["DART_DATA", data])
  431. save_in_file(unit.get('TEST_DART_OUT_FILE'), data)
  432. def java_srcdirs_to_data(unit, var):
  433. extra_data = []
  434. for srcdir in (unit.get(var) or '').replace('$' + var, '').split():
  435. if srcdir == '.':
  436. srcdir = unit.get('MODDIR')
  437. if srcdir.startswith('${ARCADIA_ROOT}/') or srcdir.startswith('$ARCADIA_ROOT/'):
  438. srcdir = srcdir.replace('${ARCADIA_ROOT}/', '$S/')
  439. srcdir = srcdir.replace('$ARCADIA_ROOT/', '$S/')
  440. if srcdir.startswith('${CURDIR}/') or srcdir.startswith('$CURDIR/'):
  441. srcdir = srcdir.replace('${CURDIR}/', os.path.join('$S', unit.get('MODDIR')))
  442. srcdir = srcdir.replace('$CURDIR/', os.path.join('$S', unit.get('MODDIR')))
  443. srcdir = unit.resolve_arc_path(srcdir)
  444. if not srcdir.startswith('$'):
  445. srcdir = os.path.join('$S', unit.get('MODDIR'), srcdir)
  446. if srcdir.startswith('$S'):
  447. extra_data.append(srcdir.replace('$S', 'arcadia'))
  448. return serialize_list(extra_data)
  449. def onadd_check(unit, *args):
  450. if unit.get("TIDY") == "yes":
  451. # graph changed for clang_tidy tests
  452. return
  453. flat_args, spec_args = _common.sort_by_keywords({"DEPENDS": -1, "TIMEOUT": 1, "DATA": -1, "TAG": -1,
  454. "REQUIREMENTS": -1, "FORK_MODE": 1, "SPLIT_FACTOR": 1,
  455. "FORK_SUBTESTS": 0, "FORK_TESTS": 0, "SIZE": 1}, args)
  456. check_type = flat_args[0]
  457. test_dir = get_norm_unit_path(unit)
  458. test_timeout = ''
  459. fork_mode = ''
  460. extra_test_data = ''
  461. extra_test_dart_data = {}
  462. ymake_java_test = unit.get('YMAKE_JAVA_TEST') == 'yes'
  463. if check_type in ["flake8.py2", "flake8.py3"]:
  464. script_rel_path = check_type
  465. fork_mode = unit.get('TEST_FORK_MODE') or ''
  466. elif check_type == "black":
  467. script_rel_path = check_type
  468. fork_mode = unit.get('TEST_FORK_MODE') or ''
  469. elif check_type == "JAVA_STYLE":
  470. if ymake_java_test and not unit.get('ALL_SRCDIRS') or '':
  471. return
  472. if len(flat_args) < 2:
  473. raise Exception("Not enough arguments for JAVA_STYLE check")
  474. check_level = flat_args[1]
  475. allowed_levels = {
  476. 'base': '/yandex_checks.xml',
  477. 'strict': '/yandex_checks_strict.xml',
  478. 'extended': '/yandex_checks_extended.xml',
  479. 'library': '/yandex_checks_library.xml',
  480. }
  481. if check_level not in allowed_levels:
  482. raise Exception('{} is not allowed in LINT(), use one of {}'.format(check_level, allowed_levels.keys()))
  483. flat_args[1] = allowed_levels[check_level]
  484. if check_level == 'none':
  485. return
  486. script_rel_path = "java.style"
  487. test_timeout = '120'
  488. fork_mode = unit.get('TEST_FORK_MODE') or ''
  489. if ymake_java_test:
  490. extra_test_data = java_srcdirs_to_data(unit, 'ALL_SRCDIRS')
  491. extra_test_dart_data['JDK_RESOURCE'] = 'JDK' + (unit.get('JDK_VERSION') or unit.get('JDK_REAL_VERSION') or '_DEFAULT')
  492. elif check_type == "gofmt":
  493. script_rel_path = check_type
  494. go_files = flat_args[1:]
  495. if go_files:
  496. test_dir = os.path.dirname(go_files[0]).lstrip("$S/")
  497. else:
  498. script_rel_path = check_type
  499. use_arcadia_python = unit.get('USE_ARCADIA_PYTHON')
  500. uid_ext = ''
  501. if check_type in ("check.data", "check.resource"):
  502. if unit.get("VALIDATE_DATA") == "no":
  503. return
  504. if check_type == "check.data":
  505. uid_ext = unit.get("SBR_UID_EXT").split(" ", 1)[-1] # strip variable name
  506. data_re = re.compile(r"sbr:/?/?(\d+)=?.*")
  507. data = flat_args[1:]
  508. resources = []
  509. for f in data:
  510. matched = re.match(data_re, f)
  511. if matched:
  512. resources.append(matched.group(1))
  513. if resources:
  514. test_files = serialize_list(resources)
  515. else:
  516. return
  517. else:
  518. test_files = serialize_list(flat_args[1:])
  519. test_record = {
  520. 'TEST-NAME': check_type.lower(),
  521. 'TEST-TIMEOUT': test_timeout,
  522. 'SCRIPT-REL-PATH': script_rel_path,
  523. 'TESTED-PROJECT-NAME': os.path.basename(test_dir),
  524. 'SOURCE-FOLDER-PATH': test_dir,
  525. 'CUSTOM-DEPENDENCIES': " ".join(spec_args.get('DEPENDS', [])),
  526. 'TEST-DATA': extra_test_data,
  527. 'SBR-UID-EXT': uid_ext,
  528. 'SPLIT-FACTOR': '',
  529. 'TEST_PARTITION': 'SEQUENTIAL',
  530. 'FORK-MODE': fork_mode,
  531. 'FORK-TEST-FILES': '',
  532. 'SIZE': 'SMALL',
  533. 'TAG': '',
  534. 'REQUIREMENTS': '',
  535. 'USE_ARCADIA_PYTHON': use_arcadia_python or '',
  536. 'OLD_PYTEST': 'no',
  537. 'PYTHON-PATHS': '',
  538. # TODO remove FILES, see DEVTOOLS-7052
  539. 'FILES': test_files,
  540. 'TEST-FILES': test_files,
  541. 'NO_JBUILD': 'yes' if ymake_java_test else 'no',
  542. }
  543. test_record.update(extra_test_dart_data)
  544. data = dump_test(unit, test_record)
  545. if data:
  546. unit.set_property(["DART_DATA", data])
  547. save_in_file(unit.get('TEST_DART_OUT_FILE'), data)
  548. def on_register_no_check_imports(unit):
  549. s = unit.get('NO_CHECK_IMPORTS_FOR_VALUE')
  550. if s not in ('', 'None'):
  551. unit.onresource(['-', 'py/no_check_imports/{}="{}"'.format(_common.pathid(s), s)])
  552. def onadd_check_py_imports(unit, *args):
  553. if unit.get("TIDY") == "yes":
  554. # graph changed for clang_tidy tests
  555. return
  556. if unit.get('NO_CHECK_IMPORTS_FOR_VALUE').strip() == "":
  557. return
  558. unit.onpeerdir(['library/python/testing/import_test'])
  559. check_type = "py.imports"
  560. test_dir = get_norm_unit_path(unit)
  561. use_arcadia_python = unit.get('USE_ARCADIA_PYTHON')
  562. test_files = serialize_list([get_norm_unit_path(unit, unit.filename())])
  563. test_record = {
  564. 'TEST-NAME': "pyimports",
  565. 'TEST-TIMEOUT': '',
  566. 'SCRIPT-REL-PATH': check_type,
  567. 'TESTED-PROJECT-NAME': os.path.basename(test_dir),
  568. 'SOURCE-FOLDER-PATH': test_dir,
  569. 'CUSTOM-DEPENDENCIES': '',
  570. 'TEST-DATA': '',
  571. 'TEST-ENV': prepare_env(unit.get("TEST_ENV_VALUE")),
  572. 'SPLIT-FACTOR': '',
  573. 'TEST_PARTITION': 'SEQUENTIAL',
  574. 'FORK-MODE': '',
  575. 'FORK-TEST-FILES': '',
  576. 'SIZE': 'SMALL',
  577. 'TAG': '',
  578. 'USE_ARCADIA_PYTHON': use_arcadia_python or '',
  579. 'OLD_PYTEST': 'no',
  580. 'PYTHON-PATHS': '',
  581. # TODO remove FILES, see DEVTOOLS-7052
  582. 'FILES': test_files,
  583. 'TEST-FILES': test_files,
  584. }
  585. if unit.get('NO_CHECK_IMPORTS_FOR_VALUE') != "None":
  586. test_record["NO-CHECK"] = serialize_list(get_values_list(unit, 'NO_CHECK_IMPORTS_FOR_VALUE') or ["*"])
  587. else:
  588. test_record["NO-CHECK"] = ''
  589. data = dump_test(unit, test_record)
  590. if data:
  591. unit.set_property(["DART_DATA", data])
  592. save_in_file(unit.get('TEST_DART_OUT_FILE'), data)
  593. def onadd_pytest_script(unit, *args):
  594. if unit.get("TIDY") == "yes":
  595. # graph changed for clang_tidy tests
  596. return
  597. unit.set(["PYTEST_BIN", "no"])
  598. custom_deps = get_values_list(unit, 'TEST_DEPENDS_VALUE')
  599. timeout = filter(None, [unit.get(["TEST_TIMEOUT"])])
  600. if timeout:
  601. timeout = timeout[0]
  602. else:
  603. timeout = '0'
  604. test_type = args[0]
  605. fork_mode = unit.get('TEST_FORK_MODE').split() or ''
  606. split_factor = unit.get('TEST_SPLIT_FACTOR') or ''
  607. test_size = unit.get('TEST_SIZE_NAME') or ''
  608. test_files = get_values_list(unit, 'TEST_SRCS_VALUE')
  609. tags = _get_test_tags(unit)
  610. requirements = get_values_list(unit, 'TEST_REQUIREMENTS_VALUE')
  611. test_data = get_norm_paths(unit, 'TEST_DATA_VALUE')
  612. data, data_files = get_canonical_test_resources(unit)
  613. test_data += data
  614. python_paths = get_values_list(unit, 'TEST_PYTHON_PATH_VALUE')
  615. binary_path = None
  616. test_cwd = unit.get('TEST_CWD_VALUE') or ''
  617. _dump_test(unit, test_type, test_files, timeout, get_norm_unit_path(unit), custom_deps, test_data, python_paths, split_factor, fork_mode, test_size, tags, requirements, binary_path, test_cwd=test_cwd, data_files=data_files)
  618. def onadd_pytest_bin(unit, *args):
  619. if unit.get("TIDY") == "yes":
  620. # graph changed for clang_tidy tests
  621. return
  622. flat, kws = _common.sort_by_keywords({'RUNNER_BIN': 1}, args)
  623. if flat:
  624. ymake.report_configure_error(
  625. 'Unknown arguments found while processing add_pytest_bin macro: {!r}'
  626. .format(flat)
  627. )
  628. runner_bin = kws.get('RUNNER_BIN', [None])[0]
  629. test_type = 'py3test.bin' if (unit.get("PYTHON3") == 'yes') else "pytest.bin"
  630. add_test_to_dart(unit, test_type, runner_bin=runner_bin)
  631. def add_test_to_dart(unit, test_type, binary_path=None, runner_bin=None):
  632. if unit.get("TIDY") == "yes":
  633. # graph changed for clang_tidy tests
  634. return
  635. custom_deps = get_values_list(unit, 'TEST_DEPENDS_VALUE')
  636. timeout = filter(None, [unit.get(["TEST_TIMEOUT"])])
  637. if timeout:
  638. timeout = timeout[0]
  639. else:
  640. timeout = '0'
  641. fork_mode = unit.get('TEST_FORK_MODE').split() or ''
  642. split_factor = unit.get('TEST_SPLIT_FACTOR') or ''
  643. test_size = unit.get('TEST_SIZE_NAME') or ''
  644. test_cwd = unit.get('TEST_CWD_VALUE') or ''
  645. unit_path = unit.path()
  646. test_files = get_values_list(unit, 'TEST_SRCS_VALUE')
  647. tags = _get_test_tags(unit)
  648. requirements = get_values_list(unit, 'TEST_REQUIREMENTS_VALUE')
  649. test_data = get_norm_paths(unit, 'TEST_DATA_VALUE')
  650. data, data_files = get_canonical_test_resources(unit)
  651. test_data += data
  652. python_paths = get_values_list(unit, 'TEST_PYTHON_PATH_VALUE')
  653. yt_spec = get_values_list(unit, 'TEST_YT_SPEC_VALUE')
  654. if not binary_path:
  655. binary_path = os.path.join(unit_path, unit.filename())
  656. _dump_test(unit, test_type, test_files, timeout, get_norm_unit_path(unit), custom_deps, test_data, python_paths, split_factor, fork_mode, test_size, tags, requirements, binary_path, test_cwd=test_cwd, runner_bin=runner_bin, yt_spec=yt_spec, data_files=data_files)
  657. def extract_java_system_properties(unit, args):
  658. if len(args) % 2:
  659. return [], 'Wrong use of SYSTEM_PROPERTIES in {}: odd number of arguments'.format(unit.path())
  660. props = []
  661. for x, y in zip(args[::2], args[1::2]):
  662. if x == 'FILE':
  663. if y.startswith('${BINDIR}') or y.startswith('${ARCADIA_BUILD_ROOT}') or y.startswith('/'):
  664. return [], 'Wrong use of SYSTEM_PROPERTIES in {}: absolute/build file path {}'.format(unit.path(), y)
  665. y = _common.rootrel_arc_src(y, unit)
  666. if not os.path.exists(unit.resolve('$S/' + y)):
  667. return [], 'Wrong use of SYSTEM_PROPERTIES in {}: can\'t resolve {}'.format(unit.path(), y)
  668. y = '${ARCADIA_ROOT}/' + y
  669. props.append({'type': 'file', 'path': y})
  670. else:
  671. props.append({'type': 'inline', 'key': x, 'value': y})
  672. return props, None
  673. def onjava_test(unit, *args):
  674. if unit.get("TIDY") == "yes":
  675. # graph changed for clang_tidy tests
  676. return
  677. assert unit.get('MODULE_TYPE') is not None
  678. if unit.get('MODULE_TYPE') == 'JTEST_FOR':
  679. if not unit.get('UNITTEST_DIR'):
  680. ymake.report_configure_error('skip JTEST_FOR in {}: no args provided'.format(unit.path()))
  681. return
  682. java_cp_arg_type = unit.get('JAVA_CLASSPATH_CMD_TYPE_VALUE') or 'MANIFEST'
  683. if java_cp_arg_type not in ('MANIFEST', 'COMMAND_FILE', 'LIST'):
  684. ymake.report_configure_error('{}: TEST_JAVA_CLASSPATH_CMD_TYPE({}) are invalid. Choose argument from MANIFEST, COMMAND_FILE or LIST)'.format(unit.path(), java_cp_arg_type))
  685. return
  686. unit_path = unit.path()
  687. path = _common.strip_roots(unit_path)
  688. test_data = get_norm_paths(unit, 'TEST_DATA_VALUE')
  689. test_data.append('arcadia/build/scripts/run_junit.py')
  690. test_data.append('arcadia/build/scripts/unpacking_jtest_runner.py')
  691. data, data_files = get_canonical_test_resources(unit)
  692. test_data += data
  693. props, error_mgs = extract_java_system_properties(unit, get_values_list(unit, 'SYSTEM_PROPERTIES_VALUE'))
  694. if error_mgs:
  695. ymake.report_configure_error(error_mgs)
  696. return
  697. for prop in props:
  698. if prop['type'] == 'file':
  699. test_data.append(prop['path'].replace('${ARCADIA_ROOT}', 'arcadia'))
  700. props = base64.b64encode(json.dumps(props, encoding='utf-8'))
  701. test_cwd = unit.get('TEST_CWD_VALUE') or '' # TODO: validate test_cwd value
  702. if unit.get('MODULE_TYPE') == 'JUNIT5':
  703. script_rel_path = 'junit5.test'
  704. else:
  705. script_rel_path = 'junit.test'
  706. ymake_java_test = unit.get('YMAKE_JAVA_TEST') == 'yes'
  707. test_record = {
  708. 'SOURCE-FOLDER-PATH': path,
  709. 'TEST-NAME': '-'.join([os.path.basename(os.path.dirname(path)), os.path.basename(path)]),
  710. 'SCRIPT-REL-PATH': script_rel_path,
  711. 'TEST-TIMEOUT': unit.get('TEST_TIMEOUT') or '',
  712. 'TESTED-PROJECT-NAME': path,
  713. 'TEST-ENV': prepare_env(unit.get("TEST_ENV_VALUE")),
  714. # 'TEST-PRESERVE-ENV': 'da',
  715. 'TEST-DATA': serialize_list(sorted(_common.filter_out_by_keyword(test_data, 'AUTOUPDATED'))),
  716. 'FORK-MODE': unit.get('TEST_FORK_MODE') or '',
  717. 'SPLIT-FACTOR': unit.get('TEST_SPLIT_FACTOR') or '',
  718. 'CUSTOM-DEPENDENCIES': ' '.join(get_values_list(unit, 'TEST_DEPENDS_VALUE')),
  719. 'TAG': serialize_list(_get_test_tags(unit)),
  720. 'SIZE': unit.get('TEST_SIZE_NAME') or '',
  721. 'REQUIREMENTS': serialize_list(get_values_list(unit, 'TEST_REQUIREMENTS_VALUE')),
  722. 'TEST-RECIPES': prepare_recipes(unit.get("TEST_RECIPES_VALUE")),
  723. # JTEST/JTEST_FOR only
  724. 'MODULE_TYPE': unit.get('MODULE_TYPE'),
  725. 'UNITTEST_DIR': unit.get('UNITTEST_DIR') or '',
  726. 'JVM_ARGS': serialize_list(get_values_list(unit, 'JVM_ARGS_VALUE')),
  727. 'SYSTEM_PROPERTIES': props,
  728. 'TEST-CWD': test_cwd,
  729. 'SKIP_TEST': unit.get('SKIP_TEST_VALUE') or '',
  730. 'JAVA_CLASSPATH_CMD_TYPE': java_cp_arg_type,
  731. 'NO_JBUILD': 'yes' if ymake_java_test else 'no',
  732. 'JDK_RESOURCE': 'JDK' + (unit.get('JDK_VERSION') or unit.get('JDK_REAL_VERSION') or '_DEFAULT'),
  733. 'JDK_FOR_TESTS': 'JDK' + (unit.get('JDK_VERSION') or unit.get('JDK_REAL_VERSION') or '_DEFAULT') + '_FOR_TESTS',
  734. 'YT-SPEC': serialize_list(get_unit_list_variable(unit, 'TEST_YT_SPEC_VALUE')),
  735. }
  736. test_classpath_origins = unit.get('TEST_CLASSPATH_VALUE')
  737. if test_classpath_origins:
  738. test_record['TEST_CLASSPATH_ORIGINS'] = test_classpath_origins
  739. test_record['TEST_CLASSPATH'] = '${TEST_CLASSPATH_MANAGED}'
  740. elif ymake_java_test:
  741. test_record['TEST_CLASSPATH'] = '${DART_CLASSPATH}'
  742. test_record['TEST_CLASSPATH_DEPS'] = '${DART_CLASSPATH_DEPS}'
  743. if unit.get('UNITTEST_DIR'):
  744. test_record['TEST_JAR'] = '${UNITTEST_MOD}'
  745. else:
  746. test_record['TEST_JAR'] = '{}/{}.jar'.format(unit.get('MODDIR'), unit.get('REALPRJNAME'))
  747. data = dump_test(unit, test_record)
  748. if data:
  749. unit.set_property(['DART_DATA', data])
  750. def onjava_test_deps(unit, *args):
  751. if unit.get("TIDY") == "yes":
  752. # graph changed for clang_tidy tests
  753. return
  754. assert unit.get('MODULE_TYPE') is not None
  755. assert len(args) == 1
  756. mode = args[0]
  757. path = get_norm_unit_path(unit)
  758. ymake_java_test = unit.get('YMAKE_JAVA_TEST') == 'yes'
  759. test_record = {
  760. 'SOURCE-FOLDER-PATH': path,
  761. 'TEST-NAME': '-'.join([os.path.basename(os.path.dirname(path)), os.path.basename(path), 'dependencies']).strip('-'),
  762. 'SCRIPT-REL-PATH': 'java.dependency.test',
  763. 'TEST-TIMEOUT': '',
  764. 'TESTED-PROJECT-NAME': path,
  765. 'TEST-DATA': '',
  766. 'TEST_PARTITION': 'SEQUENTIAL',
  767. 'FORK-MODE': '',
  768. 'SPLIT-FACTOR': '',
  769. 'CUSTOM-DEPENDENCIES': ' '.join(get_values_list(unit, 'TEST_DEPENDS_VALUE')),
  770. 'TAG': '',
  771. 'SIZE': 'SMALL',
  772. 'IGNORE_CLASSPATH_CLASH': ' '.join(get_values_list(unit, 'JAVA_IGNORE_CLASSPATH_CLASH_VALUE')),
  773. 'NO_JBUILD': 'yes' if ymake_java_test else 'no',
  774. # JTEST/JTEST_FOR only
  775. 'MODULE_TYPE': unit.get('MODULE_TYPE'),
  776. 'UNITTEST_DIR': '',
  777. 'SYSTEM_PROPERTIES': '',
  778. 'TEST-CWD': '',
  779. }
  780. if mode == 'strict':
  781. test_record['STRICT_CLASSPATH_CLASH'] = 'yes'
  782. if ymake_java_test:
  783. test_record['CLASSPATH'] = '$B/{}/{}.jar ${{DART_CLASSPATH}}'.format(unit.get('MODDIR'), unit.get('REALPRJNAME'))
  784. data = dump_test(unit, test_record)
  785. unit.set_property(['DART_DATA', data])
  786. def _get_test_tags(unit, spec_args=None):
  787. if spec_args is None:
  788. spec_args = {}
  789. tags = spec_args.get('TAG', []) + get_values_list(unit, 'TEST_TAGS_VALUE')
  790. # DEVTOOLS-7571
  791. if unit.get('SKIP_TEST_VALUE') and 'ya:fat' in tags and "ya:not_autocheck" not in tags:
  792. tags.append("ya:not_autocheck")
  793. return tags
  794. def _dump_test(
  795. unit,
  796. test_type,
  797. test_files,
  798. timeout,
  799. test_dir,
  800. custom_deps,
  801. test_data,
  802. python_paths,
  803. split_factor,
  804. fork_mode,
  805. test_size,
  806. tags,
  807. requirements,
  808. binary_path='',
  809. old_pytest=False,
  810. test_cwd=None,
  811. runner_bin=None,
  812. yt_spec=None,
  813. data_files=None
  814. ):
  815. if test_type == "PY_TEST":
  816. script_rel_path = "py.test"
  817. else:
  818. script_rel_path = test_type
  819. unit_path = unit.path()
  820. fork_test_files = unit.get('FORK_TEST_FILES_MODE')
  821. fork_mode = ' '.join(fork_mode) if fork_mode else ''
  822. use_arcadia_python = unit.get('USE_ARCADIA_PYTHON')
  823. if test_cwd:
  824. test_cwd = test_cwd.replace("$TEST_CWD_VALUE", "").replace('"MACRO_CALLS_DELIM"', "").strip()
  825. test_name = os.path.basename(binary_path)
  826. test_record = {
  827. 'TEST-NAME': os.path.splitext(test_name)[0],
  828. 'TEST-TIMEOUT': timeout,
  829. 'SCRIPT-REL-PATH': script_rel_path,
  830. 'TESTED-PROJECT-NAME': test_name,
  831. 'SOURCE-FOLDER-PATH': test_dir,
  832. 'CUSTOM-DEPENDENCIES': " ".join(custom_deps),
  833. 'TEST-ENV': prepare_env(unit.get("TEST_ENV_VALUE")),
  834. # 'TEST-PRESERVE-ENV': 'da',
  835. 'TEST-DATA': serialize_list(sorted(_common.filter_out_by_keyword(test_data, 'AUTOUPDATED'))),
  836. 'TEST-RECIPES': prepare_recipes(unit.get("TEST_RECIPES_VALUE")),
  837. 'SPLIT-FACTOR': split_factor,
  838. 'TEST_PARTITION': unit.get('TEST_PARTITION') or 'SEQUENTIAL',
  839. 'FORK-MODE': fork_mode,
  840. 'FORK-TEST-FILES': fork_test_files,
  841. 'TEST-FILES': serialize_list(test_files),
  842. 'SIZE': test_size,
  843. 'TAG': serialize_list(tags),
  844. 'REQUIREMENTS': serialize_list(requirements),
  845. 'USE_ARCADIA_PYTHON': use_arcadia_python or '',
  846. 'OLD_PYTEST': 'yes' if old_pytest else 'no',
  847. 'PYTHON-PATHS': serialize_list(python_paths),
  848. 'TEST-CWD': test_cwd or '',
  849. 'SKIP_TEST': unit.get('SKIP_TEST_VALUE') or '',
  850. 'BUILD-FOLDER-PATH': _common.strip_roots(unit_path),
  851. 'BLOB': unit.get('TEST_BLOB_DATA') or '',
  852. 'CANONIZE_SUB_PATH': unit.get('CANONIZE_SUB_PATH') or '',
  853. }
  854. if binary_path:
  855. test_record['BINARY-PATH'] = _common.strip_roots(binary_path)
  856. if runner_bin:
  857. test_record['TEST-RUNNER-BIN'] = runner_bin
  858. if yt_spec:
  859. test_record['YT-SPEC'] = serialize_list(yt_spec)
  860. data = dump_test(unit, test_record)
  861. if data:
  862. unit.set_property(["DART_DATA", data])
  863. save_in_file(unit.get('TEST_DART_OUT_FILE'), data)
  864. def onsetup_pytest_bin(unit, *args):
  865. use_arcadia_python = unit.get('USE_ARCADIA_PYTHON') == "yes"
  866. if use_arcadia_python:
  867. unit.onresource(['-', 'PY_MAIN={}'.format("library.python.pytest.main:main")]) # XXX
  868. unit.onadd_pytest_bin(list(args))
  869. else:
  870. unit.onno_platform()
  871. unit.onadd_pytest_script(["PY_TEST"])
  872. def onrun(unit, *args):
  873. exectest_cmd = unit.get(["EXECTEST_COMMAND_VALUE"]) or ''
  874. exectest_cmd += "\n" + subprocess.list2cmdline(args)
  875. unit.set(["EXECTEST_COMMAND_VALUE", exectest_cmd])
  876. def onsetup_exectest(unit, *args):
  877. command = unit.get(["EXECTEST_COMMAND_VALUE"])
  878. if command is None:
  879. ymake.report_configure_error("EXECTEST must have at least one RUN macro")
  880. return
  881. command = command.replace("$EXECTEST_COMMAND_VALUE", "")
  882. if "PYTHON_BIN" in command:
  883. unit.ondepends('contrib/tools/python')
  884. unit.set(["TEST_BLOB_DATA", base64.b64encode(command)])
  885. add_test_to_dart(unit, "exectest", binary_path=os.path.join(unit.path(), unit.filename()).replace(".pkg", ""))
  886. def onsetup_run_python(unit):
  887. if unit.get("USE_ARCADIA_PYTHON") == "yes":
  888. unit.ondepends('contrib/tools/python')
  889. def get_canonical_test_resources(unit):
  890. unit_path = unit.path()
  891. canon_data_dir = os.path.join(unit.resolve(unit_path), CANON_DATA_DIR_NAME, unit.get('CANONIZE_SUB_PATH') or '')
  892. try:
  893. _, dirs, files = next(os.walk(canon_data_dir))
  894. except StopIteration:
  895. # path doesn't exist
  896. return [], []
  897. if CANON_RESULT_FILE_NAME in files:
  898. return _get_canonical_data_resources_v2(os.path.join(canon_data_dir, CANON_RESULT_FILE_NAME), unit_path)
  899. return [], []
  900. def _load_canonical_file(filename, unit_path):
  901. try:
  902. with open(filename) as results_file:
  903. return json.load(results_file)
  904. except Exception as e:
  905. print>>sys.stderr, "malformed canonical data in {}: {} ({})".format(unit_path, e, filename)
  906. return {}
  907. def _get_resource_from_uri(uri):
  908. m = CANON_MDS_RESOURCE_REGEX.match(uri)
  909. if m:
  910. res_id = m.group(1)
  911. return "{}:{}".format(MDS_SCHEME, res_id)
  912. m = CANON_SBR_RESOURCE_REGEX.match(uri)
  913. if m:
  914. # There might be conflict between resources, because all resources in sandbox have 'resource.tar.gz' name
  915. # That's why we use notation with '=' to specify specific path for resource
  916. uri = m.group(1)
  917. res_id = m.group(2)
  918. return "{}={}".format(uri, '/'.join([CANON_OUTPUT_STORAGE, res_id]))
  919. def _get_external_resources_from_canon_data(data):
  920. # Method should work with both canonization versions:
  921. # result.json: {'uri':X 'checksum':Y}
  922. # result.json: {'testname': {'uri':X 'checksum':Y}}
  923. # result.json: {'testname': [{'uri':X 'checksum':Y}]}
  924. # Also there is a bug - if user returns {'uri': 1} from test - machinery will fail
  925. # That's why we check 'uri' and 'checksum' fields presence
  926. # (it's still a bug - user can return {'uri':X, 'checksum': Y}, we need to unify canonization format)
  927. res = set()
  928. if isinstance(data, dict):
  929. if 'uri' in data and 'checksum' in data:
  930. resource = _get_resource_from_uri(data['uri'])
  931. if resource:
  932. res.add(resource)
  933. else:
  934. for k, v in data.iteritems():
  935. res.update(_get_external_resources_from_canon_data(v))
  936. elif isinstance(data, list):
  937. for e in data:
  938. res.update(_get_external_resources_from_canon_data(e))
  939. return res
  940. def _get_canonical_data_resources_v2(filename, unit_path):
  941. return (_get_external_resources_from_canon_data(_load_canonical_file(filename, unit_path)), [filename])