Debian Codegraph @

tests/integration/test_manylinux.py

raw
1 from __future__ import annotations
2
3 import io
4 import json
5 import logging
6 import os
7 import re
8 import shutil
9 import sys
10 import zipfile
11 from contextlib import contextmanager
12 from pathlib import Path
13 from subprocess import CalledProcessError
14 from typing import TYPE_CHECKING, Any
15
16 import docker
17 import pytest
18
19 if TYPE_CHECKING:
20 from collections.abc import Generator
21
22 from docker.models.containers import Container
23 from elftools.elf.elffile import ELFFile
24
25 from auditwheel.architecture import Architecture
26 from auditwheel.libc import Libc
27 from auditwheel.policy import WheelPolicies
28
29 logger = logging.getLogger(__name__)
30
31 if "GITHUB_ACTIONS" in os.environ and sys.platform == "darwin":
32 pytest.skip("Docker is not available on GitHub Actions macOS runners", allow_module_level=True)
33
34 PLATFORM = os.environ.get("AUDITWHEEL_ARCH", Architecture.detect().value)
35 MANYLINUX2010_IMAGE_ID = f"quay.io/pypa/manylinux2010_{PLATFORM}:latest"
36 MANYLINUX2014_IMAGE_ID = f"quay.io/pypa/manylinux2014_{PLATFORM}:latest"
37 MANYLINUX_2_28_IMAGE_ID = f"quay.io/pypa/manylinux_2_28_{PLATFORM}:latest"
38 MANYLINUX_2_31_IMAGE_ID = f"quay.io/pypa/manylinux_2_31_{PLATFORM}:latest"
39 MANYLINUX_2_34_IMAGE_ID = f"quay.io/pypa/manylinux_2_34_{PLATFORM}:latest"
40 MANYLINUX_2_35_IMAGE_ID = f"quay.io/pypa/manylinux_2_35_{PLATFORM}:latest"
41 MANYLINUX_2_39_IMAGE_ID = f"quay.io/pypa/manylinux_2_39_{PLATFORM}:latest"
42 if PLATFORM in {"i686", "x86_64"}:
43 MANYLINUX_IMAGES = {
44 "manylinux_2_12": MANYLINUX2010_IMAGE_ID,
45 "manylinux_2_17": MANYLINUX2014_IMAGE_ID,
46 "manylinux_2_28": MANYLINUX_2_28_IMAGE_ID,
47 "manylinux_2_34": MANYLINUX_2_34_IMAGE_ID,
48 }
49 POLICY_ALIASES = {
50 "manylinux_2_5": ["manylinux1"],
51 "manylinux_2_12": ["manylinux2010"],
52 "manylinux_2_17": ["manylinux2014"],
53 }
54 elif PLATFORM == "armv7l":
55 MANYLINUX_IMAGES = {
56 "manylinux_2_31": MANYLINUX_2_31_IMAGE_ID,
57 "manylinux_2_35": MANYLINUX_2_35_IMAGE_ID,
58 }
59 POLICY_ALIASES = {}
60 elif PLATFORM == "riscv64":
61 MANYLINUX_IMAGES = {"manylinux_2_39": MANYLINUX_2_39_IMAGE_ID}
62 POLICY_ALIASES = {}
63 else:
64 MANYLINUX_IMAGES = {
65 "manylinux_2_17": MANYLINUX2014_IMAGE_ID,
66 "manylinux_2_28": MANYLINUX_2_28_IMAGE_ID,
67 }
68 if os.environ.get("AUDITWHEEL_QEMU", "") != "true":
69 MANYLINUX_IMAGES.update({"manylinux_2_34": MANYLINUX_2_34_IMAGE_ID})
70 if PLATFORM == "aarch64":
71 MANYLINUX_IMAGES.update({"manylinux_2_39": MANYLINUX_2_39_IMAGE_ID})
72 POLICY_ALIASES = {
73 "manylinux_2_17": ["manylinux2014"],
74 }
75 DOCKER_CONTAINER_NAME = "auditwheel-test-anylinux"
76 PYTHON_MAJ_MIN = [str(i) for i in sys.version_info[:2]]
77 PYTHON_ABI_MAJ_MIN = "".join(PYTHON_MAJ_MIN)
78 PYTHON_ABI = f"cp{PYTHON_ABI_MAJ_MIN}-cp{PYTHON_ABI_MAJ_MIN}"
79 PYTHON_IMAGE_TAG = ".".join(PYTHON_MAJ_MIN) + ("-rc" if PYTHON_ABI_MAJ_MIN == "314" else "")
80 MANYLINUX_PYTHON_IMAGE_ID = f"python:{PYTHON_IMAGE_TAG}-slim-trixie"
81 MUSLLINUX_IMAGES = {
82 "musllinux_1_2": f"quay.io/pypa/musllinux_1_2_{PLATFORM}:latest",
83 }
84 MUSLLINUX_PYTHON_IMAGE_ID = f"python:{PYTHON_IMAGE_TAG}-alpine"
85 DEVTOOLSET = {
86 "manylinux_2_12": "devtoolset-8",
87 "manylinux_2_17": "devtoolset-10",
88 "manylinux_2_28": "gcc-toolset-14",
89 "manylinux_2_31": "devtoolset-not-present",
90 "manylinux_2_34": "gcc-toolset-14",
91 "manylinux_2_35": "devtoolset-not-present",
92 "manylinux_2_39": "devtoolset-not-present",
93 "musllinux_1_2": "devtoolset-not-present",
94 }
95 PATH_DIRS = [
96 f"/opt/python/{PYTHON_ABI}/bin",
97 "/opt/rh/{devtoolset}/root/usr/bin",
98 "/usr/local/sbin",
99 "/usr/local/bin",
100 "/usr/sbin",
101 "/usr/bin",
102 "/sbin",
103 "/bin",
104 ]
105 PATH = {k: ":".join(PATH_DIRS).format(devtoolset=v) for k, v in DEVTOOLSET.items()}
106 WHEEL_CACHE_FOLDER = Path.home().joinpath(".cache", "auditwheel_tests")
107 HERE = Path(__file__).parent.resolve(strict=True)
108 NUMPY_VERSION_MAP = {
109 "310": "1.21.4",
110 "311": "1.23.4",
111 "312": "1.26.4",
112 "313": "2.0.1",
113 "314": "2.3.2",
114 }
115 NUMPY_VERSION = NUMPY_VERSION_MAP[PYTHON_ABI_MAJ_MIN]
116 ORIGINAL_NUMPY_WHEEL = f"numpy-{NUMPY_VERSION}-{PYTHON_ABI}-linux_{PLATFORM}.whl"
117 SHOW_RE = re.compile(
118 r'.*[\s](?P<wheel>\S+) is consistent with the following platform tag: "(?P<tag>\S+)".*',
119 flags=re.DOTALL,
120 )
121 TAG_RE = re.compile(r"^manylinux_(?P<major>[0-9]+)_(?P<minor>[0-9]+)_(?P<arch>\S+)$")
122
123
124 class AnyLinuxContainer:
125 def __init__(self, policy: str, tag: str, container: Container, io_folder: Path):
126 self._policy = policy
127 self._tag = tag
128 self._container = container
129 self._io_folder = io_folder
130
131 @property
132 def policy(self):
133 return self._policy
134
135 @property
136 def io_folder(self):
137 return self._io_folder
138
139 def exec(
140 self,
141 cmd: str | list[str],
142 *,
143 expected_retcode: int = 0,
144 cwd: str | None = None,
145 env: dict[str, str] | None = None,
146 coverage: bool = False,
147 ) -> str:
148 return docker_exec(
149 self._container,
150 cmd,
151 expected_retcode=expected_retcode,
152 cwd=cwd,
153 env=env,
154 coverage=coverage,
155 )
156
157 def show(
158 self,
159 wheel: str,
160 *,
161 verbose: bool = False,
162 isa_ext_check: bool = True,
163 expected_retcode: int = 0,
164 ) -> str:
165 isa_ext_check_arg = "" if isa_ext_check else "--disable-isa-ext-check"
166 verbose_arg = "-v" if verbose else ""
167 cmd = f"auditwheel {verbose_arg} show {isa_ext_check_arg} /io/{wheel}"
168 return self.exec(cmd, expected_retcode=expected_retcode, coverage=True)
169
170 def repair(
171 self,
172 wheel: str,
173 *,
174 isa_ext_check: bool = True,
175 expected_retcode: int = 0,
176 plat: str | None = None,
177 only_plat: bool = True,
178 strip: bool = False,
179 library_paths: list[str] | None = None,
180 excludes: list[str] | None = None,
181 ) -> str:
182 plat = plat or self._policy
183 args = []
184 if library_paths:
185 ld_library_path = ":".join([*library_paths, "$LD_LIBRARY_PATH"])
186 args.append(f"LD_LIBRARY_PATH={ld_library_path}")
187 args.extend(["auditwheel", "repair", "-w", "/io", "--plat", plat])
188 if only_plat:
189 args.append("--only-plat")
190 if not isa_ext_check:
191 args.append("--disable-isa-ext-check")
192 if strip:
193 args.append("--strip")
194 if excludes:
195 args.extend(f"--exclude={exclude}" for exclude in excludes)
196 args.append(f"/io/{wheel}")
197 cmd = ["bash", "-c", " ".join(args)]
198 return self.exec(cmd, expected_retcode=expected_retcode, coverage=True)
199
200 def build_wheel(
201 self,
202 path: str,
203 *,
204 pre_wheel_cmd: str | None = None,
205 env: dict[str, str] | None = None,
206 check_filename: bool = True,
207 ) -> str:
208 args = ["if [ -d ./build ]; then rm -rf ./build ./*.egg-info; fi"]
209 if pre_wheel_cmd:
210 args.append(pre_wheel_cmd)
211 args.append("python -m pip wheel --no-deps -w /io .")
212 cmd = " && ".join(args)
213 self.exec(["bash", "-c", cmd], cwd=path, env=env)
214
215 filenames = os.listdir(self._io_folder)
216 assert len(filenames) == 1
217 orig_wheel = filenames[0]
218 if check_filename:
219 assert orig_wheel.endswith(f"-{PYTHON_ABI}-linux_{PLATFORM}.whl")
220 assert "manylinux" not in orig_wheel
221 assert "musllinux" not in orig_wheel
222 return orig_wheel
223
224 def check_wheel(
225 self,
226 name: str,
227 *,
228 version: str | None = None,
229 python_abi: str | None = None,
230 platform_tag: str | None = None,
231 ) -> str:
232 version = version or "0.0.1"
233 python_abi = python_abi or PYTHON_ABI
234 platform_tag = platform_tag or self._tag
235 repaired_wheel = f"{name}-{version}-{python_abi}-{platform_tag}.whl"
236 filenames = os.listdir(self._io_folder)
237 assert len(filenames) == 2
238 assert repaired_wheel in filenames
239 return repaired_wheel
240
241 @property
242 def cache_dir(self) -> Path:
243 return WHEEL_CACHE_FOLDER / self._policy
244
245
246 class PythonContainer:
247 def __init__(self, container: Container):
248 self._container = container
249
250 def pip_install(self, args: str) -> str:
251 cmd = f"pip install {args}"
252 return self.exec(cmd)
253
254 def install_wheel(self, filename: str) -> str:
255 return self.pip_install(f"/io/{filename}")
256
257 def run(self, cmd: str, *, env: dict[str, str] | None = None) -> str:
258 args = ["python", "-c", cmd] if cmd.startswith(("from ", "import ")) else f"python {cmd}"
259 return self.exec(args, env=env)
260
261 def exec(
262 self,
263 cmd: str | list[str],
264 expected_retcode: int = 0,
265 env: dict[str, str] | None = None,
266 ) -> str:
267 return docker_exec(
268 self._container,
269 cmd,
270 expected_retcode=expected_retcode,
271 env=env,
272 )
273
274
275 def find_src_folder() -> Path | None:
276 candidate = HERE.parent.parent.resolve(strict=True)
277 contents = os.listdir(candidate)
278 if "pyproject.toml" in contents and "src" in contents:
279 return candidate
280 return None
281
282
283 def docker_start(
284 image: str,
285 volumes: dict[str, str] | None = None,
286 env_variables: dict[str, str] | None = None,
287 ) -> Container:
288 """Start a long waiting idle program in container
289
290 Return the container object to be used for 'docker exec' commands.
291 """
292 # Make sure to use the latest public version of the docker image
293 if env_variables is None:
294 env_variables = {}
295 if volumes is None:
296 volumes = {}
297 client = docker.from_env()
298
299 dvolumes = {host: {"bind": ctr, "mode": "rw"} for (ctr, host) in volumes.items()}
300 goarch = {
301 "x86_64": "amd64",
302 "i686": "386",
303 "aarch64": "arm64",
304 "armv7l": "arm/v7",
305 }.get(PLATFORM, PLATFORM)
306
307 logger.info("Starting container with image %r", image)
308 con = client.containers.run(
309 image,
310 ["tail", "-f", "/dev/null"],
311 detach=True,
312 volumes=dvolumes,
313 environment=env_variables,
314 platform=f"linux/{goarch}",
315 working_dir="/auditwheel_src" if "/auditwheel_src" in volumes else None,
316 )
317 assert isinstance(con.id, str)
318 logger.info("Started container %s", con.id[:12])
319 return con
320
321
322 @contextmanager
323 def docker_container_ctx(
324 image: str,
325 io_dir: Path | None = None,
326 env_variables: dict[str, str] | None = None,
327 ) -> Generator[Container, None, None]:
328 src_folder = find_src_folder()
329 if src_folder is None:
330 pytest.skip("Can only be run from the source folder")
331 assert src_folder is not None
332
333 if env_variables is None:
334 env_variables = {}
335 vols = {"/auditwheel_src": str(src_folder)}
336 if io_dir is not None:
337 vols["/io"] = str(io_dir)
338
339 container = docker_start(image, vols, env_variables)
340 try:
341 yield container
342 finally:
343 container.remove(force=True)
344
345
346 def docker_exec(
347 container: Container,
348 cmd: str | list[str],
349 *,
350 expected_retcode: int = 0,
351 cwd: str | None = None,
352 env: dict[str, str] | None = None,
353 coverage: bool = False,
354 ) -> str:
355 assert isinstance(container.id, str)
356 logger.info("docker exec %s: %r", container.id[:12], cmd)
357 # coverage is too slow with QEMU, even more so on ppc64le & s390x which lack a
358 # C extension.
359 # only enable coverage when QEMU is not enabled.
360 if coverage and os.environ.get("AUDITWHEEL_QEMU", "") != "true":
361 env = env.copy() if env is not None else {}
362 env["COVERAGE_PROCESS_START"] = "/auditwheel_src/pyproject.toml"
363 ec, raw_output = container.exec_run(cmd, workdir=cwd, environment=env)
364 assert isinstance(raw_output, bytes)
365 output = raw_output.decode("utf-8")
366 assert isinstance(ec, int)
367 if ec != expected_retcode:
368 logger.info("docker exec error %s: %s", container.id[:12], output)
369 raise CalledProcessError(ec, cmd, output=output)
370 return output
371
372
373 @contextmanager
374 def tmp_docker_image(
375 base: str,
376 commands: list[str],
377 setup_env: dict[str, str] | None = None,
378 ) -> Generator[Any, None, None]:
379 """Make a temporary docker image for tests
380
381 Pulls the *base* image, runs *commands* inside it with *setup_env*, and
382 commits the result as a new image. The image is removed on exiting the
383 context.
384
385 Making temporary images like this avoids each test having to re-run the
386 same container setup steps.
387 """
388 if setup_env is None:
389 setup_env = {}
390 with docker_container_ctx(base, env_variables=setup_env) as con:
391 for cmd in commands:
392 docker_exec(con, cmd)
393 image = con.commit()
394
395 logger.info("Made image %s based on %s", image.short_id, base)
396 try:
397 yield image.id
398 finally:
399 client = image.client
400 assert client is not None
401 client.images.remove(image.id)
402
403
404 def assert_show_output(
405 anylinux_ctr: AnyLinuxContainer,
406 wheel: str,
407 expected_tag: str,
408 strict: bool,
409 isa_ext_check: bool = True,
410 ) -> None:
411 output = anylinux_ctr.show(wheel, isa_ext_check=isa_ext_check)
412 output = output.replace("\n", " ")
413 match = SHOW_RE.match(output)
414 assert match, f"{SHOW_RE.pattern!r} not found in:\n{output}"
415 assert match["wheel"] == wheel
416 if strict or "musllinux" in expected_tag:
417 assert match["tag"] == expected_tag
418 else:
419 expected_match = TAG_RE.match(expected_tag)
420 assert expected_match, f"No match for tag {expected_tag}"
421 expected_glibc = (int(expected_match["major"]), int(expected_match["minor"]))
422 actual_match = TAG_RE.match(match["tag"])
423 assert actual_match, f"No match for tag {match['tag']}"
424 actual_glibc = (int(actual_match["major"]), int(actual_match["minor"]))
425 assert expected_match["arch"] == actual_match["arch"]
426 assert actual_glibc <= expected_glibc
427
428
429 def build_numpy(container: AnyLinuxContainer, output_dir: Path) -> str:
430 """Helper to build numpy from source using the specified container, into
431 output_dir.
432 """
433 if container.policy.startswith("musllinux_"):
434 container.exec("apk add openblas-dev")
435 if container.policy.endswith("_s390x"):
436 # https://github.com/numpy/numpy/issues/27932
437 fix_hwcap = "echo '#define HWCAP_S390_VX 2048' >> /usr/include/bits/hwcap.h"
438 container.exec(f'sh -c "{fix_hwcap}"')
439 elif container.policy.startswith(("manylinux_2_12_", "manylinux_2_17_")):
440 if tuple(int(part) for part in NUMPY_VERSION.split(".")[:2]) >= (1, 26):
441 pytest.skip("numpy>=1.26 requires openblas")
442 container.exec("yum install -y atlas atlas-devel")
443 elif container.policy.startswith(("manylinux_2_31_", "manylinux_2_35_")):
444 container.exec("apt-get install -y libopenblas-dev execstack")
445 # TODO auditwheel shall check for executable stack:
446 # https://github.com/pypa/auditwheel/issues/634
447 container.exec(
448 ["bash", "-c", "execstack -c $(find /usr/lib* -name 'libopenblas*.so')"],
449 )
450 else:
451 container.exec("dnf install -y openblas-devel")
452
453 cached_wheel = container.cache_dir / ORIGINAL_NUMPY_WHEEL
454 orig_wheel = output_dir / ORIGINAL_NUMPY_WHEEL
455 if cached_wheel.exists():
456 # If numpy has already been built and put in cache, let's reuse this.
457 shutil.copy2(cached_wheel, orig_wheel)
458 else:
459 # otherwise build the original linux_x86_64 numpy wheel from source
460 # and put the result in the cache folder to speed-up future build.
461 # This part of the build is independent of the auditwheel code-base
462 # so it's safe to put it in cache.
463 container.exec(f"pip wheel -w /io --no-binary=numpy numpy=={NUMPY_VERSION}")
464 cached_wheel.parent.mkdir(parents=True, exist_ok=True)
465 shutil.copy2(orig_wheel, cached_wheel)
466 return orig_wheel.name
467
468
469 class Anylinux:
470 @pytest.fixture
471 def io_folder(self, tmp_path):
472 d = tmp_path / "io"
473 d.mkdir(exist_ok=True)
474 return d
475
476 @pytest.fixture
477 def python(
478 self,
479 docker_python_img: str,
480 io_folder: Path,
481 ) -> Generator[PythonContainer, None, None]:
482 with docker_container_ctx(docker_python_img, io_folder) as container:
483 yield PythonContainer(container)
484
485 @pytest.fixture
486 def anylinux(
487 self,
488 any_manylinux_img: tuple[str, str],
489 io_folder: Path,
490 ) -> Generator[AnyLinuxContainer, None, None]:
491 policy, manylinux_img = any_manylinux_img
492 env = {"PATH": PATH[policy]}
493 with docker_container_ctx(manylinux_img, io_folder, env) as container:
494 platform_tag = ".".join(
495 sorted(
496 [f"{p}_{PLATFORM}" for p in [policy, *POLICY_ALIASES.get(policy, [])]],
497 ),
498 )
499 yield AnyLinuxContainer(
500 f"{policy}_{PLATFORM}",
501 platform_tag,
502 container,
503 io_folder,
504 )
505
506 def test_numpy(self, anylinux: AnyLinuxContainer, python: PythonContainer) -> None:
507 # Integration test: repair numpy built from scratch
508 policy = anylinux.policy
509
510 # First build numpy from source as a naive linux wheel that is tied
511 # to system libraries (blas, libgfortran...)
512 orig_wheel = build_numpy(anylinux, anylinux.io_folder)
513 assert orig_wheel == ORIGINAL_NUMPY_WHEEL
514 assert "manylinux" not in orig_wheel
515
516 # Repair the wheel using the manylinux container
517 anylinux.repair(orig_wheel)
518 repaired_wheel = anylinux.check_wheel("numpy", version=NUMPY_VERSION)
519 assert_show_output(anylinux, repaired_wheel, policy, False)
520
521 # Check that the repaired numpy wheel can be installed and executed
522 # on a modern linux image.
523 python.install_wheel(repaired_wheel)
524 output = python.run("/auditwheel_src/tests/integration/quick_check_numpy.py")
525 assert output.strip() == "ok"
526
527 # Check that numpy f2py works with a more recent version of gfortran
528 if policy.startswith("musllinux_"):
529 python.exec("apk add musl-dev gfortran")
530 else:
531 python.exec("apt-get install -y gfortran")
532 if tuple(int(part) for part in NUMPY_VERSION.split(".")[:2]) >= (1, 26):
533 python.pip_install("meson ninja")
534 f2py_env = None
535 else:
536 f2py_env = {"SETUPTOOLS_USE_DISTUTILS": "stdlib"}
537 python.run(
538 "-m numpy.f2py -c /auditwheel_src/tests/integration/foo.f90 -m foo",
539 env=f2py_env,
540 )
541
542 # Check that the 2 fortran runtimes are well isolated and can be loaded
543 # at once in the same Python program:
544 python.run("import numpy; import foo")
545
546 def test_numpy_sbom(
547 self,
548 anylinux: AnyLinuxContainer,
549 python: PythonContainer,
550 ) -> None:
551 policy = anylinux.policy
552 if policy.startswith("manylinux_2_12_"):
553 pytest.skip(f"whichprovides doesn't support {policy}")
554
555 # Build and repair numpy
556 orig_wheel = build_numpy(anylinux, anylinux.io_folder)
557 assert orig_wheel == ORIGINAL_NUMPY_WHEEL
558 assert "manylinux" not in orig_wheel
559
560 # Repair the wheel using the manylinux container
561 anylinux.repair(orig_wheel)
562 repaired_wheel = anylinux.check_wheel("numpy", version=NUMPY_VERSION)
563 assert_show_output(anylinux, repaired_wheel, policy, False)
564
565 # Install the wheel so the SBOM document is added to the environment.
566 python.install_wheel(repaired_wheel)
567
568 # Load the auditwheel SBOM from .dist-info/sboms
569 site_packages = python.run(
570 "import site; print(site.getsitepackages()[0])",
571 ).strip()
572 assert re.match(
573 r"\A/usr/local/lib/python[0-9.]+/site-packages\Z",
574 site_packages,
575 )
576 sbom_data = python.run(
577 f"-c \"print(open('{site_packages}/numpy-{NUMPY_VERSION}.dist-info/sboms/auditwheel.cdx.json').read())\"", # noqa: E501
578 ).strip()
579 sbom = json.loads(sbom_data)
580
581 # Separate all the components that vary over test runs.
582 sbom_tools = sbom["metadata"].pop("tools")
583 sbom_components = sbom.pop("components")
584 sbom_dependencies = sbom.pop("dependencies")
585
586 expected_numpy_purl = f"pkg:pypi/numpy@{NUMPY_VERSION}?file_name={repaired_wheel}"
587 assert sbom == {
588 "bomFormat": "CycloneDX",
589 "specVersion": "1.4",
590 "version": 1,
591 "metadata": {
592 "component": {
593 "type": "library",
594 "bom-ref": expected_numpy_purl,
595 "name": "numpy",
596 "version": NUMPY_VERSION,
597 "purl": expected_numpy_purl,
598 },
599 # "tools": [{...}, ...],
600 },
601 # "components": [{...}, ...],
602 # "dependencies": [{...}, ...],
603 }
604
605 assert len(sbom_tools) == 1
606 assert sbom_tools[0]["name"] == "auditwheel"
607 assert "version" in sbom_tools[0]
608
609 assert sbom_components[0] == {
610 "bom-ref": expected_numpy_purl,
611 "name": "numpy",
612 "purl": expected_numpy_purl,
613 "type": "library",
614 "version": NUMPY_VERSION,
615 }
616
617 component_purls = {component["purl"].split("@")[0] for component in sbom_components[1:]}
618 # Package URL prefixes must match for a policy.
619 if policy.startswith("musllinux"):
620 expected_purl_prefix = "pkg:apk/alpine/"
621 elif policy.startswith("manylinux_2_17_"):
622 expected_purl_prefix = "pkg:rpm/centos/"
623 elif policy.startswith(("manylinux_2_31_", "manylinux_2_35_")):
624 expected_purl_prefix = "pkg:deb/ubuntu/"
625 elif policy == "manylinux_2_39_riscv64":
626 expected_purl_prefix = "pkg:rpm/rocky/"
627 else:
628 expected_purl_prefix = "pkg:rpm/almalinux/"
629
630 assert all(purl.startswith(expected_purl_prefix) for purl in component_purls), str(
631 component_purls,
632 )
633
634 # We expect libgfortran and openblas* (aka atlas) as dependencies.
635 if policy != "musllinux_1_2_riscv64":
636 assert any("libgfortran" in purl for purl in component_purls), str(
637 component_purls,
638 )
639 assert any("openblas" in purl for purl in component_purls) or any(
640 "atlas" in purl for purl in component_purls
641 ), str(component_purls)
642
643 assert len(sbom_dependencies) == len(component_purls) + 1
644
645 def test_exclude(self, anylinux: AnyLinuxContainer) -> None:
646 """Test the --exclude argument to avoid grafting certain libraries."""
647 test_path = "/auditwheel_src/tests/integration/testrpath"
648 orig_wheel = anylinux.build_wheel(test_path)
649
650 output = anylinux.repair(
651 orig_wheel,
652 excludes=["liba.so"],
653 library_paths=[f"{test_path}/a"],
654 )
655 assert "Excluding liba.so" in output
656 repaired_wheel = anylinux.check_wheel("testrpath")
657
658 # Make sure we don't have liba.so & libb.so in the result
659 contents = zipfile.ZipFile(anylinux.io_folder / repaired_wheel).namelist()
660 assert not any(x for x in contents if "/liba" in x or "/libb" in x)
661
662 def test_with_binary_executable(
663 self,
664 anylinux: AnyLinuxContainer,
665 python: PythonContainer,
666 ) -> None:
667 # Test building a wheel that contains a binary executable (e.g., a program)
668 policy = anylinux.policy
669 if policy.startswith("musllinux_"):
670 anylinux.exec("apk add gsl-dev")
671 elif policy.startswith(("manylinux_2_31_", "manylinux_2_35_")):
672 anylinux.exec("apt-get install -y libgsl-dev")
673 elif policy == "manylinux_2_39_riscv64":
674 pytest.skip(reason=f"no gsl-devel on {policy}")
675 else:
676 anylinux.exec("yum install -y gsl-devel")
677
678 test_path = "/auditwheel_src/tests/integration/testpackage"
679 orig_wheel = anylinux.build_wheel(test_path, check_filename=False)
680 assert orig_wheel == "testpackage-0.0.1-py3-none-any.whl"
681
682 # manylinux_2_34_x86_64 uses x86_64_v2 for this test
683 isa_ext_check = policy != "manylinux_2_34_x86_64"
684
685 # Repair the wheel using the appropriate manylinux container
686 anylinux.repair(orig_wheel, isa_ext_check=isa_ext_check)
687 repaired_wheel = anylinux.check_wheel("testpackage", python_abi="py3-none")
688 assert_show_output(anylinux, repaired_wheel, policy, False, isa_ext_check)
689
690 python.install_wheel(repaired_wheel)
691 output = python.run("from testpackage import runit; print(runit(1.5))")
692 assert output.strip() == "2.25"
693
694 # Both testprogram and testprogram_nodeps square a number, but:
695 # * testprogram links against libgsl and had to have its RPATH
696 # rewritten.
697 # * testprogram_nodeps links against no shared libraries and wasn't
698 # rewritten.
699 #
700 # Both executables should work when called from the installed bin directory.
701 assert python.exec(["/usr/local/bin/testprogram", "4"]) == "16\n"
702 assert python.exec(["/usr/local/bin/testprogram_nodeps", "4"]) == "16\n"
703
704 # testprogram should be a Python shim since we had to rewrite its RPATH.
705 shebang = python.exec(["head", "-n1", "/usr/local/bin/testprogram"])
706 assert shebang in {
707 "#!/usr/local/bin/python\n",
708 "#!/usr/local/bin/python3\n",
709 f"#!/usr/local/bin/python{'.'.join(PYTHON_MAJ_MIN)}\n",
710 }
711
712 # testprogram_nodeps should be the unmodified ELF binary.
713 assert python.exec(["head", "-c4", "/usr/local/bin/testprogram_nodeps"]) == "\x7fELF"
714
715 def test_pure_wheel(self, anylinux: AnyLinuxContainer) -> None:
716 anylinux.exec(
717 "pip download --no-deps -d /io --only-binary=:all: six==1.16.0",
718 )
719 orig_wheel = "six-1.16.0-py2.py3-none-any.whl"
720 assert anylinux.io_folder.joinpath(orig_wheel).exists()
721
722 # Repair the wheel using the manylinux container
723 output = anylinux.repair(orig_wheel, expected_retcode=1)
724 assert "This does not look like a platform wheel" in output
725
726 output = anylinux.show(orig_wheel, expected_retcode=1)
727 assert "This does not look like a platform wheel" in output
728
729 @pytest.mark.parametrize("dtag", ["none", "rpath", "runpath"])
730 def test_rpath(
731 self,
732 anylinux: AnyLinuxContainer,
733 python: PythonContainer,
734 dtag: str,
735 ) -> None:
736 # Test building a wheel that contains an extension depending on a library
737 # with RPATH or RUNPATH set.
738 # Following checks are performed:
739 # - check if RUNPATH is replaced by RPATH if the library has other grafted deps
740 # - check if RPATH location is correct, i.e. it is inside .libs directory
741 # where all gathered libraries are put
742 # - check a library with no deps has no RUNPATH/RPATH tags
743
744 policy = anylinux.policy
745
746 test_path = "/auditwheel_src/tests/integration/testrpath"
747 orig_wheel = anylinux.build_wheel(test_path, env={"DTAG": dtag})
748
749 for lib in ["a", "b"]:
750 with HERE.joinpath("testrpath", lib, f"lib{lib}.so").open("rb") as f:
751 elf = ELFFile(f)
752 dynamic = elf.get_section_by_name(".dynamic")
753 tags = {t.entry.d_tag for t in dynamic.iter_tags()}
754 if dtag != "none":
755 assert f"DT_{dtag.upper()}" in tags
756 else:
757 assert "DT_RPATH" not in tags
758 assert "DT_RUNPATH" not in tags
759
760 # Repair the wheel using the appropriate manylinux container
761 library_paths = [f"{test_path}/a"]
762 if dtag == "none":
763 library_paths.append(f"{test_path}/b")
764 anylinux.repair(orig_wheel, library_paths=library_paths)
765 repaired_wheel = anylinux.check_wheel("testrpath")
766 assert_show_output(anylinux, repaired_wheel, policy, False)
767
768 python.install_wheel(repaired_wheel)
769 output = python.run("from testrpath import testrpath; print(testrpath.func())")
770 assert output.strip() == "11"
771 with zipfile.ZipFile(anylinux.io_folder / repaired_wheel) as w:
772 libraries = tuple(name for name in w.namelist() if "testrpath.libs/lib" in name)
773 assert len(libraries) == 2
774 assert any(".libs/liba" in name for name in libraries)
775 assert any(".libs/libb" in name for name in libraries)
776 for name in libraries:
777 with w.open(name) as f:
778 elf = ELFFile(io.BytesIO(f.read()))
779 dynamic = elf.get_section_by_name(".dynamic")
780 # DT_RUNPATH shall be removed
781 runpath_tags = [t for t in dynamic.iter_tags() if t.entry.d_tag == "DT_RUNPATH"]
782 assert len(runpath_tags) == 0
783 rpath_tags = [t for t in dynamic.iter_tags() if t.entry.d_tag == "DT_RPATH"]
784 if ".libs/liba" in name:
785 # liba has a dependency on libb
786 # DT_RPATH shall be overridden or written with "$ORIGIN"
787 assert len(rpath_tags) == 1
788 assert rpath_tags[0].rpath == "$ORIGIN"
789 if ".libs/libb" in name:
790 # libb has no dependency
791 # DT_RPATH shall be removed
792 assert len(rpath_tags) == 0
793
794 def test_partialresolution(self, anylinux: AnyLinuxContainer, python: PythonContainer) -> None:
795
796 policy = anylinux.policy
797
798 test_path = "/auditwheel_src/tests/integration/testpartialresolution"
799 orig_wheel = anylinux.build_wheel(test_path)
800
801 # Repair the wheel using the appropriate manylinux container
802 anylinux.repair(orig_wheel)
803 repaired_wheel = anylinux.check_wheel("testpartialresolution")
804 assert_show_output(anylinux, repaired_wheel, policy, False)
805
806 python.install_wheel(repaired_wheel)
807 output = python.run(
808 "from testpartialresolution import testpartialresolution;"
809 "print(testpartialresolution.func())",
810 )
811 assert output.strip() == "11"
812
813 with zipfile.ZipFile(anylinux.io_folder / repaired_wheel) as w:
814 libraries = tuple(name for name in w.namelist() if "testpartialresolution/lib" in name)
815 assert len(libraries) == 2
816 for name in libraries:
817 with w.open(name) as f:
818 elf = ELFFile(io.BytesIO(f.read()))
819 dynamic = elf.get_section_by_name(".dynamic")
820 runpath_tags = [t for t in dynamic.iter_tags() if t.entry.d_tag == "DT_RUNPATH"]
821 assert len(runpath_tags) == 0
822 rpath_tags = [t for t in dynamic.iter_tags() if t.entry.d_tag == "DT_RPATH"]
823 assert len(rpath_tags) == 0
824
825 def test_multiple_top_level(
826 self,
827 anylinux: AnyLinuxContainer,
828 python: PythonContainer,
829 ) -> None:
830 policy = anylinux.policy
831
832 test_path = "/auditwheel_src/tests/integration/multiple_top_level"
833 orig_wheel = anylinux.build_wheel(test_path, pre_wheel_cmd="make clean all")
834
835 # Repair the wheel using the appropriate manylinux container
836 anylinux.repair(
837 orig_wheel,
838 library_paths=[f"{test_path}/lib-src/a", f"{test_path}/lib-src/b"],
839 )
840 repaired_wheel = anylinux.check_wheel("multiple_top_level")
841 assert_show_output(anylinux, repaired_wheel, policy, False)
842
843 python.install_wheel(repaired_wheel)
844 for mod, func, expected in [
845 ("example_a", "example_a", "11"),
846 ("example_b", "example_b", "110"),
847 ]:
848 output = python.run(f"from {mod} import {func}; print({func}())").strip()
849 assert output.strip() == expected
850 with zipfile.ZipFile(anylinux.io_folder / repaired_wheel) as w:
851 for lib_name in ["liba", "libb"]:
852 assert any(
853 re.match(rf"multiple_top_level.libs/{lib_name}.*\.so", name)
854 for name in w.namelist()
855 )
856
857 def test_internal_rpath(
858 self,
859 anylinux: AnyLinuxContainer,
860 python: PythonContainer,
861 ) -> None:
862 policy = anylinux.policy
863
864 test_path = "/auditwheel_src/tests/integration/internal_rpath"
865 orig_wheel = anylinux.build_wheel(
866 test_path,
867 pre_wheel_cmd="make clean all && mv lib-src/a/liba.so internal_rpath",
868 )
869
870 # Repair the wheel using the appropriate manylinux container
871 anylinux.repair(orig_wheel, library_paths=[f"{test_path}/lib-src/b"])
872 repaired_wheel = anylinux.check_wheel("internal_rpath")
873 assert_show_output(anylinux, repaired_wheel, policy, False)
874
875 python.install_wheel(repaired_wheel)
876 for mod, func, expected in [
877 ("example_a", "example_a", "11"),
878 ("example_b", "example_b", "10"),
879 ]:
880 output = python.run(
881 f"from internal_rpath.{mod} import {func}; print({func}())",
882 )
883 assert output.strip() == expected
884 with zipfile.ZipFile(anylinux.io_folder / repaired_wheel) as w:
885 for lib_name in ["libb"]:
886 assert any(
887 re.match(rf"internal_rpath.libs/{lib_name}.*\.so", name)
888 for name in w.namelist()
889 )
890
891 def test_strip(self, anylinux: AnyLinuxContainer, python: PythonContainer) -> None:
892 policy = anylinux.policy
893
894 test_path = "/auditwheel_src/tests/integration/sample_extension"
895 orig_wheel = anylinux.build_wheel(test_path)
896 assert orig_wheel.startswith("sample_extension-0.1.0")
897
898 # Repair the wheel using the appropriate manylinux container
899 anylinux.repair(orig_wheel, strip=True)
900
901 repaired_wheel = next(anylinux.io_folder.glob(f"*{policy}*.whl")).name
902
903 python.install_wheel(repaired_wheel)
904 output = python.run(
905 "from sample_extension import test_func; print(test_func(1))",
906 )
907 assert output.strip() == "2"
908
909 def test_nonpy_rpath(
910 self,
911 anylinux: AnyLinuxContainer,
912 python: PythonContainer,
913 ) -> None:
914 # Tests https://github.com/pypa/auditwheel/issues/136
915 policy = anylinux.policy
916
917 test_path = "/auditwheel_src/tests/integration/nonpy_rpath"
918 orig_wheel = anylinux.build_wheel(test_path)
919
920 # Repair the wheel using the appropriate manylinux container
921 anylinux.repair(orig_wheel)
922 repaired_wheel = anylinux.check_wheel("nonpy_rpath")
923 assert_show_output(anylinux, repaired_wheel, policy, False)
924
925 # Test the resulting wheel outside the manylinux container
926 python.install_wheel(repaired_wheel)
927 python.run(
928 "import nonpy_rpath; assert nonpy_rpath.crypt_something().startswith('*')",
929 )
930
931 def test_glibcxx_3_4_25(
932 self,
933 anylinux: AnyLinuxContainer,
934 python: PythonContainer,
935 ) -> None:
936 policy = anylinux.policy
937
938 test_path = "/auditwheel_src/tests/integration/test_glibcxx_3_4_25"
939 orig_wheel = anylinux.build_wheel(test_path)
940 assert orig_wheel.startswith("testentropy-0.0.1")
941
942 # Repair the wheel using the appropriate manylinux container
943 if policy.startswith("manylinux_2_28_"):
944 with pytest.raises(CalledProcessError):
945 anylinux.repair(orig_wheel)
946 # TODO if a "permissive" mode is implemented, add the relevant flag to the
947 # repair_command here and drop the return statement below
948 return
949
950 anylinux.repair(orig_wheel)
951
952 repaired_wheel = next(anylinux.io_folder.glob(f"*{policy}*.whl")).name
953
954 python.install_wheel(repaired_wheel)
955 python.run("from testentropy import run; exit(run())")
956
957 @pytest.mark.skipif(
958 PLATFORM != "x86_64",
959 reason="ISA extension only implemented on x86_64",
960 )
961 @pytest.mark.parametrize("isa_ext", ["x86-64-v2", "x86-64-v3", "x86-64-v4"])
962 def test_isa_variants(self, anylinux: AnyLinuxContainer, isa_ext: str) -> None:
963 policy = anylinux.policy
964 if policy.startswith(("manylinux_2_12_", "manylinux_2_17_")):
965 pytest.skip("skip old gcc")
966
967 test_path = "/auditwheel_src/tests/integration/testdependencies"
968 orig_wheel = anylinux.build_wheel(
969 test_path,
970 env={"WITH_DEPENDENCY": "1", "WITH_ARCH": isa_ext},
971 )
972
973 # repair failure with ISA check
974 with pytest.raises(CalledProcessError):
975 anylinux.repair(orig_wheel, library_paths=[test_path])
976
977 anylinux.repair(orig_wheel, library_paths=[test_path], isa_ext_check=False)
978 repaired_wheel = anylinux.check_wheel("testdependencies", platform_tag=policy)
979 assert_show_output(anylinux, repaired_wheel, policy, True, False)
980
981 # with ISA check, we shall not report a manylinux/musllinux policy
982 assert_show_output(anylinux, repaired_wheel, f"linux_{PLATFORM}", True)
983
984 @pytest.mark.parametrize(
985 "arch",
986 [
987 Architecture.aarch64,
988 Architecture.armv7l,
989 Architecture.i686,
990 Architecture.ppc64le,
991 Architecture.riscv64,
992 Architecture.s390x,
993 Architecture.x86_64,
994 ],
995 )
996 @pytest.mark.parametrize("libc", [Libc.GLIBC, Libc.MUSL])
997 def test_cross_repair(
998 self,
999 anylinux: AnyLinuxContainer,
1000 libc: Libc,
1001 arch: Architecture,
1002 ) -> None:
1003 if libc == Libc.MUSL:
1004 source = "musllinux_1_2"
1005 platform_tag = f"musllinux_1_2_{arch.value}"
1006 python_abi = "cp312-cp312"
1007 else:
1008 assert libc == Libc.GLIBC
1009 source = "glibc"
1010 platform_tag = f"manylinux2014_{arch.value}.manylinux_2_17_{arch.value}"
1011 if arch in {Architecture.x86_64, Architecture.i686}:
1012 platform_tag = f"manylinux1_{arch.value}.manylinux_2_5_{arch.value}"
1013 elif arch == Architecture.riscv64:
1014 platform_tag = f"manylinux_2_31_{arch.value}"
1015 python_abi = "cp313-cp313"
1016 test_path = f"/auditwheel_src/tests/integration/arch-wheels/{source}"
1017 orig_wheel = f"testsimple-0.0.1-{python_abi}-linux_{arch.value}.whl"
1018 anylinux.exec(["cp", "-f", f"{test_path}/{orig_wheel}", f"/io/{orig_wheel}"])
1019 anylinux.repair(orig_wheel, plat="auto", only_plat=False)
1020 anylinux.check_wheel(
1021 "testsimple",
1022 python_abi=python_abi,
1023 platform_tag=platform_tag,
1024 )
1025
1026
1027 class TestManylinux(Anylinux):
1028 @pytest.fixture(scope="session")
1029 def docker_python_img(self):
1030 """The glibc Python base image with up-to-date pip"""
1031 commnds = ["pip install -U pip", "apt-get update -yqq"]
1032 with tmp_docker_image(MANYLINUX_PYTHON_IMAGE_ID, commnds) as img_id:
1033 yield img_id
1034
1035 @pytest.fixture(scope="session", params=MANYLINUX_IMAGES.keys())
1036 def any_manylinux_img(self, request):
1037 """Each manylinux image, with auditwheel installed.
1038
1039 Plus up-to-date pip, setuptools and coverage
1040 """
1041 policy = request.param
1042 check_set = {
1043 "manylinux_2_12": {"38", "39", "310"},
1044 }.get(policy)
1045 if check_set and PYTHON_ABI_MAJ_MIN not in check_set:
1046 pytest.skip(f"{policy} images do not support cp{PYTHON_ABI_MAJ_MIN}")
1047
1048 base = MANYLINUX_IMAGES[policy]
1049 env = {"PATH": PATH[policy]}
1050 commands = [
1051 'git config --global --add safe.directory "/auditwheel_src"',
1052 "pip install -U pip setuptools 'coverage[toml]>=7.13'",
1053 "pip install -U -e /auditwheel_src",
1054 ]
1055 if policy in {"manylinux_2_31", "manylinux_2_35"}:
1056 commands.append("apt-get update -yqq")
1057 with tmp_docker_image(base, commands, env) as img_id:
1058 yield policy, img_id
1059
1060 @pytest.mark.parametrize("with_dependency", ["0", "1"])
1061 def test_image_dependencies(
1062 self,
1063 with_dependency: str,
1064 anylinux: AnyLinuxContainer,
1065 python: PythonContainer,
1066 ) -> None:
1067 # try to repair the wheel targeting different policies
1068 #
1069 # with_dependency == 0
1070 # The python module has no dependencies that should be grafted-in and
1071 # uses versioned symbols not available on policies pre-dating the policy
1072 # matching the image being tested.
1073 # with_dependency == 1
1074 # The python module itself does not use versioned symbols but has a
1075 # dependency that should be grafted-in that uses versioned symbols not
1076 # available on policies pre-dating the policy matching the image being
1077 # tested.
1078
1079 policy_name = anylinux.policy
1080
1081 test_path = "/auditwheel_src/tests/integration/testdependencies"
1082 orig_wheel = anylinux.build_wheel(
1083 test_path,
1084 env={"WITH_DEPENDENCY": with_dependency},
1085 )
1086
1087 policies = WheelPolicies(libc=Libc.GLIBC, arch=Architecture(PLATFORM))
1088 policy = policies.get_policy_by_name(policy_name)
1089 older_policies = [
1090 f"{p}_{PLATFORM}"
1091 for p in MANYLINUX_IMAGES
1092 if policy < policies.get_policy_by_name(f"{p}_{PLATFORM}")
1093 ]
1094 for target_policy in older_policies:
1095 # we shall fail to repair the wheel when targeting an older policy than
1096 # the one matching the image
1097 with pytest.raises(CalledProcessError):
1098 anylinux.repair(
1099 orig_wheel,
1100 plat=target_policy,
1101 library_paths=[test_path],
1102 )
1103
1104 # check all works properly when targeting the policy matching the image
1105 # use "auto" platform
1106 anylinux.repair(
1107 orig_wheel,
1108 only_plat=False,
1109 plat="auto",
1110 library_paths=[test_path],
1111 )
1112 repaired_wheel = anylinux.check_wheel("testdependencies")
1113 # we shall only get the current policy tag with "auto" platform
1114 assert_show_output(anylinux, repaired_wheel, policy_name, True)
1115
1116 # check the original wheel with a dependency was not compliant
1117 # and check the one without a dependency was already compliant
1118 expected = f"linux_{PLATFORM}" if with_dependency == "1" else policy_name
1119 assert_show_output(anylinux, orig_wheel, expected, True)
1120
1121 python.install_wheel(repaired_wheel)
1122 python.run("from testdependencies import run; exit(run())")
1123
1124 @pytest.mark.parametrize(
1125 "target_policy",
1126 [f"{p}_{PLATFORM}" for p in list(MANYLINUX_IMAGES.keys())]
1127 + [f"{p}_{PLATFORM}" for aliases in POLICY_ALIASES.values() for p in aliases],
1128 )
1129 @pytest.mark.parametrize("only_plat", [True, False])
1130 def test_compat(
1131 self,
1132 target_policy: str,
1133 only_plat: bool,
1134 anylinux: AnyLinuxContainer,
1135 python: PythonContainer,
1136 ) -> None:
1137 # test building wheels with compatibility with older spec
1138 # check aliases for older spec
1139 test_path = "/auditwheel_src/tests/integration/testsimple"
1140 orig_wheel = anylinux.build_wheel(test_path)
1141
1142 if PLATFORM in {"x86_64", "i686"}:
1143 expect = f"manylinux_2_5_{PLATFORM}"
1144 expect_tag = f"manylinux1_{PLATFORM}.manylinux_2_5_{PLATFORM}"
1145 elif PLATFORM == "riscv64":
1146 expect = f"manylinux_2_31_{PLATFORM}"
1147 expect_tag = f"manylinux_2_31_{PLATFORM}"
1148 else:
1149 expect = f"manylinux_2_17_{PLATFORM}"
1150 expect_tag = f"manylinux2014_{PLATFORM}.manylinux_2_17_{PLATFORM}"
1151
1152 target_tag = target_policy
1153 for pep600_policy, aliases in POLICY_ALIASES.items():
1154 policy_ = f"{pep600_policy}_{PLATFORM}"
1155 aliases_ = [f"{p}_{PLATFORM}" for p in aliases]
1156 if target_policy == policy_ or target_policy in aliases_:
1157 target_tag = ".".join(sorted([policy_, *aliases_]))
1158
1159 # we shall ba able to repair the wheel for all targets
1160 anylinux.repair(orig_wheel, plat=target_policy, only_plat=only_plat)
1161 if only_plat or target_tag == expect_tag:
1162 repaired_tag = target_tag
1163 else:
1164 repaired_tag = ".".join(
1165 sorted(expect_tag.split(".") + target_tag.split(".")),
1166 )
1167 repaired_wheel = anylinux.check_wheel("testsimple", platform_tag=repaired_tag)
1168
1169 assert_show_output(anylinux, repaired_wheel, expect, True)
1170
1171 with zipfile.ZipFile(anylinux.io_folder / repaired_wheel) as z:
1172 for file in z.namelist():
1173 assert not file.startswith("testsimple.libs"), "should not have empty .libs folder"
1174
1175 python.install_wheel(repaired_wheel)
1176 python.run("from testsimple import run; exit(run())")
1177
1178 @pytest.mark.skipif(
1179 PLATFORM != "x86_64",
1180 reason=f"libmvec not supported on {PLATFORM}",
1181 )
1182 def test_mvec(self, anylinux: AnyLinuxContainer, python: PythonContainer) -> None:
1183 # Tests https://github.com/pypa/auditwheel/issues/645
1184 policy = anylinux.policy
1185
1186 if policy.startswith(("manylinux_2_12_", "manylinux_2_17_")):
1187 pytest.skip(f"libmvec not supported on {policy}")
1188
1189 test_path = "/auditwheel_src/tests/integration/test_mvec"
1190 orig_wheel = anylinux.build_wheel(test_path, check_filename=False)
1191
1192 # Repair the wheel using the appropriate manylinux container
1193 anylinux.repair(orig_wheel, only_plat=False)
1194 platform_tag = f"manylinux_2_24_x86_64.{policy}"
1195 repaired_wheel = anylinux.check_wheel(
1196 "test_mvec",
1197 python_abi="py3-none",
1198 platform_tag=platform_tag,
1199 )
1200 assert_show_output(anylinux, repaired_wheel, policy, False)
1201
1202 # Test the resulting wheel outside the manylinux container
1203 python.install_wheel(repaired_wheel)
1204
1205 def test_zlib_blacklist(self, anylinux: AnyLinuxContainer) -> None:
1206 policy = anylinux.policy
1207 if policy.startswith(
1208 (
1209 "manylinux_2_17_",
1210 "manylinux_2_28_",
1211 "manylinux_2_31_",
1212 "manylinux_2_34_",
1213 "manylinux_2_35_",
1214 "manylinux_2_39_",
1215 ),
1216 ):
1217 pytest.skip(f"{policy} image has no blacklist symbols in libz.so.1")
1218
1219 test_path = "/auditwheel_src/tests/integration/testzlib"
1220 orig_wheel = anylinux.build_wheel(test_path)
1221 assert orig_wheel.startswith("testzlib-0.0.1")
1222
1223 # Repair the wheel using the appropriate manylinux container
1224 with pytest.raises(CalledProcessError):
1225 anylinux.repair(orig_wheel)
1226
1227 # Check auditwheel show warns about the black listed symbols
1228 output = anylinux.show(orig_wheel, verbose=True)
1229 assert "black-listed symbol dependencies" in output.replace("\n", " ")
1230
1231 @pytest.mark.skipif(PLATFORM != "aarch64", reason="glibc blacklist only for aarch64")
1232 def test_glibc_blacklist(self, anylinux: AnyLinuxContainer, python: PythonContainer) -> None:
1233 # https://github.com/pypa/auditwheel/issues/647
1234 policy = anylinux.policy
1235 if policy.startswith("manylinux_2_17_"):
1236 pytest.skip(f"{policy} image can't build this test")
1237
1238 test_path = "/auditwheel_src/tests/integration/test_aarch64_glibc_blacklist"
1239 orig_wheel = anylinux.build_wheel(test_path, check_filename=False)
1240 assert orig_wheel.startswith("test_aarch64_glibc_blacklist-0.0.1-")
1241
1242 # Repair the wheel using the appropriate manylinux container
1243 anylinux.repair(orig_wheel, only_plat=not policy.startswith("manylinux_2_28_"))
1244 platform_tag = policy
1245 if policy.startswith("manylinux_2_28_"):
1246 platform_tag = f"manylinux_2_24_aarch64.{platform_tag}"
1247 repaired_wheel = anylinux.check_wheel(
1248 "test_aarch64_glibc_blacklist",
1249 python_abi="py3-none",
1250 platform_tag=platform_tag,
1251 )
1252
1253 # Check auditwheel show warns about the black listed symbols
1254 output = anylinux.show(orig_wheel, verbose=True)
1255 output = output.replace("\n", " ")
1256 assert "black-listed symbol dependencies" in output
1257 # glibc moves symbol from library to library so libc.so.6 is used as a catch all
1258 # as it's more likely to be needed
1259 needle = (
1260 "From libc.so.6: __cxa_thread_atexit_impl, __issignaling, __issignalingf, "
1261 "__issignalingl, pthread_getattr_default_np, pthread_setattr_default_np"
1262 )
1263 assert needle in output
1264 needle = "From libm.so.6: __issignaling, __issignalingf, __issignalingl"
1265 assert needle in output
1266 needle = "From libpthread.so.0: pthread_getattr_default_np, pthread_setattr_default_np"
1267 if policy.startswith("manylinux_2_28_"):
1268 assert needle in output
1269 else:
1270 assert needle not in output
1271
1272 # Test the resulting wheel outside the manylinux container
1273 python.install_wheel(repaired_wheel)
1274 python.exec("test_signaling")
1275 python.exec("test_signalingf")
1276 python.exec("test_signalingl")
1277 python.exec("test_pthread")
1278
1279
1280 class TestMusllinux(Anylinux):
1281 @pytest.fixture(scope="session")
1282 def docker_python_img(self):
1283 """The alpine Python base image with up-to-date pip"""
1284 commands = ["pip install -U pip"]
1285 with tmp_docker_image(MUSLLINUX_PYTHON_IMAGE_ID, commands) as img_id:
1286 yield img_id
1287
1288 @pytest.fixture(scope="session", params=MUSLLINUX_IMAGES.keys())
1289 def any_manylinux_img(self, request):
1290 """Each musllinux image, with auditwheel installed.
1291
1292 Plus up-to-date pip, setuptools and coverage
1293 """
1294 policy = request.param
1295 base = MUSLLINUX_IMAGES[policy]
1296 env = {"PATH": PATH[policy]}
1297 commands = [
1298 'git config --global --add safe.directory "/auditwheel_src"',
1299 "pip install -U pip setuptools 'coverage[toml]>=7.13'",
1300 "pip install -U -e /auditwheel_src",
1301 ]
1302 with tmp_docker_image(base, commands, env) as img_id:
1303 yield policy, img_id