Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 29.4k
Expand file tree
/
Copy pathrun-tests.py
More file actions
Latest commit
executable file
·594 lines (534 loc) · 22.1 KB
/
Copy pathrun-tests.py
File metadata and controls
executable file
·594 lines (534 loc) · 22.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
#!/usr/bin/env python3
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
importasyncio
importio
importlogging
importos
importplatform
importpty
importqueueasQueue
importre
importshutil
importsubprocess
importsys
importtempfile
importtime
importuuid
fromargparseimportArgumentParser
frommultiprocessingimportManager
fromthreadingimportLock, Thread
# Append `SPARK_HOME/dev` to the Python path so that we can import the sparktestsupport module
sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), "../dev/"))
fromsparktestsupportimportSPARK_HOME
fromsparktestsupport.modulesimportall_modules, pyspark_sql# noqa
fromsparktestsupport.shellutilsimportsubprocess_check_output, which
python_modules=dict((m.name, m) forminall_modulesifm.python_test_goalsifm.name!="root")
defprint_red(text):
print("\033[31m"+text+"\033[0m")
defget_valid_filename(s):
"""Replace whitespaces and special characters in the given string to get a valid file name."""
s=s.strip().replace(" ", "_").replace(os.sep, "_")
returnre.sub(r"(?u)[^-\w.]", "", s)
SKIPPED_TESTS=None
LOG_FILE=os.path.join(SPARK_HOME, "python/unit-tests.log")
FAILURE_REPORTING_LOCK=Lock()
LOGGER=logging.getLogger()
# Find out where the assembly jars are located.
# TODO: revisit for Scala 2.13
SPARK_DIST_CLASSPATH=""
if"SPARK_SKIP_CONNECT_COMPAT_TESTS"notinos.environ:
forscalain ["2.13"]:
build_dir=os.path.join(SPARK_HOME, "assembly", "target", "scala-"+scala)
ifos.path.isdir(build_dir):
SPARK_DIST_CLASSPATH=os.path.join(build_dir, "jars", "*")
break
else:
raiseRuntimeError("Cannot find assembly build directory, please build Spark first.")
classTestRunner:
def__init__(self, test_name, cmd, env, test_output, timeout=None):
self.test_name=test_name
self.cmd=cmd
self.env=env
self.test_output=test_output
self.timeout=timeout
self.p=None
self.pdb_mode=False
self.master_fd=None
self.write_task=None
self.read_task=None
self.timeout_task=None
defrun(self):
"""
Run a command in subprocess, with stdin, stdout, stderr hooked.
In normaly case, all the outputs from subprocess will be redirected to
the test_output file.
When `(Pdb)` is detected, the subprocess will be in interactive mode,
and the output will be redirected to the console.
"""
self.master_fd, slave_fd=pty.openpty()
# Start child connected to the PTY
self.p=subprocess.Popen(
self.cmd,
env=self.env,
stdin=slave_fd,
stdout=slave_fd,
stderr=slave_fd,
)
os.close(slave_fd)
try:
asyncio.run(self.handle_inout())
exceptsubprocess.TimeoutExpired:
LOGGER.error(f"Test {self.test_name} timed out after {self.timeout} seconds")
try:
returnself.p.wait(timeout=30)
exceptsubprocess.TimeoutExpired:
# If SIGTERM is intercepted, do a hard kill
self.p.kill()
returnself.p.wait()
asyncdefhandle_inout(self):
tasks= []
self.read_task=asyncio.create_task(self.read_from_child())
tasks.append(self.read_task)
ifself.timeoutisnotNone:
self.timeout_task=asyncio.create_task(self.check_timeout())
tasks.append(self.timeout_task)
try:
awaitasyncio.gather(*tasks)
exceptasyncio.CancelledError:
pass
defoutput_line(self, line):
ifself.pdb_mode:
sys.stdout.write(line.decode("utf-8", "replace"))
sys.stdout.flush()
else:
ifisinstance(self.test_output, io.TextIOBase):
self.test_output.write(line.decode("utf-8", "replace"))
else:
self.test_output.write(line)
defprocess_buffer(self, buffer, force_flush=False):
# Process all full lines first
while (nl:=buffer.find(b"\n")) !=-1:
self.output_line(buffer[: nl+1])
buffer=buffer[nl+1 :]
# Process the remaining buffer
ifb"(Pdb)"inbuffer:
self.pdb_mode=True
self.output_line(buffer)
returnb""
elifforce_flush:
self.output_line(buffer)
returnb""
else:
returnbuffer
# Reader: forward child output to our stdout
asyncdefread_from_child(self):
buffer=b""
whileTrue:
try:
data=awaitasyncio.to_thread(os.read, self.master_fd, 1024)
exceptOSError:
break
ifnotdata:
break
buffer+=data
buffer=self.process_buffer(buffer)
ifself.pdb_modeandself.write_taskisNone:
self.write_task=asyncio.create_task(self.write_to_child())
buffer=self.process_buffer(buffer, force_flush=True)
self.test_output.flush()
ifself.write_taskisnotNone:
self.write_task.cancel()
try:
awaitself.write_task
exceptasyncio.CancelledError:
pass
self.write_task=None
self.pdb_mode=False
ifself.timeout_taskisnotNone:
self.timeout_task.cancel()
self.timeout_task=None
# Writer: forward our stdin to child tty
asyncdefwrite_to_child(self):
whileTrue:
data=awaitself.loop.run_in_executor(None, sys.stdin.buffer.read, 1)
ifnotdata:
break
os.write(self.master_fd, data)
# Kill the child process if the timeout is reached
asyncdefcheck_timeout(self):
awaitasyncio.sleep(self.timeout)
ifself.pdb_mode:
# We don't want to kill the process if it's in pdb mode
return
ifself.p.poll() isNone:
ifsys.platform=="linux":
self.thread_dump(self.p.pid)
self.p.terminate()
raisesubprocess.TimeoutExpired(self.cmd, self.timeout)
defthread_dump(self, pid):
pyspark_python=self.env["PYSPARK_PYTHON"]
python_path=f"{os.path.join(SPARK_HOME, 'python')}"
py4j_path=f"{os.path.join(SPARK_HOME, 'python/lib/py4j-0.10.9.9-src.zip')}"
p=subprocess.run(
[pyspark_python, "-m", "pyspark.threaddump", "-p", str(pid)],
env={
**self.env,
"PYTHONPATH": f"{python_path}:{py4j_path}:{os.environ.get('PYTHONPATH', '')}",
},
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
)
ifp.returncode==0:
LOGGER.error(f"Thread dump:\n{p.stdout.decode('utf-8')}")
elifp.returncode==5:
# pystack or psutil not installed, that's okay
pass
else:
LOGGER.error(
f"Failed to get thread dump, exit code {p.returncode}:\n{p.stdout.decode('utf-8')}"
)
defrun_individual_python_test(target_dir, test_name, pyspark_python, keep_test_output):
"""
Runs an individual test. This function is called by the multi-process runner of all tests.
Parameters
----------
target_dir
Destination for the Hive and log directory.
test_name
Test name.
pyspark_python
Python version used to run the test.
keep_test_output
Flag indicating if the test output should be retained after successful execution.
"""
env=dict(os.environ)
env.update(
{
"SPARK_DIST_CLASSPATH": SPARK_DIST_CLASSPATH,
"SPARK_TESTING": "1",
"SPARK_PREPEND_CLASSES": "1",
"PYSPARK_PYTHON": which(pyspark_python),
"PYSPARK_DRIVER_PYTHON": which(pyspark_python),
}
)
if"SPARK_CONNECT_TESTING_REMOTE"inos.environ:
env.update({"SPARK_CONNECT_TESTING_REMOTE": os.environ["SPARK_CONNECT_TESTING_REMOTE"]})
if"SPARK_SKIP_CONNECT_COMPAT_TESTS"inos.environ:
env.update({"SPARK_SKIP_JVM_REQUIRED_TESTS": os.environ["SPARK_SKIP_CONNECT_COMPAT_TESTS"]})
# Create a unique temp directory under 'target/' for each run. The TMPDIR variable is
# recognized by the tempfile module to override the default system temp directory.
tmp_dir=os.path.join(target_dir, str(uuid.uuid4()))
whileos.path.isdir(tmp_dir):
tmp_dir=os.path.join(target_dir, str(uuid.uuid4()))
os.mkdir(tmp_dir)
sock_dir=os.getenv("TMPDIR") oros.getenv("TEMP") oros.getenv("TMP") or"/tmp"
env["TMPDIR"] =tmp_dir
metastore_dir=os.path.join(tmp_dir, str(uuid.uuid4()))
whileos.path.isdir(metastore_dir):
metastore_dir=os.path.join(metastore_dir, str(uuid.uuid4()))
os.mkdir(metastore_dir)
# Also override the JVM's temp directory and log4j conf by setting driver and executor options.
log4j2_path=os.path.join(SPARK_HOME, "python/test_support/log4j2.properties")
java_options="-Djava.io.tmpdir={0} -Dlog4j.configurationFile={1}".format(tmp_dir, log4j2_path)
java_options=java_options+" -Xss4M"
spark_args= [
"--conf",
"spark.driver.extraJavaOptions='{0}'".format(java_options),
"--conf",
"spark.executor.extraJavaOptions='{0}'".format(java_options),
"--conf",
"spark.sql.warehouse.dir='{0}'".format(metastore_dir),
"--conf",
"spark.python.unix.domain.socket.dir={0}".format(sock_dir),
"pyspark-shell",
]
env["PYSPARK_SUBMIT_ARGS"] =" ".join(spark_args)
timeout=os.environ.get("PYSPARK_TEST_TIMEOUT")
iftimeoutisnotNone:
env["PYSPARK_TEST_TIMEOUT"] =timeout
timeout=int(timeout)
output_prefix=get_valid_filename(pyspark_python+"__"+test_name+"__").lstrip("_")
# Delete is always set to False since the cleanup will be either done by removing the
# whole test dir, or the test output is retained.
per_test_output=tempfile.NamedTemporaryFile(
prefix=output_prefix, dir=tmp_dir, suffix=".log", delete=False
)
LOGGER.info(
"Starting test(%s): %s (temp output: %s)", pyspark_python, test_name, per_test_output.name
)
cmd= [os.path.join(SPARK_HOME, "bin/pyspark")] +test_name.split()
start_time=time.time()
retcode=None
try:
retcode=TestRunner(test_name, cmd, env, per_test_output, timeout).run()
ifnotkeep_test_output:
# There exists a race condition in Python and it causes flakiness in MacOS
# https://github.com/python/cpython/issues/73885
ifplatform.system() =="Darwin":
os.system("rm -rf "+tmp_dir)
else:
shutil.rmtree(tmp_dir, ignore_errors=True)
exceptBaseException:
LOGGER.exception("Got exception while running %s with %s", test_name, pyspark_python)
# Here, we use os._exit() instead of sys.exit() in order to force Python to exit even if
# this code is invoked from a thread other than the main thread.
os._exit(1)
duration=time.time() -start_time
# Exit on the first failure but exclude the code 5 for no test ran, see SPARK-46801.
ifretcode!=0andretcode!=5:
try:
per_test_output.seek(0)
withFAILURE_REPORTING_LOCK:
withopen(LOG_FILE, "ab") aslog_file:
log_file.writelines(per_test_output)
# We don't want the logging lines interleave with the test output, so we read the
# full file and output with LOGGER which has internal locking.
per_test_output.seek(0)
lines= []
forlineinper_test_output:
line=line.decode("utf-8", "replace")
ifnotre.match("[0-9]+", line):
lines.append(line)
LOGGER.error(f"{test_name} with {pyspark_python} failed:\n{''.join(lines)}")
per_test_output.close()
exceptBaseException:
LOGGER.exception("Got an exception while trying to print failed test output")
finally:
print_red("\nHad test failures in %s with %s; see logs."% (test_name, pyspark_python))
# Here, we use os._exit() instead of sys.exit() in order to force Python to exit even if
# this code is invoked from a thread other than the main thread.
os._exit(-1)
else:
skipped_counts=0
try:
per_test_output.seek(0)
# Here expects skipped test output from unittest when verbosity level is
# 2 (or --verbose option is enabled).
decoded_lines=map(lambdaline: line.decode("utf-8", "replace"), iter(per_test_output))
skipped_tests=list(
filter(
lambdaline: re.search(r"test_.* \(pyspark\..*\) ... (skip|SKIP)", line),
decoded_lines,
)
)
skipped_counts=len(skipped_tests)
ifskipped_counts>0:
key= (pyspark_python, test_name)
assertSKIPPED_TESTSisnotNone
SKIPPED_TESTS[key] =skipped_tests
per_test_output.close()
exceptBaseException:
importtraceback
print_red(
"\nGot an exception while trying to store "
"skipped test output:\n%s"%traceback.format_exc()
)
# Here, we use os._exit() instead of sys.exit() in order to force Python to exit even if
# this code is invoked from a thread other than the main thread.
os._exit(-1)
ifskipped_counts!=0:
LOGGER.info(
"Finished test(%s): %s (%is) ... %s tests were skipped",
pyspark_python,
test_name,
duration,
skipped_counts,
)
else:
LOGGER.info("Finished test(%s): %s (%is)", pyspark_python, test_name, duration)
defget_default_python_executables():
return [sys.executable]
defparse_opts():
parser=ArgumentParser(prog="run-tests")
parser.add_argument(
"--python-executables",
type=str,
default=",".join(get_default_python_executables()),
help="A comma-separated list of Python executables to test against (default: %(default)s)",
)
parser.add_argument(
"--modules",
type=str,
default=",".join(sorted(python_modules.keys())),
help="A comma-separated list of Python modules to test (default: %(default)s)",
)
parser.add_argument(
"-p",
"--parallelism",
type=int,
default=4,
help="The number of suites to test in parallel (default %(default)d)",
)
parser.add_argument(
"--changed-files",
type=str,
default=None,
help="A file containing a list of changed files (default: %(default)s)",
)
parser.add_argument("--verbose", action="store_true", help="Enable additional debug logging")
group=parser.add_argument_group("Developer Options")
group.add_argument(
"--testnames",
type=str,
default=None,
help=(
"A comma-separated list of specific modules, classes and functions of doctest "
"or unittest to test. "
"For example, 'pyspark.sql.foo' to run the module as unittests or doctests, "
"'pyspark.sql.tests FooTests' to run the specific class of unittests, "
"'pyspark.sql.tests FooTests.test_foo' to run the specific unittest in the class. "
"'--modules' option is ignored if they are given."
),
)
group.add_argument(
"-k",
"--keep-test-output",
action="store_true",
default=False,
help=(
"If set to true will retain the temporary test directories. In addition, the "
"standard output and standard error are redirected to a file in the target "
"directory."
),
)
args, unknown=parser.parse_known_args()
ifunknown:
parser.error("Unsupported arguments: %s"%" ".join(unknown))
ifargs.parallelism<1:
parser.error("Parallelism cannot be less than 1")
returnargs
def_check_coverage(python_exec):
# Make sure if coverage is installed.
try:
subprocess_check_output(
[python_exec, "-c", "import coverage"], stderr=open(os.devnull, "w")
)
exceptBaseException:
print_red(
"Coverage is not installed in Python executable '%s' "
"but 'COVERAGE_PROCESS_START' environment variable is set, "
"exiting."%python_exec
)
sys.exit(-1)
defmain():
opts=parse_opts()
ifopts.verbose:
log_level=logging.DEBUG
else:
log_level=logging.INFO
should_test_modules=opts.testnamesisNone
logging.basicConfig(stream=sys.stdout, level=log_level, format="%(message)s")
LOGGER.info("Running PySpark tests. Output is in %s", LOG_FILE)
ifos.path.exists(LOG_FILE):
os.remove(LOG_FILE)
python_execs=opts.python_executables.split(",")
LOGGER.info("Will test against the following Python executables: %s", python_execs)
ifopts.changed_files:
withopen(opts.changed_files, "r") asf:
changed_files=f.read().splitlines()
os.environ["PYSPARK_CHANGED_FILES"] =opts.changed_files
LOGGER.info("Will select tests based on the following changed files: %s", changed_files)
ifshould_test_modules:
modules_to_test= []
formodule_nameinopts.modules.split(","):
ifmodule_nameinpython_modules:
modules_to_test.append(python_modules[module_name])
else:
print(
"Error: unrecognized module '%s'. Supported modules: %s"
% (module_name, ", ".join(python_modules))
)
sys.exit(-1)
LOGGER.info("Will test the following Python modules: %s", [x.nameforxinmodules_to_test])
else:
testnames_to_test=opts.testnames.split(",")
LOGGER.info("Will test the following Python tests: %s", testnames_to_test)
task_queue=Queue.PriorityQueue()
forpython_execinpython_execs:
# Check if the python executable has coverage installed when 'COVERAGE_PROCESS_START'
# environmental variable is set.
if"COVERAGE_PROCESS_START"inos.environ:
_check_coverage(python_exec)
python_implementation=subprocess_check_output(
[python_exec, "-c", "import platform; print(platform.python_implementation())"],
universal_newlines=True,
).strip()
LOGGER.info("%s python_implementation is %s", python_exec, python_implementation)
LOGGER.info(
"%s version is: %s",
python_exec,
subprocess_check_output(
[python_exec, "--version"], stderr=subprocess.STDOUT, universal_newlines=True
).strip(),
)
ifshould_test_modules:
formoduleinmodules_to_test:
ifpython_implementationnotinmodule.excluded_python_implementations:
fortest_goalinmodule.python_test_goals:
heavy_tests= [
"pyspark.streaming.tests",
"pyspark.mllib.tests",
"pyspark.tests",
"pyspark.sql.tests",
"pyspark.ml.tests",
"pyspark.pandas.tests",
]
ifany(map(lambdaprefix: test_goal.startswith(prefix), heavy_tests)):
priority=0
else:
priority=100
task_queue.put((priority, (python_exec, test_goal)))
else:
fortest_goalintestnames_to_test:
task_queue.put((0, (python_exec, test_goal)))
# Create the target directory before starting tasks to avoid races.
target_dir=os.path.abspath(os.path.join(os.path.dirname(__file__), "target"))
ifnotos.path.isdir(target_dir):
os.mkdir(target_dir)
defprocess_queue(task_queue):
whileTrue:
try:
(priority, (python_exec, test_goal)) =task_queue.get_nowait()
exceptQueue.Empty:
break
try:
run_individual_python_test(
target_dir, test_goal, python_exec, opts.keep_test_output
)
finally:
task_queue.task_done()
start_time=time.time()
for_inrange(opts.parallelism):
worker=Thread(target=process_queue, args=(task_queue,))
worker.daemon=True
worker.start()
try:
task_queue.join()
except (KeyboardInterrupt, SystemExit):
print_red("Exiting due to interrupt")
sys.exit(-1)
total_duration=time.time() -start_time
LOGGER.info("Tests passed in %i seconds", total_duration)
forkey, linesinsorted(SKIPPED_TESTS.items()):
pyspark_python, test_name=key
LOGGER.info("\nSkipped tests in %s with %s:"% (test_name, pyspark_python))
forlineinlines:
LOGGER.info(" %s"%line.rstrip())
if__name__=="__main__":
SKIPPED_TESTS=Manager().dict()
main()