Newer
Older
#!/usr/bin/env python
#
# run-tests.py - Run a set of tests on Mercurial
#
# Copyright 2006 Matt Mackall <mpm@selenic.com>
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2 or any later version.
# Modifying this script is tricky because it has many modes:
# - serial (default) vs parallel (-jN, N > 1)
# - no coverage (default) vs coverage (-c, -C, -s)
# - temp install (default) vs specific hg script (--with-hg, --local)
# - tests are a mix of shell scripts and Python scripts
#
# If you change this script, it is recommended that you ensure you
# haven't broken it by running it in various modes with a representative
# sample of test scripts. For example:
# 1) serial, no coverage, temp install:
# ./run-tests.py test-s*
# 2) serial, no coverage, local hg:
# ./run-tests.py --local test-s*
# 3) serial, coverage, temp install:
# ./run-tests.py -c test-s*
# 4) serial, coverage, local hg:
# ./run-tests.py -c --local test-s* # unsupported
# 5) parallel, no coverage, temp install:
# ./run-tests.py -j2 test-s*
# 6) parallel, no coverage, local hg:
# ./run-tests.py -j2 --local test-s*
# 7) parallel, coverage, temp install:
# ./run-tests.py -j2 -c test-s* # currently broken
# 8) parallel, coverage, local install:
# ./run-tests.py -j2 -c --local test-s* # unsupported (and broken)
# 9) parallel, custom tmp dir:
# ./run-tests.py -j2 --tmpdir /tmp/myhgtests
# 10) parallel, pure, tests that call run-tests:
# ./run-tests.py --pure `grep -l run-tests.py *.t`
#
# (You could use any subset of the tests: test-s* happens to match
# enough that it's worth doing parallel runs, few enough that it
# completes fairly quickly, includes both shell and Python scripts, and
# includes some scripts that run daemon processes.)
from __future__ import absolute_import, print_function
import difflib
import distutils.version as version
import errno
import optparse
import os
import random
import re
import signal
import socket
import sys
import sysconfig
import time
import unittest
import xml.dom.minidom as minidom
try:
import Queue as queue
except ImportError:
import queue
if os.environ.get('RTUNICODEPEDANTRY', False):
try:
reload(sys)
sys.setdefaultencoding("undefined")
except NameError:
pass
osenvironb = getattr(os, 'environb', os.environ)
processlock = threading.Lock()
if sys.version_info > (3, 5, 0):
xrange = range # we use xrange in one place, and we'd rather not use range
Augie Fackler
committed
def _bytespath(p):
return p.encode('utf-8')
def _strpath(p):
return p.decode('utf-8')
elif sys.version_info >= (3, 0, 0):
print('%s is only supported on Python 3.5+ and 2.7, not %s' %
(sys.argv[0], '.'.join(str(v) for v in sys.version_info[:3])))
sys.exit(70) # EX_SOFTWARE from `man 3 sysexit`
else:
PYTHON3 = False
# In python 2.x, path operations are generally done using
# bytestrings by default, so we don't have to do any extra
# fiddling there. We define the wrapper functions anyway just to
# help keep code consistent between platforms.
Augie Fackler
committed
def _bytespath(p):
return p
_strpath = _bytespath
# For Windows support
wifexited = getattr(os, "WIFEXITED", lambda x: False)
def checksocketfamily(name, port=20058):
"""return true if we can listen on localhost using family=name
name should be either 'AF_INET', or 'AF_INET6'.
port being used is okay - EADDRINUSE is considered as successful.
"""
family = getattr(socket, name, None)
if family is None:
return False
try:
s = socket.socket(family, socket.SOCK_STREAM)
s.bind(('localhost', port))
s.close()
return True
except socket.error as exc:
if exc.errno == errno.EADDRINUSE:
return True
elif exc.errno in (errno.EADDRNOTAVAIL, errno.EPROTONOSUPPORT):
return False
else:
raise
else:
return False
# useipv6 will be set by parseargs
useipv6 = None
def checkportisavailable(port):
"""return true if a port seems free to bind on localhost"""
if useipv6:
family = socket.AF_INET6
else:
family = socket.AF_INET
try:
s = socket.socket(family, socket.SOCK_STREAM)
s.bind(('localhost', port))
s.close()
return True
except socket.error as exc:
if exc.errno not in (errno.EADDRINUSE, errno.EADDRNOTAVAIL,
errno.EPROTONOSUPPORT):
raise
def Popen4(cmd, wd, timeout, env=None):
processlock.acquire()
p = subprocess.Popen(cmd, shell=True, bufsize=-1, cwd=wd, env=env,
close_fds=closefds,
stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
processlock.release()
p.fromchild = p.stdout
p.tochild = p.stdin
p.childerr = p.stderr
p.timeout = False
if timeout:
def t():
start = time.time()
while time.time() - start < timeout and p.returncode is None:
p.timeout = True
if p.returncode is None:
Thomas Arendsen Hein
committed
terminate(p)
threading.Thread(target=t).start()
Augie Fackler
committed
PYTHON = _bytespath(sys.executable.replace('\\', '/'))
IMPL_PATH = b'PYTHONPATH'
if 'java' in sys.platform:
IMPL_PATH = b'JYTHONPATH'
defaults = {
'jobs': ('HGTEST_JOBS', 1),
'timeout': ('HGTEST_TIMEOUT', 180),
'slowtimeout': ('HGTEST_SLOWTIMEOUT', 500),
'port': ('HGTEST_PORT', 20059),
'shell': ('HGTEST_SHELL', 'sh'),
}
def canonpath(path):
return os.path.realpath(os.path.expanduser(path))
def parselistfiles(files, listtype, warn=True):
entries = dict()
for filename in files:
try:
path = os.path.expanduser(os.path.expandvars(filename))
except IOError as err:
if err.errno != errno.ENOENT:
raise
if warn:
print("warning: no such %s file: %s" % (listtype, filename))
continue
for line in f.readlines():
line = line.split(b'#', 1)[0].strip()
if line:
entries[line] = filename
f.close()
return entries
def parsettestcases(path):
"""read a .t test file, return a set of test case names
If path does not exist, return an empty set.
"""
cases = set()
try:
with open(path, 'rb') as f:
for l in f:
if l.startswith(b'#testcases '):
cases.update(l[11:].split())
except IOError as ex:
if ex.errno != errno.ENOENT:
raise
return cases
"""Obtain the OptionParser used by the CLI."""
parser = optparse.OptionParser("%prog [options] [tests]")
# keep these sorted
parser.add_option("--blacklist", action="append",
help="skip tests listed in the specified blacklist file")
parser.add_option("--whitelist", action="append",
help="always run tests listed in the specified whitelist file")
Mads Kiilerich
committed
parser.add_option("--changed", type="string",
help="run tests that are changed in parent rev or working directory")
parser.add_option("-C", "--annotate", action="store_true",
help="output files annotated with coverage")
parser.add_option("-c", "--cover", action="store_true",
help="print a test coverage report")
parser.add_option("-d", "--debug", action="store_true",
help="debug mode: write output of test scripts to console"
" rather than capturing and diffing it (disables timeout)")
parser.add_option("-f", "--first", action="store_true",
help="exit on the first test failure")
parser.add_option("-H", "--htmlcov", action="store_true",
help="create an HTML report of the coverage of the files")
parser.add_option("-i", "--interactive", action="store_true",
help="prompt to accept changed output")
parser.add_option("-j", "--jobs", type="int",
help="number of jobs to run in parallel"
" (default: $%s or %d)" % defaults['jobs'])
parser.add_option("--keep-tmpdir", action="store_true",
help="keep temporary directory after running tests")
parser.add_option("-k", "--keywords",
help="run tests matching keywords")
parser.add_option("--list-tests", action="store_true",
help="list tests instead of running them")
parser.add_option("-l", "--local", action="store_true",
help="shortcut for --with-hg=<testdir>/../hg, "
"and --with-chg=<testdir>/../contrib/chg/chg if --chg is set")
parser.add_option("--loop", action="store_true",
help="loop tests repeatedly")
parser.add_option("--runs-per-test", type="int", dest="runs_per_test",
help="run each test N times (default=1)", default=1)
parser.add_option("-n", "--nodiff", action="store_true",
help="skip showing test changes")
parser.add_option("--outputdir", type="string",
help="directory to write error logs to (default=test directory)")
parser.add_option("-p", "--port", type="int",
help="port on which servers should listen"
" (default: $%s or %d)" % defaults['port'])
parser.add_option("--compiler", type="string",
help="compiler to build with")
parser.add_option("--pure", action="store_true",
help="use pure Python code instead of C extensions")
parser.add_option("-R", "--restart", action="store_true",
help="restart at last error")
parser.add_option("-r", "--retest", action="store_true",
help="retest failed tests")
parser.add_option("-S", "--noskips", action="store_true",
help="don't report skip tests verbosely")
parser.add_option("--shell", type="string",
help="shell to use (default: $%s or %s)" % defaults['shell'])
parser.add_option("-t", "--timeout", type="int",
help="kill errant tests after TIMEOUT seconds"
" (default: $%s or %d)" % defaults['timeout'])
parser.add_option("--slowtimeout", type="int",
help="kill errant slow tests after SLOWTIMEOUT seconds"
" (default: $%s or %d)" % defaults['slowtimeout'])
parser.add_option("--time", action="store_true",
help="time how long each test takes")
parser.add_option("--json", action="store_true",
help="store test result data in 'report.json' file")
parser.add_option("--tmpdir", type="string",
help="run tests in the given temporary directory"
" (implies --keep-tmpdir)")
parser.add_option("-v", "--verbose", action="store_true",
help="output verbose messages")
parser.add_option("--xunit", type="string",
help="record xunit results at specified path")
parser.add_option("--view", type="string",
help="external diff viewer")
parser.add_option("--with-hg", type="string",
metavar="HG",
help="test using specified hg script rather than a "
"temporary installation")
parser.add_option("--chg", action="store_true",
help="install and use chg wrapper in place of hg")
parser.add_option("--with-chg", metavar="CHG",
help="use specified chg wrapper in place of hg")
parser.add_option("--ipv6", action="store_true",
help="prefer IPv6 to IPv4 for network related tests")
parser.add_option("-3", "--py3k-warnings", action="store_true",
help="enable Py3k warnings on Python 2.7+")
# This option should be deleted once test-check-py3-compat.t and other
# Python 3 tests run with Python 3.
parser.add_option("--with-python3", metavar="PYTHON3",
help="Python 3 interpreter (if running under Python 2)"
" (TEMPORARY)")
parser.add_option('--extra-config-opt', action="append",
help='set the given config opt in the test hgrc')
parser.add_option('--random', action="store_true",
help='run tests in random order')
parser.add_option('--profile-runner', action='store_true',
help='run statprof on run-tests')
parser.add_option('--allow-slow-tests', action='store_true',
help='allow extremely slow tests')
parser.add_option('--showchannels', action='store_true',
help='show scheduling channels')
parser.add_option('--known-good-rev', type="string",
metavar="known_good_rev",
help=("Automatically bisect any failures using this "
"revision as a known-good revision."))
for option, (envvar, default) in defaults.items():
defaults[option] = type(default)(os.environ.get(envvar, default))
parser.set_defaults(**defaults)
return parser
def parseargs(args, parser):
"""Parse arguments with our OptionParser and validate results."""
(options, args) = parser.parse_args(args)
# jython is always pure
if 'java' in sys.platform or '__pypy__' in sys.modules:
if options.with_hg:
options.with_hg = canonpath(_bytespath(options.with_hg))
if not (os.path.isfile(options.with_hg) and
os.access(options.with_hg, os.X_OK)):
parser.error('--with-hg must specify an executable hg script')
if os.path.basename(options.with_hg) not in [b'hg', b'hg.exe']:
sys.stderr.write('warning: --with-hg should specify an hg script\n')
if options.local:
testdir = os.path.dirname(_bytespath(canonpath(sys.argv[0])))
reporootdir = os.path.dirname(testdir)
pathandattrs = [(b'hg', 'with_hg')]
if options.chg:
pathandattrs.append((b'contrib/chg/chg', 'with_chg'))
for relpath, attr in pathandattrs:
binpath = os.path.join(reporootdir, relpath)
if os.name != 'nt' and not os.access(binpath, os.X_OK):
parser.error('--local specified, but %r not found or '
'not executable' % binpath)
setattr(options, attr, binpath)
if (options.chg or options.with_chg) and os.name == 'nt':
parser.error('chg does not work on %s' % os.name)
if options.with_chg:
options.chg = False # no installation to temporary location
options.with_chg = canonpath(_bytespath(options.with_chg))
if not (os.path.isfile(options.with_chg) and
os.access(options.with_chg, os.X_OK)):
parser.error('--with-chg must specify a chg executable')
if options.chg and options.with_hg:
# chg shares installation location with hg
parser.error('--chg does not work when --with-hg is specified '
'(use --with-chg instead)')
global useipv6
if options.ipv6:
useipv6 = checksocketfamily('AF_INET6')
else:
# only use IPv6 if IPv4 is unavailable and IPv6 is available
useipv6 = ((not checksocketfamily('AF_INET'))
and checksocketfamily('AF_INET6'))
options.anycoverage = options.cover or options.annotate or options.htmlcov
if options.anycoverage:
try:
import coverage
covver = version.StrictVersion(coverage.__version__).version
if covver < (3, 3):
parser.error('coverage options require coverage 3.3 or later')
except ImportError:
parser.error('coverage options now require the coverage package')
if options.anycoverage and options.local:
# this needs some path mangling somewhere, I guess
parser.error("sorry, coverage options do not work when --local "
"is specified")
if options.anycoverage and options.with_hg:
parser.error("sorry, coverage options do not work when --with-hg "
"is specified")
if options.jobs < 1:
parser.error('--jobs must be positive')
if options.interactive and options.debug:
parser.error("-i/--interactive and -d/--debug are incompatible")
if options.debug:
if options.timeout != defaults['timeout']:
sys.stderr.write(
'warning: --timeout option ignored with --debug\n')
if options.slowtimeout != defaults['slowtimeout']:
sys.stderr.write(
'warning: --slowtimeout option ignored with --debug\n')
options.timeout = 0
options.slowtimeout = 0
if PYTHON3:
parser.error(
'--py3k-warnings can only be used on Python 2.7')
if options.with_python3:
if PYTHON3:
parser.error('--with-python3 cannot be used when executing with '
'Python 3')
options.with_python3 = canonpath(options.with_python3)
# Verify Python3 executable is acceptable.
proc = subprocess.Popen([options.with_python3, b'--version'],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
out, _err = proc.communicate()
ret = proc.wait()
if ret != 0:
parser.error('could not determine version of python 3')
if not out.startswith('Python '):
parser.error('unexpected output from python3 --version: %s' %
out)
vers = version.LooseVersion(out[len('Python '):])
if vers < version.LooseVersion('3.5.0'):
parser.error('--with-python3 version must be 3.5.0 or greater; '
'got %s' % out)
Nicolas Dumazet
committed
if options.blacklist:
options.blacklist = parselistfiles(options.blacklist, 'blacklist')
if options.whitelist:
options.whitelisted = parselistfiles(options.whitelist, 'whitelist')
else:
options.whitelisted = {}
if options.showchannels:
options.nodiff = True
return (options, args)
def rename(src, dst):
"""Like os.rename(), trade atomicity and opened files friendliness
for existing destination support.
"""
shutil.copy(src, dst)
os.remove(src)
_unified_diff = difflib.unified_diff
Augie Fackler
committed
if PYTHON3:
import functools
_unified_diff = functools.partial(difflib.diff_bytes, difflib.unified_diff)
def getdiff(expected, output, ref, err):
servefail = False
for line in _unified_diff(expected, output, ref, err):
if line.startswith(b'+++') or line.startswith(b'---'):
line = line.replace(b'\\', b'/')
if line.endswith(b' \n'):
line = line[:-2] + b'\n'
if not servefail and line.startswith(
b'+ abort: child process failed to start'):
servefail = True
verbose = False
def vlog(*msg):
"""Log only when in verbose mode."""
if verbose is False:
return
return log(*msg)
# Bytes that break XML even in a CDATA block: control characters 0-31
# sans \t, \n and \r
CDATA_EVIL = re.compile(br"[\000-\010\013\014\016-\037]")
# Match feature conditionalized output lines in the form, capturing the feature
# list in group 2, and the preceeding line output in group 1:
#
# output..output (feature !)\n
optline = re.compile(b'(.+) \((.+?) !\)\n$')
def cdatasafe(data):
"""Make a string safe to include in a CDATA block.
Certain control characters are illegal in a CDATA block, and
there's no way to include a ]]> in a CDATA either. This function
replaces illegal bytes with ? and adds a space between the ]] so
that it won't break the CDATA block.
"""
return CDATA_EVIL.sub(b'?', data).replace(b']]>', b'] ]>')
"""Log something to stdout.
Arguments are strings to print.
"""
with iolock:
if verbose:
print(verbose, end=' ')
for m in msg:
print(m, end=' ')
print()
sys.stdout.flush()
Thomas Arendsen Hein
committed
def terminate(proc):
"""Terminate subprocess"""
Thomas Arendsen Hein
committed
vlog('# Terminating process %d' % proc.pid)
try:
proc.terminate()
Thomas Arendsen Hein
committed
except OSError:
pass
import killdaemons as killmod
return killmod.killdaemons(pidfile, tryhard=False, remove=True,
"""Encapsulates a single, runnable test.
While this class conforms to the unittest.TestCase API, it differs in that
instances need to be instantiated manually. (Typically, unittest.TestCase
classes are instantiated automatically by scanning modules.)
# Status code reserved for skipped tests (used by hghave).
SKIPPED_STATUS = 80
def __init__(self, path, outputdir, tmpdir, keeptmpdir=False,
timeout=defaults['timeout'],
startport=defaults['port'], extraconfigopts=None,
py3kwarnings=False, shell=None, hgcommand=None,
slowtimeout=defaults['slowtimeout'], usechg=False,
useipv6=False):
"""Create a test from parameters.
path is the full path to the file defining the test.
tmpdir is the main temporary directory to use for this test.
keeptmpdir determines whether to keep the test's temporary directory
after execution. It defaults to removal (False).
debug mode will make the test execute verbosely, with unfiltered
output.
timeout controls the maximum run time of the test. It is ignored when
debug is True. See slowtimeout for tests with #require slow.
slowtimeout overrides timeout if the test has #require slow.
startport controls the starting port number to use for this test. Each
test will reserve 3 port numbers for execution. It is the caller's
responsibility to allocate a non-overlapping port range to Test
instances.
extraconfigopts is an iterable of extra hgrc config options. Values
must have the form "key=value" (something understood by hgrc). Values
of the form "foo.key=value" will result in "[foo] key=value".
py3kwarnings enables Py3k warnings.
shell is the shell to execute tests in.
self.path = path
self.bname = os.path.basename(path)
self.name = _strpath(self.bname)
self._testdir = os.path.dirname(path)
self._outputdir = outputdir
self._tmpname = os.path.basename(path)
self.errpath = os.path.join(self._outputdir, b'%s.err' % self.bname)
self._threadtmp = tmpdir
self._keeptmpdir = keeptmpdir
self._debug = debug
self._slowtimeout = slowtimeout
self._extraconfigopts = extraconfigopts or []
self._py3kwarnings = py3kwarnings
Augie Fackler
committed
self._shell = _bytespath(shell)
self._hgcommand = hgcommand or b'hg'
self._usechg = usechg
self._useipv6 = useipv6
self._finished = None
self._ret = None
self._out = None
self._chgsockdir = None
# If we're not in --debug mode and reference output file exists,
# check test output against it.
self._refout = None # to match "out is None"
elif os.path.exists(self.refpath):
self._refout = f.read().splitlines(True)
f.close()
else:
self._refout = []
# needed to get base class __repr__ running
@property
def _testMethodName(self):
return self.name
def __str__(self):
return self.name
def shortDescription(self):
return self.name
def setUp(self):
"""Tasks to perform before run()."""
self._finished = False
self._ret = None
self._out = None
try:
os.mkdir(self._threadtmp)
except OSError as e:
if e.errno != errno.EEXIST:
raise
self._testtmp = os.path.join(self._threadtmp, name)
# Remove any previous output files.
if os.path.exists(self.errpath):
try:
os.remove(self.errpath)
except OSError as e:
# We might have raced another test to clean up a .err
# file, so ignore ENOENT when removing a previous .err
# file.
if e.errno != errno.ENOENT:
raise
if self._usechg:
self._chgsockdir = os.path.join(self._threadtmp,
b'%s.chgsock' % name)
os.mkdir(self._chgsockdir)
"""Run this test and report results against a TestResult instance."""
# This function is extremely similar to unittest.TestCase.run(). Once
# we require Python 2.7 (or at least its version of unittest), this
# function can largely go away.
result.startTest(self)
try:
try:
self.setUp()
except (KeyboardInterrupt, SystemExit):
raise
except Exception:
result.addError(self, sys.exc_info())
return
success = False
try:
self.runTest()
except KeyboardInterrupt:
# The base class will have already counted this as a
# test we "ran", but we want to exclude skipped tests
# from those we count towards those run.
result.testsRun -= 1
except self.failureException as e:
# This differs from unittest in that we don't capture
# the stack trace. This is for historical reasons and
# this decision could be revisited in the future,
# especially for PythonTest instances.
if result.addFailure(self, str(e)):
success = True
except Exception:
result.addError(self, sys.exc_info())
else:
success = True
try:
self.tearDown()
except (KeyboardInterrupt, SystemExit):
raise
except Exception:
result.addError(self, sys.exc_info())
success = False
if success:
result.addSuccess(self)
finally:
result.stopTest(self, interrupted=self._aborted)
"""Run this test instance.
This will return a tuple describing the result of the test.
"""
self._daemonpids.append(env['DAEMON_PIDS'])
ret, out = self._run(env)
self._finished = True
self._ret = ret
self._out = out
def describe(ret):
if ret < 0:
return 'killed by signal: %d' % -ret
return 'returned error code %d' % ret
if ret == self.SKIPPED_STATUS:
if out is None: # Debug mode, nothing to parse.
missing = ['unknown']
failed = None
else:
missing, failed = TTest.parsehghaveoutput(out)
Mads Kiilerich
committed
missing = ['skipped']
self.fail('hg have failed checking for %s' % failed[-1])
self.fail('timed out')
elif out != self._refout:
# Diff generation may rely on written .err file.
if (ret != 0 or out != self._refout) and not self._skipped \
and not self._debug:
f = open(self.errpath, 'wb')
for line in out:
f.write(line)
f.close()
# The result object handles diff calculation for us.
if self._result.addOutputMismatch(self, ret, out, self._refout):
# change was accepted, skip failing
return
msg = 'output changed and ' + describe(ret)
self.fail(msg)
self.fail(describe(ret))
def tearDown(self):
"""Tasks to perform after run()."""
for entry in self._daemonpids:
killdaemons(entry)
self._daemonpids = []
if self._keeptmpdir:
log('\nKeeping testtmp dir: %s\nKeeping threadtmp dir: %s' %
(self._testtmp.decode('utf-8'),
self._threadtmp.decode('utf-8')))
shutil.rmtree(self._testtmp, True)
shutil.rmtree(self._threadtmp, True)
if self._usechg:
# chgservers will stop automatically after they find the socket
# files are deleted
shutil.rmtree(self._chgsockdir, True)
if (self._ret != 0 or self._out != self._refout) and not self._skipped \
and not self._debug and self._out:
f = open(self.errpath, 'wb')
for line in self._out:
f.write(line)
f.close()
vlog("# Ret was:", self._ret, '(%s)' % self.name)
def _run(self, env):
# This should be implemented in child classes to run tests.
raise unittest.SkipTest('unknown test type')
def abort(self):
"""Terminate execution of this test."""
self._aborted = True
offset = b'' if i == 0 else b'%d' % i
return (br':%d\b' % (self._startport + i), b':$HGPORT%s' % offset)
"""Obtain a mapping of text replacements to apply to test output.
Test output needs to be normalized so it can be compared to expected
output. This function defines how some of that normalization will
occur.
"""
# This list should be parallel to defineport in _getenv
self._portmap(0),
self._portmap(1),
self._portmap(2),
(br'(?m)^(saved backup bundle to .*\.hg)( \(glob\))?$',
br'\1 (glob)'),
(br'([^0-9])%s' % re.escape(self._localip()), br'\1$LOCALIP'),
(br'\bHG_TXNID=TXN:[a-f0-9]{40}\b', br'HG_TXNID=TXN:$ID$'),
r.append((self._escapepath(self._testtmp), b'$TESTTMP'))
(b''.join(c.isalpha() and b'[%s%s]' % (c.lower(), c.upper()) or
c in b'/\\' and br'[/\\]' or c.isdigit() and c or b'\\' + c
def _localip(self):
if self._useipv6:
return b'::1'
else:
return b'127.0.0.1'
"""Obtain environment variables to use during test execution."""
def defineport(i):
offset = '' if i == 0 else '%s' % i
env["HGPORT%s" % offset] = '%s' % (self._startport + i)
env['PYTHONUSERBASE'] = sysconfig.get_config_var('userbase')
env['HGEMITWARNINGS'] = '1'
env['TESTTMP'] = self._testtmp
env['HOME'] = self._testtmp
# This number should match portneeded in _getport
# This list should be parallel to _portmap in _getreplacements
defineport(port)
env["HGRCPATH"] = os.path.join(self._threadtmp, b'.hgrc')
env["DAEMON_PIDS"] = os.path.join(self._threadtmp, b'daemon.pids')
env["HGEDITOR"] = ('"' + sys.executable + '"'
+ ' -c "import sys; sys.exit(0)"')
env["HGMERGE"] = "internal:merge"
env["HGUSER"] = "test"
env["HGENCODING"] = "ascii"
env["HGENCODINGMODE"] = "strict"
env['HGIPV6'] = str(int(self._useipv6))
# LOCALIP could be ::1 or 127.0.0.1. Useful for tests that require raw
# IP addresses.
env['LOCALIP'] = self._localip()
# Reset some environment variables to well-known values so that
# the tests produce repeatable output.
env['LANG'] = env['LC_ALL'] = env['LANGUAGE'] = 'C'
env['TZ'] = 'GMT'
env["EMAIL"] = "Foo Bar <foo.bar@example.com>"
env['COLUMNS'] = '80'
env['TERM'] = 'xterm'
for k in ('HG HGPROF CDPATH GREP_OPTIONS http_proxy no_proxy ' +
'HGPLAIN HGPLAINEXCEPT EDITOR VISUAL PAGER ' +
if k in env:
del env[k]
# unset env related to hooks
for k in env.keys():
if k.startswith('HG_'):
del env[k]
if self._usechg:
env['CHGSOCKNAME'] = os.path.join(self._chgsockdir, b'server')
hgrc.write(b'[ui]\n')
hgrc.write(b'slash = True\n')
hgrc.write(b'interactive = False\n')
hgrc.write(b'mergemarkers = detailed\n')
hgrc.write(b'promptecho = True\n')
hgrc.write(b'[defaults]\n')
hgrc.write(b'[devel]\n')
hgrc.write(b'all-warnings = true\n')
hgrc.write(b'default-date = 0 0\n')
hgrc.write(b'[largefiles]\n')
hgrc.write(b'usercache = %s\n' %
(os.path.join(self._testtmp, b'.cache/largefiles')))
hgrc.write(b'[web]\n')
hgrc.write(b'address = localhost\n')
hgrc.write(b'ipv6 = %s\n' % str(self._useipv6).encode('ascii'))
for opt in self._extraconfigopts:
section, key = opt.split('.', 1)
assert '=' in key, ('extra config opt %s must '
'have an = for assignment' % opt)
hgrc.write(b'[%s]\n%s\n' % (section, key))
def fail(self, msg):
# unittest differentiates between errored and failed.
# Failed is denoted by AssertionError (by default at least).
raise AssertionError(msg)
def _runcommand(self, cmd, env, normalizenewlines=False):
"""Run command in a sub-process, capturing the output (stdout and
stderr).
Return a tuple (exitcode, output). output is None in debug mode.
"""
if self._debug:
proc = subprocess.Popen(cmd, shell=True, cwd=self._testtmp,
env=env)
ret = proc.wait()
return (ret, None)
proc = Popen4(cmd, self._testtmp, self._timeout, env)
def cleanup():
terminate(proc)
ret = proc.wait()
if ret == 0:
ret = signal.SIGTERM << 8
killdaemons(env['DAEMON_PIDS'])
return ret
output = ''
proc.tochild.close()
try:
output = proc.fromchild.read()
except KeyboardInterrupt:
vlog('# Handling keyboard interrupt')
cleanup()
raise