ytest.py 51 KB

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