ytest.py 50 KB

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