1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347
|
#!/usr/bin/python3
#
# Copyright (c) 2022 Peter Pentchev <roam@ringlet.net>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
"""Run tox-delay from a temporary directory, examine its output."""
from __future__ import annotations
import argparse
import dataclasses
import os
import pathlib
import subprocess
import sys
import tempfile
import feature_check
import utf8_locale
TOX_ENVLIST = [
("fou$rth.", "fourth"),
("second", "second"),
("first", "first"),
("third", "third"),
]
TOX_ENVLIST_ORDERED = [TOX_ENVLIST[2], TOX_ENVLIST[1], TOX_ENVLIST[3], TOX_ENVLIST[0]]
assert len(TOX_ENVLIST_ORDERED) == len(TOX_ENVLIST)
TOX_INI = (
"""
[tox]
skipsdist = True
envlist =
"""
+ "\n".join(f" {name}" for name, _ in TOX_ENVLIST_ORDERED)
+ "".join(
f"""
[testenv:{name}]
commands =
python3 -c 'import sys; lst=["{tag}"] + sys.argv[1:] + ["thing-marker"]; print(" ".join(lst))' {{posargs}}
""" # noqa: E501 # pylint: disable=line-too-long
for name, tag in TOX_ENVLIST_ORDERED
)
)
@dataclasses.dataclass(frozen=True)
class Config:
"""Runtime configuration for the tox-delay functional test."""
executable: pathlib.Path | None
python: pathlib.Path
python_env: dict[str, str]
utf8_env: dict[str, str]
def parse_args() -> Config:
"""Parse the command-line options."""
def validate_python_path(python_path: str) -> str:
"""Split into components, make them absolute paths."""
components = []
for comp in python_path.split(":"):
if not comp:
sys.exit("No empty strings allowed in the Python path for now")
path = pathlib.Path(comp).absolute()
if not path.exists():
sys.exit(
f"No non-existent components like {path!r} allowed in the Python path for now"
)
components.append(path)
return ":".join(map(str, components))
parser = argparse.ArgumentParser(prog="tox-delay-functional-test")
parser.add_argument(
"-e",
"--executable",
type=str,
help="the program executable to run instead of python3 -m tox_delay",
)
parser.add_argument(
"-p", "--python", type=str, default="python3", help="the Python interpreter to use"
)
parser.add_argument(
"-P",
"--python-path",
type=str,
help="paths, if any, to prepend to PYTHONPATH to find tox-delay",
)
args = parser.parse_args()
utf8_env = utf8_locale.UTF8Detect().detect().env
print(f"Using UTF-8 settings: LC_ALL {utf8_env['LC_ALL']!r} LANGUAGE {utf8_env['LANGUAGE']!r}")
executable = None if args.executable is None else pathlib.Path(args.executable).absolute()
if executable is not None:
if not executable.is_file() or not os.access(executable, os.X_OK):
sys.exit(f"Not an executable file: {executable}")
python = args.python
print(f"Trying to find the absolute path to the {python} Python interpreter")
lines = subprocess.check_output(
[python, "-c", "import sys; print(sys.executable)"], encoding="UTF-8", env=utf8_env
).splitlines()
if len(lines) != 1:
sys.exit(f"Unexpected output from 'print sys.executable': {lines!r}")
ppython = pathlib.Path(lines[0])
if not ppython.is_absolute() or not ppython.is_file() or not os.access(ppython, os.X_OK):
sys.exit(f"Not an absolute path to an executable file: {ppython!r}")
python_env = dict(utf8_env)
if args.python_path is not None:
python_path = validate_python_path(args.python_path)
print(f"Converted {args.python_path!r} into {python_path!r}")
curpath = python_env.get("PYTHONPATH")
if curpath is None:
print("Using it as it is")
python_env["PYTHONPATH"] = python_path
else:
print(f"Combining it with {curpath!r}")
python_env["PYTHONPATH"] = ":".join((python_path, curpath))
if "PYTHONPATH" in python_env:
print(f"Using {python_env.get('PYTHONPATH')!r} as PYTHONPATH")
else:
print("Apparently there is no need to set PYTHONPATH at all")
return Config(executable=executable, python=ppython, python_env=python_env, utf8_env=utf8_env)
def check_tox_delay_features(cfg: Config, tempd: pathlib.Path) -> None:
"""Run `tox-delay --features`, look for a tox-delay one."""
def get_executable() -> pathlib.Path:
"""Make sure we have a single program to run."""
if cfg.executable is not None:
return cfg.executable
path = tempd / "tdelay"
print(f"Creating a {path} shell script")
if "PYTHONPATH" in cfg.python_env:
python_env = f"env PYTHONPATH='{cfg.python_env['PYTHONPATH']}'"
else:
python_env = ""
path.write_text(
f"""#!/bin/sh
exec {python_env} '{cfg.python}' -m tox_delay "$@"
""",
encoding="UTF-8",
)
path.chmod(0o755)
return path
tdelay = get_executable()
features = feature_check.obtain_features(str(tdelay))
tdver = features.get("tox-delay")
print(f"Got a tox-delay feature version {tdver!r}")
if tdver is None:
sys.exit("tox-delay did not report a 'tox-delay' feature")
if not tdver.startswith("0.1."):
sys.exit("tox-delay did not report a 'tox-delay' feature with a supported version")
def create_tox_ini(tempd: pathlib.Path) -> None:
"""Create the tox.ini file and show what we did there."""
path = tempd / "tox.ini"
path.write_text(TOX_INI, encoding="UTF-8")
print(f"Wrote something to {path}:")
print(path.read_text(encoding="UTF-8"))
def check_tox_output(
cfg: Config,
tempd: pathlib.Path,
tox: str,
envlist: list[tuple[str, str]],
*,
ignore: list[tuple[str, str]] | None = None,
order: list[tuple[str, str]] | None = None,
parallel: bool = False,
) -> None:
"""Run tox or tox-delay, check its output."""
envstr = ",".join(item[0] for item in envlist)
if tox == "tox" or cfg.executable is None:
tox_cmd = [str(cfg.python), "-m", tox]
tox_env = cfg.python_env
else:
tox_cmd = [str(cfg.executable)]
tox_env = cfg.utf8_env
def cmdline(args: list[str] | None = None) -> list[str]:
"""Build the command line to test."""
return (
tox_cmd
+ ["-e", envstr]
+ (["-i", ",".join(item[0] for item in ignore)] if ignore is not None else [])
+ (["-p", "all"] if parallel else [])
+ (["--"] + args if args is not None else [])
)
def check_output(args: list[str] | None = None) -> None:
"""Run the command and check its output."""
print(
f"\nRunning {tox} for {envstr}"
+ (" with arguments" if args is not None else "")
+ (" in parallel" if parallel else "")
+ " and examining its output\n"
)
cmd = cmdline(args)
print(cmd)
lines = subprocess.check_output(cmd, cwd=tempd, encoding="UTF-8", env=tox_env).splitlines()
found = [line for line in lines if line.endswith(" thing-marker")]
template = ([] if args is None else args) + ["thing-marker"]
expected = [
" ".join([item[1]] + template)
for item in (envlist if order is None or parallel else order)
]
if found != expected:
sys.exit(f"Unexpected tox -e {envstr} output: found {found!r} expected {expected!r}")
posargs = ["this", "and that"]
print(f"\nRunning {tox} for {envstr} without output capturing\n")
subprocess.run(
cmdline(),
check=True,
cwd=tempd,
env=tox_env,
)
subprocess.run(
cmdline(posargs),
check=True,
cwd=tempd,
env=tox_env,
)
check_output()
check_output(posargs)
def test_real_tox(cfg: Config, tempd: pathlib.Path) -> None:
"""Test a couple of actual Tox invocations."""
print("Making sure Tox itself works")
check_tox_output(cfg, tempd, "tox", TOX_ENVLIST)
def test_tox_delay(cfg: Config, tempd: pathlib.Path, parallel: bool) -> None:
"""Test a real tox-delay invocation."""
print(f"Testing tox-delay in {'' if parallel else 'non-'}parallel mode")
print("Let's see if it can run *all* the environments first")
check_tox_output(cfg, tempd, "tox_delay", TOX_ENVLIST)
print("Now let us delay some")
check_tox_output(
cfg,
tempd,
"tox_delay",
TOX_ENVLIST_ORDERED[1:3],
order=[
TOX_ENVLIST_ORDERED[0],
TOX_ENVLIST_ORDERED[3],
TOX_ENVLIST_ORDERED[1],
TOX_ENVLIST_ORDERED[2],
],
parallel=parallel,
)
print("Let us delay others")
check_tox_output(
cfg,
tempd,
"tox_delay",
[TOX_ENVLIST_ORDERED[2]],
order=[
TOX_ENVLIST_ORDERED[0],
TOX_ENVLIST_ORDERED[1],
TOX_ENVLIST_ORDERED[3],
TOX_ENVLIST_ORDERED[2],
],
parallel=parallel,
)
print("Ignore some environments")
check_tox_output(
cfg,
tempd,
"tox_delay",
[TOX_ENVLIST_ORDERED[2]],
order=[TOX_ENVLIST_ORDERED[0], TOX_ENVLIST_ORDERED[2]],
parallel=parallel,
ignore=[TOX_ENVLIST_ORDERED[1], TOX_ENVLIST_ORDERED[3]],
)
def main() -> None:
"""Main program: parse command-line options, run things."""
cfg = parse_args()
with tempfile.TemporaryDirectory() as tempd_obj:
tempd = pathlib.Path(tempd_obj)
print(f"Using {tempd} as a temporary directory")
check_tox_delay_features(cfg, tempd)
create_tox_ini(tempd)
test_real_tox(cfg, tempd)
test_tox_delay(cfg, tempd, False)
test_tox_delay(cfg, tempd, True)
print("Seems fine")
if __name__ == "__main__":
main()
|