ytest.py 50 KB

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