ytest.py 51 KB

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