ytest.py 50 KB

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