ytest.py 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370
  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 reference_group_var(varname: str, extensions: list[str] | None = None) -> str:
  306. if extensions is None:
  307. return f'"${{join=\\;:{varname}}}"'
  308. return serialize_list(f'${{ext={ext};join=\\;:{varname}}}' for ext in extensions)
  309. def count_entries(x):
  310. # see (de)serialize_list
  311. assert x is None or isinstance(x, str), type(x)
  312. if not x:
  313. return 0
  314. return x.count(";") + 1
  315. def get_values_list(unit, key):
  316. res = map(str.strip, (unit.get(key) or '').replace('$' + key, '').strip().split())
  317. return [r for r in res if r and r not in ['""', "''"]]
  318. def get_norm_paths(unit, key):
  319. # return paths without trailing (back)slash
  320. return [x.rstrip('\\/').replace('${ARCADIA_ROOT}/', '') for x in get_values_list(unit, key)]
  321. def get_unit_list_variable(unit, name):
  322. items = unit.get(name)
  323. if items:
  324. items = items.split(' ')
  325. assert items[0] == "${}".format(name), (items, name)
  326. return items[1:]
  327. return []
  328. def implies(a, b):
  329. return bool((not a) or b)
  330. def match_coverage_extractor_requirements(unit):
  331. # we shouldn't add test if
  332. return all(
  333. [
  334. # tests are not requested
  335. unit.get("TESTS_REQUESTED") == "yes",
  336. # build doesn't imply clang coverage, which supports segment extraction from the binaries
  337. unit.get("CLANG_COVERAGE") == "yes",
  338. # contrib wasn't requested
  339. implies(
  340. _common.get_norm_unit_path(unit).startswith("contrib/"), unit.get("ENABLE_CONTRIB_COVERAGE") == "yes"
  341. ),
  342. ]
  343. )
  344. def get_tidy_config_map(unit, map_path):
  345. config_map_path = unit.resolve(os.path.join("$S", map_path))
  346. config_map = {}
  347. try:
  348. with open(config_map_path, 'r') as afile:
  349. config_map = json.load(afile)
  350. except ValueError:
  351. ymake.report_configure_error("{} is invalid json".format(map_path))
  352. except Exception as e:
  353. ymake.report_configure_error(str(e))
  354. return config_map
  355. def get_default_tidy_config(unit):
  356. unit_path = _common.get_norm_unit_path(unit)
  357. tidy_default_config_map = get_tidy_config_map(unit, DEFAULT_TIDY_CONFIG_MAP_PATH)
  358. for project_prefix, config_path in tidy_default_config_map.items():
  359. if unit_path.startswith(project_prefix):
  360. return config_path
  361. return DEFAULT_TIDY_CONFIG
  362. ordered_tidy_map = None
  363. def get_project_tidy_config(unit):
  364. global ordered_tidy_map
  365. if ordered_tidy_map is None:
  366. ordered_tidy_map = list(reversed(sorted(get_tidy_config_map(unit, PROJECT_TIDY_CONFIG_MAP_PATH).items())))
  367. unit_path = _common.get_norm_unit_path(unit)
  368. for project_prefix, config_path in ordered_tidy_map:
  369. if unit_path.startswith(project_prefix):
  370. return config_path
  371. else:
  372. return get_default_tidy_config(unit)
  373. def onadd_ytest(unit, *args):
  374. keywords = {
  375. "DEPENDS": -1,
  376. "DATA": -1,
  377. "TIMEOUT": 1,
  378. "FORK_MODE": 1,
  379. "SPLIT_FACTOR": 1,
  380. "FORK_SUBTESTS": 0,
  381. "FORK_TESTS": 0,
  382. }
  383. flat_args, spec_args = _common.sort_by_keywords(keywords, args)
  384. is_implicit_data_needed = flat_args[1] in (
  385. "unittest.py",
  386. "gunittest",
  387. "g_benchmark",
  388. "go.test",
  389. "boost.test",
  390. "fuzz.test",
  391. )
  392. if is_implicit_data_needed and unit.get('ADD_SRCDIR_TO_TEST_DATA') == "yes":
  393. unit.ondata_files(_common.get_norm_unit_path(unit))
  394. if flat_args[1] == "fuzz.test":
  395. unit.ondata_files("fuzzing/{}/corpus.json".format(_common.get_norm_unit_path(unit)))
  396. if not flat_args[1] in ("unittest.py", "gunittest", "g_benchmark"):
  397. unit.ondata_files(get_unit_list_variable(unit, 'TEST_YT_SPEC_VALUE'))
  398. test_data = sorted(
  399. _common.filter_out_by_keyword(
  400. spec_args.get('DATA', []) + get_norm_paths(unit, 'TEST_DATA_VALUE'), 'AUTOUPDATED'
  401. )
  402. )
  403. if flat_args[1] == "go.test":
  404. data, _ = get_canonical_test_resources(unit)
  405. test_data += data
  406. elif flat_args[1] == "coverage.extractor" and not match_coverage_extractor_requirements(unit):
  407. # XXX
  408. # Current ymake implementation doesn't allow to call macro inside the 'when' body
  409. # that's why we add ADD_YTEST(coverage.extractor) to every PROGRAM entry and check requirements later
  410. return
  411. elif flat_args[1] == "clang_tidy" and unit.get("TIDY_ENABLED") != "yes":
  412. # Graph is not prepared
  413. return
  414. elif unit.get("TIDY") == "yes" and unit.get("TIDY_ENABLED") != "yes":
  415. # clang_tidy disabled for module
  416. return
  417. elif flat_args[1] == "no.test":
  418. return
  419. test_size = ''.join(spec_args.get('SIZE', [])) or unit.get('TEST_SIZE_NAME') or ''
  420. test_tags = serialize_list(sorted(_get_test_tags(unit, spec_args)))
  421. test_timeout = ''.join(spec_args.get('TIMEOUT', [])) or unit.get('TEST_TIMEOUT') or ''
  422. test_requirements = spec_args.get('REQUIREMENTS', []) + get_values_list(unit, 'TEST_REQUIREMENTS_VALUE')
  423. if flat_args[1] != "clang_tidy" and unit.get("TIDY_ENABLED") == "yes":
  424. # graph changed for clang_tidy tests
  425. if flat_args[1] in ("unittest.py", "gunittest", "g_benchmark", "boost.test"):
  426. flat_args[1] = "clang_tidy"
  427. test_size = 'SMALL'
  428. test_tags = ''
  429. test_timeout = "60"
  430. test_requirements = []
  431. unit.set(["TEST_YT_SPEC_VALUE", ""])
  432. else:
  433. return
  434. if flat_args[1] == "clang_tidy" and unit.get("TIDY_ENABLED") == "yes":
  435. if unit.get("TIDY_CONFIG"):
  436. default_config_path = unit.get("TIDY_CONFIG")
  437. project_config_path = unit.get("TIDY_CONFIG")
  438. else:
  439. default_config_path = get_default_tidy_config(unit)
  440. project_config_path = get_project_tidy_config(unit)
  441. unit.set(["DEFAULT_TIDY_CONFIG", default_config_path])
  442. unit.set(["PROJECT_TIDY_CONFIG", project_config_path])
  443. fork_mode = []
  444. if 'FORK_SUBTESTS' in spec_args:
  445. fork_mode.append('subtests')
  446. if 'FORK_TESTS' in spec_args:
  447. fork_mode.append('tests')
  448. fork_mode = fork_mode or spec_args.get('FORK_MODE', []) or unit.get('TEST_FORK_MODE').split()
  449. fork_mode = ' '.join(fork_mode) if fork_mode else ''
  450. unit_path = _common.get_norm_unit_path(unit)
  451. test_record = {
  452. 'TEST-NAME': flat_args[0],
  453. 'SCRIPT-REL-PATH': flat_args[1],
  454. 'TESTED-PROJECT-NAME': unit.name(),
  455. 'TESTED-PROJECT-FILENAME': unit.filename(),
  456. 'SOURCE-FOLDER-PATH': unit_path,
  457. # TODO get rid of BUILD-FOLDER-PATH
  458. 'BUILD-FOLDER-PATH': unit_path,
  459. 'BINARY-PATH': "{}/{}".format(unit_path, unit.filename()),
  460. 'GLOBAL-LIBRARY-PATH': unit.global_filename(),
  461. 'CUSTOM-DEPENDENCIES': ' '.join(spec_args.get('DEPENDS', []) + get_values_list(unit, 'TEST_DEPENDS_VALUE')),
  462. 'TEST-RECIPES': prepare_recipes(unit.get("TEST_RECIPES_VALUE")),
  463. 'TEST-ENV': prepare_env(unit.get("TEST_ENV_VALUE")),
  464. # 'TEST-PRESERVE-ENV': 'da',
  465. 'TEST-DATA': serialize_list(sorted(test_data)),
  466. 'TEST-TIMEOUT': test_timeout,
  467. 'FORK-MODE': fork_mode,
  468. 'SPLIT-FACTOR': ''.join(spec_args.get('SPLIT_FACTOR', [])) or unit.get('TEST_SPLIT_FACTOR') or '',
  469. 'SIZE': test_size,
  470. 'TAG': test_tags,
  471. 'REQUIREMENTS': serialize_list(test_requirements),
  472. 'TEST-CWD': unit.get('TEST_CWD_VALUE') or '',
  473. 'FUZZ-DICTS': serialize_list(
  474. spec_args.get('FUZZ_DICTS', []) + get_unit_list_variable(unit, 'FUZZ_DICTS_VALUE')
  475. ),
  476. 'FUZZ-OPTS': serialize_list(spec_args.get('FUZZ_OPTS', []) + get_unit_list_variable(unit, 'FUZZ_OPTS_VALUE')),
  477. 'YT-SPEC': serialize_list(spec_args.get('YT_SPEC', []) + get_unit_list_variable(unit, 'TEST_YT_SPEC_VALUE')),
  478. 'BLOB': unit.get('TEST_BLOB_DATA') or '',
  479. 'SKIP_TEST': unit.get('SKIP_TEST_VALUE') or '',
  480. 'TEST_IOS_DEVICE_TYPE': unit.get('TEST_IOS_DEVICE_TYPE_VALUE') or '',
  481. 'TEST_IOS_RUNTIME_TYPE': unit.get('TEST_IOS_RUNTIME_TYPE_VALUE') or '',
  482. 'ANDROID_APK_TEST_ACTIVITY': unit.get('ANDROID_APK_TEST_ACTIVITY_VALUE') or '',
  483. 'TEST_PARTITION': unit.get("TEST_PARTITION") or 'SEQUENTIAL',
  484. 'GO_BENCH_TIMEOUT': unit.get('GO_BENCH_TIMEOUT') or '',
  485. }
  486. if flat_args[1] == "go.bench":
  487. if "ya:run_go_benchmark" not in test_record["TAG"]:
  488. return
  489. else:
  490. test_record["TEST-NAME"] += "_bench"
  491. elif flat_args[1] in ("g_benchmark", "y_benchmark"):
  492. benchmark_opts = get_unit_list_variable(unit, 'BENCHMARK_OPTS_VALUE')
  493. test_record['BENCHMARK-OPTS'] = serialize_list(benchmark_opts)
  494. elif flat_args[1] == 'fuzz.test' and unit.get('FUZZING') == 'yes':
  495. test_record['FUZZING'] = '1'
  496. # use all cores if fuzzing requested
  497. test_record['REQUIREMENTS'] = serialize_list(
  498. filter(None, deserialize_list(test_record['REQUIREMENTS']) + ["cpu:all", "ram:all"])
  499. )
  500. data = dump_test(unit, test_record)
  501. if data:
  502. unit.set_property(["DART_DATA", data])
  503. def java_srcdirs_to_data(unit, var):
  504. extra_data = []
  505. for srcdir in (unit.get(var) or '').replace('$' + var, '').split():
  506. if srcdir == '.':
  507. srcdir = unit.get('MODDIR')
  508. if srcdir.startswith('${ARCADIA_ROOT}/') or srcdir.startswith('$ARCADIA_ROOT/'):
  509. srcdir = srcdir.replace('${ARCADIA_ROOT}/', '$S/')
  510. srcdir = srcdir.replace('$ARCADIA_ROOT/', '$S/')
  511. if srcdir.startswith('${CURDIR}') or srcdir.startswith('$CURDIR'):
  512. srcdir = srcdir.replace('${CURDIR}', os.path.join('$S', unit.get('MODDIR')))
  513. srcdir = srcdir.replace('$CURDIR', os.path.join('$S', unit.get('MODDIR')))
  514. srcdir = unit.resolve_arc_path(srcdir)
  515. if not srcdir.startswith('$'):
  516. srcdir = os.path.join('$S', unit.get('MODDIR'), srcdir)
  517. if srcdir.startswith('$S'):
  518. extra_data.append(srcdir.replace('$S', 'arcadia'))
  519. return serialize_list(extra_data)
  520. def onadd_check(unit, *args):
  521. if unit.get("TIDY") == "yes":
  522. # graph changed for clang_tidy tests
  523. return
  524. flat_args, spec_args = _common.sort_by_keywords(
  525. {
  526. "DEPENDS": -1,
  527. "TIMEOUT": 1,
  528. "DATA": -1,
  529. "TAG": -1,
  530. "REQUIREMENTS": -1,
  531. "FORK_MODE": 1,
  532. "SPLIT_FACTOR": 1,
  533. "FORK_SUBTESTS": 0,
  534. "FORK_TESTS": 0,
  535. "SIZE": 1,
  536. },
  537. args,
  538. )
  539. check_type = flat_args[0]
  540. if check_type in ("check.data", "check.resource") and unit.get('VALIDATE_DATA') == "no":
  541. return
  542. test_dir = _common.get_norm_unit_path(unit)
  543. test_timeout = ''
  544. fork_mode = ''
  545. extra_test_data = ''
  546. extra_test_dart_data = {}
  547. ymake_java_test = unit.get('YMAKE_JAVA_TEST') == 'yes'
  548. use_arcadia_python = unit.get('USE_ARCADIA_PYTHON')
  549. uid_ext = ''
  550. script_rel_path = check_type
  551. test_files = flat_args[1:]
  552. if check_type in ["check.data", "check.resource"]:
  553. uid_ext = unit.get("SBR_UID_EXT").split(" ", 1)[-1] # strip variable name
  554. if check_type in ["flake8.py2", "flake8.py3", "black"]:
  555. fork_mode = unit.get('TEST_FORK_MODE') or ''
  556. elif check_type == "ktlint":
  557. test_timeout = '120'
  558. if unit.get('_USE_KTLINT_OLD') == 'yes':
  559. extra_test_data = serialize_list([KTLINT_OLD_EDITOR_CONFIG])
  560. extra_test_dart_data['KTLINT_BINARY'] = '$(KTLINT_OLD)/run.bat'
  561. extra_test_dart_data['USE_KTLINT_OLD'] = 'yes'
  562. else:
  563. data_list = [KTLINT_CURRENT_EDITOR_CONFIG]
  564. baseline_path_relative = unit.get('_KTLINT_BASELINE_FILE')
  565. if baseline_path_relative:
  566. baseline_path = unit.resolve_arc_path(baseline_path_relative).replace('$S', 'arcadia')
  567. data_list += [baseline_path]
  568. extra_test_dart_data['KTLINT_BASELINE_FILE'] = baseline_path_relative
  569. extra_test_data = serialize_list(data_list)
  570. extra_test_dart_data['KTLINT_BINARY'] = '$(KTLINT)/run.bat'
  571. elif check_type == "JAVA_STYLE":
  572. if ymake_java_test and not unit.get('ALL_SRCDIRS'):
  573. return
  574. if len(flat_args) < 2:
  575. raise Exception("Not enough arguments for JAVA_STYLE check")
  576. check_level = flat_args[1]
  577. allowed_levels = {
  578. 'base': '/yandex_checks.xml',
  579. 'strict': '/yandex_checks_strict.xml',
  580. 'extended': '/yandex_checks_extended.xml',
  581. 'library': '/yandex_checks_library.xml',
  582. }
  583. if check_level not in allowed_levels:
  584. raise Exception("'{}' is not allowed in LINT(), use one of {}".format(check_level, allowed_levels.keys()))
  585. test_files[0] = allowed_levels[check_level] # replace check_level with path to config file
  586. script_rel_path = "java.style"
  587. test_timeout = '240'
  588. fork_mode = unit.get('TEST_FORK_MODE') or ''
  589. if ymake_java_test:
  590. extra_test_data = java_srcdirs_to_data(unit, 'ALL_SRCDIRS')
  591. # jstyle should use the latest jdk
  592. unit.onpeerdir([unit.get('JDK_LATEST_PEERDIR')])
  593. extra_test_dart_data['JDK_LATEST_VERSION'] = unit.get('JDK_LATEST_VERSION')
  594. # TODO remove when ya-bin will be released (https://st.yandex-team.ru/DEVTOOLS-9611)
  595. extra_test_dart_data['JDK_RESOURCE'] = 'JDK' + (
  596. unit.get('JDK_VERSION') or unit.get('JDK_REAL_VERSION') or '_DEFAULT'
  597. )
  598. elif check_type == "gofmt":
  599. if test_files:
  600. test_dir = os.path.dirname(test_files[0]).lstrip("$S/")
  601. elif check_type == "check.data":
  602. data_re = re.compile(r"sbr:/?/?(\d+)=?.*")
  603. data = flat_args[1:]
  604. resources = []
  605. for f in data:
  606. matched = re.match(data_re, f)
  607. if matched:
  608. resources.append(matched.group(1))
  609. if resources:
  610. test_files = resources
  611. else:
  612. return
  613. serialized_test_files = serialize_list(test_files)
  614. test_record = {
  615. 'TEST-NAME': check_type.lower(),
  616. 'TEST-TIMEOUT': test_timeout,
  617. 'SCRIPT-REL-PATH': script_rel_path,
  618. 'TESTED-PROJECT-NAME': os.path.basename(test_dir),
  619. 'SOURCE-FOLDER-PATH': test_dir,
  620. 'CUSTOM-DEPENDENCIES': " ".join(spec_args.get('DEPENDS', [])),
  621. 'TEST-DATA': extra_test_data,
  622. 'TEST-ENV': prepare_env(unit.get("TEST_ENV_VALUE")),
  623. 'SBR-UID-EXT': uid_ext,
  624. 'SPLIT-FACTOR': '',
  625. 'TEST_PARTITION': 'SEQUENTIAL',
  626. 'FORK-MODE': fork_mode,
  627. 'FORK-TEST-FILES': '',
  628. 'SIZE': 'SMALL',
  629. 'TAG': '',
  630. 'REQUIREMENTS': " ".join(spec_args.get('REQUIREMENTS', [])),
  631. 'USE_ARCADIA_PYTHON': use_arcadia_python or '',
  632. 'OLD_PYTEST': 'no',
  633. 'PYTHON-PATHS': '',
  634. # TODO remove FILES, see DEVTOOLS-7052
  635. 'FILES': serialized_test_files,
  636. 'TEST-FILES': serialized_test_files,
  637. }
  638. test_record.update(extra_test_dart_data)
  639. data = dump_test(unit, test_record)
  640. if data:
  641. unit.set_property(["DART_DATA", data])
  642. def on_register_no_check_imports(unit):
  643. s = unit.get('NO_CHECK_IMPORTS_FOR_VALUE')
  644. if s not in ('', 'None'):
  645. unit.onresource(['-', 'py/no_check_imports/{}="{}"'.format(_common.pathid(s), s)])
  646. def onadd_check_py_imports(unit, *args):
  647. if unit.get("TIDY") == "yes":
  648. # graph changed for clang_tidy tests
  649. return
  650. if unit.get('NO_CHECK_IMPORTS_FOR_VALUE').strip() == "":
  651. return
  652. unit.onpeerdir(['library/python/testing/import_test'])
  653. check_type = "py.imports"
  654. test_dir = _common.get_norm_unit_path(unit)
  655. use_arcadia_python = unit.get('USE_ARCADIA_PYTHON')
  656. test_files = serialize_list([_common.get_norm_unit_path(unit, unit.filename())])
  657. test_record = {
  658. 'TEST-NAME': "pyimports",
  659. 'TEST-TIMEOUT': '',
  660. 'SCRIPT-REL-PATH': check_type,
  661. 'TESTED-PROJECT-NAME': os.path.basename(test_dir),
  662. 'SOURCE-FOLDER-PATH': test_dir,
  663. 'CUSTOM-DEPENDENCIES': '',
  664. 'TEST-DATA': '',
  665. 'TEST-ENV': prepare_env(unit.get("TEST_ENV_VALUE")),
  666. 'SPLIT-FACTOR': '',
  667. 'TEST_PARTITION': 'SEQUENTIAL',
  668. 'FORK-MODE': '',
  669. 'FORK-TEST-FILES': '',
  670. 'SIZE': 'SMALL',
  671. 'TAG': '',
  672. 'USE_ARCADIA_PYTHON': use_arcadia_python or '',
  673. 'OLD_PYTEST': 'no',
  674. 'PYTHON-PATHS': '',
  675. # TODO remove FILES, see DEVTOOLS-7052
  676. 'FILES': test_files,
  677. 'TEST-FILES': test_files,
  678. }
  679. if unit.get('NO_CHECK_IMPORTS_FOR_VALUE') != "None":
  680. test_record["NO-CHECK"] = serialize_list(get_values_list(unit, 'NO_CHECK_IMPORTS_FOR_VALUE') or ["*"])
  681. else:
  682. test_record["NO-CHECK"] = ''
  683. data = dump_test(unit, test_record)
  684. if data:
  685. unit.set_property(["DART_DATA", data])
  686. def onadd_pytest_script(unit, *args):
  687. if unit.get("TIDY") == "yes":
  688. # graph changed for clang_tidy tests
  689. return
  690. unit.set(["PYTEST_BIN", "no"])
  691. custom_deps = get_values_list(unit, 'TEST_DEPENDS_VALUE')
  692. timeout = list(filter(None, [unit.get(["TEST_TIMEOUT"])]))
  693. if unit.get('ADD_SRCDIR_TO_TEST_DATA') == "yes":
  694. unit.ondata_files(_common.get_norm_unit_path(unit))
  695. if timeout:
  696. timeout = timeout[0]
  697. else:
  698. timeout = '0'
  699. test_type = args[0]
  700. fork_mode = unit.get('TEST_FORK_MODE').split() or ''
  701. split_factor = unit.get('TEST_SPLIT_FACTOR') or ''
  702. test_size = unit.get('TEST_SIZE_NAME') or ''
  703. test_files = get_values_list(unit, 'TEST_SRCS_VALUE')
  704. tags = _get_test_tags(unit)
  705. requirements = get_values_list(unit, 'TEST_REQUIREMENTS_VALUE')
  706. test_data = get_norm_paths(unit, 'TEST_DATA_VALUE')
  707. data, data_files = get_canonical_test_resources(unit)
  708. test_data += data
  709. python_paths = get_values_list(unit, 'TEST_PYTHON_PATH_VALUE')
  710. binary_path = os.path.join(_common.get_norm_unit_path(unit), unit.filename())
  711. test_cwd = unit.get('TEST_CWD_VALUE') or ''
  712. _dump_test(
  713. unit,
  714. test_type,
  715. test_files,
  716. timeout,
  717. _common.get_norm_unit_path(unit),
  718. custom_deps,
  719. test_data,
  720. python_paths,
  721. split_factor,
  722. fork_mode,
  723. test_size,
  724. tags,
  725. requirements,
  726. binary_path,
  727. test_cwd=test_cwd,
  728. data_files=data_files,
  729. )
  730. def onadd_pytest_bin(unit, *args):
  731. if unit.get("TIDY") == "yes":
  732. # graph changed for clang_tidy tests
  733. return
  734. flat, kws = _common.sort_by_keywords({'RUNNER_BIN': 1}, args)
  735. if flat:
  736. ymake.report_configure_error('Unknown arguments found while processing add_pytest_bin macro: {!r}'.format(flat))
  737. runner_bin = kws.get('RUNNER_BIN', [None])[0]
  738. test_type = 'py3test.bin' if (unit.get("PYTHON3") == 'yes') else "pytest.bin"
  739. add_test_to_dart(unit, test_type, runner_bin=runner_bin)
  740. def add_test_to_dart(unit, test_type, binary_path=None, runner_bin=None):
  741. if unit.get("TIDY") == "yes":
  742. # graph changed for clang_tidy tests
  743. return
  744. if unit.get('ADD_SRCDIR_TO_TEST_DATA') == "yes":
  745. unit.ondata_files(_common.get_norm_unit_path(unit))
  746. custom_deps = get_values_list(unit, 'TEST_DEPENDS_VALUE')
  747. timeout = list(filter(None, [unit.get(["TEST_TIMEOUT"])]))
  748. if timeout:
  749. timeout = timeout[0]
  750. else:
  751. timeout = '0'
  752. fork_mode = unit.get('TEST_FORK_MODE').split() or ''
  753. split_factor = unit.get('TEST_SPLIT_FACTOR') or ''
  754. test_size = unit.get('TEST_SIZE_NAME') or ''
  755. test_cwd = unit.get('TEST_CWD_VALUE') or ''
  756. yt_spec = get_values_list(unit, 'TEST_YT_SPEC_VALUE')
  757. unit.ondata_files(yt_spec)
  758. unit_path = unit.path()
  759. test_files = get_values_list(unit, 'TEST_SRCS_VALUE')
  760. tags = _get_test_tags(unit)
  761. requirements = get_values_list(unit, 'TEST_REQUIREMENTS_VALUE')
  762. test_data = get_norm_paths(unit, 'TEST_DATA_VALUE')
  763. data, data_files = get_canonical_test_resources(unit)
  764. test_data += data
  765. python_paths = get_values_list(unit, 'TEST_PYTHON_PATH_VALUE')
  766. if not binary_path:
  767. binary_path = os.path.join(unit_path, unit.filename())
  768. _dump_test(
  769. unit,
  770. test_type,
  771. test_files,
  772. timeout,
  773. _common.get_norm_unit_path(unit),
  774. custom_deps,
  775. test_data,
  776. python_paths,
  777. split_factor,
  778. fork_mode,
  779. test_size,
  780. tags,
  781. requirements,
  782. binary_path,
  783. test_cwd=test_cwd,
  784. runner_bin=runner_bin,
  785. yt_spec=yt_spec,
  786. data_files=data_files,
  787. )
  788. def extract_java_system_properties(unit, args):
  789. if len(args) % 2:
  790. return [], 'Wrong use of SYSTEM_PROPERTIES in {}: odd number of arguments'.format(unit.path())
  791. props = []
  792. for x, y in zip(args[::2], args[1::2]):
  793. if x == 'FILE':
  794. if y.startswith('${BINDIR}') or y.startswith('${ARCADIA_BUILD_ROOT}') or y.startswith('/'):
  795. return [], 'Wrong use of SYSTEM_PROPERTIES in {}: absolute/build file path {}'.format(unit.path(), y)
  796. y = _common.rootrel_arc_src(y, unit)
  797. if not os.path.exists(unit.resolve('$S/' + y)):
  798. return [], 'Wrong use of SYSTEM_PROPERTIES in {}: can\'t resolve {}'.format(unit.path(), y)
  799. y = '${ARCADIA_ROOT}/' + y
  800. props.append({'type': 'file', 'path': y})
  801. else:
  802. props.append({'type': 'inline', 'key': x, 'value': y})
  803. return props, None
  804. def onjava_test(unit, *args):
  805. if unit.get("TIDY") == "yes":
  806. # graph changed for clang_tidy tests
  807. return
  808. assert unit.get('MODULE_TYPE') is not None
  809. if unit.get('MODULE_TYPE') == 'JTEST_FOR':
  810. if not unit.get('UNITTEST_DIR'):
  811. ymake.report_configure_error('skip JTEST_FOR in {}: no args provided'.format(unit.path()))
  812. return
  813. java_cp_arg_type = unit.get('JAVA_CLASSPATH_CMD_TYPE_VALUE') or 'MANIFEST'
  814. if java_cp_arg_type not in ('MANIFEST', 'COMMAND_FILE', 'LIST'):
  815. ymake.report_configure_error(
  816. '{}: TEST_JAVA_CLASSPATH_CMD_TYPE({}) are invalid. Choose argument from MANIFEST, COMMAND_FILE or LIST)'.format(
  817. unit.path(), java_cp_arg_type
  818. )
  819. )
  820. return
  821. unit_path = unit.path()
  822. path = _common.strip_roots(unit_path)
  823. if unit.get('ADD_SRCDIR_TO_TEST_DATA') == "yes":
  824. unit.ondata_files(_common.get_norm_unit_path(unit))
  825. yt_spec_values = get_unit_list_variable(unit, 'TEST_YT_SPEC_VALUE')
  826. unit.ondata_files(yt_spec_values)
  827. test_data = get_norm_paths(unit, 'TEST_DATA_VALUE')
  828. test_data.append('arcadia/build/scripts/run_junit.py')
  829. test_data.append('arcadia/build/scripts/unpacking_jtest_runner.py')
  830. data, data_files = get_canonical_test_resources(unit)
  831. test_data += data
  832. props, error_mgs = extract_java_system_properties(unit, get_values_list(unit, 'SYSTEM_PROPERTIES_VALUE'))
  833. if error_mgs:
  834. ymake.report_configure_error(error_mgs)
  835. return
  836. for prop in props:
  837. if prop['type'] == 'file':
  838. test_data.append(prop['path'].replace('${ARCADIA_ROOT}', 'arcadia'))
  839. props = base64.b64encode(six.ensure_binary(json.dumps(props)))
  840. test_cwd = unit.get('TEST_CWD_VALUE') or '' # TODO: validate test_cwd value
  841. if unit.get('MODULE_TYPE') == 'JUNIT5':
  842. script_rel_path = 'junit5.test'
  843. else:
  844. script_rel_path = 'junit.test'
  845. ymake_java_test = unit.get('YMAKE_JAVA_TEST') == 'yes'
  846. test_record = {
  847. 'SOURCE-FOLDER-PATH': path,
  848. 'TEST-NAME': '-'.join([os.path.basename(os.path.dirname(path)), os.path.basename(path)]),
  849. 'SCRIPT-REL-PATH': script_rel_path,
  850. 'TEST-TIMEOUT': unit.get('TEST_TIMEOUT') or '',
  851. 'TESTED-PROJECT-NAME': path,
  852. 'TEST-ENV': prepare_env(unit.get("TEST_ENV_VALUE")),
  853. # 'TEST-PRESERVE-ENV': 'da',
  854. 'TEST-DATA': serialize_list(sorted(_common.filter_out_by_keyword(test_data, 'AUTOUPDATED'))),
  855. 'FORK-MODE': unit.get('TEST_FORK_MODE') or '',
  856. 'SPLIT-FACTOR': unit.get('TEST_SPLIT_FACTOR') or '',
  857. 'CUSTOM-DEPENDENCIES': ' '.join(get_values_list(unit, 'TEST_DEPENDS_VALUE')),
  858. 'TAG': serialize_list(sorted(_get_test_tags(unit))),
  859. 'SIZE': unit.get('TEST_SIZE_NAME') or '',
  860. 'REQUIREMENTS': serialize_list(get_values_list(unit, 'TEST_REQUIREMENTS_VALUE')),
  861. 'TEST-RECIPES': prepare_recipes(unit.get("TEST_RECIPES_VALUE")),
  862. # JTEST/JTEST_FOR only
  863. 'MODULE_TYPE': unit.get('MODULE_TYPE'),
  864. 'UNITTEST_DIR': unit.get('UNITTEST_DIR') or '',
  865. 'JVM_ARGS': serialize_list(get_values_list(unit, 'JVM_ARGS_VALUE')),
  866. 'SYSTEM_PROPERTIES': props,
  867. 'TEST-CWD': test_cwd,
  868. 'SKIP_TEST': unit.get('SKIP_TEST_VALUE') or '',
  869. 'JAVA_CLASSPATH_CMD_TYPE': java_cp_arg_type,
  870. 'JDK_RESOURCE': 'JDK' + (unit.get('JDK_VERSION') or unit.get('JDK_REAL_VERSION') or '_DEFAULT'),
  871. 'JDK_FOR_TESTS': 'JDK' + (unit.get('JDK_VERSION') or unit.get('JDK_REAL_VERSION') or '_DEFAULT') + '_FOR_TESTS',
  872. 'YT-SPEC': serialize_list(yt_spec_values),
  873. }
  874. test_classpath_origins = unit.get('TEST_CLASSPATH_VALUE')
  875. if test_classpath_origins:
  876. test_record['TEST_CLASSPATH_ORIGINS'] = test_classpath_origins
  877. test_record['TEST_CLASSPATH'] = '${TEST_CLASSPATH_MANAGED}'
  878. elif ymake_java_test:
  879. test_record['TEST_CLASSPATH'] = '${DART_CLASSPATH}'
  880. test_record['TEST_CLASSPATH_DEPS'] = '${DART_CLASSPATH_DEPS}'
  881. if unit.get('UNITTEST_DIR'):
  882. test_record['TEST_JAR'] = '${UNITTEST_MOD}'
  883. else:
  884. test_record['TEST_JAR'] = '{}/{}.jar'.format(unit.get('MODDIR'), unit.get('REALPRJNAME'))
  885. data = dump_test(unit, test_record)
  886. if data:
  887. unit.set_property(['DART_DATA', data])
  888. def onjava_test_deps(unit, *args):
  889. if unit.get("TIDY") == "yes":
  890. # graph changed for clang_tidy tests
  891. return
  892. assert unit.get('MODULE_TYPE') is not None
  893. assert len(args) == 1
  894. mode = args[0]
  895. path = _common.get_norm_unit_path(unit)
  896. ymake_java_test = unit.get('YMAKE_JAVA_TEST') == 'yes'
  897. test_record = {
  898. 'SOURCE-FOLDER-PATH': path,
  899. 'TEST-NAME': '-'.join([os.path.basename(os.path.dirname(path)), os.path.basename(path), 'dependencies']).strip(
  900. '-'
  901. ),
  902. 'SCRIPT-REL-PATH': 'java.dependency.test',
  903. 'TEST-TIMEOUT': '',
  904. 'TESTED-PROJECT-NAME': path,
  905. 'TEST-DATA': '',
  906. 'TEST_PARTITION': 'SEQUENTIAL',
  907. 'FORK-MODE': '',
  908. 'SPLIT-FACTOR': '',
  909. 'CUSTOM-DEPENDENCIES': ' '.join(get_values_list(unit, 'TEST_DEPENDS_VALUE')),
  910. 'TAG': '',
  911. 'SIZE': 'SMALL',
  912. 'IGNORE_CLASSPATH_CLASH': ' '.join(get_values_list(unit, 'JAVA_IGNORE_CLASSPATH_CLASH_VALUE')),
  913. # JTEST/JTEST_FOR only
  914. 'MODULE_TYPE': unit.get('MODULE_TYPE'),
  915. 'UNITTEST_DIR': '',
  916. 'SYSTEM_PROPERTIES': '',
  917. 'TEST-CWD': '',
  918. }
  919. if mode == 'strict':
  920. test_record['STRICT_CLASSPATH_CLASH'] = 'yes'
  921. if ymake_java_test:
  922. test_record['CLASSPATH'] = '$B/{}/{}.jar ${{DART_CLASSPATH}}'.format(
  923. unit.get('MODDIR'), unit.get('REALPRJNAME')
  924. )
  925. data = dump_test(unit, test_record)
  926. unit.set_property(['DART_DATA', data])
  927. def _get_test_tags(unit, spec_args=None):
  928. if spec_args is None:
  929. spec_args = {}
  930. tags = spec_args.get('TAG', []) + get_values_list(unit, 'TEST_TAGS_VALUE')
  931. tags = set(tags)
  932. if unit.get('EXPORT_SEM') == 'yes':
  933. filter_only_tags = sorted(t for t in tags if ':' not in t)
  934. unit.set(['FILTER_ONLY_TEST_TAGS', ' '.join(filter_only_tags)])
  935. # DEVTOOLS-7571
  936. if unit.get('SKIP_TEST_VALUE') and consts.YaTestTags.Fat in tags:
  937. tags.add(consts.YaTestTags.NotAutocheck)
  938. return tags
  939. def _dump_test(
  940. unit,
  941. test_type,
  942. test_files,
  943. timeout,
  944. test_dir,
  945. custom_deps,
  946. test_data,
  947. python_paths,
  948. split_factor,
  949. fork_mode,
  950. test_size,
  951. tags,
  952. requirements,
  953. binary_path='',
  954. old_pytest=False,
  955. test_cwd=None,
  956. runner_bin=None,
  957. yt_spec=None,
  958. data_files=None,
  959. ):
  960. if test_type == "PY_TEST":
  961. script_rel_path = "py.test"
  962. else:
  963. script_rel_path = test_type
  964. unit_path = unit.path()
  965. fork_test_files = unit.get('FORK_TEST_FILES_MODE')
  966. fork_mode = ' '.join(fork_mode) if fork_mode else ''
  967. use_arcadia_python = unit.get('USE_ARCADIA_PYTHON')
  968. if test_cwd:
  969. test_cwd = test_cwd.replace("$TEST_CWD_VALUE", "").replace('"MACRO_CALLS_DELIM"', "").strip()
  970. test_name = os.path.basename(binary_path)
  971. test_record = {
  972. 'TEST-NAME': os.path.splitext(test_name)[0],
  973. 'TEST-TIMEOUT': timeout,
  974. 'SCRIPT-REL-PATH': script_rel_path,
  975. 'TESTED-PROJECT-NAME': test_name,
  976. 'SOURCE-FOLDER-PATH': test_dir,
  977. 'CUSTOM-DEPENDENCIES': " ".join(custom_deps),
  978. 'TEST-ENV': prepare_env(unit.get("TEST_ENV_VALUE")),
  979. # 'TEST-PRESERVE-ENV': 'da',
  980. 'TEST-DATA': serialize_list(sorted(_common.filter_out_by_keyword(test_data, 'AUTOUPDATED'))),
  981. 'TEST-RECIPES': prepare_recipes(unit.get("TEST_RECIPES_VALUE")),
  982. 'SPLIT-FACTOR': split_factor,
  983. 'TEST_PARTITION': unit.get('TEST_PARTITION') or 'SEQUENTIAL',
  984. 'FORK-MODE': fork_mode,
  985. 'FORK-TEST-FILES': fork_test_files,
  986. 'TEST-FILES': serialize_list(test_files),
  987. 'SIZE': test_size,
  988. 'TAG': serialize_list(sorted(tags)),
  989. 'REQUIREMENTS': serialize_list(requirements),
  990. 'USE_ARCADIA_PYTHON': use_arcadia_python or '',
  991. 'OLD_PYTEST': 'yes' if old_pytest else 'no',
  992. 'PYTHON-PATHS': serialize_list(python_paths),
  993. 'TEST-CWD': test_cwd or '',
  994. 'SKIP_TEST': unit.get('SKIP_TEST_VALUE') or '',
  995. 'BUILD-FOLDER-PATH': _common.strip_roots(unit_path),
  996. 'BLOB': unit.get('TEST_BLOB_DATA') or '',
  997. 'CANONIZE_SUB_PATH': unit.get('CANONIZE_SUB_PATH') or '',
  998. }
  999. if binary_path:
  1000. test_record['BINARY-PATH'] = _common.strip_roots(binary_path)
  1001. if runner_bin:
  1002. test_record['TEST-RUNNER-BIN'] = runner_bin
  1003. if yt_spec:
  1004. test_record['YT-SPEC'] = serialize_list(yt_spec)
  1005. data = dump_test(unit, test_record)
  1006. if data:
  1007. unit.set_property(["DART_DATA", data])
  1008. def onsetup_pytest_bin(unit, *args):
  1009. use_arcadia_python = unit.get('USE_ARCADIA_PYTHON') == "yes"
  1010. if use_arcadia_python:
  1011. unit.onresource(['-', 'PY_MAIN={}'.format("library.python.pytest.main:main")]) # XXX
  1012. unit.onadd_pytest_bin(list(args))
  1013. else:
  1014. unit.onno_platform()
  1015. unit.onadd_pytest_script(["PY_TEST"])
  1016. def onrun(unit, *args):
  1017. exectest_cmd = unit.get(["EXECTEST_COMMAND_VALUE"]) or ''
  1018. exectest_cmd += "\n" + subprocess.list2cmdline(args)
  1019. unit.set(["EXECTEST_COMMAND_VALUE", exectest_cmd])
  1020. def onsetup_exectest(unit, *args):
  1021. command = unit.get(["EXECTEST_COMMAND_VALUE"])
  1022. if command is None:
  1023. ymake.report_configure_error("EXECTEST must have at least one RUN macro")
  1024. return
  1025. command = command.replace("$EXECTEST_COMMAND_VALUE", "")
  1026. if "PYTHON_BIN" in command:
  1027. unit.ondepends('contrib/tools/python')
  1028. unit.set(["TEST_BLOB_DATA", base64.b64encode(six.ensure_binary(command))])
  1029. add_test_to_dart(unit, "exectest", binary_path=os.path.join(unit.path(), unit.filename()).replace(".pkg", ""))
  1030. def onsetup_run_python(unit):
  1031. if unit.get("USE_ARCADIA_PYTHON") == "yes":
  1032. unit.ondepends('contrib/tools/python')
  1033. def get_canonical_test_resources(unit):
  1034. unit_path = unit.path()
  1035. if unit.get("CUSTOM_CANONDATA_PATH"):
  1036. path_to_canondata = unit_path.replace("$S", unit.get("CUSTOM_CANONDATA_PATH"))
  1037. else:
  1038. path_to_canondata = unit.resolve(unit_path)
  1039. canon_data_dir = os.path.join(path_to_canondata, CANON_DATA_DIR_NAME, unit.get('CANONIZE_SUB_PATH') or '')
  1040. try:
  1041. _, dirs, files = next(os.walk(canon_data_dir))
  1042. except StopIteration:
  1043. # path doesn't exist
  1044. return [], []
  1045. if CANON_RESULT_FILE_NAME in files:
  1046. return _get_canonical_data_resources_v2(os.path.join(canon_data_dir, CANON_RESULT_FILE_NAME), unit_path)
  1047. return [], []
  1048. def _load_canonical_file(filename, unit_path):
  1049. try:
  1050. with open(filename, 'rb') as results_file:
  1051. return json.load(results_file)
  1052. except Exception as e:
  1053. print("malformed canonical data in {}: {} ({})".format(unit_path, e, filename), file=sys.stderr)
  1054. return {}
  1055. def _get_resource_from_uri(uri):
  1056. m = consts.CANON_MDS_RESOURCE_REGEX.match(uri)
  1057. if m:
  1058. key = m.group(1)
  1059. return "{}:{}".format(consts.MDS_SCHEME, key)
  1060. m = consts.CANON_BACKEND_RESOURCE_REGEX.match(uri)
  1061. if m:
  1062. key = m.group(1)
  1063. return "{}:{}".format(consts.MDS_SCHEME, key)
  1064. m = consts.CANON_SBR_RESOURCE_REGEX.match(uri)
  1065. if m:
  1066. # There might be conflict between resources, because all resources in sandbox have 'resource.tar.gz' name
  1067. # That's why we use notation with '=' to specify specific path for resource
  1068. uri = m.group(1)
  1069. res_id = m.group(2)
  1070. return "{}={}".format(uri, '/'.join([CANON_OUTPUT_STORAGE, res_id]))
  1071. def _get_external_resources_from_canon_data(data):
  1072. # Method should work with both canonization versions:
  1073. # result.json: {'uri':X 'checksum':Y}
  1074. # result.json: {'testname': {'uri':X 'checksum':Y}}
  1075. # result.json: {'testname': [{'uri':X 'checksum':Y}]}
  1076. # Also there is a bug - if user returns {'uri': 1} from test - machinery will fail
  1077. # That's why we check 'uri' and 'checksum' fields presence
  1078. # (it's still a bug - user can return {'uri':X, 'checksum': Y}, we need to unify canonization format)
  1079. res = set()
  1080. if isinstance(data, dict):
  1081. if 'uri' in data and 'checksum' in data:
  1082. resource = _get_resource_from_uri(data['uri'])
  1083. if resource:
  1084. res.add(resource)
  1085. else:
  1086. for k, v in six.iteritems(data):
  1087. res.update(_get_external_resources_from_canon_data(v))
  1088. elif isinstance(data, list):
  1089. for e in data:
  1090. res.update(_get_external_resources_from_canon_data(e))
  1091. return res
  1092. def _get_canonical_data_resources_v2(filename, unit_path):
  1093. return (_get_external_resources_from_canon_data(_load_canonical_file(filename, unit_path)), [filename])
  1094. def on_add_linter_check(unit, *args):
  1095. if unit.get("TIDY") == "yes":
  1096. return
  1097. source_root_from_prefix = '${ARCADIA_ROOT}/'
  1098. source_root_to_prefix = '$S/'
  1099. unlimited = -1
  1100. no_lint_value = _common.get_no_lint_value(unit)
  1101. if no_lint_value in ("none", "none_internal"):
  1102. return
  1103. keywords = {
  1104. "DEPENDS": unlimited,
  1105. "FILES": unlimited,
  1106. "CONFIGS": unlimited,
  1107. "GLOBAL_RESOURCES": unlimited,
  1108. "FILE_PROCESSING_TIME": 1,
  1109. "EXTRA_PARAMS": unlimited,
  1110. }
  1111. flat_args, spec_args = _common.sort_by_keywords(keywords, args)
  1112. if len(flat_args) != 2:
  1113. unit.message(['ERROR', '_ADD_LINTER_CHECK params: expected 2 free parameters'])
  1114. return
  1115. configs = []
  1116. for cfg in spec_args.get('CONFIGS', []):
  1117. filename = unit.resolve(source_root_to_prefix + cfg)
  1118. if not os.path.exists(filename):
  1119. unit.message(['ERROR', 'Configuration file {} is not found'.format(filename)])
  1120. return
  1121. configs.append(cfg)
  1122. deps = []
  1123. lint_name, linter = flat_args
  1124. deps.append(os.path.dirname(linter))
  1125. test_files = []
  1126. for path in spec_args.get('FILES', []):
  1127. if path.startswith(source_root_from_prefix):
  1128. test_files.append(path.replace(source_root_from_prefix, source_root_to_prefix, 1))
  1129. elif path.startswith(source_root_to_prefix):
  1130. test_files.append(path)
  1131. if lint_name == 'cpp_style':
  1132. cpp_extensions = ["cpp", "cxx", "cc", "c"]
  1133. header_extensions = ["h", "hh", "hpp"]
  1134. files_dart = reference_group_var("ALL_SRCS", cpp_extensions + header_extensions)
  1135. else:
  1136. if not test_files:
  1137. unit.message(['WARN', 'No files to lint for {}'.format(lint_name)])
  1138. return
  1139. files_dart = serialize_list(test_files)
  1140. for arg in spec_args.get('EXTRA_PARAMS', []):
  1141. if '=' not in arg:
  1142. unit.message(['WARN', 'Wrong EXTRA_PARAMS value: "{}". Values must have format "name=value".'.format(arg)])
  1143. return
  1144. deps += spec_args.get('DEPENDS', [])
  1145. for dep in deps:
  1146. unit.ondepends(dep)
  1147. for resource in spec_args.get('GLOBAL_RESOURCES', []):
  1148. unit.onpeerdir(resource)
  1149. test_record = {
  1150. 'TEST-NAME': lint_name,
  1151. 'SCRIPT-REL-PATH': 'custom_lint',
  1152. 'TESTED-PROJECT-NAME': unit.name(),
  1153. 'SOURCE-FOLDER-PATH': _common.get_norm_unit_path(unit),
  1154. 'CUSTOM-DEPENDENCIES': " ".join(deps),
  1155. 'TEST-DATA': '',
  1156. 'TEST-ENV': prepare_env(unit.get("TEST_ENV_VALUE")),
  1157. 'TEST-TIMEOUT': '',
  1158. 'SPLIT-FACTOR': '',
  1159. 'TEST_PARTITION': 'SEQUENTIAL',
  1160. 'FORK-MODE': '',
  1161. 'FORK-TEST-FILES': '',
  1162. 'SIZE': 'SMALL',
  1163. 'TAG': '',
  1164. 'USE_ARCADIA_PYTHON': unit.get('USE_ARCADIA_PYTHON') or '',
  1165. 'OLD_PYTEST': 'no',
  1166. 'PYTHON-PATHS': '',
  1167. # TODO remove FILES, see DEVTOOLS-7052
  1168. 'FILES': files_dart,
  1169. 'TEST-FILES': files_dart,
  1170. # Linter specific parameters
  1171. # TODO Add configs to DATA. See YMAKE-427
  1172. 'LINT-CONFIGS': serialize_list(configs),
  1173. 'LINT-NAME': lint_name,
  1174. 'LINT-FILE-PROCESSING-TIME': spec_args.get('FILE_PROCESSING_TIME', [''])[0],
  1175. 'LINT-EXTRA-PARAMS': serialize_list(spec_args.get('EXTRA_PARAMS', [])),
  1176. 'LINTER': linter,
  1177. }
  1178. data = dump_test(unit, test_record)
  1179. if data:
  1180. unit.set_property(["DART_DATA", data])