ytest.py 51 KB

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