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. MDS_URI_PREFIX = 'https://storage.yandex-team.ru/get-devtools/'
  21. MDS_SCHEME = 'mds'
  22. CANON_DATA_DIR_NAME = 'canondata'
  23. CANON_OUTPUT_STORAGE = 'canondata_storage'
  24. CANON_RESULT_FILE_NAME = 'result.json'
  25. CANON_MDS_RESOURCE_REGEX = re.compile(re.escape(MDS_URI_PREFIX) + r'(.*?)($|#)')
  26. CANON_SBR_RESOURCE_REGEX = re.compile(r'(sbr:/?/?(\d+))')
  27. BLOCK_SEPARATOR = '============================================================='
  28. SPLIT_FACTOR_MAX_VALUE = 1000
  29. SPLIT_FACTOR_TEST_FILES_MAX_VALUE = 4250
  30. PARTITION_MODS = ('SEQUENTIAL', 'MODULO')
  31. DEFAULT_TIDY_CONFIG = "build/config/tests/clang_tidy/config.yaml"
  32. DEFAULT_TIDY_CONFIG_MAP_PATH = "build/yandex_specific/config/clang_tidy/tidy_default_map.json"
  33. PROJECT_TIDY_CONFIG_MAP_PATH = "build/yandex_specific/config/clang_tidy/tidy_project_map.json"
  34. tidy_config_map = None
  35. def ontest_data(unit, *args):
  36. ymake.report_configure_error("TEST_DATA is removed in favour of DATA")
  37. def prepare_recipes(data):
  38. data = data.replace('"USE_RECIPE_DELIM"', "\n")
  39. data = data.replace("$TEST_RECIPES_VALUE", "")
  40. return base64.b64encode(six.ensure_binary(data or ""))
  41. def prepare_env(data):
  42. data = data.replace("$TEST_ENV_VALUE", "")
  43. return serialize_list(shlex.split(data))
  44. def is_yt_spec_contain_pool_info(filename): # XXX switch to yson in ymake + perf test for configure
  45. pool_re = re.compile(r"""['"]*pool['"]*\s*?=""")
  46. cypress_root_re = re.compile(r"""['"]*cypress_root['"]*\s*=""")
  47. with open(filename, 'r') as afile:
  48. yt_spec = afile.read()
  49. return pool_re.search(yt_spec) and cypress_root_re.search(yt_spec)
  50. def validate_test(unit, kw):
  51. def get_list(key):
  52. return deserialize_list(kw.get(key, ""))
  53. valid_kw = copy.deepcopy(kw)
  54. errors = []
  55. warnings = []
  56. if valid_kw.get('SCRIPT-REL-PATH') == 'boost.test':
  57. project_path = valid_kw.get('BUILD-FOLDER-PATH', "")
  58. if not project_path.startswith(
  59. ("contrib", "mail", "maps", "tools/idl", "metrika", "devtools", "mds", "yandex_io", "smart_devices")
  60. ):
  61. errors.append("BOOSTTEST is not allowed here")
  62. size_timeout = collections.OrderedDict(sorted(consts.TestSize.DefaultTimeouts.items(), key=lambda t: t[1]))
  63. size = valid_kw.get('SIZE', consts.TestSize.Small).lower()
  64. tags = set(get_list("TAG"))
  65. requirements_orig = get_list("REQUIREMENTS")
  66. in_autocheck = consts.YaTestTags.NotAutocheck not in tags and consts.YaTestTags.Manual not in tags
  67. is_fat = consts.YaTestTags.Fat in tags
  68. is_force_sandbox = consts.YaTestTags.ForceDistbuild not in tags and is_fat
  69. is_ytexec_run = consts.YaTestTags.YtRunner in tags
  70. is_fuzzing = valid_kw.get("FUZZING", False)
  71. is_kvm = 'kvm' in requirements_orig
  72. requirements = {}
  73. secret_requirements = ('sb_vault', 'yav')
  74. list_requirements = secret_requirements
  75. for req in requirements_orig:
  76. if req in ('kvm',):
  77. requirements[req] = str(True)
  78. continue
  79. if ":" in req:
  80. req_name, req_value = req.split(":", 1)
  81. if req_name in list_requirements:
  82. requirements[req_name] = ",".join(filter(None, [requirements.get(req_name), req_value]))
  83. else:
  84. if req_name in requirements:
  85. if req_value in ["0"]:
  86. warnings.append(
  87. "Requirement [[imp]]{}[[rst]] is dropped [[imp]]{}[[rst]] -> [[imp]]{}[[rst]]".format(
  88. req_name, requirements[req_name], req_value
  89. )
  90. )
  91. del requirements[req_name]
  92. elif requirements[req_name] != req_value:
  93. warnings.append(
  94. "Requirement [[imp]]{}[[rst]] is redefined [[imp]]{}[[rst]] -> [[imp]]{}[[rst]]".format(
  95. req_name, requirements[req_name], req_value
  96. )
  97. )
  98. requirements[req_name] = req_value
  99. else:
  100. requirements[req_name] = req_value
  101. else:
  102. errors.append("Invalid requirement syntax [[imp]]{}[[rst]]: expect <requirement>:<value>".format(req))
  103. if not errors:
  104. for req_name, req_value in requirements.items():
  105. try:
  106. error_msg = reqs.validate_requirement(
  107. req_name,
  108. req_value,
  109. size,
  110. is_force_sandbox,
  111. in_autocheck,
  112. is_fuzzing,
  113. is_kvm,
  114. is_ytexec_run,
  115. requirements,
  116. )
  117. except Exception as e:
  118. error_msg = str(e)
  119. if error_msg:
  120. errors += [error_msg]
  121. invalid_requirements_for_distbuild = [
  122. requirement for requirement in requirements.keys() if requirement not in ('ram', 'ram_disk', 'cpu', 'network')
  123. ]
  124. sb_tags = []
  125. # XXX Unfortunately, some users have already started using colons
  126. # in their tag names. Use skip set to avoid treating their tag as system ones.
  127. # Remove this check when all such user tags are removed.
  128. skip_set = ('ynmt_benchmark', 'bert_models', 'zeliboba_map')
  129. # Verify the prefixes of the system tags to avoid pointless use of the REQUIREMENTS macro parameters in the TAG macro.
  130. for tag in tags:
  131. if tag.startswith('sb:'):
  132. sb_tags.append(tag)
  133. elif ':' in tag and not tag.startswith('ya:') and tag.split(':')[0] not in skip_set:
  134. errors.append("Only [[imp]]sb:[[rst]] and [[imp]]ya:[[rst]] prefixes are allowed in system tags: {}".format(tag))
  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(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 ("unittest.py", "gunittest", "g_benchmark", "go.test", "boost.test", "fuzz.test")
  382. if is_implicit_data_needed and unit.get('ADD_SRCDIR_TO_TEST_DATA') == "yes":
  383. unit.ondata_files(_common.get_norm_unit_path(unit))
  384. if flat_args[1] == "fuzz.test":
  385. unit.ondata_files("fuzzing/{}/corpus.json".format(_common.get_norm_unit_path(unit)))
  386. if not flat_args[1] in ("unittest.py", "gunittest", "g_benchmark"):
  387. unit.ondata_files(get_unit_list_variable(unit, 'TEST_YT_SPEC_VALUE'))
  388. test_data = sorted(
  389. _common.filter_out_by_keyword(
  390. spec_args.get('DATA', []) + get_norm_paths(unit, 'TEST_DATA_VALUE'), 'AUTOUPDATED'
  391. )
  392. )
  393. if flat_args[1] == "go.test":
  394. data, _ = get_canonical_test_resources(unit)
  395. test_data += data
  396. elif flat_args[1] == "coverage.extractor" and not match_coverage_extractor_requirements(unit):
  397. # XXX
  398. # Current ymake implementation doesn't allow to call macro inside the 'when' body
  399. # that's why we add ADD_YTEST(coverage.extractor) to every PROGRAM entry and check requirements later
  400. return
  401. elif flat_args[1] == "clang_tidy" and unit.get("TIDY_ENABLED") != "yes":
  402. # Graph is not prepared
  403. return
  404. elif unit.get("TIDY") == "yes" and unit.get("TIDY_ENABLED") != "yes":
  405. # clang_tidy disabled for module
  406. return
  407. elif flat_args[1] == "no.test":
  408. return
  409. test_size = ''.join(spec_args.get('SIZE', [])) or unit.get('TEST_SIZE_NAME') or ''
  410. test_tags = serialize_list(sorted(_get_test_tags(unit, spec_args)))
  411. test_timeout = ''.join(spec_args.get('TIMEOUT', [])) or unit.get('TEST_TIMEOUT') or ''
  412. test_requirements = spec_args.get('REQUIREMENTS', []) + get_values_list(unit, 'TEST_REQUIREMENTS_VALUE')
  413. if flat_args[1] != "clang_tidy" and unit.get("TIDY_ENABLED") == "yes":
  414. # graph changed for clang_tidy tests
  415. if flat_args[1] in ("unittest.py", "gunittest", "g_benchmark"):
  416. flat_args[1] = "clang_tidy"
  417. test_size = 'SMALL'
  418. test_tags = ''
  419. test_timeout = "60"
  420. test_requirements = []
  421. unit.set(["TEST_YT_SPEC_VALUE", ""])
  422. else:
  423. return
  424. if flat_args[1] == "clang_tidy" and unit.get("TIDY_ENABLED") == "yes":
  425. if unit.get("TIDY_CONFIG"):
  426. default_config_path = unit.get("TIDY_CONFIG")
  427. project_config_path = unit.get("TIDY_CONFIG")
  428. else:
  429. default_config_path = get_default_tidy_config(unit)
  430. project_config_path = get_project_tidy_config(unit)
  431. unit.set(["DEFAULT_TIDY_CONFIG", default_config_path])
  432. unit.set(["PROJECT_TIDY_CONFIG", project_config_path])
  433. fork_mode = []
  434. if 'FORK_SUBTESTS' in spec_args:
  435. fork_mode.append('subtests')
  436. if 'FORK_TESTS' in spec_args:
  437. fork_mode.append('tests')
  438. fork_mode = fork_mode or spec_args.get('FORK_MODE', []) or unit.get('TEST_FORK_MODE').split()
  439. fork_mode = ' '.join(fork_mode) if fork_mode else ''
  440. unit_path = _common.get_norm_unit_path(unit)
  441. test_record = {
  442. 'TEST-NAME': flat_args[0],
  443. 'SCRIPT-REL-PATH': flat_args[1],
  444. 'TESTED-PROJECT-NAME': unit.name(),
  445. 'TESTED-PROJECT-FILENAME': unit.filename(),
  446. 'SOURCE-FOLDER-PATH': unit_path,
  447. # TODO get rid of BUILD-FOLDER-PATH
  448. 'BUILD-FOLDER-PATH': unit_path,
  449. 'BINARY-PATH': "{}/{}".format(unit_path, unit.filename()),
  450. 'GLOBAL-LIBRARY-PATH': unit.global_filename(),
  451. 'CUSTOM-DEPENDENCIES': ' '.join(spec_args.get('DEPENDS', []) + get_values_list(unit, 'TEST_DEPENDS_VALUE')),
  452. 'TEST-RECIPES': prepare_recipes(unit.get("TEST_RECIPES_VALUE")),
  453. 'TEST-ENV': prepare_env(unit.get("TEST_ENV_VALUE")),
  454. # 'TEST-PRESERVE-ENV': 'da',
  455. 'TEST-DATA': serialize_list(sorted(test_data)),
  456. 'TEST-TIMEOUT': test_timeout,
  457. 'FORK-MODE': fork_mode,
  458. 'SPLIT-FACTOR': ''.join(spec_args.get('SPLIT_FACTOR', [])) or unit.get('TEST_SPLIT_FACTOR') or '',
  459. 'SIZE': test_size,
  460. 'TAG': test_tags,
  461. 'REQUIREMENTS': serialize_list(test_requirements),
  462. 'TEST-CWD': unit.get('TEST_CWD_VALUE') or '',
  463. 'FUZZ-DICTS': serialize_list(
  464. spec_args.get('FUZZ_DICTS', []) + get_unit_list_variable(unit, 'FUZZ_DICTS_VALUE')
  465. ),
  466. 'FUZZ-OPTS': serialize_list(spec_args.get('FUZZ_OPTS', []) + get_unit_list_variable(unit, 'FUZZ_OPTS_VALUE')),
  467. 'YT-SPEC': serialize_list(spec_args.get('YT_SPEC', []) + get_unit_list_variable(unit, 'TEST_YT_SPEC_VALUE')),
  468. 'BLOB': unit.get('TEST_BLOB_DATA') or '',
  469. 'SKIP_TEST': unit.get('SKIP_TEST_VALUE') or '',
  470. 'TEST_IOS_DEVICE_TYPE': unit.get('TEST_IOS_DEVICE_TYPE_VALUE') or '',
  471. 'TEST_IOS_RUNTIME_TYPE': unit.get('TEST_IOS_RUNTIME_TYPE_VALUE') or '',
  472. 'ANDROID_APK_TEST_ACTIVITY': unit.get('ANDROID_APK_TEST_ACTIVITY_VALUE') or '',
  473. 'TEST_PARTITION': unit.get("TEST_PARTITION") or 'SEQUENTIAL',
  474. 'GO_BENCH_TIMEOUT': unit.get('GO_BENCH_TIMEOUT') or '',
  475. }
  476. if flat_args[1] == "go.bench":
  477. if "ya:run_go_benchmark" not in test_record["TAG"]:
  478. return
  479. else:
  480. test_record["TEST-NAME"] += "_bench"
  481. elif flat_args[1] in ("g_benchmark", "y_benchmark"):
  482. benchmark_opts = get_unit_list_variable(unit, 'BENCHMARK_OPTS_VALUE')
  483. test_record['BENCHMARK-OPTS'] = serialize_list(benchmark_opts)
  484. elif flat_args[1] == 'fuzz.test' and unit.get('FUZZING') == 'yes':
  485. test_record['FUZZING'] = '1'
  486. # use all cores if fuzzing requested
  487. test_record['REQUIREMENTS'] = serialize_list(
  488. filter(None, deserialize_list(test_record['REQUIREMENTS']) + ["cpu:all", "ram:all"])
  489. )
  490. data = dump_test(unit, test_record)
  491. if data:
  492. unit.set_property(["DART_DATA", data])
  493. def java_srcdirs_to_data(unit, var):
  494. extra_data = []
  495. for srcdir in (unit.get(var) or '').replace('$' + var, '').split():
  496. if srcdir == '.':
  497. srcdir = unit.get('MODDIR')
  498. if srcdir.startswith('${ARCADIA_ROOT}/') or srcdir.startswith('$ARCADIA_ROOT/'):
  499. srcdir = srcdir.replace('${ARCADIA_ROOT}/', '$S/')
  500. srcdir = srcdir.replace('$ARCADIA_ROOT/', '$S/')
  501. if srcdir.startswith('${CURDIR}') or srcdir.startswith('$CURDIR'):
  502. srcdir = srcdir.replace('${CURDIR}', os.path.join('$S', unit.get('MODDIR')))
  503. srcdir = srcdir.replace('$CURDIR', os.path.join('$S', unit.get('MODDIR')))
  504. srcdir = unit.resolve_arc_path(srcdir)
  505. if not srcdir.startswith('$'):
  506. srcdir = os.path.join('$S', unit.get('MODDIR'), srcdir)
  507. if srcdir.startswith('$S'):
  508. extra_data.append(srcdir.replace('$S', 'arcadia'))
  509. return serialize_list(extra_data)
  510. def onadd_check(unit, *args):
  511. if unit.get("TIDY") == "yes":
  512. # graph changed for clang_tidy tests
  513. return
  514. flat_args, spec_args = _common.sort_by_keywords(
  515. {
  516. "DEPENDS": -1,
  517. "TIMEOUT": 1,
  518. "DATA": -1,
  519. "TAG": -1,
  520. "REQUIREMENTS": -1,
  521. "FORK_MODE": 1,
  522. "SPLIT_FACTOR": 1,
  523. "FORK_SUBTESTS": 0,
  524. "FORK_TESTS": 0,
  525. "SIZE": 1,
  526. },
  527. args,
  528. )
  529. check_type = flat_args[0]
  530. if check_type in ("check.data", "check.resource") and unit.get('VALIDATE_DATA') == "no":
  531. return
  532. if check_type == "check.external" and (len(flat_args) == 1 or not flat_args[1]):
  533. return
  534. test_dir = _common.get_norm_unit_path(unit)
  535. test_timeout = ''
  536. fork_mode = ''
  537. extra_test_data = ''
  538. extra_test_dart_data = {}
  539. ymake_java_test = unit.get('YMAKE_JAVA_TEST') == 'yes'
  540. use_arcadia_python = unit.get('USE_ARCADIA_PYTHON')
  541. uid_ext = ''
  542. script_rel_path = check_type
  543. test_files = flat_args[1:]
  544. if check_type in ["check.data", "check.resource"]:
  545. uid_ext = unit.get("SBR_UID_EXT").split(" ", 1)[-1] # strip variable name
  546. if check_type in ["flake8.py2", "flake8.py3", "black"]:
  547. fork_mode = unit.get('TEST_FORK_MODE') or ''
  548. elif check_type == "ktlint":
  549. test_timeout = '120'
  550. ktlint_binary = '$(KTLINT_OLD)/run.bat' if unit.get('_USE_KTLINT_OLD') == 'yes' else '$(KTLINT)/run.bat'
  551. extra_test_dart_data['KTLINT_BINARY'] = ktlint_binary
  552. elif check_type == "JAVA_STYLE":
  553. if ymake_java_test and not unit.get('ALL_SRCDIRS') or '':
  554. return
  555. if len(flat_args) < 2:
  556. raise Exception("Not enough arguments for JAVA_STYLE check")
  557. check_level = flat_args[1]
  558. allowed_levels = {
  559. 'base': '/yandex_checks.xml',
  560. 'strict': '/yandex_checks_strict.xml',
  561. 'extended': '/yandex_checks_extended.xml',
  562. 'library': '/yandex_checks_library.xml',
  563. }
  564. if check_level not in allowed_levels:
  565. raise Exception("'{}' is not allowed in LINT(), use one of {}".format(check_level, allowed_levels.keys()))
  566. test_files[0] = allowed_levels[check_level] # replace check_level with path to config file
  567. script_rel_path = "java.style"
  568. test_timeout = '240'
  569. fork_mode = unit.get('TEST_FORK_MODE') or ''
  570. if ymake_java_test:
  571. extra_test_data = java_srcdirs_to_data(unit, 'ALL_SRCDIRS')
  572. # jstyle should use the latest jdk
  573. unit.onpeerdir([unit.get('JDK_LATEST_PEERDIR')])
  574. extra_test_dart_data['JDK_LATEST_VERSION'] = unit.get('JDK_LATEST_VERSION')
  575. # TODO remove when ya-bin will be released (https://st.yandex-team.ru/DEVTOOLS-9611)
  576. extra_test_dart_data['JDK_RESOURCE'] = 'JDK' + (
  577. unit.get('JDK_VERSION') or unit.get('JDK_REAL_VERSION') or '_DEFAULT'
  578. )
  579. elif check_type == "gofmt":
  580. if test_files:
  581. test_dir = os.path.dirname(test_files[0]).lstrip("$S/")
  582. elif check_type == "check.data":
  583. data_re = re.compile(r"sbr:/?/?(\d+)=?.*")
  584. data = flat_args[1:]
  585. resources = []
  586. for f in data:
  587. matched = re.match(data_re, f)
  588. if matched:
  589. resources.append(matched.group(1))
  590. if resources:
  591. test_files = resources
  592. else:
  593. return
  594. serialized_test_files = serialize_list(test_files)
  595. test_record = {
  596. 'TEST-NAME': check_type.lower(),
  597. 'TEST-TIMEOUT': test_timeout,
  598. 'SCRIPT-REL-PATH': script_rel_path,
  599. 'TESTED-PROJECT-NAME': os.path.basename(test_dir),
  600. 'SOURCE-FOLDER-PATH': test_dir,
  601. 'CUSTOM-DEPENDENCIES': " ".join(spec_args.get('DEPENDS', [])),
  602. 'TEST-DATA': extra_test_data,
  603. 'TEST-ENV': prepare_env(unit.get("TEST_ENV_VALUE")),
  604. 'SBR-UID-EXT': uid_ext,
  605. 'SPLIT-FACTOR': '',
  606. 'TEST_PARTITION': 'SEQUENTIAL',
  607. 'FORK-MODE': fork_mode,
  608. 'FORK-TEST-FILES': '',
  609. 'SIZE': 'SMALL',
  610. 'TAG': '',
  611. 'REQUIREMENTS': " ".join(spec_args.get('REQUIREMENTS', [])),
  612. 'USE_ARCADIA_PYTHON': use_arcadia_python or '',
  613. 'OLD_PYTEST': 'no',
  614. 'PYTHON-PATHS': '',
  615. # TODO remove FILES, see DEVTOOLS-7052
  616. 'FILES': serialized_test_files,
  617. 'TEST-FILES': serialized_test_files,
  618. }
  619. test_record.update(extra_test_dart_data)
  620. data = dump_test(unit, test_record)
  621. if data:
  622. unit.set_property(["DART_DATA", data])
  623. def on_register_no_check_imports(unit):
  624. s = unit.get('NO_CHECK_IMPORTS_FOR_VALUE')
  625. if s not in ('', 'None'):
  626. unit.onresource(['-', 'py/no_check_imports/{}="{}"'.format(_common.pathid(s), s)])
  627. def onadd_check_py_imports(unit, *args):
  628. if unit.get("TIDY") == "yes":
  629. # graph changed for clang_tidy tests
  630. return
  631. if unit.get('NO_CHECK_IMPORTS_FOR_VALUE').strip() == "":
  632. return
  633. unit.onpeerdir(['library/python/testing/import_test'])
  634. check_type = "py.imports"
  635. test_dir = _common.get_norm_unit_path(unit)
  636. use_arcadia_python = unit.get('USE_ARCADIA_PYTHON')
  637. test_files = serialize_list([_common.get_norm_unit_path(unit, unit.filename())])
  638. test_record = {
  639. 'TEST-NAME': "pyimports",
  640. 'TEST-TIMEOUT': '',
  641. 'SCRIPT-REL-PATH': check_type,
  642. 'TESTED-PROJECT-NAME': os.path.basename(test_dir),
  643. 'SOURCE-FOLDER-PATH': test_dir,
  644. 'CUSTOM-DEPENDENCIES': '',
  645. 'TEST-DATA': '',
  646. 'TEST-ENV': prepare_env(unit.get("TEST_ENV_VALUE")),
  647. 'SPLIT-FACTOR': '',
  648. 'TEST_PARTITION': 'SEQUENTIAL',
  649. 'FORK-MODE': '',
  650. 'FORK-TEST-FILES': '',
  651. 'SIZE': 'SMALL',
  652. 'TAG': '',
  653. 'USE_ARCADIA_PYTHON': use_arcadia_python or '',
  654. 'OLD_PYTEST': 'no',
  655. 'PYTHON-PATHS': '',
  656. # TODO remove FILES, see DEVTOOLS-7052
  657. 'FILES': test_files,
  658. 'TEST-FILES': test_files,
  659. }
  660. if unit.get('NO_CHECK_IMPORTS_FOR_VALUE') != "None":
  661. test_record["NO-CHECK"] = serialize_list(get_values_list(unit, 'NO_CHECK_IMPORTS_FOR_VALUE') or ["*"])
  662. else:
  663. test_record["NO-CHECK"] = ''
  664. data = dump_test(unit, test_record)
  665. if data:
  666. unit.set_property(["DART_DATA", data])
  667. def onadd_pytest_script(unit, *args):
  668. if unit.get("TIDY") == "yes":
  669. # graph changed for clang_tidy tests
  670. return
  671. unit.set(["PYTEST_BIN", "no"])
  672. custom_deps = get_values_list(unit, 'TEST_DEPENDS_VALUE')
  673. timeout = list(filter(None, [unit.get(["TEST_TIMEOUT"])]))
  674. if unit.get('ADD_SRCDIR_TO_TEST_DATA') == "yes":
  675. unit.ondata_files(_common.get_norm_unit_path(unit))
  676. if timeout:
  677. timeout = timeout[0]
  678. else:
  679. timeout = '0'
  680. test_type = args[0]
  681. fork_mode = unit.get('TEST_FORK_MODE').split() or ''
  682. split_factor = unit.get('TEST_SPLIT_FACTOR') or ''
  683. test_size = unit.get('TEST_SIZE_NAME') or ''
  684. test_files = get_values_list(unit, 'TEST_SRCS_VALUE')
  685. tags = _get_test_tags(unit)
  686. requirements = get_values_list(unit, 'TEST_REQUIREMENTS_VALUE')
  687. test_data = get_norm_paths(unit, 'TEST_DATA_VALUE')
  688. data, data_files = get_canonical_test_resources(unit)
  689. test_data += data
  690. python_paths = get_values_list(unit, 'TEST_PYTHON_PATH_VALUE')
  691. binary_path = os.path.join(_common.get_norm_unit_path(unit), unit.filename())
  692. test_cwd = unit.get('TEST_CWD_VALUE') or ''
  693. _dump_test(
  694. unit,
  695. test_type,
  696. test_files,
  697. timeout,
  698. _common.get_norm_unit_path(unit),
  699. custom_deps,
  700. test_data,
  701. python_paths,
  702. split_factor,
  703. fork_mode,
  704. test_size,
  705. tags,
  706. requirements,
  707. binary_path,
  708. test_cwd=test_cwd,
  709. data_files=data_files,
  710. )
  711. def onadd_pytest_bin(unit, *args):
  712. if unit.get("TIDY") == "yes":
  713. # graph changed for clang_tidy tests
  714. return
  715. flat, kws = _common.sort_by_keywords({'RUNNER_BIN': 1}, args)
  716. if flat:
  717. ymake.report_configure_error('Unknown arguments found while processing add_pytest_bin macro: {!r}'.format(flat))
  718. runner_bin = kws.get('RUNNER_BIN', [None])[0]
  719. test_type = 'py3test.bin' if (unit.get("PYTHON3") == 'yes') else "pytest.bin"
  720. add_test_to_dart(unit, test_type, runner_bin=runner_bin)
  721. def add_test_to_dart(unit, test_type, binary_path=None, runner_bin=None):
  722. if unit.get("TIDY") == "yes":
  723. # graph changed for clang_tidy tests
  724. return
  725. if unit.get('ADD_SRCDIR_TO_TEST_DATA') == "yes":
  726. unit.ondata_files(_common.get_norm_unit_path(unit))
  727. custom_deps = get_values_list(unit, 'TEST_DEPENDS_VALUE')
  728. timeout = list(filter(None, [unit.get(["TEST_TIMEOUT"])]))
  729. if timeout:
  730. timeout = timeout[0]
  731. else:
  732. timeout = '0'
  733. fork_mode = unit.get('TEST_FORK_MODE').split() or ''
  734. split_factor = unit.get('TEST_SPLIT_FACTOR') or ''
  735. test_size = unit.get('TEST_SIZE_NAME') or ''
  736. test_cwd = unit.get('TEST_CWD_VALUE') or ''
  737. yt_spec = get_values_list(unit, 'TEST_YT_SPEC_VALUE')
  738. unit.ondata_files(yt_spec)
  739. unit_path = unit.path()
  740. test_files = get_values_list(unit, 'TEST_SRCS_VALUE')
  741. tags = _get_test_tags(unit)
  742. requirements = get_values_list(unit, 'TEST_REQUIREMENTS_VALUE')
  743. test_data = get_norm_paths(unit, 'TEST_DATA_VALUE')
  744. data, data_files = get_canonical_test_resources(unit)
  745. test_data += data
  746. python_paths = get_values_list(unit, 'TEST_PYTHON_PATH_VALUE')
  747. if not binary_path:
  748. binary_path = os.path.join(unit_path, unit.filename())
  749. _dump_test(
  750. unit,
  751. test_type,
  752. test_files,
  753. timeout,
  754. _common.get_norm_unit_path(unit),
  755. custom_deps,
  756. test_data,
  757. python_paths,
  758. split_factor,
  759. fork_mode,
  760. test_size,
  761. tags,
  762. requirements,
  763. binary_path,
  764. test_cwd=test_cwd,
  765. runner_bin=runner_bin,
  766. yt_spec=yt_spec,
  767. data_files=data_files,
  768. )
  769. def extract_java_system_properties(unit, args):
  770. if len(args) % 2:
  771. return [], 'Wrong use of SYSTEM_PROPERTIES in {}: odd number of arguments'.format(unit.path())
  772. props = []
  773. for x, y in zip(args[::2], args[1::2]):
  774. if x == 'FILE':
  775. if y.startswith('${BINDIR}') or y.startswith('${ARCADIA_BUILD_ROOT}') or y.startswith('/'):
  776. return [], 'Wrong use of SYSTEM_PROPERTIES in {}: absolute/build file path {}'.format(unit.path(), y)
  777. y = _common.rootrel_arc_src(y, unit)
  778. if not os.path.exists(unit.resolve('$S/' + y)):
  779. return [], 'Wrong use of SYSTEM_PROPERTIES in {}: can\'t resolve {}'.format(unit.path(), y)
  780. y = '${ARCADIA_ROOT}/' + y
  781. props.append({'type': 'file', 'path': y})
  782. else:
  783. props.append({'type': 'inline', 'key': x, 'value': y})
  784. return props, None
  785. def onjava_test(unit, *args):
  786. if unit.get("TIDY") == "yes":
  787. # graph changed for clang_tidy tests
  788. return
  789. assert unit.get('MODULE_TYPE') is not None
  790. if unit.get('MODULE_TYPE') == 'JTEST_FOR':
  791. if not unit.get('UNITTEST_DIR'):
  792. ymake.report_configure_error('skip JTEST_FOR in {}: no args provided'.format(unit.path()))
  793. return
  794. java_cp_arg_type = unit.get('JAVA_CLASSPATH_CMD_TYPE_VALUE') or 'MANIFEST'
  795. if java_cp_arg_type not in ('MANIFEST', 'COMMAND_FILE', 'LIST'):
  796. ymake.report_configure_error(
  797. '{}: TEST_JAVA_CLASSPATH_CMD_TYPE({}) are invalid. Choose argument from MANIFEST, COMMAND_FILE or LIST)'.format(
  798. unit.path(), java_cp_arg_type
  799. )
  800. )
  801. return
  802. unit_path = unit.path()
  803. path = _common.strip_roots(unit_path)
  804. if unit.get('ADD_SRCDIR_TO_TEST_DATA') == "yes":
  805. unit.ondata_files(_common.get_norm_unit_path(unit))
  806. yt_spec_values = get_unit_list_variable(unit, 'TEST_YT_SPEC_VALUE')
  807. unit.ondata_files(yt_spec_values)
  808. test_data = get_norm_paths(unit, 'TEST_DATA_VALUE')
  809. test_data.append('arcadia/build/scripts/run_junit.py')
  810. test_data.append('arcadia/build/scripts/unpacking_jtest_runner.py')
  811. data, data_files = get_canonical_test_resources(unit)
  812. test_data += data
  813. props, error_mgs = extract_java_system_properties(unit, get_values_list(unit, 'SYSTEM_PROPERTIES_VALUE'))
  814. if error_mgs:
  815. ymake.report_configure_error(error_mgs)
  816. return
  817. for prop in props:
  818. if prop['type'] == 'file':
  819. test_data.append(prop['path'].replace('${ARCADIA_ROOT}', 'arcadia'))
  820. props = base64.b64encode(six.ensure_binary(json.dumps(props)))
  821. test_cwd = unit.get('TEST_CWD_VALUE') or '' # TODO: validate test_cwd value
  822. if unit.get('MODULE_TYPE') == 'JUNIT5':
  823. script_rel_path = 'junit5.test'
  824. else:
  825. script_rel_path = 'junit.test'
  826. ymake_java_test = unit.get('YMAKE_JAVA_TEST') == 'yes'
  827. test_record = {
  828. 'SOURCE-FOLDER-PATH': path,
  829. 'TEST-NAME': '-'.join([os.path.basename(os.path.dirname(path)), os.path.basename(path)]),
  830. 'SCRIPT-REL-PATH': script_rel_path,
  831. 'TEST-TIMEOUT': unit.get('TEST_TIMEOUT') or '',
  832. 'TESTED-PROJECT-NAME': path,
  833. 'TEST-ENV': prepare_env(unit.get("TEST_ENV_VALUE")),
  834. # 'TEST-PRESERVE-ENV': 'da',
  835. 'TEST-DATA': serialize_list(sorted(_common.filter_out_by_keyword(test_data, 'AUTOUPDATED'))),
  836. 'FORK-MODE': unit.get('TEST_FORK_MODE') or '',
  837. 'SPLIT-FACTOR': unit.get('TEST_SPLIT_FACTOR') or '',
  838. 'CUSTOM-DEPENDENCIES': ' '.join(get_values_list(unit, 'TEST_DEPENDS_VALUE')),
  839. 'TAG': serialize_list(sorted(_get_test_tags(unit))),
  840. 'SIZE': unit.get('TEST_SIZE_NAME') or '',
  841. 'REQUIREMENTS': serialize_list(get_values_list(unit, 'TEST_REQUIREMENTS_VALUE')),
  842. 'TEST-RECIPES': prepare_recipes(unit.get("TEST_RECIPES_VALUE")),
  843. # JTEST/JTEST_FOR only
  844. 'MODULE_TYPE': unit.get('MODULE_TYPE'),
  845. 'UNITTEST_DIR': unit.get('UNITTEST_DIR') or '',
  846. 'JVM_ARGS': serialize_list(get_values_list(unit, 'JVM_ARGS_VALUE')),
  847. 'SYSTEM_PROPERTIES': props,
  848. 'TEST-CWD': test_cwd,
  849. 'SKIP_TEST': unit.get('SKIP_TEST_VALUE') or '',
  850. 'JAVA_CLASSPATH_CMD_TYPE': java_cp_arg_type,
  851. 'JDK_RESOURCE': 'JDK' + (unit.get('JDK_VERSION') or unit.get('JDK_REAL_VERSION') or '_DEFAULT'),
  852. 'JDK_FOR_TESTS': 'JDK' + (unit.get('JDK_VERSION') or unit.get('JDK_REAL_VERSION') or '_DEFAULT') + '_FOR_TESTS',
  853. 'YT-SPEC': serialize_list(yt_spec_values),
  854. }
  855. test_classpath_origins = unit.get('TEST_CLASSPATH_VALUE')
  856. if test_classpath_origins:
  857. test_record['TEST_CLASSPATH_ORIGINS'] = test_classpath_origins
  858. test_record['TEST_CLASSPATH'] = '${TEST_CLASSPATH_MANAGED}'
  859. elif ymake_java_test:
  860. test_record['TEST_CLASSPATH'] = '${DART_CLASSPATH}'
  861. test_record['TEST_CLASSPATH_DEPS'] = '${DART_CLASSPATH_DEPS}'
  862. if unit.get('UNITTEST_DIR'):
  863. test_record['TEST_JAR'] = '${UNITTEST_MOD}'
  864. else:
  865. test_record['TEST_JAR'] = '{}/{}.jar'.format(unit.get('MODDIR'), unit.get('REALPRJNAME'))
  866. data = dump_test(unit, test_record)
  867. if data:
  868. unit.set_property(['DART_DATA', data])
  869. def onjava_test_deps(unit, *args):
  870. if unit.get("TIDY") == "yes":
  871. # graph changed for clang_tidy tests
  872. return
  873. assert unit.get('MODULE_TYPE') is not None
  874. assert len(args) == 1
  875. mode = args[0]
  876. path = _common.get_norm_unit_path(unit)
  877. ymake_java_test = unit.get('YMAKE_JAVA_TEST') == 'yes'
  878. test_record = {
  879. 'SOURCE-FOLDER-PATH': path,
  880. 'TEST-NAME': '-'.join([os.path.basename(os.path.dirname(path)), os.path.basename(path), 'dependencies']).strip(
  881. '-'
  882. ),
  883. 'SCRIPT-REL-PATH': 'java.dependency.test',
  884. 'TEST-TIMEOUT': '',
  885. 'TESTED-PROJECT-NAME': path,
  886. 'TEST-DATA': '',
  887. 'TEST_PARTITION': 'SEQUENTIAL',
  888. 'FORK-MODE': '',
  889. 'SPLIT-FACTOR': '',
  890. 'CUSTOM-DEPENDENCIES': ' '.join(get_values_list(unit, 'TEST_DEPENDS_VALUE')),
  891. 'TAG': '',
  892. 'SIZE': 'SMALL',
  893. 'IGNORE_CLASSPATH_CLASH': ' '.join(get_values_list(unit, 'JAVA_IGNORE_CLASSPATH_CLASH_VALUE')),
  894. # JTEST/JTEST_FOR only
  895. 'MODULE_TYPE': unit.get('MODULE_TYPE'),
  896. 'UNITTEST_DIR': '',
  897. 'SYSTEM_PROPERTIES': '',
  898. 'TEST-CWD': '',
  899. }
  900. if mode == 'strict':
  901. test_record['STRICT_CLASSPATH_CLASH'] = 'yes'
  902. if ymake_java_test:
  903. test_record['CLASSPATH'] = '$B/{}/{}.jar ${{DART_CLASSPATH}}'.format(
  904. unit.get('MODDIR'), unit.get('REALPRJNAME')
  905. )
  906. data = dump_test(unit, test_record)
  907. unit.set_property(['DART_DATA', data])
  908. def _get_test_tags(unit, spec_args=None):
  909. if spec_args is None:
  910. spec_args = {}
  911. tags = spec_args.get('TAG', []) + get_values_list(unit, 'TEST_TAGS_VALUE')
  912. tags = set(tags)
  913. if unit.get('EXPORT_SEM') == 'yes':
  914. filter_only_tags = sorted(t for t in tags if ':' not in t)
  915. unit.set(['FILTER_ONLY_TEST_TAGS', ' '.join(filter_only_tags)])
  916. # DEVTOOLS-7571
  917. if unit.get('SKIP_TEST_VALUE') and consts.YaTestTags.Fat in tags:
  918. tags.add(consts.YaTestTags.NotAutocheck)
  919. return tags
  920. def _dump_test(
  921. unit,
  922. test_type,
  923. test_files,
  924. timeout,
  925. test_dir,
  926. custom_deps,
  927. test_data,
  928. python_paths,
  929. split_factor,
  930. fork_mode,
  931. test_size,
  932. tags,
  933. requirements,
  934. binary_path='',
  935. old_pytest=False,
  936. test_cwd=None,
  937. runner_bin=None,
  938. yt_spec=None,
  939. data_files=None,
  940. ):
  941. if test_type == "PY_TEST":
  942. script_rel_path = "py.test"
  943. else:
  944. script_rel_path = test_type
  945. unit_path = unit.path()
  946. fork_test_files = unit.get('FORK_TEST_FILES_MODE')
  947. fork_mode = ' '.join(fork_mode) if fork_mode else ''
  948. use_arcadia_python = unit.get('USE_ARCADIA_PYTHON')
  949. if test_cwd:
  950. test_cwd = test_cwd.replace("$TEST_CWD_VALUE", "").replace('"MACRO_CALLS_DELIM"', "").strip()
  951. test_name = os.path.basename(binary_path)
  952. test_record = {
  953. 'TEST-NAME': os.path.splitext(test_name)[0],
  954. 'TEST-TIMEOUT': timeout,
  955. 'SCRIPT-REL-PATH': script_rel_path,
  956. 'TESTED-PROJECT-NAME': test_name,
  957. 'SOURCE-FOLDER-PATH': test_dir,
  958. 'CUSTOM-DEPENDENCIES': " ".join(custom_deps),
  959. 'TEST-ENV': prepare_env(unit.get("TEST_ENV_VALUE")),
  960. # 'TEST-PRESERVE-ENV': 'da',
  961. 'TEST-DATA': serialize_list(sorted(_common.filter_out_by_keyword(test_data, 'AUTOUPDATED'))),
  962. 'TEST-RECIPES': prepare_recipes(unit.get("TEST_RECIPES_VALUE")),
  963. 'SPLIT-FACTOR': split_factor,
  964. 'TEST_PARTITION': unit.get('TEST_PARTITION') or 'SEQUENTIAL',
  965. 'FORK-MODE': fork_mode,
  966. 'FORK-TEST-FILES': fork_test_files,
  967. 'TEST-FILES': serialize_list(test_files),
  968. 'SIZE': test_size,
  969. 'TAG': serialize_list(sorted(tags)),
  970. 'REQUIREMENTS': serialize_list(requirements),
  971. 'USE_ARCADIA_PYTHON': use_arcadia_python or '',
  972. 'OLD_PYTEST': 'yes' if old_pytest else 'no',
  973. 'PYTHON-PATHS': serialize_list(python_paths),
  974. 'TEST-CWD': test_cwd or '',
  975. 'SKIP_TEST': unit.get('SKIP_TEST_VALUE') or '',
  976. 'BUILD-FOLDER-PATH': _common.strip_roots(unit_path),
  977. 'BLOB': unit.get('TEST_BLOB_DATA') or '',
  978. 'CANONIZE_SUB_PATH': unit.get('CANONIZE_SUB_PATH') or '',
  979. }
  980. if binary_path:
  981. test_record['BINARY-PATH'] = _common.strip_roots(binary_path)
  982. if runner_bin:
  983. test_record['TEST-RUNNER-BIN'] = runner_bin
  984. if yt_spec:
  985. test_record['YT-SPEC'] = serialize_list(yt_spec)
  986. data = dump_test(unit, test_record)
  987. if data:
  988. unit.set_property(["DART_DATA", data])
  989. def onsetup_pytest_bin(unit, *args):
  990. use_arcadia_python = unit.get('USE_ARCADIA_PYTHON') == "yes"
  991. if use_arcadia_python:
  992. unit.onresource(['-', 'PY_MAIN={}'.format("library.python.pytest.main:main")]) # XXX
  993. unit.onadd_pytest_bin(list(args))
  994. else:
  995. unit.onno_platform()
  996. unit.onadd_pytest_script(["PY_TEST"])
  997. def onrun(unit, *args):
  998. exectest_cmd = unit.get(["EXECTEST_COMMAND_VALUE"]) or ''
  999. exectest_cmd += "\n" + subprocess.list2cmdline(args)
  1000. unit.set(["EXECTEST_COMMAND_VALUE", exectest_cmd])
  1001. def onsetup_exectest(unit, *args):
  1002. command = unit.get(["EXECTEST_COMMAND_VALUE"])
  1003. if command is None:
  1004. ymake.report_configure_error("EXECTEST must have at least one RUN macro")
  1005. return
  1006. command = command.replace("$EXECTEST_COMMAND_VALUE", "")
  1007. if "PYTHON_BIN" in command:
  1008. unit.ondepends('contrib/tools/python')
  1009. unit.set(["TEST_BLOB_DATA", base64.b64encode(six.ensure_binary(command))])
  1010. add_test_to_dart(unit, "exectest", binary_path=os.path.join(unit.path(), unit.filename()).replace(".pkg", ""))
  1011. def onsetup_run_python(unit):
  1012. if unit.get("USE_ARCADIA_PYTHON") == "yes":
  1013. unit.ondepends('contrib/tools/python')
  1014. def get_canonical_test_resources(unit):
  1015. unit_path = unit.path()
  1016. canon_data_dir = os.path.join(unit.resolve(unit_path), CANON_DATA_DIR_NAME, unit.get('CANONIZE_SUB_PATH') or '')
  1017. try:
  1018. _, dirs, files = next(os.walk(canon_data_dir))
  1019. except StopIteration:
  1020. # path doesn't exist
  1021. return [], []
  1022. if CANON_RESULT_FILE_NAME in files:
  1023. return _get_canonical_data_resources_v2(os.path.join(canon_data_dir, CANON_RESULT_FILE_NAME), unit_path)
  1024. return [], []
  1025. def _load_canonical_file(filename, unit_path):
  1026. try:
  1027. with open(filename, 'rb') as results_file:
  1028. return json.load(results_file)
  1029. except Exception as e:
  1030. print("malformed canonical data in {}: {} ({})".format(unit_path, e, filename), file=sys.stderr)
  1031. return {}
  1032. def _get_resource_from_uri(uri):
  1033. m = CANON_MDS_RESOURCE_REGEX.match(uri)
  1034. if m:
  1035. res_id = m.group(1)
  1036. return "{}:{}".format(MDS_SCHEME, res_id)
  1037. m = 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])