Debian Codegraph @

tests/run-tests.py

raw
1 #!/usr/bin/env python3
2 #
3 # run-tests.py - Run a set of tests on Mercurial
4 #
5 # Copyright 2006 Olivia Mackall <[email protected]>
6 #
7 # This software may be used and distributed according to the terms of the
8 # GNU General Public License version 2 or any later version.
9
10 # Modifying this script is tricky because it has many modes:
11 # - serial (default) vs parallel (-jN, N > 1)
12 # - no coverage (default) vs coverage (-c, -C, -s)
13 # - temp install (default) vs specific hg script (--with-hg, --local)
14 # - tests are a mix of shell scripts and Python scripts
15 #
16 # If you change this script, it is recommended that you ensure you
17 # haven't broken it by running it in various modes with a representative
18 # sample of test scripts. For example:
19 #
20 # 1) serial, no coverage, temp install:
21 # ./run-tests.py test-s*
22 # 2) serial, no coverage, local hg:
23 # ./run-tests.py --local test-s*
24 # 3) serial, coverage, temp install:
25 # ./run-tests.py -c test-s*
26 # 4) serial, coverage, local hg:
27 # ./run-tests.py -c --local test-s* # unsupported
28 # 5) parallel, no coverage, temp install:
29 # ./run-tests.py -j2 test-s*
30 # 6) parallel, no coverage, local hg:
31 # ./run-tests.py -j2 --local test-s*
32 # 7) parallel, coverage, temp install:
33 # ./run-tests.py -j2 -c test-s* # currently broken
34 # 8) parallel, coverage, local install:
35 # ./run-tests.py -j2 -c --local test-s* # unsupported (and broken)
36 # 9) parallel, custom tmp dir:
37 # ./run-tests.py -j2 --tmpdir /tmp/myhgtests
38 # 10) parallel, pure, tests that call run-tests:
39 # ./run-tests.py --pure `grep -l run-tests.py *.t`
40 #
41 # (You could use any subset of the tests: test-s* happens to match
42 # enough that it's worth doing parallel runs, few enough that it
43 # completes fairly quickly, includes both shell and Python scripts, and
44 # includes some scripts that run daemon processes.)
45
46
47 import argparse
48 import collections
49 import contextlib
50 import difflib
51
52 import errno
53 import functools
54 import json
55 import multiprocessing
56 import os
57 import platform
58 import queue
59 import random
60 import re
61 import shlex
62 import shutil
63 import signal
64 import socket
65 import subprocess
66 import sys
67 import sysconfig
68 import tempfile
69 import threading
70 import time
71 import unittest
72 import uuid
73 import xml.dom.minidom as minidom
74
75 # Don't compare sys.version_info directly, to prevent pyupgrade from dropping
76 # the conditional.
77 sys_version_info = sys.version_info
78
79 if sys_version_info < (3, 8, 0):
80 print(
81 '%s is only supported on Python 3.8+, not %s'
82 % (sys.argv[0], '.'.join(str(v) for v in sys.version_info[:3]))
83 )
84 sys.exit(70) # EX_SOFTWARE from `man 3 sysexit`
85
86 MACOS = sys.platform == 'darwin'
87 WINDOWS = os.name == r'nt'
88 shellquote = shlex.quote
89 BINDIRNAME = b"Scripts" if WINDOWS else b"bin"
90
91 # The number of HGPORTx ports allocated to each test.
92 HGPORT_COUNT = 4
93
94 RUNTEST_DIR = os.path.abspath(os.path.dirname(__file__.encode('utf-8')))
95 RUNTEST_DIR_FORWARD_SLASH = RUNTEST_DIR.replace(os.sep.encode('utf-8'), b'/')
96
97 INITIAL_CWD = os.getcwdb()
98
99
100 processlock = threading.Lock()
101
102 pygmentspresent = False
103 try: # is pygments installed
104 import pygments
105 import pygments.lexers as lexers
106 import pygments.lexer as lexer
107 import pygments.formatters as formatters
108 import pygments.token as token
109 import pygments.style as style
110 from pygments.console import ansiformat
111
112 if WINDOWS:
113 hgpath = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
114 sys.path.append(hgpath)
115 try:
116 from mercurial import win32 # pytype: disable=import-error
117
118 # Don't check the result code because it fails on heptapod, but
119 # something is able to convert to color anyway.
120 win32.enablevtmode()
121 finally:
122 sys.path = sys.path[:-1]
123
124 pygmentspresent = True
125 difflexer = lexers.DiffLexer()
126 terminal256formatter = formatters.Terminal256Formatter()
127
128 def colorize(text: str, style: str, color: bool = True) -> str:
129 if not color:
130 return text
131 return ansiformat(style, text)
132
133 except ImportError:
134
135 def colorize(text: str, style: str, color: bool = True) -> str:
136 return text
137
138
139 progress_type = {}
140
141 if pygmentspresent:
142 _T_ERROR = token.string_to_tokentype("Token.Generic.Error")
143 _T_FAILED = token.string_to_tokentype("Token.Generic.Failed")
144 _T_FNAME = token.string_to_tokentype("Token.Generic.FName")
145 _T_IGNORED = token.string_to_tokentype("Token.Generic.Ignored")
146 _T_SKIPPED = token.string_to_tokentype("Token.Generic.Skipped")
147 _T_SNAME = token.string_to_tokentype("Token.Generic.SName")
148 _T_SKIPPED_DOT = token.string_to_tokentype("Token.Generic.SkippedDot")
149 _T_SUCCESS = token.string_to_tokentype("Token.Generic.Success")
150 _T_TIMEDOUT = token.string_to_tokentype("Token.Generic.TimedOut")
151
152 class TestRunnerStyle(style.Style):
153 default_style = ""
154 styles = {
155 _T_ERROR: '#cd00cd',
156 _T_FAILED: '#7f0000',
157 _T_FNAME: '#ff0000',
158 _T_IGNORED: '#cdcd00',
159 _T_SKIPPED: '#e5e5e5',
160 _T_SNAME: '#00ffff',
161 _T_SKIPPED_DOT: '#00ffff',
162 _T_SUCCESS: '#00cd00',
163 _T_TIMEDOUT: '#ff00ff',
164 }
165
166 class TestRunnerLexer(lexer.RegexLexer):
167 testpattern = r'[\w/-]+\.(t|py)(#[a-zA-Z0-9_\-\.]+)?'
168 tokens = {
169 'root': [
170 (r'^Skipped', _T_SKIPPED, 'skipped'),
171 (r'^Failed ', _T_FAILED, 'failed'),
172 (r'^ERROR: ', _T_FAILED, 'failed'),
173 ],
174 'skipped': [
175 (testpattern, _T_SNAME),
176 (r':.*', _T_SKIPPED),
177 ],
178 'failed': [
179 (testpattern, _T_FNAME),
180 (r'(:| ).*', _T_FAILED),
181 ],
182 }
183
184 progress_type['.'] = _T_SUCCESS
185 progress_type['s'] = _T_SKIPPED_DOT
186 progress_type['i'] = _T_IGNORED
187 progress_type['!'] = _T_FAILED
188 progress_type['E'] = _T_ERROR
189 progress_type['t'] = _T_TIMEDOUT
190
191 class progressLexer(lexer.RegexLexer):
192 testpattern = r'[\w-]+\.(t|py)(#[a-zA-Z0-9_\-\.]+)?'
193 tokens = {
194 'root': [
195 (r'^Skipped', _T_SKIPPED, 'skipped'),
196 (r'^Failed ', _T_FAILED, 'failed'),
197 (r'^ERROR: ', _T_FAILED, 'failed'),
198 ],
199 'skipped': [
200 (testpattern, _T_SNAME),
201 (r':.*', _T_SKIPPED),
202 ],
203 'failed': [
204 (testpattern, _T_FNAME),
205 (r'(:| ).*', _T_FAILED),
206 ],
207 }
208
209 runnerformatter = formatters.Terminal256Formatter(style=TestRunnerStyle)
210 runnerlexer = TestRunnerLexer()
211
212 origenviron = os.environ.copy()
213
214
215 def _sys2bytes(p):
216 if p is None:
217 return p
218 return p.encode('utf-8')
219
220
221 def _bytes2sys(p):
222 if p is None:
223 return p
224 return p.decode('utf-8')
225
226
227 original_env = os.environ.copy()
228 osenvironb = getattr(os, 'environb', None)
229 if osenvironb is None:
230 # Windows lacks os.environb, for instance. A proxy over the real thing
231 # instead of a copy allows the environment to be updated via bytes on
232 # all platforms.
233 class environbytes:
234 def __init__(self, strenv):
235 self.__len__ = strenv.__len__
236 self.clear = strenv.clear
237 self._strenv = strenv
238
239 def __getitem__(self, k):
240 v = self._strenv.__getitem__(_bytes2sys(k))
241 return _sys2bytes(v)
242
243 def __setitem__(self, k, v):
244 self._strenv.__setitem__(_bytes2sys(k), _bytes2sys(v))
245
246 def __delitem__(self, k):
247 self._strenv.__delitem__(_bytes2sys(k))
248
249 def __contains__(self, k):
250 return self._strenv.__contains__(_bytes2sys(k))
251
252 def __iter__(self):
253 return iter([_sys2bytes(k) for k in iter(self._strenv)])
254
255 def get(self, k, default=None):
256 v = self._strenv.get(_bytes2sys(k), _bytes2sys(default))
257 return _sys2bytes(v)
258
259 def pop(self, k, default=None):
260 v = self._strenv.pop(_bytes2sys(k), _bytes2sys(default))
261 return _sys2bytes(v)
262
263 osenvironb = environbytes(os.environ)
264
265 getcwdb = getattr(os, 'getcwdb')
266 if not getcwdb or WINDOWS:
267 getcwdb = lambda: _sys2bytes(os.getcwd())
268
269
270 if WINDOWS:
271 _getcwdb = getcwdb
272
273 def getcwdb():
274 cwd = _getcwdb()
275 if re.match(b'^[a-z]:', cwd):
276 # os.getcwd() is inconsistent on the capitalization of the drive
277 # letter, so adjust it. see https://bugs.python.org/issue40368
278 cwd = cwd[0:1].upper() + cwd[1:]
279 return cwd
280
281
282 # For Windows support
283 wifexited = getattr(os, "WIFEXITED", lambda x: False)
284
285
286 # Whether to use IPv6
287 def checksocketfamily(name, port=20058):
288 """return true if we can listen on localhost using family=name
289
290 name should be either 'AF_INET', or 'AF_INET6'.
291 port being used is okay - EADDRINUSE is considered as successful.
292 """
293 family = getattr(socket, name, None)
294 if family is None:
295 return False
296 try:
297 s = socket.socket(family, socket.SOCK_STREAM)
298 s.bind(('localhost', port))
299 s.close()
300 return True
301 except OSError as exc:
302 if exc.errno == errno.EADDRINUSE:
303 return True
304 elif exc.errno in (
305 errno.EADDRNOTAVAIL,
306 errno.EPROTONOSUPPORT,
307 errno.EAFNOSUPPORT,
308 ):
309 return False
310 else:
311 raise
312 else:
313 return False
314
315
316 # useipv6 will be set by parseargs
317 useipv6 = None
318
319
320 def checkportisavailable(port):
321 """return true if a port seems free to bind on localhost"""
322 if useipv6:
323 family = socket.AF_INET6
324 else:
325 family = socket.AF_INET
326 try:
327 with contextlib.closing(socket.socket(family, socket.SOCK_STREAM)) as s:
328 s.bind(('localhost', port))
329 return True
330 except PermissionError:
331 return False
332 except OSError as exc:
333 if WINDOWS and exc.errno == errno.WSAEACCES:
334 return False
335 if exc.errno not in (
336 errno.EADDRINUSE,
337 errno.EADDRNOTAVAIL,
338 errno.EPROTONOSUPPORT,
339 ):
340 raise
341 return False
342
343
344 closefds = os.name == 'posix'
345
346
347 def Popen4(cmd, wd, timeout, env=None):
348 processlock.acquire()
349 p = subprocess.Popen(
350 _bytes2sys(cmd),
351 shell=True,
352 bufsize=-1,
353 cwd=_bytes2sys(wd),
354 env=env,
355 close_fds=closefds,
356 stdin=subprocess.PIPE,
357 stdout=subprocess.PIPE,
358 stderr=subprocess.STDOUT,
359 )
360 processlock.release()
361
362 p.fromchild = p.stdout
363 p.tochild = p.stdin
364 p.childerr = p.stderr
365
366 p.timeout = False
367 if timeout:
368
369 def t():
370 start = time.time()
371 while time.time() - start < timeout and p.returncode is None:
372 time.sleep(0.1)
373 if p.returncode is None:
374 p.timeout = True
375 vlog('# Timout reached for process %d' % p.pid)
376 terminate(p)
377
378 threading.Thread(target=t).start()
379
380 return p
381
382
383 default_defaults = {
384 'jobs': ('HGTEST_JOBS', multiprocessing.cpu_count()),
385 'timeout': ('HGTEST_TIMEOUT', 360 if not WINDOWS else 360 * 4),
386 'slowtimeout': ('HGTEST_SLOWTIMEOUT', 1500),
387 'port': ('HGTEST_PORT', 20059),
388 'shell': ('HGTEST_SHELL', 'sh'),
389 }
390
391 defaults = default_defaults.copy()
392
393
394 def canonpath(path):
395 return os.path.realpath(os.path.expanduser(path))
396
397
398 def parselistfiles(files, listtype, warn=True):
399 entries = dict()
400 for filename in files:
401 try:
402 path = os.path.expanduser(os.path.expandvars(filename))
403 f = open(path, "rb")
404 except FileNotFoundError:
405 if warn:
406 print("warning: no such %s file: %s" % (listtype, filename))
407 continue
408
409 for line in f.readlines():
410 line = line.split(b'#', 1)[0].strip()
411 if line:
412 # Ensure path entries are compatible with os.path.relpath()
413 entries[os.path.normpath(line)] = filename
414
415 f.close()
416 return entries
417
418
419 def parsettestcases(path):
420 """read a .t test file, return a set of test case names
421
422 If path does not exist, return an empty set.
423 """
424 cases = []
425 try:
426 with open(path, 'rb') as f:
427 for l in f:
428 if l.startswith(b'#testcases '):
429 cases.append(sorted(l[11:].split()))
430 except FileNotFoundError:
431 pass
432 return cases
433
434
435 def getparser():
436 """Obtain the OptionParser used by the CLI."""
437 parser = argparse.ArgumentParser(usage='%(prog)s [options] [tests]')
438
439 def validate_wheel_path(wheel):
440 """Validate the wheel path and convert to abspath early."""
441 if wheel:
442 wheel = os.path.realpath(wheel)
443 if not os.path.exists(wheel):
444 raise argparse.ArgumentTypeError(
445 "wheel does not exist: %r" % wheel
446 )
447 return wheel
448
449 selection = parser.add_argument_group('Test Selection')
450 selection.add_argument(
451 '--allow-slow-tests',
452 action='store_true',
453 help='allow extremely slow tests',
454 )
455 selection.add_argument(
456 "--blacklist",
457 action="append",
458 help="skip tests listed in the specified blacklist file",
459 )
460 selection.add_argument(
461 "--shard-total",
462 type=int,
463 default=None,
464 help="total number of shard to use (enable sharding)",
465 )
466 selection.add_argument(
467 "--shard-index",
468 type=int,
469 default=None,
470 help="index of this shard [1-N]",
471 )
472 selection.add_argument(
473 "--changed",
474 help="run tests that are changed in parent rev or working directory",
475 )
476 selection.add_argument(
477 "-k", "--keywords", help="run tests matching keywords"
478 )
479 selection.add_argument(
480 "-r", "--retest", action="store_true", help="retest failed tests"
481 )
482 selection.add_argument(
483 "--test-list",
484 action="append",
485 help="read tests to run from the specified file",
486 )
487 selection.add_argument(
488 "--whitelist",
489 action="append",
490 help="always run tests listed in the specified whitelist file",
491 )
492 selection.add_argument(
493 'tests', metavar='TESTS', nargs='*', help='Tests to run'
494 )
495
496 harness = parser.add_argument_group('Test Harness Behavior')
497 harness.add_argument(
498 "-d",
499 "--debug",
500 action="store_true",
501 help="debug mode: write output of test scripts to console"
502 " rather than capturing and diffing it (disables timeout)",
503 )
504 harness.add_argument(
505 "-f",
506 "--first",
507 action="store_true",
508 help="exit on the first test failure",
509 )
510 harness.add_argument(
511 "-i",
512 "--interactive",
513 action="store_true",
514 help="prompt to accept changed output",
515 )
516 harness.add_argument(
517 "-j",
518 "--jobs",
519 type=int,
520 help="number of jobs to run in parallel"
521 " (default: $%s or %d)" % defaults['jobs'],
522 )
523 harness.add_argument(
524 "--keep-tmpdir",
525 action="store_true",
526 help="keep temporary directory after running tests",
527 )
528 harness.add_argument(
529 "--list-tests",
530 action="store_true",
531 help="list tests instead of running them",
532 )
533 harness.add_argument(
534 "--loop", action="store_true", help="loop tests repeatedly"
535 )
536 harness.add_argument(
537 '--random', action="store_true", help='run tests in random order'
538 )
539 harness.add_argument(
540 '--order-by-runtime',
541 action="store_true",
542 help='run slowest tests first, according to .testtimes',
543 )
544 harness.add_argument(
545 "-p",
546 "--port",
547 type=int,
548 help="port on which servers should listen"
549 " (default: $%s or %d)" % defaults['port'],
550 )
551 harness.add_argument(
552 '--profile-runner',
553 action='store_true',
554 help='run statprof on run-tests',
555 )
556 harness.add_argument(
557 "-R", "--restart", action="store_true", help="restart at last error"
558 )
559 harness.add_argument(
560 "--runs-per-test",
561 type=int,
562 dest="runs_per_test",
563 help="run each test N times (default=1)",
564 default=1,
565 )
566 harness.add_argument(
567 "--shell", help="shell to use (default: $%s or %s)" % defaults['shell']
568 )
569 harness.add_argument(
570 '--showchannels', action='store_true', help='show scheduling channels'
571 )
572 harness.add_argument(
573 "--slowtimeout",
574 type=int,
575 help="kill errant slow tests after SLOWTIMEOUT seconds"
576 " (default: $%s or %d)" % defaults['slowtimeout'],
577 )
578 harness.add_argument(
579 "-t",
580 "--timeout",
581 type=int,
582 help="kill errant tests after TIMEOUT seconds"
583 " (default: $%s or %d)" % defaults['timeout'],
584 )
585 harness.add_argument(
586 "--tmpdir",
587 help="run tests in the given temporary directory"
588 " (implies --keep-tmpdir)",
589 )
590 harness.add_argument(
591 "-v", "--verbose", action="store_true", help="output verbose messages"
592 )
593
594 hgconf = parser.add_argument_group('Mercurial Configuration')
595 hgconf.add_argument(
596 "--chg",
597 action="store_true",
598 help="install and use chg wrapper in place of hg",
599 )
600 hgconf.add_argument(
601 "--chg-debug",
602 action="store_true",
603 help="show chg debug logs",
604 )
605 hgconf.add_argument(
606 "--rhg",
607 action="store_true",
608 help="install and use rhg Rust implementation in place of hg",
609 )
610 hgconf.add_argument(
611 "--pyoxidized",
612 action="store_true",
613 help="build the hg binary using pyoxidizer",
614 )
615 hgconf.add_argument(
616 '--extra-config-opt',
617 action="append",
618 default=[],
619 help='set the given config opt in the test hgrc',
620 )
621 hgconf.add_argument(
622 "-l",
623 "--local",
624 action="store_true",
625 help="shortcut for --with-hg=<testdir>/../hg, "
626 "--with-rhg=<testdir>/../rust/target/release/rhg if --rhg is set, "
627 "and --with-chg=<testdir>/../contrib/chg/chg if --chg is set",
628 )
629 hgconf.add_argument(
630 "--py-installer",
631 choices=["auto", "uv", "pip"],
632 default="auto",
633 help="Python installer: auto|uv|pip (default: auto)",
634 )
635 hgconf.add_argument(
636 "--ipv6",
637 action="store_true",
638 help="prefer IPv6 to IPv4 for network related tests",
639 )
640 hgconf.add_argument(
641 "--hg-wheel",
642 default=None,
643 type=validate_wheel_path,
644 metavar="WHEEL_PATH",
645 dest="wheel",
646 help="install mercurial from the given wheel",
647 )
648 hgconf.add_argument(
649 "--pure",
650 action="store_true",
651 help="use pure Python code instead of C extensions",
652 )
653 hgconf.add_argument(
654 "--rust",
655 action="store_true",
656 help="use Rust code alongside C extensions",
657 )
658 hgconf.add_argument(
659 "--no-rust",
660 action="store_true",
661 help="do not use Rust code even if compiled",
662 )
663 hgconf.add_argument(
664 "--with-chg",
665 metavar="CHG",
666 help="use specified chg wrapper in place of hg",
667 )
668 hgconf.add_argument(
669 "--with-rhg",
670 metavar="RHG",
671 help="use specified rhg Rust implementation in place of hg",
672 )
673 hgconf.add_argument(
674 "--with-hg",
675 metavar="HG",
676 help="test using specified hg script rather than a "
677 "temporary installation",
678 )
679 hgconf.add_argument(
680 "--offline",
681 action="store_true",
682 help="Disable network access (requires UV)",
683 )
684
685 reporting = parser.add_argument_group('Results Reporting')
686 reporting.add_argument(
687 "-C",
688 "--annotate",
689 action="store_true",
690 help="output files annotated with coverage",
691 )
692 reporting.add_argument(
693 "--color",
694 choices=["always", "auto", "never"],
695 default=os.environ.get('HGRUNTESTSCOLOR', 'auto'),
696 help="colorisation: always|auto|never (default: auto)",
697 )
698 reporting.add_argument(
699 "-c",
700 "--cover",
701 action="store_true",
702 help="print a test coverage report",
703 )
704 reporting.add_argument(
705 '--exceptions',
706 action='store_true',
707 help='log all exceptions and generate an exception report',
708 )
709 reporting.add_argument(
710 "-H",
711 "--htmlcov",
712 action="store_true",
713 help="create an HTML report of the coverage of the files",
714 )
715 reporting.add_argument(
716 "--json",
717 action="store_true",
718 help="store test result data in 'report.json' file",
719 )
720 reporting.add_argument(
721 "--outputdir",
722 help="directory to write error logs to (default=test directory)",
723 )
724 reporting.add_argument(
725 "-n", "--nodiff", action="store_true", help="skip showing test changes"
726 )
727 reporting.add_argument(
728 "--forbid-skip",
729 action="store_true",
730 help="forbid skipping any test",
731 )
732 reporting.add_argument(
733 "-S",
734 "--noskips",
735 action="store_true",
736 help="don't report skip tests verbosely",
737 )
738 reporting.add_argument(
739 "--time", action="store_true", help="time how long each test takes"
740 )
741 reporting.add_argument(
742 "--tail-report",
743 action="store_true",
744 help="display information about the final test of each thread",
745 )
746 reporting.add_argument("--view", help="external diff viewer")
747 reporting.add_argument(
748 "--xunit", help="record xunit results at specified path"
749 )
750
751 for option, (envvar, default) in defaults.items():
752 defaults[option] = type(default)(os.environ.get(envvar, default))
753 parser.set_defaults(**defaults)
754
755 return parser
756
757
758 def parseargs(args, parser):
759 """Parse arguments with our OptionParser and validate results."""
760 options = parser.parse_args(args)
761
762 # jython is always pure
763 if 'java' in sys.platform or '__pypy__' in sys.modules:
764 options.pure = True
765
766 if platform.python_implementation() != 'CPython' and options.rust:
767 parser.error('Rust extensions are only available with CPython')
768
769 if options.pure and options.rust:
770 parser.error('--rust cannot be used with --pure')
771
772 if options.rust and options.no_rust:
773 parser.error('--rust cannot be used with --no-rust')
774
775 if options.local:
776 if options.with_hg or options.with_rhg or options.with_chg:
777 parser.error(
778 '--local cannot be used with --with-hg or --with-rhg or --with-chg'
779 )
780 if options.pyoxidized:
781 parser.error('--pyoxidized does not work with --local (yet)')
782 testdir = os.path.dirname(_sys2bytes(canonpath(sys.argv[0])))
783 reporootdir = os.path.dirname(testdir)
784 path_local_hg = os.path.join(
785 reporootdir, b'.local-venv', BINDIRNAME, b"hg"
786 )
787 if not os.path.exists(path_local_hg):
788 if "HGTEST_REAL_HG" in os.environ:
789 # this file is run from a test (typically test-run-tests.t)
790 # no local environment but we can still use ./hg to please test-run-tests.t
791 path_local_hg = os.path.join(reporootdir, b"hg")
792 else:
793 message = (
794 f"run-tests.py called with --local but .local-venv does not exist.\n"
795 f'To create it, run \nmake local PYTHON="{sys.executable}"'
796 )
797 print(message, file=sys.stderr)
798 sys.exit(1)
799
800 pathandattrs = [(path_local_hg, 'with_hg')]
801 if options.chg:
802 pathandattrs.append((b'contrib/chg/chg', 'with_chg'))
803 if options.rhg:
804 pathandattrs.append((b'rust/target/release/rhg', 'with_rhg'))
805 for relpath, attr in pathandattrs:
806 binpath = os.path.join(reporootdir, relpath)
807 if not (WINDOWS or os.access(binpath, os.X_OK)):
808 parser.error(
809 '--local specified, but %r not found or '
810 'not executable' % binpath
811 )
812 setattr(options, attr, _bytes2sys(binpath))
813
814 if options.with_hg:
815 options.with_hg = canonpath(_sys2bytes(options.with_hg))
816 if not (
817 os.path.isfile(options.with_hg)
818 and os.access(options.with_hg, os.X_OK)
819 ):
820 parser.error('--with-hg must specify an executable hg script')
821 if os.path.basename(options.with_hg) not in [b'hg', b'hg.exe']:
822 msg = 'warning: --with-hg should specify an hg script, not: %s\n'
823 msg %= _bytes2sys(os.path.basename(options.with_hg))
824 sys.stderr.write(msg)
825 sys.stderr.flush()
826
827 if (options.chg or options.with_chg) and WINDOWS:
828 parser.error('chg does not work on %s' % os.name)
829 if (options.rhg or options.with_rhg) and WINDOWS:
830 parser.error('rhg does not work on %s' % os.name)
831 if options.pyoxidized and not (MACOS or WINDOWS):
832 parser.error('--pyoxidized is currently macOS and Windows only')
833 if options.with_chg:
834 options.chg = False # no installation to temporary location
835 options.with_chg = canonpath(_sys2bytes(options.with_chg))
836 if not (
837 os.path.isfile(options.with_chg)
838 and os.access(options.with_chg, os.X_OK)
839 ):
840 parser.error('--with-chg must specify a chg executable')
841 if options.with_rhg:
842 options.rhg = False # no installation to temporary location
843 options.with_rhg = canonpath(_sys2bytes(options.with_rhg))
844 if not (
845 os.path.isfile(options.with_rhg)
846 and os.access(options.with_rhg, os.X_OK)
847 ):
848 parser.error('--with-rhg must specify a rhg executable')
849 if options.chg and options.with_hg:
850 # chg shares installation location with hg
851 parser.error(
852 '--chg does not work when --with-hg is specified '
853 '(use --with-chg instead)'
854 )
855 if options.rhg and options.with_hg:
856 # rhg shares installation location with hg
857 parser.error(
858 '--rhg does not work when --with-hg is specified '
859 '(use --with-rhg instead)'
860 )
861 if options.rhg and options.chg:
862 parser.error('--rhg and --chg do not work together')
863
864 if options.color == 'always' and not pygmentspresent:
865 sys.stderr.write(
866 'warning: --color=always ignored because '
867 'pygments is not installed\n'
868 )
869
870 global useipv6
871 if options.ipv6:
872 useipv6 = checksocketfamily('AF_INET6')
873 else:
874 # only use IPv6 if IPv4 is unavailable and IPv6 is available
875 useipv6 = (not checksocketfamily('AF_INET')) and checksocketfamily(
876 'AF_INET6'
877 )
878
879 options.anycoverage = options.cover or options.annotate or options.htmlcov
880 if options.anycoverage:
881 try:
882 import coverage
883
884 coverage.__version__ # silence unused import warning
885 except ImportError:
886 parser.error('coverage options now require the coverage package')
887
888 if options.anycoverage and options.local:
889 # this needs some path mangling somewhere, I guess
890 parser.error(
891 "sorry, coverage options do not work when --local " "is specified"
892 )
893
894 if options.anycoverage and options.with_hg:
895 parser.error(
896 "sorry, coverage options do not work when --with-hg " "is specified"
897 )
898
899 global verbose
900 if options.verbose:
901 verbose = ''
902
903 if options.tmpdir:
904 options.tmpdir = canonpath(options.tmpdir)
905
906 if options.jobs < 1:
907 parser.error('--jobs must be positive')
908 if options.interactive and options.debug:
909 parser.error("-i/--interactive and -d/--debug are incompatible")
910 if options.debug:
911 if options.timeout != defaults['timeout']:
912 sys.stderr.write('warning: --timeout option ignored with --debug\n')
913 if options.slowtimeout != defaults['slowtimeout']:
914 sys.stderr.write(
915 'warning: --slowtimeout option ignored with --debug\n'
916 )
917 options.timeout = 0
918 options.slowtimeout = 0
919
920 if options.blacklist:
921 options.blacklist = parselistfiles(options.blacklist, 'blacklist')
922 if options.whitelist:
923 options.whitelisted = parselistfiles(options.whitelist, 'whitelist')
924 else:
925 options.whitelisted = {}
926
927 if options.showchannels:
928 options.nodiff = True
929
930 if options.shard_total is not None:
931 if options.shard_index is None:
932 parser.error("--shard-total requires --shard-index to be set")
933
934 if options.shard_index is not None:
935 if options.shard_total is None:
936 parser.error("--shard-index requires --shard-total to be set")
937 elif options.shard_index <= 0:
938 msg = "--shard-index must be > 0 (%d)"
939 msg %= options.shard_index
940 parser.error(msg)
941 elif options.shard_index > options.shard_total:
942 msg = (
943 "--shard-index must be <= than --shard-total (%d not in [1,%d])"
944 )
945 msg %= (options.shard_index, options.shard_total)
946 parser.error(msg)
947
948 if options.shard_total is not None and options.order_by_runtime:
949 msg = "cannot use --order-by-runtime when sharding"
950 parser.error(msg)
951
952 if options.shard_total is not None and options.random:
953 msg = "cannot use --random when sharding"
954 parser.error(msg)
955
956 return options
957
958
959 def rename(src, dst):
960 """Like os.rename(), trade atomicity and opened files friendliness
961 for existing destination support.
962 """
963 shutil.copy(src, dst)
964 os.remove(src)
965
966
967 def makecleanable(path):
968 """Try to fix directory permission recursively so that the entire tree
969 can be deleted"""
970 for dirpath, dirnames, _filenames in os.walk(path, topdown=True):
971 for d in dirnames:
972 p = os.path.join(dirpath, d)
973 try:
974 os.chmod(p, os.stat(p).st_mode & 0o777 | 0o700) # chmod u+rwx
975 except OSError:
976 pass
977
978
979 _unified_diff = functools.partial(difflib.diff_bytes, difflib.unified_diff)
980
981
982 def getdiff(expected, output, ref, err):
983 servefail = False
984 lines = []
985 for line in _unified_diff(expected, output, ref, err):
986 if line.startswith(b'+++') or line.startswith(b'---'):
987 line = line.replace(b'\\', b'/')
988 if line.endswith(b' \n'):
989 line = line[:-2] + b'\n'
990 lines.append(line)
991 if not servefail and line.startswith(
992 b'+ abort: child process failed to start'
993 ):
994 servefail = True
995
996 return servefail, lines
997
998
999 verbose = False
1000
1001
1002 def vlog(*msg):
1003 """Log only when in verbose mode."""
1004 if verbose is False:
1005 return
1006
1007 return log(*msg)
1008
1009
1010 # Bytes that break XML even in a CDATA block: control characters 0-31
1011 # sans \t, \n and \r
1012 CDATA_EVIL = re.compile(br"[\000-\010\013\014\016-\037]")
1013
1014 # Match feature conditionalized output lines in the form, capturing the feature
1015 # list in group 2, and the preceeding line output in group 1:
1016 #
1017 # output..output (feature !)\n
1018 optline = re.compile(br'(.*) \((.+?) !\)\n$')
1019
1020
1021 def cdatasafe(data):
1022 """Make a string safe to include in a CDATA block.
1023
1024 Certain control characters are illegal in a CDATA block, and
1025 there's no way to include a ]]> in a CDATA either. This function
1026 replaces illegal bytes with ? and adds a space between the ]] so
1027 that it won't break the CDATA block.
1028 """
1029 return CDATA_EVIL.sub(b'?', data).replace(b']]>', b'] ]>')
1030
1031
1032 def log(*msg):
1033 """Log something to stdout.
1034
1035 Arguments are strings to print.
1036 """
1037 with iolock:
1038 if verbose:
1039 print(verbose, end=' ')
1040 for m in msg:
1041 print(m, end=' ')
1042 print()
1043 sys.stdout.flush()
1044
1045
1046 def highlightdiff(line, color):
1047 if not color:
1048 return line
1049 assert pygmentspresent
1050 return pygments.highlight(
1051 line.decode('latin1'), difflexer, terminal256formatter
1052 ).encode('latin1')
1053
1054
1055 def highlightmsg(msg, color):
1056 if not color:
1057 return msg
1058 assert pygmentspresent
1059 return pygments.highlight(msg, runnerlexer, runnerformatter)
1060
1061
1062 def highlight_progress(progress, color):
1063 if not color:
1064 return progress
1065 assert pygmentspresent
1066 token = progress_type.get(progress)
1067 if token is None:
1068 return progress
1069 style = runnerformatter.style_string.get(str(token))
1070 if style is None:
1071 return progress
1072 else:
1073 return style[0] + progress + style[1]
1074
1075
1076 def terminate(proc):
1077 """Terminate subprocess"""
1078 vlog('# Terminating process %d' % proc.pid)
1079 try:
1080 proc.terminate()
1081 except OSError:
1082 pass
1083
1084
1085 def killdaemons(pidfile):
1086 import killdaemons as killmod
1087
1088 return killmod.killdaemons(pidfile, tryhard=False, remove=True, logfn=vlog)
1089
1090
1091 # sysconfig is not thread-safe (https://github.com/python/cpython/issues/92452)
1092 sysconfiglock = threading.Lock()
1093
1094 # magic return for TTest that indicate syntax issue.
1095 RET_SYNTAX_ERROR = 1025
1096
1097
1098 class TestError(RuntimeError):
1099 def __init__(self, summary: str):
1100 self.summary = summary
1101 super().__init__(summary)
1102
1103
1104 class Test(unittest.TestCase):
1105 """Encapsulates a single, runnable test.
1106
1107 While this class conforms to the unittest.TestCase API, it differs in that
1108 instances need to be instantiated manually. (Typically, unittest.TestCase
1109 classes are instantiated automatically by scanning modules.)
1110 """
1111
1112 # Status code reserved for skipped tests (used by hghave).
1113 SKIPPED_STATUS = 80
1114
1115 def __init__(
1116 self,
1117 path,
1118 outputdir,
1119 tmpdir,
1120 keeptmpdir=False,
1121 debug=False,
1122 first=False,
1123 timeout=None,
1124 startport=None,
1125 extraconfigopts=None,
1126 shell=None,
1127 python=None,
1128 hgcommand=None,
1129 slowtimeout=None,
1130 usechg=False,
1131 chgdebug=False,
1132 useipv6=False,
1133 forbid_skip=False,
1134 ):
1135 """Create a test from parameters.
1136
1137 path is the full path to the file defining the test.
1138
1139 tmpdir is the main temporary directory to use for this test.
1140
1141 keeptmpdir determines whether to keep the test's temporary directory
1142 after execution. It defaults to removal (False).
1143
1144 debug mode will make the test execute verbosely, with unfiltered
1145 output.
1146
1147 timeout controls the maximum run time of the test. It is ignored when
1148 debug is True. See slowtimeout for tests with #require slow.
1149
1150 slowtimeout overrides timeout if the test has #require slow.
1151
1152 startport controls the starting port number to use for this test. Each
1153 test will reserve 3 port numbers for execution. It is the caller's
1154 responsibility to allocate a non-overlapping port range to Test
1155 instances.
1156
1157 extraconfigopts is an iterable of extra hgrc config options. Values
1158 must have the form "key=value" (something understood by hgrc). Values
1159 of the form "foo.key=value" will result in "[foo] key=value".
1160
1161 shell is the shell to execute tests in.
1162 """
1163 if timeout is None:
1164 timeout = defaults['timeout']
1165 if startport is None:
1166 startport = defaults['port']
1167 if slowtimeout is None:
1168 slowtimeout = defaults['slowtimeout']
1169 self.path = path
1170 self.relpath = os.path.relpath(path)
1171 self.bname = os.path.basename(path)
1172 base_relpath = _bytes2sys(os.path.relpath(path, INITIAL_CWD))
1173 self.name = base_relpath.replace(os.path.sep, '/')
1174 self._testdir = os.path.dirname(path)
1175 self._outputdir = outputdir
1176 self._tmpname = os.path.basename(path)
1177 self.errpath = os.path.join(self._outputdir, b'%s.err' % self.bname)
1178
1179 self._threadtmp = tmpdir
1180 self._hgrcpath = os.path.join(self._threadtmp, b'.hgrc')
1181 self._keeptmpdir = keeptmpdir
1182 self._debug = debug
1183 self._first = first
1184 self._timeout = timeout
1185 self._slowtimeout = slowtimeout
1186 self._startport = startport
1187 self._extraconfigopts = extraconfigopts or []
1188 self._shell = _sys2bytes(shell)
1189 assert python is not None
1190 self._python = python
1191 self._hgcommand = hgcommand or b'hg'
1192 self._usechg = usechg
1193 self._chgdebug = chgdebug
1194 self._useipv6 = useipv6
1195
1196 self._aborted = False
1197 self._daemonpids = []
1198 self._finished = None
1199 self._ret = None
1200 self._out = None
1201 self._skipped = None
1202 self._testtmp = None
1203 self._chgsockdir = None
1204 self._forbid_skip = forbid_skip
1205
1206 self._refout = self.readrefout()
1207
1208 @property
1209 def _pythonb(self):
1210 return _sys2bytes(self._python.replace('\\', '/'))
1211
1212 def readrefout(self):
1213 """read reference output"""
1214 # If we're not in --debug mode and reference output file exists,
1215 # check test output against it.
1216 if self._debug:
1217 return None # to match "out is None"
1218 elif os.path.exists(self.refpath):
1219 with open(self.refpath, 'rb') as f:
1220 return f.read().splitlines(True)
1221 else:
1222 return []
1223
1224 # needed to get base class __repr__ running
1225 @property
1226 def _testMethodName(self):
1227 return self.name
1228
1229 def __str__(self):
1230 return self.name
1231
1232 def shortDescription(self):
1233 return self.name
1234
1235 def setUp(self):
1236 """Tasks to perform before run()."""
1237 self._finished = False
1238 self._ret = None
1239 self._out = None
1240 self._skipped = None
1241
1242 try:
1243 os.mkdir(self._threadtmp)
1244 except FileExistsError:
1245 pass
1246
1247 name = self._tmpname
1248 self._testtmp = os.path.join(self._threadtmp, name)
1249 os.mkdir(self._testtmp)
1250
1251 # Remove any previous output files.
1252 if os.path.exists(self.errpath):
1253 try:
1254 os.remove(self.errpath)
1255 except FileNotFoundError:
1256 # We might have raced another test to clean up a .err file,
1257 # so ignore FileNotFoundError when removing a previous .err
1258 # file.
1259 pass
1260
1261 if self._usechg:
1262 self._chgsockdir = os.path.join(
1263 self._threadtmp, b'%s.chgsock' % name
1264 )
1265 os.mkdir(self._chgsockdir)
1266
1267 def run(self, result):
1268 """Run this test and report results against a TestResult instance."""
1269 # This function is extremely similar to unittest.TestCase.run(). Once
1270 # we require Python 2.7 (or at least its version of unittest), this
1271 # function can largely go away.
1272 self._result = result
1273 result.startTest(self)
1274 try:
1275 try:
1276 self.setUp()
1277 except (KeyboardInterrupt, SystemExit):
1278 self._aborted = True
1279 raise
1280 except Exception:
1281 result.addError(self, sys.exc_info())
1282 return
1283
1284 success = False
1285 try:
1286 self.runTest()
1287 except KeyboardInterrupt:
1288 self._aborted = True
1289 raise
1290 except unittest.SkipTest as e:
1291 result.addSkip(self, str(e))
1292 # The base class will have already counted this as a
1293 # test we "ran", but we want to exclude skipped tests
1294 # from those we count towards those run.
1295 result.testsRun -= 1
1296 except self.failureException as e:
1297 # This differs from unittest in that we don't capture
1298 # the stack trace. This is for historical reasons and
1299 # this decision could be revisited in the future,
1300 # especially for PythonTest instances.
1301 if result.addFailure(self, str(e)):
1302 success = True
1303 except TestError as exc:
1304 result.addError(self, message=exc.summary)
1305 except Exception:
1306 result.addError(self, sys.exc_info())
1307 else:
1308 success = True
1309
1310 try:
1311 self.tearDown()
1312 except (KeyboardInterrupt, SystemExit):
1313 self._aborted = True
1314 raise
1315 except Exception:
1316 result.addError(self, sys.exc_info())
1317 success = False
1318
1319 if success:
1320 result.addSuccess(self)
1321 finally:
1322 result.stopTest(self, interrupted=self._aborted)
1323
1324 def runTest(self):
1325 """Run this test instance.
1326
1327 This will return a tuple describing the result of the test.
1328 """
1329 env = self._getenv()
1330 self._genrestoreenv(env)
1331 self._daemonpids.append(env['DAEMON_PIDS'])
1332 self._createhgrc(env['HGRCPATH'])
1333
1334 vlog('# Test', self.name)
1335
1336 ret, out = self._run(env)
1337 self._finished = True
1338 self._ret = ret
1339 self._out = out
1340
1341 def describe(ret):
1342 if ret < 0:
1343 return 'killed by signal: %d' % -ret
1344 return 'returned error code %d' % ret
1345
1346 self._skipped = False
1347
1348 if ret == self.SKIPPED_STATUS:
1349 if out is None: # Debug mode, nothing to parse.
1350 missing = ['unknown']
1351 failed = None
1352 else:
1353 missing, failed = TTest.parsehghaveoutput(out)
1354
1355 if not missing:
1356 missing = ['skipped']
1357
1358 if failed:
1359 self.fail('hg have failed checking for %s' % failed[-1])
1360 else:
1361 if self._forbid_skip:
1362 msg = "%s, but skipping is forbidden" % missing[-1]
1363 self.raise_error(msg)
1364 self._skipped = True
1365 raise unittest.SkipTest(missing[-1])
1366 elif ret == 'timeout':
1367 self.fail('timed out')
1368 elif ret is False:
1369 self.fail('no result code from test')
1370 elif out != self._refout:
1371 # Diff generation may rely on written .err file.
1372 if (
1373 (ret != 0 or out != self._refout)
1374 and not self._skipped
1375 and not self._debug
1376 ):
1377 with open(self.errpath, 'wb') as f:
1378 for line in out:
1379 f.write(line)
1380
1381 # The result object handles diff calculation for us.
1382 with firstlock:
1383 if self._result.addOutputMismatch(self, ret, out, self._refout):
1384 # change was accepted, skip failing
1385 return
1386 if self._first:
1387 global firsterror
1388 firsterror = True
1389
1390 if ret == RET_SYNTAX_ERROR:
1391 msg = 'bad syntax'
1392 self.raise_error(msg)
1393 else:
1394 if ret:
1395 msg = 'output changed and ' + describe(ret)
1396 else:
1397 msg = 'output changed'
1398 self.fail(msg)
1399 elif ret:
1400 self.fail(describe(ret))
1401
1402 def tearDown(self):
1403 """Tasks to perform after run()."""
1404 for entry in self._daemonpids:
1405 killdaemons(entry)
1406 self._daemonpids = []
1407
1408 if self._keeptmpdir:
1409 log(
1410 '\nKeeping testtmp dir: %s\nKeeping threadtmp dir: %s'
1411 % (
1412 _bytes2sys(self._testtmp),
1413 _bytes2sys(self._threadtmp),
1414 )
1415 )
1416 else:
1417 try:
1418 shutil.rmtree(self._testtmp)
1419 except OSError:
1420 # unreadable directory may be left in $TESTTMP; fix permission
1421 # and try again
1422 makecleanable(self._testtmp)
1423 shutil.rmtree(self._testtmp, True)
1424 shutil.rmtree(self._threadtmp, True)
1425
1426 if self._usechg:
1427 # chgservers will stop automatically after they find the socket
1428 # files are deleted
1429 shutil.rmtree(self._chgsockdir, True)
1430
1431 if (
1432 (self._ret != 0 or self._out != self._refout)
1433 and not self._skipped
1434 and not self._debug
1435 and self._out
1436 ):
1437 with open(self.errpath, 'wb') as f:
1438 for line in self._out:
1439 f.write(line)
1440
1441 vlog("# Ret was:", self._ret, '(%s)' % self.name)
1442
1443 def _run(self, env):
1444 # This should be implemented in child classes to run tests.
1445 raise unittest.SkipTest('unknown test type')
1446
1447 def abort(self):
1448 """Terminate execution of this test."""
1449 self._aborted = True
1450
1451 def _portmap(self, i):
1452 offset = b'' if i == 0 else b'%d' % i
1453 return (br':%d\b' % (self._startport + i), b':$HGPORT%s' % offset)
1454
1455 def _getreplacements(self):
1456 """Obtain a mapping of text replacements to apply to test output.
1457
1458 Test output needs to be normalized so it can be compared to expected
1459 output. This function defines how some of that normalization will
1460 occur.
1461 """
1462 r = [self._portmap(port) for port in range(HGPORT_COUNT)]
1463
1464 r.extend(
1465 [
1466 (br'([^0-9])%s' % re.escape(self._localip()), br'\1$LOCALIP'),
1467 (br'\bHG_TXNID=TXN:[a-f0-9]{40}\b', br'HG_TXNID=TXN:$ID$'),
1468 (self._escapepath(self._testtmp), b'$TESTTMP'),
1469 (self._escapepath(self._hgrcpath), b'$HGRCPATH'),
1470 (self._escapepath(self._testdir), b'$TESTDIR'),
1471 # we don't add escape for RUNTEST_DIR because it might be the
1472 # same as TESTDIR and the replacement won't work well.
1473 ]
1474 )
1475
1476 if WINDOWS:
1477 # JSON output escapes backslashes in Windows paths, so also catch a
1478 # double-escape.
1479 replaced = self._testtmp.replace(b'\\', br'\\')
1480 r.append((self._escapepath(replaced), b'$STR_REPR_TESTTMP'))
1481 replaced = self._hgrcpath.replace(b'\\', br'\\')
1482 r.append((self._escapepath(replaced), b'$STR_REPR_HGRCPATH'))
1483 replaced = self._testdir.replace(b'\\', br'\\')
1484 r.append((self._escapepath(replaced), b'$STR_REPR_TESTDIR'))
1485
1486 replacementfile = os.path.join(self._testdir, b'common-pattern.py')
1487
1488 if os.path.exists(replacementfile):
1489 data = {}
1490 with open(replacementfile, mode='rb') as source:
1491 # the intermediate 'compile' step help with debugging
1492 code = compile(source.read(), replacementfile, 'exec')
1493 exec(code, data)
1494 for value in data.get('substitutions', ()):
1495 if len(value) != 2:
1496 msg = 'malformatted substitution in %s: %r'
1497 msg %= (replacementfile, value)
1498 raise ValueError(msg)
1499 r.append(value)
1500 return r
1501
1502 def _escapepath(self, p):
1503 if WINDOWS:
1504 return b''.join(
1505 c.isalpha()
1506 and b'[%s%s]' % (c.lower(), c.upper())
1507 or c in b'/\\'
1508 and br'[/\\]'
1509 or c.isdigit()
1510 and c
1511 or b'\\' + c
1512 for c in [p[i : i + 1] for i in range(len(p))]
1513 )
1514 else:
1515 return re.escape(p)
1516
1517 def _localip(self):
1518 if self._useipv6:
1519 return b'::1'
1520 else:
1521 return b'127.0.0.1'
1522
1523 def _genrestoreenv(self, testenv):
1524 """Generate a script that can be used by tests to restore the original
1525 environment."""
1526 # Put the restoreenv script inside self._threadtmp
1527 scriptpath = os.path.join(self._threadtmp, b'restoreenv.sh')
1528 testenv['HGTEST_RESTOREENV'] = _bytes2sys(scriptpath)
1529
1530 # Only restore environment variable names that the shell allows
1531 # us to export.
1532 name_regex = re.compile('^[a-zA-Z][a-zA-Z0-9_]*$')
1533
1534 # Do not restore these variables; otherwise tests would fail.
1535 reqnames = {'PYTHON', 'TESTDIR', 'TESTTMP'}
1536
1537 with open(scriptpath, 'w') as envf:
1538 for name, value in origenviron.items():
1539 if not name_regex.match(name):
1540 # Skip environment variables with unusual names not
1541 # allowed by most shells.
1542 continue
1543 if name in reqnames:
1544 continue
1545 envf.write('%s=%s\n' % (name, shellquote(value)))
1546
1547 for name in testenv:
1548 if name in origenviron or name in reqnames:
1549 continue
1550 envf.write('unset %s\n' % (name,))
1551
1552 def _getenv(self):
1553 """Obtain environment variables to use during test execution."""
1554
1555 def defineport(i):
1556 offset = '' if i == 0 else '%s' % i
1557 env["HGPORT%s" % offset] = '%s' % (self._startport + i)
1558
1559 env = os.environ.copy()
1560 with sysconfiglock:
1561 env['PYTHONUSERBASE'] = sysconfig.get_config_var('userbase') or ''
1562 env['HGEMITWARNINGS'] = '1'
1563 env['TESTTMP'] = _bytes2sys(self._testtmp)
1564 # the FORWARD_SLASH version is useful when running `sh` on non unix
1565 # system (e.g. Windows)
1566 env['TESTTMP_FORWARD_SLASH'] = env['TESTTMP'].replace(os.sep, '/')
1567 uid_file = os.path.join(_bytes2sys(self._testtmp), 'UID')
1568 env['HGTEST_UUIDFILE'] = uid_file
1569 env['TESTNAME'] = self.name
1570 env['HOME'] = _bytes2sys(self._testtmp)
1571 if WINDOWS:
1572 env['REALUSERPROFILE'] = env['USERPROFILE']
1573 # py3.8+ ignores HOME: https://bugs.python.org/issue36264
1574 env['USERPROFILE'] = env['HOME']
1575 default_timeout = default_defaults['timeout'][1]
1576 formated_timeout = _bytes2sys(b"%d" % default_timeout)
1577 env['HGTEST_TIMEOUT_DEFAULT'] = formated_timeout
1578 env['HGTEST_TIMEOUT'] = _bytes2sys(b"%d" % self._timeout)
1579 timeout_perc = max(100, (self._timeout * 100) // default_timeout)
1580 env['HGTEST_TIMEOUT_PERCENTAGE'] = _bytes2sys(b"%d" % timeout_perc)
1581
1582 for port in range(HGPORT_COUNT):
1583 defineport(port)
1584 env["HGRCPATH"] = _bytes2sys(self._hgrcpath)
1585 env["DAEMON_PIDS"] = _bytes2sys(
1586 os.path.join(self._threadtmp, b'daemon.pids')
1587 )
1588 env["HGEDITOR"] = f'"{self._python}" -c "import sys; sys.exit(0)"'
1589 env["HGUSER"] = "test"
1590 env["HGENCODING"] = "ascii"
1591 env["HGENCODINGMODE"] = "strict"
1592 env["HGHOSTNAME"] = "test-hostname"
1593 env['HGIPV6'] = str(int(self._useipv6))
1594 # See contrib/catapipe.py for how to use this functionality.
1595 if 'HGTESTCATAPULTSERVERPIPE' not in env:
1596 # If we don't have HGTESTCATAPULTSERVERPIPE explicitly set, pull the
1597 # non-test one in as a default, otherwise set to devnull
1598 env['HGTESTCATAPULTSERVERPIPE'] = env.get(
1599 'HGCATAPULTSERVERPIPE', os.devnull
1600 )
1601
1602 extraextensions = []
1603 for opt in self._extraconfigopts:
1604 section, key = opt.split('.', 1)
1605 if section != 'extensions':
1606 continue
1607 name = key.split('=', 1)[0]
1608 extraextensions.append(name)
1609
1610 if extraextensions:
1611 env['HGTESTEXTRAEXTENSIONS'] = ' '.join(extraextensions)
1612
1613 # LOCALIP could be ::1 or 127.0.0.1. Useful for tests that require raw
1614 # IP addresses.
1615 env['LOCALIP'] = _bytes2sys(self._localip())
1616
1617 # This has the same effect as Py_LegacyWindowsStdioFlag in exewrapper.c,
1618 # but this is needed for testing python instances like dummyssh,
1619 # dummysmtpd.py, and dumbhttp.py.
1620 if WINDOWS:
1621 env['PYTHONLEGACYWINDOWSSTDIO'] = '1'
1622
1623 # Modified HOME in test environment can confuse Rust tools. So set
1624 # CARGO_HOME and RUSTUP_HOME automatically if a Rust toolchain is
1625 # present and these variables aren't already defined.
1626 cargo_home_path = os.path.expanduser('~/.cargo')
1627 rustup_home_path = os.path.expanduser('~/.rustup')
1628
1629 if os.path.exists(cargo_home_path) and b'CARGO_HOME' not in osenvironb:
1630 env['CARGO_HOME'] = cargo_home_path
1631 if (
1632 os.path.exists(rustup_home_path)
1633 and b'RUSTUP_HOME' not in osenvironb
1634 ):
1635 env['RUSTUP_HOME'] = rustup_home_path
1636
1637 # Reset some environment variables to well-known values so that
1638 # the tests produce repeatable output.
1639 env['LANG'] = env['LC_ALL'] = env['LANGUAGE'] = 'C'
1640 env['TZ'] = 'GMT'
1641 env["EMAIL"] = "Foo Bar <[email protected]>"
1642 env['COLUMNS'] = '80'
1643 env['TERM'] = 'xterm'
1644
1645 dropped = [
1646 'CDPATH',
1647 'CHGDEBUG',
1648 'EDITOR',
1649 'GREP_OPTIONS',
1650 'HG',
1651 'HGMERGE',
1652 'HGPLAIN',
1653 'HGPLAINEXCEPT',
1654 'HGPROF',
1655 'http_proxy',
1656 'no_proxy',
1657 'NO_PROXY',
1658 'PAGER',
1659 'VISUAL',
1660 ]
1661
1662 for k in dropped:
1663 if k in env:
1664 del env[k]
1665
1666 # unset env related to hooks
1667 for k in list(env):
1668 if k.startswith('HG_'):
1669 del env[k]
1670
1671 if self._usechg:
1672 env['CHGSOCKNAME'] = os.path.join(self._chgsockdir, b'server')
1673 if self._chgdebug:
1674 env['CHGDEBUG'] = 'true'
1675
1676 return env
1677
1678 def _createhgrc(self, path):
1679 """Create an hgrc file for this test."""
1680 with open(path, 'wb') as hgrc:
1681 hgrc.write(b'[ui]\n')
1682 hgrc.write(b'slash = True\n')
1683 hgrc.write(b'interactive = False\n')
1684 hgrc.write(b'detailed-exit-code = True\n')
1685 hgrc.write(b'merge = internal:merge\n')
1686 hgrc.write(b'mergemarkers = detailed\n')
1687 hgrc.write(b'promptecho = True\n')
1688 dummyssh = os.path.join(self._testdir, b'dummyssh')
1689 hgrc.write(b'ssh = "%s" "%s"\n' % (self._pythonb, dummyssh))
1690 hgrc.write(b'timeout.warn=15\n')
1691 hgrc.write(b'[chgserver]\n')
1692 hgrc.write(b'idletimeout=60\n')
1693 hgrc.write(b'[defaults]\n')
1694 hgrc.write(b'[devel]\n')
1695 hgrc.write(b'all-warnings = true\n')
1696 hgrc.write(b'default-date = 0 0\n')
1697 hgrc.write(b'[largefiles]\n')
1698 hgrc.write(
1699 b'usercache = %s\n'
1700 % (os.path.join(self._testtmp, b'.cache/largefiles'))
1701 )
1702 hgrc.write(b'[lfs]\n')
1703 hgrc.write(
1704 b'usercache = %s\n'
1705 % (os.path.join(self._testtmp, b'.cache/lfs'))
1706 )
1707 hgrc.write(b'[web]\n')
1708 hgrc.write(b'address = localhost\n')
1709 hgrc.write(b'ipv6 = %r\n' % self._useipv6)
1710 hgrc.write(b'server-header = testing stub value\n')
1711
1712 for opt in self._extraconfigopts:
1713 section, key = _sys2bytes(opt).split(b'.', 1)
1714 assert b'=' in key, (
1715 'extra config opt %s must ' 'have an = for assignment' % opt
1716 )
1717 hgrc.write(b'[%s]\n%s\n' % (section, key))
1718
1719 def fail(self, msg):
1720 # unittest differentiates between errored and failed.
1721 # Failed is denoted by AssertionError (by default at least).
1722 raise AssertionError(msg)
1723
1724 def raise_error(self, msg):
1725 # unittest differentiates between errored and failed.
1726 # Failed is denoted by AssertionError (by default at least).
1727 raise TestError(msg)
1728
1729 def _runcommand(self, cmd, env, normalizenewlines=False):
1730 """Run command in a sub-process, capturing the output (stdout and
1731 stderr).
1732
1733 Return a tuple (exitcode, output). output is None in debug mode.
1734 """
1735 if self._debug:
1736 proc = subprocess.Popen(
1737 _bytes2sys(cmd),
1738 shell=True,
1739 close_fds=closefds,
1740 cwd=_bytes2sys(self._testtmp),
1741 env=env,
1742 )
1743 ret = proc.wait()
1744 return (ret, None)
1745
1746 proc = Popen4(cmd, self._testtmp, self._timeout, env)
1747
1748 def cleanup():
1749 terminate(proc)
1750 ret = proc.wait()
1751 if ret == 0:
1752 ret = signal.SIGTERM << 8
1753 killdaemons(env['DAEMON_PIDS'])
1754 return ret
1755
1756 proc.tochild.close()
1757
1758 try:
1759 output = proc.fromchild.read()
1760 except KeyboardInterrupt:
1761 vlog('# Handling keyboard interrupt')
1762 cleanup()
1763 raise
1764
1765 ret = proc.wait()
1766 if wifexited(ret):
1767 ret = os.WEXITSTATUS(ret)
1768
1769 if proc.timeout:
1770 ret = 'timeout'
1771
1772 if ret:
1773 killdaemons(env['DAEMON_PIDS'])
1774
1775 for s, r in self._getreplacements():
1776 output = re.sub(s, r, output)
1777
1778 if normalizenewlines:
1779 output = output.replace(b'\r\n', b'\n')
1780
1781 return ret, output.splitlines(True)
1782
1783
1784 class PythonTest(Test):
1785 """A Python-based test."""
1786
1787 @property
1788 def refpath(self):
1789 return os.path.join(self._testdir, b'%s.out' % self.bname)
1790
1791 def _run(self, env):
1792 # Quote the python(3) executable for Windows
1793 cmd = b'"%s" "%s"' % (self._pythonb, self.path)
1794 vlog("# Running", cmd.decode("utf-8"))
1795 result = self._runcommand(cmd, env, normalizenewlines=WINDOWS)
1796 if self._aborted:
1797 raise KeyboardInterrupt()
1798
1799 return result
1800
1801
1802 # Some glob patterns apply only in some circumstances, so the script
1803 # might want to remove (glob) annotations that otherwise should be
1804 # retained.
1805 checkcodeglobpats = [
1806 # On Windows it looks like \ doesn't require a (glob), but we know
1807 # better.
1808 re.compile(br'^pushing to \$TESTTMP/.*[^)]$'),
1809 re.compile(br'^moving \S+/.*[^)]$'),
1810 re.compile(br'^pulling from \$TESTTMP/.*[^)]$'),
1811 # Not all platforms have 127.0.0.1 as loopback (though most do),
1812 # so we always glob that too.
1813 re.compile(br'.*\$LOCALIP.*$'),
1814 ]
1815
1816 bchr = lambda x: bytes([x])
1817
1818 WARN_UNDEFINED = 1
1819 WARN_YES = 2
1820 WARN_NO = 3
1821
1822 MARK_OPTIONAL = b" (?)\n"
1823
1824
1825 def isoptional(line):
1826 return line.endswith(MARK_OPTIONAL)
1827
1828
1829 class TTest(Test):
1830 """A "t test" is a test backed by a .t file."""
1831
1832 SKIPPED_PREFIX = b'skipped: '
1833 FAILED_PREFIX = b'hghave check failed: '
1834 NEEDESCAPE = re.compile(br'[\x00-\x08\x0b-\x1f\x7f-\xff]').search
1835
1836 ESCAPESUB = re.compile(br'[\x00-\x08\x0b-\x1f\\\x7f-\xff]').sub
1837 ESCAPEMAP = {bchr(i): br'\x%02x' % i for i in range(256)}
1838 ESCAPEMAP.update({b'\\': b'\\\\', b'\r': br'\r'})
1839
1840 def __init__(self, path, *args, **kwds):
1841 # accept an extra "case" parameter
1842 case = kwds.pop('case', [])
1843 self._case = case
1844 self._allcases = {x for y in parsettestcases(path) for x in y}
1845 super().__init__(path, *args, **kwds)
1846 if case:
1847 casepath = b'#'.join(case)
1848 self.name = '%s#%s' % (self.name, _bytes2sys(casepath))
1849 self.errpath = b'%s#%s.err' % (self.errpath[:-4], casepath)
1850 self._tmpname += b'-%s' % casepath.replace(b'#', b'-')
1851 self._have = {}
1852
1853 @property
1854 def refpath(self):
1855 return os.path.join(self._testdir, self.bname)
1856
1857 def _run(self, env):
1858 ok, stdout = self._hghave([b"true"])
1859 if not ok:
1860 self.raise_error("broken hghave")
1861
1862 with open(self.path, 'rb') as f:
1863 lines = f.readlines()
1864
1865 # .t file is both reference output and the test input, keep reference
1866 # output updated with the the test input. This avoids some race
1867 # conditions where the reference output does not match the actual test.
1868 if self._refout is not None:
1869 self._refout = lines
1870
1871 salt, script, after, expected, syntax_ok = self._parsetest(lines)
1872
1873 # Write out the generated script.
1874 fname = b'%s.sh' % self._testtmp
1875 with open(fname, 'wb') as f:
1876 for l in script:
1877 f.write(l)
1878
1879 cmd = b'%s "%s"' % (self._shell, fname)
1880 vlog("# Running", cmd.decode("utf-8"))
1881
1882 exitcode, output = self._runcommand(cmd, env)
1883
1884 if self._aborted:
1885 raise KeyboardInterrupt()
1886
1887 # Do not merge output if skipped. Return hghave message instead.
1888 # Similarly, with --debug, output is None.
1889 if exitcode == self.SKIPPED_STATUS or output is None:
1890 return exitcode, output
1891
1892 r = self._processoutput(exitcode, output, salt, after, expected)
1893 if not syntax_ok:
1894 # inject a magic exit code to signal that we had syntax error.
1895 return (RET_SYNTAX_ERROR,) + r[1:]
1896 return r
1897
1898 def _hghave(self, reqs):
1899 allreqs = b' '.join(reqs)
1900
1901 self._detectslow(reqs)
1902
1903 if allreqs in self._have:
1904 return self._have.get(allreqs)
1905
1906 # TODO do something smarter when all other uses of hghave are gone.
1907 cmd = b'%s -c "%s/hghave %s"'
1908 cmd %= (self._shell, RUNTEST_DIR_FORWARD_SLASH, allreqs)
1909 proc = Popen4(
1910 cmd,
1911 self._testtmp,
1912 0,
1913 self._getenv(),
1914 )
1915 stdout, stderr = proc.communicate()
1916 ret = proc.wait()
1917 if wifexited(ret):
1918 ret = os.WEXITSTATUS(ret)
1919 if ret == 2:
1920 msg = "hghave failure: %s"
1921 msg %= stdout.decode('utf-8').strip()
1922 self.raise_error(msg)
1923
1924 if ret != 0:
1925 self._have[allreqs] = (False, stdout)
1926 return False, stdout
1927
1928 self._have[allreqs] = (True, None)
1929 return True, None
1930
1931 def _detectslow(self, reqs):
1932 """update the timeout of slow test when appropriate"""
1933 if b'slow' in reqs:
1934 self._timeout = self._slowtimeout
1935
1936 def _iftest(self, args):
1937 # implements "#if"
1938 reqs = []
1939 for arg in args:
1940 if arg.startswith(b'no-') and arg[3:] in self._allcases:
1941 if arg[3:] in self._case:
1942 return False
1943 elif arg in self._allcases:
1944 if arg not in self._case:
1945 return False
1946 else:
1947 reqs.append(arg)
1948 self._detectslow(reqs)
1949 return self._hghave(reqs)[0]
1950
1951 def _parsetest(self, lines):
1952 # We generate a shell script which outputs unique markers to line
1953 # up script results with our source. These markers include input
1954 # line number and the last return code.
1955 salt = b"SALT%d" % time.time()
1956
1957 def addsalt(line, inpython):
1958 if inpython:
1959 script.append(b'%s %d 0\n' % (salt, line))
1960 else:
1961 script.append(b'echo %s %d $?\n' % (salt, line))
1962
1963 activetrace = []
1964 session = str(uuid.uuid4()).encode('ascii')
1965 hgcatapult = os.getenv('HGTESTCATAPULTSERVERPIPE') or os.getenv(
1966 'HGCATAPULTSERVERPIPE'
1967 )
1968
1969 def toggletrace(cmd=None):
1970 if not hgcatapult or hgcatapult == os.devnull:
1971 return
1972
1973 if activetrace:
1974 script.append(
1975 b'echo END %s %s >> "$HGTESTCATAPULTSERVERPIPE"\n'
1976 % (session, activetrace[0])
1977 )
1978 if cmd is None:
1979 return
1980
1981 if isinstance(cmd, str):
1982 quoted = shellquote(cmd.strip())
1983 else:
1984 quoted = shellquote(cmd.strip().decode('utf8')).encode('utf8')
1985 quoted = quoted.replace(b'\\', b'\\\\')
1986 script.append(
1987 b'echo START %s %s >> "$HGTESTCATAPULTSERVERPIPE"\n'
1988 % (session, quoted)
1989 )
1990 activetrace[0:] = [quoted]
1991
1992 script = []
1993
1994 # After we run the shell script, we re-unify the script output
1995 # with non-active parts of the source, with synchronization by our
1996 # SALT line number markers. The after table contains the non-active
1997 # components, ordered by line number.
1998 after = {}
1999
2000 # Expected shell script output.
2001 expected = {}
2002
2003 pos = prepos = -1
2004
2005 condition_issues = 0
2006
2007 # The current stack of conditionnal section.
2008 # Each relevant conditionnal section can have the following value:
2009 # - True: we should run this block
2010 # - False: we should skip this block
2011 # - None: The parent block is skipped,
2012 # (no branch of this one will ever run)
2013 condition_stack = []
2014
2015 def run_line():
2016 """return True if the current line should be run"""
2017 if not condition_stack:
2018 return True
2019 return bool(condition_stack[-1])
2020
2021 def push_conditional_block(should_run):
2022 """Push a new conditional context, with its initial state
2023
2024 i.e. entry a #if block"""
2025 if not run_line():
2026 condition_stack.append(None)
2027 else:
2028 condition_stack.append(should_run)
2029
2030 def flip_conditional():
2031 """reverse the current condition state
2032
2033 i.e. enter a #else
2034 """
2035 assert condition_stack
2036 if condition_stack[-1] is not None:
2037 condition_stack[-1] = not condition_stack[-1]
2038
2039 def pop_conditional():
2040 """exit the current skipping context
2041
2042 i.e. reach the #endif"""
2043 assert condition_stack
2044 condition_stack.pop()
2045
2046 # We keep track of whether or not we're in a Python block so we
2047 # can generate the surrounding doctest magic.
2048 inpython = False
2049
2050 if self._debug:
2051 script.append(b'set -x\n')
2052 if os.getenv('MSYSTEM'):
2053 script.append(b'alias pwd="pwd -W"\n')
2054
2055 if hgcatapult and hgcatapult != os.devnull:
2056 hgcatapult = hgcatapult.encode('utf8')
2057 cataname = self.name.encode('utf8')
2058
2059 # Kludge: use a while loop to keep the pipe from getting
2060 # closed by our echo commands. The still-running file gets
2061 # reaped at the end of the script, which causes the while
2062 # loop to exit and closes the pipe. Sigh.
2063 script.append(
2064 b'rtendtracing() {\n'
2065 b' echo END %(session)s %(name)s >> %(catapult)s\n'
2066 b' rm -f "$TESTTMP/.still-running"\n'
2067 b'}\n'
2068 b'trap "rtendtracing" 0\n'
2069 b'touch "$TESTTMP/.still-running"\n'
2070 b'while [ -f "$TESTTMP/.still-running" ]; do sleep 1; done '
2071 b'> %(catapult)s &\n'
2072 b'HGCATAPULTSESSION=%(session)s ; export HGCATAPULTSESSION\n'
2073 b'echo START %(session)s %(name)s >> %(catapult)s\n'
2074 % {
2075 b'name': cataname,
2076 b'session': session,
2077 b'catapult': hgcatapult,
2078 }
2079 )
2080
2081 if self._case:
2082 casestr = b'#'.join(self._case)
2083 if isinstance(casestr, str):
2084 quoted = shellquote(casestr)
2085 else:
2086 quoted = shellquote(casestr.decode('utf8')).encode('utf8')
2087 script.append(b'TESTCASE=%s\n' % quoted)
2088 script.append(b'export TESTCASE\n')
2089
2090 n = 0
2091 for n, l in enumerate(lines):
2092 if not l.endswith(b'\n'):
2093 l += b'\n'
2094 if l.startswith(b'#require'):
2095 lsplit = l.split()
2096 if len(lsplit) < 2 or lsplit[0] != b'#require':
2097 after.setdefault(pos, []).append(
2098 b' !!! invalid #require\n'
2099 )
2100 if run_line():
2101 haveresult, message = self._hghave(lsplit[1:])
2102 if not haveresult:
2103 script = [b'echo "%s"\nexit 80\n' % message]
2104 break
2105 after.setdefault(pos, []).append(l)
2106 elif l.startswith(b'#if'):
2107 lsplit = l.split()
2108 if len(lsplit) < 2 or lsplit[0] != b'#if':
2109 after.setdefault(pos, []).append(b' !!! invalid #if\n')
2110 push_conditional_block(self._iftest(lsplit[1:]))
2111 after.setdefault(pos, []).append(l)
2112 elif l.startswith(b'#else'):
2113 if not condition_stack:
2114 after.setdefault(pos, []).append(b' !!! missing #if\n')
2115 condition_issues += 1
2116 flip_conditional()
2117 after.setdefault(pos, []).append(l)
2118 elif l.startswith(b'#endif'):
2119 if not condition_stack:
2120 after.setdefault(pos, []).append(b' !!! missing #if\n')
2121 condition_issues += 1
2122 pop_conditional()
2123 after.setdefault(pos, []).append(l)
2124 elif not run_line():
2125 after.setdefault(pos, []).append(l)
2126 elif l.startswith(b' >>> '): # python inlines
2127 after.setdefault(pos, []).append(l)
2128 prepos = pos
2129 pos = n
2130 if not inpython:
2131 # We've just entered a Python block. Add the header.
2132 inpython = True
2133 addsalt(prepos, False) # Make sure we report the exit code.
2134 pyh = b'"%s" %s/testlib/heredoctest.py <<EOF\n'
2135 pyh %= (self._pythonb, RUNTEST_DIR_FORWARD_SLASH)
2136 script.append(pyh)
2137 addsalt(n, True)
2138 script.append(l[2:])
2139 elif l.startswith(b' ... '): # python inlines
2140 after.setdefault(prepos, []).append(l)
2141 script.append(l[2:])
2142 elif l.startswith(b' $ '): # commands
2143 if inpython:
2144 script.append(b'EOF\n')
2145 inpython = False
2146 after.setdefault(pos, []).append(l)
2147 prepos = pos
2148 pos = n
2149 addsalt(n, False)
2150 rawcmd = l[4:]
2151 cmd = rawcmd.split()
2152 toggletrace(rawcmd)
2153 if len(cmd) == 2 and cmd[0] == b'cd':
2154 rawcmd = b'cd %s || exit 1\n' % cmd[1]
2155 script.append(rawcmd)
2156 elif l.startswith(b' > '): # continuations
2157 after.setdefault(prepos, []).append(l)
2158 script.append(l[4:])
2159 elif l.startswith(b' '): # results
2160 # Queue up a list of expected results.
2161 expected.setdefault(pos, []).append(l[2:])
2162 else:
2163 if inpython:
2164 script.append(b'EOF\n')
2165 inpython = False
2166 # Non-command/result. Queue up for merged output.
2167 after.setdefault(pos, []).append(l)
2168
2169 if inpython:
2170 script.append(b'EOF\n')
2171 if condition_stack:
2172 after.setdefault(pos, []).append(b' !!! missing #endif\n')
2173 condition_issues += 1
2174 addsalt(n + 1, False)
2175 # Need to end any current per-command trace
2176 if activetrace:
2177 toggletrace()
2178 return salt, script, after, expected, condition_issues == 0
2179
2180 def _processoutput(self, exitcode, output, salt, after, expected):
2181 # Merge the script output back into a unified test.
2182 warnonly = WARN_UNDEFINED # 1: not yet; 2: yes; 3: for sure not
2183 if exitcode != 0:
2184 warnonly = WARN_NO
2185
2186 pos = -1
2187 postout = []
2188 for out_rawline in output:
2189 out_line, cmd_line = out_rawline, None
2190 if salt in out_rawline:
2191 out_line, cmd_line = out_rawline.split(salt, 1)
2192
2193 pos, postout, warnonly = self._process_out_line(
2194 out_line, pos, postout, expected, warnonly
2195 )
2196 pos, postout = self._process_cmd_line(cmd_line, pos, postout, after)
2197
2198 if pos in after:
2199 postout += after.pop(pos)
2200
2201 if warnonly == WARN_YES:
2202 exitcode = False # Set exitcode to warned.
2203
2204 return exitcode, postout
2205
2206 def _process_out_line(self, out_line, pos, postout, expected, warnonly):
2207 while out_line:
2208 if not out_line.endswith(b'\n'):
2209 out_line += b' (no-eol)\n'
2210
2211 # Find the expected output at the current position.
2212 els = [None]
2213 if expected.get(pos, None):
2214 els = expected[pos]
2215
2216 optional = []
2217 for i, el in enumerate(els):
2218 r = False
2219 if el:
2220 r, exact = self.linematch(el, out_line)
2221 if isinstance(r, str):
2222 if r == '-glob':
2223 out_line = ''.join(el.rsplit(' (glob)', 1))
2224 r = '' # Warn only this line.
2225 elif r == "retry":
2226 postout.append(b' ' + el)
2227 else:
2228 log('\ninfo, unknown linematch result: %r\n' % r)
2229 r = False
2230 if r:
2231 els.pop(i)
2232 break
2233 if el:
2234 if isoptional(el):
2235 optional.append(i)
2236 else:
2237 m = optline.match(el)
2238 if m:
2239 conditions = [c for c in m.group(2).split(b' ')]
2240
2241 if not self._iftest(conditions):
2242 optional.append(i)
2243 if exact:
2244 # Don't allow line to be matches against a later
2245 # line in the output
2246 els.pop(i)
2247 break
2248
2249 if r:
2250 if r == "retry":
2251 continue
2252 # clean up any optional leftovers
2253 for i in optional:
2254 postout.append(b' ' + els[i])
2255 for i in reversed(optional):
2256 del els[i]
2257 postout.append(b' ' + el)
2258 else:
2259 if self.NEEDESCAPE(out_line):
2260 out_line = TTest._stringescape(
2261 b'%s (esc)\n' % out_line.rstrip(b'\n')
2262 )
2263 postout.append(b' ' + out_line) # Let diff deal with it.
2264 if r != '': # If line failed.
2265 warnonly = WARN_NO
2266 elif warnonly == WARN_UNDEFINED:
2267 warnonly = WARN_YES
2268 break
2269 else:
2270 # clean up any optional leftovers
2271 while expected.get(pos, None):
2272 el = expected[pos].pop(0)
2273 if el:
2274 if not isoptional(el):
2275 m = optline.match(el)
2276 if m:
2277 conditions = [c for c in m.group(2).split(b' ')]
2278
2279 if self._iftest(conditions):
2280 # Don't append as optional line
2281 continue
2282 else:
2283 continue
2284 postout.append(b' ' + el)
2285 return pos, postout, warnonly
2286
2287 def _process_cmd_line(self, cmd_line, pos, postout, after):
2288 """process a "command" part of a line from unified test output"""
2289 if cmd_line:
2290 # Add on last return code.
2291 ret = int(cmd_line.split()[1])
2292 if ret != 0:
2293 postout.append(b' [%d]\n' % ret)
2294 if pos in after:
2295 # Merge in non-active test bits.
2296 postout += after.pop(pos)
2297 pos = int(cmd_line.split()[0])
2298 return pos, postout
2299
2300 @staticmethod
2301 def rematch(el, l):
2302 try:
2303 # parse any flags at the beginning of the regex. Only 'i' is
2304 # supported right now, but this should be easy to extend.
2305 flags, el = re.match(br'^(\(\?i\))?(.*)', el).groups()[0:2]
2306 flags = flags or b''
2307 el = flags + b'(?:' + el + b')'
2308 # use \Z to ensure that the regex matches to the end of the string
2309 if WINDOWS:
2310 return re.match(el + br'\r?\n\Z', l)
2311 return re.match(el + br'\n\Z', l)
2312 except re.error:
2313 # el is an invalid regex
2314 return False
2315
2316 @staticmethod
2317 def globmatch(el, l):
2318 # The only supported special characters are * and ? plus / which also
2319 # matches \ on windows. Escaping of these characters is supported.
2320 if el + b'\n' == l:
2321 if os.altsep:
2322 # matching on "/" is not needed for this line
2323 for pat in checkcodeglobpats:
2324 if pat.match(el):
2325 return True
2326 return b'-glob'
2327 return True
2328 el = el.replace(b'$LOCALIP', b'*')
2329 i, n = 0, len(el)
2330 res = b''
2331 while i < n:
2332 c = el[i : i + 1]
2333 i += 1
2334 if c == b'\\' and i < n and el[i : i + 1] in b'*?\\/':
2335 res += el[i - 1 : i + 1]
2336 i += 1
2337 elif c == b'*':
2338 res += b'.*'
2339 elif c == b'?':
2340 res += b'.'
2341 elif c == b'/' and os.altsep:
2342 res += b'[/\\\\]'
2343 else:
2344 res += re.escape(c)
2345 return TTest.rematch(res, l)
2346
2347 def linematch(self, el, l):
2348 if el == l: # perfect match (fast)
2349 return True, True
2350 retry = False
2351 if isoptional(el):
2352 retry = "retry"
2353 el = el[: -len(MARK_OPTIONAL)] + b"\n"
2354 else:
2355 m = optline.match(el)
2356 if m:
2357 conditions = [c for c in m.group(2).split(b' ')]
2358
2359 el = m.group(1) + b"\n"
2360 if not self._iftest(conditions):
2361 # listed feature missing, should not match
2362 return "retry", False
2363
2364 if el.endswith(b" (esc)\n"):
2365 el = el[:-7].decode('unicode_escape') + '\n'
2366 el = el.encode('latin-1')
2367 if el == l or WINDOWS and el[:-1] + b'\r\n' == l:
2368 return True, True
2369 if el.endswith(b" (re)\n"):
2370 return (TTest.rematch(el[:-6], l) or retry), False
2371 if el.endswith(b" (glob)\n"):
2372 # ignore '(glob)' added to l by 'replacements'
2373 if l.endswith(b" (glob)\n"):
2374 l = l[:-8] + b"\n"
2375 return (TTest.globmatch(el[:-8], l) or retry), False
2376 if os.altsep:
2377 _l = l.replace(b'\\', b'/')
2378 if el == _l or WINDOWS and el[:-1] + b'\r\n' == _l:
2379 return True, True
2380 return retry, True
2381
2382 @staticmethod
2383 def parsehghaveoutput(lines):
2384 """Parse hghave log lines.
2385
2386 Return tuple of lists (missing, failed):
2387 * the missing/unknown features
2388 * the features for which existence check failed"""
2389 missing = []
2390 failed = []
2391 for line in lines:
2392 if line.startswith(TTest.SKIPPED_PREFIX):
2393 line = line.splitlines()[0]
2394 missing.append(_bytes2sys(line[len(TTest.SKIPPED_PREFIX) :]))
2395 elif line.startswith(TTest.FAILED_PREFIX):
2396 line = line.splitlines()[0]
2397 failed.append(_bytes2sys(line[len(TTest.FAILED_PREFIX) :]))
2398
2399 return missing, failed
2400
2401 @staticmethod
2402 def _escapef(m):
2403 return TTest.ESCAPEMAP[m.group(0)]
2404
2405 @staticmethod
2406 def _stringescape(s):
2407 return TTest.ESCAPESUB(TTest._escapef, s)
2408
2409
2410 iolock = threading.RLock()
2411 firstlock = threading.RLock()
2412 firsterror = False
2413
2414 base_class = unittest.TextTestResult
2415
2416
2417 class TestResult(base_class):
2418 """Holds results when executing via unittest."""
2419
2420 def __init__(self, options, *args, **kwargs):
2421 super().__init__(*args, **kwargs)
2422
2423 self._options = options
2424
2425 # unittest.TestResult didn't have skipped until 2.7. We need to
2426 # polyfill it.
2427 self.skipped = []
2428
2429 # We have a custom "ignored" result that isn't present in any Python
2430 # unittest implementation. It is very similar to skipped. It may make
2431 # sense to map it into skip some day.
2432 self.ignored = []
2433
2434 self._dot_printed = 0
2435 self.times = []
2436 self._firststarttime = None
2437 # Data stored for the benefit of generating xunit reports.
2438 self.successes = []
2439 self.faildata = {}
2440
2441 if options.color == 'auto':
2442 isatty = self.stream.isatty()
2443 # For some reason, redirecting stdout on Windows disables the ANSI
2444 # color processing of stderr, which is what is used to print the
2445 # output. Therefore, both must be tty on Windows to enable color.
2446 if WINDOWS:
2447 isatty = isatty and sys.stdout.isatty()
2448 self.color = pygmentspresent and isatty
2449 elif options.color == 'never':
2450 self.color = False
2451 else: # 'always', for testing purposes
2452 self.color = pygmentspresent
2453
2454 def _write_dot(self, progress):
2455 """write an item of the "dot" progress"""
2456 formated = highlight_progress(progress, self.color)
2457 self.stream.write(formated)
2458 self._dot_printed += 1
2459 if not self._dot_printed % 75:
2460 self.stream.write(f' [{self._dot_printed}]\n'.rjust(8))
2461 self.stream.flush()
2462
2463 def onStart(self, test):
2464 """Can be overriden by custom TestResult"""
2465
2466 def onEnd(self):
2467 """Can be overriden by custom TestResult"""
2468
2469 def addFailure(self, test, reason):
2470 self.failures.append((test, reason))
2471
2472 if self._options.first:
2473 self.stop()
2474 else:
2475 with iolock:
2476 if reason == "timed out":
2477 self._write_dot('t')
2478 else:
2479 if not self._options.nodiff:
2480 self.stream.write('\n')
2481 # Exclude the '\n' from highlighting to lex correctly
2482 formatted = 'ERROR: %s output changed\n' % test
2483 self.stream.write(highlightmsg(formatted, self.color))
2484 self._write_dot('!')
2485
2486 self.stream.flush()
2487
2488 def addSuccess(self, test):
2489 with iolock:
2490 # bypass the TextTestResult method as do deal with the output ourself
2491 super(base_class, self).addSuccess(test)
2492 if self.showAll:
2493 self._write_status(test, "ok")
2494 elif self.dots:
2495 self._write_dot('.')
2496 self.successes.append(test)
2497
2498 def addError(self, test, err=None, message=None):
2499 if message is not None:
2500 self.errors.append((test, message))
2501 else:
2502 assert err is not None
2503 super(base_class, self).addError(test, err)
2504 if self.showAll:
2505 self._write_status(test, "ERROR")
2506 elif self.dots:
2507 self._write_dot('E')
2508 if self._options.first:
2509 self.stop()
2510
2511 # Polyfill.
2512 def addSkip(self, test, reason):
2513 self.skipped.append((test, reason))
2514 with iolock:
2515 if self.showAll:
2516 self.stream.writeln('skipped %s' % reason)
2517 else:
2518 self._write_dot('s')
2519
2520 def addIgnore(self, test, reason):
2521 self.ignored.append((test, reason))
2522 with iolock:
2523 if self.showAll:
2524 self.stream.writeln('ignored %s' % reason)
2525 else:
2526 if reason not in ('not retesting', "doesn't match keyword"):
2527 self._write_dot('i')
2528 else:
2529 self.testsRun += 1
2530
2531 def addOutputMismatch(self, test, ret, got, expected):
2532 """Record a mismatch in test output for a particular test."""
2533 if self.shouldStop or firsterror:
2534 # don't print, some other test case already failed and
2535 # printed, we're just stale and probably failed due to our
2536 # temp dir getting cleaned up.
2537 return
2538
2539 accepted = False
2540 lines = []
2541
2542 with iolock:
2543 if self._options.nodiff:
2544 pass
2545 elif self._options.view:
2546 v = self._options.view
2547 subprocess.call(
2548 r'"%s" "%s" "%s"'
2549 % (v, _bytes2sys(test.refpath), _bytes2sys(test.errpath)),
2550 shell=True,
2551 )
2552 else:
2553 servefail, lines = getdiff(
2554 expected, got, test.refpath, test.errpath
2555 )
2556 self.stream.write('\n')
2557 for line in lines:
2558 line = highlightdiff(line, self.color)
2559 self.stream.flush()
2560 self.stream.buffer.write(line)
2561 self.stream.buffer.flush()
2562
2563 if servefail:
2564 raise test.failureException(
2565 'server failed to start (HGPORT=%s)' % test._startport
2566 )
2567
2568 # handle interactive prompt without releasing iolock
2569 if self._options.interactive:
2570 if test.readrefout() != expected:
2571 self.stream.write(
2572 'Reference output has changed (run again to prompt '
2573 'changes)'
2574 )
2575 else:
2576 self.stream.write('Accept this change? [y/N] ')
2577 self.stream.flush()
2578 answer = sys.stdin.readline().strip()
2579 if answer.lower() in ('y', 'yes'):
2580 if test.path.endswith(b'.t'):
2581 rename(test.errpath, test.path)
2582 else:
2583 rename(test.errpath, b'%s.out' % test.path)
2584 accepted = True
2585 if not accepted:
2586 self.faildata[test.name] = b''.join(lines)
2587
2588 return accepted
2589
2590 def startTest(self, test):
2591 super().startTest(test)
2592
2593 # os.times module computes the user time and system time spent by
2594 # child's processes along with real elapsed time taken by a process.
2595 # This module has one limitation. It can only work for Linux user
2596 # and not for Windows. Hence why we fall back to another function
2597 # for wall time calculations.
2598 test.started_times = os.times()
2599 # TODO use a monotonic clock once support for Python 2.7 is dropped.
2600 test.started_time = time.time()
2601 if self._firststarttime is None: # thread racy but irrelevant
2602 self._firststarttime = test.started_time
2603
2604 def stopTest(self, test, interrupted=False):
2605 super().stopTest(test)
2606
2607 test.stopped_times = os.times()
2608 stopped_time = time.time()
2609
2610 starttime = test.started_times
2611 endtime = test.stopped_times
2612 origin = self._firststarttime
2613 self.times.append(
2614 (
2615 test.name,
2616 endtime[2] - starttime[2], # user space CPU time
2617 endtime[3] - starttime[3], # sys space CPU time
2618 stopped_time - test.started_time, # real time
2619 test.started_time - origin, # start date in run context
2620 stopped_time - origin, # end date in run context
2621 )
2622 )
2623
2624 if interrupted:
2625 with iolock:
2626 self.stream.writeln(
2627 'INTERRUPTED: %s (after %d seconds)'
2628 % (test.name, self.times[-1][3])
2629 )
2630
2631
2632 def getTestResult():
2633 """
2634 Returns the relevant test result
2635 """
2636 if "CUSTOM_TEST_RESULT" in os.environ:
2637 testresultmodule = __import__(os.environ["CUSTOM_TEST_RESULT"])
2638 return testresultmodule.TestResult
2639 else:
2640 return TestResult
2641
2642
2643 class TestSuite(unittest.TestSuite):
2644 """Custom unittest TestSuite that knows how to execute Mercurial tests."""
2645
2646 def __init__(
2647 self,
2648 testdir,
2649 jobs=1,
2650 whitelist=None,
2651 blacklist=None,
2652 keywords=None,
2653 loop=False,
2654 runs_per_test=1,
2655 loadtest=None,
2656 showchannels=False,
2657 tail_report=False,
2658 *args,
2659 **kwargs,
2660 ):
2661 """Create a new instance that can run tests with a configuration.
2662
2663 testdir specifies the directory where tests are executed from. This
2664 is typically the ``tests`` directory from Mercurial's source
2665 repository.
2666
2667 jobs specifies the number of jobs to run concurrently. Each test
2668 executes on its own thread. Tests actually spawn new processes, so
2669 state mutation should not be an issue.
2670
2671 If there is only one job, it will use the main thread.
2672
2673 whitelist and blacklist denote tests that have been whitelisted and
2674 blacklisted, respectively. These arguments don't belong in TestSuite.
2675 Instead, whitelist and blacklist should be handled by the thing that
2676 populates the TestSuite with tests. They are present to preserve
2677 backwards compatible behavior which reports skipped tests as part
2678 of the results.
2679
2680 keywords denotes key words that will be used to filter which tests
2681 to execute. This arguably belongs outside of TestSuite.
2682
2683 loop denotes whether to loop over tests forever.
2684 """
2685 super().__init__(*args, **kwargs)
2686
2687 self._jobs = jobs
2688 self._whitelist = whitelist
2689 self._blacklist = blacklist
2690 self._keywords = keywords
2691 self._loop = loop
2692 self._runs_per_test = runs_per_test
2693 self._loadtest = loadtest
2694 self._showchannels = showchannels
2695 self._tail_report = tail_report
2696
2697 def run(self, result):
2698 # We have a number of filters that need to be applied. We do this
2699 # here instead of inside Test because it makes the running logic for
2700 # Test simpler.
2701 tests = []
2702 num_tests = [0]
2703 for test in self._tests:
2704
2705 def get():
2706 num_tests[0] += 1
2707 if getattr(test, 'should_reload', False):
2708 return self._loadtest(test, num_tests[0])
2709 return test
2710
2711 if not os.path.exists(test.path):
2712 result.addSkip(test, "Doesn't exist")
2713 continue
2714
2715 is_whitelisted = self._whitelist and (
2716 test.relpath in self._whitelist or test.bname in self._whitelist
2717 )
2718 if not is_whitelisted:
2719 is_blacklisted = self._blacklist and (
2720 test.relpath in self._blacklist
2721 or test.bname in self._blacklist
2722 )
2723 if is_blacklisted:
2724 result.addSkip(test, 'blacklisted')
2725 continue
2726 if self._keywords:
2727 with open(test.path, 'rb') as f:
2728 t = f.read().lower() + test.bname.lower()
2729 ignored = False
2730 for k in self._keywords.lower().split():
2731 if k not in t:
2732 result.addIgnore(test, "doesn't match keyword")
2733 ignored = True
2734 break
2735
2736 if ignored:
2737 continue
2738 for _ in range(self._runs_per_test):
2739 tests.append(get())
2740
2741 runtests = list(tests)
2742 done = queue.Queue()
2743 running = 0
2744
2745 channels_lock = threading.Lock()
2746 channels = [""] * self._jobs
2747
2748 def job(test, result):
2749 with channels_lock:
2750 for n, v in enumerate(channels):
2751 if not v:
2752 channel = n
2753 break
2754 else:
2755 raise ValueError('Could not find output channel')
2756 channels[channel] = "=" + test.name[5:].split(".")[0]
2757
2758 r = (None, test, None)
2759 try:
2760 test(result)
2761 except KeyboardInterrupt:
2762 pass
2763 except: # re-raises
2764 r = ('!', test, 'run-test raised an error, see traceback')
2765 raise
2766 finally:
2767 try:
2768 channels[channel] = ''
2769 except IndexError:
2770 pass
2771 done.put(r)
2772
2773 def stat():
2774 count = 0
2775 while channels:
2776 d = '\n%03s ' % count
2777 for n, v in enumerate(channels):
2778 if v:
2779 d += v[0]
2780 channels[n] = v[1:] or '.'
2781 else:
2782 d += ' '
2783 d += ' '
2784 with iolock:
2785 sys.stdout.write(d + ' ')
2786 sys.stdout.flush()
2787 for x in range(10):
2788 if channels:
2789 time.sleep(0.1)
2790 count += 1
2791
2792 stoppedearly = False
2793
2794 if self._showchannels:
2795 statthread = threading.Thread(target=stat, name="stat")
2796 statthread.start()
2797
2798 start_time = time.monotonic()
2799 tail_data = []
2800 try:
2801 while tests or running:
2802 finished = None
2803 if not done.empty() or running == self._jobs or not tests:
2804 try:
2805 _, finished, _ = done.get(True, 1)
2806 running -= 1
2807 if result and result.shouldStop:
2808 stoppedearly = True
2809 break
2810 except queue.Empty:
2811 continue
2812 if tests and not running == self._jobs:
2813 test = tests.pop(0)
2814 if self._loop:
2815 if getattr(test, 'should_reload', False):
2816 num_tests[0] += 1
2817 tests.append(self._loadtest(test, num_tests[0]))
2818 else:
2819 tests.append(test)
2820 if self._jobs == 1:
2821 job(test, result)
2822 else:
2823 t = threading.Thread(
2824 target=job, name=test.name, args=(test, result)
2825 )
2826 t.start()
2827 running += 1
2828 if finished is not None and running < self._jobs:
2829 tail_data.append((finished, running, time.monotonic()))
2830
2831 # If we stop early we still need to wait on started tests to
2832 # finish. Otherwise, there is a race between the test completing
2833 # and the test's cleanup code running. This could result in the
2834 # test reporting incorrect.
2835 if stoppedearly:
2836 while running:
2837 try:
2838 done.get(True, 1)
2839 running -= 1
2840 except queue.Empty:
2841 continue
2842 except KeyboardInterrupt:
2843 for test in runtests:
2844 test.abort()
2845
2846 if self._tail_report:
2847 with iolock:
2848 sys.stdout.write('\n### test tail-report ###\n')
2849 sys.stdout.flush()
2850 channels = []
2851 for test, remaining, end_time in tail_data:
2852 m = "[% 13.6f s] %d tests still running; finished %s\n"
2853 m %= (end_time - start_time, remaining, test)
2854 sys.stdout.write(m)
2855 sys.stdout.flush()
2856
2857 return result
2858
2859
2860 # Save the most recent 5 wall-clock runtimes of each test to a
2861 # human-readable text file named .testtimes. Tests are sorted
2862 # alphabetically, while times for each test are listed from oldest to
2863 # newest.
2864
2865
2866 def loadtimes(outputdir):
2867 times = []
2868 try:
2869 with open(os.path.join(outputdir, b'.testtimes'), 'br') as fp:
2870 for line in fp:
2871 m = re.match(b'(.*?) ([0-9. ]+)', line)
2872 times.append(
2873 (m.group(1), [float(t) for t in m.group(2).split()])
2874 )
2875 except FileNotFoundError:
2876 pass
2877 return times
2878
2879
2880 def savetimes(outputdir, result):
2881 saved = dict(loadtimes(outputdir))
2882 maxruns = 5
2883 skipped = {str(t[0]) for t in result.skipped}
2884 new_times = collections.defaultdict(list)
2885 for tdata in result.times:
2886 test_full, real = _sys2bytes(tdata[0]), tdata[3]
2887 test = test_full.split(b'#', 1)[0]
2888 if test not in skipped:
2889 new_times[test].append(real)
2890
2891 for test, new in new_times.items():
2892 # keep the slowest variant last
2893 new.sort()
2894 all_times = (saved.get(test, []) + new)[-maxruns:]
2895 saved[test] = all_times
2896
2897 fd, tmpname = tempfile.mkstemp(
2898 prefix=b'.testtimes', dir=outputdir, text=True
2899 )
2900 with os.fdopen(fd, 'wb') as fp:
2901 for name, ts in sorted(saved.items()):
2902 times = b' '.join([b'%.3f' % (t,) for t in ts])
2903 fp.write(b'%s %s\n' % (name, times))
2904 timepath = os.path.join(outputdir, b'.testtimes')
2905 try:
2906 os.unlink(timepath)
2907 except OSError:
2908 pass
2909 try:
2910 os.rename(tmpname, timepath)
2911 except OSError:
2912 pass
2913
2914
2915 def get_site_packages_dir(python_exe):
2916 return subprocess.run(
2917 [
2918 python_exe,
2919 "-c",
2920 "import sys; print([p for p in sys.path if p.startswith(sys.prefix) and p.endswith('site-packages')][0])",
2921 ],
2922 check=True,
2923 capture_output=True,
2924 ).stdout.strip()
2925
2926
2927 class TextTestRunner(unittest.TextTestRunner):
2928 """Custom unittest test runner that uses appropriate settings."""
2929
2930 def __init__(self, runner, *args, **kwargs):
2931 super().__init__(*args, **kwargs)
2932
2933 self._runner = runner
2934
2935 self._result = getTestResult()(
2936 self._runner.options, self.stream, self.descriptions, self.verbosity
2937 )
2938
2939 def listtests(self, test):
2940 test = sorted(test, key=lambda t: t.name)
2941
2942 self._result.onStart(test)
2943
2944 for t in test:
2945 print(t.name)
2946 self._result.addSuccess(t)
2947
2948 if self._runner.options.xunit:
2949 with open(self._runner.options.xunit, "wb") as xuf:
2950 self._writexunit(self._result, xuf)
2951
2952 if self._runner.options.json:
2953 jsonpath = os.path.join(self._runner._outputdir, b'report.json')
2954 with open(jsonpath, 'w') as fp:
2955 self._writejson(self._result, fp)
2956
2957 return self._result
2958
2959 def run(self, test):
2960 self._result.onStart(test)
2961 test(self._result)
2962
2963 test_count = self._result.testsRun
2964 failed = len(self._result.failures)
2965 skipped = len(self._result.skipped)
2966 ignored = len(self._result.ignored)
2967 error_count = len(self._result.errors)
2968
2969 with iolock:
2970 if not self._runner.options.tail_report:
2971 self.stream.writeln('')
2972
2973 if not self._runner.options.noskips:
2974 for test, msg in sorted(
2975 self._result.skipped, key=lambda s: s[0].name
2976 ):
2977 formatted = 'Skipped %s: %s\n' % (test.name, msg)
2978 msg = highlightmsg(formatted, self._result.color)
2979 self.stream.write(msg)
2980 for test, msg in sorted(
2981 self._result.failures, key=lambda f: f[0].name
2982 ):
2983 formatted = 'Failed %s: %s\n' % (test.name, msg)
2984 self.stream.write(highlightmsg(formatted, self._result.color))
2985 for test, msg in sorted(
2986 self._result.errors, key=lambda e: e[0].name
2987 ):
2988 self.stream.writeln('ERROR: %s: %s' % (test.name, msg))
2989
2990 if self._runner.options.xunit:
2991 with open(self._runner.options.xunit, "wb") as xuf:
2992 self._writexunit(self._result, xuf)
2993
2994 if self._runner.options.json:
2995 jsonpath = os.path.join(self._runner._outputdir, b'report.json')
2996 with open(jsonpath, 'w') as fp:
2997 self._writejson(self._result, fp)
2998
2999 self._runner._check_hg('Tested')
3000
3001 savetimes(self._runner._outputdir, self._result)
3002
3003 if error_count:
3004 msg = '# Ran %d tests, %d skipped, %d failed, %d errors.'
3005 msg %= (test_count, skipped + ignored, failed, error_count)
3006 else:
3007 msg = '# Ran %d tests, %d skipped, %d failed.'
3008 msg %= (test_count, skipped + ignored, failed)
3009
3010 self.stream.writeln(msg)
3011 if failed or error_count:
3012 self.stream.writeln(
3013 'python hash seed: %s' % os.environ['PYTHONHASHSEED']
3014 )
3015 if self._runner.options.time:
3016 self.printtimes(self._result.times)
3017
3018 if self._runner.options.exceptions:
3019 exceptions = aggregateexceptions(
3020 os.path.join(self._runner._outputdir, b'exceptions')
3021 )
3022
3023 self.stream.writeln('Exceptions Report:')
3024 self.stream.writeln(
3025 '%d total from %d frames'
3026 % (exceptions['total'], len(exceptions['exceptioncounts']))
3027 )
3028 combined = exceptions['combined']
3029 for key in sorted(combined, key=combined.get, reverse=True):
3030 frame, line, exc = key
3031 totalcount, testcount, leastcount, leasttest = combined[key]
3032
3033 self.stream.writeln(
3034 '%d (%d tests)\t%s: %s (%s - %d total)'
3035 % (
3036 totalcount,
3037 testcount,
3038 frame,
3039 exc,
3040 leasttest,
3041 leastcount,
3042 )
3043 )
3044
3045 self.stream.flush()
3046
3047 return self._result
3048
3049 def printtimes(self, times):
3050 # iolock held by run
3051 self.stream.writeln('# Producing time report')
3052 times.sort(key=lambda t: (t[3]))
3053 cols = '%7.3f %7.3f %7.3f %7.3f %7.3f %s'
3054 self.stream.writeln(
3055 '%-7s %-7s %-7s %-7s %-7s %s'
3056 % ('start', 'end', 'cuser', 'csys', 'real', 'Test')
3057 )
3058 for tdata in times:
3059 test = tdata[0]
3060 cuser, csys, real, start, end = tdata[1:6]
3061 self.stream.writeln(cols % (start, end, cuser, csys, real, test))
3062
3063 @staticmethod
3064 def _writexunit(result, outf):
3065 # See http://llg.cubic.org/docs/junit/ for a reference.
3066 timesd = {t[0]: t[3] for t in result.times}
3067 doc = minidom.Document()
3068 s = doc.createElement('testsuite')
3069 s.setAttribute('errors', "0") # TODO
3070 s.setAttribute('failures', str(len(result.failures)))
3071 s.setAttribute('name', 'run-tests')
3072 s.setAttribute(
3073 'skipped', str(len(result.skipped) + len(result.ignored))
3074 )
3075 s.setAttribute('tests', str(result.testsRun))
3076 doc.appendChild(s)
3077 for tc in result.successes:
3078 t = doc.createElement('testcase')
3079 t.setAttribute('name', tc.name)
3080 tctime = timesd.get(tc.name)
3081 if tctime is not None:
3082 t.setAttribute('time', '%.3f' % tctime)
3083 s.appendChild(t)
3084 for tc, err in sorted(result.faildata.items()):
3085 t = doc.createElement('testcase')
3086 t.setAttribute('name', tc)
3087 tctime = timesd.get(tc)
3088 if tctime is not None:
3089 t.setAttribute('time', '%.3f' % tctime)
3090 # createCDATASection expects a unicode or it will
3091 # convert using default conversion rules, which will
3092 # fail if string isn't ASCII.
3093 err = cdatasafe(err).decode('utf-8', 'replace')
3094 cd = doc.createCDATASection(err)
3095 # Use 'failure' here instead of 'error' to match errors = 0,
3096 # failures = len(result.failures) in the testsuite element.
3097 failelem = doc.createElement('failure')
3098 failelem.setAttribute('message', 'output changed')
3099 failelem.setAttribute('type', 'output-mismatch')
3100 failelem.appendChild(cd)
3101 t.appendChild(failelem)
3102 s.appendChild(t)
3103 for tc, message in result.skipped:
3104 # According to the schema, 'skipped' has no attributes. So store
3105 # the skip message as a text node instead.
3106 t = doc.createElement('testcase')
3107 t.setAttribute('name', tc.name)
3108 binmessage = message.encode('utf-8')
3109 message = cdatasafe(binmessage).decode('utf-8', 'replace')
3110 cd = doc.createCDATASection(message)
3111 skipelem = doc.createElement('skipped')
3112 skipelem.appendChild(cd)
3113 t.appendChild(skipelem)
3114 s.appendChild(t)
3115 outf.write(doc.toprettyxml(indent=' ', encoding='utf-8'))
3116
3117 @staticmethod
3118 def _writejson(result, outf):
3119 timesd = {}
3120 for tdata in result.times:
3121 test = tdata[0]
3122 timesd[test] = tdata[1:]
3123
3124 outcome = {}
3125 groups = [
3126 ('success', ((tc, None) for tc in result.successes)),
3127 ('failure', result.failures),
3128 ('skip', result.skipped),
3129 ]
3130 for res, testcases in groups:
3131 for tc, __ in testcases:
3132 if tc.name in timesd:
3133 diff = result.faildata.get(tc.name, b'')
3134 try:
3135 diff = diff.decode('unicode_escape')
3136 except UnicodeDecodeError as e:
3137 diff = '%r decoding diff, sorry' % e
3138 tres = {
3139 'result': res,
3140 'time': ('%0.3f' % timesd[tc.name][2]),
3141 'cuser': ('%0.3f' % timesd[tc.name][0]),
3142 'csys': ('%0.3f' % timesd[tc.name][1]),
3143 'start': ('%0.3f' % timesd[tc.name][3]),
3144 'end': ('%0.3f' % timesd[tc.name][4]),
3145 'diff': diff,
3146 }
3147 else:
3148 # blacklisted test
3149 tres = {'result': res}
3150
3151 outcome[tc.name] = tres
3152 jsonout = json.dumps(
3153 outcome, sort_keys=True, indent=4, separators=(',', ': ')
3154 )
3155 outf.writelines(("testreport =", jsonout))
3156
3157
3158 def sorttests(testdescs, previoustimes, shuffle=False):
3159 """Do an in-place sort of tests."""
3160 if shuffle:
3161 random.shuffle(testdescs)
3162 return
3163
3164 if previoustimes:
3165
3166 def sortkey(f):
3167 f = f['path']
3168 if f in previoustimes:
3169 # Use most recent time as estimate
3170 return previoustimes[f][-1]
3171 else:
3172 # Default to a rather arbitrary value of 1 second for new tests
3173 return 1.0
3174
3175 else:
3176 # keywords for slow tests
3177 slow = {
3178 b'check': 100,
3179 b'contrib-perf': 200,
3180 b'corruption': 10,
3181 b'cvs': 10,
3182 b'gendoc': 100,
3183 b'hghave': 10,
3184 b'i18n': 10,
3185 b'largefiles-update': 10,
3186 b'merge-combination': 100,
3187 b'race': 10,
3188 b'run-tests': 10,
3189 b'sparse-revlog': 50,
3190 b'svn': 10,
3191 }
3192 perf = {}
3193
3194 def sortkey(f):
3195 # run largest tests first, as they tend to take the longest
3196 f = f['path']
3197 try:
3198 return perf[f]
3199 except KeyError:
3200 try:
3201 val = os.stat(f).st_size
3202 except FileNotFoundError:
3203 perf[f] = 1e9 # file does not exist, tell early
3204 return 1e9
3205 for kw, mul in slow.items():
3206 if kw in f:
3207 val *= mul
3208 if f.endswith(b'.py'):
3209 val /= 10.0
3210 perf[f] = val / 1000.0
3211 return perf[f]
3212
3213 testdescs.sort(key=sortkey, reverse=True)
3214
3215
3216 class TestRunner:
3217 """Holds context for executing tests.
3218
3219 Tests rely on a lot of state. This object holds it for them.
3220 """
3221
3222 # Programs required to run tests.
3223 REQUIREDTOOLS = [
3224 b'diff',
3225 b'grep',
3226 b'unzip',
3227 b'gunzip',
3228 b'bunzip2',
3229 b'sed',
3230 ]
3231
3232 # Maps file extensions to test class.
3233 TESTTYPES = [
3234 (b'.py', PythonTest),
3235 (b'.t', TTest),
3236 ]
3237
3238 def __init__(self):
3239 self.options = None
3240 self._hgroot = None
3241 self._testdir = None
3242 self._outputdir = None
3243 self._hgtmp = None
3244 self._installdir = None
3245 self._bindir = None
3246 # a place for run-tests.py to generate executable it needs
3247 self._custom_bin_dir = None
3248 self._pythondir = None
3249
3250 if sys.executable:
3251 self._python = sys.executable
3252 elif os.environ.get('PYTHONEXECUTABLE'):
3253 self._python = os.environ['PYTHONEXECUTABLE']
3254 elif os.environ.get('PYTHON'):
3255 self._python = os.environ['PYTHON']
3256 else:
3257 raise AssertionError('Could not find Python interpreter')
3258
3259 # True if we had to infer the pythondir from --with-hg
3260 self._pythondir_inferred = False
3261 self._coveragefile = None
3262 self._createdfiles = []
3263 self._hgcommand = None
3264 self._hgpath = None
3265 self._portoffset = 0
3266 self._ports = {}
3267
3268 @property
3269 def _pythonb(self):
3270 return _sys2bytes(self._python.replace('\\', '/'))
3271
3272 def run(self, args, parser=None):
3273 """Run the test suite."""
3274 oldmask = os.umask(0o22)
3275 try:
3276 parser = parser or getparser()
3277 options = parseargs(args, parser)
3278 tests = [_sys2bytes(a) for a in options.tests]
3279 if options.test_list is not None:
3280 for listfile in options.test_list:
3281 with open(listfile, 'rb') as f:
3282 tests.extend(t for t in f.read().splitlines() if t)
3283 self.options = options
3284
3285 self._checktools()
3286 testdescs = self.findtests(tests)
3287 if options.profile_runner:
3288 import statprof
3289
3290 statprof.start()
3291 result = self._run(
3292 testdescs,
3293 shard_index=options.shard_index,
3294 shard_total=options.shard_total,
3295 )
3296 if options.profile_runner:
3297 statprof.stop()
3298 statprof.display()
3299 return result
3300
3301 finally:
3302 os.umask(oldmask)
3303
3304 def _run(self, testdescs, shard_index=None, shard_total=None):
3305 testdir = getcwdb()
3306 # assume all tests in same folder for now
3307 if testdescs:
3308 pathname = os.path.dirname(testdescs[0]['path'])
3309 if pathname:
3310 testdir = os.path.join(testdir, pathname)
3311 self._testdir = osenvironb[b'TESTDIR'] = testdir
3312 osenvironb[b'TESTDIR_FORWARD_SLASH'] = osenvironb[b'TESTDIR'].replace(
3313 os.sep.encode('ascii'), b'/'
3314 )
3315
3316 if self.options.outputdir:
3317 self._outputdir = canonpath(_sys2bytes(self.options.outputdir))
3318 else:
3319 self._outputdir = getcwdb()
3320 if testdescs and pathname:
3321 self._outputdir = os.path.join(self._outputdir, pathname)
3322 previoustimes = {}
3323 if self.options.order_by_runtime:
3324 previoustimes = dict(loadtimes(self._outputdir))
3325 sorttests(testdescs, previoustimes, shuffle=self.options.random)
3326
3327 if 'PYTHONHASHSEED' not in os.environ:
3328 # use a random python hash seed all the time
3329 # we do the randomness ourself to know what seed is used
3330 os.environ['PYTHONHASHSEED'] = str(random.getrandbits(32))
3331
3332 # Rayon (Rust crate for multi-threading) will use all logical CPU cores
3333 # by default, causing thrashing on high-cpu-count systems.
3334 # Setting its limit to 3 during tests should still let us uncover
3335 # multi-threading bugs while keeping the thrashing reasonable.
3336 os.environ.setdefault("RAYON_NUM_THREADS", "3")
3337
3338 if self.options.tmpdir:
3339 self.options.keep_tmpdir = True
3340 tmpdir = _sys2bytes(self.options.tmpdir)
3341 if os.path.exists(tmpdir):
3342 # Meaning of tmpdir has changed since 1.3: we used to create
3343 # HGTMP inside tmpdir; now HGTMP is tmpdir. So fail if
3344 # tmpdir already exists.
3345 print("error: temp dir %r already exists" % tmpdir)
3346 return 1
3347
3348 os.makedirs(tmpdir)
3349 else:
3350 d = None
3351 if WINDOWS:
3352 # without this, we get the default temp dir location, but
3353 # in all lowercase, which causes troubles with paths (issue3490)
3354 d = osenvironb.get(b'TMP', None)
3355 tmpdir = tempfile.mkdtemp(b'', b'hgtests.', d)
3356
3357 self._hgtmp = osenvironb[b'HGTMP'] = os.path.realpath(tmpdir)
3358
3359 self._custom_bin_dir = os.path.join(self._hgtmp, b'custom-bin')
3360 os.makedirs(self._custom_bin_dir)
3361
3362 if self.options.with_hg:
3363 self._installdir = None
3364 whg = self.options.with_hg
3365 self._bindir = os.path.dirname(os.path.realpath(whg))
3366 assert isinstance(self._bindir, bytes)
3367 self._hgcommand = os.path.basename(whg)
3368
3369 normbin = os.path.normpath(os.path.abspath(whg))
3370 normbin = normbin.replace(_sys2bytes(os.sep), b'/')
3371
3372 # Other Python scripts in the test harness need to
3373 # `import mercurial`. If `hg` is a Python script, we assume
3374 # the Mercurial modules are relative to its path and tell the tests
3375 # to load Python modules from its directory.
3376 with open(whg, 'rb') as fh:
3377 first_line = fh.readline()
3378
3379 if re.match(b'#!.*python', first_line):
3380 python_exe = first_line.split(b"#!")[1].strip()
3381 try:
3382 self._pythondir = get_site_packages_dir(python_exe)
3383 except (FileNotFoundError, subprocess.CalledProcessError):
3384 self._pythondir = self._bindir
3385 if self.options.local:
3386 self._python = _bytes2sys(python_exe)
3387
3388 # If it looks like our in-repo Rust binary, use the source root.
3389 # This is a bit hacky. But rhg is still not supported outside the
3390 # source directory. So until it is, do the simple thing.
3391 elif re.search(b'/rust/target/[^/]+/hg', normbin):
3392 self._pythondir = os.path.dirname(self._testdir)
3393 # Fall back to the legacy behavior.
3394 else:
3395 self._pythondir = self._bindir
3396 self._pythondir_inferred = True
3397
3398 else:
3399 self._hgcommand = b'hg'
3400 self._installdir = os.path.join(self._hgtmp, b"install")
3401
3402 # create a virtual env where hg is going to be installed
3403 command_create_venv = [
3404 self._python,
3405 "-m",
3406 "venv",
3407 "--system-site-packages",
3408 "--without-pip",
3409 self._installdir,
3410 ]
3411 subprocess.run(command_create_venv, check=True)
3412
3413 bindir = b"Scripts" if WINDOWS else b"bin"
3414 python = b"python.exe" if WINDOWS else b"python"
3415
3416 self._bindir = os.path.join(self._installdir, bindir)
3417 self._python = _bytes2sys(os.path.join(self._bindir, python))
3418 self._pythondir = get_site_packages_dir(self._python)
3419
3420 # Force the use of hg.exe instead of relying on MSYS to recognize hg is
3421 # a python script and feed it to python.exe. Legacy stdio is force
3422 # enabled by hg.exe, and this is a more realistic way to launch hg
3423 # anyway.
3424 #
3425 # We do not do it when using wheels and they do not install a .exe.
3426 if WINDOWS and not self.options.wheel:
3427 # Currently no hg.exe without compiler, unless `run-tests.py` was
3428 # invoked without --pure, but then a *.t file invoked it again with
3429 # `--pure` (looking at you, test-hghave.t). In that case, don't
3430 # try to run hg.exe.bat.
3431 if self.options.pure and not self._hgcommand.endswith(b'.exe'):
3432 self._hgcommand += b'.bat'
3433 elif not self._hgcommand.endswith(b'.exe'):
3434 self._hgcommand += b'.exe'
3435
3436 self._real_hg = os.path.join(self._bindir, self._hgcommand)
3437 osenvironb[b'HGTEST_REAL_HG'] = self._real_hg
3438 # set CHGHG, then replace "hg" command by "chg"
3439 chgbindir = self._bindir
3440 if self.options.chg or self.options.with_chg:
3441 osenvironb[b'CHG_INSTALLED_AS_HG'] = b'1'
3442 osenvironb[b'CHGHG'] = self._real_hg
3443 else:
3444 # drop flag for hghave
3445 osenvironb.pop(b'CHG_INSTALLED_AS_HG', None)
3446 if self.options.chg:
3447 self._hgcommand = b'chg'
3448 elif self.options.with_chg:
3449 chgbindir = os.path.dirname(os.path.realpath(self.options.with_chg))
3450 self._hgcommand = os.path.basename(self.options.with_chg)
3451
3452 # configure fallback and replace "hg" command by "rhg"
3453 rhgbindir = self._bindir
3454 if self.options.rhg or self.options.with_rhg:
3455 # Affects hghave.py
3456 osenvironb[b'RHG_INSTALLED_AS_HG'] = b'1'
3457 # Affects configuration. Alternatives would be setting configuration through
3458 # `$HGRCPATH` but some tests override that, or changing `_hgcommand` to include
3459 # `--config` but that disrupts tests that print command lines and check expected
3460 # output.
3461 osenvironb[b'RHG_ON_UNSUPPORTED'] = b'fallback'
3462 osenvironb[b'RHG_FALLBACK_EXECUTABLE'] = self._real_hg
3463 else:
3464 # drop flag for hghave
3465 osenvironb.pop(b'RHG_INSTALLED_AS_HG', None)
3466 if self.options.rhg:
3467 self._hgcommand = b'rhg'
3468 elif self.options.with_rhg:
3469 rhgbindir = os.path.dirname(os.path.realpath(self.options.with_rhg))
3470 self._hgcommand = os.path.basename(self.options.with_rhg)
3471
3472 if self.options.pyoxidized:
3473 testdir = os.path.dirname(_sys2bytes(canonpath(sys.argv[0])))
3474 reporootdir = os.path.dirname(testdir)
3475 # XXX we should ideally install stuff instead of using the local build
3476
3477 exe = b'hg'
3478 triple = b''
3479
3480 if WINDOWS:
3481 triple = b'x86_64-pc-windows-msvc'
3482 exe = b'hg.exe'
3483 elif MACOS:
3484 # TODO: support Apple silicon too
3485 triple = b'x86_64-apple-darwin'
3486
3487 bin_path = b'build/pyoxidizer/%s/release/app/%s' % (triple, exe)
3488 full_path = os.path.join(reporootdir, bin_path)
3489 self._hgcommand = full_path
3490 # Affects hghave.py
3491 osenvironb[b'PYOXIDIZED_INSTALLED_AS_HG'] = b'1'
3492 else:
3493 osenvironb.pop(b'PYOXIDIZED_INSTALLED_AS_HG', None)
3494
3495 osenvironb[b"BINDIR"] = self._bindir
3496 osenvironb[b"PYTHON"] = self._pythonb
3497
3498 fileb = _sys2bytes(__file__)
3499 osenvironb[b'RUNTESTDIR'] = RUNTEST_DIR
3500 osenvironb[b'RUNTESTDIR_FORWARD_SLASH'] = RUNTEST_DIR_FORWARD_SLASH
3501 sepb = _sys2bytes(os.pathsep)
3502 path = [self._bindir, RUNTEST_DIR] + osenvironb[b"PATH"].split(sepb)
3503 if os.path.islink(__file__):
3504 # test helper will likely be at the end of the symlink
3505 realfile = os.path.realpath(fileb)
3506 realdir = os.path.abspath(os.path.dirname(realfile))
3507 path.insert(2, realdir)
3508 if chgbindir != self._bindir:
3509 path.insert(1, chgbindir)
3510 if rhgbindir != self._bindir:
3511 path.insert(1, rhgbindir)
3512 if self._testdir != RUNTEST_DIR:
3513 path = [self._testdir] + path
3514 path = [self._custom_bin_dir] + path
3515 osenvironb[b"PATH"] = sepb.join(path)
3516
3517 os.environ["HGTEST_BASE_HGMODULEPOLICY"] = os.environ.get(
3518 "HGMODULEPOLICY", ""
3519 )
3520
3521 if self.options.pure:
3522 os.environ["HGTEST_RUN_TESTS_PURE"] = "--pure"
3523 os.environ["HGMODULEPOLICY"] = "py"
3524 if self.options.rust:
3525 os.environ["HGMODULEPOLICY"] = "rust+c"
3526 if self.options.no_rust:
3527 current_policy = os.environ.get("HGMODULEPOLICY", "")
3528 if current_policy.startswith("rust+"):
3529 os.environ["HGMODULEPOLICY"] = current_policy[len("rust+") :]
3530
3531 if self.options.allow_slow_tests:
3532 os.environ["HGTEST_SLOW"] = "slow"
3533 elif 'HGTEST_SLOW' in os.environ:
3534 del os.environ['HGTEST_SLOW']
3535
3536 self._coveragefile = os.path.join(self._testdir, b'.coverage')
3537
3538 if self.options.exceptions:
3539 exceptionsdir = os.path.join(self._outputdir, b'exceptions')
3540 try:
3541 os.makedirs(exceptionsdir)
3542 except FileExistsError:
3543 pass
3544
3545 # Remove all existing exception reports.
3546 for f in os.listdir(exceptionsdir):
3547 os.unlink(os.path.join(exceptionsdir, f))
3548
3549 osenvironb[b'HGEXCEPTIONSDIR'] = exceptionsdir
3550 logexceptions = os.path.join(self._testdir, b'logexceptions.py')
3551 self.options.extra_config_opt.append(
3552 'extensions.logexceptions=%s' % logexceptions.decode('utf-8')
3553 )
3554
3555 vlog("# Using TESTDIR", _bytes2sys(self._testdir))
3556 vlog("# Using RUNTESTDIR", _bytes2sys(osenvironb[b'RUNTESTDIR']))
3557 vlog("# Using HGTMP", _bytes2sys(self._hgtmp))
3558 vlog("# Using PATH", os.environ["PATH"])
3559 vlog("# Using PYTHONPATH", os.environ.get("PYTHONPATH", ""))
3560 vlog("# Writing to directory", _bytes2sys(self._outputdir))
3561
3562 if shard_total is not None:
3563 slot = shard_index - 1
3564 testdescs = [
3565 t
3566 for (idx, t) in enumerate(testdescs)
3567 if (idx % shard_total == slot)
3568 ]
3569
3570 try:
3571 return self._runtests(testdescs) or 0
3572 finally:
3573 time.sleep(0.1)
3574 self._cleanup()
3575
3576 def findtests(self, args):
3577 """Finds possible test files from arguments.
3578
3579 If you wish to inject custom tests into the test harness, this would
3580 be a good function to monkeypatch or override in a derived class.
3581 """
3582 if not args:
3583 if self.options.changed:
3584 proc = Popen4(
3585 b'hg st --rev "%s" -man0 .'
3586 % _sys2bytes(self.options.changed),
3587 None,
3588 0,
3589 )
3590 stdout, stderr = proc.communicate()
3591 args = stdout.strip(b'\0').split(b'\0')
3592 else:
3593 args = os.listdir(b'.')
3594
3595 expanded_args = []
3596 for arg in args:
3597 if os.path.isdir(arg):
3598 if not arg.endswith(b'/'):
3599 arg += b'/'
3600 expanded_args.extend([arg + a for a in os.listdir(arg)])
3601 else:
3602 expanded_args.append(arg)
3603 args = expanded_args
3604
3605 testcasepattern = re.compile(br'([\w-]+\.t|py)(?:#([a-zA-Z0-9_\-.#]+))')
3606 tests = []
3607 for t in args:
3608 case = []
3609
3610 if not (
3611 os.path.basename(t).startswith(b'test-')
3612 and (t.endswith(b'.py') or t.endswith(b'.t'))
3613 ):
3614 m = testcasepattern.match(os.path.basename(t))
3615 if m is not None:
3616 t_basename, casestr = m.groups()
3617 t = os.path.join(os.path.dirname(t), t_basename)
3618 if casestr:
3619 case = casestr.split(b'#')
3620 else:
3621 continue
3622
3623 if t.endswith(b'.t'):
3624 # .t file may contain multiple test cases
3625 casedimensions = parsettestcases(t)
3626 if casedimensions:
3627 cases = []
3628
3629 def addcases(case, casedimensions):
3630 if not casedimensions:
3631 cases.append(case)
3632 else:
3633 for c in casedimensions[0]:
3634 addcases(case + [c], casedimensions[1:])
3635
3636 addcases([], casedimensions)
3637 if case and case in cases:
3638 cases = [case]
3639 elif case:
3640 # Ignore invalid cases
3641 cases = []
3642 else:
3643 pass
3644 tests += [{'path': t, 'case': c} for c in sorted(cases)]
3645 else:
3646 tests.append({'path': t})
3647 else:
3648 tests.append({'path': t})
3649
3650 if self.options.retest:
3651 retest_args = []
3652 for test in tests:
3653 errpath = self._geterrpath(test)
3654 if os.path.exists(errpath):
3655 retest_args.append(test)
3656 tests = retest_args
3657 return tests
3658
3659 def _runtests(self, testdescs):
3660 def _reloadtest(test, i):
3661 # convert a test back to its description dict
3662 desc = {'path': test.path}
3663 case = getattr(test, '_case', [])
3664 if case:
3665 desc['case'] = case
3666 return self._gettest(desc, i)
3667
3668 try:
3669 if self.options.restart:
3670 orig = list(testdescs)
3671 while testdescs:
3672 desc = testdescs[0]
3673 errpath = self._geterrpath(desc)
3674 if os.path.exists(errpath):
3675 break
3676 testdescs.pop(0)
3677 if not testdescs:
3678 print("running all tests")
3679 testdescs = orig
3680
3681 tests = [self._gettest(d, i) for i, d in enumerate(testdescs)]
3682 num_tests = len(tests) * self.options.runs_per_test
3683
3684 jobs = min(num_tests, self.options.jobs)
3685
3686 failed = False
3687 kws = self.options.keywords
3688 if kws is not None:
3689 kws = kws.encode('utf-8')
3690
3691 suite = TestSuite(
3692 self._testdir,
3693 jobs=jobs,
3694 whitelist=self.options.whitelisted,
3695 blacklist=self.options.blacklist,
3696 keywords=kws,
3697 loop=self.options.loop,
3698 runs_per_test=self.options.runs_per_test,
3699 showchannels=self.options.showchannels,
3700 tail_report=self.options.tail_report,
3701 tests=tests,
3702 loadtest=_reloadtest,
3703 )
3704 verbosity = 1
3705 if self.options.list_tests:
3706 verbosity = 0
3707 elif self.options.verbose:
3708 verbosity = 2
3709 runner = TextTestRunner(self, verbosity=verbosity)
3710
3711 osenvironb.pop(b'PYOXIDIZED_IN_MEMORY_RSRC', None)
3712 osenvironb.pop(b'PYOXIDIZED_FILESYSTEM_RSRC', None)
3713
3714 if self.options.list_tests:
3715 result = runner.listtests(suite)
3716 else:
3717 install_start_time = time.monotonic()
3718 self._usecorrectpython()
3719 if self._installdir:
3720 self._installhg()
3721 self._check_hg("Testing")
3722 if self.options.chg:
3723 assert self._installdir
3724 self._installchg()
3725 if self.options.rhg:
3726 assert self._installdir
3727 self._installrhg()
3728 elif self.options.pyoxidized:
3729 self._build_pyoxidized()
3730 self._use_correct_mercurial()
3731 install_end_time = time.monotonic()
3732 if self._installdir:
3733 msg = 'installed Mercurial in %.2f seconds'
3734 msg %= install_end_time - install_start_time
3735 log(msg)
3736
3737 log(
3738 'running %d tests using %d parallel processes'
3739 % (num_tests, jobs)
3740 )
3741
3742 result = runner.run(suite)
3743
3744 if result.failures or result.errors:
3745 failed = True
3746
3747 result.onEnd()
3748
3749 if self.options.anycoverage:
3750 self._outputcoverage()
3751 except KeyboardInterrupt:
3752 failed = True
3753 print("\ninterrupted!")
3754
3755 if failed:
3756 return 1
3757
3758 def _geterrpath(self, test):
3759 # test['path'] is a relative path
3760 if 'case' in test:
3761 # for multiple dimensions test cases
3762 casestr = b'#'.join(test['case'])
3763 errpath = b'%s#%s.err' % (test['path'], casestr)
3764 else:
3765 errpath = b'%s.err' % test['path']
3766 if self.options.outputdir:
3767 self._outputdir = canonpath(_sys2bytes(self.options.outputdir))
3768 errpath = os.path.join(self._outputdir, errpath)
3769 return errpath
3770
3771 def _getport(self, count):
3772 port = self._ports.get(count) # do we have a cached entry?
3773 if port is None:
3774 portneeded = HGPORT_COUNT
3775 # above 100 tries we just give up and let test reports failure
3776 for tries in range(100):
3777 allfree = True
3778 port = self.options.port + self._portoffset
3779 for idx in range(portneeded):
3780 if not checkportisavailable(port + idx):
3781 allfree = False
3782 break
3783 self._portoffset += portneeded
3784 if allfree:
3785 break
3786 self._ports[count] = port
3787 return port
3788
3789 def _gettest(self, testdesc, count):
3790 """Obtain a Test by looking at its filename.
3791
3792 Returns a Test instance. The Test may not be runnable if it doesn't
3793 map to a known type.
3794 """
3795 path = testdesc['path']
3796 lctest = path.lower()
3797 testcls = Test
3798
3799 for ext, cls in self.TESTTYPES:
3800 if lctest.endswith(ext):
3801 testcls = cls
3802 break
3803
3804 refpath = os.path.join(getcwdb(), path)
3805 tmpdir = os.path.join(self._hgtmp, b'child%d' % count)
3806
3807 # extra keyword parameters. 'case' is used by .t tests
3808 kwds = {k: testdesc[k] for k in ['case'] if k in testdesc}
3809
3810 t = testcls(
3811 refpath,
3812 self._outputdir,
3813 tmpdir,
3814 python=self._python,
3815 keeptmpdir=self.options.keep_tmpdir,
3816 debug=self.options.debug,
3817 first=self.options.first,
3818 timeout=self.options.timeout,
3819 startport=self._getport(count),
3820 extraconfigopts=self.options.extra_config_opt,
3821 shell=self.options.shell,
3822 hgcommand=self._hgcommand,
3823 usechg=bool(self.options.with_chg or self.options.chg),
3824 chgdebug=self.options.chg_debug,
3825 useipv6=useipv6,
3826 forbid_skip=self.options.forbid_skip,
3827 **kwds,
3828 )
3829 t.should_reload = True
3830 return t
3831
3832 def _cleanup(self):
3833 """Clean up state from this test invocation."""
3834 if self.options.keep_tmpdir:
3835 return
3836
3837 vlog("# Cleaning up HGTMP", _bytes2sys(self._hgtmp))
3838 shutil.rmtree(self._hgtmp, True)
3839 for f in self._createdfiles:
3840 try:
3841 os.remove(f)
3842 except OSError:
3843 pass
3844
3845 def _usecorrectpython(self):
3846 """Configure the environment to use the appropriate Python in tests."""
3847 # Tests must use the same interpreter as us or bad things will happen.
3848
3849 # install dir != None means we did install mercurial within a temporary
3850 # virtual env and do need to make sure the right python will be in
3851 # front of the PATH. Except for Windows who lack a `python3` executable
3852 # in this case.
3853 if self._installdir is None:
3854 pyexe_names = [b'python', b'python3']
3855 elif WINDOWS:
3856 pyexe_names = [b'python3']
3857 else:
3858 return
3859
3860 # os.symlink() is a thing with py3 on Windows, but it requires
3861 # Administrator rights.
3862 if not WINDOWS and getattr(os, 'symlink', None):
3863 msg = "# Making python executable in test path a symlink to '%s'"
3864 msg %= self._python
3865 vlog(msg)
3866 for pyexename in pyexe_names:
3867 mypython = os.path.join(self._custom_bin_dir, pyexename)
3868 try:
3869 if os.readlink(mypython) == self._python:
3870 continue
3871 os.unlink(mypython)
3872 except FileNotFoundError:
3873 pass
3874 if self._findprogram(pyexename) != self._python:
3875 try:
3876 os.symlink(self._python, mypython)
3877 self._createdfiles.append(mypython)
3878 except FileExistsError:
3879 # child processes may race, which is harmless
3880 pass
3881 elif WINDOWS and not os.getenv('MSYSTEM'):
3882 raise AssertionError('cannot run test on Windows without MSYSTEM')
3883 else:
3884 # Generate explicit file instead of symlink
3885 #
3886 # This is especially important as Windows doesn't have
3887 # `python3.exe`, and MSYS cannot understand the reparse point with
3888 # that name provided by Microsoft. Create a simple script on PATH
3889 # with that name that delegates to the py3 launcher so the shebang
3890 # lines work.
3891 esc_executable = _sys2bytes(shellquote(self._python))
3892 for pyexename in pyexe_names:
3893 stub_exec_path = os.path.join(self._custom_bin_dir, pyexename)
3894 with open(stub_exec_path, 'wb') as f:
3895 f.write(b'#!/bin/sh\n')
3896 f.write(b'%s "$@"\n' % esc_executable)
3897
3898 if WINDOWS:
3899 # adjust the path to make sur the main python finds itself and
3900 # its own dll
3901 path = os.environ['PATH'].split(os.pathsep)
3902 main_exec_dir = os.path.dirname(self._python)
3903 extra_paths = [
3904 _bytes2sys(self._custom_bin_dir),
3905 main_exec_dir,
3906 sys.base_exec_prefix, # for python3X.dll in main install
3907 ]
3908
3909 # Binaries installed by pip into the user area like pylint.exe may
3910 # not be in PATH by default.
3911 appdata = os.environ.get('APPDATA')
3912 vi = sys.version_info
3913 if appdata is not None:
3914 python_dir = 'Python%d%d' % (vi[0], vi[1])
3915 scripts_path = [appdata, 'Python', python_dir, 'Scripts']
3916 scripts_dir = os.path.join(*scripts_path)
3917 extra_paths.append(scripts_dir)
3918
3919 os.environ['PATH'] = os.pathsep.join(extra_paths + path)
3920
3921 def _use_correct_mercurial(self):
3922 target_exec = os.path.join(self._custom_bin_dir, b'hg')
3923 # hgcommand is ≠ hg in case like `rhg` and `chg` or with windows .exe's
3924 if self._hgcommand != b'hg':
3925 real_exec = shutil.which(self._hgcommand)
3926 if real_exec is None:
3927 raise ValueError(
3928 'could not find exec path for "%s"', self._hgcommand
3929 )
3930 if real_exec == target_exec:
3931 # do not overwrite something with itself
3932 return
3933 if os.path.exists(target_exec):
3934 # there is already something at the destination. Let's not
3935 # overwrite it.
3936 return
3937 if WINDOWS:
3938 with open(target_exec, 'wb') as f:
3939 f.write(b'#!/bin/sh\n')
3940 escaped_exec = shellquote(_bytes2sys(real_exec))
3941 f.write(b'%s "$@"\n' % _sys2bytes(escaped_exec))
3942 else:
3943 os.symlink(real_exec, target_exec)
3944 self._createdfiles.append(target_exec)
3945
3946 def _install_hg_cmd_wheel(self):
3947 wheel_path = self.options.wheel
3948 assert wheel_path
3949
3950 script = _sys2bytes(os.path.realpath(sys.argv[0]))
3951 hgroot = os.path.dirname(os.path.dirname(script))
3952 self._hgroot = hgroot
3953 os.chdir(hgroot)
3954 cmd = [
3955 self._pythonb,
3956 b"-m",
3957 b"pip",
3958 b"install",
3959 wheel_path,
3960 b"--no-cache-dir",
3961 b"--force",
3962 b"--ignore-installed",
3963 ]
3964
3965 return cmd
3966
3967 def _install_hg_cmd_setup(self):
3968 # Run installer in hg root
3969 setup_opts = b""
3970 if self.options.pure:
3971 setup_opts = b"--pure"
3972 elif self.options.rust:
3973 setup_opts = b"--rust"
3974 elif self.options.no_rust:
3975 setup_opts = b"--no-rust"
3976
3977 script = _sys2bytes(os.path.realpath(sys.argv[0]))
3978 hgroot = os.path.dirname(os.path.dirname(script))
3979 self._hgroot = hgroot
3980 os.chdir(hgroot)
3981
3982 if self.options.py_installer == "auto":
3983 if shutil.which("uv") is None:
3984 installer = "pip"
3985 else:
3986 installer = "uv"
3987 else:
3988 installer = self.options.py_installer
3989
3990 if installer == "uv":
3991 cmd = [b"uv", b"pip", b"install", b".", b"-p", self._pythonb]
3992 if self.options.offline:
3993 cmd.append(b"--offline")
3994 else:
3995 if self.options.offline:
3996 sys.stderr.write("fatal: --offline requires UV\n")
3997 sys.exit(1)
3998 cmd = [self._pythonb, b"-m", b"pip", b"install", b"."]
3999
4000 if setup_opts:
4001 if installer == "uv":
4002 cmd.append(b"-C=--global-option=%s" % setup_opts)
4003 else:
4004 cmd.extend(
4005 [b"--config-settings", b"--global-option=%s" % setup_opts]
4006 )
4007
4008 return cmd
4009
4010 def _installhg(self):
4011 """Install hg into the test environment.
4012
4013 This will also configure hg with the appropriate testing settings.
4014 """
4015 vlog("# Performing temporary installation of HG")
4016 install_env = original_env.copy()
4017 if self.options.wheel is None:
4018 cmd = self._install_hg_cmd_setup()
4019 else:
4020 cmd = self._install_hg_cmd_wheel()
4021 install_env["PYTHONUSERBASE"] = _bytes2sys(self._installdir)
4022
4023 installerrs = os.path.join(self._hgtmp, b"install.err")
4024
4025 if self.options.offline:
4026 install_env["CARGO_NET_OFFLINE"] = "1"
4027
4028 vlog("# Running", cmd)
4029 with open(installerrs, "wb") as logfile:
4030 r = subprocess.call(
4031 cmd,
4032 env=install_env,
4033 stdout=logfile,
4034 stderr=subprocess.STDOUT,
4035 )
4036 if r == 0:
4037 if not self.options.verbose:
4038 try:
4039 os.remove(installerrs)
4040 except FileNotFoundError:
4041 pass
4042 else:
4043 with open(installerrs, 'rb') as f:
4044 for line in f:
4045 sys.stdout.buffer.write(line)
4046 sys.exit(1)
4047 os.chdir(self._testdir)
4048
4049 hgbat = os.path.join(self._bindir, b'hg.bat')
4050 if os.path.isfile(hgbat):
4051 # hg.bat expects to be put in bin/scripts while run-tests.py
4052 # installation layout put it in bin/ directly. Fix it
4053 with open(hgbat, 'rb') as f:
4054 data = f.read()
4055 if br'"%~dp0..\python" "%~dp0hg" %*' in data:
4056 data = data.replace(
4057 br'"%~dp0..\python" "%~dp0hg" %*',
4058 b'"%~dp0python" "%~dp0hg" %*',
4059 )
4060 with open(hgbat, 'wb') as f:
4061 f.write(data)
4062 else:
4063 print('WARNING: cannot fix hg.bat reference to python.exe')
4064
4065 if self.options.anycoverage:
4066 custom = os.path.join(RUNTEST_DIR, b'sitecustomize.py')
4067 target = os.path.join(self._pythondir, b'sitecustomize.py')
4068 vlog('# Installing coverage trigger to %s' % target)
4069 shutil.copyfile(custom, target)
4070 rc = os.path.join(self._testdir, b'.coveragerc')
4071 vlog('# Installing coverage rc to %s' % rc)
4072 osenvironb[b'COVERAGE_PROCESS_START'] = rc
4073 covdir = os.path.join(self._installdir, b'..', b'coverage')
4074 try:
4075 os.mkdir(covdir)
4076 except FileExistsError:
4077 pass
4078
4079 osenvironb[b'COVERAGE_DIR'] = covdir
4080
4081 def _check_hg(self, verb):
4082 """Ensure that the 'mercurial' package imported by python is
4083 the one we expect it to be. If not, print a warning to stderr."""
4084 if self._pythondir_inferred:
4085 # The pythondir has been inferred from --with-hg flag.
4086 # We cannot expect anything sensible here.
4087 return
4088 expecthg = os.path.join(self._pythondir, b'mercurial')
4089 actual_bin_hg = self._get_hg_bin_path()
4090 actual_py_hg = self._get_hg_py_path()
4091 if actual_bin_hg != actual_py_hg:
4092 msg = (
4093 b'fatal: "python" and "hg" disagree about mercurial lib path:\n'
4094 b' hg: %s:\n'
4095 b' py: %s:\n'
4096 )
4097 msg %= (actual_bin_hg, actual_py_hg)
4098 msg = colorize(msg.decode(), "red", self.options.color)
4099 sys.stderr.write(msg)
4100 sys.exit(2)
4101 if os.path.abspath(actual_py_hg) != os.path.abspath(expecthg):
4102 msg = (
4103 'warning: %s with unexpected mercurial lib: %s\n'
4104 ' (expected %s)\n'
4105 )
4106 msg %= (verb, actual_py_hg.decode(), expecthg.decode())
4107 msg = colorize(msg, "yellow", self.options.color)
4108 sys.stderr.write(msg)
4109 policy = self._get_hg_module_policy()
4110 msg = b"fatal: mercurial binary has unexpected flavor for %s: %s\n"
4111 err = None
4112 if self.options.pure and policy != b"py":
4113 err = msg % (b"--pure", policy)
4114 elif self.options.rust and b"rust" not in policy:
4115 err = msg % (b"--rust", policy)
4116 elif self.options.no_rust and b"rust" in policy:
4117 err = msg % (b"--no-rust", policy)
4118 if err is not None:
4119 err = colorize(err.decode(), "red", self.options.color)
4120 sys.stderr.write(err)
4121 sys.exit(3)
4122
4123 @staticmethod
4124 def _get_debuginstall_env():
4125 """return the environment to run ``hg debuginstall`` safely"""
4126 # The debuginstall command checks a bunch of things, and exits with the
4127 # number of errors encountered, even if -T is passed and the template
4128 # didn't ask for things related to the error(s). Supply a fallback so
4129 # that running tests without --local doesn't hinge on Mercurial being
4130 # configured on the current system.
4131 env = os.environ.copy()
4132 env["HGUSER"] = "test_gremlin"
4133 env["HGRCPATH"] = "/dev/null"
4134 env["HGEDITOR"] = sys.executable # The executable must exist
4135 return env
4136
4137 def _get_hg_module_policy(self):
4138 """return the module policy as seen by the "hg" binary"""
4139 cmd = [
4140 _bytes2sys(self._real_hg),
4141 "debuginstall",
4142 "--template",
4143 "{hgmodulepolicy}",
4144 ]
4145 p = subprocess.Popen(
4146 " ".join(cmd),
4147 stdout=subprocess.PIPE,
4148 stderr=subprocess.PIPE,
4149 shell=True,
4150 env=self._get_debuginstall_env(),
4151 )
4152 out, err = p.communicate()
4153 if p.returncode != 0:
4154 msg = "fatal: fetching module policy from `hg` failed:\n"
4155 msg = colorize(msg, "red", self.options.color)
4156 sys.stderr.write(msg)
4157 cmd_err = colorize(err.decode(), "magenta", self.options.color)
4158 sys.stderr.write(cmd_err)
4159 cmd_err = colorize(out.decode(), "yellow", self.options.color)
4160 sys.stderr.write(cmd_err)
4161 sys.exit(4)
4162 return out
4163
4164 def _get_hg_bin_path(self):
4165 """return the path to the mercurial lib according to the "hg" binary"""
4166 cmd = [
4167 _bytes2sys(self._real_hg),
4168 "debuginstall",
4169 "--template",
4170 "{hgmodules}",
4171 ]
4172 p = subprocess.Popen(
4173 " ".join(cmd),
4174 stdout=subprocess.PIPE,
4175 stderr=subprocess.PIPE,
4176 shell=True,
4177 env=self._get_debuginstall_env(),
4178 )
4179 out, err = p.communicate()
4180 if p.returncode != 0:
4181 msg = f"fatal: fetching library from `hg` failed with {p.returncode}:\n"
4182 msg = colorize(msg, "red", self.options.color)
4183 sys.stderr.write(msg)
4184 cmd_err = colorize(err.decode(), "magenta", self.options.color)
4185 sys.stderr.write(cmd_err)
4186 cmd_err = colorize(out.decode(), "yellow", self.options.color)
4187 sys.stderr.write(cmd_err)
4188 sys.exit(4)
4189 return out
4190
4191 def _get_hg_py_path(self):
4192 """Return the path to the mercurial package that is actually found by
4193 the current Python interpreter."""
4194 if self._hgpath is not None:
4195 return self._hgpath
4196
4197 # PYTHONSAFEPATH (-P) new in 3.11
4198 if sys.version_info >= (3, 11, 0):
4199 python_safe_path = "-P "
4200 else:
4201 python_safe_path = ""
4202
4203 cmd = '"%s" %s-c "import mercurial; print (mercurial.__path__[0])"'
4204 cmd %= (self._python, python_safe_path)
4205
4206 p = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
4207 out, err = p.communicate()
4208
4209 self._hgpath = out.strip()
4210
4211 return self._hgpath
4212
4213 def _installchg(self):
4214 """Install chg into the test environment"""
4215 vlog('# Performing temporary installation of CHG')
4216 assert os.path.dirname(self._bindir) == self._installdir
4217 assert self._hgroot, 'must be called after _installhg()'
4218 cmd = b'"%(make)s" clean install PREFIX="%(prefix)s"' % {
4219 b'make': b'make', # TODO: switch by option or environment?
4220 b'prefix': self._installdir,
4221 }
4222 cwd = os.path.join(self._hgroot, b'contrib', b'chg')
4223 vlog("# Running", cmd)
4224 proc = subprocess.Popen(
4225 cmd,
4226 shell=True,
4227 cwd=cwd,
4228 stdin=subprocess.PIPE,
4229 stdout=subprocess.PIPE,
4230 stderr=subprocess.STDOUT,
4231 )
4232 out, _err = proc.communicate()
4233 if proc.returncode != 0:
4234 sys.stdout.buffer.write(out)
4235 sys.exit(1)
4236
4237 def _installrhg(self):
4238 """Install rhg into the test environment"""
4239 vlog('# Performing temporary installation of rhg')
4240 assert os.path.dirname(self._bindir) == self._installdir
4241 assert self._hgroot, 'must be called after _installhg()'
4242 cmd = b'"%(make)s" install-rhg PREFIX="%(prefix)s"' % {
4243 b'make': b'make', # TODO: switch by option or environment?
4244 b'prefix': self._installdir,
4245 }
4246 cwd = self._hgroot
4247 vlog("# Running", cmd)
4248 proc = subprocess.Popen(
4249 cmd,
4250 shell=True,
4251 cwd=cwd,
4252 stdin=subprocess.PIPE,
4253 stdout=subprocess.PIPE,
4254 stderr=subprocess.STDOUT,
4255 )
4256 out, _err = proc.communicate()
4257 if proc.returncode != 0:
4258 sys.stdout.buffer.write(out)
4259 sys.exit(1)
4260
4261 def _build_pyoxidized(self):
4262 """build a pyoxidized version of mercurial into the test environment
4263
4264 Ideally this function would be `install_pyoxidier` and would both build
4265 and install pyoxidier. However we are starting small to get pyoxidizer
4266 build binary to testing quickly.
4267 """
4268 vlog('# build a pyoxidized version of Mercurial')
4269 assert os.path.dirname(self._bindir) == self._installdir
4270 assert self._hgroot, 'must be called after _installhg()'
4271 target = b''
4272 if WINDOWS:
4273 target = b'windows'
4274 elif MACOS:
4275 target = b'macos'
4276
4277 cmd = b'"%(make)s" pyoxidizer-%(platform)s-tests' % {
4278 b'make': b'make',
4279 b'platform': target,
4280 }
4281 cwd = self._hgroot
4282 vlog("# Running", cmd)
4283 proc = subprocess.Popen(
4284 _bytes2sys(cmd),
4285 shell=True,
4286 cwd=_bytes2sys(cwd),
4287 stdin=subprocess.PIPE,
4288 stdout=subprocess.PIPE,
4289 stderr=subprocess.STDOUT,
4290 )
4291 out, _err = proc.communicate()
4292 if proc.returncode != 0:
4293 sys.stdout.buffer.write(out)
4294 sys.exit(1)
4295
4296 cmd = _bytes2sys(b"%s debuginstall -Tjson" % self._hgcommand)
4297 p = subprocess.Popen(
4298 cmd,
4299 stdout=subprocess.PIPE,
4300 shell=True,
4301 env=self._get_debuginstall_env(),
4302 )
4303 out, err = p.communicate()
4304
4305 props = json.loads(out)[0]
4306
4307 # Affects hghave.py
4308 osenvironb.pop(b'PYOXIDIZED_IN_MEMORY_RSRC', None)
4309 osenvironb.pop(b'PYOXIDIZED_FILESYSTEM_RSRC', None)
4310 if props["hgmodules"] == props["pythonexe"]:
4311 osenvironb[b'PYOXIDIZED_IN_MEMORY_RSRC'] = b'1'
4312 else:
4313 osenvironb[b'PYOXIDIZED_FILESYSTEM_RSRC'] = b'1'
4314
4315 def _outputcoverage(self):
4316 """Produce code coverage output."""
4317 import coverage
4318
4319 coverage = coverage.coverage
4320
4321 vlog('# Producing coverage report')
4322 # chdir is the easiest way to get short, relative paths in the
4323 # output.
4324 os.chdir(self._hgroot)
4325 covdir = os.path.join(_bytes2sys(self._installdir), '..', 'coverage')
4326 cov = coverage(data_file=os.path.join(covdir, 'cov'))
4327
4328 # Map install directory paths back to source directory.
4329 cov.config.paths['srcdir'] = ['.', _bytes2sys(self._pythondir)]
4330
4331 cov.combine()
4332
4333 omit = [
4334 _bytes2sys(os.path.join(x, b'*'))
4335 for x in [self._bindir, self._testdir]
4336 ]
4337 cov.report(ignore_errors=True, omit=omit)
4338
4339 if self.options.htmlcov:
4340 htmldir = os.path.join(_bytes2sys(self._outputdir), 'htmlcov')
4341 cov.html_report(directory=htmldir, omit=omit)
4342 if self.options.annotate:
4343 adir = os.path.join(_bytes2sys(self._outputdir), 'annotated')
4344 if not os.path.isdir(adir):
4345 os.mkdir(adir)
4346 cov.annotate(directory=adir, omit=omit)
4347
4348 def _findprogram(self, program):
4349 """Search PATH for a executable program"""
4350 dpb = _sys2bytes(os.defpath)
4351 sepb = _sys2bytes(os.pathsep)
4352 for p in osenvironb.get(b'PATH', dpb).split(sepb):
4353 name = os.path.join(p, program)
4354 if WINDOWS or os.access(name, os.X_OK):
4355 return _bytes2sys(name)
4356 return None
4357
4358 def _checktools(self):
4359 """Ensure tools required to run tests are present."""
4360 for p in self.REQUIREDTOOLS:
4361 if WINDOWS and not p.endswith(b'.exe'):
4362 p += b'.exe'
4363 found = self._findprogram(p)
4364 p = p.decode("utf-8")
4365 if found:
4366 vlog("# Found prerequisite", p, "at", found)
4367 else:
4368 print("WARNING: Did not find prerequisite tool: %s " % p)
4369
4370
4371 def aggregateexceptions(path):
4372 exceptioncounts = collections.Counter()
4373 testsbyfailure = collections.defaultdict(set)
4374 failuresbytest = collections.defaultdict(set)
4375
4376 for f in os.listdir(path):
4377 with open(os.path.join(path, f), 'rb') as fh:
4378 data = fh.read().split(b'\0')
4379 if len(data) != 5:
4380 continue
4381
4382 exc, mainframe, hgframe, hgline, testname = data
4383 exc = exc.decode('utf-8')
4384 mainframe = mainframe.decode('utf-8')
4385 hgframe = hgframe.decode('utf-8')
4386 hgline = hgline.decode('utf-8')
4387 testname = testname.decode('utf-8')
4388
4389 key = (hgframe, hgline, exc)
4390 exceptioncounts[key] += 1
4391 testsbyfailure[key].add(testname)
4392 failuresbytest[testname].add(key)
4393
4394 # Find test having fewest failures for each failure.
4395 leastfailing = {}
4396 for key, tests in testsbyfailure.items():
4397 fewesttest = None
4398 fewestcount = 99999999
4399 for test in sorted(tests):
4400 if len(failuresbytest[test]) < fewestcount:
4401 fewesttest = test
4402 fewestcount = len(failuresbytest[test])
4403
4404 leastfailing[key] = (fewestcount, fewesttest)
4405
4406 # Create a combined counter so we can sort by total occurrences and
4407 # impacted tests.
4408 combined = {}
4409 for key in exceptioncounts:
4410 combined[key] = (
4411 exceptioncounts[key],
4412 len(testsbyfailure[key]),
4413 leastfailing[key][0],
4414 leastfailing[key][1],
4415 )
4416
4417 return {
4418 'exceptioncounts': exceptioncounts,
4419 'total': sum(exceptioncounts.values()),
4420 'combined': combined,
4421 'leastfailing': leastfailing,
4422 'byfailure': testsbyfailure,
4423 'bytest': failuresbytest,
4424 }
4425
4426
4427 if __name__ == '__main__':
4428 if WINDOWS and not os.getenv('MSYSTEM'):
4429 print('cannot run test on Windows without MSYSTEM', file=sys.stderr)
4430 print(
4431 '(if you need to do so contact the mercurial devs: '
4432 '[email protected])',
4433 file=sys.stderr,
4434 )
4435 sys.exit(255)
4436
4437 runner = TestRunner()
4438
4439 try:
4440 import msvcrt
4441
4442 msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY)
4443 msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
4444 msvcrt.setmode(sys.stderr.fileno(), os.O_BINARY)
4445 except ImportError:
4446 pass
4447
4448 sys.exit(runner.run(sys.argv[1:]))