/
run-tests.py
executable file
·3522 lines (3052 loc) · 120 KB
/
run-tests.py
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
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
#
# run-tests.py - Run a set of tests on Mercurial
#
# Copyright 2006 Matt Mackall <mpm@selenic.com>
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2 or any later version.
# Modifying this script is tricky because it has many modes:
# - serial vs parallel (default) (-jN, N > 1)
# - no coverage (default) vs coverage (-c, -C, -s)
# - temp install vs specific hg script (--with-hg, --local (default))
# - tests are a mix of shell scripts and Python scripts
#
# If you change this script, it is recommended that you ensure you
# haven't broken it by running it in various modes with a representative
# sample of test scripts. For example:
#
# 1) serial, no coverage, temp install:
# ./run-tests.py -j1 --build test-s*
# 2) serial, no coverage, local hg:
# ./run-tests.py -j1 --local test-s*
# 3) serial, coverage, temp install:
# ./run-tests.py -j1 -b -c test-s*
# 4) serial, coverage, local hg:
# ./run-tests.py -j1 -c --local test-s* # unsupported
# 5) parallel, no coverage, temp install:
# ./run-tests.py -j2 -b test-s*
# 6) parallel, no coverage, local hg:
# ./run-tests.py -j2 --local test-s*
# 7) parallel, coverage, temp install:
# ./run-tests.py -j2 -c -b test-s* # currently broken
# 8) parallel, coverage, local install:
# ./run-tests.py -j2 -c --local test-s* # unsupported (and broken)
# 9) parallel, custom tmp dir:
# ./run-tests.py -j2 --tmpdir /tmp/myhgtests
# 10) parallel, pure, tests that call run-tests:
# ./run-tests.py --pure `grep -l run-tests.py *.t`
#
# (You could use any subset of the tests: test-s* happens to match
# enough that it's worth doing parallel runs, few enough that it
# completes fairly quickly, includes both shell and Python scripts, and
# includes some scripts that run daemon processes.)
from __future__ import absolute_import, print_function
import argparse
import collections
import difflib
import distutils.version as version
import errno
import hashlib
import json
import multiprocessing
import os
import random
import re
import shutil
import signal
import socket
import subprocess
import sys
import sysconfig
import tempfile
import threading
import time
import unittest
import uuid
import xml.dom.minidom as minidom
try:
import Queue as queue
except ImportError:
import queue
try:
import shlex
shellquote = shlex.quote
except (ImportError, AttributeError):
import pipes
shellquote = pipes.quote
if os.environ.get("RTUNICODEPEDANTRY", False):
try:
reload(sys)
sys.setdefaultencoding("undefined")
except NameError:
pass
origenviron = os.environ.copy()
osenvironb = getattr(os, "environb", os.environ)
processlock = threading.Lock()
pygmentspresent = False
# ANSI color is unsupported prior to Windows 10
if os.name != "nt":
try: # is pygments installed
import pygments
import pygments.lexers as lexers
import pygments.lexer as lexer
import pygments.formatters as formatters
import pygments.token as token
import pygments.style as style
pygmentspresent = True
difflexer = lexers.DiffLexer()
terminal256formatter = formatters.Terminal256Formatter()
except ImportError:
pass
if pygmentspresent:
class TestRunnerStyle(style.Style):
default_style = ""
skipped = token.string_to_tokentype("Token.Generic.Skipped")
failed = token.string_to_tokentype("Token.Generic.Failed")
skippedname = token.string_to_tokentype("Token.Generic.SName")
failedname = token.string_to_tokentype("Token.Generic.FName")
styles = {
skipped: "#e5e5e5",
skippedname: "#00ffff",
failed: "#7f0000",
failedname: "#ff0000",
}
class TestRunnerLexer(lexer.RegexLexer):
tokens = {
"root": [
(r"^Skipped", token.Generic.Skipped, "skipped"),
(r"^Failed ", token.Generic.Failed, "failed"),
(r"^ERROR: ", token.Generic.Failed, "failed"),
],
"skipped": [
(r"[\w-]+\.(t|py)", token.Generic.SName),
(r":.*", token.Generic.Skipped),
],
"failed": [
(r"[\w-]+\.(t|py)", token.Generic.FName),
(r"(:| ).*", token.Generic.Failed),
],
}
runnerformatter = formatters.Terminal256Formatter(style=TestRunnerStyle)
runnerlexer = TestRunnerLexer()
if sys.version_info > (3, 5, 0):
PYTHON3 = True
xrange = range # we use xrange in one place, and we'd rather not use range
def _bytespath(p):
if p is None:
return p
return p.encode("utf-8")
def _strpath(p):
if p is None:
return p
return p.decode("utf-8")
elif sys.version_info >= (3, 0, 0):
print(
"%s is only supported on Python 3.5+ and 2.7, not %s"
% (sys.argv[0], ".".join(str(v) for v in sys.version_info[:3]))
)
sys.exit(70) # EX_SOFTWARE from `man 3 sysexit`
else:
PYTHON3 = False
# In python 2.x, path operations are generally done using
# bytestrings by default, so we don't have to do any extra
# fiddling there. We define the wrapper functions anyway just to
# help keep code consistent between platforms.
def _bytespath(p):
return p
_strpath = _bytespath
# For Windows support
wifexited = getattr(os, "WIFEXITED", lambda x: False)
# Whether to use IPv6
def checksocketfamily(name, port=20058):
"""return true if we can listen on localhost using family=name
name should be either 'AF_INET', or 'AF_INET6'.
port being used is okay - EADDRINUSE is considered as successful.
"""
family = getattr(socket, name, None)
if family is None:
return False
try:
s = socket.socket(family, socket.SOCK_STREAM)
s.bind(("localhost", port))
s.close()
return True
except socket.error as exc:
if exc.errno == errno.EADDRINUSE:
return True
elif exc.errno in (errno.EADDRNOTAVAIL, errno.EPROTONOSUPPORT):
return False
else:
raise
else:
return False
# useipv6 will be set by parseargs
useipv6 = None
def checkportisavailable(port):
"""return true if a port seems free to bind on localhost"""
if useipv6:
family = socket.AF_INET6
else:
family = socket.AF_INET
try:
s = socket.socket(family, socket.SOCK_STREAM)
s.bind(("localhost", port))
s.close()
return True
except socket.error as exc:
if exc.errno not in (
errno.EADDRINUSE,
errno.EADDRNOTAVAIL,
errno.EPROTONOSUPPORT,
):
raise
return False
closefds = os.name == "posix"
def Popen4(cmd, wd, timeout, env=None):
processlock.acquire()
p = subprocess.Popen(
cmd,
shell=True,
bufsize=-1,
cwd=wd,
env=env,
close_fds=closefds,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
)
processlock.release()
p.fromchild = p.stdout
p.tochild = p.stdin
p.childerr = p.stderr
p.timeout = False
if timeout:
def t():
start = time.time()
while time.time() - start < timeout and p.returncode is None:
time.sleep(.1)
p.timeout = True
if p.returncode is None:
terminate(p)
threading.Thread(target=t).start()
return p
PYTHON = _bytespath(sys.executable.replace("\\", "/"))
IMPL_PATH = b"PYTHONPATH"
if "java" in sys.platform:
IMPL_PATH = b"JYTHONPATH"
defaults = {
"jobs": ("HGTEST_JOBS", multiprocessing.cpu_count()),
"timeout": ("HGTEST_TIMEOUT", 360),
"slowtimeout": ("HGTEST_SLOWTIMEOUT", 1000),
"port": ("HGTEST_PORT", 20059),
"shell": ("HGTEST_SHELL", "bash"),
}
def canonpath(path):
return os.path.realpath(os.path.expanduser(path))
def parselistfiles(files, listtype, warn=True):
entries = dict()
for filename in files:
try:
path = os.path.expanduser(os.path.expandvars(filename))
f = open(path, "rb")
except IOError as err:
if err.errno != errno.ENOENT:
raise
if warn:
print("warning: no such %s file: %s" % (listtype, filename))
continue
for line in f.readlines():
line = line.split(b"#", 1)[0].strip()
if line:
entries[line] = filename
f.close()
return entries
def parsettestcases(path):
"""read a .t test file, return a set of test case names
If path does not exist, return an empty set.
"""
cases = set()
try:
with open(path, "rb") as f:
for l in f:
if l.startswith(b"#testcases "):
cases.update(l[11:].split())
except IOError as ex:
if ex.errno != errno.ENOENT:
raise
return cases
def getparser():
"""Obtain the OptionParser used by the CLI."""
parser = argparse.ArgumentParser(usage="%(prog)s [options] [tests]")
selection = parser.add_argument_group("Test Selection")
selection.add_argument(
"--allow-slow-tests", action="store_true", help="allow extremely slow tests"
)
selection.add_argument(
"--blacklist",
action="append",
help="skip tests listed in the specified blacklist file",
)
selection.add_argument(
"--changed",
help="run tests that are changed in parent rev or working directory",
)
selection.add_argument("-k", "--keywords", help="run tests matching keywords")
selection.add_argument(
"-r", "--retest", action="store_true", help="retest failed tests"
)
selection.add_argument(
"--test-list", action="append", help="read tests to run from the specified file"
)
selection.add_argument(
"--whitelist",
action="append",
help="always run tests listed in the specified whitelist file",
)
selection.add_argument("tests", metavar="TESTS", nargs="*", help="Tests to run")
harness = parser.add_argument_group("Test Harness Behavior")
harness.add_argument(
"--bisect-repo",
metavar="bisect_repo",
help=("Path of a repo to bisect. Use together with --known-good-rev"),
)
harness.add_argument(
"-d",
"--debug",
action="store_true",
help="debug mode: write output of test scripts to console"
" rather than capturing and diffing it (disables timeout)",
)
harness.add_argument(
"-f", "--first", action="store_true", help="exit on the first test failure"
)
harness.add_argument(
"-i",
"--interactive",
action="store_true",
help="prompt to accept changed output",
)
harness.add_argument(
"-j",
"--jobs",
type=int,
help="number of jobs to run in parallel"
" (default: $%s or %d)" % defaults["jobs"],
)
harness.add_argument(
"--keep-tmpdir",
action="store_true",
help="keep temporary directory after running tests",
)
harness.add_argument(
"--known-good-rev",
metavar="known_good_rev",
help=(
"Automatically bisect any failures using this "
"revision as a known-good revision."
),
)
harness.add_argument(
"--list-tests", action="store_true", help="list tests instead of running them"
)
harness.add_argument("--loop", action="store_true", help="loop tests repeatedly")
harness.add_argument(
"--random", action="store_true", help="run tests in random order"
)
harness.add_argument(
"-p",
"--port",
type=int,
help="port on which servers should listen"
" (default: $%s or %d)" % defaults["port"],
)
harness.add_argument(
"--profile-runner", action="store_true", help="run statprof on run-tests"
)
harness.add_argument(
"-R", "--restart", action="store_true", help="restart at last error"
)
harness.add_argument(
"--runs-per-test",
type=int,
dest="runs_per_test",
help="run each test N times (default=1)",
default=1,
)
harness.add_argument(
"--shell", help="shell to use (default: $%s or %s)" % defaults["shell"]
)
harness.add_argument(
"--showchannels", action="store_true", help="show scheduling channels"
)
harness.add_argument(
"--slowtimeout",
type=int,
help="kill errant slow tests after SLOWTIMEOUT seconds"
" (default: $%s or %d)" % defaults["slowtimeout"],
)
harness.add_argument(
"-t",
"--timeout",
type=int,
help="kill errant tests after TIMEOUT seconds"
" (default: $%s or %d)" % defaults["timeout"],
)
harness.add_argument(
"--tmpdir",
help="run tests in the given temporary directory (implies --keep-tmpdir)",
)
harness.add_argument(
"-v", "--verbose", action="store_true", help="output verbose messages"
)
hgconf = parser.add_argument_group("Mercurial Configuration")
hgconf.add_argument(
"--chg", action="store_true", help="install and use chg wrapper in place of hg"
)
hgconf.add_argument(
"--watchman", action="store_true", help="shortcut for --with-watchman=watchman"
)
hgconf.add_argument("--compiler", help="compiler to build with")
hgconf.add_argument(
"--extra-config-opt",
action="append",
default=[],
help="set the given config opt in the test hgrc",
)
hgconf.add_argument(
"--extra-rcpath",
action="append",
default=[],
help="load the given config file or directory in the test hgrc",
)
hgconf.add_argument(
"-l",
"--local",
action="store_true",
help="shortcut for --with-hg=<testdir>/../hg, "
"and --with-chg=<testdir>/../contrib/chg/chg if --chg is set",
)
hgconf.add_argument(
"-b",
"--rebuild",
dest="local",
action="store_false",
help="build and install to a temporary location before running tests, "
"the reverse of --local",
)
hgconf.set_defaults(local=True)
hgconf.add_argument(
"--ipv6",
action="store_true",
help="prefer IPv6 to IPv4 for network related tests",
)
hgconf.add_argument(
"--pure",
action="store_true",
help="use pure Python code instead of C extensions",
)
hgconf.add_argument(
"-3",
"--py3k-warnings",
action="store_true",
help="enable Py3k warnings on Python 2.7+",
)
hgconf.add_argument(
"--with-chg", metavar="CHG", help="use specified chg wrapper in place of hg"
)
hgconf.add_argument(
"--with-hg",
metavar="HG",
help="test using specified hg script rather than a temporary installation",
)
hgconf.add_argument(
"--with-watchman", metavar="WATCHMAN", help="test using specified watchman"
)
# This option should be deleted once test-check-py3-compat.t and other
# Python 3 tests run with Python 3.
hgconf.add_argument(
"--with-python3",
metavar="PYTHON3",
help="Python 3 interpreter (if running under Python 2) (TEMPORARY)",
)
reporting = parser.add_argument_group("Results Reporting")
reporting.add_argument(
"-C",
"--annotate",
action="store_true",
help="output files annotated with coverage",
)
reporting.add_argument(
"--color",
choices=["always", "auto", "never"],
default=os.environ.get("HGRUNTESTSCOLOR", "auto"),
help="colorisation: always|auto|never (default: auto)",
)
reporting.add_argument(
"-c", "--cover", action="store_true", help="print a test coverage report"
)
reporting.add_argument(
"--exceptions",
action="store_true",
help="log all exceptions and generate an exception report",
)
reporting.add_argument(
"-H",
"--htmlcov",
action="store_true",
help="create an HTML report of the coverage of the files",
)
reporting.add_argument(
"--json",
action="store_true",
help="store test result data in 'report.json' file",
)
reporting.add_argument(
"--outputdir", help="directory to write error logs to (default=test directory)"
)
reporting.add_argument(
"-n", "--nodiff", action="store_true", help="skip showing test changes"
)
reporting.add_argument(
"-S", "--noskips", action="store_true", help="don't report skip tests verbosely"
)
reporting.add_argument(
"--time", action="store_true", help="time how long each test takes"
)
reporting.add_argument("--view", help="external diff viewer")
reporting.add_argument("--xunit", help="record xunit results at specified path")
for option, (envvar, default) in defaults.items():
defaults[option] = type(default)(os.environ.get(envvar, default))
parser.set_defaults(**defaults)
return parser
def parseargs(args, parser):
"""Parse arguments with our OptionParser and validate results."""
options = parser.parse_args(args)
# jython is always pure
if "java" in sys.platform or "__pypy__" in sys.modules:
options.pure = True
if options.with_hg:
options.with_hg = canonpath(_bytespath(options.with_hg))
if not (
os.path.isfile(options.with_hg) and os.access(options.with_hg, os.X_OK)
):
parser.error("--with-hg must specify an executable hg script")
if options.local:
testdir = os.path.dirname(_bytespath(canonpath(sys.argv[0])))
reporootdir = os.path.dirname(testdir)
pathandattrs = [(b"hg", "with_hg")]
if options.chg:
pathandattrs.append((b"contrib/chg/chg", "with_chg"))
for relpath, attr in pathandattrs:
if getattr(options, attr, None):
continue
binpath = os.path.join(reporootdir, relpath)
if os.name != "nt" and not os.access(binpath, os.X_OK):
parser.error(
"--local specified, but %r not found or not executable" % binpath
)
setattr(options, attr, binpath)
if (options.chg or options.with_chg) and os.name == "nt":
parser.error("chg does not work on %s" % os.name)
if options.with_chg:
options.chg = False # no installation to temporary location
options.with_chg = canonpath(_bytespath(options.with_chg))
if not (
os.path.isfile(options.with_chg) and os.access(options.with_chg, os.X_OK)
):
parser.error("--with-chg must specify a chg executable")
if options.chg and options.with_hg:
# chg shares installation location with hg
parser.error(
"--chg does not work when --with-hg is specified "
"(use --with-chg instead)"
)
if options.watchman and options.with_watchman:
parser.error(
"--watchman does not work when --with-watchman is specified "
"(use --with-watchman instead)"
)
if options.color == "always" and not pygmentspresent:
sys.stderr.write(
"warning: --color=always ignored because pygments is not installed\n"
)
if options.bisect_repo and not options.known_good_rev:
parser.error("--bisect-repo cannot be used without --known-good-rev")
global useipv6
if options.ipv6:
useipv6 = checksocketfamily("AF_INET6")
else:
# only use IPv6 if IPv4 is unavailable and IPv6 is available
useipv6 = (not checksocketfamily("AF_INET")) and checksocketfamily("AF_INET6")
options.anycoverage = options.cover or options.annotate or options.htmlcov
if options.anycoverage:
try:
import coverage
covver = version.StrictVersion(coverage.__version__).version
if covver < (3, 3):
parser.error("coverage options require coverage 3.3 or later")
except ImportError:
parser.error("coverage options now require the coverage package")
if options.anycoverage and options.local:
# this needs some path mangling somewhere, I guess
parser.error("sorry, coverage options do not work when --local is specified")
if options.anycoverage and options.with_hg:
parser.error("sorry, coverage options do not work when --with-hg is specified")
global verbose
if options.verbose:
verbose = ""
if options.tmpdir:
options.tmpdir = canonpath(options.tmpdir)
if options.jobs < 1:
parser.error("--jobs must be positive")
if options.interactive and options.debug:
parser.error("-i/--interactive and -d/--debug are incompatible")
if options.debug:
if options.timeout != defaults["timeout"]:
sys.stderr.write("warning: --timeout option ignored with --debug\n")
if options.slowtimeout != defaults["slowtimeout"]:
sys.stderr.write("warning: --slowtimeout option ignored with --debug\n")
options.timeout = 0
options.slowtimeout = 0
if options.py3k_warnings:
if PYTHON3:
parser.error("--py3k-warnings can only be used on Python 2.7")
if options.with_python3:
if PYTHON3:
parser.error("--with-python3 cannot be used when executing with Python 3")
options.with_python3 = canonpath(options.with_python3)
# Verify Python3 executable is acceptable.
proc = subprocess.Popen(
[options.with_python3, b"--version"],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
)
out, _err = proc.communicate()
ret = proc.wait()
if ret != 0:
parser.error("could not determine version of python 3")
if not out.startswith("Python "):
parser.error("unexpected output from python3 --version: %s" % out)
vers = version.LooseVersion(out[len("Python ") :])
if vers < version.LooseVersion("3.5.0"):
parser.error(
"--with-python3 version must be 3.5.0 or greater; got %s" % out
)
if options.blacklist:
options.blacklist = parselistfiles(options.blacklist, "blacklist")
if options.whitelist:
options.whitelisted = parselistfiles(options.whitelist, "whitelist")
else:
options.whitelisted = {}
if options.showchannels:
options.nodiff = True
return options
def rename(src, dst):
"""Like os.rename(), trade atomicity and opened files friendliness
for existing destination support.
"""
shutil.copy(src, dst)
os.remove(src)
_unified_diff = difflib.unified_diff
if PYTHON3:
import functools
_unified_diff = functools.partial(difflib.diff_bytes, difflib.unified_diff)
def getdiff(expected, output, ref, err):
servefail = False
lines = []
for line in _unified_diff(
expected, output, os.path.basename(ref), os.path.basename(err)
):
if line.startswith(b"+++") or line.startswith(b"---"):
line = line.replace(b"\\", b"/")
if line.endswith(b" \n"):
line = line[:-2] + b"\n"
lines.append(line)
if not servefail and line.startswith(
b"+ abort: child process failed to start"
):
servefail = True
return servefail, lines
verbose = False
def vlog(*msg):
"""Log only when in verbose mode."""
if verbose is False:
return
return log(*msg)
# Bytes that break XML even in a CDATA block: control characters 0-31
# sans \t, \n and \r
CDATA_EVIL = re.compile(br"[\000-\010\013\014\016-\037]")
# Match feature conditionalized output lines in the form, capturing the feature
# list in group 2, and the preceeding line output in group 1:
#
# output..output (feature !)\n
optline = re.compile(b"(.*) \((.+?) !\)\n$")
def cdatasafe(data):
"""Make a string safe to include in a CDATA block.
Certain control characters are illegal in a CDATA block, and
there's no way to include a ]]> in a CDATA either. This function
replaces illegal bytes with ? and adds a space between the ]] so
that it won't break the CDATA block.
"""
return CDATA_EVIL.sub(b"?", data).replace(b"]]>", b"] ]>")
def log(*msg):
"""Log something to stdout.
Arguments are strings to print.
"""
with iolock:
if verbose:
print(verbose, end=" ")
for m in msg:
print(m, end=" ")
print()
sys.stdout.flush()
def highlightdiff(line, color):
if not color:
return line
assert pygmentspresent
return pygments.highlight(
line.decode("latin1"), difflexer, terminal256formatter
).encode("latin1")
def highlightmsg(msg, color):
if not color:
return msg
assert pygmentspresent
return pygments.highlight(msg, runnerlexer, runnerformatter)
def terminate(proc):
"""Terminate subprocess"""
vlog("# Terminating process %d" % proc.pid)
try:
proc.terminate()
except OSError:
pass
def killdaemons(pidfile):
import killdaemons as killmod
return killmod.killdaemons(pidfile, tryhard=False, remove=True, logfn=vlog)
class Test(unittest.TestCase):
"""Encapsulates a single, runnable test.
While this class conforms to the unittest.TestCase API, it differs in that
instances need to be instantiated manually. (Typically, unittest.TestCase
classes are instantiated automatically by scanning modules.)
"""
# Status code reserved for skipped tests (used by hghave).
SKIPPED_STATUS = 80
def __init__(
self,
path,
outputdir,
tmpdir,
keeptmpdir=False,
debug=False,
first=False,
timeout=None,
startport=None,
extraconfigopts=None,
extrarcpaths=None,
py3kwarnings=False,
shell=None,
hgcommand=None,
slowtimeout=None,
usechg=False,
useipv6=False,
watchman=None,
):
"""Create a test from parameters.
path is the full path to the file defining the test.
tmpdir is the main temporary directory to use for this test.
keeptmpdir determines whether to keep the test's temporary directory
after execution. It defaults to removal (False).
debug mode will make the test execute verbosely, with unfiltered
output.
timeout controls the maximum run time of the test. It is ignored when
debug is True. See slowtimeout for tests with #require slow.
slowtimeout overrides timeout if the test has #require slow.
startport controls the starting port number to use for this test. Each
test will reserve 3 port numbers for execution. It is the caller's
responsibility to allocate a non-overlapping port range to Test
instances.
extraconfigopts is an iterable of extra hgrc config options. Values
must have the form "key=value" (something understood by hgrc). Values
of the form "foo.key=value" will result in "[foo] key=value".
extrarcpaths is an iterable for extra hgrc paths (files or
directories).
py3kwarnings enables Py3k warnings.
shell is the shell to execute tests in.
"""
if timeout is None:
timeout = defaults["timeout"]
if startport is None:
startport = defaults["port"]
if slowtimeout is None:
slowtimeout = defaults["slowtimeout"]
self.path = path
self.bname = os.path.basename(path)
self.name = _strpath(self.bname)
self._testdir = os.path.dirname(path)
self._outputdir = outputdir
self._tmpname = os.path.basename(path)
self.errpath = os.path.join(self._outputdir, b"%s.err" % self.bname)
self._threadtmp = tmpdir
self._keeptmpdir = keeptmpdir
self._debug = debug
self._first = first
self._timeout = timeout
self._slowtimeout = slowtimeout
self._startport = startport
self._extraconfigopts = extraconfigopts or []
self._extrarcpaths = extrarcpaths or []
self._py3kwarnings = py3kwarnings
self._shell = _bytespath(shell)
self._hgcommand = hgcommand or b"hg"
self._usechg = usechg
self._useipv6 = useipv6
self._watchman = watchman
self._aborted = False
self._daemonpids = []
self._finished = None
self._ret = None
self._out = None
self._skipped = None
self._testtmp = None
self._chgsockdir = None
self._refout = self.readrefout()
def readrefout(self):
"""read reference output"""
# If we're not in --debug mode and reference output file exists,
# check test output against it.
if self._debug:
return None # to match "out is None"
elif os.path.exists(self.refpath):
with open(self.refpath, "rb") as f:
return f.read().splitlines(True)
else:
return []
# needed to get base class __repr__ running
@property
def _testMethodName(self):
return self.name
def __str__(self):
return self.name
def shortDescription(self):
return self.name
def setUp(self):
"""Tasks to perform before run()."""
self._finished = False
self._ret = None
self._out = None
self._skipped = None
try:
os.mkdir(self._threadtmp)
except OSError as e:
if e.errno != errno.EEXIST:
raise
name = self._tmpname
self._testtmp = os.path.join(self._threadtmp, name)
os.mkdir(self._testtmp)
# Remove any previous output files.
if os.path.exists(self.errpath):
try:
os.remove(self.errpath)
except OSError as e:
# We might have raced another test to clean up a .err
# file, so ignore ENOENT when removing a previous .err
# file.
if e.errno != errno.ENOENT:
raise
if self._usechg:
self._chgsockdir = os.path.join(self._threadtmp, b"%s.chgsock" % name)
os.mkdir(self._chgsockdir)
if self._watchman:
shortname = hashlib.sha1(b"%s" % name).hexdigest()[:6]
self._watchmandir = os.path.join(
self._threadtmp, b"%s.watchman" % shortname