Debian Codegraph @

tools/run_tests/run_tests.py

raw ◀ ▶
1 Debian patch touch this file
1 #!/usr/bin/env python3
2 # Copyright 2015 gRPC authors.
3 #
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at
7 #
8 # http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
15 """Run tests in parallel."""
16
17 from __future__ import print_function
18
19 import argparse
20 import ast
21 import collections
22 import glob
23 import itertools
24 import json
25 import logging
26 import multiprocessing
27 import os
28 import os.path
29 import platform
30 import random
31 import re
•32 import shlex
33 import socket
34 import subprocess
35 import sys
36 import tempfile
37 import time
38 import traceback
39 import uuid
40
41 import six
42 from six.moves import urllib
43
44 import python_utils.jobset as jobset
45 import python_utils.report_utils as report_utils
46 import python_utils.start_port_server as start_port_server
47 import python_utils.watch_dirs as watch_dirs
48
49 try:
50 from python_utils.upload_test_results import upload_results_to_bq
51 except (ImportError):
52 pass # It's ok to not import because this is only necessary to upload results to BQ.
53
54 gcp_utils_dir = os.path.abspath(
55 os.path.join(os.path.dirname(__file__), '../gcp/utils'))
56 sys.path.append(gcp_utils_dir)
57
58 _ROOT = os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]), '../..'))
59 os.chdir(_ROOT)
60
61 _FORCE_ENVIRON_FOR_WRAPPERS = {
62 'GRPC_VERBOSITY': 'DEBUG',
63 }
64
65 _POLLING_STRATEGIES = {
66 'linux': ['epoll1', 'poll'],
67 'mac': ['poll'],
68 }
69
70
71 def platform_string():
72 return jobset.platform_string()
73
74
75 _DEFAULT_TIMEOUT_SECONDS = 5 * 60
76 _PRE_BUILD_STEP_TIMEOUT_SECONDS = 10 * 60
77
78
79 def run_shell_command(cmd, env=None, cwd=None):
80 try:
81 subprocess.check_output(cmd, shell=True, env=env, cwd=cwd)
82 except subprocess.CalledProcessError as e:
83 logging.exception(
84 "Error while running command '%s'. Exit status %d. Output:\n%s",
85 e.cmd, e.returncode, e.output)
86 raise
87
88
89 def max_parallel_tests_for_current_platform():
90 # Too much test parallelization has only been seen to be a problem
91 # so far on windows.
92 if jobset.platform_string() == 'windows':
93 return 64
94 return 1024
95
96
97 def _print_debug_info_epilogue(dockerfile_dir=None):
98 """Use to print useful info for debug/repro just before exiting."""
99 print('')
100 print('=== run_tests.py DEBUG INFO ===')
101 print('command: \"%s\"' % ' '.join(sys.argv))
102 if dockerfile_dir:
103 print('dockerfile: %s' % dockerfile_dir)
104 kokoro_job_name = os.getenv('KOKORO_JOB_NAME')
105 if kokoro_job_name:
106 print('kokoro job name: %s' % kokoro_job_name)
107 print('===============================')
108
109
110 # SimpleConfig: just compile with CONFIG=config, and run the binary to test
111 class Config(object):
112
113 def __init__(self,
114 config,
115 environ=None,
116 timeout_multiplier=1,
117 tool_prefix=[],
118 iomgr_platform='native'):
119 if environ is None:
120 environ = {}
121 self.build_config = config
122 self.environ = environ
123 self.environ['CONFIG'] = config
124 self.tool_prefix = tool_prefix
125 self.timeout_multiplier = timeout_multiplier
126 self.iomgr_platform = iomgr_platform
127
128 def job_spec(self,
129 cmdline,
130 timeout_seconds=_DEFAULT_TIMEOUT_SECONDS,
131 shortname=None,
132 environ={},
133 cpu_cost=1.0,
134 flaky=False):
135 """Construct a jobset.JobSpec for a test under this config
136
137 Args:
138 cmdline: a list of strings specifying the command line the test
139 would like to run
140 """
141 actual_environ = self.environ.copy()
142 for k, v in environ.items():
143 actual_environ[k] = v
144 if not flaky and shortname and shortname in flaky_tests:
145 flaky = True
146 if shortname in shortname_to_cpu:
147 cpu_cost = shortname_to_cpu[shortname]
148 return jobset.JobSpec(
149 cmdline=self.tool_prefix + cmdline,
150 shortname=shortname,
151 environ=actual_environ,
152 cpu_cost=cpu_cost,
153 timeout_seconds=(self.timeout_multiplier *
154 timeout_seconds if timeout_seconds else None),
155 flake_retries=4 if flaky or args.allow_flakes else 0,
156 timeout_retries=1 if flaky or args.allow_flakes else 0)
157
158
159 def get_c_tests(travis, test_lang):
160 out = []
161 platforms_str = 'ci_platforms' if travis else 'platforms'
162 with open('tools/run_tests/generated/tests.json') as f:
163 js = json.load(f)
164 return [
165 tgt for tgt in js
166 if tgt['language'] == test_lang and platform_string() in
167 tgt[platforms_str] and not (travis and tgt['flaky'])
168 ]
169
170
171 def _check_compiler(compiler, supported_compilers):
172 if compiler not in supported_compilers:
173 raise Exception('Compiler %s not supported (on this platform).' %
174 compiler)
175
176
177 def _check_arch(arch, supported_archs):
178 if arch not in supported_archs:
179 raise Exception('Architecture %s not supported.' % arch)
180
181
182 def _is_use_docker_child():
183 """Returns True if running running as a --use_docker child."""
184 return True if os.getenv('DOCKER_RUN_SCRIPT_COMMAND') else False
185
186
187 _PythonConfigVars = collections.namedtuple('_ConfigVars', [
188 'shell',
189 'builder',
190 'builder_prefix_arguments',
191 'venv_relative_python',
192 'toolchain',
193 'runner',
194 ])
195
196
197 def _python_config_generator(name, major, minor, bits, config_vars):
198 build = (config_vars.shell + config_vars.builder +
199 config_vars.builder_prefix_arguments +
200 [_python_pattern_function(major=major, minor=minor, bits=bits)] +
201 [name] + config_vars.venv_relative_python + config_vars.toolchain)
202 run = (config_vars.shell + config_vars.runner + [
203 os.path.join(name, config_vars.venv_relative_python[0]),
204 ])
205 return PythonConfig(name, build, run)
206
207
208 def _pypy_config_generator(name, major, config_vars):
209 return PythonConfig(
210 name, config_vars.shell + config_vars.builder +
211 config_vars.builder_prefix_arguments +
212 [_pypy_pattern_function(major=major)] + [name] +
213 config_vars.venv_relative_python + config_vars.toolchain,
214 config_vars.shell + config_vars.runner +
215 [os.path.join(name, config_vars.venv_relative_python[0])])
216
217
218 def _python_pattern_function(major, minor, bits):
219 # Bit-ness is handled by the test machine's environment
220 if os.name == "nt":
221 if bits == "64":
222 return '/c/Python{major}{minor}/python.exe'.format(major=major,
223 minor=minor,
224 bits=bits)
225 else:
226 return '/c/Python{major}{minor}_{bits}bits/python.exe'.format(
227 major=major, minor=minor, bits=bits)
228 else:
229 return 'python{major}.{minor}'.format(major=major, minor=minor)
230
231
232 def _pypy_pattern_function(major):
233 if major == '2':
234 return 'pypy'
235 elif major == '3':
236 return 'pypy3'
237 else:
238 raise ValueError("Unknown PyPy major version")
239
240
241 class CLanguage(object):
242
243 def __init__(self, lang_suffix, test_lang):
244 self.lang_suffix = lang_suffix
245 self.platform = platform_string()
246 self.test_lang = test_lang
247
248 def configure(self, config, args):
249 self.config = config
250 self.args = args
251 if self.platform == 'windows':
252 _check_compiler(self.args.compiler, [
253 'default',
254 'cmake',
255 'cmake_ninja_vs2017',
256 'cmake_vs2017',
257 'cmake_vs2019',
258 ])
259 _check_arch(self.args.arch, ['default', 'x64', 'x86'])
260
261 activate_vs_tools = ''
262 if self.args.compiler == 'cmake_ninja_vs2017' or self.args.compiler == 'cmake' or self.args.compiler == 'default':
263 # cmake + ninja build is the default because it is faster and supports boringssl assembly optimizations
264 # the compiler used is exactly the same as for cmake_vs2017
265 cmake_generator = 'Ninja'
266 activate_vs_tools = '2017'
267 elif self.args.compiler == 'cmake_vs2017':
268 cmake_generator = 'Visual Studio 15 2017'
269 elif self.args.compiler == 'cmake_vs2019':
270 cmake_generator = 'Visual Studio 16 2019'
271 else:
272 print('should never reach here.')
273 sys.exit(1)
274
275 self._cmake_configure_extra_args = []
276 self._cmake_generator_windows = cmake_generator
277 # required to pass as cmake "-A" configuration for VS builds (but not for Ninja)
278 self._cmake_architecture_windows = 'x64' if self.args.arch == 'x64' else 'Win32'
279 # when builing with Ninja, the VS common tools need to be activated first
280 self._activate_vs_tools_windows = activate_vs_tools
281 # "x64_x86" means create 32bit binaries, but use 64bit toolkit to secure more memory for the build
282 self._vs_tools_architecture_windows = 'x64' if self.args.arch == 'x64' else 'x64_x86'
283
284 else:
285 if self.platform == 'linux':
286 # Allow all the known architectures. _check_arch_option has already checked that we're not doing
287 # something illegal when not running under docker.
288 _check_arch(self.args.arch, ['default', 'x64', 'x86', 'arm64'])
289 else:
290 _check_arch(self.args.arch, ['default'])
291
292 self._docker_distro, self._cmake_configure_extra_args = self._compiler_options(
293 self.args.use_docker, self.args.compiler)
294
295 if self.args.arch == 'x86':
296 # disable boringssl asm optimizations when on x86
297 # see https://github.com/grpc/grpc/blob/b5b8578b3f8b4a9ce61ed6677e19d546e43c5c68/tools/run_tests/artifacts/artifact_targets.py#L253
298 self._cmake_configure_extra_args.append('-DOPENSSL_NO_ASM=ON')
299
300 def test_specs(self):
301 out = []
302 binaries = get_c_tests(self.args.travis, self.test_lang)
303 for target in binaries:
304 if target.get('boringssl', False):
305 # cmake doesn't build boringssl tests
306 continue
307 auto_timeout_scaling = target.get('auto_timeout_scaling', True)
308 polling_strategies = (_POLLING_STRATEGIES.get(
309 self.platform, ['all']) if target.get('uses_polling', True) else
310 ['none'])
311 for polling_strategy in polling_strategies:
312 env = {
313 'GRPC_DEFAULT_SSL_ROOTS_FILE_PATH':
314 _ROOT + '/src/core/tsi/test_creds/ca.pem',
315 'GRPC_POLL_STRATEGY':
316 polling_strategy,
317 'GRPC_VERBOSITY':
318 'DEBUG'
319 }
320 resolver = os.environ.get('GRPC_DNS_RESOLVER', None)
321 if resolver:
322 env['GRPC_DNS_RESOLVER'] = resolver
323 shortname_ext = '' if polling_strategy == 'all' else ' GRPC_POLL_STRATEGY=%s' % polling_strategy
324 if polling_strategy in target.get('excluded_poll_engines', []):
325 continue
326
327 timeout_scaling = 1
328 if auto_timeout_scaling:
329 config = self.args.config
330 if ('asan' in config or config == 'msan' or
331 config == 'tsan' or config == 'ubsan' or
332 config == 'helgrind' or config == 'memcheck'):
333 # Scale overall test timeout if running under various sanitizers.
334 # scaling value is based on historical data analysis
335 timeout_scaling *= 3
336
337 if self.config.build_config in target['exclude_configs']:
338 continue
339 if self.args.iomgr_platform in target.get('exclude_iomgrs', []):
340 continue
341 if self.platform == 'windows':
342 binary = 'cmake/build/%s/%s.exe' % (_MSBUILD_CONFIG[
343 self.config.build_config], target['name'])
344 else:
345 binary = 'cmake/build/%s' % target['name']
346
347 cpu_cost = target['cpu_cost']
348 if cpu_cost == 'capacity':
349 cpu_cost = multiprocessing.cpu_count()
350 if os.path.isfile(binary):
351 list_test_command = None
352 filter_test_command = None
353
354 # these are the flag defined by gtest and benchmark framework to list
355 # and filter test runs. We use them to split each individual test
356 # into its own JobSpec, and thus into its own process.
357 if 'benchmark' in target and target['benchmark']:
358 with open(os.devnull, 'w') as fnull:
359 tests = subprocess.check_output(
360 [binary, '--benchmark_list_tests'],
361 stderr=fnull)
362 for line in tests.decode().split('\n'):
363 test = line.strip()
364 if not test:
365 continue
366 cmdline = [binary,
367 '--benchmark_filter=%s$' % test
368 ] + target['args']
369 out.append(
370 self.config.job_spec(
371 cmdline,
372 shortname='%s %s' %
373 (' '.join(cmdline), shortname_ext),
374 cpu_cost=cpu_cost,
375 timeout_seconds=target.get(
376 'timeout_seconds',
377 _DEFAULT_TIMEOUT_SECONDS) *
378 timeout_scaling,
379 environ=env))
380 elif 'gtest' in target and target['gtest']:
381 # here we parse the output of --gtest_list_tests to build up a complete
382 # list of the tests contained in a binary for each test, we then
383 # add a job to run, filtering for just that test.
384 with open(os.devnull, 'w') as fnull:
385 tests = subprocess.check_output(
386 [binary, '--gtest_list_tests'], stderr=fnull)
387 base = None
388 for line in tests.decode().split('\n'):
389 i = line.find('#')
390 if i >= 0:
391 line = line[:i]
392 if not line:
393 continue
394 if line[0] != ' ':
395 base = line.strip()
396 else:
397 assert base is not None
398 assert line[1] == ' '
399 test = base + line.strip()
400 cmdline = [binary,
401 '--gtest_filter=%s' % test
402 ] + target['args']
403 out.append(
404 self.config.job_spec(
405 cmdline,
406 shortname='%s %s' %
407 (' '.join(cmdline), shortname_ext),
408 cpu_cost=cpu_cost,
409 timeout_seconds=target.get(
410 'timeout_seconds',
411 _DEFAULT_TIMEOUT_SECONDS) *
412 timeout_scaling,
413 environ=env))
414 else:
415 cmdline = [binary] + target['args']
416 shortname = target.get(
417 'shortname',
•418 ' '.join(shlex.quote(arg) for arg in cmdline))
419 shortname += shortname_ext
420 out.append(
421 self.config.job_spec(
422 cmdline,
423 shortname=shortname,
424 cpu_cost=cpu_cost,
425 flaky=target.get('flaky', False),
426 timeout_seconds=target.get(
427 'timeout_seconds',
428 _DEFAULT_TIMEOUT_SECONDS) * timeout_scaling,
429 environ=env))
430 elif self.args.regex == '.*' or self.platform == 'windows':
431 print('\nWARNING: binary not found, skipping', binary)
432 return sorted(out)
433
434 def pre_build_steps(self):
435 return []
436
437 def build_steps(self):
438 if self.platform == 'windows':
439 return [[
440 'tools\\run_tests\\helper_scripts\\build_cxx.bat',
441 '-DgRPC_BUILD_MSVC_MP_COUNT=%d' % self.args.jobs
442 ] + self._cmake_configure_extra_args]
443 else:
444 return [['tools/run_tests/helper_scripts/build_cxx.sh'] +
445 self._cmake_configure_extra_args]
446
447 def build_steps_environ(self):
448 """Extra environment variables set for pre_build_steps and build_steps jobs."""
449 environ = {'GRPC_RUN_TESTS_CXX_LANGUAGE_SUFFIX': self.lang_suffix}
450 if self.platform == 'windows':
451 environ['GRPC_CMAKE_GENERATOR'] = self._cmake_generator_windows
452 environ[
453 'GRPC_CMAKE_ARCHITECTURE'] = self._cmake_architecture_windows
454 environ[
455 'GRPC_BUILD_ACTIVATE_VS_TOOLS'] = self._activate_vs_tools_windows
456 environ[
457 'GRPC_BUILD_VS_TOOLS_ARCHITECTURE'] = self._vs_tools_architecture_windows
458 return environ
459
460 def post_tests_steps(self):
461 if self.platform == 'windows':
462 return []
463 else:
464 return [['tools/run_tests/helper_scripts/post_tests_c.sh']]
465
466 def _clang_cmake_configure_extra_args(self, version_suffix=''):
467 return [
468 '-DCMAKE_C_COMPILER=clang%s' % version_suffix,
469 '-DCMAKE_CXX_COMPILER=clang++%s' % version_suffix,
470 ]
471
472 def _compiler_options(self, use_docker, compiler):
473 """Returns docker distro and cmake configure args to use for given compiler."""
474 if not use_docker and not _is_use_docker_child():
475 # if not running under docker, we cannot ensure the right compiler version will be used,
476 # so we only allow the non-specific choices.
477 _check_compiler(compiler, ['default', 'cmake'])
478
479 if compiler == 'default' or compiler == 'cmake':
480 return ('debian11', [])
481 elif compiler == 'gcc7':
482 return ('gcc_7', [])
483 elif compiler == 'gcc10.2':
484 return ('debian11', [])
485 elif compiler == 'gcc10.2_openssl102':
486 return ('debian11_openssl102', [
487 "-DgRPC_SSL_PROVIDER=package",
488 ])
489 elif compiler == 'gcc12':
490 return ('gcc_12', ["-DCMAKE_CXX_STANDARD=20"])
491 elif compiler == 'gcc_musl':
492 return ('alpine', [])
493 elif compiler == 'clang6':
494 return ('clang_6', self._clang_cmake_configure_extra_args())
495 elif compiler == 'clang15':
496 return ('clang_15', self._clang_cmake_configure_extra_args())
497 else:
498 raise Exception('Compiler %s not supported.' % compiler)
499
500 def dockerfile_dir(self):
501 return 'tools/dockerfile/test/cxx_%s_%s' % (
502 self._docker_distro, _docker_arch_suffix(self.args.arch))
503
504 def __str__(self):
505 return self.lang_suffix
506
507
508 # This tests Node on grpc/grpc-node and will become the standard for Node testing
509 class RemoteNodeLanguage(object):
510
511 def __init__(self):
512 self.platform = platform_string()
513
514 def configure(self, config, args):
515 self.config = config
516 self.args = args
517 # Note: electron ABI only depends on major and minor version, so that's all
518 # we should specify in the compiler argument
519 _check_compiler(self.args.compiler, [
520 'default', 'node0.12', 'node4', 'node5', 'node6', 'node7', 'node8',
521 'electron1.3', 'electron1.6'
522 ])
523 if self.args.compiler == 'default':
524 self.runtime = 'node'
525 self.node_version = '8'
526 else:
527 if self.args.compiler.startswith('electron'):
528 self.runtime = 'electron'
529 self.node_version = self.args.compiler[8:]
530 else:
531 self.runtime = 'node'
532 # Take off the word "node"
533 self.node_version = self.args.compiler[4:]
534
535 # TODO: update with Windows/electron scripts when available for grpc/grpc-node
536 def test_specs(self):
537 if self.platform == 'windows':
538 return [
539 self.config.job_spec(
540 ['tools\\run_tests\\helper_scripts\\run_node.bat'])
541 ]
542 else:
543 return [
544 self.config.job_spec(
545 ['tools/run_tests/helper_scripts/run_grpc-node.sh'],
546 None,
547 environ=_FORCE_ENVIRON_FOR_WRAPPERS)
548 ]
549
550 def pre_build_steps(self):
551 return []
552
553 def build_steps(self):
554 return []
555
556 def build_steps_environ(self):
557 """Extra environment variables set for pre_build_steps and build_steps jobs."""
558 return {}
559
560 def post_tests_steps(self):
561 return []
562
563 def dockerfile_dir(self):
564 return 'tools/dockerfile/test/node_jessie_%s' % _docker_arch_suffix(
565 self.args.arch)
566
567 def __str__(self):
568 return 'grpc-node'
569
570
571 class Php7Language(object):
572
573 def configure(self, config, args):
574 self.config = config
575 self.args = args
576 _check_compiler(self.args.compiler, ['default'])
577
578 def test_specs(self):
579 return [
580 self.config.job_spec(['src/php/bin/run_tests.sh'],
581 environ=_FORCE_ENVIRON_FOR_WRAPPERS)
582 ]
583
584 def pre_build_steps(self):
585 return []
586
587 def build_steps(self):
588 return [['tools/run_tests/helper_scripts/build_php.sh']]
589
590 def build_steps_environ(self):
591 """Extra environment variables set for pre_build_steps and build_steps jobs."""
592 return {}
593
594 def post_tests_steps(self):
595 return [['tools/run_tests/helper_scripts/post_tests_php.sh']]
596
597 def dockerfile_dir(self):
598 return 'tools/dockerfile/test/php7_debian11_%s' % _docker_arch_suffix(
599 self.args.arch)
600
601 def __str__(self):
602 return 'php7'
603
604
605 class PythonConfig(
606 collections.namedtuple('PythonConfig', ['name', 'build', 'run'])):
607 """Tuple of commands (named s.t. 'what it says on the tin' applies)"""
608
609
610 class PythonLanguage(object):
611
612 _TEST_SPECS_FILE = {
613 'native': ['src/python/grpcio_tests/tests/tests.json'],
614 'gevent': [
615 'src/python/grpcio_tests/tests/tests.json',
616 'src/python/grpcio_tests/tests_gevent/tests.json',
617 ],
618 'asyncio': ['src/python/grpcio_tests/tests_aio/tests.json'],
619 }
620
621 _TEST_COMMAND = {
622 'native': 'test_lite',
623 'gevent': 'test_gevent',
624 'asyncio': 'test_aio',
625 }
626
627 def configure(self, config, args):
628 self.config = config
629 self.args = args
630 self.pythons = self._get_pythons(self.args)
631
632 def test_specs(self):
633 # load list of known test suites
634 jobs = []
635 for io_platform in self._TEST_SPECS_FILE:
636 test_cases = []
637 for tests_json_file_name in self._TEST_SPECS_FILE[io_platform]:
638 with open(tests_json_file_name) as tests_json_file:
639 test_cases.extend(json.load(tests_json_file))
640
641 environment = dict(_FORCE_ENVIRON_FOR_WRAPPERS)
642 # TODO(https://github.com/grpc/grpc/issues/21401) Fork handlers is not
643 # designed for non-native IO manager. It has a side-effect that
644 # overrides threading settings in C-Core.
645 if io_platform != 'native':
646 environment['GRPC_ENABLE_FORK_SUPPORT'] = '0'
647 for python_config in self.pythons:
648 jobs.extend([
649 self.config.job_spec(
650 python_config.run + [self._TEST_COMMAND[io_platform]],
651 timeout_seconds=8 * 60,
652 environ=dict(
653 GRPC_PYTHON_TESTRUNNER_FILTER=str(test_case),
654 **environment),
655 shortname='%s.%s.%s' %
656 (python_config.name, io_platform, test_case),
657 ) for test_case in test_cases
658 ])
659 return jobs
660
661 def pre_build_steps(self):
662 return []
663
664 def build_steps(self):
665 return [config.build for config in self.pythons]
666
667 def build_steps_environ(self):
668 """Extra environment variables set for pre_build_steps and build_steps jobs."""
669 return {}
670
671 def post_tests_steps(self):
672 if self.config.build_config != 'gcov':
673 return []
674 else:
675 return [['tools/run_tests/helper_scripts/post_tests_python.sh']]
676
677 def dockerfile_dir(self):
678 return 'tools/dockerfile/test/python_%s_%s' % (
679 self._python_docker_distro_name(),
680 _docker_arch_suffix(self.args.arch))
681
682 def _python_docker_distro_name(self):
683 """Choose the docker image to use based on python version."""
684 if self.args.compiler == 'python_alpine':
685 return 'alpine'
686 else:
687 return 'debian11_default'
688
689 def _get_pythons(self, args):
690 """Get python runtimes to test with, based on current platform, architecture, compiler etc."""
691 if args.iomgr_platform != 'native':
692 raise ValueError(
693 'Python builds no longer differentiate IO Manager platforms, please use "native"'
694 )
695
696 if args.arch == 'x86':
697 bits = '32'
698 else:
699 bits = '64'
700
701 if os.name == 'nt':
702 shell = ['bash']
703 builder = [
704 os.path.abspath(
705 'tools/run_tests/helper_scripts/build_python_msys2.sh')
706 ]
707 builder_prefix_arguments = ['MINGW{}'.format(bits)]
708 venv_relative_python = ['Scripts/python.exe']
709 toolchain = ['mingw32']
710 else:
711 shell = []
712 builder = [
713 os.path.abspath(
714 'tools/run_tests/helper_scripts/build_python.sh')
715 ]
716 builder_prefix_arguments = []
717 venv_relative_python = ['bin/python']
718 toolchain = ['unix']
719
720 runner = [
721 os.path.abspath('tools/run_tests/helper_scripts/run_python.sh')
722 ]
723
724 config_vars = _PythonConfigVars(shell, builder,
725 builder_prefix_arguments,
726 venv_relative_python, toolchain, runner)
727 python37_config = _python_config_generator(name='py37',
728 major='3',
729 minor='7',
730 bits=bits,
731 config_vars=config_vars)
732 python38_config = _python_config_generator(name='py38',
733 major='3',
734 minor='8',
735 bits=bits,
736 config_vars=config_vars)
737 python39_config = _python_config_generator(name='py39',
738 major='3',
739 minor='9',
740 bits=bits,
741 config_vars=config_vars)
742 python310_config = _python_config_generator(name='py310',
743 major='3',
744 minor='10',
745 bits=bits,
746 config_vars=config_vars)
747 pypy27_config = _pypy_config_generator(name='pypy',
748 major='2',
749 config_vars=config_vars)
750 pypy32_config = _pypy_config_generator(name='pypy3',
751 major='3',
752 config_vars=config_vars)
753
754 if args.compiler == 'default':
755 if os.name == 'nt':
756 return (python38_config,)
757 elif os.uname()[0] == 'Darwin':
758 # NOTE(rbellevi): Testing takes significantly longer on
759 # MacOS, so we restrict the number of interpreter versions
760 # tested.
761 return (python38_config,)
762 elif platform.machine() == 'aarch64':
763 # Currently the python_debian11_default_arm64 docker image
764 # only has python3.9 installed (and that seems sufficient
765 # for arm64 testing)
766 return (python39_config,)
767 else:
768 return (
769 python37_config,
770 python38_config,
771 )
772 elif args.compiler == 'python3.7':
773 return (python37_config,)
774 elif args.compiler == 'python3.8':
775 return (python38_config,)
776 elif args.compiler == 'python3.9':
777 return (python39_config,)
778 elif args.compiler == 'python3.10':
779 return (python310_config,)
780 elif args.compiler == 'pypy':
781 return (pypy27_config,)
782 elif args.compiler == 'pypy3':
783 return (pypy32_config,)
784 elif args.compiler == 'python_alpine':
785 return (python38_config,)
786 elif args.compiler == 'all_the_cpythons':
787 return (
788 python37_config,
789 python38_config,
790 python39_config,
791 python310_config,
792 )
793 else:
794 raise Exception('Compiler %s not supported.' % args.compiler)
795
796 def __str__(self):
797 return 'python'
798
799
800 class RubyLanguage(object):
801
802 def configure(self, config, args):
803 self.config = config
804 self.args = args
805 _check_compiler(self.args.compiler, ['default'])
806
807 def test_specs(self):
808 tests = [
809 self.config.job_spec(['tools/run_tests/helper_scripts/run_ruby.sh'],
810 timeout_seconds=10 * 60,
811 environ=_FORCE_ENVIRON_FOR_WRAPPERS)
812 ]
813 # TODO(apolcyn): re-enable the following tests after
814 # https://bugs.ruby-lang.org/issues/15499 is fixed:
815 # They previously worked on ruby 2.5 but needed to be disabled
816 # after dropping support for ruby 2.5:
817 # - src/ruby/end2end/channel_state_test.rb
818 # - src/ruby/end2end/sig_int_during_channel_watch_test.rb
819 for test in [
820 'src/ruby/end2end/sig_handling_test.rb',
821 'src/ruby/end2end/channel_closing_test.rb',
822 'src/ruby/end2end/killed_client_thread_test.rb',
823 'src/ruby/end2end/forking_client_test.rb',
824 'src/ruby/end2end/grpc_class_init_test.rb',
825 'src/ruby/end2end/multiple_killed_watching_threads_test.rb',
826 'src/ruby/end2end/load_grpc_with_gc_stress_test.rb',
827 'src/ruby/end2end/client_memory_usage_test.rb',
828 'src/ruby/end2end/package_with_underscore_test.rb',
829 'src/ruby/end2end/graceful_sig_handling_test.rb',
830 'src/ruby/end2end/graceful_sig_stop_test.rb',
831 'src/ruby/end2end/errors_load_before_grpc_lib_test.rb',
832 'src/ruby/end2end/logger_load_before_grpc_lib_test.rb',
833 'src/ruby/end2end/status_codes_load_before_grpc_lib_test.rb',
834 'src/ruby/end2end/call_credentials_timeout_test.rb',
835 'src/ruby/end2end/call_credentials_returning_bad_metadata_doesnt_kill_background_thread_test.rb'
836 ]:
837 tests.append(
838 self.config.job_spec(['ruby', test],
839 shortname=test,
840 timeout_seconds=20 * 60,
841 environ=_FORCE_ENVIRON_FOR_WRAPPERS))
842 return tests
843
844 def pre_build_steps(self):
845 return [['tools/run_tests/helper_scripts/pre_build_ruby.sh']]
846
847 def build_steps(self):
848 return [['tools/run_tests/helper_scripts/build_ruby.sh']]
849
850 def build_steps_environ(self):
851 """Extra environment variables set for pre_build_steps and build_steps jobs."""
852 return {}
853
854 def post_tests_steps(self):
855 return [['tools/run_tests/helper_scripts/post_tests_ruby.sh']]
856
857 def dockerfile_dir(self):
858 return 'tools/dockerfile/test/ruby_debian11_%s' % _docker_arch_suffix(
859 self.args.arch)
860
861 def __str__(self):
862 return 'ruby'
863
864
865 class CSharpLanguage(object):
866
867 def __init__(self):
868 self.platform = platform_string()
869
870 def configure(self, config, args):
871 self.config = config
872 self.args = args
873 _check_compiler(self.args.compiler, ['default', 'coreclr', 'mono'])
874 if self.args.compiler == 'default':
875 # test both runtimes by default
876 self.test_runtimes = ['coreclr', 'mono']
877 else:
878 # only test the specified runtime
879 self.test_runtimes = [self.args.compiler]
880
881 if self.platform == 'windows':
882 _check_arch(self.args.arch, ['default'])
883 self._cmake_arch_option = 'x64'
884 else:
885 self._docker_distro = 'debian11'
886
887 def test_specs(self):
888 with open('src/csharp/tests.json') as f:
889 tests_by_assembly = json.load(f)
890
891 msbuild_config = _MSBUILD_CONFIG[self.config.build_config]
892 nunit_args = ['--labels=All', '--noresult', '--workers=1']
893
894 specs = []
895 for test_runtime in self.test_runtimes:
896 if test_runtime == 'coreclr':
897 assembly_extension = '.dll'
898 assembly_subdir = 'bin/%s/netcoreapp3.1' % msbuild_config
899 runtime_cmd = ['dotnet', 'exec']
900 elif test_runtime == 'mono':
901 assembly_extension = '.exe'
902 assembly_subdir = 'bin/%s/net45' % msbuild_config
903 if self.platform == 'windows':
904 runtime_cmd = []
905 elif self.platform == 'mac':
906 # mono before version 5.2 on MacOS defaults to 32bit runtime
907 runtime_cmd = ['mono', '--arch=64']
908 else:
909 runtime_cmd = ['mono']
910 else:
911 raise Exception('Illegal runtime "%s" was specified.')
912
913 for assembly in six.iterkeys(tests_by_assembly):
914 assembly_file = 'src/csharp/%s/%s/%s%s' % (
915 assembly, assembly_subdir, assembly, assembly_extension)
916
917 # normally, run each test as a separate process
918 for test in tests_by_assembly[assembly]:
919 cmdline = runtime_cmd + [assembly_file,
920 '--test=%s' % test] + nunit_args
921 specs.append(
922 self.config.job_spec(
923 cmdline,
924 shortname='csharp.%s.%s' % (test_runtime, test),
925 environ=_FORCE_ENVIRON_FOR_WRAPPERS))
926 return specs
927
928 def pre_build_steps(self):
929 if self.platform == 'windows':
930 return [['tools\\run_tests\\helper_scripts\\pre_build_csharp.bat']]
931 else:
932 return [['tools/run_tests/helper_scripts/pre_build_csharp.sh']]
933
934 def build_steps(self):
935 if self.platform == 'windows':
936 return [['tools\\run_tests\\helper_scripts\\build_csharp.bat']]
937 else:
938 return [['tools/run_tests/helper_scripts/build_csharp.sh']]
939
940 def build_steps_environ(self):
941 """Extra environment variables set for pre_build_steps and build_steps jobs."""
942 if self.platform == 'windows':
943 return {'ARCHITECTURE': self._cmake_arch_option}
944 else:
945 return {}
946
947 def post_tests_steps(self):
948 if self.platform == 'windows':
949 return [['tools\\run_tests\\helper_scripts\\post_tests_csharp.bat']]
950 else:
951 return [['tools/run_tests/helper_scripts/post_tests_csharp.sh']]
952
953 def dockerfile_dir(self):
954 return 'tools/dockerfile/test/csharp_%s_%s' % (
955 self._docker_distro, _docker_arch_suffix(self.args.arch))
956
957 def __str__(self):
958 return 'csharp'
959
960
961 class ObjCLanguage(object):
962
963 def configure(self, config, args):
964 self.config = config
965 self.args = args
966 _check_compiler(self.args.compiler, ['default'])
967
968 def test_specs(self):
969 out = []
970 # Currently not supporting compiling as frameworks in Bazel
971 # TODO(jtattermusch): verify the above claim is still accurate.
972 out.append(
973 self.config.job_spec(
974 ['src/objective-c/tests/build_one_example.sh'],
975 timeout_seconds=20 * 60,
976 shortname='ios-buildtest-example-sample-frameworks',
977 cpu_cost=1e6,
978 environ={
979 'SCHEME': 'Sample',
980 'EXAMPLE_PATH': 'src/objective-c/examples/Sample',
981 'FRAMEWORKS': 'YES'
982 }))
983 # TODO(jtattermusch): Create bazel target for the sample and remove the test task from here.
984 out.append(
985 self.config.job_spec(
986 ['src/objective-c/tests/build_one_example.sh'],
987 timeout_seconds=20 * 60,
988 shortname='ios-buildtest-example-switftsample',
989 cpu_cost=1e6,
990 environ={
991 'SCHEME': 'SwiftSample',
992 'EXAMPLE_PATH': 'src/objective-c/examples/SwiftSample'
993 }))
994 # Disabled due to #20258
995 # TODO (mxyan): Reenable this test when #20258 is resolved.
996 # out.append(
997 # self.config.job_spec(
998 # ['src/objective-c/tests/build_one_example_bazel.sh'],
999 # timeout_seconds=20 * 60,
1000 # shortname='ios-buildtest-example-watchOS-sample',
1001 # cpu_cost=1e6,
1002 # environ={
1003 # 'SCHEME': 'watchOS-sample-WatchKit-App',
1004 # 'EXAMPLE_PATH': 'src/objective-c/examples/watchOS-sample',
1005 # 'FRAMEWORKS': 'NO'
1006 # }))
1007
1008 # TODO(jtattermusch): move the test out of the test/core/iomgr/CFStreamTests directory?
1009 # How does one add the cfstream dependency in bazel?
1010 out.append(
1011 self.config.job_spec(
1012 ['test/core/iomgr/ios/CFStreamTests/build_and_run_tests.sh'],
1013 timeout_seconds=60 * 60,
1014 shortname='ios-test-cfstream-tests',
1015 cpu_cost=1e6,
1016 environ=_FORCE_ENVIRON_FOR_WRAPPERS))
1017 # TODO(jtattermusch): Create bazel target for the test (how does one add the cronet dependency in bazel?)
1018 # TODO(jtattermusch): move the test out of the test/cpp/ios directory?
1019 out.append(
1020 self.config.job_spec(['test/cpp/ios/build_and_run_tests.sh'],
1021 timeout_seconds=60 * 60,
1022 shortname='ios-cpp-test-cronet',
1023 cpu_cost=1e6,
1024 environ=_FORCE_ENVIRON_FOR_WRAPPERS))
1025 return sorted(out)
1026
1027 def pre_build_steps(self):
1028 return []
1029
1030 def build_steps(self):
1031 return []
1032
1033 def build_steps_environ(self):
1034 """Extra environment variables set for pre_build_steps and build_steps jobs."""
1035 return {}
1036
1037 def post_tests_steps(self):
1038 return []
1039
1040 def dockerfile_dir(self):
1041 return None
1042
1043 def __str__(self):
1044 return 'objc'
1045
1046
1047 class Sanity(object):
1048
1049 def __init__(self, config_file):
1050 self.config_file = config_file
1051
1052 def configure(self, config, args):
1053 self.config = config
1054 self.args = args
1055 _check_compiler(self.args.compiler, ['default'])
1056
1057 def test_specs(self):
1058 import yaml
1059 with open('tools/run_tests/sanity/%s' % self.config_file, 'r') as f:
1060 environ = {'TEST': 'true'}
1061 if _is_use_docker_child():
1062 environ['CLANG_FORMAT_SKIP_DOCKER'] = 'true'
1063 environ['CLANG_TIDY_SKIP_DOCKER'] = 'true'
1064 environ['IWYU_SKIP_DOCKER'] = 'true'
1065 # sanity tests run tools/bazel wrapper concurrently
1066 # and that can result in a download/run race in the wrapper.
1067 # under docker we already have the right version of bazel
1068 # so we can just disable the wrapper.
1069 environ['DISABLE_BAZEL_WRAPPER'] = 'true'
1070 return [
1071 self.config.job_spec(cmd['script'].split(),
1072 timeout_seconds=30 * 60,
1073 environ=environ,
1074 cpu_cost=cmd.get('cpu_cost', 1))
1075 for cmd in yaml.load(f)
1076 ]
1077
1078 def pre_build_steps(self):
1079 return []
1080
1081 def build_steps(self):
1082 return []
1083
1084 def build_steps_environ(self):
1085 """Extra environment variables set for pre_build_steps and build_steps jobs."""
1086 return {}
1087
1088 def post_tests_steps(self):
1089 return []
1090
1091 def dockerfile_dir(self):
1092 return 'tools/dockerfile/test/sanity'
1093
1094 def __str__(self):
1095 return 'sanity'
1096
1097
1098 # different configurations we can run under
1099 with open('tools/run_tests/generated/configs.json') as f:
1100 _CONFIGS = dict(
1101 (cfg['config'], Config(**cfg)) for cfg in ast.literal_eval(f.read()))
1102
1103 _LANGUAGES = {
1104 'c++': CLanguage('cxx', 'c++'),
1105 'c': CLanguage('c', 'c'),
1106 'grpc-node': RemoteNodeLanguage(),
1107 'php7': Php7Language(),
1108 'python': PythonLanguage(),
1109 'ruby': RubyLanguage(),
1110 'csharp': CSharpLanguage(),
1111 'objc': ObjCLanguage(),
1112 'sanity': Sanity('sanity_tests.yaml'),
1113 'clang-tidy': Sanity('clang_tidy_tests.yaml'),
1114 'iwyu': Sanity('iwyu_tests.yaml'),
1115 }
1116
1117 _MSBUILD_CONFIG = {
1118 'dbg': 'Debug',
1119 'opt': 'Release',
1120 'gcov': 'Debug',
1121 }
1122
1123
1124 def _build_step_environ(cfg, extra_env={}):
1125 """Environment variables set for each build step."""
1126 environ = {'CONFIG': cfg, 'GRPC_RUN_TESTS_JOBS': str(args.jobs)}
1127 msbuild_cfg = _MSBUILD_CONFIG.get(cfg)
1128 if msbuild_cfg:
1129 environ['MSBUILD_CONFIG'] = msbuild_cfg
1130 environ.update(extra_env)
1131 return environ
1132
1133
1134 def _windows_arch_option(arch):
1135 """Returns msbuild cmdline option for selected architecture."""
1136 if arch == 'default' or arch == 'x86':
1137 return '/p:Platform=Win32'
1138 elif arch == 'x64':
1139 return '/p:Platform=x64'
1140 else:
1141 print('Architecture %s not supported.' % arch)
1142 sys.exit(1)
1143
1144
1145 def _check_arch_option(arch):
1146 """Checks that architecture option is valid."""
1147 if platform_string() == 'windows':
1148 _windows_arch_option(arch)
1149 elif platform_string() == 'linux':
1150 # On linux, we need to be running under docker with the right architecture.
1151 runtime_machine = platform.machine()
1152 runtime_arch = platform.architecture()[0]
1153 if arch == 'default':
1154 return
1155 elif runtime_machine == 'x86_64' and runtime_arch == '64bit' and arch == 'x64':
1156 return
1157 elif runtime_machine == 'x86_64' and runtime_arch == '32bit' and arch == 'x86':
1158 return
1159 elif runtime_machine == 'aarch64' and runtime_arch == '64bit' and arch == 'arm64':
1160 return
1161 else:
1162 print(
1163 'Architecture %s does not match current runtime architecture.' %
1164 arch)
1165 sys.exit(1)
1166 else:
1167 if args.arch != 'default':
1168 print('Architecture %s not supported on current platform.' %
1169 args.arch)
1170 sys.exit(1)
1171
1172
1173 def _docker_arch_suffix(arch):
1174 """Returns suffix to dockerfile dir to use."""
1175 if arch == 'default' or arch == 'x64':
1176 return 'x64'
1177 elif arch == 'x86':
1178 return 'x86'
1179 elif arch == 'arm64':
1180 return 'arm64'
1181 else:
1182 print('Architecture %s not supported with current settings.' % arch)
1183 sys.exit(1)
1184
1185
1186 def runs_per_test_type(arg_str):
1187 """Auxiliary function to parse the "runs_per_test" flag.
1188
1189 Returns:
1190 A positive integer or 0, the latter indicating an infinite number of
1191 runs.
1192
1193 Raises:
1194 argparse.ArgumentTypeError: Upon invalid input.
1195 """
1196 if arg_str == 'inf':
1197 return 0
1198 try:
1199 n = int(arg_str)
1200 if n <= 0:
1201 raise ValueError
1202 return n
1203 except:
1204 msg = '\'{}\' is not a positive integer or \'inf\''.format(arg_str)
1205 raise argparse.ArgumentTypeError(msg)
1206
1207
1208 def percent_type(arg_str):
1209 pct = float(arg_str)
1210 if pct > 100 or pct < 0:
1211 raise argparse.ArgumentTypeError(
1212 "'%f' is not a valid percentage in the [0, 100] range" % pct)
1213 return pct
1214
1215
1216 # This is math.isclose in python >= 3.5
1217 def isclose(a, b, rel_tol=1e-09, abs_tol=0.0):
1218 return abs(a - b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)
1219
1220
1221 def _shut_down_legacy_server(legacy_server_port):
1222 """Shut down legacy version of port server."""
1223 try:
1224 version = int(
1225 urllib.request.urlopen('http://localhost:%d/version_number' %
1226 legacy_server_port,
1227 timeout=10).read())
1228 except:
1229 pass
1230 else:
1231 urllib.request.urlopen('http://localhost:%d/quitquitquit' %
1232 legacy_server_port).read()
1233
1234
1235 def _calculate_num_runs_failures(list_of_results):
1236 """Calculate number of runs and failures for a particular test.
1237
1238 Args:
1239 list_of_results: (List) of JobResult object.
1240 Returns:
1241 A tuple of total number of runs and failures.
1242 """
1243 num_runs = len(list_of_results) # By default, there is 1 run per JobResult.
1244 num_failures = 0
1245 for jobresult in list_of_results:
1246 if jobresult.retries > 0:
1247 num_runs += jobresult.retries
1248 if jobresult.num_failures > 0:
1249 num_failures += jobresult.num_failures
1250 return num_runs, num_failures
1251
1252
1253 class BuildAndRunError(object):
1254 """Represents error type in _build_and_run."""
1255
1256 BUILD = object()
1257 TEST = object()
1258 POST_TEST = object()
1259
1260
1261 # returns a list of things that failed (or an empty list on success)
1262 def _build_and_run(check_cancelled,
1263 newline_on_success,
1264 xml_report=None,
1265 build_only=False):
1266 """Do one pass of building & running tests."""
1267 # build latest sequentially
1268 num_failures, resultset = jobset.run(build_steps,
1269 maxjobs=1,
1270 stop_on_failure=True,
1271 newline_on_success=newline_on_success,
1272 travis=args.travis)
1273 if num_failures:
1274 return [BuildAndRunError.BUILD]
1275
1276 if build_only:
1277 if xml_report:
1278 report_utils.render_junit_xml_report(
1279 resultset, xml_report, suite_name=args.report_suite_name)
1280 return []
1281
1282 # start antagonists
1283 antagonists = [
1284 subprocess.Popen(['tools/run_tests/python_utils/antagonist.py'])
1285 for _ in range(0, args.antagonists)
1286 ]
1287 start_port_server.start_port_server()
1288 resultset = None
1289 num_test_failures = 0
1290 try:
1291 infinite_runs = runs_per_test == 0
1292 one_run = set(spec for language in languages
1293 for spec in language.test_specs()
1294 if (re.search(args.regex, spec.shortname) and
1295 (args.regex_exclude == '' or
1296 not re.search(args.regex_exclude, spec.shortname))))
1297 # When running on travis, we want out test runs to be as similar as possible
1298 # for reproducibility purposes.
1299 if args.travis and args.max_time <= 0:
1300 massaged_one_run = sorted(one_run, key=lambda x: x.cpu_cost)
1301 else:
1302 # whereas otherwise, we want to shuffle things up to give all tests a
1303 # chance to run.
1304 massaged_one_run = list(
1305 one_run) # random.sample needs an indexable seq.
1306 num_jobs = len(massaged_one_run)
1307 # for a random sample, get as many as indicated by the 'sample_percent'
1308 # argument. By default this arg is 100, resulting in a shuffle of all
1309 # jobs.
1310 sample_size = int(num_jobs * args.sample_percent / 100.0)
1311 massaged_one_run = random.sample(massaged_one_run, sample_size)
1312 if not isclose(args.sample_percent, 100.0):
1313 assert args.runs_per_test == 1, "Can't do sampling (-p) over multiple runs (-n)."
1314 print("Running %d tests out of %d (~%d%%)" %
1315 (sample_size, num_jobs, args.sample_percent))
1316 if infinite_runs:
1317 assert len(massaged_one_run
1318 ) > 0, 'Must have at least one test for a -n inf run'
1319 runs_sequence = (itertools.repeat(massaged_one_run) if infinite_runs
1320 else itertools.repeat(massaged_one_run, runs_per_test))
1321 all_runs = itertools.chain.from_iterable(runs_sequence)
1322
1323 if args.quiet_success:
1324 jobset.message(
1325 'START',
1326 'Running tests quietly, only failing tests will be reported',
1327 do_newline=True)
1328 num_test_failures, resultset = jobset.run(
1329 all_runs,
1330 check_cancelled,
1331 newline_on_success=newline_on_success,
1332 travis=args.travis,
1333 maxjobs=args.jobs,
1334 maxjobs_cpu_agnostic=max_parallel_tests_for_current_platform(),
1335 stop_on_failure=args.stop_on_failure,
1336 quiet_success=args.quiet_success,
1337 max_time=args.max_time)
1338 if resultset:
1339 for k, v in sorted(resultset.items()):
1340 num_runs, num_failures = _calculate_num_runs_failures(v)
1341 if num_failures > 0:
1342 if num_failures == num_runs: # what about infinite_runs???
1343 jobset.message('FAILED', k, do_newline=True)
1344 else:
1345 jobset.message('FLAKE',
1346 '%s [%d/%d runs flaked]' %
1347 (k, num_failures, num_runs),
1348 do_newline=True)
1349 finally:
1350 for antagonist in antagonists:
1351 antagonist.kill()
1352 if args.bq_result_table and resultset:
1353 upload_extra_fields = {
1354 'compiler': args.compiler,
1355 'config': args.config,
1356 'iomgr_platform': args.iomgr_platform,
1357 'language': args.language[
1358 0
1359 ], # args.language is a list but will always have one element when uploading to BQ is enabled.
1360 'platform': platform_string()
1361 }
1362 try:
1363 upload_results_to_bq(resultset, args.bq_result_table,
1364 upload_extra_fields)
1365 except NameError as e:
1366 logging.warning(
1367 e) # It's fine to ignore since this is not critical
1368 if xml_report and resultset:
1369 report_utils.render_junit_xml_report(
1370 resultset,
1371 xml_report,
1372 suite_name=args.report_suite_name,
1373 multi_target=args.report_multi_target)
1374
1375 number_failures, _ = jobset.run(post_tests_steps,
1376 maxjobs=1,
1377 stop_on_failure=False,
1378 newline_on_success=newline_on_success,
1379 travis=args.travis)
1380
1381 out = []
1382 if number_failures:
1383 out.append(BuildAndRunError.POST_TEST)
1384 if num_test_failures:
1385 out.append(BuildAndRunError.TEST)
1386
1387 return out
1388
1389
1390 # parse command line
1391 argp = argparse.ArgumentParser(description='Run grpc tests.')
1392 argp.add_argument('-c',
1393 '--config',
1394 choices=sorted(_CONFIGS.keys()),
1395 default='opt')
1396 argp.add_argument(
1397 '-n',
1398 '--runs_per_test',
1399 default=1,
1400 type=runs_per_test_type,
1401 help='A positive integer or "inf". If "inf", all tests will run in an '
1402 'infinite loop. Especially useful in combination with "-f"')
1403 argp.add_argument('-r', '--regex', default='.*', type=str)
1404 argp.add_argument('--regex_exclude', default='', type=str)
1405 argp.add_argument('-j', '--jobs', default=multiprocessing.cpu_count(), type=int)
1406 argp.add_argument('-s', '--slowdown', default=1.0, type=float)
1407 argp.add_argument('-p',
1408 '--sample_percent',
1409 default=100.0,
1410 type=percent_type,
1411 help='Run a random sample with that percentage of tests')
1412 argp.add_argument(
1413 '-t',
1414 '--travis',
1415 default=False,
1416 action='store_const',
1417 const=True,
1418 help='When set, indicates that the script is running on CI (= not locally).'
1419 )
1420 argp.add_argument('--newline_on_success',
1421 default=False,
1422 action='store_const',
1423 const=True)
1424 argp.add_argument('-l',
1425 '--language',
1426 choices=sorted(_LANGUAGES.keys()),
1427 nargs='+',
1428 required=True)
1429 argp.add_argument('-S',
1430 '--stop_on_failure',
1431 default=False,
1432 action='store_const',
1433 const=True)
1434 argp.add_argument('--use_docker',
1435 default=False,
1436 action='store_const',
1437 const=True,
1438 help='Run all the tests under docker. That provides ' +
1439 'additional isolation and prevents the need to install ' +
1440 'language specific prerequisites. Only available on Linux.')
1441 argp.add_argument(
1442 '--allow_flakes',
1443 default=False,
1444 action='store_const',
1445 const=True,
1446 help=
1447 'Allow flaky tests to show as passing (re-runs failed tests up to five times)'
1448 )
1449 argp.add_argument(
1450 '--arch',
1451 choices=['default', 'x86', 'x64', 'arm64'],
1452 default='default',
1453 help=
1454 'Selects architecture to target. For some platforms "default" is the only supported choice.'
1455 )
1456 argp.add_argument(
1457 '--compiler',
1458 choices=[
1459 'default',
1460 'gcc7',
1461 'gcc10.2',
1462 'gcc10.2_openssl102',
1463 'gcc12',
1464 'gcc_musl',
1465 'clang6',
1466 'clang15',
1467 'python2.7',
1468 'python3.5',
1469 'python3.7',
1470 'python3.8',
1471 'python3.9',
1472 'pypy',
1473 'pypy3',
1474 'python_alpine',
1475 'all_the_cpythons',
1476 'electron1.3',
1477 'electron1.6',
1478 'coreclr',
1479 'cmake',
1480 'cmake_ninja_vs2017',
1481 'cmake_vs2017',
1482 'cmake_vs2019',
1483 'mono',
1484 ],
1485 default='default',
1486 help=
1487 'Selects compiler to use. Allowed values depend on the platform and language.'
1488 )
1489 argp.add_argument('--iomgr_platform',
1490 choices=['native', 'gevent', 'asyncio'],
1491 default='native',
1492 help='Selects iomgr platform to build on')
1493 argp.add_argument('--build_only',
1494 default=False,
1495 action='store_const',
1496 const=True,
1497 help='Perform all the build steps but don\'t run any tests.')
1498 argp.add_argument('--measure_cpu_costs',
1499 default=False,
1500 action='store_const',
1501 const=True,
1502 help='Measure the cpu costs of tests')
1503 argp.add_argument('-a', '--antagonists', default=0, type=int)
1504 argp.add_argument('-x',
1505 '--xml_report',
1506 default=None,
1507 type=str,
1508 help='Generates a JUnit-compatible XML report')
1509 argp.add_argument('--report_suite_name',
1510 default='tests',
1511 type=str,
1512 help='Test suite name to use in generated JUnit XML report')
1513 argp.add_argument(
1514 '--report_multi_target',
1515 default=False,
1516 const=True,
1517 action='store_const',
1518 help='Generate separate XML report for each test job (Looks better in UIs).'
1519 )
1520 argp.add_argument(
1521 '--quiet_success',
1522 default=False,
1523 action='store_const',
1524 const=True,
1525 help=
1526 'Don\'t print anything when a test passes. Passing tests also will not be reported in XML report. '
1527 + 'Useful when running many iterations of each test (argument -n).')
1528 argp.add_argument(
1529 '--force_default_poller',
1530 default=False,
1531 action='store_const',
1532 const=True,
1533 help='Don\'t try to iterate over many polling strategies when they exist')
1534 argp.add_argument(
1535 '--force_use_pollers',
1536 default=None,
1537 type=str,
1538 help='Only use the specified comma-delimited list of polling engines. '
1539 'Example: --force_use_pollers epoll1,poll '
1540 ' (This flag has no effect if --force_default_poller flag is also used)')
1541 argp.add_argument('--max_time',
1542 default=-1,
1543 type=int,
1544 help='Maximum test runtime in seconds')
1545 argp.add_argument('--bq_result_table',
1546 default='',
1547 type=str,
1548 nargs='?',
1549 help='Upload test results to a specified BQ table.')
1550 args = argp.parse_args()
1551
1552 flaky_tests = set()
1553 shortname_to_cpu = {}
1554
1555 if args.force_default_poller:
1556 _POLLING_STRATEGIES = {}
1557 elif args.force_use_pollers:
1558 _POLLING_STRATEGIES[platform_string()] = args.force_use_pollers.split(',')
1559
1560 jobset.measure_cpu_costs = args.measure_cpu_costs
1561
1562 # grab config
1563 run_config = _CONFIGS[args.config]
1564 build_config = run_config.build_config
1565
1566 # TODO(jtattermusch): is this setting applied/being used?
1567 if args.travis:
1568 _FORCE_ENVIRON_FOR_WRAPPERS = {'GRPC_TRACE': 'api'}
1569
1570 languages = set(_LANGUAGES[l] for l in args.language)
1571 for l in languages:
1572 l.configure(run_config, args)
1573
1574 if len(languages) != 1:
1575 print('Building multiple languages simultaneously is not supported!')
1576 sys.exit(1)
1577
1578 # If --use_docker was used, respawn the run_tests.py script under a docker container
1579 # instead of continuing.
1580 if args.use_docker:
1581 if not args.travis:
1582 print('Seen --use_docker flag, will run tests under docker.')
1583 print('')
1584 print(
1585 'IMPORTANT: The changes you are testing need to be locally committed'
1586 )
1587 print(
1588 'because only the committed changes in the current branch will be')
1589 print('copied to the docker environment.')
1590 time.sleep(5)
1591
1592 dockerfile_dirs = set([l.dockerfile_dir() for l in languages])
1593 if len(dockerfile_dirs) > 1:
1594 print('Languages to be tested require running under different docker '
1595 'images.')
1596 sys.exit(1)
1597 else:
1598 dockerfile_dir = next(iter(dockerfile_dirs))
1599
1600 child_argv = [arg for arg in sys.argv if not arg == '--use_docker']
1601 run_tests_cmd = 'python3 tools/run_tests/run_tests.py %s' % ' '.join(
1602 child_argv[1:])
1603
1604 env = os.environ.copy()
1605 env['DOCKERFILE_DIR'] = dockerfile_dir
1606 env['DOCKER_RUN_SCRIPT'] = 'tools/run_tests/dockerize/docker_run.sh'
1607 env['DOCKER_RUN_SCRIPT_COMMAND'] = run_tests_cmd
1608
1609 retcode = subprocess.call(
1610 'tools/run_tests/dockerize/build_and_run_docker.sh',
1611 shell=True,
1612 env=env)
1613 _print_debug_info_epilogue(dockerfile_dir=dockerfile_dir)
1614 sys.exit(retcode)
1615
1616 _check_arch_option(args.arch)
1617
1618 # collect pre-build steps (which get retried if they fail, e.g. to avoid
1619 # flakes on downloading dependencies etc.)
1620 build_steps = list(
1621 set(
1622 jobset.JobSpec(cmdline,
1623 environ=_build_step_environ(
1624 build_config, extra_env=l.build_steps_environ()),
1625 timeout_seconds=_PRE_BUILD_STEP_TIMEOUT_SECONDS,
1626 flake_retries=2)
1627 for l in languages
1628 for cmdline in l.pre_build_steps()))
1629
1630 # collect build steps
1631 build_steps.extend(
1632 set(
1633 jobset.JobSpec(cmdline,
1634 environ=_build_step_environ(
1635 build_config, extra_env=l.build_steps_environ()),
1636 timeout_seconds=None)
1637 for l in languages
1638 for cmdline in l.build_steps()))
1639
1640 # collect post test steps
1641 post_tests_steps = list(
1642 set(
1643 jobset.JobSpec(cmdline,
1644 environ=_build_step_environ(
1645 build_config, extra_env=l.build_steps_environ()))
1646 for l in languages
1647 for cmdline in l.post_tests_steps()))
1648 runs_per_test = args.runs_per_test
1649
1650 errors = _build_and_run(check_cancelled=lambda: False,
1651 newline_on_success=args.newline_on_success,
1652 xml_report=args.xml_report,
1653 build_only=args.build_only)
1654 if not errors:
1655 jobset.message('SUCCESS', 'All tests passed', do_newline=True)
1656 else:
1657 jobset.message('FAILED', 'Some tests failed', do_newline=True)
1658
1659 if not _is_use_docker_child():
1660 # if --use_docker was used, the outer invocation of run_tests.py will
1661 # print the debug info instead.
1662 _print_debug_info_epilogue()
1663
1664 exit_code = 0
1665 if BuildAndRunError.BUILD in errors:
1666 exit_code |= 1
1667 if BuildAndRunError.TEST in errors:
1668 exit_code |= 2
1669 if BuildAndRunError.POST_TEST in errors:
1670 exit_code |= 4
1671 sys.exit(exit_code)